Int type

Integer type. On 64 bit platforms it's a 61 bit signed integer

Direct parent types

Eachable1
Eachable which each() calls the callback with one argument
Direct subtypes: 18
Num
A number
Direct subtypes: 2

Constructors

Int(r:Real)
Convert Real (floating) number to Int. Floating part is truncated.

Returns

Int
Int(s:Str, base:Int)
Convert Str to Int.

Example

Int("100", 2)  # 8
Int("80", 16)  # 128
Int() Source: stdlib.ngs:583
Get zero

Returns

0
Int(i:Int) Source: stdlib.ngs:5004
Convert Int to Int, a no-op

Returns

i
Int(s:Str, base:Any=10) Source: stdlib.ngs:5006
Convert to Int. Surrounding whitespace is ignored. Throws InvalidArgument if the number in s is not well-formatted.

Returns

Int

Example

Int(" 100 ")  # 100
Int(b:Bool) Source: stdlib.ngs:5033
Convert Bool to int.

Returns

Int

Example

true.Int()   # 1
false.Int()  # 0
Int(t:Time) Source: stdlib.ngs:8997
Undocumented
Int(d:Duration) Source: stdlib.ngs:9020
Undocumented

Methods

%(a:Int, b:Int)
Modulus

Returns

Int

Example

10 % 3  # 1
*(a:Int, b:Int)
Multiplication
*(arr:Arr, n:Int) Source: stdlib.ngs:3778
Repeat all elements in arr n times

Parameters

arrElements to repeat
nNumber of times to repeat the elements

Returns

Arr

Example

[10,20] * 2  # [10,20,10,20]
*(s:Str, n:Int) Source: stdlib.ngs:5259
Repeat string n times

Example

"abc" * 3  # "abcabcabc"
*(cb:Fun, n:Int) Source: stdlib.ngs:8539
Call cb n times without any parameters and accumulate the results.

Example

a = Box * 2; a[0] is Box and a[1] is Box and a[0] !== a[1]  # true
*(a:Int, b:Real) Source: stdlib.ngs:9647
Undocumented
*(a:Real, b:Int) Source: stdlib.ngs:9648
Undocumented
+(a:Int, b:Int)
Addition
+(a:Int, b:Real) Source: stdlib.ngs:9641
Undocumented
+(a:Real, b:Int) Source: stdlib.ngs:9642
Undocumented
-(a:Int, b:Int)
Subtraction
-(a:Int, b:Real) Source: stdlib.ngs:9643
Undocumented
-(a:Real, b:Int) Source: stdlib.ngs:9644
Undocumented
/(a:Int, b:Int)
Division
/(a:Int, b:Real) Source: stdlib.ngs:9645
Undocumented
/(a:Real, b:Int) Source: stdlib.ngs:9646
Undocumented
<(a:Int, b:Int)
Less-than comparison
<=(a:Int, b:Int)
Less-than-or-equal comparison
==(a:Int, b:Int)
Equality comparison
>(a:Int, b:Int)
Greater-than comparison
>=(a:Int, b:Int)
Greater-than-or-equal comparison
[](arr:Arr, idx:Int)
Get element at the given index or throw IndexNotFound if the index is out of range (element at the given index does not exist).

Returns

Any
[](al:ArrLike, idx:Int) Source: stdlib.ngs:2060
Get element from the underlying array.
[](arr:Arr, idx:Int) Source: stdlib.ngs:3592
Get array element by index from the end (negative indexes handler). Throws IndexNotFound if abs(idx) > len(arr).

Parameters

idxNegative index

Example

[10,20,30][-1]  # 30
[](s:Str, i:Int) Source: stdlib.ngs:5137
Get given character (currently byte) of the string

Parameters

sOriginal string
iIndex of the character to return

Example

"abc"[0]  # "a"
[](s:Str, i:Int) Source: stdlib.ngs:5147
Get given character (currently byte) of the string (negative indexes handler). Throws IndexNotFound if abs(i) > len(s).

Parameters

sOriginal string.
iNegative index of the character to return

Example

"abc"[-1]  # "c"
[](ms:MatchSuccess, idx:Int) Source: stdlib.ngs:8277
Convenience method to access matches in MatchSuccess

Example

("abc" ~ /a(.)c/)[1]  # "b"
[]=(arr:Arr, idx:Int, v:Any)
Set element at the given index or throw IndexNotFound if the index is out of range.

