Re: what's the correct way to handle unicode? - trying to print out graphemes here.

2018-07-04 Thread crimaniak via Digitalmars-d-learn

On Tuesday, 3 July 2018 at 14:39:34 UTC, ag0aep6g wrote:

Looks like forum.dlang.org has a problem when they appear side 
by-side.


Works (in the preview): ‍‍‍ ️‍
Doesn't work: ‍‍‍️‍


For me, it looks as the used font has ligatures for these faces. 
Mozilla under Linux, I guess it's 'EmojiOne Mozilla' font.




Re: High memory usage in vibe.d application

2018-07-01 Thread crimaniak via Digitalmars-d-learn

On Sunday, 1 July 2018 at 13:44:23 UTC, Anton Fediushin wrote:


I reduced the test case to _one_ line:
```
1.seconds.setTimer(() => "http://google.com".requestHTTP((scope 
req) {}, (scope res) {res.disconnect;}), true);

```

What happens is `res.disconnect` doesn't free all of the 
internal buffers, causing leakage. One way to avoid that is to 
call `res.dropBody`, but it isn't always wanted (just like in 
my example).

 The problem is known and mentioned in the documentation:
http://vibed.org/api/vibe.http.client/requestHTTP

Note that it is highly recommended to use one of the overloads 
that take a responder callback, as they can avoid some memory 
allocations and are safe against accidentally leaving stale 
response objects (objects whose response body wasn't fully 
read). For the returning overloads of the function it is 
recommended to put a scope(exit) right after the call in which 
HTTPClientResponse.dropBody is called to avoid this.


As I understand the situation, request object will reside in 
memory until you fully read or do something with response body.




Re: Can't start application on heroku

2018-06-16 Thread crimaniak via Digitalmars-d-learn

On Saturday, 16 June 2018 at 09:00:21 UTC, Jacob Shtokolov wrote:

On Saturday, 16 June 2018 at 01:24:04 UTC, crimaniak wrote:

Hi all!

The first try to host application on Heroku provider. The 
application is started and starts to listen in 3 seconds on 
the port, provided by heroku-buildpack-d. But the server 
doesn't detect listening and stops the application. On the 
local machine, the application works as expected. What can be 
the problem here?


[...]


Probably you could try to change your listening address from 
127.0.0.1 to 0.0.0.0


Thanks! It is. Initially, I did not pay attention to the default 
interface address, because I expected the 'bind-address' 
parameter according to the documentation.


Can't start application on heroku

2018-06-15 Thread crimaniak via Digitalmars-d-learn

Hi all!

The first try to host application on Heroku provider. The 
application is started and starts to listen in 3 seconds on the 
port, provided by heroku-buildpack-d. But the server doesn't 
detect listening and stops the application. On the local machine, 
the application works as expected. What can be the problem here?


...
2018-06-16T00:34:33.00+00:00 app[api]: Build succeeded
2018-06-16T00:34:35.078239+00:00 heroku[web.1]: Starting process 
with command `./virtual-cm --port 9254`

...
2018-06-16T00:34:38.199381+00:00 app[web.1]: [main() INF] 
Listening for requests on http://127.0.0.1:9254/
2018-06-16T00:35:35.416464+00:00 heroku[web.1]: Stopping process 
with SIGKILL
2018-06-16T00:35:35.416377+00:00 heroku[web.1]: Error R10 (Boot 
timeout) -> Web process failed to bind to $PORT within 60 seconds 
of launch
2018-06-16T00:35:35.537505+00:00 heroku[web.1]: State changed 
from starting to crashed

...


Re: How to task pool in vibe.d?

2018-06-09 Thread crimaniak via Digitalmars-d-learn

On Saturday, 9 June 2018 at 15:11:02 UTC, Computermatronic wrote:
I'd like to create a bunch of tasks in vibe.d, then wait for 
them all to complete.


Using std.concurrency and std.parallelism this is trivial.

I could just spawn a bunch of vibe.d tasks and then iteratively 
join them, but I would think vibe.d would provide some 
primitives for task-pooling.

  Yes. https://vibed.org/api/vibe.core.taskpool/TaskPool



Re: GDC on Travis-CI

2018-06-02 Thread crimaniak via Digitalmars-d-learn

On Saturday, 2 June 2018 at 19:48:36 UTC, Matthias Klumpp wrote:

@crimaniak: If you really want to build with all compilers, 
there is a workaround for this issue that does not involve you 
supporting ancient D versions, and that is to actually use 
Debian's GDC on Travis. I use this excessively for my own 
projects, mostly though because I need newer system libraries 
and because I explicitly want to build with the packaged 
compilers as well.
You can use a similar approach and limit it to GDC only, I 
created a PR for that: 
https://github.com/crimaniak/json-patch/pull/1
As you can see on 
https://travis-ci.org/crimaniak/json-patch/jobs/387197216 , 
your code builds fine with the latest GDC.

 Wow! It works! Thanks!

So, if you want that workaround, please take it, if not it may 
serve as a reference for others facing the same problem.
 Yes, pull request is approved. This is exactly what I was hoping 
to find. I also recommend this to others who have this problem. 
It takes some time to install required packages so build was much 
longer than dmd and lcd builds but I think it's not a problem for 
most cases.


Thanks to everyone who answered!


GDC on Travis-CI

2018-06-01 Thread crimaniak via Digitalmars-d-learn
I started to work with Travis-CI, building packages using all 
three main compilers, and noticed that I have problems with gdc 
every time and need to tweak code because of many things missing. 
For example: 
https://travis-ci.org/crimaniak/json-patch/jobs/386963340

Why this situation with gdc and how best to deal with it?


Re: Any way to override base type with dervived in derived type

2018-05-25 Thread crimaniak via Digitalmars-d-learn
On Thursday, 24 May 2018 at 20:24:32 UTC, IntegratedDimensions 
wrote:
I'm pretty much guaranteed that in C, t will be type TT due to 
the design(C goes with TT like bread with butter).

...
1) Your architecture is wrong, I recommend to rethink it.
2) You still can deal with it using template mixins 
https://dlang.org/spec/template-mixin.html


Re: Reactive data

2018-04-02 Thread crimaniak via Digitalmars-d-learn

On Saturday, 31 March 2018 at 16:08:36 UTC, lempiji wrote:



---
import rx;

auto firstWord = new BehaviorSubject!string("Change");
auto secondWord = new BehaviorSubject!string("me!");

auto bothWords = new BehaviorSubject!string("");
combineLatest!((a, b) => a ~ " " ~ b)(firstWord, 
secondWord).doSubscribe(bothWords);


writeln(bothWords.value); // Change me!

firstWord.value = "TEST";
writeln(bothWords.value); // TEST me!
---


Thanks! I will play with it.


Reactive data

2018-03-23 Thread crimaniak via Digitalmars-d-learn

I want to have reactive variables like in this example:

```
USING_REACTIVE_DOMAIN(D)

// The two words
VarSignalT firstWord  = MakeVar(string( "Change" ));
VarSignalT secondWord = MakeVar(string( "me!" ));
// ...
SignalT bothWords = firstWord + string( " " ) + 
secondWord;

```

from this page: 
http://schlangster.github.io/cpp.react/tutorials/BasicSignals.html


Is this possible to make it in D with 
https://github.com/lempiji/rx ? Is there other libraries exists 
for this topic?




Re: Forwarding arguments through a std.algorithm.map

2018-03-10 Thread crimaniak via Digitalmars-d-learn

On Saturday, 10 March 2018 at 20:48:06 UTC, Nordlöw wrote:

If I have a function

bool f(Rs...)(Rs rs)

is it somehow possible to map and forward all its arguments 
`rs` to another function


bool g(Rs...)(Rs rs);


docs:
 https://dlang.org/phobos/std_traits.html#.Parameters
usage example:
 
https://github.com/crimaniak/d-vision/blob/master/src/vision/eventbus.d#L173


Re: What's the proper way to add a local file dependence to dub?

2018-03-09 Thread crimaniak via Digitalmars-d-learn

On Sunday, 4 March 2018 at 16:46:56 UTC, Marc wrote:

then copy it to sources folder?

...
Also, symlinks are power tool for organizing your files without 
copying.


Re: need help with vibe.d receive()

2018-01-16 Thread crimaniak via Digitalmars-d-learn

On Tuesday, 16 January 2018 at 08:54:58 UTC, Sönke Ludwig wrote:
...

The problem is with the `immutable struct StopEvent {}`

  Thanks!
...
So, removing the `immutable` from the declaration solved the 
issue for me, but if possible I'd rather remove the 
`cast(shared Unqual!EventType)` from `emit`, and pass 
`shared`/`immutable` events to it from the outside (or plain 
events with no unshared indirections).
  No, I can't remove casting here, because some other services 
can't work with immutable or shared, so I just fix StopEvent type.




need help with vibe.d receive()

2018-01-10 Thread crimaniak via Digitalmars-d-learn

Hi!

I make multi-task event bus, but there is a problem with the task 
stops.

Please see end of file
https://github.com/crimaniak/d-vision/blob/master/src/vision/eventbus.d

Expected behavior: After sending the StopEvent message in line 
244 it is must be detected in listeners (line 147), so all 
listeners must set exit flag to 'true' and quit immediately.
De-facto behavior: StopEvent() message is not detected by the 
first delegate in line 147 (logger task logs this message by the 
handler in line 185), so subscribed tasks never exit and test 
stops on line 248.


I tried to play with yield() and sleep(), with 'shared' 
attributes and so on, but without result. Can you say please what 
I am doing wrong here?


'dub test' can be used to play with tests.


Re: why ushort alias casted to int?

2017-12-22 Thread crimaniak via Digitalmars-d-learn

On Friday, 22 December 2017 at 10:18:52 UTC, ketmar wrote:

crimaniak wrote:

Both operands are the same type, so as I understand casting to 
longest type is not needed at all, and longest type here is 
ushort in any case. What am I doing wrong?


