Re: Global variable type does not match previous declaration

2017-12-14 Thread Nicholas Wilson via Digitalmars-d-learn

On Wednesday, 13 December 2017 at 21:39:40 UTC, Satoshi wrote:

On Wednesday, 13 December 2017 at 21:38:49 UTC, Satoshi wrote:

What means this error and how to solve it?

object.d-mixin-1072(1112): Error: Global variable type does 
not match previous declaration with same mangled name: 
_D10TypeInfo_m6__initZ


Actually, I'm working on OS with minimal D runtime and I'm 
unable to compile object.d


source code:
https://github.com/Rikarin/Trinix/blob/a42a6e1fb4b87374b3e5ad8b9be501b080655ccd/Kernel/object.d

Thanks


Compiling with
ldc2 -debuglib= -defaultlib= -code-model=kernel 
-disable-red-zone -w -wi -de -O3 -mattr=-sse -I../ 
-of=obj-amd64/object.d.o -c -deps=obj-amd64/object.d.o.o.dep 
object.d


Can you add -vv to the command line and post the relevant portion 
of the result (i.e. the portion that correlates to the symbol 
that gives the error)?  (You'll want to pipe the output to a file 
as it produces a lot of output.)


Re: Is there anyway to access LLVM's 128 bit int type for C from LDC?

2017-12-14 Thread Nicholas Wilson via Digitalmars-d-learn
On Thursday, 14 December 2017 at 19:47:53 UTC, Jack Stouffer 
wrote:

Clang has __int128. Is there anyway to use this with D with LDC?


Not really as a plain type, although there is effort to get 
[u]cent working. I could have sworn that mir was using InlineIR 
with it for multiplication. But InlineIR is the only way to get 
at it.


What operation do you need on it?




Re: Is there anyway to access LLVM's 128 bit int type for C from LDC?

2017-12-14 Thread Nicholas Wilson via Digitalmars-d-learn

On Friday, 15 December 2017 at 01:17:17 UTC, Jack Stouffer wrote:
On Thursday, 14 December 2017 at 23:33:34 UTC, Nicholas Wilson 
wrote:
On Thursday, 14 December 2017 at 19:47:53 UTC, Jack Stouffer 
wrote:
Clang has __int128. Is there anyway to use this with D with 
LDC?


Not really as a plain type, although there is effort to get 
[u]cent working. I could have sworn that mir was using 
InlineIR with it for multiplication. But InlineIR is the only 
way to get at it.


What operation do you need on it?


I'm looking to use it to store the coefficient in my precise 
decimal type when you need more than 9 significant digits.


I might just end up translating Boost's multiprecision lib to D 
if ucent is impossible.


See also 
https://github.com/d-gamedev-team/gfm/tree/master/integers/gfm/integers


Re: Inline assembly question

2017-11-12 Thread Nicholas Wilson via Digitalmars-d-learn
On Sunday, 12 November 2017 at 11:01:39 UTC, Dibyendu Majumdar 
wrote:

Hi,

I have recently started work on building a VM for Lua (actually 
a derivative of Lua) in X86-64 assembly. I am using the dynasm 
tool that is part of LuaJIT. I was wondering whether I could 
also write this in D's inline assembly perhaps, but there is 
one aspect that I am not sure how to do.


The assembly code uses static allocation of registers, but 
because of the differences in how registers are used in Win64 
versus Unix X64 - different registers are assigned depending on 
the architecture. dynasm makes this easy to do using macros; 
e.g. below.


|.if X64WIN
|.define CARG1, rcx // x64/WIN64 C call arguments.
|.define CARG2, rdx
|.define CARG3, r8
|.define CARG4, r9
|.else
|.define CARG1, rdi // x64/POSIX C call arguments.
|.define CARG2, rsi
|.define CARG3, rdx
|.define CARG4, rcx
|.endif

With above in place, the code can use the mnemonics to refer to 
the registers rather than the registers themselves. This allows 
the assembly code to be coded once for both architectures.


How would one do this in D inline assembly?

Thanks and Regards
Dibyendu


You could do it with a mixin, it would be rather ugly though. Not 
sure of another way off the top of my head.




Re: One liner alternatives for initing and pushing some values into array

2017-11-20 Thread Nicholas Wilson via Digitalmars-d-learn

On Monday, 20 November 2017 at 08:37:32 UTC, kerdemdemir wrote:

I need to init and push some values into a array something like:

//DMD64 D Compiler 2.072.2
import std.stdio;
import std.array;

void main()
{
bool a = true;
bool b = false;
bool c = false;

bool[] boolList;
auto boolListAppender = boolList.appender();
boolListAppender ~= [ a, b, c];
}

Live example : http://rextester.com/TJLIXU71426

My question is about

bool[] boolList;
auto boolListAppender = boolList.appender();
boolListAppender ~= [ a, b, c];


I could do the same in one line with C++:

bool boolList[] = { a, b, c };



Change the braces to brackets.

D alternative(at least my D alternative) seem long. Is there 
any better way for

initialing  and pushing values at the same time.

Erdem




Re: problem with multiwayMerge and chunkBy

2017-11-05 Thread Nicholas Wilson via Digitalmars-d-learn

On Sunday, 5 November 2017 at 22:47:10 UTC, Nicholas Wilson wrote:

f.multiwayMerge.chunks(128).joiner.chunkBy!(pred).writeln;

since it seems to be the iteration that stuff things up and 
this changes it.


If that doesn't work you could try rolling your own version of 
chunk with `take` and a static array.


Re: problem with multiwayMerge and chunkBy

2017-11-05 Thread Nicholas Wilson via Digitalmars-d-learn

On Sunday, 5 November 2017 at 13:32:57 UTC, Matthew Gamble wrote:
On Sunday, 5 November 2017 at 03:21:06 UTC, Nicholas Wilson 
wrote:
On Saturday, 4 November 2017 at 18:57:17 UTC, Matthew Gamble 
wrote:

[...]


It should, this looks like a bug somewhere, please file one at 
issues.dlang.org/ .


in the mean time

struct Replicate(T)
{
Tuple!(T, uint) e;
@property bool empty() { return e[1] == 0 ; }
@property auto front() {return e[0]; }
void popFront() { --e[1]; }
}

Replicate!T replicate(T)(Tuple!(T, uint) e)
{
return typeof(return)(e);
}

f.multiwayMerge.group!"a == b".map!(replicate).writeln;

Does the same thing provided your predicate is "a == b".



Thanks Nicholas.
I posted the bug as you suggested. My predicate is not quite a 
== b, otherwise I would never have needed chunkBy in the first 
place. But thanks, I'm pursuing a workaround.


Matt


One thing you might try is instead of using .array to eagerly 
evaluate the whole range, eagerly evaluate only a part (say 128 
elements) and .joiner them.


import std.range : chunks;

f.multiwayMerge.chunks(128).joiner.chunkBy!(pred).writeln;

since it seems to be the iteration that stuff things up and this 
changes it.


Re: problem with multiwayMerge and chunkBy

2017-11-04 Thread Nicholas Wilson via Digitalmars-d-learn
On Saturday, 4 November 2017 at 18:57:17 UTC, Matthew Gamble 
wrote:

Dear most helpful and appreciated D community,

I'm a non-pro academic biologist trying to code a modeler of 
transcription in D. I've run into a small roadblock. Any help 
would be greatly appreciated. I'm hoping someone can tell me 
why I get the following run-time error from this code. I've 
reduced it to something simple:


import std.algorithm;
import std.range;

auto d =[2,4,6,8];
auto e =[1,2,3,5,7];
auto f =[d,e];

writeln(f.multiwayMerge.chunkBy!"a == b");//error happens
writeln(f.multiwayMerge.array.chunkBy!"a == b");//no 
error, but there must be a better way!


My understanding is that chunkBy should be able to take an 
input range. Is that not true? I'm trying to get a merged 
sorted view of two sorted ranges followed by merging records 
based on a predicate without allocating memory or swapping the 
underlying values. Speed will be very important at the end of 
the day and sticking the ".array" in the middle kills me, given 
the size of the actual ranges.


It should, this looks like a bug somewhere, please file one at 
issues.dlang.org/ .


in the mean time

struct Replicate(T)
{
Tuple!(T, uint) e;
@property bool empty() { return e[1] == 0 ; }
@property auto front() {return e[0]; }
void popFront() { --e[1]; }
}

Replicate!T replicate(T)(Tuple!(T, uint) e)
{
return typeof(return)(e);
}

f.multiwayMerge.group!"a == b".map!(replicate).writeln;

Does the same thing provided your predicate is "a == b".


Re: Request Assistance Calling D from C++: weird visibility issue inside struct and namespace

2017-11-07 Thread Nicholas Wilson via Digitalmars-d-learn
On Wednesday, 8 November 2017 at 06:34:27 UTC, Andrew Edwards 
wrote:
I'm having a little bit of problem calling D code from C++ and 
would appreciate some assistance. First, given the following 
C++ program wich compiles, links, and runs without any problem:


Try using `nm` on the C++ object to find out what it thinks the 
mangling should be.

Check that against the mangling DMD produces.


Re: Cannot reduce an empty iterable w/o an explicit seed value

2017-11-09 Thread Nicholas Wilson via Digitalmars-d-learn

On Thursday, 9 November 2017 at 12:40:49 UTC, Vino wrote:

Hi All,

  Request your help, when i execute the below line of code i am 
getting an error message as "Cannot reduce an empty iterable 
w/o an explicit seed value" , The below lie of code will 
iterate several file system and will report the size of the 
folder (level 1) which is greater than 10GB.



Program:
auto coSizeDirList (string FFs, int SizeDir) {
float subdirTotal;
float subdirTotalGB;
Array!string Result;
	auto dFiles = Array!string ((dirEntries(FFs, 
SpanMode.shallow).filter!(a => a.isDir))[].map!(a => a.name));

foreach (d; parallel(dFiles[], 1)) {
	auto SdFiles = Array!float ((dirEntries(join(["?\\", d]), 
SpanMode.depth).filter!(a => a.isFile))[].map!(a => 
to!float(a.size)));

{
	subdirTotalGB = ((reduce!((a,b) => a + b)(SdFiles)) / 1024 / 
1024 / 1024);

}
 if (subdirTotalGB > SizeDir) {
Result.insertBack(d); 
Result.insertBack(to!string(subdirTotalGB));

}
}
return Result;
}

From,
Vino.B


The problem is
subdirTotalGB = ((reduce!((a,b) => a + b)(SdFiles)) / 1024 / 1024 
/ 1024);
with reduce you need to give it a seed (an initial value to start 
with).

See
https://dlang.org/phobos/std_algorithm_iteration.html#.reduce


int[] arr = [ 1, 2, 3, 4, 5 ];
// Sum all elements
auto sum = reduce!((a,b) => a + b)(0, arr);
writeln(sum); // 15

// Sum again, using a string predicate with "a" and "b"
sum = reduce!"a + b"(0, arr);
writeln(sum); // 15


To your actual use case, you can do:

foreach (d; parallel(dFiles[], 1)) {
float subdirTotalGB = dirEntries(join(["?\\", d]), 
SpanMode.depth)

.filter!(a => a.isFile))
.map!(a => to!float(a.size)))
.fold!((a, b) => a + b)(0) // Provide an explicit seed.

if (subdirTotalGB > SizeDir) {
Result.insertBack(d);
Result.insertBack(to!string(subdirTotalGB));
}
}




Re: Cannot reduce an empty iterable w/o an explicit seed value

2017-11-09 Thread Nicholas Wilson via Digitalmars-d-learn

On Thursday, 9 November 2017 at 12:40:49 UTC, Vino wrote:

Hi All,

  Request your help, when i execute the below line of code i am 
getting an error message as "Cannot reduce an empty iterable 
w/o an explicit seed value" , The below lie of code will 
iterate several file system and will report the size of the 
folder (level 1) which is greater than 10GB.


The reason you get this is because when evaluating an empty 
directory there are no files, so it is like you are trying to do

   [].sum

which can give no sensible result.



Re: check mountpoint status and send email on timeout/failure?

2017-12-11 Thread Nicholas Wilson via Digitalmars-d-learn

On Monday, 11 December 2017 at 10:50:17 UTC, biocyberman wrote:
For someone using NFS or some other remote filesystems, one may 
have experienced many times the nasty silent hang. For example, 
if I run `ls /mnt/remote/nfsmount`, and the remote NFS server 
is down while /mnt/remote/nfsmount was mounted, it will take 
very long time or forever for the `ls` command to return an 
error. Imagine if it were not `ls` but a data producing 
program, or user's home directly, it will be very inconvenient. 
Since I want to learn D, I want to write a program that does:
1. Check a path and to see it is a mount point. If it is not a 
mount point, try to mount it, and send an email. If it is a 
mount point, go to step 2.
2. If it is amount point, but fails to response after a certain 
time period (e.g 5 seconds), then send an email.


I know nothing about how to write it in D, or which library to 
use. So, some help please.


You will need to use the system APIs for that I assume, nothing 
special for that. Just search for how to do what you want, 
probably in C, and translate that to D.


As for the email, not so sure.


Re: Removing some of the elements from vibe.core.concurrency.Future[] futurelist

2017-10-28 Thread Nicholas Wilson via Digitalmars-d-learn

On Saturday, 28 October 2017 at 13:51:42 UTC, kerdemdemir wrote:

I am trying to make non blocking web requests to a web service.