Returns

v
[]=(al:ArrLike, idx:Int, x:Any) Source: stdlib.ngs:2063
Set element in the underlying array.
[]=(arr:Arr, idx:Int, val:Any) Source: stdlib.ngs:3602
Set array element by index from the end (negative indexes handler). Throws IndexNotFound if abs(idx) > len(arr).

Parameters

idxNegative index

Example

a = [1, 2, 3]; a[-1] = 99  # [1, 2, 99]
abs(i:Int) Source: stdlib.ngs:4970
Absolute value of a number

Example

abs(5)   # 5
abs(-5)  # 5
access(f:File, mode:Int=0) Source: stdlib.ngs:9271
Check whether current process has the specified access to the file. Wrapper around ACCESS(2). Throws CError.

Parameters

modeOne of the file ACCESS::* modes, defaults to ACCESS::F_OK (test file existence only).

Returns

Bool

Example

access(File("mydata"), ACCESS::R_OK).not() throws Error("No access to data file").set("file", "mydata")
Arg(x:Int) Source: stdlib.ngs:7207
Convert to string, appropriate for using as argument to external process.

Automatically called by NGS for syntax

$(mycommand $num) # num is Int
assert_exit_code(pp:ProcessesPipeline, expected:Int, title:Str=null) Source: autoload/globals/test.ngs:171
Assert process exits with the specified exit code. Throws TestFail.

Returns

pp

Example

p = $(true); assert_exit_code(p, 0)   # OK
p = $(false); assert_exit_code(p, 1)  # OK
p = $(false); assert_exit_code(p, 0)  # Throws TestFail
band(a:Int, b:Int)
Bitwise and

Returns

Int

Example

7.band(5)  # 5
bor(a:Int, b:Int)
Bitwise or

Returns

Int

Example

1.bor(8)  # 9
Box(a:Arr, idx:Int) Source: stdlib.ngs:4637
Convert array value indexed by the given index

Parameters

idxkey to look in hash

Returns

Box. FullBox if the array has the element indexed by idx, EmptyBox otherwise.

Example

my_array = [10, 20]
my_array.Box(1).map(X*2).each(echo)
# output: 40
my_array.Box(5).map(X*2).each(echo)
# no output
bxor(a:Int, b:Int)
Bitwise xor

Returns

Int

Example

15.bxor(1)  # 14
c_accept(socket:Int)
Call ACCEPT(2)

Returns

Array with 2 items: accept() return value (the accepted socket, -1 on error), peer address: c_sockaddr or a subtype, null on error
c_access(pathname:Str, mode:Int)
Call ACCESS(2)
c_bind(socket:Int, address:c_sockaddr_un)
Undocumented
c_bind(socket:Int, address:c_sockaddr_in)
Undocumented
c_close(fd:Int)
Close a file. Uses CLOSE(2).

Returns

Int - zero on success or -1
c_connect(socket:Int, address:c_sockaddr_un)
Undocumented
c_connect(socket:Int, address:c_sockaddr_in)
Undocumented
c_dlopen(filename:Str, flags:Int)
Unfinished feature. Don't use!
c_dup2(oldfd:Int, newfd:Int)
Duplicate a file descriptor. Uses DUP2(2).

Returns

Int - file descriptor or -1
c_exit(status:Int)
Call EXIT(3). Don't use directly unless you must. Use FatalError exception.
c_fcntl(fd:Int, cmd:Int, arg:Int)
Control a file descriptor, with an int argument, e.g. C_F_GETFL, C_F_SETFL. Uses FCNTL(2).

Returns

Int - fcntl() return value or -1
c_fstat(fd:Int)
Call FSTAT(2)
c_getsockname(socket:Int)
Call GETSOCKNAME(2)

Returns

Array with 2 items: getsockname() return value (0 on success, -1 on error), address: c_sockaddr or a subtype, null on error
c_getsockopt(socket:Int, level:Int, option_name:Int)
Call GETSOCKOPT(2) for an option with an int value, e.g. C_SO_ERROR

Returns

Array with 2 items: getsockopt() return value (0 on success, -1 on error), the option value: Int, null on error
c_gmtime(timep:Int)
Call GMTIME_R(3)

Example

