Re: Heterogen lists

2018-11-26 Thread mashingan
This is perfect example case for [object 
variant](https://nim-lang.org/docs/manual.html#types-object-variants)


Re: Does nim implement predicate dispatch?

2018-11-26 Thread geohuz
Yeah I agree, I may come up with functional closure solution or have an object 
to maintain an internal "dispatch registry". I'm missing decorator in python 
here.


Re: HttpClient networking problem

2018-11-26 Thread jlhouchin
I have a plain except:. It should catch everything. But nothing is being caught.

It isn't a server problem. I am testing what happens to the program if there 
are network problems like when a network goes down briefly. In this instance. I 
am simply turning off my wifi while it is running.

I was hoping to find what Errors get raised that I could catch and simply have 
a loop which sleeps a little while, then tries again, until I have success.

I can work on writing a sample app. It shouldn't be difficult. But it can't be 
the one I am using at the moment because it is for a secured api which requires 
an account and credentials.

But again the key part is nothing is happening when I disconnect the network. 
It just goes comatose. No errors. The server side is fine. When my network is 
up, the app works flawlessly.

If the outage is short enough, 2 minutes and under from what I have briefly 
experimented with. It simply resumes. But my app has not been informed of any 
issues and I have missed ??? amount of data during the outage.

I am at a loss on how to make this fault tolerant and how to debug.

Thanks. 


Re: How to kill/timeout threads | non-blocking IO with stdin

2018-11-26 Thread mashingan
try with combination of channel, lock and condition ?

like this 
[example](https://forum.nim-lang.org/\(https:/github.com/mashingan/nim-etc/blob/master/cond_loop.nim)


Re: HttpClient networking problem

2018-11-26 Thread mashingan
afaik, get proc raise TimeoutError, if it's not like that then it should be 
bug. If you can provide reproducible case it would help team a lot.

Because, when some request is just hanging there, it's possible too the server 
doesn't return the response due to logic-error or bug in there.


Re: Does nim implement predicate dispatch?

2018-11-26 Thread mashingan
Some people said closure is poor-man object/method, but I disagree, IMHO 
object/method is poor emulation for closure .

in my case, I never found method as much useful as closure, maybe it's just 
because I don't have that vast experience tho


Re: Does nim implement predicate dispatch?

2018-11-26 Thread geohuz
Well I think the previous experiment fails coz we can't add another "POST" 
dispatch into the code, simply because of compile doesn't allow duplicate 
declaration. 


Re: Does nim implement predicate dispatch?

2018-11-26 Thread geohuz
Well, I tried add condition statement in the multi-method and found it worked 
very well, and here is my tiny view dispatch framework!:


type
  Document = ref object of RootObj
text: string
  Request = ref object of RootObj
reqMethod: string

method view(doc: Document, req: Request): string {.base.} =
  if req.reqMethod=="GET":
return doc.text

let doc = Document(text: "Hello World!")
echo view(doc, Request(reqMethod: "GET"))


Run


HttpClient networking problem

2018-11-26 Thread jlhouchin
Hello,

I am writing an app which requests data from a REST API multiple times a 
second. At the moment I am testing in a loop which collects data, sleeps until 
the next .1 of second and then continues collecting data.

Below is some slightly modified, abbreviated and cleaned up code which does 
what I want.

It works fine most of the time. I am wanting to make the code robust against 
network failures.

I am not sure how to do that. When running it on my laptop I will disconnect my 
wifi. It produces no output while the wifi is disconnected. I get no output 
from the request which as to be expected. But I also get no errors. It just 
sits idle. I don't like that. I can imagine there is some code built into 
HttpClient that also attempts to be robust. However, I do not know how or when 
it will fail.

If there is network failure I want to be able to resume as soon as it is back 
up.

The app sometime seems to just go comatose. Even after the network is back up, 
it does not resume, nor give any kind of exceptions. Which is why I wrapped 
this proc in a try/except and put in many echo statments. How do I debug this 
when disconnected? How do I make this robust to failure where I can resume 
immediately after any sort of network failure when the network returns?

Any help and wisdom greatly appreciated.

Thanks.


var client = newHttpClient()

proc secondLoop() =
  try:
dt = getTime().utc
let pathQuery = "my path and query string"
echo("before secondLoop1:  ", getTime().utc)
let result = client.get(pathQuery)
echo("in secondLoop2:  ", getTime().utc)
echo("print some of the result")
let diff = getTime().utc - dt
if diff < deciSecondDuration:
  sleep(diff.milliseconds.int)
echo("after secondLoop3: ", getTime().utc)
  except:
echo("exception message:  ", getCurrentExceptionMsg())


Run


Re: iup.getFile fails

2018-11-26 Thread matkuki
Well this one seems the best to me: 


import iup, strutils
discard iup.open(nil,nil)
var str : string = "../docs/*.txt\0".alignleft(4096, padding=' ')
echo iup.getFile(str)
echo str.strip()
iup.close()


Run


Re: Should we get rid of style insensitivity?

2018-11-26 Thread matkuki
@dom96

  * Case insensitivity: `fooBar == foobar`
  * Style insensitivity: `foo_Bar == foobar`
  * Nim's style insensitivity: `foo_Bar == foobar`, but `F != f`



I will only add my experience regarding the above distinction between the 2nd 
and 3rd point. There have been at least three occasions where I came back to 
programming in Nim after a week or so and always get bitten by the same mistake:

  * Right, I don't have to care about underscores and case,
  * hack, hack, hack,
  * compile,
  * What do you mean: undeclared identifier: 'quitsuccess' !!!
  * Ohh, right! the first character is case sensitive, it's 'QuitSuccess'!,
  * But 'Quitsuccess' is even uglier!
  * Then comes the realization that Nim is not really style insensitive... Sigh.



My wish would be that we would pick between either the 1st or 2nd point.


Re: Advent of Code 2018 megathread

2018-11-26 Thread rarino
My repo for AoC 2018 is here: 
[https://github.com/jabbalaci/AdventOfCode2018](https://github.com/jabbalaci/AdventOfCode2018)
 . 


Re: Heterogen lists

2018-11-26 Thread trtt
That's great! Thanks!


Re: Heterogen lists

2018-11-26 Thread miran
> if Nim would have pattern matching

[https://github.com/alehander42/gara](https://github.com/alehander42/gara)


Re: Heterogen lists

2018-11-26 Thread trtt
That would be useful too if Nim would have pattern matching...


Re: iup.getFile fails

2018-11-26 Thread matkuki
@Stefan_Salewski Excellent, it works with string: 


import iup
discard iup.open(nil,nil)
var
str : string = newString(1024)
i: int = 0
for ch in "../docs/*.txt":
str[i] = ch
i += 1
echo iup.getFile(str)
echo str
iup.close()


Run

But even this works with string like this: 


import iup
discard iup.open(nil,nil)
var
str : string = "../docs/*.txt"
echo iup.getFile(str)
echo str
iup.close()


Run

the only thing is it cuts the reply to len("../docs/*.txt")!

But why doesn't it work with cstring??? It's weird to see a signature `proc 
getFile*(arq: cstring): cint`, then when using cstring it doesn't work while it 
works with string. I know the whole concept is a bad way of passing data 
around, but still, it's very confusing, it should also work with cstring!


Re: Heterogen lists

2018-11-26 Thread Arrrrrrrrr
The usual answer is json 
[https://nim-lang.org/docs/json.html](https://nim-lang.org/docs/json.html)


Re: Does nim implement predicate dispatch?

2018-11-26 Thread Arrrrrrrrr
Looks to me like pattern matching from the examples I have seen 
[http://andreaferretti.github.io/patty](http://andreaferretti.github.io/patty)/


Advent of Code 2018 megathread

2018-11-26 Thread miran
It is time for [Advent of Code 2018](https://adventofcode.com/)!

Nim is organizing [private 
leaderboard](https://adventofcode.com/2018/leaderboard/private) where you can 
compete against other Nim users. To join the Nim leaderboard, all you have to 
do is use `40415-c732e66e` code in the previous link.

More information about this event and the prizes you might win in [this blog 
post](https://nim-lang.org/blog/2018/11/26/advent-of-nim.html)

* * *

Use this thread to post links to your AoC repositories and share your solutions.


Re: Does nim implement predicate dispatch?

2018-11-26 Thread Araq
Well, yeah, Nim doesn't have that, but you can build your own dispatchers with 
macros. And that's one reason I don't like `method`, the language could emulate 
that one too.


Heterogen lists

2018-11-26 Thread trtt
Hi,

> How to implement heterogen lists in nim? In FP languages we've access to 
> better pattern matching and sum types but in nim I can't reproduce them 
> properly. I've tried it two different ways:

1\. this one fails because it can't infer the type of any(auto) - I need a 
third type parameter which should be optional:


type
  HListKind = enum hkNil, hkCons
  HList*[H, T] = ref object of RootObj
case kind*: HListKind
of hkNil:
  isEmpty*: bool
of hkCons:
  head*: H
  tail*: HList[T, any]

let hNil*: HList[void, void] = HList[void, void](kind: hkNil, isEmpty: true)
proc hList*[H, T](hd: H, tl: HList[T, any] = hNil): HList[H, T] =
  HList[H, T](hd, tl)


Run

2\. this one doesn't fail but I don't know how to iterate over it:


type
  HList*[H] = ref object of RootObj
isEmpty*: bool
  HNil = ref object of HList[void]
  HCons*[H, T] = ref object of HList[H]
head*: H
tail*: HList[T]

let hNil* = HNil(isEmpty: true)

proc hList*[H](hd: H): HList[H] =
  HCons[H, void](head: hd, tail: hNil, isEmpty: false)

proc hList*[H, T](hd: H, tl: HList[T]): HList[H] =
  HCons[H, T](head: hd, tail: tl, isEmpty: false)


Run

Normally, I'd just use pattern matching but Nim doesn't support it so I'm stuck.


Re: FE web libraries

2018-11-26 Thread dom96
Awesome start :O

> I had one major issue... none of the yaml or markdown parsers worked with 
> nim's JS backend. So my yaml frontmatter is parsed as key/value pairs 
> (probably poorly too) and I parse the markdown in javascript.

What you could do is extend the markdown packages to either:

  * Fix them to work in the JS backend; or
  * Simply call a JS library transparently for the JS backend



This is how the stdlib `json` module works for example :)

> WOW the .importc pragma is amazing for doing things like that. just wow.

:D


Re: FE web libraries

2018-11-26 Thread bketelsen
In the process of learning more Nim I whipped this up last night:

[https://github.com/bketelsen/blog](https://github.com/bketelsen/blog)

Served on netlify at:

[https://loving-albattani-9f17d6.netlify.com](https://loving-albattani-9f17d6.netlify.com)/

  * the Contact link in the header doesn't work (no page there yet)
  * the blog posts list (which is served in the default route) is hard-coded
  * about/links content in the nav bar come from the /pages folder and are 
stored in markdown - the blog posts will be like this too



I had one major issue... none of the yaml or markdown parsers worked with nim's 
JS backend. So my yaml frontmatter is parsed as key/value pairs (probably 
poorly too) and I parse the markdown in javascript. WOW the .importc pragma is 
amazing for doing things like that. just wow.

Any constructive criticism or advice on the code so far would be welcomed, I'd 
much rather start with good habits than bad!


Re: Does nim implement predicate dispatch?

2018-11-26 Thread geohuz
Thanks @LeuGim, to my understanding the predicate dispatch is sth like adding 
conditional predicate to the multimethod. I just found libs like gara: 
[https://github.com/alehander42/gara](https://github.com/alehander42/gara) or 
patty doing sort of pattern matching, not sure if those libs suffice the 
criteria.


Re: Does nim implement predicate dispatch?

2018-11-26 Thread LeuGim
"Concept" is that, but only for compile-time predicates and dispatch, i.e. for 
each call the routine to be called is determined at compile-time and will not 
change, at run-time it will be the same for a particular call each time. In 
contrast to methods, for which, depending on argumets passed, one or another 
concrete method is chosen at call-time.

Some illustration of concepts and how they are static:


type
  # Just for illustration, some random concepts
  HasInc = concept x
inc x
  HasNotIncButHasAbs = concept x
x isnot HasInc
x.abs is x.type

var
  i = 3
  f = -5.0
  c = 'a'
echo i is HasInc
echo i is HasNotIncButHasAbs
echo f is HasInc
echo f is HasNotIncButHasAbs
echo c is HasInc
echo c is HasNotIncButHasAbs

echo "_"

proc p(n: var HasInc) = # let's refer to it as `p1`
  echo "p1 called; ", n, " has `inc`, calling it"
  inc n
  echo "now it's ", n
proc p(n: HasNotIncButHasAbs) = # let's refer to it as `p2`
  echo "p2 called;", n, "'s absolute value is ", n.abs

p i # p1
p f # p2
p c # p1

echo "__"

# Really 2 concrete `pp` are created by the same name and with the same 
code,
# one always calling the 1st `p` (`p1`) and one always calling the 2nd 
(`p2`)
proc pp(n: var (HasInc or HasNotIncButHasAbs)) =
  p n # No run-time choice here,
  # for each instance of `pp` it's one of `p1` or `p2`, not any
pp i # calls the instance of `pp` which calls `p1`
pp f # this line calls another instance of `pp`, than the previous
pp c # the first one again

echo "__"

var a = [1.0, 2.0, 3.0]
for i in a.mitems:
  p i # `p2` for each iteration; you may not refer here to different `p`,
  # except if they are `method`s (or you can manually dispatch with 
`if`s)

echo "__"

# = #
# What concepts cannot (needs run-time choice),
# of what may be supposed by "predicate dispatch".
# The code below won't work.

#type
#  X = concept x
#x < 10
#  Y = concept y
#y >= 10
#proc q(n: X) = echo "X ", n
#proc q(n: Y) = echo "Y ", n
#
#var n = 5
#q n
#n = 50
#q n


Run


Re: How to kill/timeout threads | non-blocking IO with stdin

2018-11-26 Thread trtt
I want to kill the thread after a certain amount of time. I need this to be 
able to communicate with another program in a single thread without blocking 
forever and without race issues.


Re: How to kill/timeout threads | non-blocking IO with stdin

2018-11-26 Thread dom96
What do you mean by "intercept"? And why do you need this?


Re: How to kill/timeout threads | non-blocking IO with stdin

2018-11-26 Thread trtt
Is it possible to intercept the thread? I couldn't find anything in the 
threadpool module...


Re: Unix Sockets can't receive messages or I'm not using them properly

2018-11-26 Thread trtt
@moerm yep, the problem was that the buffer was too large: [in 
recv()]([https://nim-lang.org/docs/net.html#recv%2CSocket%2Cstring%2Cint](https://nim-lang.org/docs/net.html#recv%2CSocket%2Cstring%2Cint))
 the size parameter should be maxSize. I thought about this too but I also 
thought that it'd be too stupid. Thanks for the tip!

@dom96 could it be a good idea to append this useful information to the docs? 
I'd create an MR too.


Re: How to kill/timeout threads | non-blocking IO with stdin

2018-11-26 Thread dom96
Here is an example of how to mix stdin reading (with spawn) with async IO: 
[https://github.com/dom96/nim-in-action-code/blob/master/Chapter3/ChatApp/src/client.nim#L38-L50](https://github.com/dom96/nim-in-action-code/blob/master/Chapter3/ChatApp/src/client.nim#L38-L50)


Re: Unix Sockets can't receive messages or I'm not using them properly

2018-11-26 Thread moerm
For a start you should wrap receiving in a try ... except because recv() will 
raise an exception on timeout or error which might tell you valuable 
information. Looking at `rd` might also be helpful as it's the return value of 
the "deeper" basic recv() (called by the "comfort" recv() version you call).

Finally also keep in mind the intricacies of sockets also in the operating 
systems and implementations some of which, to provide an example, return a 
timeout or error if less than the specified read size bytes are available, i.e. 
if you try to get 1000 bytes and 999 are available you may not get those 999 
but rather an error or timeout.

In tough cases ltrace or strace can be very helpful and valuable.


Re: FE web libraries

2018-11-26 Thread andrea
@miran thank you, I did not think of that! :-D


Does nim implement predicate dispatch?

2018-11-26 Thread geohuz
I'm learning the nim and excited to know that it supports multimethod natively! 
And when I learning the concept of multi-method from wikipedia, I saw there is 
a general concept of 'predicate' dispatch which is more generalized, I'm not 
sure if nim has this? Is the "concept" of nim can be used for prediate 
dispatch? Hope somebody can help with this question with code sample. Thanks!


Re: FE web libraries

2018-11-26 Thread miran
> What's a FE lib?

Did you, just as I did, thought this might be about Finite Elements? :)

After I've read the whole thread, I'm guessing it means Front End.


Re: iup.getFile fails

2018-11-26 Thread Stefan_Salewski
> The problem might be because the function writes the selected file name back 
> into arq

Great work!

That behaviour is uncommon, but indeed stated in IUP docs! What should work is 
allocating a large string with newString(4048) and then assigning chars one by 
one, or maybe assigning string first, and then calling setLen() with large 
size. But such a low level interface in IUP is really an ugly trap. 


Re: FE web libraries

2018-11-26 Thread andrea
What's a FE lib?


Re: iup.getFile fails

2018-11-26 Thread matkuki
Hey @StefanSalewski The original signature is: 


proc getFile*(arq: cstring): cint


Run

and the C prototype is: 


int  IupGetFile(char *arq);


Run

The problem might be because the function writes the selected file name back 
into `arq`, but I have no idea. I tried 


proc getFile*(arq: var cstring): cint


Run

but nothing changed.


Re: iup.getFile fails

2018-11-26 Thread Stefan_Salewski
Sorry, I don't understand it.

I have the feeling that your code does basically the same as the code in the 
initial post.

For my Nim 0.19 on LinuxAMD64 the cstring seems to be allocated fine.

May your compiler version include a already fixed bug?

Note that generally we use plain Nim strings in our code, Nim strings get 
converted automatically to cstrings when passed to a proc which expects c 
string.

Can you post the original signature of your iup wrapper getFile() proc. 


How to kill/timeout threads | non-blocking IO with stdin

2018-11-26 Thread trtt
Hi,

I want to timeout the reading from stdin and I couldn't find anything in the 
threads and os modules. It'd be also good if I could use stdin/read in a 
non-blocking way.