vibe.core.concurrency.Future!(UserData)[] futurelist;

// I will make http requests in for loop and push them to 
futureList

foreach( elem; elemList )
{
// In makeWebRequest I make the httprequest, parse json 
and push to my UserData
auto future = vibe.core.concurrency.async( 
 );

futurelist ~= future;
}


// I want to do call ProcessResponceData for each future which 
is ready.

while ( futurelist.length > 0 )
{
futurelist.filter!(a => a.ready()).each!(a=> 
ProcessResponceData(a.getResult()));


//!  Here is my problem
//!  I want to remove the futures which are already 
processed.

futurelist = futurelist.filter!(a => !a.ready()).array;  
sleep(10.msecs);

}

I am having troubles while trying to remove the future which I 
already processed.


futurelist = futurelist.filter!(a => !a.ready()).array;	 
results with:


/usr/local/bin/../import/std/array.d(2716,20): Error: can't 
have array of nothrow @safe void()
/usr/local/bin/../import/std/array.d(2782,46): Error: can't 
have array of inout nothrow @safe void()
/usr/local/bin/../import/std/array.d(3158,1): Error: template 
instance std.array.Appender!(Future!(UserData)[]) error 
instantiating
/usr/local/bin/../import/std/array.d(133,32):
instantiated from here: appender!(Future!(UserData)[])


futurelist = futurelist.filter!(a => !a.ready()); results with:

 Error: cannot implicitly convert expression 
(filter(futurelist)) of type FilterResult!(__lambda5, 
Future!(UserData)[]) to Future!(AnalyzeData)[]


Do you have any suggestion or workaround for my case?
What lesson I should learn from this case? Do you guys have any 
idea why I am getting those compile errors?



Thanks
Erdem


I'd take a look at why the error message says
`Future!(UserData)[]) to Future!(AnalyzeData)[]`
is AnalyzeData  the type returned by ProcessResponceData?

Alternatively you could use a singly linked list and splice out 
elements that pass the filter predicate. I think you'd have to 
roll your own though.







Re: Removing some of the elements from vibe.core.concurrency.Future[] futurelist

2017-10-28 Thread Nicholas Wilson via Digitalmars-d-learn

On Sunday, 29 October 2017 at 01:44:37 UTC, Nicholas Wilson wrote:
Alternatively you could use a singly linked list and splice out 
elements that pass the filter predicate. I think you'd have to 
roll your own though.


Something like https://github.com/dlang/phobos/pull/5821


Why are deprecated aliases considered equal for resolution?

2018-05-11 Thread Nicholas Wilson via Digitalmars-d-learn

-
module a;

struct foo {}

deprecated alias bar = foo;

--
module b;
struct bar {};


---
module c;

import a;
import b;

void baz(bar b) {}

Error: `a.bar` at source/a.d(5,1) conflicts with `b.bar` at 
.b.d(2,1)


I would have thought the undeprecated alias would have been used.


Re: Efficient idiom for fastest code

2018-05-22 Thread Nicholas Wilson via Digitalmars-d-learn
On Wednesday, 23 May 2018 at 02:24:08 UTC, IntegratedDimensions 
wrote:


Many times in expensive loops one must make decisions. 
Decisions must be determined and the determination costs.


for(int i = 0; i < N; i++)
{
if(decision(i)) A; else B;
}

the if statement costs N times the cycle cost.

In some cases the decision holds for continuous ranges. For 
some 0 <= n <= N the decision is constant, but n is 
arbitrary(determined by unknown factors at compile time).


One can speed up the routine by using something akin to a 
simplified strategy pattern where one uses 
functions/delegates/lambdas to code a faster version without 
the test:



