What I can understand that you need the lib's user should implement their own
proc implementation right?
Actually tables modules exactly does like that, when the user wants to use a
specific object as the key, should implement `hash` and `==` so the object can
be used as key.
It's also catch-a
It's different because `AsyncFile` keeps its `fd` field private. The Windows
one is using the version from `winlean` which actually wrapper for
`GetFileSize` from win32.
Also, windows has peculiarity of different handling whether the file handle is
synchronous and asynchronous one. That's why i
Most viable option is using [winim](https://github.com/khchen/winim/) and just
searching on internet how to work with Win32 API.
Another way is using available example in rosetta code [simulating
keyboard](https://rosettacode.org/wiki/Simulate_input/Keyboard#Nim) and
add/change some codes to
> By removing something from the seq it needs to be reordered. ( shift elements
> )
If you don't need the ordering, use
[del](https://nim-lang.org/docs/system.html#del%2Cseq%5BT%5D%5BT%5D%2CNatural)
Try the testing by choosing the span element randomly instead of pre-determined
value. It will
I used it to generate Golang boilerplate source codes for my last job.
$ c2nim --header gr.h
gr.h(27, 25) Error: token expected: ;
Run
AFAIK, c2nim cannot read something with c custom macro. You can edit the header
temporarily to remove that custom macro. In this case it's the `DLLEXPORT`.
just a genuine question
> > Not null safe by default
How compiler know whether the data is nil or not if the data for example taken
from IO? Or is it adding the additional `if thedata == nil` in the code? But
the checking still done in run-time right?
Or is it just limited to data/object const
> What other arguments do they have against using tab?
I got this from a tweet, just food for thought:
> Remember, when you are read, you do not know you are dead. It is only painful
> for others. It's the same when you use tabs and not spaces
;D
The streams implementation on Windows (FileHandleStream to be precise) didn't
implement peekDataImpl, setPositionImpl and getPositionImpl hence it crashed
because the streams module accessing nil implementation.
I actually fixed this (not PR-ed it yet tho, maybe already fixed in devel too,
have
[https://github.com/SSPkrolik/nimongo/pull/81](https://github.com/SSPkrolik/nimongo/pull/81)
there, added for limited elementary functionalities for GridFS.
Unfortunately I never intensively used mongo except for simplest CRUD and those
GridFS features only tested on Windows, very likely you nee
perhaps like this
#include
int main() {
fprintf(stdout, "This is from hello to stdout\n");
fprintf(stderr, "This is from hello to stderr\n");
return 0;
}
Run
and our nim file
import os, osproc, selectors
when defin
> it seems there is a offset error in the code (files are not identically but
> shifted by some bytes at certain offsets)
This is quite tricky to find out, TBH. I tried running it on windows and debian
(in virtual box) and using chromium and firefox (both on windows) and it gave
the correct fil
Uploading file has been tricky, but thankfully nowadays there's websocket to
send blob. Here's example how to send a file.
import os, jester, asyncdispatch, htmlgen, asyncfile, asyncstreams, streams
import strutils
import ws, ws/jester_extra
settings:
port = Po
It seems the problem is elsewhere, not on how writing it to file, whether
sync/async file write.
Idk what to tweak on Jester to support larger chunk processing. As for example
on writeFromStream (not actually solving the problem tho):
routes:
post "/upload":
var f: As
spammer? [https://forum.nim-lang.org/t/5791](https://forum.nim-lang.org/t/5791)
try to use
[writeFromStream](https://nim-lang.github.io/Nim/asyncfile.html#writeFromStream%2CAsyncFile%2CFutureStream%5Bstring%5D).
rand proc has side effect.
Having _ as initial variable name only acts as visual cue, it's not related to
readability or anything.
Having clear/distinct/helpful/noisy visual cues doesn't change the fact whether
the code is well written or not.
What actually helpful is good structure and sane APIs. Whatever the variable
Same case
[https://forum.nim-lang.org/t/5792#35941](https://forum.nim-lang.org/t/5792#35941)
> Error: overloaded 'initElement' leads to ambiguous calls
You tried to overload using generic but actually proc overload usually done
with argument types. When you defined generic, it's actually creating overload
proc based on argument type, for example
proc add[T: SomeInteger](a,
> template/generic instantiation of + from here
This means + is generic and the real operation/error is elsewhere.
Error: type mismatch: got
but expected one of:
iterator items[T](a: seq[T]): T
first type mismatch at position: 1
required type for a: seq[
> I have to provide an initElement proc in the generic module in order to
> compile foo[T] (line #10). That's the reason there's a forward declaration of
> initElement (line #7).
I tried your code, removed the forward-declaration and fixed your initElement
definition and it's working fine.
[getIoHandler](https://nim-lang.github.io/Nim/asyncdispatch.html#getIoHandler%2CPDispatcher)
will returning IOCP Handle on Windows or
[Selector[AsyncData]](https://github.com/nim-lang/Nim/blob/devel/lib/pure/asyncdispatch.nim#L1137-L1138)
on Unix
If I understand you correctly, you wanted the client/user of the module to
provide their own initElement proc of their type, didn't you?
In that case, you're able to ensure the compiler to check whether the user
provide their own initElement using
[compile](https://nim-lang.github.io/Nim/system
> If Nim has setjump/longjump features (I've just found them in segfaults
> library!), I could change that pattern to write two coroutines, consumer and
> producer.
There's [coro](http://nim-lang.github.io/Nim/coro.html) module in case you
didn't realize it.
> Is there a standard way to resume
> /usercode/in.nim(25, 15) Error: type mismatch: got
>From this message is quite clear that your template didn't return the untyped
>as unchecked proc.
>From your template definition, you just defined a proc that only available
>within that template scope and you didn't return anything. Simply
This immediately leave the proc when across something nil
template safe(obj: typed, field: untyped): untyped =
if obj.isNil:
return
`obj`.`field`
type
MyNullObj = ref object
x: int
proc main =
var nullobj: MyNullObj
Very likely the of-branch cannot evaluate iterator and/or template. The `..<`
not defined as proc, the workaround is
template test(v: typed) =
case v
of low(int) .. pred(5):
echo "under 5"
else:
echo "5 or above"
Run
> Now what if I wanted to create 32-bit-executable?
In your current cmd session, invoke `set
PATH=d:\your-mingw32-i686-path-bin;%PATH%` , this way the mingw32 32bit will be
prioritized.
> And good comments everywhere.
That's from Ffmpeg header files comment :D , it's preferable to refer the c
header file directly as the header also written with documentation there.
> and sometimes there are misspelled variable ...
This very likely because of `:%s/_t//g` :P , I'll fix whenever
Information of `T` and `V` already available from parent function so your
iterator doesn't have to generic. Also, if a function cannot infer from
argument, the workaround is that you have to be explicit.
proc allExactCover*[T, V](constraints: Constraints[T, V]): iterator ():
Soluti
This worked in [my example
here](https://github.com/mashingan/nimffmpeg/blob/master/fplay.nim#L44)
var streams = cast[ptr UncheckedArray[ptr
AVStream]](pFormatContext[].streams)
Run
I had issues with that too but I fixed my [FFMpeg
binding](https://github.com/mashingan
> What do you mean?
If I understand correctly, you defined the Node with information of incoming /
outgoing Edge
type
Node*[N] = object ## The graph's node type.
weight*: N ## Associated node data.
next: array[2, EdgeIndex] ## Next edge in outgoing and inco
IMO, It's not worthy to make it distinct, moreover, you should use generic
instead of int for nodes label.
Unrelated to the question, you should keep the Node definition is literally as
a node, and keep Edge definition is the connection from Node1 and Node2. The
array of two nodes index for inc
> there is no nil, it reports wrong size.
I remember something when doing ffmpeg c binding. At first I wrote the binding
without adding the header pragma, and just simply importc pragma only. In the c
header file, that particular object actually internal struct that isn't
included in dev header
Another workaround
type
# The 3 notations refer to the same 3-D entity, and some coordinates are
shared
CoordinateSystem = enum
csCar, # Cartesian(x,y,z)
csCyl, # Cylindrical (r,φ,z)
csSph # Spherical(ρ,θ,φ)
Coordinate
workaround
import strformat
type
# The 3 notations refer to the same 3-D entity, and some coordinates are
shared
CoordinateSystem = enum
csCar, # Cartesian(x,y,z)
csCyl, # Cylindrical (r,φ,z)
csSph # Spherical(ρ,θ,φ)
Idk too, but try to wrap the functionality in some proc like main or anything
and just call that proc.
Another thing, you can always use gdb to check each variable which one has nil.
> And i dont want to mix the implementation code with type declaration code. I
> need to split as much code as possible.
In different modules or in different files?
If in different modules, as for now, everything exported are visible to other
modules that import it.
If it's only needed in diff
If you need to access the field from other modules, then it's literally not
private anymore.
If you have specific function that have to work with that private field, then
implement it in that common module and have that function exported.
If you want to have read only for that specific field, i
Checking with
[compiles](https://nim-lang.github.io/Nim/system.html#compiles%2Cuntyped)
should enough
when compiles(hash(a)): # a is the T object
doWith(a)
else:
{.error: "need hash implementation of " & T.type.}
Run
It's checked during compile-time.
Same here, love Erlang's philosophy too :D
Perhaps you're looking for [var return
type](https://nim-lang.github.io/Nim/manual.html#procedures-var-return-type) ?
AFAIK, `Stream` is usually when you're dealing with bytes; whether opening
binary files, or reading/writing network bytes stream, or reading/writing bytes
to file etc.
Especially for writing bytes, just like in the example.
since b is declared as WASDLetters , it's inferred so.
But since it's WASDLetters you won't be able to ord(b) and it's detected during
compile-time checking.
Dunno if more elegant or not, but you can try using mapIt
import tables, sequtils
var int2str = {0: "Zero", 1: "One", 2: "Two", 3: "Three"}.toTable
var str2int = toSeq(int2str.pairs).mapIt((it[1], it[0])).toTable
Run
proc in Nim is static
Yes, it's whether you to wait with asyncCheck or go with future.failed is up to
application. But the idea is same.
the problem that the client cannot be shared to other download
import httpClient, asyncdispatch
proc download(url: string): Future[string] {.async.} =
await newHttpClient().getContent(url)
}
proc downloadAll(urls: seq[string]) {.async.} =
var asyncr
[encodeQuery](https://nim-lang.org/docs/uri.html#encodeQuery%2CopenArray%5B%5D)
How to get the documentation based on keyword/name?
1. Open [the
index](https://nim-lang.org/docs/uri.html#encodeQuery%2CopenArray%5B%5D) page.
2. Search the page there with `encodeUrl`.
3. See available procs
Trick to find all procedures that return SomeType: `:) SomeType`
_tldr; if the size of integer is important, always opt to explicit conversion_
* * *
you can define your own `+` operator for your case
proc `+`(x: uint16, y: uint32): uint32 = x.uint32 + y
Run
But then the definition then become tedious if you have to define another
Played the idea of pool connections and wrote some example in [gist
here](https://gist.github.com/mashingan/7532bd89c4e3bde6526a896a3ae611b7).
Can you try changing [line
236](https://github.com/pb-cdunn/nim-help/blob/master/raptor_db.nim#L236) with
`var sr = SequenceRecord()` ?
I'm not sure but maybe what you're doing is scope-escaping memory? That `var
sr: SequenceRecord` only available in the stack and it got destroyed after you
co
> send connect three sockets and read from each of the asynchronously?
like this?
import asyncnet, asyncdispatch, strutils, random
proc genAddr(): string =
randomize()
var
ip0 = rand(1..255)
ip1 = rand(255)
ip2 = rand(255)
Consider using FileStream for reading and writing binary file.
I'm not sure but after I see in your wutilc
char buffer[INET6_ADDRSTRLEN];
char *get_from(...) {
\\
return buffer;
}
Run
I guess it's the problem with global variable; you should change the c api too
void *get_from(struct
> (calling again with the same type param does not create a new code block)
This doesn't seem good idea.
Try `cdecl` calling convention or others like mentioned in [manual
page](https://nim-lang.github.io/Nim/manual.html#types-procedural-type)
Maybe your client-side hit with pre-flight request.
> What prevents you from using Nim as main proglang
Job, I still cannot win struggling fight against fate as corporate-slave :3
> I have used Nim for many small experiments, but the main reason why I am not
> using Nim as my main programming language is that it is not popular enough.
This is a
Read about iterator in
[manual](https://nim-lang.github.io/Nim/manual.html#iterators-and-the-for-statement)
[playground](https://play.nim-lang.org/index.html?ix=1MaK)
proc countTo(maxi: int): iterator(x = 1): int =
result = iterator(x = 1): int =
var i = 0
whil
> I don't understand why the implicit local() inzoning is done if the input
> string specifies the time zone explicitly
I think the problem is in stdlib in C only provided `gmtime` and `localtime`
[https://en.cppreference.com/w/c/chrono](https://en.cppreference.com/w/c/chrono)
CMIIW, since I ha
> What's confusing to me is that I tried about the same approach as yours but
> without using the sugar =>, and it didn't work because it failed to compile
> because the newTimeZone needed gcsafe proc args.
You're capturing `string` which is not gc-safe, in my case I just get the
integer value
something like this
import times, strutils, sugar
let
dtStr = "2019/06/06 18:17:43 +02:00"
dt = parse(dtStr, "/MM/dd HH:mm:ss zzz")
myM10 = newTimezone("M-10",
(x: Time) => ZonedTime(utcOffset: Hours.convert(Seconds, 10), time: x),
(x: Time) =
> The dtStr is what I get by parsing something else. I don't know the target
> timezone beforehand. The dtStr example just happens to be UTC.. the timezone
> in it could even be +01:30.. I don't know that beforehand.
I see, what you want is the datetime as it is with its original timezone.
The
there's [utc](https://nim-lang.github.io/Nim/times#utc%2CDateTime) proc for
what you want
import times
let
dtStr = "2019/06/06 18:17:43 +00:00"
dt = parse(dtStr, "/MM/dd HH:mm:ss zzz").utc
echo dt
Run
parseopt of course can extract the argument too
import parseopt
let cmdline = "config create \"a configuration\""
var opt = initOptParser(cmdline)
for kind, key, val in opt.getOpt():
case kind
of cmdArgument:
echo "argument: ", key
else:
> -d:ssl
This is same with `--define:ssl` , two hyphens is long option while single
hyphen is short option.
This `--define` option is to define a compile-time variable ala `#DEFINE` in C
for example you define 'goThisWay' when compiling then you can use it in code
when defined(goT
elaborate example case please.
also you can use
[quote](https://nim-lang.github.io/Nim/macros.html#quote%2Ctyped%2Cstring) proc
which easier to use
macro compileFiles(path: static[string], files: untyped): untyped =
result = newStmtList()
for f in files:
let file = newLit(path & $f)
re
try remove nimcache folder
compile with option `--threads:on`
> Can I specify binary-specific defines for the nimble build process?
You can specify which kind of binary built with nimble task. See
[here](https://github.com/nim-lang/nimble#creating-packages)
You can also make a config file specific to your nim file so the name is
_yourfile.nim.cfg_ and put
> I’ve used the to(type) macro in other code, but is there a reason to use it
> over getStr()?
Well, it's convenience, because most of times it's unwieldly to get all the
fields one by one
Welcome :)
Additional info, you can use
[to](https://nim-lang.github.io/Nim/json.html#to.m%2CJsonNode%2Ctypedesc) macro
to simplify conversion from _JsonNode_ to specified type ;)
perhaps what you want is
[quote](https://nim-lang.github.io/Nim/macros.html#quote%2Ctyped%2Cstring) proc?
Have you tried of `runes` in `unicode` module?
It's template that to convert `string` to `seq[Rune]`
> `"{$gt:10}".toBson`
This is string, not bson embedded object, what you need is
let query = %{
"temp": {
"$gt": 10
}
}
Run
If the mapping is fixed, you can use
[subrange](https://nim-lang.org/docs/manual.html#types-subrange-types) types.
Although the base type is same, you can define like
type
Row1 = range[ 0 .. 71 ] # assuming row has 72 bytes
Row2 = range[ 72 .. 143 ]
Run
Is [distinct](https://nim-lang.org/docs/manual.html#types-distinct-type) not
what you need?
You can define the needed operations from its base type using `borrow` pragma
so you don't have to cast/coerce every time you use it
Also, I did what @cdome suggested, defining `converter` s and it works
Haven't tried the event parser, but if only capturing the needed text I usually
use `find` proc
var buffer = newseq[string](10) # crash if the seq not enough
if example =~ grammar:
discard example.find(grammar, buffer)
echo buffer
# will print
# ["1", "2"
Perhaps like this
type IntAp = object
setInts: array[0 .. 2, int]
converter toIntAp(n: int): IntAp =
let ints = [n, 0, 0]
IntAp(setInts: ints)
let n: IntAp = 5
Run
My (insignificant) 2cent ;)
> V and Nim are very different. One of V's main philosophies is "there must be
> only one way of doing things". This results in predictable, simple, and
> maintanable code.
This is fallacy. Bad written code is bad, no matter what syntax is. The only
thing that make
try more the recent post
[https://forum.nim-lang.org/t/3575#22318](https://forum.nim-lang.org/t/3575#22318)
Your phone must be root-ed to do that.
It's known as source-code filter and you can read the documentation
[here](https://nim-lang.org/docs/filters.html)
> Can I re-render the page of tmpl without having to re-compile nim.
You can't, cmiiw.
handle with
[setControlCHook](https://nim-lang.org/docs/system.html#setControlCHook%2Cproc%29)
proc
I usually make the executable as service using [this
reference](https://gist.github.com/bcap/5397674)
using [fstat](https://nim-lang.org/docs/posix.html#fstat%2Ccint%2CStat) ?
import posix
var f = open "/home/jacobsin/test.txt"
var s: Stat
discard fstat(cint f, s)
Run
There's [getAppDir](https://nim-lang.org/docs/os.html#getAppDir%2C) proc
memfile is basically loading all content to memory, cmiiw
use [atEnd](https://nim-lang.org/docs/streams.html#atEnd%2CStream) to check
whether it's ended or not and use
[getPosition](https://nim-lang.org/docs/streams.html#getPosition%2CStream) for
its current position.
import os, streams
var fs = newFileStream(paramStr(1), fmRead)
You can iterate and check manually like
var
intpair = newseq[(int, int)]()
texture: int
lightmap: int
for thepair in intpair:
if thepair[0] == texture and thepair[1] == lightmap:
doSomething((texture, lightmap))
Run
or you can us
You can't generically represent `string` as `char`, but for your specific case,
you can do it like this:
import options
proc chr(s: string): Option[char] =
if s == "\\n": some('\n')
else: none(char)
let nlinerepr = r"\\n".chr
if nlinerepr.isSome:
> I always get tripped up on "damn, this is all classes and objects, how to I
> do the same thing in Nim?"
You need to change the perspective of the definition from AS to HAS, but `ref
object of` is kinda AS too, cmiiw. Thanks for link video btw :)
@ryuukoposting , 1st video is nice, waiting fo
Change the return template from `int` to `untyped` . I usually think `untyped`
as `unchecked` for easy understanding but let's wait for other to explain
better ;)
Add `hash` function and equality operator `==` for custom key.
import tables, hashes
type
Fn = proc (args: varargs[string]): int
FnSignature = tuple
name: string
arity: int
argTypes: seq[string]
proc hash(fns: FnSignature): Hash =
import std/math
your `gladLoadGL` definition is `proc gladLoadGL(load: proc): bool` but you
invoked `gladLoadGL()` without argument
1 - 100 of 421 matches
Mail list logo