Re: scope block do not handle failure, but try-catch does

2014-12-15 Thread via Digitalmars-d-learn

On Monday, 15 December 2014 at 07:41:40 UTC, drug wrote:

On 13.12.2014 23:26, Suliman wrote:

I reread docs and understood that scope not for such case.

Next code is do what I need:
try
{
string dbname = config.getKey(dbname);
string dbpass = config.getKey(dbpass);
string dbhost = config.getKey(dbhost);
string dbport = config.getKey(dbport);
}

catch (Exception msg)
{
writeln(Can't parse config: %s, msg.msg);
}

What you need probably is the following:

string dbpass, dbhost, dbport;

{ // This bracket is intended to define new scope
// New if in the current scope from now any failure occurs
// the compiler will call writeln with message
scope(failure) writeln(Can't parse config: %s, msg.msg);

dbname = config.getKey(dbname);
dbpass = config.getKey(dbpass);
dbhost = config.getKey(dbhost);
dbport = config.getKey(dbport);
} // the current scope ends, so if a failure happens later 
writeln won't be called


Unfortunately you don't have access to the exception object 
inside the `scope(failure)` block.


Re: scope block do not handle failure, but try-catch does

2014-12-15 Thread drug via Digitalmars-d-learn

On 15.12.2014 12:22, Marc Schütz schue...@gmx.net wrote:


Unfortunately you don't have access to the exception object inside the
`scope(failure)` block.


Ah, yes, it has to be without msg.msg
scope(failure) writeln(Something is wrong);


Re: Fastest Way to Append Multiple Elements to an Array

2014-12-15 Thread John Colvin via Digitalmars-d-learn

On Sunday, 14 December 2014 at 23:16:12 UTC, Nordlöw wrote:

What's the fastest way to append multiple elements to an array?:

Either

arr ~= e1;
arr ~= e2;
arr ~= e3;

or

arr ~= [e1,e2,e3];

or some other trick?


It does somewhat depend on context but std.array.appender is 
generally a good choice. It supports appending elements 
individually, appending a range of elements and manually 
reserving extra space.


E.g.

auto app = appender(somePreExistingArray);
app ~= e0;
app ~= [e1, e2];
app.reserve(3); //eagerly ensures that there's 3 elements 
capacity,
//guaranteeing at most one re-allocation for adding the following 
3 elements

app ~= e3;
app ~= e4;
app ~= e5;

or my personal favourite:

app ~= only(e6, e7, e8, e9);

When you append a range to an appender it will use the length of 
the range (if available) to reserve space ahead-of-time.


There is a (small) cost to creating an appender, so you ideally 
don't want to make a new one every time you add a couple of 
elements (this isn't a deficiency in appender, it's just how GC 
slices are in D).


Asssociative Array by Key-Value-Pair

2014-12-15 Thread Nordlöw
Is there a combined property of AAs that combine keys and values 
typically


.pairs()

or

.byPairs()

I need to sort the elements of an AA by value and then retrieved 
corresponding keys in the order sorted.


Re: Asssociative Array by Key-Value-Pair

2014-12-15 Thread bearophile via Digitalmars-d-learn

Nordlöw:

Is there a combined property of AAs that combine keys and 
values typically


.pairs()

or

.byPairs()

I need to sort the elements of an AA by value and then 
retrieved corresponding keys in the order sorted.


You can add an eager pairs() function to Phobos that returns an 
array of tuples.


byPairs can't be done in object.d for the dependency from tuples 
that aren't yet (and perhaps never) built-in in D, and it can't 
be done in Phobos because it needs access to unspecified runtime 
functions.


Bye,
bearophile


Re: Fast matrix struct

2014-12-15 Thread John Colvin via Digitalmars-d-learn

On Sunday, 14 December 2014 at 22:14:55 UTC, Ryan wrote:
I'm writing a Matrix struct that I plan to use for some number 
crunching, which will be intensive at times. So I want it to be 
fast.


Will I do better by manually managing the memory myself with 
malloc and free in the constructors/destructor or just using 
plain D arrays?


The manual way I could bypass the GC and bounds checks. I don't 
need (or want) any of the fancy appending concatenation and the 
potential slowdowns from the heap allocations that comes with 
the builtin arrays.


But I have to wonder, if I just don't use those features, will 
it be just as fast with the GC (assuming I compile out the 
bounds checks with the -release compiler option)?


Right now my strategy is to malloc one large chunk of memory in 
the constructor (and postblit) and treat the 2-d matrix as a 
1-d array internally. Then just use pointer arithmetic to 
access the elements.


I know the best way to know is just to test. But writing both 
versions would take a LOT of work, and I'm looking for guidance 
about which path will probably be most fruitful.


Thanks,


There should be no performance hit for using builtin array 
indexing if you compile with -noboundscheck or the equivalent for 
ldc/gdc.
The reverse situation is great though (Huh, that looks garbled 
recompile with bounds checks enabled, run and hit a RangeError 
Oh look, that's where it went wrong).
Even if for some reason you do hit a problem (e.g. you only want 
to disable bounds checks for one very hot loop) then adding a 
quick .ptr before your array indexing will mean no check is 
generated there under any circumstances.


Using D's builtin arrays (better referred to as slices) doesn't 
imply any necessity to use the garbage collector. You can create 
a slice from any memory you like, including malloc'd memory. Only 
appending or manually increasing .length will cause the GC to get 
involved. I would highly recommend them over raw pointers except 
in very specialised circumstances.


std.container.Array is an option, but it historically hasn't been 
perfect. I'm not sure of the current state of affairs.


Re: std.bitmanip - bitshift?

2014-12-15 Thread Steven Schveighoffer via Digitalmars-d-learn
On 12/13/14 5:47 AM, Marc =?UTF-8?B?U2Now7x0eiI=?= schue...@gmx.net 
wrote:

On Friday, 12 December 2014 at 19:35:26 UTC, Steven Schveighoffer wrote:

On 12/12/14 2:17 PM, H. S. Teoh via Digitalmars-d-learn wrote:

I've started working on an implementation of this... but it's not very
clear what the correct semantics should be. For example, if my starting
BitArray b is 1101, say, what should be the result after b=1? Should
it be 0110, 110, or 01101?


0110

In other words, I would assume the same semantics as an unsigned int.

In other other words, it's like each bit moves one to the right, and
the bit that has no source gets a 0.


There's a dedicated  operator for unsigned right shift, the normal 
operator does a signed right shift, i.e. it copies the left-most bit:
http://dlang.org/expression#ShiftExpression

IMO, for consistency, bitarray should behave the same.


But BitArray is not signed, it's an array of bits, none of which are 
signed or designated as the sign bit. The unsigned shift operator is 
only for signed integral types, for unsigned values  is simply a shift 
of bits. Note that your assertion that  copies the left-most bit is 
not in the text, and is incorrect. It copies the sign bit, which doesn't 
exist in an unsigned type.


I think  and  should do the same thing, and be unsigned shifts on 
BitArray.


-Steve


Re: Segmentation fault after having a certain number of elements in an array?

2014-12-15 Thread Steven Schveighoffer via Digitalmars-d-learn

On 12/13/14 3:59 AM, Jeremy DeHaan wrote:

I'll be trying to narrow it down even more tomorrow, but I was hoping
somone here might have some insight into this weird issue I am having.

I have a dynamic array of shorts that I had been trying to append to
(capturing sound data). I kept getting a segfault when doing the append,
and have narrowed it down to getting a segfault when the length of the
array is equal to or greater than 1024.

It looks wonky because of my many tests, but this is the code that was
causing the segfault:

override bool onProcessSamples(const(short)[] samples)
{
 import std.stdio;
 for(int i = 0; isamples.length; ++i)
 {
 writeln(m_samples.length);
 m_samples.length +=1;
 }
 return true;
}

It will print all the numbers, endikng with 1023, and then it shows
Segmentation fault and if I comment out the writeln line it just shows
the Segmentation fault line. Similar code that would cause the length to
be at 1024 or higher will also cause a segfault.

The class that this method belongs to is wraped up in a C++ interface
and it gets called C++ side.

Also, if I set the length to 1024 or higher in the class constructor or
if I create a different array elsewhere and set its length to 1024 or
higher, I don't get the segfault anymore.

As far as I can tell, this only happens because it is called in C++
code. It doesn't appear to happen on my system at all if I do anything
like this outside of my C++ interoperating. So far my fix is to set the
length of the array to 1024, and then right away set it back to 0 in the
class' constructor, but I'd like to get this to work without any strange
hacks.


A guess -- is the class instantiated in C++? if so, it probably is not 
on the D heap, and probably is not scanned during GC collections. I 
think your m_samples array is reallocated during a collection, and you 
are using dangling memory.


Try GC.addRoot(this) at the start of the function, and see if it helps.

-Steve


Re: std.bitmanip - bitshift?

2014-12-15 Thread via Digitalmars-d-learn
On Monday, 15 December 2014 at 15:19:25 UTC, Steven Schveighoffer 
wrote:
On 12/13/14 5:47 AM, Marc =?UTF-8?B?U2Now7x0eiI=?= 
schue...@gmx.net wrote:
On Friday, 12 December 2014 at 19:35:26 UTC, Steven 
Schveighoffer wrote:

On 12/12/14 2:17 PM, H. S. Teoh via Digitalmars-d-learn wrote:
I've started working on an implementation of this... but 
it's not very
clear what the correct semantics should be. For example, if 
my starting
BitArray b is 1101, say, what should be the result after 
b=1? Should

it be 0110, 110, or 01101?


0110

In other words, I would assume the same semantics as an 
unsigned int.


In other other words, it's like each bit moves one to the 
right, and

the bit that has no source gets a 0.


There's a dedicated  operator for unsigned right shift, the 
normal 
operator does a signed right shift, i.e. it copies the 
left-most bit:

http://dlang.org/expression#ShiftExpression

IMO, for consistency, bitarray should behave the same.


But BitArray is not signed, it's an array of bits, none of 
which are signed or designated as the sign bit. The unsigned 
shift operator is only for signed integral types, for unsigned 
values  is simply a shift of bits. Note that your assertion 
that  copies the left-most bit is not in the text, and is 
incorrect. It copies the sign bit, which doesn't exist in an 
unsigned type.


I think  and  should do the same thing, and be unsigned 
shifts on BitArray.


Yes, yebblies pointed that out in the PR. I was confused, because 
the documentation doesn't say that `` and `` only behave 
differently for signed integers.


Re: Segmentation fault after having a certain number of elements in an array?

2014-12-15 Thread Steven Schveighoffer via Digitalmars-d-learn

On 12/15/14 10:24 AM, Steven Schveighoffer wrote:



A guess -- is the class instantiated in C++? if so, it probably is not
on the D heap, and probably is not scanned during GC collections. I
think your m_samples array is reallocated during a collection, and you
are using dangling memory.

Try GC.addRoot(this) at the start of the function, and see if it helps.


Ugh... just after saying that, I realized this will not help, because 
the memory pointed at by 'this' is not GC allocated.


You have to GC.addRoot the m_samples array data, but even when you do 
that, any time you append it may reallocate, so every time that happens, 
you must re-add the root.


But you can add the range which includes the m_samples array pointer, 
and that should solve it (you must do this when m_samples is first 
allocated, i.e. when it starts pointing at GC memory).


GC.addRange(m_samples, sizeof(m_samples));

If that doesn't work, try this instead:

override bool onProcessSamples(const(short)[] samples)
{
import std.stdio;
import core.memory;
auto tmpsamples = m_samples.ptr;
for(int i = 0; isamples.length; ++i)
{
writeln(m_samples.length);
m_samples.length +=1;
if(m_samples.ptr !is tmpsamples) // if pointer changed
{
   GC.addRoot(m_samples.ptr);
   if(tmpsamples)
  GC.removeRoot(tmpsamples);
   tmpsamples = m_samples.ptr;
}
}
return true;
}

-Steve


Re: Are there any methods like isDestroyed or isDisposed to detect whether some object is destroyed or not?

2014-12-15 Thread Steven Schveighoffer via Digitalmars-d-learn

On 12/13/14 2:03 AM, Andrey Derzhavin wrote:

Hello!

We have object, for example, objA.

ObjectAType objA = new ObjectAType(...);

// we have a many references to objA

void someFunction1(...)
{
// destroying the objA
destroy(one_of_the_refToObjA);

//
}


void someFunction2()
{
// segmentation fault if the objA is destroyed
another_refToObjA.method1();

// I need a safe way (without using signals) to detect whether object
// destroyed or not, like this
// if (!isDestroyed(another_refToObjA))
//   another_refToObjA.method1();

}

// call functions
someFunction1(..);

// . some other operations...

// the objectA (objA) is destroyed, but debugger shows us a not null
reference
// to that objA. However, when we try to call some methods of objectA or
// try to use it's variables we get a segmentation fault error (in
// someFunction2, when objA is destroyed).
someFunction2(...);


Yes, you can tell if the typeinfo pointer is null, this is how the 
runtime does it.


Unfortunately, typeid(objA) uses the pointer to look up the most derived 
type and results in a segfault.


You can use the knowledge of the object layout (the typeinfo pointer is 
the first item in the memory block) to ascertain whether it's null or 
not, it's what the runtime does:


bool isDestroyed(Object o)
{
   return o is null || *(cast(void **)o) is null;
}

Although, I highly recommend not doing this. Instead of destroying an 
object, leave the object live and dispose of it using some other method 
(e.g. close, dispose, etc.). Then let the GC clean up the memory later 
when nothing refers to it.


-Steve


Re: Fastest Way to Append Multiple Elements to an Array

2014-12-15 Thread Steven Schveighoffer via Digitalmars-d-learn

On 12/14/14 6:16 PM, Nordlöw wrote:

What's the fastest way to append multiple elements to an array?:


Before appending, call reserve to avoid the possibility of reallocating 
multiple times:


arr.reserve(arr.length + n); // about to append n elements.


Either

 arr ~= e1;
 arr ~= e2;
 arr ~= e3;

or

 arr ~= [e1,e2,e3];


I wish this would be fastest, but it's not, because this allocates an 
array on the heap with elements e1, e2, e3 before appending. It would be 
a superb addition to D if this would simply allocate a stack array (if 
the array never escapes the expression).


-Steve


Re: Asssociative Array by Key-Value-Pair

2014-12-15 Thread Tobias Pankrath via Digitalmars-d-learn




You can add an eager pairs() function to Phobos that returns an 
array of tuples.


byPairs can't be done in object.d for the dependency from 
tuples that aren't yet (and perhaps never) built-in in D, and 
it can't be done in Phobos because it needs access to 
unspecified runtime functions.


Bye,
bearophile


I think we should require byKeys and byValues to iterate the 
elements in the same order. Than we can just zip them for the 
pairwise iteration.


Would this impose a performance problem with the current 
implementation?


Problem calling extern(C) function

2014-12-15 Thread AuoroP via Digitalmars-d-learn

I'm pretty sure my problem isn't my code but how I've built the
lib. The problem is I'm calling external C code and I am getting
valid data out of it but /some/ of my arguments to it is
corrupted.

A common thread in this newsgroup seems to be people calling
Extern(Windows). I don't that is me because I call with
extern(C) my .lst names are not mangled that way:
_tjDecompressHeader2, _tjGetErrorStr, _tjInitDecompress.

Even if you can't help, Thanks for reading this far!

This message is kinda long so here's a TOC

The code
The output
DLL code:
You WANT to be in this mess?


---=---=---=---=---=---
The code:

extern(C) tjhandle tjInitDecompress();
extern(C) int tjDecompressHeader2
(
tjhandle handle, 
void* jpegBuf,
ulong jpegSize,
int* width,
int* height,
int* jpegSubsamp
);
extern(C) char* tjGetErrorStr();

import std.conv: to;
import std.file: exists, read;
import std.stdio: writeln;

tjhandle dHandle = tjInitDecompress();
writeln(dHandle: , dHandle);
int width, height, subsamp;
void[] buffer = read(testimg.jpg);

writeln(buffer.ptr: , buffer.ptr);
writeln(buffer.length: , buffer.length);
writeln(width: , width);
writeln(height: , height);
writeln(subsamp: , subsamp);
if 
( 
0  
tjDecompressHeader2
( 
dHandle, 
buffer.ptr, 
buffer.length,
width,
height,
subsamp
)
)
{
writeln(  to!string( tjGetErrorStr() )  );
writeln(testimg.jpg gets me , buffer.length, bytes.);
write(width: , width);
write( height: , height);
writeln(subsamp: , subsamp);
}


---=---=---=---=---=---
The output:

dHandle: 5E09F0
buffer.ptr: 234
buffer.length: 5764
width: 18FDC4
height: 18FDC8
subsamp: 18FDCC
tjDecompressHeader2(): Invalid argument
testimg.jpg gets me 5764bytes.
width: 0 height: 0subsamp: 0


---=---=---=---=---=---
DLL code:

If you wanted to look in the DLL code, it is online here:
https://github.com/LibVNC/libvncserver/blob/master/common/turbojpeg.c

DLLEXPORT int DLLCALL tjDecompressHeader2(tjhandle handle,
unsigned char *jpegBuf, unsigned long jpegSize, int *width, int *height,
int *jpegSubsamp)
{
int retval=0;
getinstance(handle);
if((this-initDECOMPRESS)==0)
_throw(tjDecompressHeader2(): Instance has not been initialized for 
decompression);
if
(
jpegBuf==NULL || 
jpegSize=0 || 
width==NULL || 
height==NULL|| 
jpegSubsamp==NULL
)
_throw(tjDecompressHeader2(): Invalid argument);
// .
// .
// .
}


---=---=---=---=---=---
You WANT to be in this mess?

If you want to play with this problem yourself then I'll help you recreate it.

I'm using 1.3.1 libjpeg-turbo which can be found here:
http://sourceforge.net/projects/libjpeg-turbo/files/1.3.1/libjpeg-turbo-1.3.1-vc.exe/download

I've gotten working .lib files out of the folders lib and bin


Getting a .lib from the DLL in bin is much more straightforward:

IMPLIB /s libTurboJPEG.lib turbojpeg.dll
LIB -l libTurboJPEG.lib

Getting a .lib from lib is tricky but the following gets you turbojpeg.omf.lib:

COFFIMPLIB turbojpeg.lib turbojpeg.omf.lib
ECHO LIB -l turbojpeg.omf.lib


I've tried to use both .lib files and their behavior is the same.

Next up is trying the GCC version with the same recipes:
http://sourceforge.net/projects/libjpeg-turbo/files/1.3.1/libjpeg-turbo-1.3.1-gcc.exe/download

The behavior is unchanged.


FREE 3D EARTH SCREENSAVER - Watch the Earth right on your desktop!
Check it out at http://www.inbox.com/earth





Re: Asssociative Array by Key-Value-Pair

2014-12-15 Thread ketmar via Digitalmars-d-learn
On Mon, 15 Dec 2014 17:37:13 +
Tobias Pankrath via Digitalmars-d-learn
digitalmars-d-learn@puremagic.com wrote:

 I think we should require byKeys and byValues to iterate the 
 elements in the same order. Than we can just zip them for the 
 pairwise iteration.
 
 Would this impose a performance problem with the current 
 implementation?
i was always sure that they doing that in the same order. at least this
was true some time ago, but i see that runtime AA changed since, so i
don't sure if it works like this now. but i agree that this
requirement should be documented. and i bet it will not, 'cause this
will support principle of least astonishment, which is completely alien
for D.

the only way to get it into the specs is to write the useful library
that relies on that behavior and then scream don't break our code,
it's regression! then it eventually may be turned to requirement and
documented.


signature.asc
Description: PGP signature


Re: Problem calling extern(C) function

2014-12-15 Thread Adam D. Ruppe via Digitalmars-d-learn
On Monday, 15 December 2014 at 17:48:32 UTC, AuoroP via 
Digitalmars-d-learn wrote:

ulong jpegSize,


Without looking too closely, this sets off an alarm to me: C's 
long and D's long are not really compatible because C's long has 
variable size and D's long is 64 bit.


I'd say try import core.stdc.config; and replace all instances 
of ulong with c_ulong and all instances of long with c_long when 
interfacing with C.




DLLEXPORT int DLLCALL tjDecompressHeader2(tjhandle handle,
unsigned char *jpegBuf, unsigned long jpegSize, int *width, int 
*height,



yeah the D long is 32 bits longer than the C function expects, so 
every argument after it is offset by that amount.


Re: Asssociative Array by Key-Value-Pair

2014-12-15 Thread Steven Schveighoffer via Digitalmars-d-learn

On 12/15/14 12:52 PM, ketmar via Digitalmars-d-learn wrote:

On Mon, 15 Dec 2014 17:37:13 +
Tobias Pankrath via Digitalmars-d-learn
digitalmars-d-learn@puremagic.com wrote:


I think we should require byKeys and byValues to iterate the
elements in the same order. Than we can just zip them for the
pairwise iteration.

Would this impose a performance problem with the current
implementation?

i was always sure that they doing that in the same order. at least this
was true some time ago, but i see that runtime AA changed since, so i
don't sure if it works like this now.


It does work this way, the same structure and functions are used to do 
both byKey and byValue.



but i agree that this
requirement should be documented. and i bet it will not, 'cause this
will support principle of least astonishment, which is completely alien
for D.


Really? You done filling up that man with straw?

-Steve


Re: Asssociative Array by Key-Value-Pair

2014-12-15 Thread H. S. Teoh via Digitalmars-d-learn
On Mon, Dec 15, 2014 at 02:27:52PM +, Nordlöw via Digitalmars-d-learn 
wrote:
 Is there a combined property of AAs that combine keys and values
 typically
 
 .pairs()
 
 or
 
 .byPairs()
 
 I need to sort the elements of an AA by value and then retrieved
 corresponding keys in the order sorted.

I implemented this before, but it got rejected because people insisted
that it must return a range of Tuple, but Tuple is defined in Phobos and
druntime can't have dependencies on Phobos. :-(

Maybe I'll take another shot at this, since this question keeps coming
up.


T

-- 
LINUX = Lousy Interface for Nefarious Unix Xenophobes.


Re: Asssociative Array by Key-Value-Pair

2014-12-15 Thread ketmar via Digitalmars-d-learn
On Mon, 15 Dec 2014 13:01:10 -0500
Steven Schveighoffer via Digitalmars-d-learn
digitalmars-d-learn@puremagic.com wrote:

  but i agree that this
  requirement should be documented. and i bet it will not, 'cause this
  will support principle of least astonishment, which is completely alien
  for D.
 
 Really? You done filling up that man with straw?

so it will be documented? that was the rhetorical question.


signature.asc
Description: PGP signature


Re: Asssociative Array by Key-Value-Pair

2014-12-15 Thread bearophile via Digitalmars-d-learn

ketmar:

the only way to get it into the specs is to write the useful 
library that relies on that behavior and then scream don't

break our code, it's regression! then it eventually may be
turned to requirement and documented.


This is a bad idea.

Bye,
bearophile


Re: Asssociative Array by Key-Value-Pair

2014-12-15 Thread bearophile via Digitalmars-d-learn

H. S. Teoh:

I implemented this before, but it got rejected because people 
insisted
that it must return a range of Tuple, but Tuple is defined in 
Phobos and

druntime can't have dependencies on Phobos. :-(

Maybe I'll take another shot at this, since this question keeps 
coming up.


One possible solution: have a hidden but documented runtime 
function that yields 2-item structs, and add a 
std.range.byPairs range and a std.range.pairs function to 
Phobos that yield the tuples (byPairs could use a cast to convert 
the runtime struct to the Phobos tuple).


Bye,
bearophile


Re: Asssociative Array by Key-Value-Pair

2014-12-15 Thread Steven Schveighoffer via Digitalmars-d-learn

On 12/15/14 1:10 PM, ketmar via Digitalmars-d-learn wrote:

On Mon, 15 Dec 2014 13:01:10 -0500
Steven Schveighoffer via Digitalmars-d-learn
digitalmars-d-learn@puremagic.com wrote:


but i agree that this
requirement should be documented. and i bet it will not, 'cause this
will support principle of least astonishment, which is completely alien
for D.


Really? You done filling up that man with straw?


so it will be documented? that was the rhetorical question.


Does it need to be? I don't see a reason for anyone to go out of their 
way to make the implementation inconsistent. Do you? The principal of 
least astonishment means that the least astonishing path is chosen. In 
this case, the least astonishing path has been chosen. Does it need 
documenting for you to believe it?


But my larger beef with your statement is that you assume D opts never 
to take that path, which is absolutely untrue.


-Steve


Re: Asssociative Array by Key-Value-Pair

2014-12-15 Thread ketmar via Digitalmars-d-learn
On Mon, 15 Dec 2014 13:47:58 -0500
Steven Schveighoffer via Digitalmars-d-learn
digitalmars-d-learn@puremagic.com wrote:

 On 12/15/14 1:10 PM, ketmar via Digitalmars-d-learn wrote:
  On Mon, 15 Dec 2014 13:01:10 -0500
  Steven Schveighoffer via Digitalmars-d-learn
  digitalmars-d-learn@puremagic.com wrote:
 
  but i agree that this
  requirement should be documented. and i bet it will not, 'cause this
  will support principle of least astonishment, which is completely alien
  for D.
 
  Really? You done filling up that man with straw?
 
  so it will be documented? that was the rhetorical question.
 
 Does it need to be? I don't see a reason for anyone to go out of their 
 way to make the implementation inconsistent. Do you? The principal of 
 least astonishment means that the least astonishing path is chosen. In 
 this case, the least astonishing path has been chosen. Does it need 
 documenting for you to believe it?
 
 But my larger beef with your statement is that you assume D opts never 
 to take that path, which is absolutely untrue.
maybe after five years of talking and after alot of people will relay
on the current behavior, it will be documented.


signature.asc
Description: PGP signature


Re: Asssociative Array by Key-Value-Pair

2014-12-15 Thread bearophile via Digitalmars-d-learn

Now this yields tuples:
assert(aa.byPair!Tuple.array == aa.pairs!Tuple);


But I'd really like tuples as built-ins for D -.- This is a 
work-around that cements the ugly Phobos tuples in the 
language... -.-


Bye,
bearophile


Re: Asssociative Array by Key-Value-Pair

2014-12-15 Thread H. S. Teoh via Digitalmars-d-learn
On Mon, Dec 15, 2014 at 06:46:20PM +, bearophile via Digitalmars-d-learn 
wrote:
 H. S. Teoh:
 
 I implemented this before, but it got rejected because people
 insisted that it must return a range of Tuple, but Tuple is defined
 in Phobos and druntime can't have dependencies on Phobos. :-(
 
 Maybe I'll take another shot at this, since this question keeps
 coming up.
 
 One possible solution: have a hidden but documented runtime function
 that yields 2-item structs, and add a std.range.byPairs range and a
 std.range.pairs function to Phobos that yield the tuples (byPairs
 could use a cast to convert the runtime struct to the Phobos tuple).
[...]

That's exactly what I plan to do. :-)


T

-- 
Let's call it an accidental feature. -- Larry Wall


Re: Are there any methods like isDestroyed or isDisposed to detect whether some object is destroyed or not?

2014-12-15 Thread Andrey Derzhavin via Digitalmars-d-learn

Thank you very much, Steven!


Re: Fastest Way to Append Multiple Elements to an Array

2014-12-15 Thread Nordlöw
On Monday, 15 December 2014 at 15:55:22 UTC, Steven Schveighoffer 
wrote:
What's the fastest way to append multiple elements to an 
array?:


Before appending, call reserve to avoid the possibility of 
reallocating multiple times:


arr.reserve(arr.length + n); // about to append n elements.


Thanks!




Either

arr ~= e1;
arr ~= e2;
arr ~= e3;

or

arr ~= [e1,e2,e3];


I wish this would be fastest, but it's not, because this 
allocates an array on the heap with elements e1, e2, e3 before 
appending. It would be a superb addition to D if this would 
simply allocate a stack array (if the array never escapes the 
expression).


That's what I thought :)


Re: Asssociative Array by Key-Value-Pair

2014-12-15 Thread Meta via Digitalmars-d-learn

On Monday, 15 December 2014 at 18:55:13 UTC, bearophile wrote:

Now this yields tuples:
assert(aa.byPair!Tuple.array == aa.pairs!Tuple);


But I'd really like tuples as built-ins for D -.- This is a 
work-around that cements the ugly Phobos tuples in the 
language... -.-


Bye,
bearophile


Kenji has had a pull for full built-in Tuple support sitting in 
Github for years now 
(https://github.com/D-Programming-Language/dmd/pull/341). The 
syntax obviously won't work as it is, but that aside there's very 
little stopping built-in tuples in D.


Don't forget, he also made a DIP about it as well: 
http://forum.dlang.org/thread/mailman.372.1364547485.4724.digitalmar...@puremagic.com




Re: Asssociative Array by Key-Value-Pair

2014-12-15 Thread ketmar via Digitalmars-d-learn
On Mon, 15 Dec 2014 21:32:23 +
Meta via Digitalmars-d-learn digitalmars-d-learn@puremagic.com wrote:

 On Monday, 15 December 2014 at 18:55:13 UTC, bearophile wrote:
  Now this yields tuples:
  assert(aa.byPair!Tuple.array == aa.pairs!Tuple);
 
  But I'd really like tuples as built-ins for D -.- This is a 
  work-around that cements the ugly Phobos tuples in the 
  language... -.-
 
  Bye,
  bearophile
 
 Kenji has had a pull for full built-in Tuple support sitting in 
 Github for years now 
 (https://github.com/D-Programming-Language/dmd/pull/341). The 
 syntax obviously won't work as it is, but that aside there's very 
 little stopping built-in tuples in D.
 
 Don't forget, he also made a DIP about it as well: 
 http://forum.dlang.org/thread/mailman.372.1364547485.4724.digitalmar...@puremagic.com

wow, thank you. i missed that PR and i really like it. will try to add
it to my patchset. ;-)


signature.asc
Description: PGP signature


Odd Error Message

2014-12-15 Thread CraigDillabaugh via Digitalmars-d-learn

Given the following program:

import std.string;
import std.stdio;

void main()
{   
File file = File(blah.txt, r);

while( !(file.eof())  count  10 ) {  //line 8
//
}
}

I get the error message:

line(8): Error: void has no value

If I comment out the import std.string; then I get an error I 
would expect.


line(8): Error: undefined identifier count

There is no 'count' symbol that I can see in std.string.

Would this error message be considered a compiler bug?

DMD32 D Compiler v2.066.1 (on Windows 7)



Re: Odd Error Message

2014-12-15 Thread bearophile via Digitalmars-d-learn

CraigDillabaugh:


Given the following program:

import std.string;
import std.stdio;

void main()
{   
File file = File(blah.txt, r);

while( !(file.eof())  count  10 ) {  //line 8
//
}
}

I get the error message:

line(8): Error: void has no value


The next error message is:

test.d(8,29): Error: incompatible types for ((count(alias pred = 
a == b, Range, E)(Range haystack, E needle) if 
(isInputRange!Range  !isInfinite!Range  
is(typeof(binaryFun!pred(haystack.front, needle)) : bool)))  
(10)): 'void' and 'int'


So it's referring to std.algorithm.count, that probably is 
imported by one of the other two imports.


Bye,
bearophile


Re: Odd Error Message

2014-12-15 Thread ketmar via Digitalmars-d-learn
On Mon, 15 Dec 2014 22:09:28 +
CraigDillabaugh via Digitalmars-d-learn
digitalmars-d-learn@puremagic.com wrote:

 Given the following program:
 
 import std.string;
 import std.stdio;
 
 void main()
 { 
   File file = File(blah.txt, r);
   
   while( !(file.eof())  count  10 ) {  //line 8
   //
   }
 }
 
 I get the error message:
 
 line(8): Error: void has no value
 
 If I comment out the import std.string; then I get an error I 
 would expect.
 
 line(8): Error: undefined identifier count
 
 There is no 'count' symbol that I can see in std.string.
there is public import from std.algorithm inside std.string, so what
you see is about std.algorithm.count.

 Would this error message be considered a compiler bug?
i don't think so. compiler tries to instantiate std.algorithm.count and
failed doing that, so it tries to tell you about that failure. newer
compiler will tell you this:

z00.d(8): Error: void has no value
z00.d(8): Error: incompatible types for ((count(alias pred = a == b, Range, 
E)(Range haystack, E needle)
  if (isInputRange!Range  !isInfinite!Range 
  is(typeof(binaryFun!pred(haystack.front, needle)) : bool)))  (10)): 'void' 
and 'int'

this is slightly better, albeit still cryptic. template instantiation
error messages are of the most noisy and hard to understand ones. alas.
but poor compiler at least tries to help you. ;-)


signature.asc
Description: PGP signature


Re: Asssociative Array by Key-Value-Pair

2014-12-15 Thread Nordlöw

On Monday, 15 December 2014 at 14:41:43 UTC, bearophile wrote:

Nordlöw:

Is there a combined property of AAs that combine keys and 
values typically


.pairs()

or

.byPairs()

I need to sort the elements of an AA by value and then 
retrieved corresponding keys in the order sorted.


You can add an eager pairs() function to Phobos that returns an 
array of tuples.


byPairs can't be done in object.d for the dependency from 
tuples that aren't yet (and perhaps never) built-in in D, and 
it can't be done in Phobos because it needs access to 
unspecified runtime functions.


Bye,
bearophile


Ok. Thanks.

Is

Tuple!(Key,Value)[] pairs(Key,Value)(Value[Key] aa);

a suitable contender for now?

I especially wonder about the mutability of parameter aa.

BTW: Why doesn't aa.byKey.map work?


Re: Asssociative Array by Key-Value-Pair

2014-12-15 Thread Nordlöw

On Monday, 15 December 2014 at 22:58:43 UTC, Nordlöw wrote:

Tuple!(Key,Value)[] pairs(Key,Value)(Value[Key] aa);

a suitable contender for now?

I especially wonder about the mutability of parameter aa.


More specifically is

https://github.com/nordlow/justd/blob/master/range_ex.d#L545

ok?


mixin template and const property qualifier?

2014-12-15 Thread aldanor via Digitalmars-d-learn
Could someone please explain why the following doesn't compile 
with const qualifier while it does work without it?


/* test.d */

module test;

mixin template Foo() {
mixin(@property int bar() const { return foo; });
}

int foo = 1;

mixin Foo;

unittest {
assert(foo == bar);
}


rdmd -main -unittest test.d
test.d-mixin-4(4): Error: function test.Foo!().bar without 'this' 
cannot be const

test.d(9): Error: mixin test.Foo!() error instantiating


Re: mixin template and const property qualifier?

2014-12-15 Thread anonymous via Digitalmars-d-learn

On Monday, 15 December 2014 at 23:14:30 UTC, aldanor wrote:
Could someone please explain why the following doesn't compile 
with const qualifier while it does work without it?


/* test.d */

module test;

mixin template Foo() {
mixin(@property int bar() const { return foo; });
}

int foo = 1;

mixin Foo;

unittest {
assert(foo == bar);
}


rdmd -main -unittest test.d
test.d-mixin-4(4): Error: function test.Foo!().bar without 
'this' cannot be const

test.d(9): Error: mixin test.Foo!() error instantiating


Has nothing to do with mixin. This produces the same error
message:

@property int bar() const { return foo; }
int foo = 1;
unittest {assert(foo == bar);}

The thing is, free functions cannot be const. In a const method,
what's const is `this`. A free function doesn't have `this`, so
it cannot be const.


Re: Problem calling extern(C) function

2014-12-15 Thread AuoroP via Digitalmars-d-learn
Thank you!!!

All I have to do is 


 -Original Message-
 From: digitalmars-d-learn@puremagic.com
 Sent: Mon, 15 Dec 2014 17:54:51 +
 To: digitalmars-d-learn@puremagic.com
 Subject: Re: Problem calling extern(C) function
 
 On Monday, 15 December 2014 at 17:48:32 UTC, AuoroP via
 Digitalmars-d-learn wrote:
 ulong jpegSize,
 
 Without looking too closely, this sets off an alarm to me: C's
 long and D's long are not really compatible because C's long has
 variable size and D's long is 64 bit.
 
 I'd say try import core.stdc.config; and replace all instances
 of ulong with c_ulong and all instances of long with c_long when
 interfacing with C.

Adam D. Ruppe, I have two words for you: thank you!!! I just changed jpegSize 
from ulong to uint and it worked! I think I had given up so I really cannot 
express the joy you've given me so thank you again!


Can't remember your password? Do you need a strong and secure password?
Use Password manager! It stores your passwords  protects your account.
Check it out at http://mysecurelogon.com/manager





I want to implement operation feasible?

2014-12-15 Thread Brian via Digitalmars-d-learn


package com.kerisy.mod.base

interface BaseMod
{
auto getInstance();
}

package com.kerisy.mod.a

class A : BaseMod
{
A getInstance()
{
return (new A);
}

void hello()
{
// in A
writeln(in A);
}
}

package com.kerisy.mod.b

class B : BaseMod
{
B getInstance()
{
return (new B);
}

void hello()
{
// in B
writeln(in B);
}
}

import std.stdio;
import com.kerisy.mod.a;
import com.kerisy.mod.b;

int main(string[] argv)
{
string packageClass;

packageClass packageClass = mod.forum.controller.forum.A;
BaseMod modObje = cast(BaseMod)Object.factory(packageClass);
auto a = modObj::getInstance();
Object.callMethod(a, hello);

packageClass packageClass = mod.forum.controller.forum.A;
BaseMod modObje = cast(BaseMod)Object.factory(packageClass);
auto a = modObj::getInstance();
Object.callMethod(a, hello);

return 0;
}


Re: I want to implement operation feasible?

2014-12-15 Thread Adam D. Ruppe via Digitalmars-d-learn

On Tuesday, 16 December 2014 at 04:45:31 UTC, Brian wrote:

interface BaseMod
{
auto getInstance();
}


You can't do that - interface methods must be either final or 
have concrete types (they can't be templates or auto returns).


Make it BaseMod getInstance(); and the rest of your classes will 
work.




auto a = modObj::getInstance();


Since this comes from the interface, a will be typed to the 
interface too. It will have the dynamic type of the underlying 
class, but the interface functions will all return the interface.


If your hello method is in the interface, you can just call it at 
that point though and you'll get the results you want.


BTW it is modObj.getInstance rather than ::. D always uses the 
dot.



Object.callMethod(a, hello);


You could write a reflection method like that in D, but it isn't 
done automatically (partially due to bloat concerns making it 
opt-in). Check out the free sample of my D book:


https://www.packtpub.com/application-development/d-cookbook

The free chapter is about D's reflection. I also go into how to 
make runtime methods like you have in other parts of the book.


detaching a thread from druntime 2.067

2014-12-15 Thread Ellery Newcomer via Digitalmars-d-learn
If I have a thread that I need to detach from druntime, I can call 
thread_detachInstance, but for 2.066, this function does not exist. Is 
there any way to do this in 2.066? I notice there is a 
thread_detachByAddr, but I'm not sure how to get a ThreadAddr out of a 
Thread..