it is hidden in specs: all types shorter than int are promoted 
to int before doing any math.


Hm, really. ok, I will use the explicit cast, but I don't like it.


why ushort alias casted to int?

2017-12-22 Thread crimaniak via Digitalmars-d-learn

My code:

alias MemSize = ushort;

struct MemRegion
{
MemSize start;
MemSize length;
@property MemSize end() const { return start+length; }
}

Error: cannot implicitly convert expression `cast(int)this.start 
+ cast(int)this.length` of type `int` to `ushort`


Both operands are the same type, so as I understand casting to 
longest type is not needed at all, and longest type here is 
ushort in any case. What am I doing wrong?


Re: git workflow for D

2017-12-04 Thread crimaniak via Digitalmars-d-learn

On Sunday, 3 December 2017 at 20:05:47 UTC, bitwise wrote:


How does one keep their fork up to date? For example, if I fork


https://help.github.com/articles/syncing-a-fork/




Re: Basic questions about D lang?

2017-11-29 Thread crimaniak via Digitalmars-d-learn

On Wednesday, 29 November 2017 at 11:32:51 UTC, Jayam wrote:

In D lang,
1. Is there any feature async/ await like "c#" ? I can't find 
feature like async.
As for me, async/await feature is a half-baked solution. With 
vibe-d you can write asynchronous code without thinking about it 
at all. Details: http://vibed.org/features


2. Is Garbage Collector work default without any code to force 
like in c# or do we need to manually trigger it ?
It starts automatically when you try to allocate memory and there 
is no space in heap. In fact, it leads to architecture 
restriction: destructors must be @nogc. Also, you can run it with 
GC.collect()
3. Can we make library file and use that in any project like 
'Util class' ?

Yes.




Problems with ctRegex

2017-11-28 Thread crimaniak via Digitalmars-d-learn

First problem: it doesn't understand enums, it seems to be a bug:

```
enum TopicMask : string
{
divider = "/",
oneLevelMask = "+",
multiLevelMask = "#",
system = "$",
level = "[^"~divider~oneLevelMask~multiLevelMask~"]*",
publishMask = "^("~divider~"|"~level~")+$"
}


bool topicIsValid(string topic) pure
{
import std.regex;
auto mask = ctRegex!(TopicMask.publishMask);
return !topic.matchFirst(mask).empty;
}

```

result:

/usr/include/dmd/phobos/std/regex/package.d(376,20): Error: 
template std.array.Appender!(TopicMask).Appender.put cannot 
deduce function from argument types !()(TopicMask), candidates 
are:
/usr/include/dmd/phobos/std/array.d(2983,10):
std.array.Appender!(TopicMask).Appender.put(U)(U item) if 
(canPutItem!U)
/usr/include/dmd/phobos/std/array.d(3011,10):
std.array.Appender!(TopicMask).Appender.put(Range)(Range items) 
if (canPutConstRange!Range)
/usr/include/dmd/phobos/std/array.d(3020,10):
std.array.Appender!(TopicMask).Appender.put(Range)(Range items) 
if (canPutRange!Range)
/usr/include/dmd/phobos/std/regex/package.d(387,15): Error: 
cannot implicitly convert expression `app.data()` of type 
`string` to `TopicMask`
/usr/include/dmd/phobos/std/regex/package.d(422,19): Error: 
template instance std.regex.internal.parser.Parser!(TopicMask, 
CodeGen) does not match template declaration Parser(R, Generator) 
if (isForwardRange!R && is(ElementType!R : dchar))
/usr/include/dmd/phobos/std/regex/package.d(393,25): Error: 
template instance std.regex.regexImpl!(TopicMask) error 
instantiating
/usr/include/dmd/phobos/std/regex/package.d(401,17):
instantiated from here: regex!(TopicMask)
/usr/include/dmd/phobos/std/regex/package.d(431,19):
instantiated from here: regex!(TopicMask)
/usr/include/dmd/phobos/std/regex/package.d(453,54):
instantiated from here: ctRegexImpl!("^(/|[^/+#]*)+$", [])
source/mqttd/topic.d(48,14):instantiated from here: 
ctRegex!("^(/|[^/+#]*)+$", [])



If I change ctRegex!(TopicMask.publishMask) to 
ctRegex!("^(/|[^/+#]*)+$") I run into next error:


source/mqttd/topic.d(48,26): Error: pure function 
'mqttd.topic.topicIsValid' cannot call impure function 
'std.regex.matchFirst!(string, StaticRegex!char).matchFirst'
source/mqttd/topic.d(48,26): Error: pure function 
'mqttd.topic.topicIsValid' cannot call impure destructor 
'std.regex.Captures!(string, ulong).Captures.~this'



Is there any change to use regex inside or pure function? I just 
need some pure bool test() method to test string against the mask.




Re: Is variable void?

2017-11-26 Thread crimaniak via Digitalmars-d-learn

On Saturday, 25 November 2017 at 15:34:21 UTC, John Chapman wrote:
Is there any way of determining whether a variable has been 
initialized or not? For example, if something is declared like 
this:


  int x = void;

can I check if it's void before I use it, say, in a function 
it's been passed to?


 You can use Nullable!int


deep copy thread local to shared or how to send() struct with indirections

2017-11-23 Thread crimaniak via Digitalmars-d-learn

Hi!

I need to send Publish struct from 
https://github.com/tchaloupka/vibe-mqtt to another vibe.d task. 
And there is the problem. First of all, I can't make it immutable 
because send() wants to mutate it. I can't send local copy 
because of "Aliases to mutable thread-local data not allowed.". 
And I can't convert it to shared because of "cannot implicitly 
convert expression `packet` of type `Publish` to 
`shared(FixedHeader)`".


I don't understand error message about FixedHeader. Why it tries 
to convert struct to its field? As I understand the real problem 
here is `ubyte[] payload` dynamic array field in Publish which is 
allocated separately, so to make a shared copy of Publish it need 
the deep copy of this struct. How to do it right? I don't want to 
copy all fields manually, is there a standard way to accomplish 
it?



```
struct MqttOnPublish
{
  Publish packet;
}

  override void onPublish(Publish packet)
  {
 super.onPublish(packet);

 // source/vcm/mqtt/bridge.d(69,41): Error: cannot implicitly 
convert expression `packet` of type `Publish` to 
`shared(FixedHeader)`

 shared Publish sp = shared Publish(packet);

/* /usr/include/dmd/phobos/std/concurrency.d(575,5): Error: 
static assert  "Aliases to mutable thread-local data not allowed."

../../.dub/packages/vibe-d-0.8.1/vibe-d/core/vibe/core/concurrency.d(1243,64):  
  instantiated from here: send!(MqttOnPublish)
source/vision/eventbus.d(72,27):instantiated from here: 
send!(MqttOnPublish)
source/vision/eventbus.d(42,13):instantiated from here: 
emit!(MqttOnPublish)
source/vcm/mqtt/bridge.d(70,14):instantiated from here: 
emit!(MqttOnPublish)

*/
 bus.emit(MqttOnPublish(packet));

  }
```



Re: Synchronize Class fields between different threads

2017-11-10 Thread crimaniak via Digitalmars-d-learn

On Friday, 10 November 2017 at 14:36:03 UTC, DrCataclysm wrote:

It is working now. The problem was that the debugger in eclipse 
ddt seems to completely broken. If i run it directly from bash 
it is working.


Be careful with such statements. Typically, this situation means 
that there are Heisenbugs in the code that appear in certain 
conditions.




Re: How to use containers in lock based concurrency

2017-11-03 Thread crimaniak via Digitalmars-d-learn

On Friday, 3 November 2017 at 12:42:29 UTC, ANtlord wrote:
Hello! I can't get how to use double linked list in 
concurrency. Please help.

...
I get a compile error onlineapp.d(8): Error: template 
std.container.dlist.DList!string.DList.insertFront cannot 
deduce function from argument types !()(string) shared,


One Does Not Simply get the non-shared object and use in the 
shared code. (/Boromir mode)


For me, it was useful to read this: 
http://www.informit.com/articles/article.aspx?p=1609144=11




Re: Tango + D2 + Mac

2017-10-17 Thread crimaniak via Digitalmars-d-learn

On Tuesday, 17 October 2017 at 04:01:54 UTC, Fat_Umpalumpa wrote:


Do you by any chance know anything that replaced std.xml?
Everything I look up on it suggests not to use it.


Is this really a problem? In this case, I can help: I recommend 
to use it. And only if you really will have performance problems, 
try something else. https://code.dlang.org/search?q=xml


Re: vibed services stop response after several days of work

2017-09-05 Thread crimaniak via Digitalmars-d-learn

On Tuesday, 5 September 2017 at 13:51:40 UTC, Sönke Ludwig wrote:

The error is most likely caused by issuing two requests to the 
MySQL server from two different tasks on the same connection. 
Usually, mysql-native uses a connection pool to avoid this, but 
that could have been circumvented by accident.


In this case, you have `Data is pending on the connection. Any 
existing ResultRange must be consumed or purged before performing 
any other communication with the server.` usually.




Re: Returning multiple values from a function

2017-09-04 Thread crimaniak via Digitalmars-d-learn

On Monday, 4 September 2017 at 09:22:25 UTC, Vino.B wrote:

 Thank you very much, i have used your idea and was able to 
resolve, and i need one more favor. the below code outputs the 
value but i need the name of the variable + value as below.


Output :
1
2
["C:\\Temp\\TEAM1\\BACKUP", "C:\\Temp\\TEAM2\\ARCHIVE"]

Required Output:
Test1 = 1
Test2 = 2
Path = ["C:\\Temp\\TEAM1\\BACKUP", "C:\\Temp\\TEAM2\\ARCHIVE"]


For fixed names case you can hardcode it:
writeln("Test1 = ", Params[0]);
writeln("Test2 = ", Params[1]);
writeln("Path = ",  Params[2]);

