nimcx/cxglobal

Search:
Group by:

::

Library     : nimcx.nim

Module      : cxglobal.nim

Status      : stable

License     : MIT opensource

Latest      : 2023-09-06

Compiler    : latest stable or devel branch

OS          : Linux

Description : provides many basic utility functions of the library

Types

RpointFloat = tuple[x, y: float]
RpointInt = tuple[x, y: int]

Procs

proc `[]`[T; U](a: seq[T]; x: Slice[U]): seq[T]
proc boxy(w: int = 20; h: int = 5; fgr = randcol(); xpos: int = 1) {.
    ...raises: [IOError, ValueError], tags: [WriteIOEffect], forbids: [].}

boxy

draws a box with width w , height h , color color at position xpos

proc boxy2(w: int = 20; h: int = 5; fgr = randcol(); xpos: int = 1) {.
    ...raises: [IOError, ValueError], tags: [WriteIOEffect], forbids: [].}

boxy2

draws a box with width w , height h , color color at position xpos

similar to boxy but with random color for each element rather than each box

proc centerMark(showpos: bool = false) {....raises: [IOError, ValueError],
    tags: [WriteIOEffect, ReadEnvEffect], forbids: [].}

centerMark

draws a red dot in the middle of the screen xpos only and also can show pos

proc centerPos(astring: string) {....raises: [IOError, ValueError],
                                  tags: [WriteIOEffect, ReadEnvEffect],
                                  forbids: [].}

centerpos

tries to move so that string is centered when printing

var s = "Hello I am centered"
centerPos(s)
printLn(s,gray)
proc centerX(): int {....raises: [], tags: [ReadEnvEffect], forbids: [].}

centerX

returns an int with best terminal center position

proc checkMem(xpos: int = 2) {....raises: [IOError, ValueError, OSError, Exception], tags: [
    ReadIOEffect, WriteIOEffect, ReadEnvEffect], forbids: [].}

checkMem

reads meminfo to give memory status for memtotal,memfree and memavailable maybe usefull during debugging of a function to see how memory is consumed

proc checkMemFull(xpos: int = 2) {....raises: [IOError, ValueError, OSError,
    IOError, ValueError, Exception], tags: [ReadIOEffect, WriteIOEffect,
    ReadEnvEffect], forbids: [].}

checkMemFull

full 45 lines output of system memory status

proc checkPrime(a: int): bool {....raises: [], tags: [], forbids: [].}

checkPrime

within maxinteger range

checks an int for primeness and returns true or false

proc cleanScreen() {....raises: [IOError], tags: [WriteIOEffect], forbids: [].}

cleanScreen

very fast clear screen proc with escape seqs

similar to terminal.eraseScreen() but cleans the terminal window

more completely

proc cpuInfo(): seq[string] {.discardable, ...raises: [IOError, ValueError], tags: [
    ExecIOEffect, ReadIOEffect, RootEffect, WriteIOEffect, ReadEnvEffect],
                              forbids: [].}
proc createRandomDataFile(filename: string = "randomdata.dat") {.
    ...raises: [ValueError], tags: [ExecIOEffect, ReadIOEffect, RootEffect],
    forbids: [].}

createRandomDataFile

this will create a file with given filename and size 1 MB filled with strong random data

createRandomDataFile("niip2.wsx")
var bc = 0
var b = @[100,200,300,700,800,3000]
withFile(fs,"niip2.wsx",fmRead):
  var line =""
  while fs.readLine(line):
     inc bc
     if bc in b:
       printLn($bc & rightarrow & spaces(3) & wrapwords(line.replace(" ",""),(tw - 5)),yellowgreen)
echo bc
proc createSeqAll(min: int = 0; max: int = 40878): seq[string] {....raises: [],
    tags: [], forbids: [].}
proc createSeqApl(): seq[string] {....raises: [ValueError], tags: [], forbids: [].}

createSeqApl

returns a seq containing apl language symbols

proc createSeqBinary(n: int = 10): seq[int] {.inline, ...raises: [], tags: [],
    forbids: [].}

createSeqBinary

returns a seq of integers between 0 and 1

proc createSeqBool(n: int = 10): seq[bool] {.inline, ...raises: [], tags: [],
    forbids: [].}
proc createSeqBoxChars(): seq[string] {....raises: [ValueError], tags: [],
                                        forbids: [].}

chars to draw a box

returns a seq containing unicode box drawing chars

proc createSeqCJK(): seq[string] {....raises: [ValueError], tags: [], forbids: [].}
full cjk unicode range returned in a seq
import nimcx
var b = createSeqCJK()
var col = 0
for x in 0 ..< b.len:
   printbicol(fmtx(["<6","",""],$x," : ", b[x]))
   inc col
   if col > 10:
      col = 0
      echo()
echo()
proc createSeqFloat(n: int = 10; prec: int = 3): seq[float] {.
    ...raises: [ValueError], tags: [], forbids: [].}

createSeqFloat

convenience proc to create an unsorted seq of rand floats with

default length ma = 10 ( always consider how much memory is in the system )

prec enables after comma precision up to 16 positions after comma

this is on a best attempt basis and may not work all the time

default after comma positions is prec = 3 max

form @0.34,0.056,... or similar

# create a seq with 50 rand floats
echo createSeqFloat(50)
# create a seq with 50 rand floats formatted
echo createSeqFloat(50,3)
proc createSeqFractur(): seq[string] {....raises: [ValueError], tags: [],
                                       forbids: [].}