ngs -pl 'c_gmtime(0).Hash().Strs()'
tm_sec=0
tm_min=0
tm_hour=0
tm_mday=1
tm_mon=0
tm_year=70
tm_wday=4
tm_yday=0
tm_isdst=0
c_isatty(fd:Int)
Check if file descriptor refers to a TTY device. Uses ISATTY(3).

Returns

Int: 1 or 0
c_kill(pid:Int, sig:Int)
Call KILL(2). Global variable SIGNALS contains mapping between signals' names and values.
c_listen(socket:Int, backlog:Int)
Undocumented
c_localtime(timep:Int)
Call LOCALTIME(3)

Example

ngs -pl 'c_gmtime(0).Hash().keys()'
tm_sec
tm_min
tm_hour
tm_mday
tm_mon
tm_year
tm_wday
tm_yday
tm_isdst
c_lseek(fd:Int, offset:Int, whence:Str)
Call LSEEK(2).

Parameters

whenceOne of: set, cur, end

Returns

Int: new offset or -1
c_nanosleep(tv_sec:Int, tv_nsec:Int)
Wraps NANOSLEEP(2).

Returns

Arr[Int] - [status, rem_tv_sec, rem_tv_nsec]. On EINTR, rem_tv_sec and rem_tv_nsec hold the unslept remainder.
c_pcre2_compile(regexp:Str, flags:Int)
Throws RegExpCompileFail on errors.

Returns

RegExp
c_pcre2_match(regexp:RegExp, subject:Str, offset:Int, options:Int)
Search string for regular expression. Uses PCRE2_MATCH(3). Do not use this function directly!

Returns

Int or Arr of Int
c_poll(fds_evs:Arr, timeout:Int)
Undocumented
c_pthread_mutexattr_settype(mutex:c_pthread_mutexattr_t, type:Int)
Call PTHREAD_MUTEXATTR_SETTYPE(3)
c_read(fd:Int, count:Int)
Read from a file. Uses READ(2).

Parameters

countMaximal number of bytes to read.

Returns

Arr of two elements: Int - number of bytes read or -1, Str - the read bytes
c_recvfrom(socket:Int, length:Int, flags:Int)
Call RECVFROM(2)

Parameters

lengthMaximal number of bytes to receive

Returns

Array with 3 items: recvfrom() return value (the number of bytes received, -1 on error), data (Str, null on error), sender address (c_sockaddr or a subtype, null on error or when no address is reported)
c_send(socket:Int, buffer:Str, flags:Int)
Undocumented
c_sockaddr_in(address:Str, port:Int)
Make c_sockaddr_in with sin_family AF_INET, sin_addr from INET_PTON(3) and sin_port in network byte order. Do not use directly.

Parameters

addressIPv4 address, passed to INET_PTON(3)
portPort in host byte order, truncated to 16 bits

Returns

c_sockaddr_in or null if INET_PTON(3) fails
c_sockaddr_in(address:Str, port:Int) Source: stdlib.ngs:9415
Make IPv4 socket address. Throws InvalidArgument on invalid address or port.

Parameters

addressIPv4 address in dotted-decimal notation, without leading zeros in octets
portPort, 0 to 65535

Returns

c_sockaddr_in

Example

bind(socket(C_PF_INET, C_SOCK_STREAM), c_sockaddr_in("127.0.0.1", 0))  # 0
c_socket(domain:Int, type:Int, protocol:Int)
Undocumented
c_strerror(errnum:Int)
Call STRERROR(2)
c_sysconf(name:Int)
Undocumented
c_waitid(idtype:Int, id:Int, options:Int)
Call WAITID(2)

Returns

Array with 2 items: waitid() return value (0 on success, -1 on error), Hash with keys: si_pid (0 with C_WNOHANG when no child changed state), si_uid (not filled on macOS), si_signo, si_status, si_code
c_waitpid(pid:Int, options:Int)
Call WAITPID(2)

Returns

Array with 2 items: waitpid() return value (0 with C_WNOHANG when no child changed state, -1 on error), status
c_waitpid(pid:Int) Source: stdlib.ngs:6999
Same as c_waitpid(pid, 0). For compatibility.
C_WEXITSTATUS(status:Int)
Use WEXITSTATUS macro.
c_write(fd:Int, s:Str)
Write to a file. Uses WRITE(2).

Returns