You can't print the actual name of the variable used in tuple 
constructing because tuple doesn't store it. More of this, the 
tuple can be constructed from expression without a name, so it's 
impossible in common case.


Re: Bug in D!!!

2017-09-04 Thread crimaniak via Digitalmars-d-learn
On Wednesday, 30 August 2017 at 20:47:12 UTC, EntangledQuanta 
wrote:



interface I
{   
void Go(T)(S!T s);

static final I New()
{
return new C();
}
}

abstract class A : I
{

}


class C : A
{
void Go(T)(S!T s)
{

}
}



This is a blocker for me! Can someone open a ticket?
  Judging by the length of the thread that I did not read, the 
real problem was not spotted, otherwise, it would be shorter. The 
problem is called "virtual method in the interface" anti-pattern. 
Just never do that, and life will be easier. In this case, I 
recommend to move Go to A and make it just dispatcher for 
specialized private non-templated virtual functions. You don't 
need all this mess with string templates for it.




Re: Returning multiple values from a function

2017-09-04 Thread crimaniak via Digitalmars-d-learn

On Monday, 4 September 2017 at 07:27:12 UTC, Vino.B wrote:

Hi,

 Can you help me in how to return multiple values from a 
function, the below code is throwing an error as below


import std.stdio: writeln;
import std.typecons: tuple, Tuple;

Tuple!(int, string[]) Params () {
return tuple(1, ["C:\\Temp\\TEAM1\\BACKUP", 
"C:\\Temp\\TEAM2\\ARCHIVE"]);

}

void main (){
Params.writeln;
}


Re: Does anyone understand how to use "shared" types with concurrency send/receive functions?

2017-08-20 Thread crimaniak via Digitalmars-d-learn

On Monday, 21 August 2017 at 02:17:57 UTC, crimaniak wrote:
...

shared A a;

...
 Sorry, accidental delete, read this as shared A a = new 
shared(A);




Re: Does anyone understand how to use "shared" types with concurrency send/receive functions?

2017-08-20 Thread crimaniak via Digitalmars-d-learn

On Monday, 14 August 2017 at 03:59:48 UTC, Jonathan M Davis wrote:

And no, this isn't ideal, but the only semi-decent solution 
that's been proposed that safely casts away shared for you is 
synchronized classes, which Andrei describes in TDPL but have 
never been implemented.
 After reading this I did some experiment to understand the 
situation better. I make a simple class and unittest:


// dmd sync1.d -unittest -main

unittest
{
import std.stdio;

synchronized
class A
{
private int a;

void inc()
{
++a;
}

int get(){ return a;}
}

shared A a;

for(int i=0; i<100; ++i)
a.inc();

writeln(a.get); 

}

Oops! Deprecation: read-modify-write operations are not allowed 
for shared variables. Use core.atomic.atomicOp!"+="(this.a, 1) 
instead.


Why use atomic operations if the class already synchronized? 
Well..


...
   import core.atomic: atomicOp;
...
	// ++a; // Deprecation: read-modify-write operations are not 
allowed for shared variables. Use 
core.atomic.atomicOp!"+="(this.a, 1) instead.

atomicOp!"+="(this.a, 1);
...

ok, works. But it works by the way as if synchronized just makes 
all methods shared, but does not provide the object methods with 
a mutex lock, as Java does. Am I right here? And what preventing 
to implement it right, lack of manpower or some ideologic 
problems?




Re: Does anyone understand how to use "shared" types with concurrency send/receive functions?

2017-08-20 Thread crimaniak via Digitalmars-d-learn

On Thursday, 17 August 2017 at 13:09:29 UTC, Kagamin wrote:

On Wednesday, 16 August 2017 at 23:15:10 UTC, crimaniak wrote:
I wonder if it possible and usable to make some template to 
support this pattern, where we give mutex(es), shared 
object(s) and delegate to operate with objects as non-shared.


https://dpaste.dzfl.pl/8b3b05c8ec0a like this? Not sure if it 
helps, don't forget that it's a casted shared object.
 Yes, something like this. In general, I thought about the 
possibility of using several shared objects in this block but 
then realized that everything can be reduced to the case of one 
object.




Re: Does anyone understand how to use "shared" types with concurrency send/receive functions?

2017-08-16 Thread crimaniak via Digitalmars-d-learn

On Monday, 14 August 2017 at 03:59:48 UTC, Jonathan M Davis wrote:

The way to handle shared is to protect the section of code 
that's using the shared object with either a mutex or 
synchronized block, and then you cast away shared from the 
object within that section and operate on it as thread-local. 
When you're done, you make sure that you don't have any 
thread-local references to the data, and you release the mutex 
or exit the synchronized block. e.g. something like


shared T sharedObj = getSharedObj();

synchronized(mutex)
{
T nonSharedObj = cast(T)sharedObject

// do stuff...

// make sure that no references to nonSharedObj have escaped
}


Casting objects just to work with it every time is so bad style 
for me that I even didn't consider such possibility. In fact, I 
did make something like this but with __gshared both object and 
mutex. I think I need to review this part of site engine and my 
programming habits too.
I wonder if it possible and usable to make some template to 
support this pattern, where we give mutex(es), shared object(s) 
and delegate to operate with objects as non-shared.




Re: Does anyone understand how to use "shared" types with concurrency send/receive functions?

2017-08-13 Thread crimaniak via Digitalmars-d-learn

On Sunday, 13 August 2017 at 11:35:05 UTC, Arek wrote:
Yeah, I've read this. But conurrency.send cannot pass immutable 
object. The same story with Unique.

 Sorry, read this as 'efficient immutable'.


More over, "shared" looks rather like unfinished concept.

 Yes, exactly.

Anyway, _gshared looks very promising, so I will try to work 
out any approach.
More of this, I think, you can't avoid __gshared for any complex 
work. Even mutexes from Phobos doesn't support shared, so I had 
to 'cowboy with __gshared' when implementing my site engine.


Re: Does anyone understand how to use "shared" types with concurrency send/receive functions?

2017-08-12 Thread crimaniak via Digitalmars-d-learn

On Saturday, 12 August 2017 at 18:57:44 UTC, Arek wrote:

I have the folowing problem:
I like to envelope the class object in struct to control the 
destruction moment and then send this object to another 
thread/fiber (or task, cause I use vibe-d).


I can't find any method to make it working. Any ideas?


I tried it too some time ago. Then I read Alexandrescu book and 
realized that the authors of the language do not want anyone to 
do this. Long story short, just plan your application so that 
each complex object is monitored by only one thread/task, and 
pass not objects, but messages (immutable structs) about what to 
do with them.




Re: stacktrace for InvalidMemoryOperationError

2017-07-16 Thread crimaniak via Digitalmars-d-learn

On Saturday, 15 July 2017 at 18:14:13 UTC, Joakim wrote:

core.exception.InvalidMemoryOperationError@src/core/exception.d(696): Invalid 
memory operation

...

See the wiki page about this:

https://wiki.dlang.org/InvalidMemoryOperationError

If you can't do all that, look for places you might be 
allocating in a destructor.  The recent GC allocation flag -vgc 
might help:


https://dlang.org/blog/2017/06/16/life-in-the-fast-lane/


Yes, I found it already and make documentation proposition about 
https://issues.dlang.org/show_bug.cgi?id=17642
Then it turned out that it was more difficult to avoid this 
problem than to find the cause. Yes, I have a heavy cleanup in 
the destructor and I can't definitely make this cleanup @nogc. So 
first I tried to make problematic object instances RefCounted. In 
my case, it means change ClientController[string] to 
RefCounted!ClientController[string] and create an object by lib 
interface, not by new. I have to change ClientController from 
object to struct because automem can't work with the object. I 
hunted all extra copies of these objects and kill them all, so 
now I sure there are no copies except the main container. I tried 
different libraries from std.typecons.RefCounted to automem. And 
I fail to make it _really_ reference counted. It's not deleted 
when I delete it from the container. Every time it's collected by 
GC and application is dropped. So I decided that in the container 
itself. Obviously, the associative array does not delete the 
elements themselves on demand, but loses them and gives them to 
the garbage collector.
I didn't find any map or multimap @nogc container so I make the 
ugly solution: I move all destruction to method destructMe() and 
in ~this() now is just assert(destructMeIsCalled). And now I have 
to call manually destructMe() before object removing. It seems it 
works. I'm wondering if there is a less ugly way to have the map 
of reference counted objects.


Re: char e string em linguagem D

2017-07-14 Thread crimaniak via Digitalmars-d-learn

On Thursday, 13 July 2017 at 22:36:47 UTC, Basile B. wrote:

  return cast(char[])`

...
Never cast a literal to char[]. modifying the resulting char[] 
will lead to AV, at least under linux.  `.dup` the literal if 
you really needs char[].


Hmm, yes, my bad. Probably, it was necessary even for this simple 
example to write const char[].


Re: char e string em linguagem D

2017-07-13 Thread crimaniak via Digitalmars-d-learn

On Thursday, 13 July 2017 at 21:49:40 UTC, dark777 wrote:

Pessoal eu fiz o seguinte programa em C++.

https://pastebin.com/CvVv6Spn

porem tentei fazer o equivalente em D mas nao entendi muito 
bem...


https://pastebin.com/2xw9geRR

alguem poderia me ajudar?


Se acepta utilizar intervalos en lugar de punteros desnudos. 
(Hola, soy traductor de google)


import std.stdio, std.string;

//https://www.vivaolinux.com.br/script/GNU-que-bacana

class GnuQueBacana
{
   this(){}

  char[] stalman()
  {
  return cast(char[])`
  ((__-^^-,-^^-__))
   *---***---*