createSeqFracture Fractur chars returned in a seq
proc createSeqGeoshapes(): seq[string] {....raises: [], tags: [], forbids: [].}

createSeqGeoshapes

returns a seq containing geoshapes unicode chars

proc createSeqHiragana(): seq[string] {....raises: [], tags: [], forbids: [].}

hiragana

returns a seq containing hiragana unicode chars

proc createSeqIching(): seq[string] {....raises: [], tags: [], forbids: [].}

createSeqIching

returns a seq containing iching unicode chars

proc createSeqInt(n: int = 10; mi: int = 0; ma: int = 1000): seq[int] {.inline,
    ...raises: [], tags: [], forbids: [].}

createSeqInt

convenience proc to create a seq of rand int with

default length 10

gives @4556,455,888,234,... or similar

# create a seq with 50 rand integers ,of set 100 .. 2000
# including the limits 100 and 2000
echo createSeqInt(50,100,2000)
proc createSeqKatakana(): seq[string] {....raises: [ValueError], tags: [],
                                        forbids: [].}

full width katakana

returns a seq containing full width katakana unicode chars

proc curFw(x: int = 1): auto {.discardable, ...raises: [IOError, ValueError],
                               tags: [WriteIOEffect], forbids: [].}

curFw

mirrors terminal Forward

proc curMove(up: int = 0; dn: int = 0; fw: int = 0; bk: int = 0) {.
    ...raises: [IOError, ValueError], tags: [WriteIOEffect], forbids: [].}

curMove

conveniently move the to where you need it

relative of current postion , which you app need to track itself

setting off terminal will wrap output to next line

proc cxBinomialCoeff(n, k: int): int {....raises: [], tags: [], forbids: [].}
proc cxCpuInfo(): string {....raises: [OSError, IOError],
                           tags: [ExecIOEffect, ReadIOEffect, RootEffect],
                           forbids: [].}

cxCpuInfo

executes a system command to get cpu information

proc cxind(indent: int; indchar: string = spaces(1)): string {....raises: [],
    tags: [], forbids: [].}
cxind indent by n using indchar, default is spaces(1)
proc cxInput(prompt: string; promptColor: string = greenYellow; xpos: int = 0;
             allowBlank: bool = false): string {.
    ...raises: [IOError, ValueError, EOFError],
    tags: [WriteIOEffect, ReadIOEffect], forbids: [].}

cxInput

simple input function with desired color and position if allowBlank is false then an alert message will be shown and function will wait for input again

allowBlank if set to true will allow "" as result

result is a string for further processing as needed.

cleanScreen()
curset(1,5)
var name = cxInput("Enter your name : ",yellowgreen,xpos=1)
curset(30,5)
var age = cxInput("Enter your age : ",yellowgreen,xpos=30)
curset(60,5)
var wallet = cxInput("Enter your Bitcoin wallet No : ",yellowgreen,xpos=60)
decho(2)
cxprintLn 1,satBlue,styleReverse,"Results "
cxprintln 1,yellowgreen,"Replies given : " ,termwhite, name,"  ",age," ",wallet
proc cxIsDigit(s: string; sep: char = '.'): bool {....raises: [], tags: [],
    forbids: [].}

cxIsDigit

checks if a string consists of elements in a digitset that is numbers 0..9 and separators like '.' or ',' default sep = '.'

proc cxlastN[T](aseq: T; n: int): T
cxlastN returns a seq with last n items of input seq
func cxLpad(s: string; padlen: int; paddy: string = spaces(1)): string {.
    ...raises: [], tags: [], forbids: [].}

cxlpad

pads a string on the left side with spaces to specified padlen

func cxLpadN(s: SomeNumber; padlen: int; paddy: string = "0"): string

cxlpadN

left pad for numbers

pads a number on the left side with "0" default or string to specified padlen

func cxLpadN(s: string; padlen: int; paddy: string = "0"): string {....raises: [],
    tags: [], forbids: [].}

cxlpadN

left pad for numbers

pads a string on the left side with "0" default or string to specified padlen

func cxLpdx(padLen: int; s: string; paddy: string = spaces(1)): string {.
    ...raises: [], tags: [], forbids: [].}

cxlpdx

same as cxpad but with padding char count in front

proc cxnormal(x, min, max: float): float {....raises: [], tags: [], forbids: [].}
normalize float
proc cxnormal(x, min, max: int): int {....raises: [], tags: [], forbids: [].}
normalize int
func cxpad(s: string; padlen: int; paddy: string = spaces(1)): string {.
    ...raises: [], tags: [], forbids: [].}

cxpad

pads a string on the right side with spaces to specified padlen

func cxpdx(padLen: int; s: string; paddy: string = spaces(1)): string {.
    ...raises: [], tags: [], forbids: [].}

pdx

same as cxpad but with padding char count in front

proc cxSeqToStr[T](asq: T): string
unpack a seq into a comma delimited string
proc cxtoLower(c: char): char {....raises: [], tags: [], forbids: [].}

cxtoLower

will be deprecated soon

use toLowerAscii()

proc cxVideoInfo(): string {....raises: [OSError, IOError],
                             tags: [ExecIOEffect, ReadIOEffect, RootEffect],
                             forbids: [].}

cxVideoInfo

executes a system command to get video setup information may show warning on certain systems to run as super user