Int - number of bytes written or -1
C_WTERMSIG(status:Int)
Use WTERMSIG macro.
calculate_num_cols_to_show(t:Table, max_columns_widths:Arr, available_cols:Int) Source: autoload/globals/Table.ngs:108
Internal method. Please do not use.
chr(code:Int)
Get character (byte) by it's ordinal value.

Returns

Str of length 1 (byte).

Example

chr(65)  # "A" on my machine
close(fd:Int) Source: stdlib.ngs:6797
Close a file. Uses CLOSE(2). Throws FileIOFail if an underlying error occurs.

Returns

fd
code(n:Int) Source: stdlib.ngs:5040
Convert an Int to NGS code that would produce the integer when executed. Not fully functional yet.

Returns

Str
collector(n:Int, body:Fun) Source: stdlib.ngs:3038
Defines collector { ... collect(...) ... } behaviour for integers (summarizes collected items).

Parameters

nInitial number
bodyThe body after collector keyword and initial value, wrapped in a function "collector/100 THIS_CODE"

Returns

The sum

Example

collector/0 { (1...10).each(collect) }  # 55
column(t:Table, n:Int) Source: autoload/globals/Table.ngs:88
Get values in the given table column.

Returns

Arr
create(rd:ResDef, n:Int, **props:Hash) Source: autoload/globals/Res.ngs:173
Create n resources with given props. Typically called by converge().

Returns

rd
digest(a:Arr, chunk_size:Int, marker:Str='(...)') Source: stdlib.ngs:8607
Convert an array to a possibly shorter version, for displaying to human.

Parameters

chunk_sizenumber of elements to retain at the beginning and at the end.
markerhow to mark the cut elements in the middle.

Returns

Arr

Example

my_array = Arr(1...100)
digest(my_array, 2).each(echo)
# 1
# 2
# (...)
# 99
# 100
drop(i:Iter, n:Int) Source: autoload/globals/Iter.ngs:74
Fetch and drop next n values from iterator i.

Example

i = Iter([10,20,30])
drop(i, 1)
echo(i.next())
# Output: 20
dup2(oldfd:Int, newfd:Int) Source: stdlib.ngs:6494
Duplicate a file descriptor. Uses DUP2(2). Handles EINTR.
dup2_reading_end(p:Pipe, newfd:Int) Source: stdlib.ngs:6687
DUP2(2) reading file descriptor
dup2_writing_end(p:Pipe, newfd:Int) Source: stdlib.ngs:6684
DUP2(2) writing file descriptor
each(arr:Arr, n:Int, cb:Fun) Source: stdlib.ngs:3345
Process each N elements of an Array at a time. Throws InvalidArgument if number of items in arr is not divisible by n. cb is called as cb(eltI, ..., eltJ) where I is multiple of n and J is I+n-1

Parameters

arrItems to iterate in chunks of n
nNumber of items in chunk
cbFunction to be called with values from arr

Returns

arr

Example

[1,2,3,4].each(2, F(a, b) echo("$a - $b"))  # Outputs: "1 - 2" and on the next line "3 - 4"
each(n:Int, cb:Fun) Source: stdlib.ngs:4987
Iterate from zero up to but not including n

Parameters

cbFunction to call with current number

Returns

n

Example

10.each(echo)  # Outputs numbers from 0 to 9 inclusive, one on each line
each_chunk(e:Eachable1, n:Int, cb:Fun)experimental Source: stdlib.ngs:3895
Call cb with array of maximum length of n, repeatedly for all items of e. TODO: better doc, rename to each() to be consistent with each(Arr, Int, Fun)?
echo(fd:Int, ss:SemanticOutput) Source: stdlib.ngs:5941
Using only while loading. Real implementation is towards the end of this file. backtick syntax and running external processes is defined by then.
echo(fd:Int, s:Str) Source: stdlib.ngs:6586
Write a string followed by newline character to a file descriptor. Throws WriteFail on failure.

Returns

null

Example

echo(2, "blah")  # Output on stderr: blah"
echo(fd:Int, ss:SemanticOutput) Source: stdlib.ngs:9720
Colored output - NO_COLOR is not set and TTY and color category known
echo(fd:Int, ss:SemanticOutput) Source: stdlib.ngs:9726
Not colored output - NO_COLOR set or not a TTY or color category unknown
encode_base64(s:Str, wrap:Int=0)experimental Source: stdlib.ngs:9375
Undocumented
encode_base64(s:Str, wrap:Int=0)experimental Source: stdlib.ngs:9382
Undocumented
encode_base64(s:Str, wrap:Int=0)experimental Source: stdlib.ngs:9389
Undocumented
ensure(n:Int, r:NumRange) Source: stdlib.ngs:2977
Ensures that x is in the range.