*--|o   o|--*
   \ /
): :(
(o_o)
  -
 https://www.gnu.org

`;
  }

  char[] torvald()
  {
  return cast(char[])`
#
   ###
   ##O#O##
   ###
   ##\#/##
#lll##
   #l##
   #l###
   #####
  OOO#ll#OOO
 OO#ll#OO
OOO#ll#OOO
 OOO##OOO
https://www.kernel.org

`;
  }

  string stallman()
  {
  return `
  ((__-^^-,-^^-__))
   *---***---*
*--|o   o|--*
   \ /
): :(
(o_o)
  -
 https://www.gnu.org

`;
  }

  string torvalds()
  {
  return `
#
   ###
   ##O#O##
   ###
   ##\#/##
#lll##
   #l##
   #l###
   #####
  OOO#ll#OOO
 OO#ll#OO
OOO#ll#OOO
 OOO##OOO
https://www.kernel.org

`;
  }

};

void main()
{
  GnuQueBacana gnu = new GnuQueBacana();

  writeln(gnu.stalman(), gnu.torvald(), gnu.stallman(), 
gnu.torvalds());

}


Re: Having a strange issue with std.net.curl.HTTP as a struct dependency

2017-07-12 Thread crimaniak via Digitalmars-d-learn

On Wednesday, 12 July 2017 at 13:47:06 UTC, Adam D. Ruppe wrote:


This tells me the problem is in the collection order at the end 
of the program.

...
So I'd say the answer is prolly to keep HTTP away from the GC. 
Manually free its arrays, or keep them outside arrays in the 
first place.


I'd try also calling GC.collect() manually before the exit.



Re: mysql-native ResultRange + map

2017-07-11 Thread crimaniak via Digitalmars-d-learn
On Tuesday, 11 July 2017 at 22:46:00 UTC, Steven Schveighoffer 
wrote:

On 7/5/17 12:04 PM, crimaniak wrote:

...
Because of the temporary copy likely inside map closes the 
connection.


See the bug I reported: 
https://github.com/mysql-d/mysql-native/issues/117
 Yes, it seems to be the same issue. (BTW, then I tried filter() 
just for curiosity and have the same problem).


I work around this in my code by moving the temporary copy. But 
I'm sorry to say you likely will not be able to fix map.
 I have WEB application (no big recordsets to transfer), so, for 
now, I "fix" it inside of my sql wrapper: just load recordset to 
an array and give it instead of ResultRange. I don't like it, but 
it works and all shit is localized in one place.


I think Nick's comment is interesting, "Seems that using struct 
dtors without refcounting should in general be regarded as a 
code smell?"


It's a good question. I've also always added ref counting when 
wanting to "auto close" a struct's resources. In fact, I can't 
really think of a good use of destructors for structs that 
isn't for reference counting itself.


I don't think so. There is architecture problem: non-copyable by 
nature resource represented by copyable struct. We need 
non-copyable class/object semantics here or have to emulate it if 
using the struct to have the correct behavior. It's fully o.k. to 
get some resources required by _this exact copy_ of struct in the 
constructor and then release it in the destructor. For example of 
good use of destructors: position in some game, requires 
non-fixed space to store itself. We want to make copies of 
positions, apply some movies to them and then make copies again 
to search in positions tree. Copy constructor will malloc some 
space and copy source position data, the destructor will free 
this space, and we don't need reference counting here.






stacktrace for InvalidMemoryOperationError

2017-07-10 Thread crimaniak via Digitalmars-d-learn

Hi!

I have vibe.d application and long-standing error in it.
For the current moment, I have logs for stdout, stderr, and 
additional log to write exceptions I catch. This error gives me 
only the short line in stderr log:


core.exception.InvalidMemoryOperationError@src/core/exception.d(696): Invalid 
memory operation


Also, I use registerMemoryErrorHandler(); (see 
http://vibed.org/docs#handling-segmentation-faults )


What else can I do to have the stack trace for this error?

I can't debug it because I don't have it on my developer's 
machine.


mysql-native ResultRange + map

2017-07-05 Thread crimaniak via Digitalmars-d-learn

Hi all!

After some hard time with debugging, I found ResultRange returned 
by query() and Prepared::query() of mysql-native package can't be 
combined with map() because after map() it becomes empty 
resultset.


Code (conn.queryRows just a wrapper for query(Connections, sql) ):

immutable sql = "SELECT id FROM "~tableName~" ORDER BY id";

	conn.queryRows(sql).each!(row => writeln("each:", 
row[0].to!string));


	string[] applied = conn.queryRows(sql).map!(row => 
row[0].to!string).array;

writeln("applied:", applied);

foreach(row; conn.queryRows(sql))
writeln("foreach: ", row[0].to!string);

	conn.queryRows(sql).map!(row => row[0].to!string).each!(row => 
writeln("map-each:", row));


foreach(row; conn.queryRows(sql).map!(row => row[0].to!string))
writeln("foreach-map: ", row);

stdout.flush;

Result:
SELECT id FROM versionupdate ORDER BY id
each:.Script20161013_create_database
each:.Script20161221_sites_table
each:.Script20161227_update_users_devices
each:.Script20170121_ownerid
each:.Script20170124_create_clients
each:.Script20170213_no_unique_site_name
each:.Script20170215_remove_site_sn
each:.Script20170228_remove_site_index
each:.Script20170301_add_linkNo
each:.Script20170301_fix_sites_indexes
each:.Script20170310_demo_client
each:.Script20170513_max_dev_number
SELECT id FROM versionupdate ORDER BY id
applied:[]
SELECT id FROM versionupdate ORDER BY id
foreach: .Script20161013_create_database
foreach: .Script20161221_sites_table
foreach: .Script20161227_update_users_devices
foreach: .Script20170121_ownerid
foreach: .Script20170124_create_clients
foreach: .Script20170213_no_unique_site_name
foreach: .Script20170215_remove_site_sn
foreach: .Script20170228_remove_site_index
foreach: .Script20170301_add_linkNo
foreach: .Script20170301_fix_sites_indexes
foreach: .Script20170310_demo_client
foreach: .Script20170513_max_dev_number
SELECT id FROM versionupdate ORDER BY id
SELECT id FROM versionupdate ORDER BY id

As you see simple each() and foreach() works, but all examples 
with map() involved always empty. Can anybody explain such 
strange behavior?




Re: weird error message

2017-07-05 Thread crimaniak via Digitalmars-d-learn

On Sunday, 2 July 2017 at 01:06:29 UTC, Ali Çehreli wrote:

On 07/01/2017 04:56 PM, crimaniak wrote:

> about very long error messages generated in some
> cases.

Please submit a bug report. The compiler may be able to 
abbreviate certain types. For example, in this case most of the 
error message text is values of a static array elements.


Done: https://issues.dlang.org/show_bug.cgi?id=17599


Re: weird error message

2017-07-01 Thread crimaniak via Digitalmars-d-learn

On Saturday, 1 July 2017 at 22:46:06 UTC, Adam D. Ruppe wrote:

On Saturday, 1 July 2017 at 22:44:33 UTC, crimaniak wrote:

enum moduleMask = ctRegex!`module\s+([^;]+)`;


That should be `static`, not `enum`. I betcha that will at 
least change the error.


Works both variants, and reason really in line with Captures c = 
..., as mentioned Ali Çehreli.  But my message not about this 
mistake (I fix it immediately), but about very long error 
messages generated in some cases. Maybe it will be good to have 
some compiler switch or special treatment for messages with so 
very long types.


weird error message

2017-07-01 Thread crimaniak via Digitalmars-d-learn

Just for fun (may be):

code:

auto findModule = execute(["dscanner", "--etags", entry.name]);
enum moduleMask = ctRegex!`module\s+([^;]+)`;
Captures c = findModule.output.matchFirst!(moduleMask);

result (even C++ guys will be impressed):

phobos_imports.d(43): Error: struct std.regex.Captures(R, DIndex 
= size_t) if (isSomeString!R) is used as a type
phobos_imports.d(43): Error: template std.regex.matchFirst cannot 
deduce function from argument types !(StaticRegex(& func, 
Regex([InversionList(CowArray([9u, 14u, 32u, 33u, 133u, 134u, 
160u, 161u, 5760u, 5761u, 8192u, 8203u, 8232u, 8234u, 8239u, 
8240u, 8287u, 8288u, 12288u, 12289u, 3u])), 
InversionList(CowArray([0u, 59u, 60u, 1114112u, 3u]))], 
[Bytecode(2147483757u), Bytecode(2147483759u), 
Bytecode(2147483748u), Bytecode(2147483765u), 
Bytecode(2147483756u), Bytecode(2147483749u), 
Bytecode(2348810240u), Bytecode(2231369729u), 
Bytecode(2348810240u), Bytecode(2248146945u), Bytecode(0u), 
Bytecode(2952790017u), Bytecode(2281701377u), 
Bytecode(2231369729u), Bytecode(2281701377u), 
Bytecode(2248146945u), Bytecode(1u), Bytecode(3019898881u), 
Bytecode(2550136833u)], null, 2u, 0u, 2u, 17u, 0u, 
[CharMatcher(BitTable([15872u, 1u, 0u, 0u]), 
Trie(MultiArray([0LU, 2048LU], [8192LU, 1536LU], 
[281479271743488LU, 281479271743489LU, 281479271743489LU, 
281479271743489LU, 281479271743489LU, 281483566710785LU, 
281479271743489LU, 281479271743489LU, 281479271743491LU, 
281479271743489LU, 281479271743489LU, 281479271743489LU, 
281479271743492LU, 281479271743489LU, 281479271743489LU, 
281479271743489LU, 281479271743489LU, 281479271743489LU, 
281479271743489LU, 281479271743489LU, 281479271743489LU, 
281479271743489LU, 281479271743489LU, 281479271743489LU, 
281479271743489LU, 281479271743489LU, 281479271743489LU, 
281479271743489LU, 281479271743489LU, 281479271743489LU, 
281479271743489LU, 281479271743489LU, 281479271743489LU, 
281479271743489LU, 281479271743489LU, 281479271743489LU, 
281479271743489LU, 281479271743489LU, 281479271743489LU, 
281479271743489LU, 281479271743489LU, 281479271743489LU, 
281479271743489LU, 281479271743489LU, 281479271743489LU, 
281479271743489LU, 281479271743489LU, 281479271743489LU, 
281479271743489LU, 281479271743489LU, 281479271743489LU, 
281479271743489LU, 281479271743489LU, 281479271743489LU, 
281479271743489LU, 281479271743489LU, 281479271743489LU, 
281479271743489LU, 281479271743489LU, 281479271743489LU, 
281479271743489LU, 281479271743489LU, 281479271743489LU, 
281479271743489LU, 281479271743489LU, 281479271743489LU, 
281479271743489LU, 281479271743489LU, 281479271743489LU, 
281479271743489LU, 281479271743489LU, 281479271743489LU, 
281479271743489LU, 281479271743489LU, 281479271743489LU, 
281479271743489LU, 281479271743489LU, 281479271743489LU, 
281479271743489LU, 281479271743489LU, 281479271743489LU, 
281479271743489LU, 281479271743489LU, 281479271743489LU, 
281479271743489LU, 281479271743489LU, 281479271743489LU, 
281479271743489LU, 281479271743489LU, 281479271743489LU, 
281479271743489LU, 281479271743489LU, 281479271743489LU, 
281479271743489LU, 281479271743489LU, 281479271743489LU, 
281479271743489LU, 281479271743489LU, 281479271743489LU, 
281479271743489LU, 281479271743489LU, 281479271743489LU, 
281479271743489LU, 281479271743489LU, 281479271743489LU, 
281479271743489LU, 281479271743489LU, 281479271743489LU, 
281479271743489LU, 281479271743489LU, 281479271743489LU, 
281479271743489LU, 281479271743489LU, 281479271743489LU, 
281479271743489LU, 281479271743489LU, 281479271743489LU, 
281479271743489LU, 281479271743489LU, 281479271743489LU, 
281479271743489LU, 281479271743489LU, 281479271743489LU, 
281479271743489LU, 281479271743489LU, 281479271743489LU, 
281479271743489LU, 281479271743489LU, 281479271743489LU, 
281479271743489LU, 281479271743489LU, 281479271743489LU, 
281479271743489LU, 281479271743489LU, 281479271743489LU, 
281479271743489LU, 281479271743489LU, 281479271743489LU, 
281479271743489LU, 281479271743489LU, 281479271743489LU, 
281479271743489LU, 281479271743489LU, 281479271743489LU, 
281479271743489LU, 281479271743489LU, 281479271743489LU, 
281479271743489LU, 281479271743489LU, 281479271743489LU, 
281479271743489LU, 281479271743489LU, 281479271743489LU, 
281479271743489LU, 281479271743489LU, 281479271743489LU, 
281479271743489LU, 281479271743489LU, 281479271743489LU, 
281479271743489LU, 281479271743489LU, 281479271743489LU, 
281479271743489LU, 281479271743489LU, 281479271743489LU, 
281479271743489LU, 281479271743489LU, 281479271743489LU, 
281479271743489LU, 281479271743489LU, 281479271743489LU, 
281479271743489LU, 281479271743489LU, 281479271743489LU, 
281479271743489LU, 281479271743489LU, 281479271743489LU, 
281479271743489LU, 281479271743489LU, 281479271743489LU, 
281479271743489LU, 281479271743489LU, 281479271743489LU, 
281479271743489LU, 281479271743489LU, 281479271743489LU, 
281479271743489LU, 281479271743489LU, 281479271743489LU, 
281479271743489LU, 281479271743489LU, 281479271743489LU, 

Re: mysql-native + vibe.d example

2017-06-30 Thread crimaniak via Digitalmars-d-learn

On Friday, 30 June 2017 at 16:18:33 UTC, tetyys wrote:

On Friday, 30 June 2017 at 00:52:28 UTC, crimaniak wrote:

Hi!
Moving my project from mysql-lited to mysql-native I faced the 
problem with null pointer error inside of mysql-native:




seems like it's already fixed 
https://github.com/mysql-d/mysql-native/commit/477636ad92a15d504308d1893f987685cd71


Yes, this is relevant fix. Thanks!


mysql-native + vibe.d example

2017-06-29 Thread crimaniak via Digitalmars-d-learn

Hi!
Moving my project from mysql-lited to mysql-native I faced the 
problem with null pointer error inside of mysql-native:


Log:
SELECT id FROM versionupdate ORDER BY id
Task terminated with unhandled exception:
etc.linux.memoryerror.NullPointerError@src/etc/linux/memoryerror.d(325)

??:? void etc.linux.memoryerror.sigsegvUserspaceProcess(void*) 
[0x102ebad]

??:? void etc.linux.memoryerror.sigsegvDataHandler() [0x102eaee]
../../.dub/packages/mysql-native-1.1.0/mysql-native/source/mysql/result.d:466 
const(pure nothrow @property bool function()) mysql.result.ResultRange.isValid 
[0xdf1626]
../../.dub/packages/mysql-native-1.1.0/mysql-native/source/mysql/result.d:536 
void mysql.result.ResultRange.close() [0xdf1cb8]
../../.dub/packages/mysql-native-1.1.0/mysql-native/source/mysql/result.d:460 
void mysql.result.ResultRange.__dtor() [0xdf15cc]
../../.dub/packages/mysql-native-1.1.0/mysql-native/source/mysql/result.d:430 
ref return mysql.result.ResultRange 
mysql.result.ResultRange.opAssign(mysql.result.ResultRange) [0xdf1dba]
source/vcm/sqlWrapper.d:63 mysql.result.ResultRange 
vcm.sqlWrapper.SqlWrapper.query!().query(immutable(char)[]) 
[0xdd57e3]
source/updater/manager.d:92 void 
updater.manager.UpdateManager.update() [0xd74886]

source/app.d:81 void app.prepareDb().__lambda1() [0xcfe740]
../../.dub/packages/vibe-d-0.7.31/vibe-d/source/vibe/core/core.d:595 void 
vibe.core.core.makeTaskFuncInfo!(void delegate()).makeTaskFuncInfo(ref void 
delegate()).callDelegate(vibe.core.core.TaskFuncInfo*) [0xc5b703]
../../.dub/packages/vibe-d-0.7.31/vibe-d/source/vibe/core/core.d:1224 void 
vibe.core.core.CoreTask.run() [0xf6a916]
??:? void core.thread.Fiber.run() [0x107f17b]
??:? fiber_entryPoint [0x107eede]
??:? [0x]

Code fragment:
string s = Sql(sqlString, args).toString!MysqlDialect;
writeln(s);stdout.flush; // debugging...

if(conn.__conn() is null) // debugging...
throw new Exception("connection is null");

ResultRange result;
// synchronized (mutex)
result = conn.query(s);  // <-- sqlWrapper.d:63 is here

It seems I am doing something wrong so myself-native fails to 
detect it in isValid(). So I search for example how to use 
mysql-native in real multi-threaded vibe.d application with usage 
of MySQLPool. Please do not point me to basic example provided 
with package because it is single thread.

Thanks.



site examples

2017-05-25 Thread crimaniak via Digitalmars-d-learn
I tried to run an example from the site. Example from 
https://dlang.org/phobos/std_regex.html#replaceAllInto section. 
And this is problem number 0: I can't give a link to the example, 
only to section. The section can be long, there can be more than 
one example, so it's good to have an anchor for each example. 
Problem #1: "Compilation output (255: Unknown signal 255)
unable to fork: Cannot allocate memory." As I understand it, this 
is a common problem, and it leaves a bad impression. Ok, I copy 
example text and try to compile it. Oh, I need to make main(). 
Ok. "t1.d(6): Error: undefined identifier 'regex'

t1.d(12): Error: undefined identifier 'replaceAllInto'
t1.d(14): Error: 'writeln' is not defined, perhaps you need to 
import std.stdio; ?"
Problem #3: we have imports in the example, but not all imports. 
Ok, I add it. Compile, run. A lot of commas. Is this proof that 
the method worked? Yes. Do these commas illustrate how this 
method works? Absolutely not. This is a replacement method, so I 
expect to see "before" and "after".
It seems to me that examples on the site require additional work 
and in the current form are counterproductive in terms of 
attracting new users.


Re: Code improvement for DNA reverse complement?

2017-05-19 Thread crimaniak via Digitalmars-d-learn

On Friday, 19 May 2017 at 12:55:05 UTC, Biotronic wrote:
revComp6 seems to be the fastest, but it's probably also the 
least readable (a common trade-off).

Try revComp7 with -release :)

string revComp7(string bps)
{
char[] result = new char[bps.length];
auto p1 = result.ptr;
auto p2 = [$ - 1];
enum AT = 'A'^'T';
enum CG = 'C'^'G';

while (p2 > bps.ptr)
{
   *p1 = *p2 ^ ((*p2 == 'A' || *p2 == 'T') ? AT : CG);
p1++;
p2--;
}
return result.assumeUnique;
}

In fact, when the size of the sequence is growing time difference 
between procedures is shrinking, so it's much more important to 
use memory-efficient presentation than to optimize logic.


Re: How to write parser?

2017-05-15 Thread crimaniak via Digitalmars-d-learn

On Sunday, 14 May 2017 at 19:00:09 UTC, Suliman wrote:
I am trying to learn how to write text parser. I have example 
doc with follow format:


#Header
my header text

##SubHeader
my sub header text




it's there any better way to parse such format?


Ready markdown Pegged based parser:
https://github.com/PhilippeSigaud/Pegged/blob/master/pegged/examples/markdown.d


Re: How to avoid throwing an exceptions for a built-in function?

2017-05-11 Thread crimaniak via Digitalmars-d-learn

On Wednesday, 10 May 2017 at 12:40:41 UTC, k-five wrote:
I have a line of code that uses "to" function in std.conv for a 
purpose like:


int index = to!int( user_apply[ 4 ] ); // string to int

When the user_apply[ 4 ] has value, there is no problem; but 
when it is empty: ""
it throws an ConvException exception and I want to avoid this 
exception.


currently I have to use a dummy catch:
try{
index = to!int( user_apply[ 4 ] );
} catch( ConvException conv_error ){
// nothing
}

I no need to handle that, so is there any way to prevent this 
exception?


try this:
https://dlang.org/phobos/std_exception.html#ifThrown


Re: Productive vibe.d dev environment (IDE, debugger) on Linux?

2017-05-08 Thread crimaniak via Digitalmars-d-learn

On Wednesday, 3 May 2017 at 17:43:07 UTC, kinke wrote:

can anyone recommend a more or less production-ready dev 
environment for vibe.d on Linux?
I'm evaluating vibe.d against Phoenix (Elixir/Erlang) for a new 
project. Today I gave Visual Studio Code a quick shot (with LDC 
1.1.1 and DMD 2.071/72/74), with Webfreak's plugins, but I'm 
not happy at all (gdb/lldb crashing most of the time incl. 
debugged process, no AutoComplete/IntelliSense due to problems 
when building some of the plugin dependencies etc.).


Any hints are greatly appreciated, as I'm really impressed by 
vibe.d itself so far.


DDT: http://ddt-ide.github.io/
It just works including debugging, but autocompletion is 
rudimental.




Re: The app hanging after reach 1750MB of RAM

2017-04-19 Thread crimaniak via Digitalmars-d-learn

On Tuesday, 18 April 2017 at 11:43:24 UTC, Suliman wrote:
I am writing app that extract data from DB to array of 
structures.


void getSingleTrackInfo()
{

foreach(item; getTablesGPSSensorList)
{
ResultRange result = mysqlconnection.query(sqlquery);
auto MySQLPointsLonLat = result.array;
Is ResultRange closing query when exhausted? Did you try to call 
.close() on it after work?


URL (or URI) Pegged grammar - is it exists?

2017-04-10 Thread crimaniak via Digitalmars-d-learn

Hi, all!

Yes, I know, most simple way to validate URL is regex and it 
works for most cases, but I search for a correct solution 
(ideally rfc3986-compatible), which will be hard to implement 
using regular expressions.


Re: 'fopen64 cannot be interpreted at compile time' for __gshared File

2017-03-25 Thread crimaniak via Digitalmars-d-learn

On Saturday, 25 March 2017 at 16:08:49 UTC, NotSpooky wrote:


__gshared implies static,...


Thanks! Confusing for me moment.


'fopen64 cannot be interpreted at compile time' for __gshared File

2017-03-25 Thread crimaniak via Digitalmars-d-learn

Simple File test:

void main()
{
import std.stdio;

File f = File("test.txt", "w");

f.writeln("hello");
}

All works as expected.

Now let's add __gshared:

void main()
{
import std.stdio;

__gshared File f = File("test.txt", "w");

f.writeln("hello");
}

Now we have:

/usr/include/dmd/phobos/std/stdio.d(3797): Error: fopen64 cannot 
be interpreted at compile time, because it has no available 
source code
/usr/include/dmd/phobos/std/stdio.d(3804):called from 
here: fopenImpl(namez.ptr(), modez.ptr())
/usr/include/dmd/phobos/std/stdio.d(404):called from 
here: fopen(name, stdioOpenmode)
/usr/include/dmd/phobos/std/stdio.d(404):called from 
here: errnoEnforce(fopen(name, stdioOpenmode), delegate string() 
=> text("Cannot open file `", name, "' in mode `", stdioOpenmode, 
"'"))
/usr/include/dmd/phobos/std/stdio.d(404):called from 
here: this.this(errnoEnforce(fopen(name, stdioOpenmode), delegate 
string() => text("Cannot open file `", name, "' in mode `", 
stdioOpenmode, "'")), name, 1u, false)
file.d(5):called from here: ((File __slFile648 = 
File(null, null);) , __slFile648).this("test.txt", "w")


