Re: Implicit conversion in constructor

2015-07-17 Thread Adam D. Ruppe via Digitalmars-d-learn

On Saturday, 18 July 2015 at 02:28:09 UTC, tcak wrote:
I even am not sure how in the world it allows implicit 
conversion from class to struct in "fine" at all.


Given:

struct Foo {
   T x;
   alias x this;
}


Any time you do

Foo foo;

foo.something = whatever;
// or
foo = whatever;
// or
whatever = foo;


It first tries that code directly. If that doesn't work, it then 
tries rewriting `foo` into `foo.x`:


foo.x.something = whatever;
foo.x = whatever;
whatever = foo.x;


And if that compiles, you're all set, that code gets generated.


The OP's situation is just case #2 here. The compiler is taking 
the illegal `thing = new Foo;` and rewriting it into the legal 
`thing.foo = new Foo;` automatically via alias this.


Re: Implicit conversion in constructor

2015-07-17 Thread Adam D. Ruppe via Digitalmars-d-learn

On Saturday, 18 July 2015 at 02:23:26 UTC, rcorre wrote:
Is there any reason why implicit conversion from Foo to Thing 
is permitted in a regular method but not in a constructor?


In the constructor, you are supposed to be constructing things, 
so the first "assignment" of structs is actually a constructor 
call. D does not support implicit construction (kinda sadly, but 
it doesn't).


In the other methods, it calls opAssign instead, since the struct 
already exists. So this is the difference between:


Thing thing = new Foo(); // in the ctor, this line in main 
wouldn't work either with the same error


and

thing = new Foo(); // in the other method, this line in main does 
work




Try adding `void opAssign(T)(T t) { static assert(0); }` to your 
struct and recompile. You'll see it throws on the method. Then 
change that `opAssign` to `this`, so it becomes a constructor. 
Then you'll see it is called in the class constructor.


Moreover, note that this only applies to the *first* assignment 
of the struct. If you copy/paste that line in the constructor 
again right under it, you'll see the compiler only throws the 
error once. The first one is a construction. The second one is a 
standard assignment again.


Put those two lines in a runtime branch: `if(something) thing = 
new Foo(); else thing = new Foo();` and notice how the compiler 
throws two errors again.


The first assignment in any branch of a constructor is a 
construction! The next one is an assignment.




So the rule is slightly complex (and the implementation may be 
buggy, though it seems good to me now), but it is intentional.


The reason for this goes beyond just that constructors are 
supposed to be constructing. It also is relevant for `immutable` 
members - these are allowed to be constructed, but not modified, 
so if the class constructor didn't treat those as constructions, 
it would be impossible to set them up with runtime data.


And it is also important for `@disable this()` struct members, 
which must be constructed explicitly. If the first assignment in 
a ctor didn't count for that, you couldn't have them in a class 
at all.


Re: Are Lua tables possible to do with D?

2015-07-17 Thread rcorre via Digitalmars-d-learn

On Thursday, 16 July 2015 at 07:20:16 UTC, Fusxfaranto wrote:


An associative array of Variant[string] ought to do the job 
well enough.


http://dlang.org/phobos/std_variant.html


For extra fun, you can implement the '.' style syntax pretty 
easily:


---
import std.variant;

struct LuaTable {
  Variant[string] _table;
  alias _table this;

  auto opDispatch(string s)() {
return _table[s];
  }

  void opDispatch(string s, T)(T val) {
_table[s] = Variant(val);
  }
}

unittest {
  LuaTable table;

  table.foo = 5;
  table.bar = "s";

  assert(table.foo == 5);
  assert(table.bar == "s");
}
---


Re: Implicit conversion in constructor

2015-07-17 Thread rcorre via Digitalmars-d-learn

On Saturday, 18 July 2015 at 02:28:09 UTC, tcak wrote:


I even am not sure how in the world it allows implicit 
conversion from class to struct in "fine" at all.


The 'alias this' in the struct permits implicit conversion.
I _think_ that is intended behavior, though I admit I'm not 
actually sure now.

I've been taking it for granted for awhile...


Re: Implicit conversion in constructor

2015-07-17 Thread tcak via Digitalmars-d-learn

On Saturday, 18 July 2015 at 02:23:26 UTC, rcorre wrote:
Is there any reason why implicit conversion from Foo to Thing 
is permitted in a regular method but not in a constructor?


Trying to figure out whether this is a bug or some sort of 
constructor-specific safety precaution.


struct Thing {
  Foo foo;
  alias foo this;
}

class Foo { }

class Bar {
  Thing thing;

  void fine() {
thing = new Foo(); // ok
  }

  this() {
thing = new Foo(); // nope!
  }
}


I even am not sure how in the world it allows implicit conversion 
from class to struct in "fine" at all.


Implicit conversion in constructor

2015-07-17 Thread rcorre via Digitalmars-d-learn
Is there any reason why implicit conversion from Foo to Thing is 
permitted in a regular method but not in a constructor?


Trying to figure out whether this is a bug or some sort of 
constructor-specific safety precaution.


struct Thing {
  Foo foo;
  alias foo this;
}

class Foo { }

class Bar {
  Thing thing;

  void fine() {
thing = new Foo(); // ok
  }

  this() {
thing = new Foo(); // nope!
  }
}



Re: Virtual value types during compile-time for static type safety, static optimizations and function overloading.

2015-07-17 Thread Adam D. Ruppe via Digitalmars-d-learn

On Friday, 17 July 2015 at 23:44:25 UTC, Tamas wrote:

I used DMD, BTW.


what compile flags?


Re: Using executeShell in multiple thread causes access violation error

2015-07-17 Thread ZombineDev via Digitalmars-d-learn

On Monday, 13 July 2015 at 09:46:26 UTC, Minas Mina wrote:
I have written a script that visits all directories in the 
current directory and executes a command. In my case, "git 
pull".


When running the script serially, everything is fine. All git 
repositories are pulled.


But I'd like to pull multiple repositories in parallel to speed 
things up.

So I've changed my loop
from foreach(entry; dirs)
   to foreach(entry; parallel(dirs))

After a while that the program is running I get:
std.exception.ErrnoException@std\stdio.d(638): Could not close 
file `HANDLE(C0)'

 (No error)

0x00411E5C
0x0040B8AB
0x0040A146
0x00402288
0x00403A99
0x00413B95
0x004095FC
0x00439AA0
0x770992B2 in RtlInitializeExceptionChain
0x77099285 in RtlInitializeExceptionChain
object.Error@(0): Access Violation

0x00439429
0x0043A277
0x00411ECD
0x763A9B2C in GetFileAttributesW

Here is the code: http://pastebin.com/Tk0TBGxs


Probably this is a Windows only problem. I tried the following 
code on my Linux machine and I didn't get any exception like 
yours:

https://gist.github.com/ZombineDev/e1e48a18a22d4fc85e8d

Can you run my code just so we can confirm that the problem is in 
the Windows implementation and not in your code? Also what 
compiler version are you using? If you don't get exception while 
using your code, it would be better if you could show me a 
complete code snippet so the issue can be reproduced.


Re: Getting Nth Row and Column from MatrixView, Scid library

2015-07-17 Thread bachmeier via Digitalmars-d-learn

On Friday, 17 July 2015 at 22:05:45 UTC, kerdemdemir wrote:

Sad times with linear algebra libraries for me,

Since I can't get  rows and columns easily with Scid, It seems 
not flexible for me. And also there are other issues for 
example I can't set matrix to row or column major.


I begin to check alternatives first I begin to investigate 
Dlib. D lib matrixes are unfortunately static once created 
their size can't be expanded  and must be square matrix. This 
restrictions seem too much to me .


The best alternative seems to me scid fork of "Cristi 
Cobzarenco" link: https://github.com/cristicbz/scid. It has the 
basic features I need. But it seems last commit made 3 years 
ago. I couldn't compile it. I am getting error:


scid\internal\regionallocator.d(364): Error: safe function 
'scid.internal.region
allocator.threadLocalSegmentSize' cannot call system function 
'scid.internal.reg

ionallocator.RegionAllocatorException.this'
Error building library

Any advice about another lib or fix compile error will be 
welcome.


No idea if it will help with what you need, and the documentation 
is still a work in progress, but this is my library for embedding 
D in R (similar to Rcpp):


https://bitbucket.org/bachmeil/dmdinline2/overview

It does have an easy way to work with rows and columns.


Re: Virtual value types during compile-time for static type safety, static optimizations and function overloading.

2015-07-17 Thread Baz via Digitalmars-d-learn

On Friday, 17 July 2015 at 21:20:41 UTC, Tamas wrote:
Although this code is fully operational, presents nice api and 
compile-time optimizations, the extra Struct wrapper is not 
without runtime penalty.


Is there a solution that results the same static optimizations, 
but has no runtime penalty, i.e. the functions just operates 
with ints? (At least when compiled)


Thanks, Tamas


Hi, I don't see the runtime penalities you talk about.

I've defined these alias:

---
alias abs1 = abs!int;
alias abs2 = abs!Positive;
alias isqrt1 = isqrt!int;
alias isqrt2 = isqrt!Positive;
---

and the asm produced for the `Positive` type is clearly faster:

;--- abs1 ---
00402074h  enter 000Ch, 00h
00402078h  test eax, eax
0040207Ah  js 00402081h
0040207Ch  mov dword ptr [ebp-0Ch], eax
0040207Fh  leave
00402080h  ret
00402081h  neg eax
00402083h  mov dword ptr [ebp-08h], eax
00402086h  leave
00402087h  ret
;

;--- abs2 (Positive)---
00402088h  enter 0004h, 00h
0040208Ch  leave
0040208Dh  ret
;

;--- isqrt1 ---
00402090h  enter 0008h, 00h
00402094h  test eax, eax
00402096h  jns 004020CFh
00402098h  mov ecx, 00454D60h
0040209Dh  push ecx
0040209Eh  call 00403410h
004020A3h  add esp, 04h
004020A6h  push dword ptr [004540A4h]
004020ACh  push dword ptr [004540A0h]
004020B2h  push dword ptr [004540E4h]
004020B8h  push dword ptr [004540E0h]
004020BEh  push 001Bh
004020C0h  push h
004020C2h  call 004035C0h
004020C7h  push eax
004020C8h  call 00403400h
004020CDh  jmp 004020E6h
004020CFh  call 0040247Ch
004020D4h  fsqrt
004020D6h  sub esp, 04h
004020D9h  fstp dword ptr [esp]
004020DCh  call 00402494h
004020E1h  mov dword ptr [ebp-08h], eax
004020E4h  leave
004020E5h  ret
004020E6h  leave
004020E7h  ret
;

;--- isqrt2 (Positive)---
004020E8h  enter 0008h, 00h
004020ECh  call 00402560h
004020F1h  fsqrt
004020F3h  sub esp, 04h
004020F6h  fstp dword ptr [esp]
004020F9h  call 00402494h
004020FEh  mov dword ptr [ebp-08h], eax
00402101h  leave
00402102h  ret
;

(dmd win32 bit, -w -wi).

Also note that i've tweaked the code to get rid of a few warnings:
---
Positive abs(T)(T n) {
static if (is(T == Positive)) {
return n;
}
else
{
if (n >= 0) return Positive(n);
else return Positive(-n);
}
}

Positive isqrt(T)(T x) {
static if (is(T == Positive)) {
return Positive(sqrt(x.to!float).to!int);
}
else
{
if (x<0)
throw new Exception("no root for negative numbers");
else return Positive(sqrt(x.to!float).to!int);
}

}
---


Re: Virtual value types during compile-time for static type safety, static optimizations and function overloading.

2015-07-17 Thread Tamas via Digitalmars-d-learn

On Friday, 17 July 2015 at 23:16:51 UTC, ZombineDev wrote:

On Friday, 17 July 2015 at 23:15:31 UTC, ZombineDev wrote:

On Friday, 17 July 2015 at 21:20:41 UTC, Tamas wrote:
Is there a solution that results the same static 
optimizations, but has no runtime penalty, i.e. the functions 
just operates with ints? (At least when compiled)


Did you try looking at assembly generated by GDC or LDC with 
full optimizations? For example GDC does quite better than DMD 
for the proposed SafeInt type:

https://github.com/D-Programming-Language/phobos/pull/3389#issuecomment-119005595


Also, see the table at the bottom of this comment:
https://github.com/D-Programming-Language/phobos/pull/3389#issuecomment-117450524


Thanks for the pointers! My first priority a  performant library, 
secondary is a nice api, 3rd is a nice implementation. So that 
kind of rules put Amy degradation compared to ints. I used DMD, 
BTW.


I see no reason for the necessity of performance degradation. 
Essentially I just want to assign a similar qualifyer like const 
or immutable. They are checked and used at compile time, but 
erased for runtime. Same here.


Re: Virtual value types during compile-time for static type safety, static optimizations and function overloading.

2015-07-17 Thread ZombineDev via Digitalmars-d-learn

On Friday, 17 July 2015 at 23:15:31 UTC, ZombineDev wrote:

On Friday, 17 July 2015 at 21:20:41 UTC, Tamas wrote:
Is there a solution that results the same static 
optimizations, but has no runtime penalty, i.e. the functions 
just operates with ints? (At least when compiled)


Did you try looking at assembly generated by GDC or LDC with 
full optimizations? For example GDC does quite better than DMD 
for the proposed SafeInt type:

https://github.com/D-Programming-Language/phobos/pull/3389#issuecomment-119005595


Also, see the table at the bottom of this comment:
https://github.com/D-Programming-Language/phobos/pull/3389#issuecomment-117450524


Re: Virtual value types during compile-time for static type safety, static optimizations and function overloading.

2015-07-17 Thread ZombineDev via Digitalmars-d-learn

On Friday, 17 July 2015 at 21:20:41 UTC, Tamas wrote:
Is there a solution that results the same static optimizations, 
but has no runtime penalty, i.e. the functions just operates 
with ints? (At least when compiled)


Did you try looking at assembly generated by GDC or LDC with full 
optimizations? For example GDC does quite better than DMD for the 
proposed SafeInt type:

https://github.com/D-Programming-Language/phobos/pull/3389#issuecomment-119005595


Re: Using executeShell in multiple thread causes access violation error

2015-07-17 Thread Minas Mina via Digitalmars-d-learn

bump


Re: Getting Nth Row and Column from MatrixView, Scid library

2015-07-17 Thread kerdemdemir via Digitalmars-d-learn

Sad times with linear algebra libraries for me,

Since I can't get  rows and columns easily with Scid, It seems 
not flexible for me. And also there are other issues for example 
I can't set matrix to row or column major.


I begin to check alternatives first I begin to investigate Dlib. 
D lib matrixes are unfortunately static once created their size 
can't be expanded  and must be square matrix. This restrictions 
seem too much to me .


The best alternative seems to me scid fork of "Cristi Cobzarenco" 
link: https://github.com/cristicbz/scid. It has the basic 
features I need. But it seems last commit made 3 years ago. I 
couldn't compile it. I am getting error:


scid\internal\regionallocator.d(364): Error: safe function 
'scid.internal.region
allocator.threadLocalSegmentSize' cannot call system function 
'scid.internal.reg

ionallocator.RegionAllocatorException.this'
Error building library

Any advice about another lib or fix compile error will be welcome.


Re: Working functionally with third party libraries

2015-07-17 Thread ZombineDev via Digitalmars-d-learn

On Friday, 17 July 2015 at 17:56:51 UTC, sigod wrote:

On Friday, 17 July 2015 at 15:41:22 UTC, ZombineDev wrote:

eager approach, since it's more straightforward.


What makes you think it's always more straightforward? 
Sometimes (like in this case with MongoDB) you cannot write 
eager approach without first writing lazy one.


Well I just wrote without properly looking up what MongoDB does. 
I thought collection.find() returned the first n elements, not a 
iterator (cursor in MongoDB's terms) and that it would be 
additional work split those n elements.

Anyway, thanks for the correction, now I am bit more educated ;)


Virtual value types during compile-time for static type safety, static optimizations and function overloading.

2015-07-17 Thread Tamas via Digitalmars-d-learn

I got inspired by Andrei's "Generic Programming Must Go" talk:
https://www.youtube.com/watch?v=mCrVYYlFTrA

I.e. writing functions with static if-s, based on what we know 
about the input.

So the question is how to annotate the input variables?

Adam showed an excellent solution for this, by wrapping the value 
into a struct, and using alias: 
http://stackoverflow.com/questions/31442059/virtual-static-value-types


Unfortunately, it's not without runtime penalty. I have checked 
this idea with ints, against the generated asm.dlang.org code. 
Unfortunately the struct wrapper results in longer asm code. In 
theory such run-time penalty is not necessary, as everything is 
available compile-time.


To understand my use-case, here is an example "math library" that 
skips certain validations or computations altogether, whether 
some properties of the input can be inferred from how the value 
was produced:


import std.math : sqrt;
import std.conv;

struct Positive {
int num;
alias num this;
}

Positive abs(T)(T n) {
static if (is(T == Positive)) {
return n;
}
if (n >= 0) return Positive(n);
return Positive(-n);
}

Positive isqrt(T)(T x) {
static if (is(T == Positive)) {
return Positive(sqrt(x.to!float).to!int);
}
if (x<0) {
throw new Exception("no root for negative numbers");
}
return Positive(sqrt(x.to!float).to!int);
}

unittest {
assert(abs(-4) == 4); // full abs runs
	assert(isqrt(4).abs() == 2); // full isqrt runs, abs returns n 
immediately.
	assert(abs(-4).isqrt() == 2); // full abs runs, isqrt return 
immediately, skipping validation;

}

Although this code is fully operational, presents nice api and 
compile-time optimizations, the extra Struct wrapper is not 
without runtime penalty.


Is there a solution that results the same static optimizations, 
but has no runtime penalty, i.e. the functions just operates with 
ints? (At least when compiled)


Thanks, Tamas



Can you add a remote repository to DUB?

2015-07-17 Thread Zekereth via Digitalmars-d-learn

All I can find is add-local. Thanks!


Re: How to convert byte array to float

2015-07-17 Thread Jonathan M Davis via Digitalmars-d-learn
On Friday, July 17, 2015 18:43:26 DLangLearner via Digitalmars-d-learn wrote:
> Excuse me for my trivial question, but I'd like to know how to
> convert byte array to float? What I could think of are
> cast(float)(byte[]) and to!float(byte[]) but they do not work for
> me. Thanks!

You could use std.bitmanip.peek or std.bitmanip.read - though you do need to
make sure that you're telling it the right endianness, depending on how the
array of bytes was generated.

- Jonathan M Davis



Re: How to convert byte array to float

2015-07-17 Thread DLangLearner via Digitalmars-d-learn

On Friday, 17 July 2015 at 18:58:33 UTC, byron wrote:

On Friday, 17 July 2015 at 18:53:24 UTC, byron wrote:

On Friday, 17 July 2015 at 18:43:27 UTC, DLangLearner wrote:
Excuse me for my trivial question, but I'd like to know how 
to convert byte array to float? What I could think of are 
cast(float)(byte[]) and to!float(byte[]) but they do not work 
for me. Thanks!


You want to include [] in the cast so:



byte[] b = [1, 2, 3, 4]
byte[] f = cast(float[])b;

writeln(b);
writeln(f);

You can even cast on a slice:

byte[] b = [1, 2, 3, 4, 5, 6, 7, 8]
byte[] f = cast(float[])b[4..8];


Ah I miss read, if you want as a float, not a float array you 
can do:


byte[] b = [1, 2, 3, 4];
float f = *cast(float*)b.ptr;

not sure if there is a better way


thanks for quick reply, i'll plug above lines into my codes.


Re: How to convert byte array to float

2015-07-17 Thread byron via Digitalmars-d-learn

On Friday, 17 July 2015 at 19:03:46 UTC, Jacob Carlborg wrote:

On 2015-07-17 20:58, byron wrote:

Ah I miss read, if you want as a float, not a float array you 
can do:


byte[] b = [1, 2, 3, 4];
float f = *cast(float*)b.ptr;

not sure if there is a better way


I think a union can be used as well, not sure if it's better 
though.


not a bad idea.

testing on asm.dlang.org both reduce to the same assembly
(-release -inline -O)

float pointerTest(inout byte[4] b) {
   return *cast(float*)b.ptr;
}

float unionTest(inout byte[4] b) {
  union U {
   byte[4] b;
float f;
  }
  return U(b).f;
}


Re: Template function that accept strings and array of strings

2015-07-17 Thread Jacob Carlborg via Digitalmars-d-learn

On 2015-07-17 19:25, badlink wrote:


My fault, I didn't test the variadic function enough and jumped to
conclusion.
It actually works well http://pastebin.com/R4EHuBLh


Cool :)

Sometimes D developers think templates will be needed to solve everything.

--
/Jacob Carlborg


Re: Environment variable for application storage under OSX ?

2015-07-17 Thread Jacob Carlborg via Digitalmars-d-learn

On 2015-07-17 15:27, anonymous wrote:


Ok so my sample can be rewritten


static this() {
  version(Win32) p = environment.get("APPDATA");
  version(linux) p = "/home/" ~ environment.get("USER");
  version(OSX) p = environment.get("HOME") ~ /Library/Application
Support/;
}
---


Ideally you should hard code the values like this. BTW, why don't you 
use the HOME environment variable on Linux.



I really wish it could be possible to buy and setup OSX on any
hardware...I will never buy a mac just to test the portability of a
couple of projects 1 hour per week...


It's possible to run OS X on non-Apple computers, including virtual 
machines. But this is not the place to discuss this.


--
/Jacob Carlborg


Re: How to convert byte array to float

2015-07-17 Thread Jacob Carlborg via Digitalmars-d-learn

On 2015-07-17 20:58, byron wrote:


Ah I miss read, if you want as a float, not a float array you can do:

byte[] b = [1, 2, 3, 4];
float f = *cast(float*)b.ptr;

not sure if there is a better way


I think a union can be used as well, not sure if it's better though.

--
/Jacob Carlborg


Re: How to convert byte array to float

2015-07-17 Thread byron via Digitalmars-d-learn

On Friday, 17 July 2015 at 18:53:24 UTC, byron wrote:

On Friday, 17 July 2015 at 18:43:27 UTC, DLangLearner wrote:
Excuse me for my trivial question, but I'd like to know how to 
convert byte array to float? What I could think of are 
cast(float)(byte[]) and to!float(byte[]) but they do not work 
for me. Thanks!


You want to include [] in the cast so:



byte[] b = [1, 2, 3, 4]
byte[] f = cast(float[])b;

writeln(b);
writeln(f);

You can even cast on a slice:

byte[] b = [1, 2, 3, 4, 5, 6, 7, 8]
byte[] f = cast(float[])b[4..8];


Ah I miss read, if you want as a float, not a float array you can 
do:


byte[] b = [1, 2, 3, 4];
float f = *cast(float*)b.ptr;

not sure if there is a better way



Re: LNK2019 error from using a function pointer to core.bitop functions?

2015-07-17 Thread Matthew Gamble via Digitalmars-d-learn

On Friday, 17 July 2015 at 15:49:46 UTC, Roland Hadinger wrote:

On Friday, 17 July 2015 at 15:47:39 UTC, Roland Hadinger wrote:
Otherwise, I'd use templates and an alias. Maybe this will 
result in faster code:


bool opIndexAssign(bool value, size_t[2] inds)
{
void impl(bool b)(size_t[2] inds)
{
static if(b)
alias btx = bts;
else
alias btx = btr;

// code from opIndexAssign goes here...
// for (size_t i = startBitInd; ...
}

if( value )
impl!true(inds);
else
impl!false(inds);


  return value; // oops

}


Roland, both of your solutions work perfectly. Thank you.

You brought up the issue of performance. Performance may be an 
issue for certain use-cases when the function is called many 
times and the values of inds[1] - inds[0] is small (e.g less than 
257). In these cases at least half the work in the function will 
be done with bts/btr. However, for larger ranges there is an 
optimization (not shown) that eliminates the need to call bts/btr 
in the middle region of the range.


Why do you think the second solution would be faster than the 
first? And do you also think that the rolled out version 
replicating the code in the "if" and "else" blocks replacing bts 
with btr would be even faster since it eliminates the need for 
any additional function call? I guess I'll have to profile all 
three versions when my program matures enough be used with a 
"big" data example.


Sorry for all the questions. I really appreciate your help.

Best, Matt


Re: How to convert byte array to float

2015-07-17 Thread byron via Digitalmars-d-learn

On Friday, 17 July 2015 at 18:43:27 UTC, DLangLearner wrote:
Excuse me for my trivial question, but I'd like to know how to 
convert byte array to float? What I could think of are 
cast(float)(byte[]) and to!float(byte[]) but they do not work 
for me. Thanks!


You want to include [] in the cast so:



byte[] b = [1, 2, 3, 4]
byte[] f = cast(float[])b;

writeln(b);
writeln(f);

You can even cast on a slice:

byte[] b = [1, 2, 3, 4, 5, 6, 7, 8]
byte[] f = cast(float[])b[4..8];



How to convert byte array to float

2015-07-17 Thread DLangLearner via Digitalmars-d-learn
Excuse me for my trivial question, but I'd like to know how to 
convert byte array to float? What I could think of are 
cast(float)(byte[]) and to!float(byte[]) but they do not work for 
me. Thanks!


Re: Comparison of struct with Nullable member

2015-07-17 Thread anonymous via Digitalmars-d-learn

On Friday, 17 July 2015 at 12:18:56 UTC, TC wrote:

Hello,
I came around a strange behavior and I'm not sure if it is a 
bug or feature.


import std.typecons : Nullable;
struct Foo
{
string bar;
Nullable!int baz;
}

auto a = Foo("bb");
auto b = Foo("bb");
assert(a == b);

This ends up with: Called `get' on null Nullable!int

But if I change bar to be an int for example, than it passes ok.
I would expect this to pass ok.

Tested on dmd 2.067.1 win64


Bug. I reported a reduced version as 
.


Re: Working functionally with third party libraries

2015-07-17 Thread sigod via Digitalmars-d-learn

On Friday, 17 July 2015 at 15:41:22 UTC, ZombineDev wrote:

eager approach, since it's more straightforward.


What makes you think it's always more straightforward? Sometimes 
(like in this case with MongoDB) you cannot write eager approach 
without first writing lazy one.


Re: Template function that accept strings and array of strings

2015-07-17 Thread badlink via Digitalmars-d-learn

On Friday, 17 July 2015 at 12:58:58 UTC, Jacob Carlborg wrote:
I don't think I really understand how you want to use/call the 
function. Could you give an example with all the different 
types you want to call the function?


My fault, I didn't test the variadic function enough and jumped 
to conclusion.

It actually works well http://pastebin.com/R4EHuBLh


Re: How to use core.thread.Thread

2015-07-17 Thread aki via Digitalmars-d-learn

On Friday, 17 July 2015 at 14:14:41 UTC, byron wrote:
Since I have yet to use or see anyone use shared in a useful 
way I avoid it.

It's one way to avoid it. So, you mean you always use send/receive
when you need threading?

I did small test to know the memory layout.

import core.atomic;
int foo;
shared int sfoo;
class DerivedThread : Thread {
int count;
shared int scount;
this() {
super(&run);
}
private void run() {
inc();
writefln("at thread: foo=%s, &foo=%s, sfoo=%s, &sfoo=%s", 
foo, &foo, sfoo, &sfoo);
writefln("at thread: count=%s, &count=%s, scount=%s, 
&scount=%s", count, &count, scount, &scount);

}
void inc() {
++foo;
atomicOp!"+="(sfoo, 1);
++count;
atomicOp!"+="(scount, 1);
}
}
void main() {
auto thr = new DerivedThread();
thr.start();
thr.inc();
thr.join();
writefln("  at main: foo=%s, &foo=%s, sfoo=%s, &sfoo=%s", 
foo, &foo, sfoo, &sfoo);
writefln("  at main: count=%s, &count=%s, scount=%s, 
&scount=%s", thr.count, &thr.count, thr.scount, &thr.scount);

}

at thread: foo=1, &foo=A33580, sfoo=2, &sfoo=5541E4
at thread: count=2, &count=240178, scount=2, &scount=24017C
  at main: foo=1, &foo=984B28, sfoo=2, &sfoo=5541E4
  at main: count=2, &count=240178, scount=2, &scount=24017C

That means Thread object "thr" is always shared while
global foo is not shared because it has different memory location.
In my understanding, shared is not only checking something at 
compile time,

but also it affects on the memory layout.

Aki.


Re: Comparison of struct with Nullable member

2015-07-17 Thread Meta via Digitalmars-d-learn

On Friday, 17 July 2015 at 15:52:45 UTC, TC wrote:

On Friday, 17 July 2015 at 15:30:42 UTC, Meta wrote:

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

I'll probably be able to submit a PR for this sometime in the 
next few days.


Thanks.
What I don't get is why this one works ok?

import std.typecons : Nullable;
struct Foo
{
int bar;
Nullable!int baz;
}
auto a = Foo(1);
auto b = Foo(1);
assert(a == b);


This may be because if your struct only contains primitive 
values, the compiler will just do a memcmp to determine equality. 
Don't quote me on that though.


Also is there some "nicer" way to init the struct with nullable 
member with default constructor?
Now I'm using Foo(1, Nullable!int(2)) but just Foo(1, 2) would 
be much nicer.

Same with calling functions with nullable params.


You can defined a custom constructor in Foo which will construct 
the Nullable.


struct Foo
{
this(int n1, int n2)
{
bar = n1;
baz = n2;
}

//...
}


Re: LNK2019 error from using a function pointer to core.bitop functions?

2015-07-17 Thread Roland Hadinger via Digitalmars-d-learn

On Thursday, 16 July 2015 at 03:24:54 UTC, Matthew Gamble wrote:
This member function of my struct uses a function pointer btx. 
When the line declaring the function pointer is present I get a 
LNK2019 error: unresolved external symbol.


Just guessing, probably because bts and btr are intrinsics?

If performance is not that important, you can always do this at 
the start of your opIndexAssign method:


static int bts(size_t* p, size_t bitnum) { return .bts(p, 
bitnum); }
static int btr(size_t* p, size_t bitnum) { return .btr(p, 
bitnum); }

int function(size_t*, size_t) btx = (value) ? &bts : &btr;

Otherwise, I'd use templates and an alias. Maybe this will result 
in faster code:


bool opIndexAssign(bool value, size_t[2] inds)
{
void impl(bool b)(size_t[2] inds)
{
static if(b)
alias btx = bts;
else
alias btx = btr;

// code from opIndexAssign goes here...
// for (size_t i = startBitInd; ...
}

if( value )
impl!true(inds);
else
impl!false(inds);
}



Re: Comparison of struct with Nullable member

2015-07-17 Thread TC via Digitalmars-d-learn

On Friday, 17 July 2015 at 15:30:42 UTC, Meta wrote:

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

I'll probably be able to submit a PR for this sometime in the 
next few days.


Thanks.
What I don't get is why this one works ok?

import std.typecons : Nullable;
struct Foo
{
int bar;
Nullable!int baz;
}
auto a = Foo(1);
auto b = Foo(1);
assert(a == b);

Also is there some "nicer" way to init the struct with nullable 
member with default constructor?
Now I'm using Foo(1, Nullable!int(2)) but just Foo(1, 2) would be 
much nicer.

Same with calling functions with nullable params.


Re: Working functionally with third party libraries

2015-07-17 Thread ZombineDev via Digitalmars-d-learn

On Friday, 17 July 2015 at 15:41:22 UTC, ZombineDev wrote:
I'm almost certain that the D database driver returns eagerly 
all the results that you've requested. The lazy stuff should 
happen when you start doing range operations after the results 
are returned from the database. It's not impossible to lazily 
query the database, but I think that the developers have chosen 
the eager approach, since it's more straightforward.




Discard this. I didn't read the previous comments.


Re: LNK2019 error from using a function pointer to core.bitop functions?

2015-07-17 Thread Roland Hadinger via Digitalmars-d-learn

On Friday, 17 July 2015 at 15:47:39 UTC, Roland Hadinger wrote:
Otherwise, I'd use templates and an alias. Maybe this will 
result in faster code:


bool opIndexAssign(bool value, size_t[2] inds)
{
void impl(bool b)(size_t[2] inds)
{
static if(b)
alias btx = bts;
else
alias btx = btr;

// code from opIndexAssign goes here...
// for (size_t i = startBitInd; ...
}

if( value )
impl!true(inds);
else
impl!false(inds);


  return value; // oops

}




Re: Working functionally with third party libraries

2015-07-17 Thread ZombineDev via Digitalmars-d-learn
On Friday, 17 July 2015 at 09:07:29 UTC, Jarl André Hübenthal 
wrote:
Thanks. Its a lot more cleaner and syntactically readable 
having .array at the end. But about laziness the same applies 
to clojure and scala. In clojure you must force evaluate the 
list, in scala you must to mostly the same as in D, put a 
toList or something at the end. Or loop it. But its pretty nice 
to know that there is laziness in D, but when I query mongo I 
expect all docs to be retrieved, since there are no paging in 
the underlying queries? Thus, having a lazy functionality on 
top of non lazy db queries seem a bit off dont you think?


I'm almost certain that the D database driver returns eagerly all 
the results that you've requested. The lazy stuff should happen 
when you start doing range operations after the results are 
returned from the database. It's not impossible to lazily query 
the database, but I think that the developers have chosen the 
eager approach, since it's more straightforward.


Currently, in D most of the laziness is a convention, rather than 
something directly built into the language. There are many 
features that enable (indirectly) effective and easy to use lazy 
algorithms, but these features are have many other uses 
(templates, auto type deduction, compile-time reflection, etc.).


The only two direct features are:
1) foreach can iterate over ranges (objects of structs or classes 
for which isInputRange is true. Here's an example:


import std.algorithm.iteration : map, filter;

foreach (name; persons.filter!(p => p.age > 18).map!(p => p.name))
writeln(name);

import std.range.primitives : isInputRange;

static assert (
isInputRange!(
typeof(
   persons.filter!(p => p.age > 18).map!(p => p.name)
)
) == true
);

See http://dlang.org/phobos/std_range_primitives.html#isInputRange

2) The lazy keyword - when you annotate function parameters with 
lazy they are evaluated not at the caller site, but only when 
needed like in other more traditional functional languages. For 
example:


void calculate(int[] numbers)
{
import std.format : format;
// ...

logErrorIf(numbers[3] < 5,
format("Expected value < 5, but got %s !", numbers[3]));
//  ^~~~ this is only evaluated

// ...
}

void logErrorIf(bool condition, lazy string error_message)
{
if (condition)
writeln(message);
//  ^~~~ here, if the condition is true
}

( In D string is just an alias to immutable(char)[], so the above 
signature is identical to this:
void logErrorIf(bool condition, lazy immutable(char)[] 
error_message) )


You can think of lazy parameters as implicit lambdas that return 
the expression passed as argument only when called.
Here you can learn more about the lazy keyword 
http://dlang.org/lazy-evaluation.html


Even though we have 'lazy' built into the language, most of the 
lazy algorithms do not use it. I just made a quick search through 
druntime and phobos for 'lazy' and 'range' (don't how correct it 
was - I admit I'm a unix noob) and here's what I got:


// (I have DMD v2.067.1 installed)

// lazy at the head of the function parameter list or in the tail
$ find /usr/include/dmd/ -name '*.d' -exec cat {} \; | grep -c 
'(lazy \|, lazy '

74

// just containing lazy
$ find /usr/include/dmd/ -name '*.d' -exec cat {} \; | grep -c 
'lazy'

138

// just containing range
$ find /usr/include/dmd/ -name '*.d' -exec cat {} \; | grep -c 
'range'

3548

I think that this because ranges are a more generic, flexible and 
powerful abstraction, and are more efficient maybe because 
they're easier to optimize to simple loops (eg. I've seen that 
the ldc compiler handles them very well).
'lazy' is still useful but generally I have seen it used for more 
simpler stuff (like the above 'lazy' example), and not for 
propagating state through range pipelines (or more simply - 
function chaining).


So you'll see both functions that are lazy and functions that are 
not throughout Phobos (and most use ranges, as you can see from 
the results).


Generally you can distinguish range functions from others by 
their signatures. Since most ranges in D are templated structs 
and not classes inheriting some interface
(though there some, see 
http://dlang.org/phobos/std_range_interfaces#InputRange),
functions that operate on ranges are templated at least on one 
range type:


// Check if the function 'fun' is really a predicate
enum isUnaryPredicate(alias fun, T) =
is( typeof( fun(T.init) ) : bool);

import std.range.primitives: isInputRange, ElementType;

// templated on predicate and range type
//v  ~~v~~
auto filter1(alias predicate, Range)(Range range)
if (isInputRange!Range &&   //   <- some template
isUnaryPredicate!(predicate, ElementType!Range))
//  ^~  constraints
{
return ...
}

// Even if you can't look at the function body, you
// can guess that it can't be lazy becau

Re: Comparison of struct with Nullable member

2015-07-17 Thread Meta via Digitalmars-d-learn

On Friday, 17 July 2015 at 12:18:56 UTC, TC wrote:

Hello,
I came around a strange behavior and I'm not sure if it is a 
bug or feature.


import std.typecons : Nullable;
struct Foo
{
string bar;
Nullable!int baz;
}

auto a = Foo("bb");
auto b = Foo("bb");
assert(a == b);

This ends up with: Called `get' on null Nullable!int

But if I change bar to be an int for example, than it passes ok.
I would expect this to pass ok.

Tested on dmd 2.067.1 win64


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

I'll probably be able to submit a PR for this sometime in the 
next few days.


Re: How to use core.thread.Thread

2015-07-17 Thread byron via Digitalmars-d-learn

On Friday, 17 July 2015 at 07:56:48 UTC, aki wrote:

On Thursday, 16 July 2015 at 09:17:47 UTC, Daniel Kozák wrote:

class DerivedThread : Thread {
shared int count = 0;
}


I thought shared is only for whole of the object.
auto thr = new DerivedThread();
Here, "thr" is not shared but it's member thr.count is shared?
But if it's not shared, thr object referred by main thread and
"this" reference of DerivedThread.run() are different?
What happen if there are both shared and unshared member exists?

class DerivedThread : Thread {
shared int count = 0;
int foo = 0;
}

Umm. I can't imagine what's the memory layout of this object.


Since I have yet to use or see anyone use shared in a useful way 
I avoid it.  But I normally think of it like const (not 
immutable).  Shared wont change the memory layout (last time I 
checked) its purpose is meant to help you write correct threaded 
code, ie make sure you synchronize access to it, its not synced 
for you.  You should read the chapter from Andrie's book.


There is also a lot of good stuff in the std lib the helps avoid 
doing things manually.


Re: Infinite range of nullable elements

2015-07-17 Thread Roland Hadinger via Digitalmars-d-learn

On Friday, 17 July 2015 at 12:44:57 UTC, anonymous wrote:
The building blocks are there. You're `map`ping the original 
range to `Nullable`, and then you're `chain`ing an infinite 
range (`cycle`) of nulls behind.



import std.range: isInputRange;

auto cushion(R)(R r)
if (isInputRange!R)
{
import std.algorithm: map;
import std.range: chain, cycle, ElementType, only;
import std.typecons: Nullable;

alias E = ElementType!R;
alias NE = Nullable!E;

return chain(r.map!NE, NE().only.cycle);
}



Nice! I didn't think of using 'chain'.



Re: Comparison of struct with Nullable member

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

On Friday, 17 July 2015 at 12:18:56 UTC, TC wrote:

Hello,
I came around a strange behavior and I'm not sure if it is a 
bug or feature.


import std.typecons : Nullable;
struct Foo
{
string bar;
Nullable!int baz;
}

auto a = Foo("bb");
auto b = Foo("bb");
assert(a == b);

This ends up with: Called `get' on null Nullable!int

But if I change bar to be an int for example, than it passes ok.
I would expect this to pass ok.

Tested on dmd 2.067.1 win64


what is happening is the complier generated default opEquals is 
accessing the payload for Nullable!T without checking for null 
(which as you've written `Foo("bb")` this constructs a and b as 
`Foo("bb",(Nullable!int).init)` i.e. in the null state)


why nullables don't automatically check for null when comparing 
for equality idk.


you can make this work by defining your own opEquals that 
explicitly checks for nulls.





Re: Environment variable for application storage under OSX ?

2015-07-17 Thread anonymous via Digitalmars-d-learn

On Friday, 17 July 2015 at 07:54:43 UTC, FreeSlave wrote:

On Friday, 17 July 2015 at 07:33:43 UTC, Anonymous wrote:

On Friday, 17 July 2015 at 07:14:24 UTC, FreeSlave wrote:

On Thursday, 16 July 2015 at 21:12:05 UTC, anonymous wrote:

I have the following code, working under Win and Linux:

---
import std.process: environment;

immutable string p;

static this() {
version(Win32) p = environment.get("APPDATA");
version(linux) p = "/home/" ~ environment.get("USER");
version(OSX) p = "?";
}
---

what would be the OSX equivalent (to get the path where the 
applications data are commonmly stored)?


Hello. You may take a look at this library 
https://github.com/MyLittleRobo/standardpaths
OSX version uses Carbon though. You may want to use Cocoa API 
(which is newer), but it's Objective-C.
Also you may consider standard path for data storage without 
using any api or spec. It's usually $HOME/Library/Application 
Support/ on OSX.


So for a software named 'SuperDownloader2015'  it would be

$HOME/Library/Application Support/SuperDownloader2015

right ?

so it's not user-specific and it's writable for the current 
user ?

sorry but it looks a bit strange, anyone can confirm ?


It is user specific obviously since it's in user home.
Can you elaborate on what do you want exactly?
From Windows and Linux examples you provided I assumed you need 
user-specific paths (APPDATA is defined per user on Windows). 
System-wide application data path is different.


Ok so my sample can be rewritten


static this() {
 version(Win32) p = environment.get("APPDATA");
 version(linux) p = "/home/" ~ environment.get("USER");
 version(OSX) p = environment.get("HOME") ~ 
/Library/Application Support/;

}
---

I really wish it could be possible to buy and setup OSX on any 
hardware...I will never buy a mac just to test the portability of 
a couple of projects 1 hour per week...


Anyway thx all for your answers.


Re: Infinite range of nullable elements

2015-07-17 Thread Roland Hadinger via Digitalmars-d-learn

On Friday, 17 July 2015 at 10:19:22 UTC, Márcio Martins wrote:

On Friday, 17 July 2015 at 07:42:09 UTC, Roland Hadinger wrote:
At this moment I'm tempted to implement a function taking a 
range of elements E and returning an infinite range of 
Nullable!E.


[...]


Wouldn't it still require the algorithms to check if an element 
isNull()?


Naturally. But this check can be done further down the function 
chain,

so all the functions before will see an infinite range.

I'm currently writing a lexer (big loop with two levels of switch 
statements inside) that needs to some looking ahead in multiple 
states. Normally, each of those lookaheads would require a check 
for "end of input". I want to avoid this because of the large 
number of states.




Re: Environment variable for application storage under OSX ?

2015-07-17 Thread Jacob Carlborg via Digitalmars-d-learn

On 2015-07-17 09:14, FreeSlave wrote:


Hello. You may take a look at this library
https://github.com/MyLittleRobo/standardpaths
OSX version uses Carbon though. You may want to use Cocoa API (which is
newer), but it's Objective-C.


DMD master now has some initial support for Objective-C.

--
/Jacob Carlborg


Re: Template function that accept strings and array of strings

2015-07-17 Thread Jacob Carlborg via Digitalmars-d-learn

On 2015-07-16 18:49, badlink wrote:


The method with the variadic function works, but I would have to use
only one parameter because this doesn't work:
fun(const(char[])[] a, const(char[])[] b ...)
and is a bit ugly in my use case ...


I don't think I really understand how you want to use/call the function. 
Could you give an example with all the different types you want to call 
the function?


--
/Jacob Carlborg


Re: Working functionally with third party libraries

2015-07-17 Thread Kagamin via Digitalmars-d-learn
On Friday, 17 July 2015 at 09:07:29 UTC, Jarl André Hübenthal 
wrote:
Or loop it. But its pretty nice to know that there is laziness 
in D, but when I query mongo I expect all docs to be retrieved, 
since there are no paging in the underlying queries? Thus, 
having a lazy functionality on top of non lazy db queries seem 
a bit off dont you think?


From the client point of view db is sort of lazy: data is 
received from server as needed. Why would you want to put all 
data into an array before processing it? Why can't you process it 
from the range directly?


Re: Environment variable for application storage under OSX ?

2015-07-17 Thread Jacob Carlborg via Digitalmars-d-learn

On 2015-07-16 23:12, anonymous wrote:

I have the following code, working under Win and Linux:

---
import std.process: environment;

immutable string p;

static this() {
 version(Win32) p = environment.get("APPDATA");
 version(linux) p = "/home/" ~ environment.get("USER");
 version(OSX) p = "?";
}
---

what would be the OSX equivalent (to get the path where the applications
data are commonmly stored)?


They are usually defined as constants in Objective-C. You can read more 
about it here [1][2][3].


You can also use the CoreServices framework which has a C API [4]. But I 
think it's deprecated and the preferred way is to use the Objective-C API's.


[1] 
https://developer.apple.com/library/mac/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/AccessingFilesandDirectories/AccessingFilesandDirectories.html#//apple_ref/doc/uid/TP40010672-CH3-SW3


[2] 
https://developer.apple.com/library/mac/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/AccessingFilesandDirectories/AccessingFilesandDirectories.html#//apple_ref/doc/uid/TP40010672-CH3-SW11


[3] 
https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Constants/index.html#//apple_ref/c/econst/NSApplicationSupportDirectory


[4] 
http://stackoverflow.com/questions/5123361/finding-library-application-support-from-c


--
/Jacob Carlborg


Re: Environment variable for application storage under OSX ?

2015-07-17 Thread Jacob Carlborg via Digitalmars-d-learn

On 2015-07-17 09:33, Anonymous wrote:


So for a software named 'SuperDownloader2015'  it would be

$HOME/Library/Application Support/SuperDownloader2015

right ?

so it's not user-specific and it's writable for the current user ?
sorry but it looks a bit strange, anyone can confirm ?


Yes, that's correct. Some applications skip the "Application Support" 
directory and creates the "SuperDownloader2015" directory directly in 
$HOME/Library


--
/Jacob Carlborg


Re: Working functionally with third party libraries

2015-07-17 Thread via Digitalmars-d-learn

On Friday, 17 July 2015 at 11:47:30 UTC, sigod wrote:
On Friday, 17 July 2015 at 09:07:29 UTC, Jarl André Hübenthal 
wrote:
But its pretty nice to know that there is laziness in D, but 
when I query mongo I expect all docs to be retrieved, since 
there are no paging in the underlying queries? Thus, having a 
lazy functionality on top of non lazy db queries seem a bit 
off dont you think?


Not true. There's paging in MongoDB. See [Cursors][0] and 
documentation for `find` method. Also, look at [`vibe.d`'s 
implementation][1].


[0]: http://docs.mongodb.org/manual/core/cursors/
[1]: 
https://github.com/rejectedsoftware/vibe.d/blob/master/source/vibe/db/mongo/cursor.d


+1 good to know.


Re: Infinite range of nullable elements

2015-07-17 Thread anonymous via Digitalmars-d-learn

On Friday, 17 July 2015 at 07:42:09 UTC, Roland Hadinger wrote:
Here's how I would implement the basic behaviour (could be 
extended to also forward bidirectional and random access 
functions):


---
auto cushion(R)(R r)
if (isInputRange!R)
{
static if (isInfinite!R) { return r; } else {

struct _Cushion(R)
{
R r;

alias E = ElementType!R;
alias NE = Nullable!E;

@property bool empty() { return false; }

@property NE front()
{
return !r.empty ? NE(r.front) : NE();
}

void popFront()
{
if (!r.empty) r.popFront();
}
}

return _Cushion!R(r);
}
}

---

I didn't find anything like this Phobos. Did I miss something?


The building blocks are there. You're `map`ping the original 
range to `Nullable`, and then you're `chain`ing an infinite range 
(`cycle`) of nulls behind.



import std.range: isInputRange;

auto cushion(R)(R r)
if (isInputRange!R)
{
import std.algorithm: map;
import std.range: chain, cycle, ElementType, only;
import std.typecons: Nullable;

alias E = ElementType!R;
alias NE = Nullable!E;

return chain(r.map!NE, NE().only.cycle);
}



Comparison of struct with Nullable member

2015-07-17 Thread TC via Digitalmars-d-learn

Hello,
I came around a strange behavior and I'm not sure if it is a bug 
or feature.


import std.typecons : Nullable;
struct Foo
{
string bar;
Nullable!int baz;
}

auto a = Foo("bb");
auto b = Foo("bb");
assert(a == b);

This ends up with: Called `get' on null Nullable!int

But if I change bar to be an int for example, than it passes ok.
I would expect this to pass ok.

Tested on dmd 2.067.1 win64


Re: Working functionally with third party libraries

2015-07-17 Thread sigod via Digitalmars-d-learn
On Friday, 17 July 2015 at 09:07:29 UTC, Jarl André Hübenthal 
wrote:
But its pretty nice to know that there is laziness in D, but 
when I query mongo I expect all docs to be retrieved, since 
there are no paging in the underlying queries? Thus, having a 
lazy functionality on top of non lazy db queries seem a bit off 
dont you think?


Not true. There's paging in MongoDB. See [Cursors][0] and 
documentation for `find` method. Also, look at [`vibe.d`'s 
implementation][1].


[0]: http://docs.mongodb.org/manual/core/cursors/
[1]: 
https://github.com/rejectedsoftware/vibe.d/blob/master/source/vibe/db/mongo/cursor.d


Re: Infinite range of nullable elements

2015-07-17 Thread via Digitalmars-d-learn

On Friday, 17 July 2015 at 07:42:09 UTC, Roland Hadinger wrote:
At this moment I'm tempted to implement a function taking a 
range of elements E and returning an infinite range of 
Nullable!E.


[...]


Wouldn't it still require the algorithms to check if an element 
isNull()? Calling get() on a null element will assert().


I'm wondering why it asserts instead of throwing.


Re: Working functionally with third party libraries

2015-07-17 Thread via Digitalmars-d-learn

On Thursday, 16 July 2015 at 20:41:21 UTC, ZombineDev wrote:
On Thursday, 16 July 2015 at 20:17:54 UTC, Jarl André Hübenthal 
wrote:

On Thursday, 16 July 2015 at 20:00:38 UTC, Ali Çehreli wrote:
On 07/16/2015 12:35 PM, "Jarl 
=?UTF-8?B?QW5kcsOpIEjDvGJlbnRoYWwi?= " 
wrote:

Hi

using mongo with vibe.d is easy. But I would like to skip 
the foreach on

MongoCursor?

I mean, I want to use map!, filter! and reduce! on the 
resulting docs.
Is there a fast way to convert MongoCursor to an array 
without resolving

to ugly for loops with appender! ?


I've never used MongoCursor but judging from the fact that it 
has empty, front, and popFront(), it is an InputRange:


  http://vibed.org/api/vibe.db.mongo.cursor/MongoCursor

Have you tried using it with map and others? What errors do 
you get?


Ali


Ah well I got another error now. Using the following code:

Resource[] getResource() {
auto coll = client.getCollection("app.resource");
		return coll.find().map!(doc => deserialize!(BsonSerializer, 
Resource)(doc));

}

I get this error:

src/app.d(51,21): Error: cannot implicitly convert expression 
(map(coll.find())) of type MapResult!(__lambda1, 
MongoCursor!(Bson, Bson, typeof(null))) to Resource[]


Most of the functions from std.algorithm and std.range return a 
lazy range which you need to iterate over go get its elements.
To turn those ranges to an array you need add a .array at the 
end (http://dlang.org/phobos/std_array#array). Here's a larger 
example: http://d.readthedocs.org/en/latest/introduction.html.


Another option is to return the elements as a range (by making 
return type of your function auto), instead of putting them 
into a newly allocated array (with .array). This way may be a 
bit more work (delaying the call to .array), but it can be 
quite efficient because it removes the need to allocate memory.


Thanks. Its a lot more cleaner and syntactically readable having 
.array at the end. But about laziness the same applies to clojure 
and scala. In clojure you must force evaluate the list, in scala 
you must to mostly the same as in D, put a toList or something at 
the end. Or loop it. But its pretty nice to know that there is 
laziness in D, but when I query mongo I expect all docs to be 
retrieved, since there are no paging in the underlying queries? 
Thus, having a lazy functionality on top of non lazy db queries 
seem a bit off dont you think?


Getting Nth Row and Column from MatrixView, Scid library

2015-07-17 Thread kerdemdemir via Digitalmars-d-learn

Hi,

I want to use Scid  matrixes for implementing GMM algorithm. I 
will start by writing Naive Bayes with linear and quadratic 
decision boundaries .


I reliaze Scid does not provides any functions for getting 
spesific row or coloumn. Matrixwview class only supplies opIndex 
function.


Is there anything that I am missing or what is the best to get 
nth column or row with Scid library.


Link to Scid lib: 
http://www.kyllingen.net/code/scid/doc/scid_matrix.html


Re: How to use core.thread.Thread

2015-07-17 Thread aki via Digitalmars-d-learn

On Thursday, 16 July 2015 at 09:17:47 UTC, Daniel Kozák wrote:

class DerivedThread : Thread {
shared int count = 0;
}


I thought shared is only for whole of the object.
auto thr = new DerivedThread();
Here, "thr" is not shared but it's member thr.count is shared?
But if it's not shared, thr object referred by main thread and
"this" reference of DerivedThread.run() are different?
What happen if there are both shared and unshared member exists?

class DerivedThread : Thread {
shared int count = 0;
int foo = 0;
}

Umm. I can't imagine what's the memory layout of this object.



Re: Environment variable for application storage under OSX ?

2015-07-17 Thread FreeSlave via Digitalmars-d-learn

On Friday, 17 July 2015 at 07:33:43 UTC, Anonymous wrote:

On Friday, 17 July 2015 at 07:14:24 UTC, FreeSlave wrote:

On Thursday, 16 July 2015 at 21:12:05 UTC, anonymous wrote:

I have the following code, working under Win and Linux:

---
import std.process: environment;

immutable string p;

static this() {
version(Win32) p = environment.get("APPDATA");
version(linux) p = "/home/" ~ environment.get("USER");
version(OSX) p = "?";
}
---

what would be the OSX equivalent (to get the path where the 
applications data are commonmly stored)?


Hello. You may take a look at this library 
https://github.com/MyLittleRobo/standardpaths
OSX version uses Carbon though. You may want to use Cocoa API 
(which is newer), but it's Objective-C.
Also you may consider standard path for data storage without 
using any api or spec. It's usually $HOME/Library/Application 
Support/ on OSX.


So for a software named 'SuperDownloader2015'  it would be

$HOME/Library/Application Support/SuperDownloader2015

right ?

so it's not user-specific and it's writable for the current 
user ?

sorry but it looks a bit strange, anyone can confirm ?


It is user specific obviously since it's in user home.
Can you elaborate on what do you want exactly?
From Windows and Linux examples you provided I assumed you need 
user-specific paths (APPDATA is defined per user on Windows). 
System-wide application data path is different.


Infinite range of nullable elements

2015-07-17 Thread Roland Hadinger via Digitalmars-d-learn
At this moment I'm tempted to implement a function taking a range 
of elements E and returning an infinite range of Nullable!E.


With this function ("cushion" for a lack of better name) I could 
do:


auto a = [0,1,2,3,4,5,6,7,8,9];

foreach (e ; a.cushion.take(20))
writeln(e); // exactly 20 elements

This would allow chaining together algorithms that need to look 
ahead in a range.


Here's how I would implement the basic behaviour (could be 
extended to also forward bidirectional and random access 
functions):


---
auto cushion(R)(R r)
if (isInputRange!R)
{
static if (isInfinite!R) { return r; } else {

struct _Cushion(R)
{
R r;

alias E = ElementType!R;
alias NE = Nullable!E;

@property bool empty() { return false; }

@property NE front()
{
return !r.empty ? NE(r.front) : NE();
}

void popFront()
{
if (!r.empty) r.popFront();
}
}

return _Cushion!R(r);
}
}

---

I didn't find anything like this Phobos. Did I miss something? Is 
this a bad idea for some reason?




Re: Environment variable for application storage under OSX ?

2015-07-17 Thread Anonymous via Digitalmars-d-learn

On Friday, 17 July 2015 at 07:14:24 UTC, FreeSlave wrote:

On Thursday, 16 July 2015 at 21:12:05 UTC, anonymous wrote:

I have the following code, working under Win and Linux:

---
import std.process: environment;

immutable string p;

static this() {
version(Win32) p = environment.get("APPDATA");
version(linux) p = "/home/" ~ environment.get("USER");
version(OSX) p = "?";
}
---

what would be the OSX equivalent (to get the path where the 
applications data are commonmly stored)?


Hello. You may take a look at this library 
https://github.com/MyLittleRobo/standardpaths
OSX version uses Carbon though. You may want to use Cocoa API 
(which is newer), but it's Objective-C.
Also you may consider standard path for data storage without 
using any api or spec. It's usually $HOME/Library/Application 
Support/ on OSX.


So for a software named 'SuperDownloader2015'  it would be

$HOME/Library/Application Support/SuperDownloader2015

right ?

so it's not user-specific and it's writable for the current user ?
sorry but it looks a bit strange, anyone can confirm ?




Re: Environment variable for application storage under OSX ?

2015-07-17 Thread FreeSlave via Digitalmars-d-learn

On Thursday, 16 July 2015 at 21:12:05 UTC, anonymous wrote:

I have the following code, working under Win and Linux:

---
import std.process: environment;

immutable string p;

static this() {
version(Win32) p = environment.get("APPDATA");
version(linux) p = "/home/" ~ environment.get("USER");
version(OSX) p = "?";
}
---

what would be the OSX equivalent (to get the path where the 
applications data are commonmly stored)?


Hello. You may take a look at this library 
https://github.com/MyLittleRobo/standardpaths
OSX version uses Carbon though. You may want to use Cocoa API 
(which is newer), but it's Objective-C.
Also you may consider standard path for data storage without 
using any api or spec. It's usually $HOME/Library/Application 
Support/ on OSX.