lshw needs to be installed on your system see lshw man pages for much more

proc cxYesNo(prompt: string = "Continue "; promptColor: string = greenYellow;
             xpos: int = 0; allowBlank: bool = false): bool {.
    ...raises: [IOError, ValueError, EOFError],
    tags: [WriteIOEffect, ReadIOEffect], forbids: [].}

cxYesNo

returns a bool , any reply other than y , yes is false

proc distanceTo(origin: (float, float); dest: (float, float)): float {.
    ...raises: [], tags: [], forbids: [].}

distanceTo

calculates distance on the great circle using haversine formular

input is 2 tuples of (longitude,latitude)

Example

also see https://github.com/qqtop/Nim-Snippets/blob/master/geodistance.nim

import nimcx
echo "Hongkong - London"
echo distanceto((114.109497,22.396427),(-0.126236,51.500153)) , " km"
echo distanceto((114.109497,22.396427),(-0.126236,51.500153)) / 1.609345 ," miles"
decho()
proc doFlag[T](flagcol: string = yellowgreen; flags: int = 1; text: T = "";
               textcol: string = termwhite): string {.discardable.}

doFlag

prints a little flag

import nimcx

# print word Hello : in color dodgerblue followed by 6 little flags in red
# and the word alert in color truetomato followed by 6 little flags in red

print("Hello :  " & doflag(red,6,"alert",truetomato) & spaces(1) & doflag(red,6), dodgerblue)
proc fastsplit(s: string; sep: char): seq[string] {....raises: [], tags: [],
    forbids: [].}

fastsplit

code by jehan lifted from Nim Forum

maybe best results compile prog with : nim cc -d:release --gc:markandsweep

seperator must be a char type

proc fastWrite(f: File; s: string) {....raises: [IOError], tags: [], forbids: [].}

fastWrite

good for logging or vast file writes

based on code ex https://hookrace.net/blog/writing-an-async-logger-in-nim/

var fft:File
discard open(fft,"fast.txt",fmReadWrite)
fastWrite(fft,"test " * 100)
fft.close()
proc ff(zz: float; n: int = 5): string {....raises: [], tags: [], forbids: [].}
proc ff2(zz: SomeNumber; n: int = 3): string
proc ff2Eu(zzz: SomeNumber; n: int = 3): string

ff2Eu

convert a number into EU locale formatted string 1234567.123 --> 1.234.567,123 set after comma positions with n , default is 3

echo ff2Eu(1234567.123)
proc fibi(n: int): int64 {....raises: [], tags: [], forbids: [].}
proc fmtx[T](fmts: openArray[string]; fstrings: varargs[T, `$`]): string

fmtx

:: simple format utility similar to strfmt to accommodate our needs implemented : right or left align within given param and float precision returns a string and seems to work fine with strformat

Some observations:

If text starts with a digit it must be on the right side... Function calls must be executed on the right side

Space adjustment can be done with any "" on left or right side an assert error is thrown if format block left and data block right are imbalanced the "" acts as suitable placeholder

If one of the operator chars are needed as a first char in some text put it on the right side

Operator chars : < > .

<12 means align left and pad so that max length = 12 and any following char will be in position 13

12 means align right so that the most right char is in position 12 8.2 means align a float right so that most right char is position 8 with precision 2

Note that thousand separators are counted as position so 123456 needs echo fmtx("<10.2",123456) ---> 123,456.00

Examples :

import nimcx
echo fmtx(["","","<8.3",""," High : ","<8","","","","","","","",""],lime,"Open : ",unquote("1234.5986"),yellow,"",3456.67,red,downarrow,white," Change:",unquote("-1.34 - 0.45%"),"  Range : ",lime,@[123,456,789])
echo fmtx(["","<18",":",">15","","",">8.2"],salmon,"nice something",steelblue,123,spaces(5),yellow,456.12345676)
echo()
showRuler()
for x in 0.. 10: printlnBiCol(fmtx([">22",">10"],"nice something :",x ))
echo()
printLnBiCol(fmtx(["",">15.3f"],"Result : ",123.456789),lime,red,":",0,false,{})  # formats the float to a string with precision 3 the f is not necessary
echo()
echo fmtx([">22.3"],234.43324234)  # this formats float and aligns last char to pos 22
echo fmtx(["22.3"],234.43324234)   # this formats float but ignores position as no align operator given
printLnBiCol(fmtx([">15." & $getRndInt(2,4),":",">10"],getRndFloat() * float(getRndInt(50000,500000)),spaces(5),getRndInt(12222,10000000)))
proc fromCString(p: pointer; len: int): string {....raises: [], tags: [],
    forbids: [].}

fromCString