Oooops! Who can explain this error message to me?

DMD64 D Compiler v2.073.0




Re: how to test if member of instance exists/defined?

2017-03-22 Thread crimaniak via Digitalmars-d-learn

On Wednesday, 22 March 2017 at 20:35:27 UTC, StarGrazer wrote:
I've tried compiles but I guess that only checks if the code 
has valid syntax, not if it actually will compile in context.


https://dlang.org/spec/traits.html#hasMember


Re: Question about vibe.conf file

2017-03-05 Thread crimaniak via Digitalmars-d-learn

On Sunday, 5 March 2017 at 13:41:23 UTC, Suliman wrote:
I had seen some mentions about `vibe.conf` file in vibed docs. 
But can't understand it's structure and find examples of it's 
usage.


Json file. Real example:
```
{
"mqttHost"   : "***.***.**.***",
"mqttPort"   : 1883,
"mqttClientName" : "*",
"mqttUsername"   : "*",
"mqttPassword"   : "*",

"listenInterface": "127.0.0.1",
"listenPort" : 8088,

"dbConnection"   : "host=127.0.0.1;user=root;pwd=;db=dbname"
}
```

You can read values from it like this:

```
// Read http setting from vibe.conf and init session store
HTTPServerSettings prepareHttpSettings()
{
auto settings = new HTTPServerSettings;
	settings.port = readRequiredOption!ushort("listenPort","Port to 
listen by internal HTTP server");
	settings.bindAddresses = 
[readRequiredOption!string("listenInterface", "Interface to 
listen by internal HTTP server")];

settings.sessionStore = new MemorySessionStore;

return settings;
}
```