Example

ensure(1, 3..10)    # 3
ensure(20, 3...10)  # 10
ExitCode(n:Int) Source: stdlib.ngs:194
Undocumented

Returns

n
expect(rd:ResDef, e:Int) Source: autoload/globals/Res.ngs:60
Throw an exception unless there is exactly e resources were found. Useful to express assumptions before operating.

Returns

rd

Example

slave_build_server = AWS::Instance(Tags={'env': 'aux', 'role': 'build-slave'}).expect(1)
subnets = AWS::Subnet(my_vpc_anchor).expect(2)
finished_ok(p:Process, field_name:Str, ok:Int)internal Source: stdlib.ngs:6900
Decide whether a process finished normally.

Example

$(ok:1 ls no-such-file)  # No exception
$(ok:10 ls no-such-file) # ProcessFail exception
get(al:ArrLike, idx:Int, dflt:Any) Source: stdlib.ngs:2066
Get element at the given index or return dflt if the index is out of range (element at the given index does not exist). See get(Arr).
get(a:Arr, idx:Int, dflt:Any=null) Source: stdlib.ngs:3152
Get element at the given index or return dflt if the index is out of range (element at the given index does not exist)

Parameters

dfltDefault value, defaults to null. If dflt is a Fun, the result of dflt(idx) is used instead.

Returns

a[idx] or Value(dflt, idx)

Example

[1,2,3].get(0, 10)    # 1
[1,2,3].get(5, 10)    # 10
[11].get(-1)          # 11
[10,20].get(-5, "X")  # "X"
get(ms:MatchSuccess, idx:Int, dflt:Any=null) Source: stdlib.ngs:8279
Get indexed match, returning dflt if the match is not found
gmtime(t:Int) Source: stdlib.ngs:8918
Low-level function. Do not use directly. Use Time type.
has_index(e:Eachable1, i:Int) Source: stdlib.ngs:1990
Check whether Eachable1 has the given index: -len(e) <= i < len(e)

Returns

Bool
in(n:Int, r:NumRange) Source: stdlib.ngs:2931
Check whether the number is in range 10 in 10..20 # true 1 in 10..20 # false
index(arr:Arr, pattern:Any=method, start:Int=0, dflt:Any=block) Source: stdlib.ngs:3455
Find index of the first value that matches the pattern. TODO: Make it work on anything with each() method. In future, will throw exception if element is not found and default is not provided. Now returns null for backwards compatibility in this case.

Parameters

arrItems to look at
patternTest function or anything else acceptable by (=~), defaults to Bool.constructors
startIndex to start search at
dfltDefault value. If dflt is a Fun, the result of dflt() is used instead.

Returns

Int or Value(dflt). Temporary also null, for backwards compatibility.

Example

[1,2,11,3,4].index(X>10)  # 2
init(r:Repeat, pattern:Any, count:Int) Source: stdlib.ngs:1454
Undocumented
init(e:CError, errno:Int, message:Str) Source: stdlib.ngs:2755
CError constructor. In addition to storing message field, adds errno and errno_name fields.
init(e:LockFail, op:Str, code:Int, msg:Str) Source: stdlib.ngs:2780
Initialize LockFail exception.
init(ee:ExitException, message:Str, exit_code:Int=1) Source: stdlib.ngs:5890
Initializes ExitException.
init(ee:ExitException, exit_code:Int=1) Source: stdlib.ngs:5896
Undocumented
init(f:File, fd:Int) Source: stdlib.ngs:6702
Create File object from the given file descriptor.
init(t:Time, epoch:Int) Source: stdlib.ngs:8943
Initialize Time object with the given epoch time.
init(d:Duration, seconds:Int) Source: stdlib.ngs:9018
Undocumented
init(c:_Cell, val:Any, width:Int) Source: autoload/globals/Table2.ngs:82
Make a cell of given width. Uses _Cell(val).
init(t:Terminal, fd_in:Int, fd_out:Int) Source: autoload/globals/Terminal.ngs:23
Undocumented
isatty(fd:Int) Source: stdlib.ngs:6596
Check whether given fd represents a TTY. Uses ISATTY(3). Throws TtyCheckFail.