convert C pointer to Nim string (code ex nim forum https://forum.nim-lang.org/t/3045 by jangko)

proc fullGcStats(xpos: int = 2): int {.discardable,
                                       ...raises: [IOError, ValueError],
                                       tags: [WriteIOEffect], forbids: [].}
proc genMacAddress(): string {....raises: [], tags: [], forbids: [].}
generates a random MacAddress
loopy(1..10,echo genMacAddress())
proc getAscii(s: string): seq[int] {....raises: [], tags: [], forbids: [].}

getAsciicode

returns a seqint with ascii integer codes of every character in a string

proc getEmojisSmall(): seq[string] {....raises: [], tags: [], forbids: [].}

getEmojisSmall

a seq with 246 emojis will be returned

for easy use in your text strings

proc getPassword(ahash: int64 = 0'i64): string {....raises: [IOError, ValueError],
    tags: [WriteIOEffect, ReadIOEffect, ReadEnvEffect, TimeEffect], forbids: [].}

getPassword

convenience function, prompts user for a password to be checked against a passwordhash which could come from a security database or other source

proc getPointInSphere(): auto {....raises: [], tags: [], forbids: [].}

getPointInSphere

returns x,y,z coordinates for a point in sphere with max size 1,1,1

https://karthikkaranth.me/blog/generating-random-points-in-a-sphere/#better-choice-of-spherical-coordinates

# display 100 coordinates of in sphere points
for x in countup(0,99,1):
   let b = getPointinSphere()
   cxwriteln(fmtx(["","","",">7","","","",">7","","","",">7"],limegreen, "  x: ",white, b[0],limegreen,"  y: ",white,b[1],limegreen,"  z: ",white,b[2]))
proc getPrimeSeq(x, y: int): seq[int] {....raises: [], tags: [], forbids: [].}

getPrimeSeq

returns all primes from x to y in a seqint

showSeq(getPrimeSeq(5000,10000))

proc getProjectDir(): string {.compileTime, ...raises: [], tags: [], forbids: [].}
proc getRandomFloat(): float {....raises: [], tags: [], forbids: [].}

getRandomFloat

convenience proc so we do not need to import rand in calling prog

to get positive or negative rand floats multiply with getRandomSignF

proc getRandomPoint(minx: float = -500.0; maxx: float = 500.0;
                    miny: float = -500.0; maxy: float = 500.0): RpointFloat {.
    ...raises: [], tags: [], forbids: [].}

getRandomPoint

generate a random x,y float point pair and return it as RpointFloat

minx min x value maxx max x value miny min y value maxy max y value

for x in 1..10:
    let n = getRandomPoint(-500.00,200.0,-100.0,300.00)
    cxwriteln(fmtx(["",">3","",">4","",">7.2","","",">4","",">7.2"],
    "point ",$x,
    yellowgreen," x:",termwhite,ff2(n.x,4),
    spaces(3),
    yellowgreen," y:",termwhite,ff2(n.y,4)))
decho(2)
proc getRandomPoint(minx: int = -500; maxx: int = 500; miny: int = -500;
                    maxy: int = 500): RpointInt {....raises: [], tags: [],
    forbids: [].}

getRandomPoint

generate a random x,y int point pair and return it as RpointInt

min x or y value max x or y value

for x in 0..10:
    var n = getRandomPoint(-500,500,-500,200)
    cxwriteln(fmtx([">4",">5","",">6",">5"],"x:",$n.x,spaces(7),"y:",$n.y),spaces(7))
proc getRandomPointInCircle(radius: float = 1.0): seq[float] {....raises: [],
    tags: [], forbids: [].}

getRandomPointInCircle

based on answers found in

http://stackoverflow.com/questions/5837572/generate-a-random-point-within-a-circle-uniformly

import nimcx
# get randompoints in a circle
var crad:float = 2.1
for x in 0..100:
    var k = getRandomPointInCircle(crad)
    assert k[0] <= crad and k[1] <= crad
    if k[0] <= crad and k[1] <= crad:
        printLnBiCol(fmtx([">25","<6",">10"],ff2(k[0])," :",ff2(k[1])))
    else:
        printLnBiCol(fmtx([">25","<6",">10"],ff2(k[0])," :",ff2(k[1])),colLeft=red,colRight=red)
proc getRandomSignF(): float {....raises: [], tags: [], forbids: [].}

getRandomSignF

returns -1.0 or 1.0 float to have a rand positive or negative multiplier

proc getRandomSignI(): int {....raises: [], tags: [], forbids: [].}

getRandomSignI

returns -1 or 1 integer to have a rand positive or negative multiplier

proc getRndBool(): bool {....raises: [], tags: [], forbids: [].}
getRndBool
proc getRndFloat(): float {....raises: [], tags: [], forbids: [].}

getRndFloat

same as getrandFloat()

proc getRndInt(mi: int = 0; ma: int = int.high): int {.noInit, inline,
    ...raises: [], tags: [], forbids: [].}
getRndInt
proc getUserName(): string {....raises: [IOError],
                             tags: [ReadIOEffect, WriteIOEffect], forbids: [].}
proc isBlank(val: string): bool {.inline, ...raises: [], tags: [], forbids: [].}

isBlank

returns true if a string is blank

proc isEmpty(val: string): bool {.inline, ...raises: [], tags: [], forbids: [].}

isEmpty

returns true if a string is empty if spaces are removed

proc isNumeric(s: string): bool {....raises: [], tags: [], forbids: [].}
proc memCheck(stats: bool = false) {....raises: [IOError, ValueError, OSError,
    Exception], tags: [WriteIOEffect, ReadEnvEffect, ReadIOEffect, RootEffect,
                       TimeEffect], forbids: [].}

memCheck

memCheck shows memory before and after a GC_FullCollect run

set stats to true for full GC_getStatistics @1, 2, 4, 8, 16, 32

proc newHiragana(minwl: int = 3; maxwl: int = 10): string {.
    ...raises: [IOError, ValueError], tags: [WriteIOEffect], forbids: [].}

newHiragana

creates a random hiragana word without meaning from the hiragana unicode set

default min word length minwl = 3

default max word length maxwl = 10

proc newKatakana(minwl: int = 3; maxwl: int = 10): string {.
    ...raises: [ValueError, IOError], tags: [WriteIOEffect], forbids: [].}

newKatakana

creates a random katakana word without meaning from the katakana unicode set

default min word length minwl = 3

default max word length maxwl = 10

proc newLine(n: int = 1): string {....raises: [], tags: [], forbids: [].}
issues n newLines , default = 1
proc newText(textLen: int = 1000; textgen: string = "newWord"): string {.
    ...raises: [IOError, ValueError], tags: [WriteIOEffect], forbids: [].}

newText

creates random text made up of random chars from

var. newWord procs

textgen can be one of :

newWord newWord2 newWord3 newHiragana newKatakana newWordCJK

printLn(newText(10000,"newHiragana"),rndcol)
proc newWord(minwl: int = 3; maxwl: int = 10): string {.
    ...raises: [IOError, ValueError], tags: [WriteIOEffect], forbids: [].}

newWord

creates a new lower case random word with chars from Letters set

default min word length minwl = 3

default max word length maxwl = 10

proc newWord2(minwl: int = 3; maxwl: int = 10): string {.
    ...raises: [IOError, ValueError], tags: [WriteIOEffect], forbids: [].}

newWord2

creates a new lower case random word with chars from IdentChars set

default min word length minwl = 3

default max word length maxwl = 10

proc newWord3(minwl: int = 3; maxwl: int = 10; nflag: bool = true): string {.
    ...raises: [IOError, ValueError], tags: [WriteIOEffect], forbids: [].}

newWord3

creates a new lower case random word with chars from AllChars set if nflag = true

creates a new anycase word with chars from AllChars set if nflag = false

default min word length minwl = 3

default max word length maxwl = 10

proc newWordCJK(minwl: int = 3; maxwl: int = 10): string {.
    ...raises: [ValueError, IOError], tags: [WriteIOEffect], forbids: [].}

newWordCJK

creates a new random string consisting of n chars default = max 10

with chars from the cjk unicode set

http://unicode-table.com/en/#cjk-unified-ideographs

requires unicode

# create a string of chinese or CJK chars with length 20
echo newWordCJK(20,20)
proc pathsandsettings() {....raises: [IOError, ValueError], tags: [WriteIOEffect],
                          forbids: [].}
proc product[T](aseq: seq[T]): T

product

returns product of float or int seqs

if a seq contains a 0 element than result will be 0

proc pswwaux() {....raises: [OSError, IOError],
                 tags: [ExecIOEffect, ReadIOEffect, RootEffect], forbids: [].}

pswwaux

utility bash command : ps -ww aux | sort -nk3 | tail displays output in console

proc quickBinaryString(width: int = 10): string {....raises: [], tags: [],
    forbids: [].}

quickBinaryString

returns a random binary string with desired width

proc quickClean() {....raises: [IOError], tags: [WriteIOEffect], forbids: [].}

quickClean

very fast clear screen proc with escape seqs

cursor is temporarily disabled

proc quickLargeInt(): string {....raises: [], tags: [], forbids: [].}

quickLargeInt

returns a random large int string

proc quickPw(l: int = 1): string {....raises: [], tags: [], forbids: [].}

quickPw

quick strong password generator

quick strong password generator

proc randpos(): int {....raises: [IOError, ValueError],
                      tags: [WriteIOEffect, ReadEnvEffect], forbids: [].}

randpos

sets to a random position in the visible terminal window

returns x position

while 1 == 1:
   for z in 1.. 50:
      print($z,randcol(),xpos = randpos())
   sleepy(0.0015)
proc remapFloatToInt(s: seq[float]): seq[int] {....raises: [], tags: [],
    forbids: [].}
remapFloatToInt
proc remapIntToFloat(s: seq[int]): seq[float] {....raises: [], tags: [],
    forbids: [].}
remapIntToFloat
proc remapToString[T](s: seq[T]): seq[string]
remapToString
proc reverse[T](s: var seq[T])

reverse

in place reverse sequence

proc reverseMe[T](xs: openArray[T]): seq[T]

reverseMe

reverse a sequence

var z = @["nice","bad","abc","zztop","reverser"]
printLn(z,lime)
printLn(z.reverseMe,red)
proc reverseString(text: string): string {....raises: [], tags: [], forbids: [].}

reverseString

reverses chars in a word

var s = "A text to reverse could be this example 12345.0"
echo "Original      : " & s
echo "reverseText   : " & reverseText(s)
echo "reverseString : " & reverseString(s)
# check if back to original is correct
assert s == reverseString(reverseString(s))
proc reverseText(text: string): string {....raises: [], tags: [], forbids: [].}

reverseText

reverses words in a sentence

proc rndRGB(): auto {....raises: [], tags: [], forbids: [].}

rndRGB

returns a random RGB value from colors available in colorNames see cxconsts.nim for available values

proc rndSample[T](asq: seq[T]): T
rndSample returns one rand sample from a sequence
proc rndStr(n: int = 20): string {....raises: [ValueError, IOError],
                                   tags: [WriteIOEffect], forbids: [].}

rndStr

random string with len n between 0 and hex 4DB5

proc sampleSeq[T](x: seq[T]; a: int; b: int): seq[T]

sampleSeq

returns a continuous subseq a..b from an array or seq if a >= b

import nimcx
let x = createSeqInt(20)
echo x
echo x.sampleseq(4,8)
echo x.sampleSeq(4,8).rndSample()    # get one randly selected value from the subsequence
proc seqHighLite[T](b: seq[T]; b1: seq[T]; col: string = gold)

seqHighLite

displays the passed in seq with highlighting of subsequence

import nimcx
var b = createSeqInt(30,1,10)
seqHighLite(b,@[5])   # subseq will be highlighted if found
proc seqLeft[T](it: seq[T]; n: int): seq[T]

seqLeft

returns a new seq with n left end elements of the original seq

proc seqRight[T](it: seq[T]; n: int): seq[T]

seqRight

returns a new seq with n right end elements of the original seq

proc shift[T](x: var seq[T]; zz: Natural = 0): T

shift takes a seq and returns the first item, and deletes it from the seq

build in pop does the same from the other side

var a: seq[float] = @[1.5, 23.3, 3.4]
echo shift(a)
echo a
proc showCpuCores() {....raises: [IOError, ValueError],
                      tags: [WriteIOEffect, ReadEnvEffect], forbids: [].}
showCpuCores
proc showCpuInfo() {....raises: [IOError, ValueError, IOError, ValueError], tags: [
    WriteIOEffect, ReadEnvEffect, ExecIOEffect, ReadIOEffect, RootEffect],
                     forbids: [].}
proc showEmojisSmall() {....raises: [IOError, ValueError, Exception],
                         tags: [WriteIOEffect, ReadEnvEffect], forbids: [].}

showEmojisSmall

show a table of small emojis

Example

showEmojisSmall()
let es = getemojisSmall()
loopy(0..10,printLn((es[197] & es[244] & es[231] ) * 20,rndcol))
proc showHostNameCtl() {....raises: [IOError, ValueError, OSError], tags: [
    WriteIOEffect, ReadEnvEffect, ExecIOEffect, ReadIOEffect, RootEffect],
                         forbids: [].}

showHostNameCtl

output of system hostnamectl command

proc showRandomCard(xpos: int = centerX()) {....raises: [IOError, ValueError],
    tags: [WriteIOEffect, ReadEnvEffect], forbids: [].}

showRandomCard

shows a random card at xpos from the cards set in cxconstant.nim, default is centered

proc showRuler(xpos: int = 0; xposE: int = 0; ypos: int = 0;
               fgr: string = white; bgr: string = getBg(bgDefault);
               vert: bool = false) {....raises: [IOError, ValueError],
                                     tags: [ReadEnvEffect, WriteIOEffect],
                                     forbids: [].}

ruler

simple terminal ruler indicating dot x positions starts with position 1

horizontal --> vert = false

for vertical --> vert = true

# this will show a full terminal width ruler
showRuler(fgr=pastelblue)
decho(3)
# this will show a specified position only
showRuler(xpos =22,xposE = 55,fgr=pastelgreen)
decho(3)
# this will show a full terminal width ruler starting at a certain position
showRuler(xpos = 75,fgr=pastelblue)
proc showRune(s: string): string {.discardable, ...raises: [ValueError], tags: [],
                                   forbids: [].}

showRune :: utility proc to show a single unicode char given in hex representation note that not all unicode chars may be available on all systems

Example

proc showSeq[T](z: seq[T]; fgr: string = pastelgreen; cols = 6;
                maxitemwidth: int = 5; displayflag: bool = true; indexstart = 0): string {.
    discardable.}

showSeq

simple table routine with default 6 cols for displaying various unicode sets fgr allows color display and fgr = "rand" displays in rand color and maxwidth for displayable items this can also be used to show items of a sequence displayflag == true means to show the output displayflag == false means do not show output , but return it as a string indexstart == 0 displays item index from 0 or from whatever indexstart is set to .. code-block:: nim showSeq(createSeqCJK(),"rand",indexstart=1) showSeq(createSeqKatakana(),yellowgreen) showSeq(createSeqCJK(),"rand") showSeq(createSeqGeoshapes(),randcol()) showSeq(createSeqint(1000,10000,100000))

Example:

discard showSeq(createSeqCJK(),"rand")
proc spiralBoxy(w: int = 20; h: int = 20; xpos: int = 1) {.
    ...raises: [IOError, ValueError], tags: [WriteIOEffect], forbids: [].}
spiralBoxy
proc spiralBoxy2(w: int = 20; h: int = 20; xpos: int = 1) {.
    ...raises: [IOError, ValueError], tags: [WriteIOEffect], forbids: [].}
spiralBoxy2 uses boxy2
proc splitty(txt: string; sep: string): seq[string] {....raises: [], tags: [],
    forbids: [].}

splitty

same as build in split function but this retains the

separator on the left side of the split

z = splitty("Nice weather in : Djibouti",":")

will yield:

Nice weather in : Djibouti

rather than:

Nice weather in Djibouti

with the original split()

proc streamFile(filename: string; mode: FileMode): FileStream {....raises: [],
    tags: [], forbids: [].}

streamFile

creates a new filestream opened with the desired filemode

proc stripFirstLast(astring: string): string {....raises: [], tags: [], forbids: [].}
stripFirstLast strips first and last char of a string
proc stripper(str: string): string {....raises: [], tags: [], forbids: [].}
proc sum[T](aseq: seq[T]): T

sum

returns sum of float or int seqs

same effect as math.sum

proc sumc(n: int): float {....raises: [], tags: [], forbids: [].}
proc superHeader(bstring: string) {....raises: [IOError, ValueError],
                                    tags: [ReadEnvEffect, WriteIOEffect],
                                    forbids: [].}

superheader

a framed header display routine

suitable for one line headers , overlong lines will

be cut to terminal window width without ceremony

proc superHeader(bstring: string; strcol: string; frmcol: string) {.
    ...raises: [IOError, ValueError], tags: [ReadEnvEffect, WriteIOEffect],
    forbids: [].}

superheader

a framed header display routine

suitable for one line headers , overlong lines will

be cut to terminal window size without ceremony

import nimcx

superheader("Ok That's it for Now !",skyblue,lightslategray)
echo()
proc tupleToStr(xs: tuple): string

tupleToStr

tuple to string unpacker , returns a string

code ex nim forum

echo tupleToStr((1,2))         # prints (1, 2)
echo tupleToStr((3,4))         # prints (3, 4)
echo tupleToStr(("A","B","C")) # prints (A, B, C)
proc tupleTypes(atuple: tuple): seq[string]

tupletypes

returns the field types of a tuple in a seqstring

proc uniform(a, b: float): float {.inline, ...raises: [], tags: [], forbids: [].}

uniform

returns a rand float uniformly distributed between a and b

# run in terminal with min. 30 rows
import nimcx,stats
proc quickTest() =
     var ps : Runningstat
     var  n = 100_000_000
     printLnBiCol("Each test loops : " & $n & " times\n\n")
     
     for x in 0..<n: ps.push(uniform(0.00,100.00))
     printLn("uniform",salmon)
     showStats(ps)
     ps.clear
     for x in 0..<n: ps.push(getRandomFloat() * 100)
     curup(15)
     printLn("getRandomFloat * 100",salmon,xpos = 30)
     showStats(ps,xpos = 30)
     
     ps.clear
     for x in 0..<n: ps.push(getRndInt(0,100))
     curup(15)
     printLn("getRndInt",salmon,xpos = 60)
     showStats(ps,xpos = 60)

quickTest()
doFinish()
proc unquote(s: string): string {....raises: [], tags: [], forbids: [].}

unquote

remove any double quotes from a string

proc utf8info(s: string): string {....raises: [ValueError], tags: [], forbids: [].}

utf8info

returns hex and int code for each char in string in a vertical list

echo utf8info("すべての数字はどこですか?")
echo utf8info("我们希望情况会尽快好转。")

Iterators

iterator primey(s: int = 0; e: int): int {....raises: [], tags: [], forbids: [].}

primey

yields prime numbers from s to e within maxinteger range var maxint = 9223372036854775807 # on 64 system

var cp = 0
for xxx in primey(s=100_000_000,e=100_005_000):
   inc cp
   echo xxx
echo cp," primes found"
iterator reverseIter[T](a: openArray[T]): T
reverse iterator
let a = createseqfloat(10)
for b in reverse(a): echo b
iterator span(s: string; first: int; last: BackwardsIndex): char {....raises: [],
    tags: [], forbids: [].}

span

iterator for strings

let s = ".something"
for c in s.span(1, ^1):   # first and index pos must be given
    print c
echo()

Converters

converter toTwInt(x: cushort): int {....raises: [], tags: [], forbids: [].}

Macros

macro cxgetType(s: typed): untyped

cxgetType

answers what type is it question in newer nim versions just use type(s)

macro procName(x: untyped): untyped

procName prints the name of the proc if annoited with pragma {.procName.}

Example .. code-block:: nim proc yippi(s:string) : string {.procName.} = result = s & "007"

printLn(yippi("Mouse"))

macro styledEchoPrint(m: varargs[untyped]): untyped
partially lifted from an earler macro in terminal.nim and removed new line improvements suggested by araq to avoid the since deprecated callsite()
macro toEnum(words: static[string]): untyped

toEnum

lifted from nim-blog

Example .. code-block:: nim type Color = toEnum("Red Green Blue Indigo")

Templates

template `*`(s: string; n: int): untyped
returns input string n times mimicking python
template `<>`(a, b: untyped): untyped
unequal operator
template aPaletteSample(coltype: string): int

aPaletteSample

returns a rand entry (int) from a palette see example at colPalette

template bitCheck(a, b: untyped): bool

bitCheck

check bitsets

template clearup(x: int = 80)

clearup

a convenience proc to clear monitor x rows

template colorsPalette(coltype: string): auto

:: colorsPalette

returns a colorpalette which can be used to iterate over

import nimcx
let z = "The big money waits in the bank"
for _ in 0..10:
   printLn(z,colPalette("pastel",getRndInt(0,colPaletteLen("pastel") - 1)),styled={styleReverse})
   print(cleareol)
doFinish()
template colPalette(coltype: string; n: int): auto

:: colPalette

returns a specific color from the palette which can be used in print statements

if n > larger than palette length the first palette entry will be used

import nimcx
cleanScreen()
decho()
var mycol = "light"
mycol = mycol.lowerCase()
let somesample = aPaletteSample(mycol)
printLn($somesample & "th color of the " & mycol & " palette  ( index starts with 0 )", colPalette(mycol,somesample))
printLn("Name of the " & $somesample & "th entry : " & colPaletteName(mycol,somesample))
echo()
printLn("Random color of the " & mycol & " palette ", colPalette(mycol,aPaletteSample(mycol)))
printLn("Length of " & mycol & " palette: " & $colPaletteLen(mycol) & " ( index starts with 0 )" )
echo()
loopy2(0,colPaletteLen(mycol)):
    printLn("Here we go " & rightarrow * 3 & spaces(2) & colPaletteName(mycol,xloopy), colPalette(mycol,xloopy))
doFinish()
template colPaletteIndexer(colx: seq[string]): auto
template colPaletteLen(coltype: string): auto

colPaletteLen

returns the len of a colPalette of colors in colorNames

template colPaletteName(coltype: string; n: int): auto

colPaletteName

returns the actual name of the palette entry n eg. "mediumslateblue" see example at colPalette

template curBk(x: int = 1)

curBkn

mirrors terminal Backward

template curDn(x: int = 1)

curDn

mirrors terminal Down

template curOff()

curOff

off , mirrors function hideCursor from terminal.nim

template curOn()

curOn

on , mirrors function showCursor from terminal.nim

template currentLine()

currentLine

simple template to return line number , maybe usefull for debugging

template curSet(x: int = 0; y: int = 0)

curSet

mirrors terminal setCursorPos at x,y position

template curSetx(x: int)

curSetx

mirrors terminal setCursorXPos

template curUp(x: int = 1)

curUp

mirrors terminal Up

template cxPos(x): string

cxPos

mirrors terminal setCursorXPos

template doSomething(secs: int; body: untyped)

doSomething

execute some code for a certain amount of seconds

doSomething(10,myproc())  # executes my proc for ten secs   , obviously this will fail if your proc uses sleep...
template getCard(): auto

getCard

gets a random card from the Cards seq

import nimcx
printLn(getCard(),randCol(),xpos = centerX())  # get card and print in random color at xpos
doFinish()
template hdx(code: untyped; frm: string = "+"; width: int = tw; nxpos: int = 0): void

hdx

a simple sandwich frame made with + default or any string passed in

width and xpos can be adjusted

hdx(printLn("Nice things happen randomly",yellowgreen,xpos = 9),width = 35,nxpos = 5)
template loopy[T](ite: T; st: untyped)

loopy

simple for-loop template

loopy(0..<10,printLn("The house is in the back.",randcol()))
template loopy2(mi: int = 0; ma: int = 5; st: untyped)

loopy2

the advanced version of loopy the simple for-loop template which also injects the loop counter xloopy if loopy2() was called with parameters if called without parameters xloopy will not be injected .

# create 10 random passwords and show the index on left
loopy2(1,10,printLnBiCol(fmtx([">3","","",],xloopy,": ",quickPw())))
template lowerCase(s: string): string

lowerCase

lower cases a string

template paletix(pl: string): untyped

paletix

returns a random color from colorNames containing the string pl

so paletix("pastel") filters on all colorNames having the string "pastel"

if filter not available then the first available color will be used

loopy2(1,10):
   var s = " Hello from NimCx !  " & $xloopy
   centerpos(s)
   printLn(cxpad(s,25),paletix("blue"),styled={styleReverse,styleItalic,styleBright})
echo()
template randCol(): string

randCol

get a randcolor from colorNames , no filter is applied

# print a string 6 times in a rand color selected from colorNames
loopy(0..5,printLn("Hello Random Color",randCol()))
template randCol2(coltype: string): auto

:: randCol2 -- experimental

returns a rand color based on a palette

palettes are filters into colorNames

coltype examples : "red","blue","medium","dark","light","pastel" etc..

loopy(0..5,printLn("Random blue shades",randcol2("blue")))
template randPastelCol(): string

randPastelCol

get a randcolor from pastelSet

# print a string 6 times in a rand color selected from pastelSet
loopy(0..5,printLn("Hello Random Color",randPastelCol()))
template rndCol(r: int = getRndInt(0, 254); g: int = getRndInt(0, 254);
                b: int = getRndInt(0, 254)): string

rndCol

return a randcolor from the whole rgb spectrum in the ranges of RGB 0..254 expect this colors maybe a bit more drab than the colors returned from randCol()

# print a string 6 times in a rand color selected from rgb spectrum
loopy(0..5,printLn("Hello Random Color",rndCol()))
template th(): int
th , a global where latest terminal height is always available
template toki(s: untyped): untyped

toki

tokenizes input string and returns token in a seqstring

var b = "酢の一種"
let s = &"a + b = 12 3.5% & {b}"
echo toki(s)
template tw(): int
tw , a global where latest terminal width is always available
template unidecodeU(ustring: untyped): untyped

unidecodeU

decode u escaped strings like "u96e8u3002" based on code by yglukhov ex Nim Forum

printLn(unidecodeU("\u5f9e\u6e05\u6668\u958b\u59cb\u4e00\u76f4\u4e0b\u96e8\u3002" & spaces(2) & "\u96e8\u3002"),yellowgreen)
template upperCase(s: string): string

upperCase

upper cases a string

template withFile(f, fn, mode, actions: untyped): untyped

withFile

easy file handling template , which is using fileStreams

f is a file handle fn is the filename mode is fmWrite,fmRead,fmReadWrite,fmAppend or fmReadWriteExisiting

Example 1

let curFile="/data5/notes.txt"    # some file
withFile(fs, curFile, fmRead):
    var line = ""
    while fs.readLine(line):
        printLn(line,yellowgreen)