Problem with send / receive

2017-03-03 Thread crimaniak via Digitalmars-d-learn

Hi all!

I make vibe-d based project and now I have problem passing 
messages between threads.
First some words about architecture. Each event in the system has 
a corresponding class that validates and performs the required 
actions. Each class has a nested structure with the parameters 
that are required for this event. Like this:


```
module vcm.bll.event.deleteSite;

import vcm.bll.basicEvent;

class DeleteSite : BasicEvent
{
import vcm.bll.model.types : Id;

struct Params
{
Id siteId;
}

mixin EventConstructor;

override bool canDo()
{
import std.conv : to;

return errorList
			.addIf(!engine.sites.contains(params.siteId), "SiteModel with 
id "~params.siteId.to!string~" is not found")

.isEmpty();
}

override EventResult doIt()
{
		engine.db.execute("DELETE FROM sites WHERE id=?", 
params.siteId);


return EventResult(true,[],0);
}

}
```
I have Engine class object which resides in own thread and listen 
message queue for messages with event parameters. After receiving 
message corresponding handler is executed, and message with 
EventResult object sent back to caller thread (Task). For every 
event type there is HTTP request handler, who make 
EventType.Params structure, send it to engine Task, then do 
receiveOnly!EventResult and take actions according to it. The 
only proble with this approach was a lot of boilerplate in engine 
receive() call because of big amout of event types. I resolve it 
by this way (is this possible without string mixin?):