Returns

Bool
Iter(n:Int) Source: autoload/globals/Iter.ngs:246
Create Iter from Int
JsonData(n:Int) Source: stdlib.ngs:5043
Convert Int into JSON compatible data structure - number
kill(p:Process, sig:Int=15) Source: stdlib.ngs:7128
Send signal to a Process. Uses KILL(2). Throws InvalidArgument if Process does not have "pid". Throws KillFail on error. Sends nothing if the process has exited: its pid may already belong to another process. While another thread's wait() is in progress, signals the process even if it has exited (its pid is not reused until that wait() reaps it).

Parameters

sigSignal to send. Defaults to SIGNALS.TERM

Returns

unspecified at this time, do not count on it
kill(pp:ProcessesPipeline, sig:Int=15) Source: stdlib.ngs:7148
Kill all processes in the ProcessesPipeline. Throws InvalidArgument if ProcessesPipeline is not running (yet). Skips processes that have exited.

Returns

pp
kill(pid:Int, sig:Int=15) Source: stdlib.ngs:7648
Send signal to a process. Uses KILL(2). Throws KillFail on error.

Parameters

sigSignal to send. Defaults to SIGNALS.TERM

Returns

unspecified at this time, do not count on it
len(i:Int) Source: stdlib.ngs:4977
Useful for knowing how much times each() callback would be invoked. Alternatively, how many elements map() result would have.

Returns

i
limit(a:Arr, l:Int) Source: stdlib.ngs:3741
Truncate an array if necessary so it would have maximum l elements.

Parameters

aArray to (possibly) truncate.
lMaximum elements

Returns

Either a or new Arr of length l

Example

[10,11,12].limit(2)   # [10,11]
[10,11,12].limit(10)  # [10,11,12]
limit(h:Hash, l:Int) Source: stdlib.ngs:4383
Truncate a Hash if necessary so it would have maximum l key-value pairs.

Parameters

hSource hash
lMaximum elements

Returns

Hash

Example

{"a": 1, "b": 2}.limit(1)  # {"a": 1}
limit(s:Str, n:Int, marker:Str='') Source: stdlib.ngs:5412
Truncate a string if necessary so it would have maximum n characters (currently bytes).

Parameters

sThe string to (possibly) truncate.
nMaximum characters
markerThe truncation marker

Returns

Either s or new Str of length n

Example

"abc".limit(5, "...")     # "abc"
"abcdef".limit(5, "...")  # "ab..."
"abcdef".limit(2)         # "ab"
ll_is_global_variable_defined(idx:Int)
Do not use directly! Check whether global variable is defined by index.
ll_set_global_variable(idx:Int, val:Any)
Do not use directly! Set global variable by index.
localtime(t:Int) Source: stdlib.ngs:8925
Low-level function. Do not use directly. Use Time type.
map(arr:Arr, n:Int, mapper:Fun) Source: stdlib.ngs:3366
Map each N elements of an Array at a time. mapper is called as cb(eltI, ..., eltJ) where I is multiple of n and J is I+n-1 Throws InvalidArgument if number of items in arr is not divisible by n. mapper is called as mapper(eltI, ..., eltJ) where I is multiple of n and J is I+n-1

Parameters

arrItems to iterate in chunks of n
nNumber of items in chunk
mapperFunction to be called with values from arr

Returns

Arr

Example

[1,2,3,4].map(2, F(a,b) "$a=$b").join("&")  # Outputs: 1=2&3=4
map_base_idx(base:Any, n:Int, mapper:Fun)deprecated Source: stdlib.ngs:1885
Deprecated. Map when there is more than one element. If there is exactly one element, it's left as is

Parameters

mapperWill be called with zero based index and successive elements from arr

Returns

Arr
ord(s:Str, idx:Int)
Get character (byte) ordinal value. Throws InvalidArgument if idx is not pointing into s.

Parameters

idxIndex of the character to get value of

Returns

Int

Example

ord("A", 0)  # 65 on my machine
pfilter(e:Eachable1, threads:Int, pattern:Any) Source: stdlib.ngs:5785
Parallel filter. Typically should be used with "heavy" pattern such as SSH.

