Created my first binding! I am impressed!

2024-08-16 Thread jackhftang
FYI, Nim can also inline code, though its usage is discouraged. {.emit:""" static char* hello_world() { return "Hello, World!"; } """.} proc hello_world(): cstring {.importc: "hello_world".} echo hello_world() Run

StableSeq

2024-07-01 Thread jackhftang
Here is another sequence of capacities 1,1,2,2,4,4,8,8... with a growth rate of sqrt(2) = 1.414, This seems to be a good balanced choice. import bitops type StableSeq*[T] = object len: int # sizeof(data[i]) == pow(2, i div 2) data: seq[ptr Unche

StableSeq

2024-06-30 Thread jackhftang
I am sorry if my comments cause disturbance in current disscusion. I try to keep this one short. @cblake `std/deques` is built upon [seq](https://github.com/nim-lang/Nim/blob/version-2-0/lib/pure/collections/deques.nim#L61) which is not stable/pinned/mobile If the cap is pre-defined, the addre

StableSeq

2024-06-30 Thread jackhftang
Feel free to copy/modify. To be in stdlib, I think at least there have to be more tests and I am sure there are improvements after code review. Btw, I don't understand why you want a no-reallocation data structure? It seems a niche use case to me.

StableSeq

2024-06-30 Thread jackhftang
There is are functional data structure call [FingerTree](https://www.staff.city.ac.uk/~ross/papers/FingerTree.html) which is normally used for immutable seq. But it can be modified to be mutable and 'no-reallocation' to suite your need. The core idea of finger tree is that at each level, keep `

Cheap exceptions, opinionated error handling

2024-06-01 Thread jackhftang
I would like add my two cents on this topic from software engineering viewpoint. Before comment on the proposal, I want to state some opinionated principles about error handling. 1. Each component should only catch an exception if and only if the component is responisble to handle the excepti

How to serve acme-challenge file dynamically with Jester REST API?

2024-04-15 Thread jackhftang
minor correction. Of course put `certbot renew` in crontab and it is recommended to renew once a day and avoid to renew at XX:00 sharp to reduce surge to letsencrypt server.

Logarithm Implementation Tutorial

2024-03-28 Thread jackhftang
First and foremost, thanks for the effort of making tutorials. I will explain the binary search method in this post. To get an intiution on how the algorithm work, let's consider only x >= 1 first. And I assume readers should already know the following equalities. log2(x) = 1 + l

Logarithm Implementation Tutorial

2024-03-27 Thread jackhftang
To be honest, 1. There is no need to compute `pow(E, result)` twice. 2. A fast numerical way should use polynomial approximation. see [musl implementation](https://git.musl-libc.org/cgit/musl/tree/src/math/log.c) 3. `pow` should not be used, not to say inside while loop. Also, implementati

How can I create a process completely detached of my process?

2023-05-06 Thread jackhftang
That is called **fork**.

How to Save Directory Listing into Variable.

2023-03-16 Thread jackhftang
Want to add that you can also use `toSeq` in `sequtils` import std/[os, rdstdin, sequtils] let userInput = readLineFromStdin "Enter a directory > " let filePaths = toSeq(walkDir(userInput, relative = true)) .filterIt(it.kind == pcFile) .mapIt(it.path) echo

How to reproduce the release build of Nim?

2023-03-14 Thread jackhftang
I have an 3-yr old private Nim project that is still able to reproduce binary-equal build and run. Here is the dockerfile I use in CI. FROM nimlang/nim:1.2.6 as build # docker image prune --filter label=stage=builder LABEL stage=build WORKDIR /mnt # cop

Shared global var in ORC?

2023-03-12 Thread jackhftang
> why compiler needs to explicitly mark that proc as gcsafe? Can't compiler > infer that automatically? Because `serve` explicitly [marked to require gcsafe](https://github.com/nim-lang/Nim/blob/v1.6.12/lib/pure/asynchttpserver.nim#L405) it is like compiler won't automatically cast int32 to int

Make Nim docker images official?

2023-03-12 Thread jackhftang
One more thing, could @moigagoo transfer the repo to [nim-lang organization](https://github.com/nim-lang) if this repo is really official.

What would be the bast way to get parsing and validation of parameters (option:value)

2023-01-13 Thread jackhftang
I realized that what I foresee the way to implement may not be what you get. Since I have not coded nim for some time, I decided to do an exercise... but it took longer than I thought T^T... Anyway, the following program have done 1. string option with choices 2. int option range validation

What would be the bast way to get parsing and validation of parameters (option:value)

2023-01-12 Thread jackhftang
> I am curious how would you implement this. Without using 100 line long case > statements, for each option. I would say the keyword is **parser combinator** (PC). You can write customized parser for each option and then combine them with combinators. And you can achieve all 3 bonus features to

Readability problems

2021-11-13 Thread jackhftang
Strictly speaking, the `proc` that convert any type to `JsonNode` is named `%`, not `%*`. `%*` is a macro that let you write inline json in a nature way. Alternatively, you can write like this. import json let j1 = {"j": %10,"s": %20,"o": %100,"n": %5000} echo %j1

Plotting library

2021-10-30 Thread jackhftang
If you already have experience with matplotlib in python, it may be convenient to transfer the knowledge to nim via nimpy. The usage is almost the same. As an example: import std/[math, sequtils] import nimpy let xs = toSeq(1..1000).mapIt(it/10) let ys = xs.mapIt(si

Block-chain binary certification

2021-10-09 Thread jackhftang
Because it is an **undecidable problem**. The only **universal** way to know the result of arbitrary program is to run it. And whenever running a program (in Turing-complete language), you have to face the non-halting problem. You will never know whether the program will end or at some point ge

Is there a way to get value as if it's reference and update it's value?

2021-09-05 Thread jackhftang
FYI, for truly functional programming style, you should think of returning a new table value and use **lenses** to help you get/set values in nested structures.

Print why assert failed?

2021-08-14 Thread jackhftang
> If it's server, you need to re-create all the condition to hit it.` This means what you actually need is a real logger, not assert. `assert` is not a logger and cannot replace a logger. A nice example of logger is [chronicles](https://github.com/status-im/nim-chronicles) Yes, reproducing prod

Nim enters top 50 programming languages list on TIOBE Index!

2021-08-06 Thread jackhftang
That is amazing! You may argue that TIOBE index does not actually reflect the real popularity of a language, but TIOBE index is among the famous one. Undeniably, this is a successful marketing campaign (by accident maybe). If Nim can keep it on the list, the real popularity will grow organically

problem of run procedure with interval and stop the running

2021-07-18 Thread jackhftang
I guess this is what you want. import asyncdispatch type Action = proc(): void {.gcsafe.} proc runInterval(cb: Action, interval: int): Future[Action] {.async.} = var running = true result = proc() = running = false proc loop() =

How to http post nested data?

2021-05-05 Thread jackhftang
[multipart/mixed](https://www.rfc-editor.org/rfc/rfc2046.html#section-5.1) actually allow different mime type per part, but current `MultipartEntry` implementation do not support it.

collision-resistant hash for 64bit pointers

2021-04-24 Thread jackhftang
Sample code of the above idea. Not verified =] import heapqueue import strutils import strformat import bitops import algorithm proc findMinCollision*(nVec: int, xs: seq[float]): (float, seq[int]) = var n = xs.len # ps[i] = probability of co

collision-resistant hash for 64bit pointers

2021-04-24 Thread jackhftang
Your problem can be viewed as noisy-channel encoding. Though in practice we map a block to larger space, your case is mapping to a smaller space, but the mathematical structure is the same. There is a family of coding call [linear code](https://en.wikipedia.org/wiki/Linear_code) . Given you **do

4th Nim online meetup

2021-04-23 Thread jackhftang
> yes, we break code when changing the major version from 1.x to 2.x which is > to be expected. Does it mean that all nimble modules that currently importing `json` will not be compiled in Nim2? This sounds really terrible... IMO, stdlib should employ stability index like `this

hashing stored passwords

2021-04-18 Thread jackhftang
argon2 is available in libsodium. Look for `crypto_pwhash_argon2id`.

Nim on raspberry PI

2021-04-18 Thread jackhftang
I did something like this nim proc hardReset*(pin: int) = writeFile("/sys/class/gpio/export", $pin) writeFile(fmt"/sys/class/gpio/gpio{pin}/direction", "out") writeFile(fmt"/sys/class/gpio/gpio{pin}/value", "0") sleep 100 writeFile(fmt"/s

Nim convention for multiple imports?

2021-04-17 Thread jackhftang
IMO, there are languages designed to limit the number of ways of express things. Those languages are usually intended to be used in enterprise environment, so that everyone somehow write syntactically same code. Nim, on the other hand, is more indie, more free style. All your examples are **val

Why is there no compile error when accessing uninitialize variable

2021-03-31 Thread jackhftang
Maybe I should use the words _many demands_ instead of _high expectation_. This is closer to what I mean.

Why is there no compile error when accessing uninitialize variable

2021-03-31 Thread jackhftang
Isn't this common behavior? Popular languages like C/C++, Java, Go... all compile fine without initializing fields of struct/class. Though you may get some warnings in some IDE. All you need to do is to make the fields private and provide constructors. Sometimes, I am wondering why people have

Processing elements of a sequence with conditional deletion

2021-03-30 Thread jackhftang
When there was no iterators (e.g. C) or not that popular in the past. It is usually done by keeping two index and scan. This keeps the elements' order (stable). var xs = @[1,2,3,4] var i,j = 0 while j < xs.len: # check xs[j] if xs[j] mod 2 == 0: # to

Criticism of Parallel Nim

2021-03-13 Thread jackhftang
I have read your [long previous post](https://forum.nim-lang.org/t/7583#48122) together with this one. My overall feeling is that you are shooting yourself in your foot. If you have some custom synchronize functions and you want to use it in web server, then create dedicated threads to those ta

Mixing Threads and Async

2021-02-26 Thread jackhftang
btw, here is another example with true multi-threaded application using [threadproxy](https://github.com/jackhftang/threadproxy.nim) which is designed to simplify Nim inter-thread communication, but again it is not `squeeze out the maximum performance` type. Also, just like others have said

Mixing Threads and Async

2021-02-26 Thread jackhftang
deal with the same problem before. You can download http_client_pool [here](https://gist.githubusercontent.com/jackhftang/7399552e0902421a6de276b8e7483e4c/raw/973fb86d300751aacc46c28261fd29f6b575f2f9/http_client_pool.nim) which wrap AsyncHttpClient for timeout and pooling. The implementation

Back on Nim: Understanding nimble

2021-01-14 Thread jackhftang
If you are writing packages for other packages, it is better to use range requires "foo >= 0.1.2 & < 0.2.0" requires "bar >= 1.3.1 & < 2.0" Run Also, be more considerate on Nim verison, don't be too aggressive using the latest one requires "nim >= 1.

Unnecessary var parameter?

2020-12-30 Thread jackhftang
For `new`, you can write like this `let foo = new(Foo)` at least since 1.0.0 As for hashset and thread, they are not ref/ptr, but value in Nim semantic. And you can call `initHashSet()` instead of `s.init()`.

Advent of Nim 2020 megathread

2020-12-25 Thread jackhftang
Finally, AOC 2020 comes to an end. This is my first year playing AOC with Nim and also my first year getting all 50 stars! During these 25 days, we have gone through a range of different topics from geometry e.g. 4,6,8,26-neighbors; to number theory e.g. linear congruence, discrete logarithm p

Cancelation points in async

2020-12-24 Thread jackhftang
If your goal is just to have a timeout future, I have an example that wrap the `request` proc for `asyncHttpClient` which do not support pooling and timeout yet. proc request*( pool: HttpClientPool, url: string, httpMethod: string, body = "", headers: H

Client-side JS with Nim

2020-12-24 Thread jackhftang
FYI, I made a quick test on the generated js file size for the following code. import times echo now() Run I compiled the code in debug, release, release+danger mode. Also, I used google closure compiler (gcc) in simple mode for minification. And also, I wrap the

Advent of Nim 2020 megathread

2020-12-23 Thread jackhftang
btw, last two days to go, cheer guys~~

Advent of Nim 2020 megathread

2020-12-23 Thread jackhftang
, SinglyLinkedNode]` for lookup (an array maybe better actually). [My solution](https://github.com/jackhftang/adventofcode2020/blob/main/day23/day23_2.nim) is only one main proc. This is the same code as my final submission to AOC 1331/447.

Looper - Another web framework written in Nim

2020-12-19 Thread jackhftang
I am curious to know the reasons behind to choose chronos.

Advent of Nim 2020 megathread

2020-12-18 Thread jackhftang
Yes, nim macro is Turing complete. Macro solution for part 1. import macros import sequtils import strutils proc `-`(a,b: int): int = a * b macro eval(s: static[string]): untyped = let ns = s.splitLines.mapIt(parseExpr(it.replace("*", "-"))) resu

Ideal design for a general purpose SparseSet?

2020-12-11 Thread jackhftang
First, I should clarify my stance. I am not interested in development of SparseSet, but I am happy if in the end this can lead to a better library. Also, the `SparseSet` is copied from @b3liever I failed to import his lib from nimble via url and I don't have time to fix it and I just copy the co

Ideal design for a general purpose SparseSet?

2020-12-10 Thread jackhftang
If performance is the primary concern (regardless ease of use, functionalities, etc), then I think benchmark is the only criterion to tell the truth. I made a [test](https://github.com/jackhftang/bench_sparseset) to compare the performance between Table, SparseSet and adix/DITab. I didn't

Ideal design for a general purpose SparseSet?

2020-12-10 Thread jackhftang
umm since I was mentioned, bear with me few sentences... I don't know much about sparse set, but after I read [this

Advent of Nim 2020 megathread

2020-12-10 Thread jackhftang
For today (day 10), I found that if proc `-`[T](a,b: openArray[T]): seq[T] Run is prepared, the solution of part 1 can be expressed in a clean way. I think it maybe useful in the future also. proc main() = let input = readFile(inputFilePath).strip

any way to extra version info from .nimble file?

2020-12-09 Thread jackhftang
> You can pretend it's of a fixed format and use simple extraction mechanisms. > Isn't that what you ended up doing anyway when you write I mean 1. sometimes the version string have to be present in a config file for third party tools 2. third party tools may not provide any mechanisms to d

any way to extra version info from .nimble file?

2020-12-09 Thread jackhftang
Interesting, it seems everyone invented their way to update/share version. Let me share my two cents. Basically, the method is same as @cblake , I made a [nim task](https://github.com/jackhftang/my_nim_github_template/blob/master/my_nim_github_template.nimble#L28) that can show the current

asynchttpserver, keep-alive and concurrent queries

2020-12-05 Thread jackhftang
You forget to return after `await req.sendFile(filename)`. I also added content-type header. I seems working fine for 1000 images. import asynchttpserver, asyncdispatch import asyncnet import os import strutils import strformat import asyncfile import uri

Advent of Nim 2020 megathread

2020-12-03 Thread jackhftang
Here is mine: <https://github.com/jackhftang/adventofcode2020>

Advent of Nim 2020 megathread

2020-12-02 Thread jackhftang
I wish to see more sponsors and players, it will be more fun~

Advent of Nim 2020 megathread

2020-12-01 Thread jackhftang
After reading the [Nim 1.4.2 is out !](https://forum.nim-lang.org/t/7185) thread, I have an idea. In order to encourage the use of Nim, celebrate the new release and make completing AOC a little bit more meaningful. **For each player in the private leaderboard 40415-c732e66e who gain all 50 sta

Advent of Nim 2020 megathread

2020-11-30 Thread jackhftang
This year the first place took 00:07:11 to complete both stars. This has not happened before and the number of participants so far do not seems to be exceptionally high. So, it is highly suspicious that someone was DOSing AOC...

Set base address of sequence

2020-11-26 Thread jackhftang
I saw in some libraries and used the following technique to interop with C code. For example // sum.c long long sum(long long* xs, unsigned int len){ long long s = 0; for(int i=0; i

Question about async

2020-11-19 Thread jackhftang
I may misunderstood your problem. Your description of Future is correct. In your example code, you just need to `waitFor f`. But as Araq point out, you should also handle the future exception. If you prefer the callback style, it should be something like this. import asyncdispatch

Question about async

2020-11-18 Thread jackhftang
`runForever` will raise exception when no more pending timers, callbacks, file descriptors. import asyncdispatch var f = sleep_async 1000 f.add_callback proc() = echo "Sleep_async finished" try: runForever() except ValueError: if getCurrent

internal error : where to report

2020-11-18 Thread jackhftang
The problem is that you called `strip` on `iterator`. import strutils proc read(input: File) = for line in input.lines: echo line.strip read(stdin) Run This should be considered as a bug in compiler, you may report it on github.

trouble , name etc...

2020-11-18 Thread jackhftang
Could you give some examples??

Which HTTP server library?

2020-11-16 Thread jackhftang
wanted to know what HTTP server there was out there with a rather complete implementation Run [Prologue](https://github.com/planety/Prologue) should be a rather complete implementation of a HTTP server and the most [featureful](https://planety.github.io/prologue/) one written in

How do you deal with dependencies in Nim ?

2020-11-15 Thread jackhftang
I hear about nix, but I don't have experience with it. How can it solve dependency problem in Nim?

How do you deal with dependencies in Nim ?

2020-11-15 Thread jackhftang
@Araq allowing duplicated libraries is terrible Run Why do you think that? >From experience in nodejs, even though allowing co-existence of multiple >version of a package will result in bloated node_modules for large >applications, there is no more dependency hell issue.

How do you deal with dependencies in Nim ?

2020-11-15 Thread jackhftang
A short description of the problem: 1. package A requires package B == 0.2.0 and package C == 0.2.0 2. package B requires package C == 0.1.0 And then when compiling package A, an error occurs saying that `Error: Cannot satisfy the dependency on C 0.1.0 and C 0.2.0` This is problematic if

Creating unique ID from strings

2020-11-13 Thread jackhftang
Isn't what you want is a hash algorithm? An example of fast and good hash is murmur3. As long as your input space is larger than the key, you cannot have a guarantee on uniqueness of keys. Though the chance to have collision of key with 128-bit murmur3 for millions record is rather low.

Quick question about acyclic pragma

2020-11-09 Thread jackhftang
Is the following statement correct? Even there are cyclic references between objects during runtime, but if I can make sure that 1. all ref fields are assigned to nil when the objects no more needed. 2. the objects do not form a closed reference loop that cannot be travelled from the root p

Overriding ==

2020-10-31 Thread jackhftang
How about this? # - # this part of code does not change type TextDocument = object DrawingDocument = object SpreadsheetDocument = object proc draw(doc: TextDocument) = echo "draw text"

Overriding ==

2020-10-31 Thread jackhftang
can't rely on the modifiability of the source code Run Seems Nim generic can satisfy your requirements, but I wonder how often such openness for extension is needed. type TextDocument = object DrawingDocument = object SpreadsheetDocument = object

Listening for variable changes in Nim?

2020-10-27 Thread jackhftang
You need a reactive or stream library. I have tried a quick keywords search on nimbler directory, but cannot hit any. I have an unpublished and unpolished library for reactive programming. Here is the base file. import deques, tables type Callback[X] = proc(x:X): bo

Convert Time to Duration

2020-10-25 Thread jackhftang
You are right that it is not suitable to use the timestamp library if the use case beyond time bound from 1677-09-21T00:12:43.145Z to 2262-04-11T23:47:16.854Z It is more plausible to use the library for time-series data which usually just the time of measurements and a lot for data points collec

Convert Time to Duration

2020-10-24 Thread jackhftang
This is the implicit function

Convert Time to Duration

2020-10-22 Thread jackhftang
**Shameless promotion** I have a feeling that [timestamp](https://github.com/jackhftang/timestamp.nim) can satisfy what you need. This library directly work on int64, if you are on x64 arch. It is very fast. If you don't have complex requirement, the simple interface of [timestamp](

How to avoid deprecation notice for libraies supporting multi-version of Nim?

2020-10-22 Thread jackhftang
Thank you. I have chosen solution 1 which look nicer.

How to avoid deprecation notice for libraies supporting multi-version of Nim?

2020-10-21 Thread jackhftang
umm... okay, the undeclared tables is solved, but then `Warning: Deprecated since 1.4.0; rightSize is deprecated` appear again in 1.4.0

How to avoid deprecation notice for libraies supporting multi-version of Nim?

2020-10-21 Thread jackhftang
Did you import from another file? I tested on three machines with the following settings, all showing `undeclared identifier: 'tables'`. Here the codes, two files or clone `git clone https://github.com/jackhftang/lrucache.nim.git -b minimal_rightsize_test` # lr

How to avoid deprecation notice for libraies supporting multi-version of Nim?

2020-10-21 Thread jackhftang
ummm.. turn out that this cannot solving the problem completely... tried a number of variants template rightSize(cap): untyped {.dirty.} = # not work in 1.2.6 as declare(table.rightSize) is false when declared(tables.rightSize) and (NimMajor,NimMinor) < (1,4): tab

How to avoid deprecation notice for libraies supporting multi-version of Nim?

2020-10-21 Thread jackhftang
thanks

How to keep a ordered table sorted with the most recent changed elements at the end?

2020-10-20 Thread jackhftang
The python and java version are basically the same as current implementation of lrucache. Except that the python one restrict the key and value to int. The python version also has two copy of key: one copy of key is hidden inside `LRUCache.node_lookup` and another copy of key is at `Node.node_ke

How to avoid deprecation notice for libraies supporting multi-version of Nim?

2020-10-19 Thread jackhftang
I use `choosenim 1.4.0` on linux. To reproduce git clone https://github.com/jackhftang/lrucache.nim.git -b remove_rightsize nimble test Run

How to avoid deprecation notice for libraies supporting multi-version of Nim?

2020-10-19 Thread jackhftang
For example, I have an old code like this initTable[K,V](rightSize(capacity)) Run Since `rightSize` is deprecated in 1.4.0, I modify the code to the following when (1,0) <= (NimMajor, NimMinor) and (NimMajor, NimMinor) < (1,4): initTable[K,V](rightSi