for(int i = 0; i < N; i++)
{
d = (){ if(decision(i)) A; else d = () { B; };
d();
}



assuming you meant

auto d = (int i){ if(decision(i)) A; else d = (int i) { B; };};
for(int i = 0; i < N; i++)
{
d(i);
}




this code basically reduces to

for(int i = 0; i < N; i++)
{
B;
}

Once the decision fails, which we assume once it fails it 
always fails in this particular case.


Therefor, once the decision fails it kicks in the "faster" 
code. Suppose decision is very slow.


The cycle cost is then n times rather than N times.

In general, such techniques can be used to speed up code, 
sometimes significantly, but are difficult to implement using a 
standard pattern and for more complex decision functions.



Does anyone see any way to use some some of D's power to help 
simplify such things but not using something like a strategy 
pattern or complexifying the overall design(using advanced 
techniques such as templates, mixins is not making the code 
more complex).


If decision is pure, consider using static foreach 
(iota(N).map!decision) { ... }to unroll it at compile time. even 
if it isn't the compiler may still be able to factor out parts of 
repeated calls to decision, look at the assembly/IR to confirm 
this.


Otherwise PROFILE! (and use profile guided optimisation! this 
implies using a compiler other than DMD which if you care about 
performance you should be doing anyway)


Blindly trying to optimise is just as likely to hurt performance.
in particular don't underestimate the branch predictor. Even if 
decision is complex, if there is a pattern in evaluating 
iota(n).map!decision the branch predictor will pick up on it.


In terms of exploiting knowledge of decision a priori that the 
compiler somehow lacks you really don't have much option but to 
do it yourself.





Re: Efficient idiom for fastest code

2018-05-23 Thread Nicholas Wilson via Digitalmars-d-learn
On Wednesday, 23 May 2018 at 03:12:52 UTC, IntegratedDimensions 
wrote:

I knew someone was going to say that and I forgot to say DON'T!

Saying to profile when I clearly said these ARE cases where 
they are slow is just moronic. Please don't use default answers 
to arguments.


This was a general question about cases on how to attack a 
problem WHEN profiling says I need to optimize. Your SO 101 
answer sucks! Sorry!


To prove to you that your answer is invalid:

I profile my code, it says that it is very slow and shows that 
it is do to the decision checking... I then I have to come here 
and write up a post trying to explain how to solve the problem. 
I then get a post telling me I should profile. I then respond I 
did profile and that this is my problem. A lot of wasted energy 
when it is better to know a general attack strategy. Yes, some 
of us can judge if code is needed to be optimized before 
profiling. It is not difficult. Giving a generic answer that 
always does not apply and is obvious to anyone trying to do 
optimization is not helpful. Everyone today pretty must does 
not even optimize code anymore... this isn't 1979. It's not ok 
to keep repeating the same mantra. I guess we should turn this 
in to a meme?


The reason I'm getting on to you is that the "profile before 
optimization" sounds a bit grade school, specially since I 
wasn't talking anything about profiling but a general 
programming pattern speed up code, which is always valid but 
not always useful(and hence that is when profiling comes in).


I'm going to ignore the tone of your response, but I am going to 
say that responding like that isn't going to get you very far. 
Don't expect others to do likewise.


Assuming that your decision function is indeed the bottleneck, 
you'll see I did actually provide some hints as to how to 
optimise the case where decision is pure. even if you can't 
convince the compiler to inline and expression combine, as in the 
case for the other answer, you can memoize it (look in 
std.functional).


One of the great things about D is that you can force lots of 
computation to happen at compile time, so in the case where 
decision is impure, factoring it into pure and impure parts and 
`enum x = pureFunc(args);`ing the part that can be can make a 
large difference if you can't convince the optimiser to do it for 
you.


If you still can't do that consider Jitting it  
(https://github.com/ldc-developers/druntime/blob/e3bfc5fb780967f1b6807039ff00b2ccaf4b03d9/src/ldc/attributes.d#L78 ) with `-enable-dynamic-compile` or running the loop in parallel with std.parallelism.


Re: Translate C/C++ patern: return a pointer

2018-05-24 Thread Nicholas Wilson via Digitalmars-d-learn

On Thursday, 24 May 2018 at 08:16:30 UTC, biocyberman wrote:
Some C and C++ projects I am working on use pointers and 
references extensively: to pass as function arguments, and to 
return from a function. For function argument I would use 
`ref`, but for return types, I can't use `ref` and can't return 
a pointer. What should be the proper way to handle this? Do I 
have to change function signature (i.e. return type) For 
example, the following function:


```
//C++ version, from:
https://github.com/bioslaD/fastp/blob/orig/src/read.cpp#L69

Read* Read::reverseComplement(){
Sequence seq = ~mSeq;
string qual;
qual.assign(mQuality.rbegin(), mQuality.rend());
string strand = (mStrand=="+") ? "-" : "+";
return new Read(mName, seq, strand, qual);
}

// D version:
Read reverseComplement(){
Sequence seq = ~mSeq;
dchar[] qual = cast(dchar[])mQuality.dup;
reverse(qual);
string strand = (mStrand=="+") ? "-" : "+";
Read newRead = new Read(mName, seq, strand, 
cast(string)qual);
// return  does not work: returning `& newRead` 
escapes a reference to local variable newRead

return newRead;

  }


```
Let's not focus on the function body, I don't know how to 
handle the return type in cases like this for the D version.


it looks like Read is a D class? in which case it already returns 
by reference.
If you make Read a struct then all you need do is change the 
function signature from

Read reverseComplement()
to
Read* reverseComplement()

about the function body
use mQuality.dup.representation.reverse;


dchar[] qual = cast(dchar[])mQuality.dup;
reverse(qual);
mQuality = cast(string)qual;


does not do what you want it to do.


Re: scope(success) lowered to try-catch ?

2018-06-17 Thread Nicholas Wilson via Digitalmars-d-learn

On Sunday, 17 June 2018 at 10:58:29 UTC, Cauterite wrote:

Hello,
I'm not sure whether I'm missing something obvious here, but is 
there a reason for scope(success) being lowered to a try-catch 
statement?
I would have expected only scope(exit) and scope(failure) to 
actually interact with exception handling, while scope(success) 
simply places code on the path of normal control flow.


Example (windows x32):

---

// main.d
void main() {
scope(success) {}
}


dmd -betterC main.d

Error: Cannot use try-catch statements with -betterC

---

Regardless of whether -betterC is used, you can see in the 
disassembly that having a scope(success) anywhere in the 
function causes the SEH prologue to be emitted in the code.


Is there a reason scope(success) needs to set up for exception 
handling?

Or is this a bug / potential enhancement ?


I suspect scope(success) is lowered because scope(exit) and 
scope(failure)
are, and that would result in a simpler (compiler) implementation 
of it.


does adding nothrow to main fix it? For dcompute I specifically 
allow scope(exit|success) because there will never be any 
exceptions _at all_.


If not, please do submit an issue. Also a better error message 
should be given.


Re: using wkhtmltopdf with D

2018-05-28 Thread Nicholas Wilson via Digitalmars-d-learn

On Tuesday, 29 May 2018 at 01:43:17 UTC, Mike Parker wrote:
In pdf.h, that CAPI macro is used in every function 
declaration. That means that on Windows, all of the functions 
have the __stdcall calling convention (which, in D, would be 
extern(Windows)) and the standard cdecl calling convetion on 
other platforms (extern(C) in D).


In the D binding, we see that all of the functions are declared 
as extern(C) (line 4 of pdf.d). That means on Windows, the 
calling convention on the D side is incorrect.


What you need to do is to change that extern(C) delcaration in 
pdf.d to extern(System). This will translate to extern(Windows) 
on Windows and extern(C) elsewhere to match the C headers.


this is represented by extern(System) in D which does the 
conditional

extern(C) vs extern(Windows) for you.




Re: using wkhtmltopdf with D

2018-05-28 Thread Nicholas Wilson via Digitalmars-d-learn

On Tuesday, 29 May 2018 at 04:49:34 UTC, Nicholas Wilson wrote:

On Tuesday, 29 May 2018 at 01:43:17 UTC, Mike Parker wrote:
In pdf.h, that CAPI macro is used in every function 
declaration. That means that on Windows, all of the functions 
have the __stdcall calling convention (which, in D, would be 
extern(Windows)) and the standard cdecl calling convetion on 
other platforms (extern(C) in D).


In the D binding, we see that all of the functions are 
declared as extern(C) (line 4 of pdf.d). That means on 
Windows, the calling convention on the D side is incorrect.


What you need to do is to change that extern(C) delcaration in 
pdf.d to extern(System). This will translate to 
extern(Windows) on Windows and extern(C) elsewhere to match 
the C headers.


this is represented by extern(System) in D which does the 
conditional

extern(C) vs extern(Windows) for you.


Apparently I can't read.


Re: using wkhtmltopdf with D

2018-05-27 Thread Nicholas Wilson via Digitalmars-d-learn

On Monday, 28 May 2018 at 01:28:10 UTC, Dr.No wrote:
I'm trying to use wkhtmltopdf[1] with D. I converted this 
header[2] with little modification using htod tool which 
resulted in this[3].

The libray is passed to link using:

pragma(lib, "wkhtmltox.lib");
(that file is in wkhtmltopdf\lib folder)


and the module imported with:
import pdf;

but it crashes right upon the start with a SEGFAULT:

void main()
{

wkhtmltopdf_global_settings * gs;
wkhtmltopdf_object_settings * os;
wkhtmltopdf_converter * c;

/* Init wkhtmltopdf in graphics less mode */
wkhtmltopdf_init(0);
}

toolset I'm using:

DUB version 1.8.1, built on Apr 29 2018
LDC - the LLVM D compiler (1.9.0):
  based on DMD v2.079.1 and LLVM 5.0.1
  built with LDC - the LLVM D compiler (1.9.0)
  Default target: i686-pc-windows-msvc
  Host CPU: skylake
  http://dlang.org - http://wiki.dlang.org/LDC

What's likely the reason of the crash? mismatch between D and C 
memory alignment?


[1]: https://wkhtmltopdf.org/index.html
[2]: 
https://github.com/clowder/wkhtmltopdf/blob/master/src/lib/pdf.h

[3]: https://pastebin.com/SrtDUhPf


You're missing const on a couple of the pointer parameters, but 
if it segfaults on calling a function then my question is: is 
wkhtmltox.lib a library that was generated to link to a dynamic 
library (is there an associated .dll)? If so you need to ensure 
that it is loaded and the function pointers are initialised.


Re: Conditionally set nothrow: for a block of code.

2018-05-28 Thread Nicholas Wilson via Digitalmars-d-learn

On Thursday, 24 May 2018 at 18:51:31 UTC, Mike Franklin wrote:
I'm trying to find a way to declare a block of code `nothrow:` 
when compiling with -betterC, but not `nothrow` when not 
compiling with -betterC.


[...]


Not one now but, DIP 1012 will allow this as nothrow will become 
a regular enum attribute.




Re: Debugging compile time memory usage

2018-06-25 Thread Nicholas Wilson via Digitalmars-d-learn

On Sunday, 24 June 2018 at 14:16:26 UTC, Kamil Koczurek wrote:
I recently wrote a brainfuck compiler in D, which loads the BF 
source at compile time, performs some (simple) optimizations, 
translates everything to D and puts it into the source code 
with a mixin.


I did manage to get some pretty good performance, but for some 
programs in brainfuck I have to use LDC instead of DMD because 
the latter runs out of memory. Is there a way for me to 
optimize my code in such a way that DMD will be able to compile 
it?


D code: https://pastebin.com/fg1bqwnd
BF program that works: 
https://github.com/erikdubbelboer/brainfuck-jit/blob/master/mandelbrot.bf
BF program that makes DMD crash: 
https://github.com/fabianishere/brainfuck/blob/master/examples/hanoi.bf


After putting BF code in code.bf and D in main.d, I compile it 
with the following command: dmd main.d -J./


Error msg: unable to fork: Cannot allocate memory
DMD version: DMD64 D Compiler v2.080.0-dirty


If you were able to compile it with LDC and not DMD, then that is 
most likely due to the LDC executable being 64-bit (limited to 
available system RAM+swaps) and the DMD executable being 32-bit 
(limited to 4GB).


If you want to use DMD, build a 64-bit version yourself and 
complain on general that the releases are not 64-bit.


Re: DerelictVorbis and string pointer

2018-06-23 Thread Nicholas Wilson via Digitalmars-d-learn

On Sunday, 24 June 2018 at 01:43:41 UTC, ANtlord wrote:

On Sunday, 24 June 2018 at 01:26:48 UTC, ANtlord wrote:


Actually I get it worked replacing `string filepath2` by 
`char[] filepath2` but filepath is string still and it works 
correctly.


It doesn't work


Vorbis is a C library, so you need to null terminate your string 
using toStringz. The reason why the one from the command line 
works is because it is already null terminate.


Re: Empty UDA for classes not allowed?

2017-10-27 Thread Nicholas Wilson via Digitalmars-d-learn

On Thursday, 26 October 2017 at 15:09:48 UTC, bauss wrote:

Why is it not allowed to have empty UDAs for classes?

Let's say we have an UDA like this:
struct Exclude { }

Then we want to put it on a class like:

@Exclude class Foo
{
...
}

This will fail with the following error:
Error: type Exclude has no value

But on everything else we can place an empty UDA like that ex. 
on a function:


This is okay:

@Exclude void foo()
{
...
}

Can someone explain to me why it's not possible with classes?


FWIW all parameterless UDA in LDC use a struct literal e.g.
https://github.com/ldc-developers/druntime/blob/ldc/src/ldc/attributes.d#L237


Re: opCast fails when this is null.

2017-10-28 Thread Nicholas Wilson via Digitalmars-d-learn

On Saturday, 28 October 2017 at 13:24:49 UTC, Mike Wey wrote:
The following code runs correctly when compiled with ldc 
(1.4.0) but fails with an assert error when compiled with dmd 
(2.076 and ldc 1.2.0)



```
class A
{

}

class B
{
T opCast(T)()
{
return this;
}
}

void main()
{
A a = null;
B b = null;

auto c = cast(Object)a;
	auto d = cast(Object)b; // Fails with: 
core.exception.AssertError@test.d(8): null this

}
```

How would you write an opCast that would handle this case 
correctly?


Testing if this is null at the start of the opCast doesn't help 
since the assert is thrown before that happens.
Making the opCast static leaves us without access to this, 
which would be needed in my use case.
We can't relay on ufcs since the rewrite to opCast doesn't 
happen when it's not a member function.


As Basile mentioned, this is compiler sticking checks in behind 
your back.
The reason it works on new LDC is because #6982 was cherry picked 
to LDC (1.3?) before it was merged into dmd (not sure what 
version, I though it was 2.076, but it might have been one of the 
betas of 2.077) because I needed it for DCompute to build without 
-release.


The only course is to use recent compilers.


Re: opCast fails when this is null.

2017-10-28 Thread Nicholas Wilson via Digitalmars-d-learn
On Saturday, 28 October 2017 at 14:19:01 UTC, Nicholas Wilson 
wrote:
As Basile mentioned, this is compiler sticking checks in behind 
your back.
The reason it works on new LDC is because #6982 was cherry 
picked to LDC (1.3?) before it was merged into dmd (not sure 
what version, I though it was 2.076, but it might have been one 
of the betas of 2.077) because I needed it for DCompute to 
build without -release.


The only course is to use recent compilers.


Erm, 2.077 is not a thing yet. Does it work with 2.076.1?


Re: structs inheriting from and implementing interfaces

2017-12-29 Thread Nicholas Wilson via Digitalmars-d-learn

On Friday, 29 December 2017 at 12:03:59 UTC, Mike Franklin wrote:

In C#, structs can inherit from and implement interfaces.


using System;

interface IPrint
{
void Print();
}

struct MyStruct : IPrint
{
public void Print()
{
Console.WriteLine(ToString());
}
}

public class Program
{
public static void Main()
{
MyStruct s = new MyStruct();
s.Print();
}
}

https://dotnetfiddle.net/lpXR1O

But in D it doesn't appear possible.

import std.stdio;

interface IPrint
{
void print();
}

// Error: base classes are not allowed for struct, did you mean 
;?
struct MyStruct : IPrint   // Error: base classes are not 
allowed for struct, did you mean ;?

{
void print()
{
writeln("MyStruct");
}
}

void main()
{
MyStruct s;
s.Print();
}

https://run.dlang.io/is/j4xwla

Is that simply because it hasn't been implemented or suggested 
yet for D, or was there a deliberate design decision?


Thanks for your insight,

Mike


The problem is that interfaces are a runtime thing (e.g. you can 
cast a class to an interface)
structs implement compile time interfaces via template duck 
typing (usually enforced via an if()).
you could probably write a wrapper that introspected an interface 
and enforced that all members were implemented.


Re: -L--demangle=dlang doesn't work

2018-01-05 Thread Nicholas Wilson via Digitalmars-d-learn

On Saturday, 6 January 2018 at 05:44:28 UTC, Venkat wrote:
Why does gcc say "unknown demangling style `dlang'" ? Do I need 
GDC for demangling to work ?



85198AB7DE24894B5F742FBD5/libvibe-d_data.a 
/home/venkat/.dub/packages/vibe-d-0.8.2/vibe-d/utils/.dub/build/library-unittest-linux.posix-x86_64-dmd_2077-B9AE30DD34FDC5ADDE81E208F10DF014/libvibe-d_utils.a -L--no-as-needed -L--demangle=dlang -L-lsqlite3 -L-levent_pthreads -L-levent -L-lssl -L-lcrypto -L-ldl -g

/usr/bin/ld: unknown demangling style `dlang'
collect2: error: ld returned 1 exit status
Error: linker exited with status 1
FAIL 
.dub/build/webmarx-test-application-unittest-linux.posix-x86_64-dmd_2077-C5DB1ABAED0A1191C5B2ACAFDC70EAC6/ webmarx-test-application executable

dmd failed with exit code 1.
Full exception: 
object.Exception@source/dub/compilers/compiler.d(115): dmd 
failed with exit code 1.


I'm not familiar with that flag maybe you have to register 
ddmangle with it? But failing all else you can pipe the output 
through ddmangle.


Re: Class instance memory overhead lower than 3 words?

2018-01-24 Thread Nicholas Wilson via Digitalmars-d-learn

On Wednesday, 24 January 2018 at 21:48:21 UTC, Nordlöw wrote:
Why is the memory overhead for a class instance as high as 3 
words (24 bytes on 64-bit systems? I find that annoyingly much 
for my knowledge database application. I'm aware of 
extern(C++), having one word overhead, but such 
extern(C++)-classes cannot use all of D; I get compilation 
errors such as


node.d(99,25): Error: Internal Compiler Error: type 
`inout(Edge)[]` can not be mapped to C++


One pointer for the vtbl, one for the monitor, not sure what the 
other one is.


C++ classes have one pointer for the vtbl at offset of -1 
size_t.sizeof


Declaring that particular method as extern(D) will fix that 
problem.


Re: Class instance memory overhead lower than 3 words?

2018-01-24 Thread Nicholas Wilson via Digitalmars-d-learn

On Wednesday, 24 January 2018 at 22:27:40 UTC, Nordlöw wrote:

On Wednesday, 24 January 2018 at 21:47:26 UTC, H. S. Teoh wrote:
On Wed, Jan 24, 2018 at 09:48:21PM +, Nordlöw via 
Digitalmars-d-learn wrote:
Why is the memory overhead for a class instance as high as 3 
words (24 bytes on 64-bit systems? I find that annoyingly 
much for my knowledge database application.

[...]

There's been an attempt to get rid of the Monitor field, which 
takes up one word, but it didn't seem to have gone anywhere 
the last time it was discussed.  I believe originally it was 
always initialized, but lately it seems to have been changed 
to be lazily initialized, so at least you'll only incur the 
computational cost if you actually use it. Nevertheless, the 
field itself is still there.



T


Can I use `*(cast(size_t*)__monitor)` for storing my own 
stuff in a class instance `c` if I never use monitors? :)


Maybe, the runtime when destroying that class might think the 
monitor is set and try and destroy the mutex it thinks is where 
the pointer points to.


BTW: the documentation on the concept of monitors is kind of 
sparse here


https://dlang.org/spec/class.html#class_properties

What is the `__monitor` property used for? Something with 
synchronized member functions?


It is used for
```
MyClass mc;
synchronized(mc) // <-
{
...
}
```
and I believe synchronized member functions and member functions 
of `synchronized class` (which are the same thing really).


The __monitor field points to a mutex object which is managed by 
the runtime.


Re: __gshared as part of alias

2018-01-17 Thread Nicholas Wilson via Digitalmars-d-learn
On Wednesday, 17 January 2018 at 07:53:24 UTC, Jonathan M Davis 
wrote:
I don't know what you're doing, and maybe __gshared is the 
appropriate solution for what you're trying to do, but in 
general, if you're not trying to bind to a C global variable, 
you should be using shared, and using __gshared is risking bugs 
precisely because it is not considered part of the type and 
does not prevent you from using it a thread-local context. The 
compiler will treat it as thread-local, risking subtle bugs 
that shared would catch.


- Jonathan M Davis


I was under the impression that with shared you have to either
a) atomically load it or
b) cast away shared before loading it.

As explained in 
https://github.com/ldc-developers/druntime/pull/114#discussion_r161472745 that would very much add boilerplate to its most frequent use case.


Re: __gshared as part of alias

2018-01-16 Thread Nicholas Wilson via Digitalmars-d-learn
On Wednesday, 17 January 2018 at 02:37:07 UTC, Steven 
Schveighoffer wrote:

On 1/11/18 11:25 PM, Nicholas Wilson wrote:

Is there a way to make __gshared part of an alias?


No, __gshared is a storage class, not a type constructor, so it 
has no meaning as part of a type:


__gshared int x;
int y;

static assert(is(typeof(x) == typeof(y)));


as in

enum AddrSpace : uint
{
     Private  = 0,
     Global   = 1,
     Shared   = 2,
     Constant = 3,
     Generic  = 4,
}

struct Variable(AddrSpace as, T)
{
     T val;
     alias val this;
}
alias Global(T)   = __gshared Variable!(AddrSpace.Global,   T);


dmd famously doesn't complain about attributes that do nothing, 
as in this case.


-Steve


I kluged this into place in LDC 
https://github.com/ldc-developers/ldc/pull/2509/commits/7cf6f417f95a5bffa4b18f2d8b132ca8f0e900d3#diff-33d7d08455db33f1182e3936fd2ba3f9R896


Re: C++ function mangling Linux GCC

2018-01-17 Thread Nicholas Wilson via Digitalmars-d-learn

On Thursday, 18 January 2018 at 04:16:18 UTC, Laeeth Isharc wrote:
Am I missing something, or should extern(C++) just work for 
binding to gcc C++ on Linux.  It works fine for primitives but 
fails for pointer type arguments.  Extern "C" works fine.


Does D know how to mangle function names based on pointer 
types? I have created matching types on both sides.


Though I am using typedefs.  Eg struct Foo_; typedef struct 
Foo_ Foo; and on D side struct Foo {}


Could that be why?



Yes. C++'s typedefs and using are just like D's alias. The 
underlying type is used in the mangling.


What the best way to see the types of library file function 
arguments for a libfoo.a file on Linux?   Sorry for the dumb 
question.




nm libfoo.a | c++filt ?
or https://demangler.com



Re: String Type Usage. String vs DString vs WString

2018-01-14 Thread Nicholas Wilson via Digitalmars-d-learn

On Monday, 15 January 2018 at 02:05:32 UTC, Chris P wrote:

Hello,

I'm extremely new to D and have a quick question regarding 
common practice when using strings. Is usage of one type over 
the others encouraged? When using 'string' it appears there is 
a length mismatch between the string length and the char array 
if large Unicode characters are used. So I figured I'd ask.


Thanks in advance,

Chris P - Tampa


 string == immutable( char)[], char == utf8
wstring == immutable(wchar)[], char == utf16
dstring == immutable(dchar)[], char == utf32

Unless you are dealing with windows, in which case you way need 
to consider using wstring, there is very little reason to use 
anything but string.


N.B. when you iterate over a string there are a number of 
different "flavours" (for want of a better term) you can iterate 
over, bytes, unicode codepoints and graphemes ( I'm possible 
forgetting some). have a look in std.uni and related modules. 
Iteration in Phobos defaults to coepoints I think.


TLDR use string.



__gshared as part of alias

2018-01-11 Thread Nicholas Wilson via Digitalmars-d-learn

Is there a way to make __gshared part of an alias?

as in

enum AddrSpace : uint
{
Private  = 0,
Global   = 1,
Shared   = 2,
Constant = 3,
Generic  = 4,
}

struct Variable(AddrSpace as, T)
{
T val;
alias val this;
}
alias Global(T)   = __gshared Variable!(AddrSpace.Global,   T);

Global!float bar1; // <- still thread local


Re: union/toString: crash/segfault: What's happening here?

2018-01-11 Thread Nicholas Wilson via Digitalmars-d-learn

On Friday, 12 January 2018 at 00:54:03 UTC, kdevel wrote:

crash.d
```
import std.stdio;

union U {
   float f;
   int i;
   string toString ()
   {
  string s;
  return s;
   }
}

void main ()
{
   U u;
   writeln (u);
}
```

$ dmd crash.d
$ ./crash



because you don't initialise `s` in


   string toString ()
   {
  string s;
  return s;
   }


so it defaults to `string s = null;` thus giving a segfault.

try `string s = "";` instead.


Re: parallelism

2018-01-27 Thread Nicholas Wilson via Digitalmars-d-learn
On Saturday, 27 January 2018 at 10:28:10 UTC, Arun Chandrasekaran 
wrote:

```
import std.parallelism;
auto pool = new TaskPool(options.threadCount);
foreach (_; 0 .. options.iterationCount) {
switch (options.operation) {
static foreach(e; EnumMembers!Operation) {
case e:
 pool.put(task!e(options));
 break;
}
pool.finish();
```


Does that do the trick?




Re: Vibe.d rest & web service?

2018-02-07 Thread Nicholas Wilson via Digitalmars-d-learn

On Wednesday, 7 February 2018 at 18:38:15 UTC, Seb wrote:

How about using the normal Vibe.d Web Service?



Stupid question: whats the difference?


An example from my WIP project vibe-by-example project:

https://github.com/wilzbach/vibe-d-by-example/blob/master/web/service.d


I also have a fork of vibe.web.web that adds additional 
convenience features to Vibe.d:


https://github.com/teamhackback/hb-web


(I have been struggling to get most of them merged upstream - 
https://github.com/vibe-d/vibe.d/pulls/wilzbach)





Re: Vibe.d rest & web service?

2018-02-07 Thread Nicholas Wilson via Digitalmars-d-learn
On Wednesday, 7 February 2018 at 17:57:09 UTC, Jesse Phillips 
wrote:
On Wednesday, 7 February 2018 at 17:04:13 UTC, Nicholas Wilson 
wrote:
Is it possible to have some urls routed to serve content and 
some to receive JSON in the same class?


This seems unlikely to me, the function signature doesn't 
provide a way to distinguish between REST and not.


I'm also not sure it is necessary, you can certainly have 
multiple class which provide REST and Web endpoints. You can 
even dynamically build routes within a route.


Hmm, this might be one of the few use cases for nested classes. 
But is would still require some routing trickery.


Debugging bad requests with vibe

2018-02-08 Thread Nicholas Wilson via Digitalmars-d-learn
I have set up a vibe.d rest interface (on a server) and have a 
client on my machine.


struct Observation
{
string desc;
DateTime time;
}

interface Obsever
{
@property void observe(Observation ra);
}

void main()
{
auto test = Observation("a duck", 
cast(DateTime)Clock.currTime(UTC()));


auto client = new RestInterfaceClient! 
Obsever("http://example.com/observation;);

client. observe = test; // 400
}

I' pretty sure the url is correct because other ones give 404.

Is there a way I can see/log what requests are being made? I can 
change both the client and server.




Re: Debugging bad requests with vibe

2018-02-08 Thread Nicholas Wilson via Digitalmars-d-learn
On Thursday, 8 February 2018 at 17:09:44 UTC, Nicholas Wilson 
wrote:
I have set up a vibe.d rest interface (on a server) and have a 
client on my machine.


struct Observation
{
string desc;
DateTime time;
}

interface Obsever
{
@property void observe(Observation ra);
}

void main()
{
auto test = Observation("a duck", 
cast(DateTime)Clock.currTime(UTC()));


auto client = new RestInterfaceClient! 
Obsever("http://example.com/observation;);

client. observe = test; // 400
}

I' pretty sure the url is correct because other ones give 404.

Is there a way I can see/log what requests are being made? I 
can change both the client and server.


Never mind, it was because I was accidentally shadowing that path 
with a get on the server.


Re: Vibe.d rest & web service?

2018-02-08 Thread Nicholas Wilson via Digitalmars-d-learn
On Wednesday, 7 February 2018 at 18:47:05 UTC, Steven 
Schveighoffer wrote:

Yes you can, but it's not pretty.

interface MyInterface
{
   void postGiveMeData(SomeData d);
}

class MyInterfaceImpl : MyInterface
{
   void postGiveMeData(SomeData d) { ... }
   void getPage() { ... }
   void index() { ... }
}

auto myI = new MyInterfaceImpl;
router.registerRestInterface(myI);
router.get("/route/to/getPage", );
router.get("/route/to/index", );

This worked for me, but note that my "non-rest" function was 
static, so I didn't need to worry about instances. I'm not sure 
if the above works exactly right for you.


However, I would recommend actually not doing this for your 
purpose. My case was different -- I still wanted routes that 
were REST routes, but I wanted to control the result streaming 
(the vibe.d return value doesn't work with ranges, so I would 
have had to construct essentially my entire database in an 
array so I could return it).


In your case, I think you are better off using 2 classes, and 
one shared data storage area.


-Steve


Thanks! (Some how I missed your post).


Re: Vibe.d rest & web service?

2018-02-07 Thread Nicholas Wilson via Digitalmars-d-learn
On Wednesday, 7 February 2018 at 19:50:31 UTC, Jacob Carlborg 
wrote:

Have you tried this?


No. But apart from the fact that I forgot to make the class 
inherit from an interface to that the rest interface would 
actually compile, the web interface is routed before the rest 
interface and so the rest interface would never be reached since 
the methods are all the same and the REST's are shadowed by the 
web's .




Re: Debugging bad requests with vibe

2018-02-09 Thread Nicholas Wilson via Digitalmars-d-learn

On Friday, 9 February 2018 at 08:06:53 UTC, Seb wrote:
On Thursday, 8 February 2018 at 17:09:44 UTC, Nicholas Wilson 
wrote:
Is there a way I can see/log what requests are being made? I 
can change both the client and server.


-v and -vv


So it turns out that structs do not work as parameters TO rest 
interface functions.


https://github.com/vibe-d/vibe.d/issues/2067


Re: uint[3] not equivalent to void[12]?

2018-02-09 Thread Nicholas Wilson via Digitalmars-d-learn

On Friday, 9 February 2018 at 15:50:24 UTC, Ralph Doncaster wrote:

On Friday, 9 February 2018 at 15:24:27 UTC, Mike Parker wrote:
On Friday, 9 February 2018 at 15:05:33 UTC, Ralph Doncaster 
wrote:
This seems odd to me.  Is there a way I can make a function 
that takes an array of any type but only of a specific size 
in bytes?


void.d(8): Error: function void.foo (void[12] arr) is not 
callable using argument types (uint[3])

Failed: ["/usr/bin/dmd", "-v", "-o-", "void.d", "-I."]
void foo(void [12] arr)
{
}

void main()
{
uint[3] arr;
foo(arr);
}


void has no size, so what does it mean to have 12 of them?


according to the docs and my testing, the size of a void array 
element is 1,


Correct.


so the following code prints 12:
import std.stdio;

void foo(void [] arr)
{
writeln("length: " arr.length);
}

void main()
{
uint[3] arr;
foo(arr);
}

I thought about using templates, but I was looking for a simple 
way of making a function that takes an array of 12 bytes, 
whether it is uint[3], ubyte[12], or ushort[6].


uint[3] and void[12] have the same size but are different types 
so the compiler will reject it.
you can reinterpret cast them(i.e. *cast(void[12])() ), but 
this is a rather blunt tool. Is it safe in the case that the 
types size is at least 12 but not safe in general.


Is there a way I can make a function that takes an array of any 
type but only of a specific size in bytes?


With a template that constrains the types size:

void foo(T)(T t) if (T.sizeof == 12)
{
//...
}

alternately reject incorrect values at runtime

void foo(ubyte[] t)
in
{
assert(t.length == 12);
}
do
{
//...
}



Re: dpq2: spurious error message

2018-02-13 Thread Nicholas Wilson via Digitalmars-d-learn
On Tuesday, 13 February 2018 at 17:08:24 UTC, Nicholas Wilson 
wrote:
Is this a problem with the library or me? Can I work around it? 
How?


Thanks
Nic


So digging around in the library code, commenting it out seems to 
work for now as I don't use UUIDs. Error didn't originate from my 
code because it wasn't a template. I'm still surprised that it 
built and then errored in my code.


dpq2: spurious error message

2018-02-13 Thread Nicholas Wilson via Digitalmars-d-learn

import vibe.vibe;
import vibe.db.postgresql;

QueryParams p;
p.sqlCommand = "select 
title,url,url_title,messagebody,generationtime from items order 
by generationtime;";

auto _items = conn.execParams(p);

struct Range
{
 immutable Answer a;
  size_t i;
  immutable(Row) front() { return a[i]; }
  @property void popFront() { i++; }
  bool empty() { return i == a.length; }
}
auto items = Range(_items,0);
res.render!("items.dt", items); // usual vibe.d function

//items.dt
- import std.datetime.date;
- import dpq2.conv.time;
- import dpq2.conv.to_d_types;
- foreach(i; items)
item
title= i["title"].as!string
link= i["url"].as!string
description= i["messagebody"].as!string
pubDate= 
DateTimeToRfc822String(i["generationTime"].as!DateTime)


I get the following _two_ lots of the following error (between 
the ):

Compiling Diet HTML template rss.dt...
-
dpq2-1.0.0-alpha.7/dpq2/src/dpq2/conv/to_bson.d(143,23): Error: 
none of the overloads of '__ctor' are callable using argument 
types (UUID), candidates are:
vibe-d-0.7.32/vibe-d/source/vibe/data/bson.d(148,2):
vibe.data.bson.Bson.this(Type type, immutable(ubyte)[] data)
vibe-d-0.7.32/vibe-d/source/vibe/data/bson.d(185,2):
vibe.data.bson.Bson.this(double value)
vibe-d-0.7.32/vibe-d/source/vibe/data/bson.d(187,2):
vibe.data.bson.Bson.this(string value, Type type = 
cast(Type)cast(ubyte)2u)
vibe-d-0.7.32/vibe-d/source/vibe/data/bson.d(194,2):
vibe.data.bson.Bson.this(const(Bson[string]) value)
vibe-d-0.7.32/vibe-d/source/vibe/data/bson.d(196,2):
vibe.data.bson.Bson.this(const(Bson[]) value)
dpq2-1.0.0-alpha.7/dpq2/src/dpq2/conv/to_bson.d(143,23):
... (10 more, -v to show) ...

-
const(ubyte[]) Is not tested in integration tests!
UUID Is not tested in integration tests!
TTimeStamp!false Is not tested in integration tests!
Json Is not tested in integration tests!


Is this a problem with the library or me? Can I work around it? 
How?


Thanks
Nic


Re: dpq2: spurious error message

2018-02-13 Thread Nicholas Wilson via Digitalmars-d-learn
On Tuesday, 13 February 2018 at 17:17:41 UTC, Nicholas Wilson 
wrote:
On Tuesday, 13 February 2018 at 17:08:24 UTC, Nicholas Wilson 
wrote:
Is this a problem with the library or me? Can I work around 
it? How?


Thanks
Nic


So digging around in the library code, commenting it out seems 
to work for now as I don't use UUIDs. Error didn't originate 
from my code because it wasn't a template. I'm still surprised 
that it built and then errored in my code.


Ahh it requires vibe.d 0.8.2


vib.d suppress 404 for no content written

2018-02-14 Thread Nicholas Wilson via Digitalmars-d-learn

I have an endpoint that is a post:

void postStuff(HTTPServerRequest req, HTTPServerResponse res)
{
// do some stuff with req
res.statusCode = 200;
}

I do not write anything to res (deliberately) but want to set the 
status code.


However it returns 404, because no content is written.
How can I make it return 200?

FWIW its a member of a web interface class.

Thanks
Nic


Re: vib.d suppress 404 for no content written

2018-02-14 Thread Nicholas Wilson via Digitalmars-d-learn

On Wednesday, 14 February 2018 at 14:58:14 UTC, Seb wrote:
On Wednesday, 14 February 2018 at 14:30:19 UTC, Nicholas Wilson 
wrote:

I have an endpoint that is a post:

void postStuff(HTTPServerRequest req, HTTPServerResponse res)
{
// do some stuff with req
res.statusCode = 200;
}

I do not write anything to res (deliberately) but want to set 
the status code.


However it returns 404, because no content is written.
How can I make it return 200?

FWIW its a member of a web interface class.

Thanks
Nic


You mean `writeVoidBody`

See Also: https://github.com/vibe-d/vibe.d/issues/2065


Thanks!


Re: opDispatch with string mixin does not work as I would expect.

2018-02-09 Thread Nicholas Wilson via Digitalmars-d-learn

On Saturday, 10 February 2018 at 06:32:43 UTC, German Diago wrote:

Hello everyone,

I am trying to forward some member functions from a struct as a 
Catch-all function, so I did something like this:


struct A {
struct HeaderData {
  align(1):
  char [21] id;
  ubyte field1;
  ubyte field2;
}

Nullable!(HeaderData) headerData;


auto opDispatch(string name)() {
  readHeader();
  static foreach (member; __traits(allMembers, 
HeaderData)) {

 static if (name == member) {
 return mixin("headerData." ~ name);
 }
  }
  }

The mixin line does not work. I want to generate the access to 
the field. How could I achieve that?


That looks like it should work. Perhaps you need to change
`static if (name == member)` to
`static if (name == member.stringof)`

Alternatively you could do something like

auto opDispatch(string name)() 
if(hasMember!(HeaderData,name){

  readHeader();
  return mixin("headerData." ~ name);
}




Re: Debugging bad requests with vibe

2018-02-09 Thread Nicholas Wilson via Digitalmars-d-learn

On Friday, 9 February 2018 at 08:06:53 UTC, Seb wrote:
On Thursday, 8 February 2018 at 17:09:44 UTC, Nicholas Wilson 
wrote:
Is there a way I can see/log what requests are being made? I 
can change both the client and server.


-v and -vv


All that gives me is a bunch of
[FAC3BFF6:FAC451F6 dia] Actively closing TCP connection

is there a way to get the JSON being sent?


Re: Debugging bad requests with vibe

2018-02-09 Thread Nicholas Wilson via Digitalmars-d-learn
On Thursday, 8 February 2018 at 20:24:19 UTC, Nicholas Wilson 
wrote:
On Thursday, 8 February 2018 at 17:09:44 UTC, Nicholas Wilson 
wrote:
I have set up a vibe.d rest interface (on a server) and have a 
client on my machine.


struct Observation
{
string desc;
DateTime time;
}

interface Obsever
{
@property void observe(Observation ra);
}

void main()
{
auto test = Observation("a duck", 
cast(DateTime)Clock.currTime(UTC()));


auto client = new RestInterfaceClient! 
Obsever("http://example.com/observation;);

client. observe = test; // 400
}

I' pretty sure the url is correct because other ones give 404.

Is there a way I can see/log what requests are being made? I 
can change both the client and server.


Never mind, it was because I was accidentally shadowing that 
path with a get on the server.


Hmm, nope it wasn't that.


Re: Vibe.d rest & web service?

2018-02-08 Thread Nicholas Wilson via Digitalmars-d-learn

On Thursday, 8 February 2018 at 10:51:39 UTC, Arjan wrote:
On Wednesday, 7 February 2018 at 20:23:10 UTC, Nicholas Wilson 
wrote:
On Wednesday, 7 February 2018 at 19:50:31 UTC, Jacob Carlborg 
wrote:

Have you tried this?


No. But apart from the fact that I forgot to make the class 
inherit from an interface to that the rest interface would 
actually compile, the web interface is routed before the rest 
interface and so the rest interface would never be reached 
since the methods are all the same and the REST's are shadowed 
by the web's .


Makes me wonder whether or not vibe does honor the http request 
Accept headers?
e.g.: application/json or application/javascript or text/html 
etc.


Hmm, I hadn't considered the Accept Headers.


Vibe.d rest & web service?

2018-02-07 Thread Nicholas Wilson via Digitalmars-d-learn
Is it possible to have some urls routed to serve content and some 
to receive JSON in the same class? Basically I want:


shared static this()
{
auto router = new URLRouter;
auto a = new MyInterface;
router.registerWebInterface(new MyInterface); //?? selective 
combination

router.registerRestInterface(new MyInterface); //??
auto settings = new HTTPServerSettings;
settings.port = 8080;
settings.bindAddresses = ["::1","127.0.0.1"];
listenHTTP(settings, router);
}

class MyInterface
{
SomeData[] items;
// Get
void index()
{
render!("index.dt");
}
// Get
void getPage()
{
render!("page.dt", items);
}

// REST -> receive d as JSON.
void postGiveMeData(SomeData d)
{
synchronized
{
items ~= d;
}
}
}


Re: ubyte[4] to int

2018-02-15 Thread Nicholas Wilson via Digitalmars-d-learn

On Thursday, 15 February 2018 at 16:51:05 UTC, Kyle wrote:
Hi. Is there a convenient way to convert a ubyte[4] into a 
signed int? I'm having trouble handling the static arrays 
returned by std.bitmanip.nativeToLittleEndian. Is there some 
magic sauce to make the static arrays into input ranges or 
something? As a side note, I'm used to using D on Linux and 
DMD's error messages on Windows are comparably terrible. Thanks!


you mean you want to convert the bitpattern represented by the 
uint[4] to an int?


You want a reinterpret style case

ubyte[4] foo = ...;
int baz = *cast(int*)


Re: Manually allocating a File

2018-02-20 Thread Nicholas Wilson via Digitalmars-d-learn

On Tuesday, 20 February 2018 at 15:32:45 UTC, Chris M. wrote:
Thanks for the info, that clears things up. Like I said, it was 
more experimentation rather than me planning to actually use 
it. Works now with the following modifications.


import std.stdio;
import core.stdc.stdlib;
import std.conv;

void main()
{
auto f = cast(File*) malloc(File.sizeof);
emplace!File(f, "test.txt", "r");
f.readln.write;
free(f);
}


(*f).readln.writeln;


That * is unnecessary btw, in D you can

f.readln

and it will see it is a pointer to struct and dereference it 
for you.


That's what I had originally, but I put the * in to see if it 
would help with the original issue and never removed it


FYI, File is a reference counted FILE* so theres not really any 
point of heap allocating it.


Re: Negative index range violation

2018-02-21 Thread Nicholas Wilson via Digitalmars-d-learn

On Thursday, 22 February 2018 at 00:13:43 UTC, SrMordred wrote:

string x = "123";
auto c = x.ptr;
c++;
writeln(c[-1]); // 1
writeln(c[-1..0]); //BOOM Range violation


Can I do this / Bug / some mistake ?


youd have to do
(c-1)[0 .. 1];


Re: multithread/concurrency/parallel methods and performance

2018-02-18 Thread Nicholas Wilson via Digitalmars-d-learn

On Sunday, 18 February 2018 at 17:54:58 UTC, SrMordred wrote:

I´m experimenting with threads and related recently.
(i´m just started so may be some terrrible mistakes here)

With this base work:

foreach(i ; 0 .. SIZE)
{
results[i] = values1[i] * values2[i];
}

and then with this 3 others methods: parallel, spawn and 
Threads.


this was my results:

_base : 456 ms and 479 us
_parallel : 331 ms, 324 us, and 4 hnsecs
_concurrency : 367 ms, 348 us, and 2 hnsecs
_thread : 369 ms, 565 us, and 3 hnsecs

(code here : https://run.dlang.io/is/2pdmmk )

All methods have minor speedup gains.  I was expecting a lot 
more.

Since I have 7 cores I expected like below 100ms.

I´m not seeing false sharing in this case. or i'm wrong?

If someone can expand on this, i'll be grateful.

Thanks!


As SIZE=1024*1024 (i.e. not much, possibly well within L2 cache 
for 32bit) it may be that dealing with the concurrency overhead 
adds a significant amount of overhead. Also the run.dlang.io link 
has no -O flag and thus no optimisations


without -O i get

_base : 323 ms, 92 μs, and 6 hnsecs
_parallel : 276 ms, 649 μs, and 3 hnsecs
_concurrency : 221 ms, 931 μs, and 7 hnsecs
_thread : 212 ms, 277 μs, and 3 hnsecs

with it I get
_base : 150 ms, 728 μs, and 5 hnsecs
_parallel : 120 ms, 78 μs, and 5 hnsecs
_concurrency : 134 ms, 787 μs, and 4 hnsecs
_thread : 129 ms, 476 μs, and 2 hnsecs

with SIZE= 16*1024*1024 without -O i get
_base : 5 secs, 835 ms, 240 μs, and 9 hnsecs
_parallel : 4 secs, 802 ms, 279 μs, and 8 hnsecs
_concurrency : 2 secs, 133 ms, 685 μs, and 3 hnsecs
_thread : 2 secs, 108 ms, 860 μs, and 9 hnsecs

with SIZE= 16*1024*1024 with -O i get
_base : 2 secs, 502 ms, 523 μs, and 4 hnsecs
_parallel : 1 sec, 769 ms, 945 μs, and 3 hnsecs
_concurrency : 1 sec, 362 ms, 747 μs, and 1 hnsec
_thread : 1 sec, 335 ms, 720 μs, and 1 hn




Re: std.array.array for immutable data types

2018-02-18 Thread Nicholas Wilson via Digitalmars-d-learn

On Monday, 19 February 2018 at 07:08:49 UTC, Fra Mecca wrote:

Is there a way to avoid using to! conversion here?

immutable string[] dst = to!(immutable 
string[])(array(pipe.readEnd.byLineCopy));


assumeUnique.

immutable string[] dst = 
pipe.readEnd.byLineCopy.array.assumeUnique;


Re: Is this an okay representation of a dynamically sized Matrix, to be used for HMM matrices m = (A,B)

2017-12-28 Thread Nicholas Wilson via Digitalmars-d-learn

On Thursday, 28 December 2017 at 01:34:10 UTC, Enjoys Math wrote:



Code:

module matrix;

import std.array;


struct Matrix(E)
{
private:
   E[][];

   this() {
   }

   void deleteRow(int i)
   {
  E = E[0..i] ~ E[i..$];
   }

   void deleteColumn(int j)
   {
  for (int i=0; i < E.length; i++)
  {
 E[i] = E[i][0..j] ~ E[i][j..$];
  }
   }

   void insertRow(int i, E[] row)
   {
  if (E.length != 0)
 assert(E[0].length == row.length);
  E.insertInPlace(i, row);
   }

   void insertColumn(int j, E[] col)
   {
  for (int i=0; i < E.length; i++)
  {
 E[i].insertInPlace(j, col[i]);
  }
   }

   int numRows() { return E.length; }

   int numColumns() {
  if (E.length == 0)
 return 0;
  return E[0].length;
   }

}


Is there a more efficient way of doing this, knowing that I'll 
be inserting columns / rows every time we need to create a new 
hidden state so this matrix will be huge, for a good model.  By 
huge we'll probably use the full capacity of a long[] in D.  
I've already tried doing this in MQL5 and we exceeded easily 
the max array capacity.


Full capacity of a long[] (or any array) is the entire 
addressable memory, which is 4GB for 32bit. You will not exceed 
the 64bit address space.


Do you know the width of the matrix ahead of time? I assume they 
are all the same given the implementation of numColumns.


Have you looked at mir (https://github.com/libmir/mir-algorithm) 
for ndslice?


by deleting rows, can you get away with just zeroing them?







Re: std way to remove multiple indices from an array at once

2017-12-20 Thread Nicholas Wilson via Digitalmars-d-learn
On Thursday, 21 December 2017 at 00:23:08 UTC, Steven 
Schveighoffer wrote:

On 12/20/17 6:01 PM, aliak wrote:
Hi, is there a way to remove a number of elements from an 
array by a range of indices in the standard library somewhere?


I wrote one (code below), but I'm wondering if there's a 
better way?


Also, can the below be made more efficient?

auto without(T, R)(T[] array, R indices) if (isForwardRange!R 
&& isIntegral!(ElementType!R) && !isInfinite!R) {

     T[] newArray;
     ElementType!R start = 0;
     foreach (i; indices) {
     newArray ~= array[start .. i];
     start = i + 1;
     }
     newArray ~= array[start .. $];
     return newArray;
}

// Usage
long[] aa = [1, 2, 3, 4]
aa = aa.without([1, 3])

Thanks!


I'm assuming here indices is sorted? Because it appears you 
expect that in your code. However, I'm going to assume it isn't 
sorted at first.


Now:

import std.range;
import std.algorithm;

auto indices = [1,2,3,4];
aa = aa.enumerate.filter!(a => !indicies.canFind(a[0])).map(a 
=> a[1]).array;


Now, this is going to be O(n^2), but if indices is sorted, you 
could use binary search:


auto sortedIdxs = indices.assumeSorted; // also could be = 
indices.sort()


arr = arr.enumerate.filter!(a => 
!sortedIdxs.contains(a[0])).map(a => a[1]).array;


Complexity would be O(n lg(n))

It's not going to be as good as hand-written code, complexity 
wise, but it's definitely shorter to write :)


-Steve


isn't that n log(m), where n is length of array and m is length 
of indices?


If indices is sorted with no duplicates and random access then 
you can do it in linear time.


int i;
int ii;
int[] indicies = ...;
arr = arr.filter!((T t)
{
scope(exit) i++;
if (i == indicies[ii])
{
ii++;
return false;
}
return true;
}).array;



Re: Function in a slice instead of just pointer?

2018-06-21 Thread Nicholas Wilson via Digitalmars-d-learn

On Thursday, 21 June 2018 at 21:00:46 UTC, Michael Brown wrote:

Hi D Community,

Is it possible to get a slice of a function, rather than just 
its start pointer?




No.

I'm interested in currying a function at runtime - So I would 
need to copy a function block (Either the original function, a 
wrapper function, or copys of manually altered functions).


see https://dlang.org/phobos/std_functional.html#partial

Addresses of labels would also be useful - Does Dlang have 
computable labels? (& in C)


Don't think so.

I suspect Ill have to do this in ASM, but seeing if there's a 
higher level solution?


Kind Regards,
Mike Brown




Linking to dynamic druntime with dub

2018-07-31 Thread Nicholas Wilson via Digitalmars-d-learn
My application needs to load shared libraries: on Posix this is 
only supported with a shared druntime. How does one link to the 
dynamic druntime with dub?


Re: Linking to dynamic druntime with dub

2018-07-31 Thread Nicholas Wilson via Digitalmars-d-learn

On Tuesday, 31 July 2018 at 13:52:21 UTC, rikki cattermole wrote:

On 01/08/2018 1:43 AM, Nicholas Wilson wrote:
My application needs to load shared libraries: on Posix this 
is only supported with a shared druntime. How does one link to 
the dynamic druntime with dub?


The same way you do it without dub.
Except you pass the flags inside of "dflags".


which is? (I usually use -link-defaultlib-shared with LDC hence 
the question with dub).


Re: Linking to dynamic druntime with dub

2018-07-31 Thread Nicholas Wilson via Digitalmars-d-learn

On Tuesday, 31 July 2018 at 14:27:18 UTC, rikki cattermole wrote:

On 01/08/2018 2:18 AM, Nicholas Wilson wrote:
On Tuesday, 31 July 2018 at 13:52:21 UTC, rikki cattermole 
wrote:

On 01/08/2018 1:43 AM, Nicholas Wilson wrote:
My application needs to load shared libraries: on Posix this 
is only supported with a shared druntime. How does one link 
to the dynamic druntime with dub?


The same way you do it without dub.
Except you pass the flags inside of "dflags".


which is? (I usually use -link-defaultlib-shared with LDC 
hence the question with dub).


No idea for dmd/gdc.
But for LDC that would be (json):

"dflags-ldc2": ["-link-defaultlib-shared"],


Ahh, it turns out that loading shared libraries is not supported 
on OSX, wonderful.


Re: Compiler build error

2018-08-04 Thread Nicholas Wilson via Digitalmars-d-learn

On Saturday, 4 August 2018 at 18:12:05 UTC, Alex wrote:
On Saturday, 4 August 2018 at 13:26:01 UTC, Nicholas Wilson 
wrote:
0  ldc2 0x000106fcc4e7 
llvm::sys::PrintStackTrace(llvm::raw_ostream&) + 37
1  ldc2 0x000106fcb9ea 
llvm::sys::RunSignalHandlers() + 83
2  ldc2 0x000106fcc90e 
SignalHandler(int) + 239

3  libsystem_platform.dylib 0x7fff5992af5a _sigtramp + 26
4  libsystem_platform.dylib 0x00015fcde600 _sigtramp + 
104543936

ldc2 failed with exit code -11.

Is this the entire stack trace? If dmd is also affected 
chances it is a frontend bug.


Well, on MacOs - yes. On a Linux, it is longer:

[snip]


That is a very long stacks trace and combined with the very short 
stack trace on OSX, this is probably a stack overflow.
1) Do you have any very deeply nested types/templates somewhere 
or somehow created a cyclic dependency in semantic analysis?
2) Can you try with a bigger stack (ulimit -s)? If it still fails 
then its probably 1.


Re: Compiler build error

2018-08-04 Thread Nicholas Wilson via Digitalmars-d-learn

On Saturday, 4 August 2018 at 12:21:36 UTC, Alex wrote:

I'm a little bit confused by following situation:

I have code, say around 8000 lines. Now, I'm facing a build 
error which just says


dmd failed with exit code -11,

(same for ldc2, with some lines of stack information, which do 
not belong to my code)


0  ldc2 0x000106fcc4e7 
llvm::sys::PrintStackTrace(llvm::raw_ostream&) + 37
1  ldc2 0x000106fcb9ea 
llvm::sys::RunSignalHandlers() + 83
2  ldc2 0x000106fcc90e 
SignalHandler(int) + 239

3  libsystem_platform.dylib 0x7fff5992af5a _sigtramp + 26
4  libsystem_platform.dylib 0x00015fcde600 _sigtramp + 
104543936

ldc2 failed with exit code -11.



Is this the entire stack trace? If dmd is also affected chances 
it is a frontend bug.


As I'm compiling rather often, I know exactly which line in my 
code causes this error. As the compiler refuses to exit 
normally, I'm not sure, if the line is buggy (so, whether I'm 
trying to compile, something, what is not compilable) or, I'm 
facing an ICE.


You are.


In both cases, I'm ready to rewrite my code a
little bit to get around the error, as I need a solution quite 
fast.


My assumption is, that I built a kind of loop, which the 
compiler does not know how to get along. But in order to 
rewrite it, I have to know, what I have to rewrite... So, 
despite I know exactly the culprit line in my code, I don't 
have any information about how to solve the problem.


What I'm trying now is to use dustmite. But this, lasts for 
about 8 hours now and is already at depth 20. Lacking 
experience with this tool, I'm not sure, if this is normal... 
The last time I tried to use it elsewhere, I got a final depth 
of 13, but also an empty file as its analysis result.


The command for dustmite was
dub dustmite ../dust --compiler-status=-11 --combined

Yes... the builds were also done with dub. So,
dub build
and
dub build --compiler=ldc2
respectively.

Any help is appreciated :)
Alex


A complete stack trace would be a good start.
If you can do enough manual bisection (git or semi-random 
deletion of potions of code) to post the code that would also be 
good.


Re: Compiler build error

2018-08-05 Thread Nicholas Wilson via Digitalmars-d-learn

On Sunday, 5 August 2018 at 10:12:39 UTC, Alex wrote:

On Sunday, 5 August 2018 at 01:15:07 UTC, Nicholas Wilson wrote:

On Saturday, 4 August 2018 at 18:12:05 UTC, Alex wrote:

On Saturday, 4 August 2018 at 13:26:01 UTC, Nicholas Wilson
That is a very long stacks trace and combined with the very 
short stack trace on OSX, this is probably a stack overflow.
1) Do you have any very deeply nested types/templates 
somewhere or somehow created a cyclic dependency in semantic 
analysis?
2) Can you try with a bigger stack (ulimit -s)? If it still 
fails then its probably 1.


:)
I assumed this at the beginning too...
The structures are not very deep, say 3-4 levels. But yes, I do 
have something like a loop you mentioned.
I'm trying to get rid of this right now. I hoped, if the 
compiler has problems with my construct, it would help me to 
find a better start place for this...


However, if I take your description: Is there a general way, to 
solve a cyclic dependency during the semantic analysis step? I 
mean, I'm trying to lowering logic in my code somehow, but the 
loop I need won't go away per se...


I can't really know without seeing the code, but if you can move 
the body of the loop into its own template that might work.


Re: pointer cast from const(Y) to immutable(void*)** is not supported at compile time

2018-08-01 Thread Nicholas Wilson via Digitalmars-d-learn

On Wednesday, 1 August 2018 at 20:10:44 UTC, Hakan Aras wrote:

On Wednesday, 1 August 2018 at 16:25:28 UTC, Hakan Aras wrote:



https://run.dlang.io/is/dSVruv



Whoops, that was the wrong one. It's fixed now.


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

As a workaround remove static, as that causes y to be initialised 
at compile time. static here has nothing to do with static_cast 
in C++.


The analogy to a static_cast would be

const X x = new Y();

casting up the hierarchy, as opposed to dynamic casting down the 
hierarchy.


Re: pointer cast from const(Y) to immutable(void*)** is not supported at compile time

2018-08-01 Thread Nicholas Wilson via Digitalmars-d-learn

On Thursday, 2 August 2018 at 02:13:41 UTC, Hakan Aras wrote:
On Thursday, 2 August 2018 at 01:39:58 UTC, Nicholas Wilson 
wrote:



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



I wasn't quite sure whether it's a bug since it happens in both 
compilers. Thanks for opening the issue.




For future reference the only time you should consider LDC/GDC 
distinct from DMD is codegen, i.e. compiler causes your code to 
crash. This is a frontend bug so it affects all the major 
compilers.


As a workaround remove static, as that causes y to be 
initialised at compile time.


I do want it at compiletime though.


static here has nothing to do with static_cast in C++.
The analogy to a static_cast would be

const X x = new Y();

casting up the hierarchy, as opposed to dynamic casting down 
the hierarchy.


Sorry, I actually meant a reinterpret_cast. I always get those 
mixed up. But now that I look at it again I don't see how that 
would help me, since my code isn't the one trying to to casting.


Ah, unfortunately you're stuck then.


Re: countUntil's constraints

2018-08-07 Thread Nicholas Wilson via Digitalmars-d-learn
On Wednesday, 8 August 2018 at 01:33:26 UTC, Steven Schveighoffer 
wrote:

On 8/7/18 9:20 PM, Nicholas Wilson wrote:

the first overload is

ptrdiff_t countUntil(alias pred = "a == b", R, Rs...)(R 
haystack, Rs needles)

if (isForwardRange!R
&& Rs.length > 0
&& isForwardRange!(Rs[0]) == isInputRange!(Rs[0])
&& is(typeof(startsWith!pred(haystack, needles[0])))
&& (Rs.length == 1
|| is(typeof(countUntil!pred(haystack, needles[1 .. $])

What does `isForwardRange!(Rs[0]) == isInputRange!(Rs[0]` mean 
here?
Is it just the same as `isForwardRange!(Rs[0])`? Why is it 
written like that?


No, not exactly the same.

Superficially, this rejects elements that are input ranges but 
NOT forward ranges. Other than that, I can't tell you the 
reason why it's that way.


-Steve


But forward ranges are a superset of input ranges so 
`isForwardRange!(Rs[0]) == isInputRange!(Rs[0]` <=> 
`isForwardRange!(Rs[0])`, right?


countUntil's constraints

2018-08-07 Thread Nicholas Wilson via Digitalmars-d-learn

the first overload is

ptrdiff_t countUntil(alias pred = "a == b", R, Rs...)(R haystack, 
Rs needles)

if (isForwardRange!R
&& Rs.length > 0
&& isForwardRange!(Rs[0]) == isInputRange!(Rs[0])
&& is(typeof(startsWith!pred(haystack, needles[0])))
&& (Rs.length == 1
|| is(typeof(countUntil!pred(haystack, needles[1 .. $])

What does `isForwardRange!(Rs[0]) == isInputRange!(Rs[0]` mean 
here?
Is it just the same as `isForwardRange!(Rs[0])`? Why is it 
written like that?


Re: countUntil's constraints

2018-08-07 Thread Nicholas Wilson via Digitalmars-d-learn
On Wednesday, 8 August 2018 at 01:33:26 UTC, Steven Schveighoffer 
wrote:

On 8/7/18 9:20 PM, Nicholas Wilson wrote:

the first overload is

ptrdiff_t countUntil(alias pred = "a == b", R, Rs...)(R 
haystack, Rs needles)

if (isForwardRange!R
&& Rs.length > 0
&& isForwardRange!(Rs[0]) == isInputRange!(Rs[0])
&& is(typeof(startsWith!pred(haystack, needles[0])))
&& (Rs.length == 1
|| is(typeof(countUntil!pred(haystack, needles[1 .. $])

What does `isForwardRange!(Rs[0]) == isInputRange!(Rs[0]` mean 
here?
Is it just the same as `isForwardRange!(Rs[0])`? Why is it 
written like that?


No, not exactly the same.

Superficially, this rejects elements that are input ranges but 
NOT forward ranges. Other than that, I can't tell you the 
reason why it's that way.


-Steve


Ahhh, Rs[0] is not necessarily a range, consider:

`assert(countUntil("hello world", 'r') == 8);`

so  that means `isForwardRange!(Rs[0]) == isInputRange!(Rs[0]` if 
Rs[0] is a range it must be a forward range.


The second overload looks as though it will never be a viable 
candidate
ptrdiff_t countUntil(alias pred = "a == b", R, N)(R haystack, N 
needle)

if (isInputRange!R &&
is(typeof(binaryFun!pred(haystack.front, needle)) : bool))
{
bool pred2(ElementType!R a) { return binaryFun!pred(a, 
needle); }

return countUntil!pred2(haystack); // <---
}

because the marked line can't recurse be cause there is only one 
arg, so it tries to call the first overload, which fails due to  
Rs.length > 0.




Re: is this a betterC bug ?

2018-08-14 Thread Nicholas Wilson via Digitalmars-d-learn

On Tuesday, 14 August 2018 at 13:01:57 UTC, learnfirst1 wrote:


enum string[] a = ["a"];

extern(C) void main() {
int i = 0;
auto s = a[i];
}
---
Error: TypeInfo cannot be used with -betterC


Yes. https://issues.dlang.org/show_bug.cgi?id=19169


Re: is this a betterC bug ?

2018-08-14 Thread Nicholas Wilson via Digitalmars-d-learn

On Tuesday, 14 August 2018 at 13:16:50 UTC, Nicholas Wilson wrote:

On Tuesday, 14 August 2018 at 13:01:57 UTC, learnfirst1 wrote:


enum string[] a = ["a"];

extern(C) void main() {
int i = 0;
auto s = a[i];
}
---
Error: TypeInfo cannot be used with -betterC


Yes. https://issues.dlang.org/show_bug.cgi?id=19169


This seems to be because dynamic array literals are allocated by 
default. So that is possibly not a bug, per se but the error 
message is definitely not helpful.


Re: unimplemented abstract function compiles.

2018-08-11 Thread Nicholas Wilson via Digitalmars-d-learn

On Saturday, 11 August 2018 at 23:12:43 UTC, ag0aep6g wrote:

On 08/11/2018 11:20 PM, rikki cattermole wrote:

On 12/08/2018 8:55 AM, Eric wrote:

Code below compiles while I would not expect it to compile.
Is there a reason that this compiles?

[...]

No bug. You forgot to throw -unittest when you compiled.

[...]

Error: program killed by signal 11


If that's DMD segfaulting, that's definitely a bug.


its not


/tmp/dmd_run2hTpLG(_D9onlineapp17__unittest_L14_C1FZv+0x3a)[0x55d9bba8fe6e]
/tmp/dmd_run2hTpLG(_D9onlineapp9__modtestFZv+0x9)[0x55d9bba8fe81]


That is run.dlang.io running the resulting executable. (I know 
because I've looked a way too many dmd segfaults ;) )


If that's not DMD segfaulting, you're running the program which 
Eric expects not to compile. So there might be a bug (or Eric's 
expectation is wrong).





Re: Generically call a function on Variant's payload?

2018-08-21 Thread Nicholas Wilson via Digitalmars-d-learn
On Monday, 20 August 2018 at 00:27:04 UTC, Nick Sabalausky 
(Abscissa) wrote:
Suppose I've wrapped a Variant in a struct/class which ensures 
the Variant *only* ever contains types which satisfy a 
particular constraint (for example: isInputRange, or hasLength, 
etc...).


Is there a way to call a function (ex: popFront) on the 
Variant, *without* knowing ahead of time all the possible 
static types it might might contain?


I assume you mean at compile time AoT of development of your 
library?


Yes, don't use Variant; use 
https://github.com/s-ludwig/taggedalgebraic





Re: Can passing an address of this to a non-copyable object be made trusted? - i.e. can I disable moving?

2018-08-26 Thread Nicholas Wilson via Digitalmars-d-learn

On Sunday, 26 August 2018 at 20:17:30 UTC, aliak wrote:


So if we had this:

struct A(T) {
  auto proxy() @trusted {
return B!T();
  }
}

struct B(T) {
  private A!T* source;
  private this(A!T* s) { source = s; }
  @disable this();
  @disable this(this) {}
  @disable void opAssign(B!T);
}

In order for f to be "safe" I need to ensure that B!T() 
does not escape the scope of A!T. I figured disable 
construction and copying may work, but it seems you can still 
get it moved:


void main() @safe {
  auto f() {
auto a = A!int();
return a.proxy;
  }
  auto escaped = f; // escaped.source is gone...
}

Anyway around this?

Cheers,
- Ali


Not sure abut the current language but DIP1014 
https://github.com/dlang/DIPs/blob/master/DIPs/DIP1014.md#final-review


"The point was made that allowing opPostMove to be overidden 
raises the question of what to do when it is annotated with 
@disable. The concensus was that, in such a case, an actual 
attempt to move the object would result in a compilation error."


So, soon™?


Re: How to use math functions in dcompute?

2018-08-27 Thread Nicholas Wilson via Digitalmars-d-learn

On Monday, 27 August 2018 at 09:57:18 UTC, Sobaya wrote:

On Monday, 27 August 2018 at 09:41:34 UTC, 9il wrote:

On Monday, 27 August 2018 at 08:25:14 UTC, Sobaya wrote:

I'm using dcompute(https://github.com/libmir/dcompute).

In the development, I have got to use math functions such as 
sqrt in @compute function.


But LDC says "can only call functions from other @compute 
modules in @compute code", so can't I call any math functions 
with dcompute?


Is there any way to use predefined math functions in dcompute?

Thanks.


You may want to try ldc.intrinsics / mir.math.common


Do you mean llvm_sqrt in ldc.intrinsics?

These functions are also not @compute code, so they cause the 
same error.


Thanks for bringing this to my attention, will fix soon. In the 
meantime you may declare your own intrinsics in a @compute module 
and it should work. as in


@compute module mymath;

pragma(LDC_intrinsic, "llvm.sqrt.f#")
T llvm_sqrt(T)(T val)
if (__traits(isFloating, T));


This will work if you are targeting CUDA, SPIRV may not like it 
because the backend is less... mature.


HMAC and toHexString

2018-07-17 Thread Nicholas Wilson via Digitalmars-d-learn

...
string key = "blahblahblah";
auto mac = hmac!SHA256(key.representation);
string s = ...,t=...u=...,v=...;
foreach(w;AliasSeq!(s,t,u,v))
mac.put(w.representation);
ubyte[32] s = mac.finish;
string sig = toHexString!(LetterCase.lower)(s);

writeln(sig);
// From what I understand Should print something like 
41771e2d0d6c1cf7f442aa8547783ea5b126bfc15a4b354e94d0eaea2ab0fa1a
// Actually prints something like x"31 36 39 33 39 32 38 31 62 38 
31 62 36 36 62 63 63 34 63 36 36 61 62 32 34 37 64 32 64 34 61 00 
78 2A 55 5B FF 7F 00 00 78 2A 55 5B FF 7F 00 00 E0 2A 55 5B FF 7F 
00 00 08 2C 55 5B FF 7F 00 00"c

Note the nuls and things like FF

What am I doing wrong here?


Re: HMAC and toHexString

2018-07-18 Thread Nicholas Wilson via Digitalmars-d-learn

On Wednesday, 18 July 2018 at 05:54:48 UTC, Nicholas Wilson wrote:

...
string key = "blahblahblah";
auto mac = hmac!SHA256(key.representation);
string s = ...,t=...u=...,v=...;
foreach(w;AliasSeq!(s,t,u,v))
mac.put(w.representation);
ubyte[32] s = mac.finish;
string sig = toHexString!(LetterCase.lower)(s);

writeln(sig);
// From what I understand Should print something like 
41771e2d0d6c1cf7f442aa8547783ea5b126bfc15a4b354e94d0eaea2ab0fa1a
// Actually prints something like x"31 36 39 33 39 32 38 31 62 
38 31 62 36 36 62 63 63 34 63 36 36 61 62 32 34 37 64 32 64 34 
61 00 78 2A 55 5B FF 7F 00 00 78 2A 55 5B FF 7F 00 00 E0 2A 55 
5B FF 7F 00 00 08 2C 55 5B FF 7F 00 00"c

Note the nuls and things like FF

What am I doing wrong here?


Ahh, the joys of memory corruption.


Re: HMAC and toHexString

2018-07-18 Thread Nicholas Wilson via Digitalmars-d-learn
On Wednesday, 18 July 2018 at 11:29:42 UTC, baz@dlang-community 
wrote:
On Wednesday, 18 July 2018 at 11:22:36 UTC, Nicholas Wilson 
wrote:
On Wednesday, 18 July 2018 at 05:54:48 UTC, Nicholas Wilson 
wrote:

[...]


Ahh, the joys of memory corruption.


You've reached https://issues.dlang.org/show_bug.cgi?id=16519 
maybe ?


Not sure if it was that or some of the other memory corruption I 
was experiencing.


Re: How to use math functions in dcompute?

2018-08-31 Thread Nicholas Wilson via Digitalmars-d-learn

On Thursday, 30 August 2018 at 10:34:33 UTC, Sobaya wrote:
On Monday, 27 August 2018 at 12:47:45 UTC, Nicholas Wilson 
wrote:

On Monday, 27 August 2018 at 09:57:18 UTC, Sobaya wrote:

On Monday, 27 August 2018 at 09:41:34 UTC, 9il wrote:

On Monday, 27 August 2018 at 08:25:14 UTC, Sobaya wrote:

I'm using dcompute(https://github.com/libmir/dcompute).

In the development, I have got to use math functions such 
as sqrt in @compute function.


But LDC says "can only call functions from other @compute 
modules in @compute code", so can't I call any math 
functions with dcompute?


Is there any way to use predefined math functions in 
dcompute?


Thanks.


You may want to try ldc.intrinsics / mir.math.common


Do you mean llvm_sqrt in ldc.intrinsics?

These functions are also not @compute code, so they cause the 
same error.


Thanks for bringing this to my attention, will fix soon. In 
the meantime you may declare your own intrinsics in a @compute 
module and it should work. as in


@compute module mymath;

pragma(LDC_intrinsic, "llvm.sqrt.f#")
T llvm_sqrt(T)(T val)
if (__traits(isFloating, T));


This will work if you are targeting CUDA, SPIRV may not like 
it because the backend is less... mature.


Thank you for replaying.

Surely the definition you told me works for "sqrt".
But "cos" and "sin" does not work.
The error message is

LLVM ERROR: Cannot select: 0xd76ffd8: f32 = fcos 
ConstantFP:f32<0.00e+00>

   0xd76ff70: f32 = ConstantFP<0.00e+00>

What's wrong?


SPIR-V or CUDA?

for SPIR-V try

pragma(mangle, "_Z3sinf")
float sin(float);
pragma(mangle, "_Z3cosf")
float cos(float);

more generally see 
https://github.com/KhronosGroup/SPIR-Tools/wiki/SPIR-2.0-built-in-functions


If this is a problem with CUDA you could try using the NVPTX 
intrinsics


pragma(LDC_intrinsic, "llvm.nvvm.namegoeshere")
T namegoeshere(Args a);

If you need to use both SPIR-V and CUDA then see the hackery e.g. 
https://github.com/libmir/dcompute/blob/master/source/dcompute/std/index.d#L45


LLVM will be released on September 5th I will fix up this shortly 
after.


Sorry for the alpha state of things right now.

Nic


Re: dub windows unrecognised file extension a

2018-09-08 Thread Nicholas Wilson via Digitalmars-d-learn
On Sunday, 9 September 2018 at 04:01:30 UTC, Nicholas Wilson 
wrote:
On windows with dub it seems to be creating libfoo.a instead of 
foo.lib, I don't think I changed any settings. Old build based 
on 2.078 DMDFE seem to have built .lib but LDC based on 2.082 
seems to be building .a


This definitely seems to be dubs fault: it passes 
-of/path/to/output/libFoo.a to LDC which compiles. `dub describe` 
also has


{
...
"packages" : [
...
{
...
"targetFileName" : "libFoo.a",




Re: dub windows unrecognised file extension a

2018-09-08 Thread Nicholas Wilson via Digitalmars-d-learn
On Sunday, 9 September 2018 at 04:53:05 UTC, Nicholas Wilson 
wrote:
On Sunday, 9 September 2018 at 04:01:30 UTC, Nicholas Wilson 
wrote:
On windows with dub it seems to be creating libfoo.a instead 
of foo.lib, I don't think I changed any settings. Old build 
based on 2.078 DMDFE seem to have built .lib but LDC based on 
2.082 seems to be building .a


This definitely seems to be dubs fault: it passes 
-of/path/to/output/libFoo.a to LDC which compiles. `dub 
describe` also has


{
...
"packages" : [
...
{
...
"targetFileName" : "libFoo.a",


https://github.com/dlang/dub/pull/1559

Ugh time to recompile LLVM & LDC again.


dub windows unrecognised file extension a

2018-09-08 Thread Nicholas Wilson via Digitalmars-d-learn
On windows with dub it seems to be creating libfoo.a instead of 
foo.lib, I don't think I changed any settings. Old build based on 
2.078 DMDFE seem to have built .lib but LDC based on 2.082 seems 
to be building .a




Re: How to use math functions in dcompute?

2018-09-07 Thread Nicholas Wilson via Digitalmars-d-learn

On Friday, 7 September 2018 at 06:45:32 UTC, Sobaya wrote:

Sorry for being late for reply.

I'm using CUDA for back-end.

So you mean if required function is "cos",

pragma(LDC_intrinsic, "llvm.nvv.cos")
T cos(T a);

Is it right?



You're missing an "m" in "nvvm", dunno if that will fix it.

I tried this declaration, but I got an error diffrent from 
previous one:


dcompute.driver.error.DComputeDriverException@../../.dub/packages/dcompute-master/dcompute/source/dcompute/driver/error.d(172):
 cast(Status)218

??:? [0x48739e]
??:? [0x48f8aa]
??:? [0x47942d]
error.d:172 [0x42fe61]
error.d:167 [0x42fdb4]
error.d:187 [0x42feca]
program.d:30 [0x42fc00]
app.d:13 [0x417bea]
??:? [0x47908f]
??:? [0x478f85]
__entrypoint.d:8 [0x4289f4]
??:? __libc_start_main [0x2b85f455282f]
??:? [0x405c08]
Program exited with code 1

My declaration is wrong?

Or fixed LLVM(LDC?) is already released?

How can I use it ?


I'll be adding these to DCompute soon (probably Sunday), LLVM7.0 
has just been released and I've been waiting on that to do 
testing.


Re: Inference of auto storage classes for interface function return type

2018-07-04 Thread Nicholas Wilson via Digitalmars-d-learn

On Wednesday, 4 July 2018 at 14:07:35 UTC, Timoses wrote:
How can I return inferred storage class from interface 
functions?
I can't use auto as return value in interface. Neither can I 
use "inout" as I don't pass a parameter.


// Ref Type
interface IRef
{
Ref opIndex(size_t idx) const;
}
class CRef : IRef
{
Ref[] a;
this() immutable
{ this.a = [new Ref()]; }
Ref opIndex(size_t idx) const
		{ return a[idx]; } // Error: cannot implicitly convert 
expression this.a[idx] of type const(Ref) to app.Ref

}
class Ref{}

void main()
{
auto a = new immutable(CRef)();
auto s = a[3];
}

For value types it works, I presume since they are passed by 
value, so the instance returned is an actual copy of the stored 
value.


// Value Type
interface IValue
{
Value opIndex(size_t idx) const;
}
class CValue : IValue
{
this() immutable { i = [Value()]; }
Value[] i;
Value opIndex(size_t idx) const
{ return i[idx]; }
}
struct Value{}

However, for ref types this doesn't work.

Do I have to define two `opIndex` in the interface? One 
mutable, one for immutable type instances?


IIRC to apply inout to the this pointer:

Ref opIndex(size_t idx) inout;

or
inout(Ref) opIndex(size_t idx) inout;

not sure off the top of my head,


Re: function template specialization question D vs. C++

2018-01-13 Thread Nicholas Wilson via Digitalmars-d-learn

On Sunday, 14 January 2018 at 00:09:42 UTC, kdevel wrote:

fusp.d
```
import std.stdio;
import std.typecons;

void foo (T) ()
{
   writeln ("(1) foo T = ", T.stringof);
}

void foo (T : float) ()
{
   writeln ("(2) foo T = ", T.stringof);
}

// void foo (T : double) ()
// {
//writeln ("(2) foo T = ", T.stringof);
// }

void main ()
{
   foo!float;
   foo!double;
   foo!real;
   foo!string;
}
```

prints

   (2) foo T = float
   (2) foo T = double
   (2) foo T = real
   (1) foo T = string

I would have expected

   (2) foo T = float
   (1) foo T = double
   (1) foo T = real
   (1) foo T = string

The compiler does not allow me to specialize the primary 
function template for double:


The `:` is not a type equality check. It is more like a "converts 
to" or "is of the form of".
i.e. `void foo (T : float) ()` reads as "foo is a template 
function returning void, taking one template type T that converts 
to float, and no runtime args."


The usual way to do what you are trying to do is with template 
constraints.


void foo(T)() if (is(T== float)) { ...}


Re: Can't "is null" an interface?!?! Incompatible types???

2018-03-07 Thread Nicholas Wilson via Digitalmars-d-learn
On Thursday, 8 March 2018 at 04:48:08 UTC, Nick Sabalausky 
(Abscissa) wrote:

-
import vibe.core.net;
TCPConnection mySocket;

void main() {
auto b = mySocket is null;
}
-

That's giving me:

-
Error: incompatible types for (mySocket) is (null): 
TCPConnection and typeof(null)

-

WTF?!?!

The type in question (vibe.core.net.TCPConnection) is an 
interface:

http://vibed.org/api/vibe.core.net/TCPConnection
https://github.com/vibe-d/vibe.d/blob/master/core/vibe/core/net.d#L344

The following works just fine:
-
interface IFoo {}

void main() {
IFoo i;
auto b = i is null;
}
-


That does seem odd.
---
/+dub.sdl:
dependency "vibe-d" version="~>0.8.3-alpha.1"
+/
import vibe.core.net;
import std.stdio;
TCPConnection mySocket;

void main() {
auto b = mySocket is null;
writeln(b);
}
---
works fine on run.dlang.io


Re: How give a module to a CTFE function

2018-03-12 Thread Nicholas Wilson via Digitalmars-d-learn

On Monday, 12 March 2018 at 22:24:15 UTC, Xavier Bigand wrote:

mixin(implementFunctionsOf("derelict.opengl3.functions"));


As string I get the following error:
..\src\api_entry.d(16): Error: variable `mod` cannot be read at 
compile time
..\src\api_entry.d(48):called from here: 
`implementFunctionsOf("derelict.opengl3.functions")`


I also tried to make implementFunctionsOf a mixin template.


make the argument to implementFunctionsOf a template arg.


Re: complex arithmetic in D: multiple questions

2018-03-09 Thread Nicholas Wilson via Digitalmars-d-learn

On Friday, 9 March 2018 at 12:34:40 UTC, J-S Caux wrote:

Please bear with me, this is a long question!
To explain, I'm a scientist considering switching from C++ to 
D, but before I do, I need to ensure that I can:
- achieve execution speeds comparable to C++ (for the same 
accuracy; I can accept a slight slowdown, call it 30%, to get a 
few more digits (which I typically don't need))
- easily perform all standard mathematical operations on 
complex numbers
- (many other things not relevant here: memory use, 
parallelization, etc).


In the two files linked below, I compare execution 
speed/accuracy between D and C++ when using log on complex 
variables:


https://www.dropbox.com/s/hfw7nkwg25mk37u/test_cx.d?dl=0
https://www.dropbox.com/s/hfw7nkwg25mk37u/test_cx.d?dl=0

The idea is simple: let a complex variable be uniformly 
distributed around the unit circle. Summing the logs should 
give zero.


In the D code, I've defined an "own" version of the log, 
log_cx, since std.complex (tragically!) does not provide this 
function (and many others, see recent threads 
https://forum.dlang.org/post/dewzhtnpqkaqkzxwp...@forum.dlang.org and https://forum.dlang.org/thread/lsnuevdefktulxlto...@forum.dlang.org, and issue https://issues.dlang.org/show_bug.cgi?id=18571).


[snip]

So simple C++ is thrice as fast as the best-achieved D I 
managed.


Now for my questions:
- I would expect the D `Complex!double` case to work faster 
than the `real` one. Why is it the other way around? [I can 
accept (and use) D with Complex!real running 1/3 the speed of 
C++ (but with increased accuracy), but I'd also love to be able 
to run D with `Complex!double` at C++ speeds, since the 
tradeoff might be worth it for some calculations]


because the double version is doing the exact same work as the 
real
except that it is also converting between real and double for 
atan2 (from arg). 
https://github.com/dlang/phobos/blob/master/std/math.d#L1352


I'm really not sure why phobos does that, it should't.

- what is the best way to correct the unfortunate (to be 
polite) omission of many standard mathematical functions from 
std.complex? [if I may be frank, this is a real pain for us 
scientists] There exists 
https://gist.github.com/Biotronic/17af645c2c9b7913de1f04980cd22b37 but can this be integrated (after improvements) in the language, or should I (re)build my own?


It will be much faster to build your own that just forward to the 
C functions (or LLVM intrinsics) see 
https://github.com/libmir/mir-algorithm/blob/master/source/mir/math/common.d#L126 for a starting point (we'd greatly appreciate pull requests for anything missing).
Even if the decision to make std.math behave at the appropriate 
precision is accepted, it will still take an entire release cycle 
(unless you use dmd master), and I'm not so sure it will.


- for my education, why was the decision made to go from the 
built-in types `creal` etc to the `Complex` type?


I think because they can be done in the library.
I personally don't think they should have been, they don't 
complicate things that much.



[related questions:


Did you press send too soon?


Re: complex arithmetic in D: multiple questions

2018-03-09 Thread Nicholas Wilson via Digitalmars-d-learn

On Friday, 9 March 2018 at 14:41:47 UTC, J-S Caux wrote:
Is this a case for a bug report? Seems pretty bizarre to do 
that, like an oversight/neglect.


Yes if there's not one there for it already.

OK thanks. I looked at libmir, and saw many good things there. 
I was wondering: is it still actively developed/maintained? How 
will it fit with the "core" D in the future? [I don't want to 
build dependencies to libraries which aren't there to stay in 
the long run, I want code which can survive for decades]. It 
would seem to me that some of the things included in there 
should be part of D core/std anyway.


Yes, it is sponsored by https://github.com/kaleidicassociates it 
will be around for a long time.
It is developed separately because the dev/release cycles don't 
easily align with the core/ stdlib developers.


https://github.com/libmir/mir-algorithm/blob/master/source/mir/ndslice/slice.d#L594
is the de facto matrix structure for D.

Going further, I'm really wondering what the plan is as far as 
Complex is concerned. Right now it just feels neglected 
(half-done/aborted transition from creal etc to Complex, lots 
of missing basic functions etc), and is one major blocking 
point as far as adoption (among scientists) is concerned. Julia 
is really taking off with many of my colleagues, mostly because 
due respect was given to maths. I'd certainly choose Julia if 
it wasn't for the fact that I can't get my exploratory/testing 
codes to run faster than about 1/10th of my C++ stuff. It seems 
D could have such an appeal in the realm of science, but these 
little things are really blocking adoption (including for 
myself).


Indeed, I'll see what I can do about it.


[related questions:


Did you press send too soon?


No, the related questions were linked in my previous post (just 
copied & pasted it further above, but didn't delete these last 
couple of words properly).


Thanks a lot Nicholas!




Re: Passing directory as compiler argument not finding file

2018-04-12 Thread Nicholas Wilson via Digitalmars-d-learn

On Thursday, 12 April 2018 at 07:48:28 UTC, Jamie wrote:

On Thursday, 12 April 2018 at 06:30:25 UTC, Tony wrote:

On Thursday, 12 April 2018 at 05:39:21 UTC, Jamie wrote:


Am I using the -I compiler option incorrectly?


I believe so. I think it is for finding import files, not the 
files you are compiling.


-
-I=directory
 Look for imports also in directory


Ahh yes I think you are correct. It sounds silly that I was 
compiling from a different spot to my file, but it was to 
demonstrate my situation. Really, it's more like:


A/
 a.d
module A.a;
import std.stdio;
import B.b;
void main()
{
writeln(f(4));
}
B/
 b.d
module B.b;
size_t f(size_t input)
{
return input * 2;
}

And in A/ I'm compiling
dmd -ofoutput a.d ../B/b.d

and instead I was thinking I could compile with
dmd -ofoutput a.d -I../B b.d

and would get the same result. The former works, the latter 
does not. Is there something like this that I can use or do I 
have to pass all the files with the direct path to them? Thanks


rdmd. from the directory above A and B:

$ rdmd -ofoutput A/a.d


Re: Is using function() in templates possible at all?

2018-04-11 Thread Nicholas Wilson via Digitalmars-d-learn

On Wednesday, 11 April 2018 at 22:13:33 UTC, Sjoerd Nijboer wrote:

On Wednesday, 11 April 2018 at 21:29:27 UTC, Alex wrote:

I would say, alias template parameter is your friend.
https://dlang.org/spec/template.html#TemplateAliasParameter

class SortedList(T, alias comparer)


It works, thank you!
But just to be shure, there's no way to have this more strongly 
typed in D so I can enforce that `comparer`is a funciton or 
delegate with a specific definition?



There is, with template constraints:

class SortedList(T, alias comparer) if(is(typeof(comparer(T.init) 
: int))

{
//...
}


Re: Passing directory as compiler argument not finding file

2018-04-12 Thread Nicholas Wilson via Digitalmars-d-learn

On Thursday, 12 April 2018 at 06:22:30 UTC, Nicholas Wilson wrote:

On Thursday, 12 April 2018 at 05:39:21 UTC, Jamie wrote:

Am I using the -I compiler option incorrectly?


is it thinking /../A is an absolute path?
try -I=./../A


Er, scratch that.  I see you already tried it.


Re: Passing directory as compiler argument not finding file

2018-04-12 Thread Nicholas Wilson via Digitalmars-d-learn

On Thursday, 12 April 2018 at 05:39:21 UTC, Jamie wrote:

With a directory structure as follows:

run/
A/
a.d

Where a.d is:
===
module A.d;


I'm attempting to compile from the run/ directory. If I run with
dmd ../A/a.d

it compiles successfully, however if I pass it the directory
dmd -I=../A a.d

it doesn't compile. Also, if I pass the exact directory
dmd -I=/../A a.d

it doesn't compile.

Both times I get the error
Error: module `a` is in the file 'a.d' which cannot be read

However it then shows the import path as being
import path[0] = ../A

for the first way and
import path[0] = /../A
for the second way.

Am I using the -I compiler option incorrectly?


is it thinking /../A is an absolute path?
try -I=./../A


<    1   2   3   4   5   6   7   >