Returns

Of same type as e

Example

Set(1..10).pfilter(2, X>3)  # <Set 4, 5, 6, 7, 8, 9>
pmap(e:Eachable1, threads:Int, mapper:Fun) Source: stdlib.ngs:5730
Parallel map. Runs mapper in "threads" total threads.

Parameters

eEachable1 to be mapped
threadsnumber of threads to use
mappercalled with elements from e

Returns

Arr, result of applying mapper to elements of e, preserving the order.

Example

pages_texts = abs_pages_urls.pmap(F(url)  `lynx -dump $url`)
pos(haystack:Str, needle:Str, start:Int)
Find substring position

Parameters

startNon-negative Int, position where the search starts

Returns

Int or null. Not -1 as in many languages
pow(base:Int, exponent:Int) Source: stdlib.ngs:9622
Calls pow(Real, Real) converting parameters and results to and from Real
print_exception(e:Exception, level:Int=0, parent:Exception=null, echo:Any=method) Source: stdlib.ngs:8761
Print exception to stderr. Uses inspect().

Parameters

levelindentation level to use (two spaces for each level)
parentparent exception if print_exception() was called for .cause exception
ptimes(n:Int, cb:Fun) Source: stdlib.ngs:5764
Run cb in n parallel threads. Each thread runs one cb but this might change in future (preserving the total n calls to cb).
rand(something:Any, n:Int) Source: stdlib.ngs:9062
Pick n elements from something. Uniqueness of picked elements is not guaranteed.

Returns

Any
rand(n:Int) Source: stdlib.ngs:9067
Pick random number from 0 up to but not including n

Returns

Int
rand(a:Str, n:Int) Source: stdlib.ngs:9084
Undocumented
rand_uniq(something:Any, n:Int) Source: stdlib.ngs:9043
Pick n random unique elements from something

Parameters

somethingSomething that has len(something) and something[idx]

Returns

Arr or Str, depending on something
read(fd:Int, count:Any=null) Source: stdlib.ngs:6505
Read all data from a file referenced by file descriptor without parsing it.

Parameters

fdFile descriptor to read from

Returns

Str

Example

read(0)  # All data from stdin
read(t:Terminal, count:Int=1) Source: autoload/globals/Terminal.ngs:31
Undocumented
Real(n:Int)
Convert Int to Real
resolve_instruction_pointer(ip:Int)
Resolves Instruction Pointer to source location

Parameters

ipResult of calling Backtrace(). Backtrace().frames[0].ip for example.

Returns

Hash with keys: file, first_line, first_column, last_line, last_column, ip

Example

resolve_instruction_pointer(Backtrace().frames[0].ip)
# {ip=4770, file=/etc/ngs/bootstrap.ngs, first_line=245, first_column=1, last_line=245, last_column=34}
retry(times:Int=60, sleep:Any=1, logger:Fun=method, success_predicate:Any=method, title:Any='<retry>', progress_cb:Fun=method, success_cb:Fun=method, fail_cb:Any=method, body:Fun=method) Source: stdlib.ngs:9107
Retry. Executes given "body" "times" times. Throws RetryFail if all calls fail and fail_cb is not provided.

Parameters

timesLimit of times to run "body"
sleepEither sleep in seconds between tries or Iter that returns successive sleep times in seconds
loggerFunction to use to log attempts, caught body exceptions and sleep times. Defaults to stdlib's debug.
success_predicateCANDIDATE FOR REMOVAL. Run against body results to. Says whether the attempt succeeded. Defaults to Bool.
titlePrefix strings sent to logger with this string. Defaults to "<retry>".
progress_cbCalled before each attempt with (1) current attempt number and (2) limit of attempts ("times"). Defaults to do nothing.
success_cbCalled when body succeeds with the result that comes from body. Defaults to identity function.
fail_cbIf passed, called if all attempts fail. Defaults to null.

Returns

Any. Result of success_cb or result of fail_cb.

Example

page = retry(times=10, sleep=ExpBackIter(), body={ try `curl "http://flaky-site.com"` })
skip(i:Iter, count:Int) Source: autoload/globals/Iter.ngs:465
Returns the given Iter after consuming first count elements.

Returns

Iter

Example