```
private static string getReceiver(EventTypes...)() pure
{
import std.traits;

string eventHandlers;
foreach(EventType; EventTypes)
			eventHandlers ~= `,(`~EventType.stringof~`.Params params, Task 
caller, Id userId){

auto event = 
scoped!`~EventType.stringof~`(userId, params);
event.setEngine(this);
caller.send(event.execute());
}`;

return
`receive
((ExitMessage _){ exitFlag = true; }
,(LogMessage entry){ logger.log(entry.message); 
}
`
~eventHandlers
~");";
}

private void run()
{
import vibe.core.concurrency : receive, send;
import std.typecons: scoped;
import vcm.bll.event;

bool exitFlag = false;

while(!exitFlag)
mixin(getReceiver!AllEvents);
}

```

After adding another event I ran into a problem:

```
Task terminated with unhandled exception: Range violation
core.exception.RangeError@source/vcm/bll/idContainer.d(44): Range 
violation


...
vcm.bll.event.deleteSite.DeleteSite.canDo() [0xd8dd5a]
source/vcm/bll/basicEvent.d:182 bool 
vcm.bll.basicEvent.BasicEvent.check() [0xd2f8bc]
source/vcm/bll/basicEvent.d:197 vcm.bll.basicEvent.EventResult 
vcm.bll.basicEvent.BasicEvent.execute() [0xd2f9a5]
source/vcm/bll/engine.d-mixin-173:198 
_D3vcm3bll6engine6Engine3runMFZ9__lambda8MFS3vcm3bll5event10deleteSite10DeleteSite6ParamsS4vibe4core4task4TaskmZv [0xd34375]
/usr/include/dmd/phobos/std/concurrency.d:168 void 
std.concurrency.Message.map!(void 
delegate(vcm.bll.event.deleteSite.DeleteSite.Params, 
vibe.core.task.Task, ulong)).map(void 
delegate(vcm.bll.event.deleteSite.DeleteSite.Params, 
vibe.core.task.Task, ulong)) [0xc7df3d]
/usr/include/dmd/phobos/std/concurrency.d:1956 
_D3std11concurrency10MessageBox1467__T3getTDFNaNbNiNfS3vcm3bll7commons11ExitMessageZvTDFS3vcm3bll6engine10LogMessageZvTDFS3vcm3bll5event9addDevice9AddDevice6ParamsS4vibe4core4task4TaskmZvTDFS3vcm3bll5event9addClient9AddClient6ParamsS4vibe4core4task4TaskmZvTDFS3vcm3bll5event7addRole7AddRole6ParamsS4vibe4core4task4TaskmZvTDFS3vcm3bll5event7addUser7AddUser6ParamsS4vibe4core4task4TaskmZvTDFS3vcm3bll5event7addSite7AddSite6ParamsS4vibe4core4task4TaskmZvTDFS3vcm3bll5event10deleteSite10DeleteSite6ParamsS4vibe4core4task4TaskmZvTDFS3vcm3bll5event13adminEditUser13AdminEditUser6ParamsS4vibe4core4task4TaskmZvTDFS3vcm3bll5event14changePassword14ChangePassword6ParamsS4vibe4core4task4TaskmZvTDFS3vcm3bll5event12deleteDevice12DeleteDevice6ParamsS4vibe4core4task4TaskmZvTDFS3vcm3bll5event10deleteRole10DeleteRole6ParamsS4vibe4core4task4TaskmZvTDFS3vcm3bll5event10deleteUser10DeleteUser6ParamsS4vibe4core4task4TaskmZvTDFS3vcm3bll5event10editDevice10EditDevice6ParamsS4vibe4core4task4TaskmZvTDFS3vcm3!


Re: code D'ish enough? - ignore previous post with same subject

2017-02-28 Thread crimaniak via Digitalmars-d-learn

On Sunday, 26 February 2017 at 21:50:38 UTC, Jordan Wilson wrote:

.map!(a => a.to!double)

 If lambda just calls another function you can pass it directly:
== .map!(to!double)



Re: Getting a segfault here, why?

2017-02-16 Thread crimaniak via Digitalmars-d-learn

On Thursday, 16 February 2017 at 09:18:16 UTC, aberba wrote:
On linux it is pretty easy. Just compile with `-g` to dmd and 
run the program in gdb. Run till it crashes and it should tell 
you the file and line of where.


Thanks, will try and see.
 Also don't forget to do this: 
http://vibed.org/docs#handling-segmentation-faults




Re: Iterate module membres

2017-01-07 Thread crimaniak via Digitalmars-d-learn


Ok, I found it: https://issues.dlang.org/show_bug.cgi?id=16044


Re: Iterate module membres

2017-01-07 Thread crimaniak via Digitalmars-d-learn

On Saturday, 7 January 2017 at 12:29:34 UTC, ketmar wrote:

On Saturday, 7 January 2017 at 12:11:20 UTC, crimaniak wrote:

Is this a bug or documentation problem?


well, it's hard to say. package.d is one of the cases where you 
*have* to provide explicit module definition. ;-) 'cause 
implicit one creates module with name `package`, which is teh 
keyword. and then all the hell broke loose. this actually may 
be both bug and documentation problem.
  Yes, removing 'module' statement leads to error on 
__traits(allMembers, mixin(__MODULE__)) expression: Error: 
expression expected, not 'package'.

But it's not related, I provide module statement in package.d.



Re: Iterate module membres

2017-01-07 Thread crimaniak via Digitalmars-d-learn

On Saturday, 7 January 2017 at 10:38:29 UTC, ketmar wrote:
On Saturday, 7 January 2017 at 10:27:51 UTC, Nicholas Wilson 
wrote:

Do you require a module statement per chance?


it doesn't matter. if there is no explicit module declaration, 
compiler will insert implicit one. from the code PoV, there is 
no difference at all.
 Yes, module statement is no reason. package.d is reason. The 
same code in two files:


class foo{};
struct bar{};
pragma (msg, "allMembers of "~__MODULE__~" in "~__FILE__);
pragma(msg, __traits(allMembers, mixin(__MODULE__)));

Result:

allMembers of vcm.bll.event in source/vcm/bll/event/package.d
tuple()
allMembers of vcm.bll.event.test in source/vcm/bll/event/test.d
tuple("object", "vcm", "foo", "bar")

So allMembers gives empty tuple for module in package.d file. 
Please check it. As I understand documentation, package.d is 
ordinary module and special here is only file name used when 
module name is directory.

DMD 2.071.1. Is this a bug or documentation problem?



Iterate module membres

2017-01-07 Thread crimaniak via Digitalmars-d-learn

Hi!

I need to iterate module members and find specific classes (and 
make tuple).


class foo{};
pragma (msg, __traits(allMembers,mixin(__MODULE__)));

gives me empty tuple. I found also this thread from 2011: 
http://forum.dlang.org/post/mailman.325.1293887146.4748.digitalmars-d-le...@puremagic.com

This is exactly what I need but this code also gives empty tuple.
Is this possible for now to iterate classes from module? Is this 
possible to iterate by classes, public imported to module? (in 
fact, I need to iterate classes imported using package.d file).






Re: [question] Access from UDA constructor to parent symbol

2016-12-27 Thread crimaniak via Digitalmars-d-learn

On Tuesday, 27 December 2016 at 02:05:27 UTC, Ali Çehreli wrote:

On 12/26/2016 02:04 PM, crimaniak wrote:


So my main question: how it is possible to do such thing?


Just to make sure we're on the same page: :)

* There is 'interface' in addition to 'class'

 Yes. I want it for structs exactly.


* If all you want is to check, then you can write template 
constraints by following the example of std.range.isInputRange.
 Interface implementation has a significant advantage over 
template constraints for implementation break case. With 
interface I have one relevant error on the implementation stage. 
With template constraints I have many less relevant errors on the 
usage stage. It's just different types of contract.




With that aside, what you need is generally achieved by a mixin:

@implements!I1
struct S1
{
// ...
}

template ValidateInterfaces() {
// Go through all members of the module here
// Identify the ones having the 'implements' UDA
// The useful tools here are
// __traits(getAttributes)
// __traits(allMembers)
// __traits(getMember)
}

mixin ValidateInterfaces;


Thanks, this is a way. The only problem user can forget to call 
this mixin. It would be useful to have module-wide compile-time 
variables, in this case it's possible to call ValidateInterfaces 
one time from first @implements instance and user don't have to 
write it at every module.




Re: [question] Access from UDA constructor to parent symbol

2016-12-26 Thread crimaniak via Digitalmars-d-learn

On Monday, 26 December 2016 at 21:15:03 UTC, Adam D. Ruppe wrote:

On Monday, 26 December 2016 at 20:07:56 UTC, crimaniak wrote:
 // I want to see Foo here and use it's reflection to 
iterate fields and methods.


then pass foo to it

What do you mean parent symbol? I assumed you mean subclass but 
your example shows one class and one struct. So is it the 
structure containing the class? Or what?


I mean the character to which the attribute belongs, Foo in this 
case.





But, the answer of just passing the argument is probably the 
best one anyway. You can use a factory function, or pass the 
type from a constructor to a super method, or something like 
that.
Let me explain. I want to have struct Foo : BarInterface {}. I 
read forums and found some discussion. Arguments against this 
feature has no sense on my opinion. But in fact I don't think it 
will be implemented. So I try to implement it as library. My idea:


class implements(Interface)
{
this()
{
// iterate all members of Interface and check if this element
// exists in parent symbol and check if parameters the same.
// Write clean error message if contract fails.
}
}

unittest
{
interface I1
{
void foo();
int bar(int i);
}


@implements!I1
struct S1
{
void foo()
{
import std.stdio;
writeln("foo");
}

		// I want error message like "function int bar(int i) should be 
implemented according to interface I1" in this case

}
}

So, if I pass both types in parameters it will not be so clean. 
It will be some separate from struct expression, but I want 
attribute like above.


It seems I can find symbol iterating all symbols in __MODULE__but 
in this case it will be O(N^2), there N is amount of @implements 
usages in module.


I also thought about such option:

struct S1
{
mixin implements!I1;
...
}

But this option I like less, and I have not researched it.

So my main question: how it is possible to do such thing?




[question] Access from UDA constructor to parent symbol

2016-12-26 Thread crimaniak via Digitalmars-d-learn

```
class uda
{
this()
{
 // I want to see Foo here and use it's reflection to 
iterate fields and methods.

}
}


@uda
struct Foo
{

}

```
Is there a way to do it?


Re: Two part question. Making a dynamic array of delegates, and taking in a delegate with unknown parameters as an argument .

2016-12-01 Thread crimaniak via Digitalmars-d-learn

On Thursday, 1 December 2016 at 23:51:19 UTC, Payotz wrote:
So, to give context, I am trying to make an event manager for a 
game I'm making.

I was writing the "register()" method so I ran into a problem.

The register method will take in delegates as an argument, but 
those delegates have varied arguments themselves, so I can't 
really put anything there. I know that it's got something to do 
with templates so I tried my hand in it and came up with this:


void registerEvent(string event_name,T...)(T delegate() dg);


May be std.variant will help you. 
https://dlang.org/phobos/std_variant.html
You can bring the delegates to a common interface, hiding the 
differences in std.variant


rpc between Tasks of vibe.d

2016-10-28 Thread crimaniak via Digitalmars-d-learn

Hi All!

I will try to illustrate by code what exactly I have in mind:

// we have not shared class/struct with some interface.
class FooController
{
...
int foo1(int a, string b);
string foo2(Struct1 c);
...
}

// now we want to make a running task with an instance inside

auto controllerTask = runTask((){

  auto controller = new FooController();
  ReceiveCalls!FooController(controller);

});


// and call it from other tasks, like this

int result1 = Call!FooController(controllerTask).foo1(123, "abc");
string result2 = 
Call!FooController(controllerTask).foo2(Struct1(...));



Is there any interface generator for this? Or what can you 
suggest?


Thanks!



Re: thisExePath purity

2016-09-20 Thread crimaniak via Digitalmars-d-learn
On Tuesday, 20 September 2016 at 13:35:27 UTC, Steven 
Schveighoffer wrote:
Yes, but if your code does instantiate it, it is called, even 
if you don't ever call the function that calls it.
Yes, it's not ideal but better then just global variable and 
static block - it's called in any case, even if variable is not 
used at all.


Ideal solution will be something like attribute for static block 
leading to make it optional, so module will not be included if no 
usage of other symbols found. But I don't know way how to make it 
so template is used.


Note that if you don't import the module that contains the 
static ctor, it should be trimmed by the linker.
 Let's imagine linker can trim even imported module with static 
ctor, if we have something like:


immutable string executablePath;

@local shared static this()
{
import std.file : thisExePath;
executablePath = thisExePath();
}

and there is no references to executablePath. Here it would be 
useful, I think. Attribute @local (or @module? the name does not 
matter) mean this block used only to init other symbols in this 
module so it can be skipped if no references.



I would absolutely caution you from putting static this() 
inside any template. Unfortunately, due to the way D generates 
these static constructors, any module that uses staticMemoize, 
or *imports a module that uses it*, will be marked as having a 
static constructor, and will potentially create cycles.
 Please be more detail about cycles. Do you mean something like 
this? https://isocpp.org/wiki/faq/ctors#static-init-order




Re: thisExePath purity

2016-09-20 Thread crimaniak via Digitalmars-d-learn

On Tuesday, 20 September 2016 at 09:14:39 UTC, Marc Schütz wrote:

Have a look at `std.concurrency.initOnce`:
https://dlang.org/phobos/std_concurrency.html#.initOnce

But you will still need to use assumePure() for calling 
`thisExePath`, and it might do other things that are impure...


Yes, it's near but in this case I try to fix purity, so any 
variants of lazy initialization is not applicable here.


Re: thisExePath purity

2016-09-20 Thread crimaniak via Digitalmars-d-learn
On Tuesday, 20 September 2016 at 04:26:05 UTC, Jonathan M Davis 
wrote:
On Tuesday, September 20, 2016 04:17:21 crimaniak via 
Digitalmars-d-learn wrote:

 static shared immutable ReturnType!T value;


I would point out that immutable is implicitly shared, so 
there's no reason to put shared on an immutable variable. 
However, you _do_ want to put shared on a static constructor 
that initializes an immutable variable so that it's only run 
once for the program instead of once per thread (the compiler 
really should enforce that, but there's a longstanding bug that 
allows you to reinitialize an immutable variable by not putting 
shared on the static constructor and starting multiple threads).

 Ok, I got it. Thanks.


Re: thisExePath purity

2016-09-19 Thread crimaniak via Digitalmars-d-learn

Hi and thanks all!

On Tuesday, 20 September 2016 at 00:43:10 UTC, Jonathan M Davis 
wrote:



immutable string executablePath;

shared static this()
{
import std.file : thisExePath();
executablePath = thisExePath();
}


This code is good for my needs but I start to think about how to 
call thisExePath only if it is really used and come to this 
solution:


import std.traits: ReturnType, Parameters;

string staticMemoize(alias T, Parms = Parameters!T)() pure
{
struct Holder(alias T)
{
static shared immutable ReturnType!T value;
shared static this(){ value = T(Parms); }
}

return Holder!T.value;
}

unittest
{
import std.file : thisExePath;
assert(staticMemoize!thisExePath == thisExePath);
}

Something like this. Need to refine about input parameters, but I 
hope, idea is clear.
Unlike the function memoize from phobos staticMemoize really 
pure. And unlike proposed solution with ordinary variable 
staticMemoize is lazy, because no call - no instantiation.


https://dlang.org/library/std/functional/memoize.html




thisExePath purity

2016-09-19 Thread crimaniak via Digitalmars-d-learn

Hi!

Is there situations when output of thisExePath() can be different 
during runtime? If yes, what the reason?

If no, is this possible to mark it as pure in phobos?

https://dlang.org/library/std/file/this_exe_path.html


Compiling vibe.d application for Amazon ec2 instance

2016-09-11 Thread crimaniak via Digitalmars-d-learn

Hi all!

I made vibe-d application, and client give me already taken 
hosting for it on Amazon aws ec2, uname -a:
Linux ip-xxx-xx-xx-xx 4.4.11-23.53.amzn1.x86_64 #1 SMP Wed Jun 1 
22:22:50 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux


Compiled on my Ubuntu binary don't run because of different 
versions of libraries (on Amazon they older).


I can try to install dmd to ec2 instance but don't think this is 
good idea. I want to compile binary on my developing machine (may 
be in specific OS in VirtualBox).

How to resolve this problem by right way?

Can I get VirtualBox image of ec2 version of Linux and use it on 
my machine?
Can I compile all libraries used as static and make more 
independent binary?

Something else?



Re: Can anybody install DDT on Eclipse Neon or Mars?

2016-06-19 Thread crimaniak via Digitalmars-d-learn

On Saturday, 18 June 2016 at 16:46:26 UTC, Mark wrote:
I've spent may hours trying to do this in OSX. Everything goes 
fine from the marketplace window...until I restart Eclipse and 
find no files have been added?


Any words of consolation or advice will be greatly appreciated.



I have Eclipse
Version: Mars.2 Release (4.5.2)
Build id: 20160218-0600
with DDT installed, don't remember any problems, but this is 
under Ubuntu 14.04.


As I remember I didn't use Marketplace window, but follow 
instructions here: 
https://github.com/DDT-IDE/DDT/blob/latest/documentation/Installation.md#installation


Re: Missing Symbol Accessing Templated Function Through Interface

2016-03-08 Thread crimaniak via Digitalmars-d-learn

On Tuesday, 8 March 2016 at 11:50:32 UTC, Peter wrote:

Hi,

Can anyone explain to me what's causing the following code to 
generate a missing symbol error...


Relevant comment: https://issues.dlang.org/show_bug.cgi?id=8553#c1



Re: Does D optimize sqrt(2.0)?

2016-02-11 Thread crimaniak via Digitalmars-d-learn

On Thursday, 11 February 2016 at 07:41:55 UTC, Enjoys Math wrote:
If I just type out sqrt(2.0) in D, is that automatically made 
into a constant for me?


Thanks.


for DMD -O :

import std.math;

immutable foo = sqrt(2.0);

pure float precalculated()
{
return foo;
}

pure float not_precalculated()
{
return sqrt(2.0);
}


How to implement to!T(JSONValue)?

2016-01-31 Thread crimaniak via Digitalmars-d-learn

Hi!
 I need to read bad-formed json files in type-tolerant mode, and 
my idea is to make JSONValue-specific 'to' method which will 
convert it to target type if applicable, else throw exception. 
Like this:


import std.json;

unittest
{
JSONValue s="123";
JSONValue i=123;
JSONValue f=123.0f;
JSONValue a=[1,2,3];

float result;

result = s.to!float;
assert(result == 123.);

result = i.to!float;
assert(result == 123.);

result = f.to!float;
assert(result == 123.);

result = a.to!float; /// <-- exception
}

Naive approach doesn't works:

T to(T)(JSONValue value)
{
final switch(value.type)
{
case JSON_TYPE.ARRAY:
return value.array.to!T;
case JSON_TYPE.FALSE:
return false.to!T;
case JSON_TYPE.TRUE:
return true.to!T;
case JSON_TYPE.FLOAT:
return value.floating.to!T;
case JSON_TYPE.INTEGER:
return value.integer.to!T;
case JSON_TYPE.NULL:
return null.to!T;
case JSON_TYPE.OBJECT:
return value.object.to!T;
case JSON_TYPE.STRING:
return value.string.to!T;
case JSON_TYPE.UINTEGER:
return value.uinteger.to!T;
}
}

So my questions: is this possible to avoid explicit writing all 
specializations for every combination of JSON_TYPE/T required? 
How to resolve this task in right way?




Re: Balanced match with std.regex

2015-12-14 Thread crimaniak via Digitalmars-d-learn

On Tuesday, 15 December 2015 at 00:16:41 UTC, Jakob Ovrum wrote:

Is there a way to do balanced match with std.regex?


It's only possible with (?R) implemented: 
http://php.net/manual/en/regexp.reference.recursive.php

But there is no (?R) in D regex implementation.



Re: method has no return statement with switch

2015-11-07 Thread crimaniak via Digitalmars-d-learn

On Saturday, 7 November 2015 at 06:02:49 UTC, BBaz wrote:

On Saturday, 7 November 2015 at 00:21:57 UTC, crimaniak wrote:

[...]
url.Cache.UrlCache.doRequest has no return statement, but is 
expected to return a value of type string

[...]
public string doRealRequest(string url, Method method)



You posted the wrong code sample: your code shows doRealRequest 
but the message is about doRequest !


 Yes! It's just my inattention. Thanks!

p.s. Don't program at 3 am


method has no return statement with switch

2015-11-06 Thread crimaniak via Digitalmars-d-learn

Hi!

I have the error message:
source/url.cache.d(20,16): Error: function 
url.Cache.UrlCache.doRequest has no return statement, but is 
expected to return a value of type string


Inserting dummy return statement doesn't help. final switch / 
switch with default - no matter.


As I understand compiler must detect when end of function is 
unreachable (and in fact it detects it - see comment about return 
""; line) and do not try to check for return value. Is this my or 
compiler's error here?



dmd --version

DMD64 D Compiler v2.069.0
Copyright (c) 1999-2015 by Digital Mars written by Walter Bright


[code]
module url.Cache;

import std.conv;
import core.exception;
import mysql.d;
import std.digest.md;
import std.net.curl;

enum Method { GET="GET", POST="POST" }

class UrlCache
{
// ...
public string doRealRequest(string url, Method method)
{
final switch(method)
{
case Method.GET:
return std.net.curl.get!AutoProtocol(url).text;
case Method.POST:
return std.net.curl.post(url, []).text;
}
		// return ""; // produces 'statement is not reachable' warning, 
don't fix the problem

}
// ...  
}
[/code]



Re: method has no return statement with switch

2015-11-06 Thread crimaniak via Digitalmars-d-learn

On Saturday, 7 November 2015 at 00:27:02 UTC, Adam D. Ruppe wrote:

On Saturday, 7 November 2015 at 00:21:57 UTC, crimaniak wrote:
Inserting dummy return statement doesn't help. final switch / 
switch with default - no matter.



Try inserting assert(0); instead of a dummy return.


 Done, no difference.