[3, 4, 5, 34, 5].Iter().skip(3).Arr() == [34, 5] 
sleep(sec:Int, nsec:Int) Source: stdlib.ngs:8887
Sleep for the given seconds and nanoseconds. Uses NANOSLEEP(2). When interrupted by a signal, sleeps for the remainder. Throws InvalidArgument if sec is negative or nsec is not in 0..999999999.

Returns

null

Example

sleep(1, 500000000)  # 1.5 seconds
sleep(seconds:Int) Source: stdlib.ngs:8903
Sleep for the given number of seconds. Uses NANOSLEEP(2). When interrupted by a signal, sleeps for the remainder. Throws InvalidArgument if seconds is negative.

Returns

null

Example

sleep(2)
split(s:Str, delim:Str, max_parts:Int=0) Source: stdlib.ngs:5181
Split string by substring

Parameters

sString to split
delimDelimiter to split by
max_partsMaximum number of resulting parts, 0 - unlimited

Returns

Arr of Str

Example

":a:bc:d:".split(":")   # ["", "a", "bc", "d", ""]
"bucket_name/dir/file".split("/", 2)  # ["bucket_name", "dir/file"]
":a:bc:d:".split("bc")  # [":a:", ":d:"]
srand(seed:Int)
Seed random generator. Uses SRANDOM(3).

Returns

Unspecified
Str(n:Int)
Convert Int to Str
Str(x:Any, target_width:Int, ch:Str=' ') Source: stdlib.ngs:5263
Convert anything to Str of a given width
Str(s:Str, target_width:Int, ch:Str=' ') Source: stdlib.ngs:5266
Pad a string to given width with spaces

Parameters

target_widthPositive pads on right, negative pads on left

Example

Str("x", 3)  # 'x  '
Str("x",-3)  # '  x'
Str(n:Int, target_width:Int, ch:Str=' ') Source: stdlib.ngs:5289
Convert a number to a string and pad it

Parameters

target_widthPositive pads on left, negative pads on right

Example

Str(10,  4)  # '  10'
Str(10, -4)  # '10  '
StrForTable(x:Any, width:Int) Source: autoload/globals/Table.ngs:12
Internal method. Please do not use.
StrForTable(x:Null, width:Int) Source: autoload/globals/Table.ngs:18
Internal method. Please do not use.
sysconf(name:Int) Source: stdlib.ngs:9694
Undocumented
take(i:Iter, n:Int) Source: autoload/globals/Iter.ngs:79
Fetch and convert to array next n values from iterator i.

Example

i = Iter([10,20,30])
echo(i.take(2))  # Output: [10,20]
times(n:Int, cb:Fun) Source: stdlib.ngs:4998
Call cb n times without arguments.

Parameters

cbFunction to call

Example

r=0; 5.times(F() r=r+2);  # r is now 10
write(s:Str, fd:Int)deprecated Source: stdlib.ngs:6542
DEPRECATED! Do not use!
write(fd:Int, s:Str) Source: stdlib.ngs:6560
Throws WriteFail on failure.

Parameters

fdFile descriptor to write to
sString of bytes to write

Returns

fd
~(haystack:Str, needle:Str, offset:Int=0) Source: stdlib.ngs:5441
Find substring in string. Uses pos().

Returns

MatchResult

Example

"abc" ~ "bc"  # <MatchSuccess ...>
"abc" ~ "X"   # <MatchFailure>
~(s:Str, r:RegExp, offset:Int=0, options:Int=0) Source: stdlib.ngs:8299
Find PCRE regular expression in s. Empty string without options returns MatchFailure. Throws Error if more than 20 captures are used or if there is an error during matching.

Automatically called by NGS for syntax

my_str ~ my_regexp

Parameters

offsetsearch start offset
optionsoptions to pass to underlying PCRE2_MATCH(3).

Returns

MatchResult

Example

globals().keys().filter(/^C_PCRE/)  # lists possible options
"xabcy" ~ /a(.)c/  # <MatchSuccess matches=[abc,b] pattern=/a(.)c/ named={} positions=[<NumRange 1..4 include_start=true include_end=false step=1>,<NumRange 2..3 include_start=true include_end=false step=1>] whole=abc before=x after=y>
m = ("xabcy" ~ /a(?P<mychar>.)c/)
echo(m.named.mychar)  # Outputs: b
AWS::util::world_open_port(port:Int, proto:Str='tcp') Source: autoload/globals/AWS.ngs:1504
Undocumented