Re: Python calling D
Sorry to be late coming to this. It would great to be able to push D as a CPython extension language. However the state of pyd.dsource.org and places reached from it do make it seem that the project died in 2009. ariovistus' GitHub project on Bitbucket is moving but everything else appears to be a problem. Is it possible to decide on a location for activity, create some infrastructure, and then get the old stuff cleaned out. My start point is to get PyD working in virtualenvs for Python 2.7 and Python 3.3. Findout out what the SCons and Tup stuff is for would be useful. On the side I could help with documentation and stuff, but only if it can be done by DVCS and pull requests with email, I am not interested in non DVCS wikis nor forums. For future reference, I tried but wasn't able to make calling D from python work. I tried to just compile D to an .a library, including statically linking phobos, and then wrapping it with cython like I would with C code. (I've made this work before with C.) My thinking was that there's already been a lot of work in the Python world in the past 4-6 years to make calling C fairly straight forward. So D should be able to piggy back on that work. (Though to a lot of Python people a legitimate question would be, "is this worth it?" You can just profile python code to find the hot spots and then use ctypes/cython to pass objects allocated by Python to C-level functions to do the time-intensive stuff.)
Re: struct postblit not called, but still destructed
On Sunday, 19 January 2014 at 20:46:06 UTC, monarch_dodra wrote: I'll file it as an ER, and try to get Kenji on it. https://d.puremagic.com/issues/show_bug.cgi?id=11952 As a workaround, it is usually recommended in the destructor to try to detect "initial state", and do nothing in such cases. This is generally recommended anyways, since the .init state could mess up your count: void main() { //Scope { A a; //No increment count }//Destruction assert(A.count == 0); //Fails } I'd say disabling "this()" would help, but in this case, your example code still fails... I'll bump the report to bug because of this.
Re: struct postblit not called, but still destructed
On Sunday, 19 January 2014 at 19:24:23 UTC, Benjamin Thaut wrote: Yes this looks like a bug to me. Please file a bug report at https://d.puremagic.com/issues/ Kind Regards Benjamin Thaut Here is a reduced case: // import std.stdio; struct B { A sup; this(A a) { writeln("Here"); sup = a; writeln("There"); } } struct A { static int count; this(int n) { writeln("A.this()"); } this(this) { writeln("A.this(this)"); } ~this() { writeln("A.~this()"); } } void main() { A a = A(1); writeln("Start"); B b = B(a); writeln("End"); } // A.this() Start A.this(this) Here A.this(this) //!!! A.~this()//!!! There A.~this() End A.~this() A.~this() // I think the behavior is not *strictly* incorrect: When you write: sup = a; it triggers a postblit of "a" into "sup". To do said postblit, you destroy sup. It's the way it works :/ Arguably, since it is initialization, we could avoid the destruction altogether, but it's not strictly *wrong*. I'll file it as an ER, and try to get Kenji on it.
Re: Better idea for double list comprehension?
That's std.array.join() there. However, I notice that the output (the order of elements) differs from the one on that page you linked earlier. The order shouldn't be a problem. Join is a great idea. I'd thought it was only for an array of strings. Thanks for all the help!
struct postblit not called, but still destructed
When a struct is passed to a function as argument, it is first copied and at the end destructed. But in the following code it is not copied, yet still destructed? module main; import std.stdio; struct C { A[] _objs; this(A[] objs...) { writeln(` C this()`); _objs = objs; // A.this(this) is not called // yet A.~this IS called } } struct B { A sup; alias sup this; this(A a) { writeln(count, ` B this()`); sup = a; } } struct A { static int count; this(int n) { count++; writeln(count, ` A this()`); } this(this) { count++; writeln(count, ` A this(this)`); } ~this() { count--; writeln(count, ` A ~this()`); } } void main() { A a = A(1); writeln(a.count == 1); B b = B(a); writeln(a.count == 2); C c = C(b); writeln(a.count == 3); }
Re: Should formattedWrite take the outputrange by ref?
On Sunday, 19 January 2014 at 15:28:04 UTC, Tobias Pankrath wrote: On Sunday, 19 January 2014 at 15:12:07 UTC, Tobias Pankrath wrote: On Sunday, 19 January 2014 at 15:03:13 UTC, monarch_dodra wrote: So, my conclusion, "*" might be a workable solution. But simply taking by ref would be cleaner, and make more sense as a whole. Or a special template constraint path for T*. foo(T)(T t) if (is(T = Q*)) && manyOtherChecks!(Q) foo(T)(T t) if (!is(T = Q*)) && manyOtherChecks!(T) Maybe that will break less code. But maybe we really should go for taking the output range by reference. See https://d.puremagic.com/issues/show_bug.cgi?id=10291 https://d.puremagic.com/issues/show_bug.cgi?id=9102 Created a new report for this: https://d.puremagic.com/issues/show_bug.cgi?id=11951 Thanks! I'll look into these.
Re: Python calling D
On Wed, 2013-12-11 at 12:56 +0100, John Colvin wrote: > On Wednesday, 11 December 2013 at 11:41:11 UTC, Chris wrote: […] > > Have you had a look at this: > > > > http://pyd.dsource.org/ > > https://github.com/dansanduleac/pyd > > both of those are out of date, this is where development is now: > https://bitbucket.org/ariovistus/pyd Sorry to be late coming to this. It would great to be able to push D as a CPython extension language. However the state of pyd.dsource.org and places reached from it do make it seem that the project died in 2009. ariovistus' GitHub project on Bitbucket is moving but everything else appears to be a problem. Is it possible to decide on a location for activity, create some infrastructure, and then get the old stuff cleaned out. My start point is to get PyD working in virtualenvs for Python 2.7 and Python 3.3. Findout out what the SCons and Tup stuff is for would be useful. On the side I could help with documentation and stuff, but only if it can be done by DVCS and pull requests with email, I am not interested in non DVCS wikis nor forums. -- Russel. = Dr Russel Winder t: +44 20 7585 2200 voip: sip:russel.win...@ekiga.net 41 Buckmaster Roadm: +44 7770 465 077 xmpp: rus...@winder.org.uk London SW11 1EN, UK w: www.russel.org.uk skype: russel_winder
How can i get the value from an enum when passed to a function?
How can i get the value from an enum when passed to a function? For example i have the following code: import std.stdio; enum E : string { one = "1", two = "2", } void print(E e) { writefln("%s", e); } void main(string[] args) { print(E.one); } The output is 'one'. How can i get at the value '1' instead. I could change the print function to accept a string like this: void print(string e) { writefln("%s", e); } but i lose the constraint of using an enum for the values.
Re: How can i get the value from an enum when passed to a function?
On Sunday, 19 January 2014 at 18:07:46 UTC, Tobias Pankrath wrote: You'll need to cast the value, but you can guard this cast using std.traits.OriginalType or write a toOType function. auto toOType(E)(E e) if(is(E == enum)) { return cast(OriginalType!E) e; } I never get these is-expressions right on first try, but the idea should be clear. You don't have to use an explicit cast. Enum values can be implicitly converted to their base enum type: --- string str = E.one; writeln(str); // prints "1" --- If DMD pull request #1356[1] is pulled, I think we'll be able to do: --- writeln(string(E.one)); // prints "1" --- I recommend avoiding the cast operator whenever possible. [1] https://github.com/D-Programming-Language/dmd/pull/1356
Re: struct postblit not called, but still destructed
Am 19.01.2014 18:48, schrieb Lemonfiend: import std.stdio; struct C { A[] _objs; this(A[] objs...) { writeln(` C this()`); _objs = objs; // A.this(this) is not called // yet A.~this IS called } } struct B { A sup; alias sup this; this(A a) { writeln(count, ` B this()`); sup = a; } } struct A { static int count; this(int n) { count++; writeln(count, ` A this()`); } this(this) { count++; writeln(count, ` A this(this)`); } ~this() { count--; writeln(count, ` A ~this()`); } } void main() { A a = A(1); writeln(a.count == 1); B b = B(a); writeln(a.count == 2); C c = C(b); writeln(a.count == 3); } Yes this looks like a bug to me. Please file a bug report at https://d.puremagic.com/issues/ Kind Regards Benjamin Thaut
Re: struct postblit not called, but still destructed
I just tried the new beta, and the issue remains.
Re: How can i get the value from an enum when passed to a function?
On Sunday, 19 January 2014 at 17:37:54 UTC, Gary Willoughby wrote: How can i get the value from an enum when passed to a function? For example i have the following code: import std.stdio; enum E : string { one = "1", two = "2", } void print(E e) { writefln("%s", e); } void main(string[] args) { print(E.one); } The output is 'one'. How can i get at the value '1' instead. I could change the print function to accept a string like this: void print(string e) { writefln("%s", e); } but i lose the constraint of using an enum for the values. You'll need to cast the value, but you can guard this cast using std.traits.OriginalType or write a toOType function. auto toOType(E)(E e) if(is(E == enum)) { return cast(OriginalType!E) e; } I never get these is-expressions right on first try, but the idea should be clear.
Re: Should formattedWrite take the outputrange by ref?
On Sunday, 19 January 2014 at 15:12:07 UTC, Tobias Pankrath wrote: On Sunday, 19 January 2014 at 15:03:13 UTC, monarch_dodra wrote: So, my conclusion, "*" might be a workable solution. But simply taking by ref would be cleaner, and make more sense as a whole. Or a special template constraint path for T*. foo(T)(T t) if (is(T = Q*)) && manyOtherChecks!(Q) foo(T)(T t) if (!is(T = Q*)) && manyOtherChecks!(T) Maybe that will break less code. But maybe we really should go for taking the output range by reference. See https://d.puremagic.com/issues/show_bug.cgi?id=10291 https://d.puremagic.com/issues/show_bug.cgi?id=9102 Created a new report for this: https://d.puremagic.com/issues/show_bug.cgi?id=11951
Re: Should formattedWrite take the outputrange by ref?
On Saturday, 18 January 2014 at 23:06:42 UTC, Tobias Pankrath wrote: I actually didn't think that a ptr (to output range) would work. This way we can have best of both worlds and I'm happy with it. A fun fact is that since "." notation works with pointers, more often than not, if "T" verifies some trait "isOutputRange", more often than not, so will "T*". But this is more of a by-product than an actual rule, and, as a rule of thumb, may not be something you want to rely on in a general sense. Limitations include: Type checking: If "R" is a random access range, "R*" will only be an input range, because "p.save" will return an "R", and not an "R*" :/ Also, it is limited to member functions, and not generic UFCS: For example, while in the general sense, "R is input range" => "R* is input range", this will fail for "T[]*", because slices have a non-member popFront, so "p.popFront()" will not actually match a function, and "T[]*" will fail the input range validation :/ So, my conclusion, "*" might be a workable solution. But simply taking by ref would be cleaner, and make more sense as a whole.
Re: Should formattedWrite take the outputrange by ref?
On Sunday, 19 January 2014 at 15:03:13 UTC, monarch_dodra wrote: So, my conclusion, "*" might be a workable solution. But simply taking by ref would be cleaner, and make more sense as a whole. Or a special template constraint path for T*. foo(T)(T t) if (is(T = Q*)) && manyOtherChecks!(Q) foo(T)(T t) if (!is(T = Q*)) && manyOtherChecks!(T) Maybe that will break less code.
Re: Better idea for double list comprehension?
CJS: units[s] = unitlist.filter!(x => any!(y => s==y)); One of your problems is that any that needs some range to work on. Bye, bearophile
Re: Better idea for double list comprehension?
On Sunday, 19 January 2014 at 06:57:37 UTC, CJS wrote: Ah, I'd been wondering if there was something like this. But why does it need unitlist's address? (Assume & has the same meaning as in C and C++.) Look at the docs for Appender. It can either provide its own storage, or use an existing one. In the latter case you feed it a pointer to your array and it uses that. This one seems like it should be unitlist.filter!(x => x.any!(y => s==y)).array(); Oh. Duh. But what is the .array() at the end doing? Allocating a new array for the results of the filter, since it's basically just a lazily computed range rather than actual storage for the results? Yes. But in this case you'd have to allocate anyways, to fill the units[s] array. I'm just trying to match what the python code was doing. In that case the line Ah, I see. peers = dict((s, set(sum(units[s],[]))-set([s])) for s in squares) was using sum to concatenate a bunch of lists together and then remove the element. But I miscounted the parentheses and didn't notice the '-' was after the concatenated lists were tured into a set. The following code appears to do what I want, but the string temporary and appender are a bit ugly. Any suggestions on getting rid of them? foreach(s; squares){ peers[s] = units[s].join().sort().uniq().filter!(a => a!=s).array(); } That's std.array.join() there. However, I notice that the output (the order of elements) differs from the one on that page you linked earlier.
Re: Better idea for double list comprehension?
On Sunday, 19 January 2014 at 02:10:01 UTC, CJS wrote: That's more concise but I also think it's more confusing. I assume that to!string is doing the exact same thing, but I was hoping for something to do the appropriate implicit conversations. Especially to a range of length 1, though I can understand that kind of auto-magical conversion would be annoying in a number of important instances. Does not compute. You mean implicit conversion of single character to a range? I changed the code to this: import std.stdio : writeln; import std.range : chunks, chain; import std.algorithm; import std.array; import std.conv; auto cross(R1, R2)(R1 A, R2 B) { return cartesianProduct(A, B).map!(ab => ab[].text).array; } void main(){ const string letters = "ABCDEFGHI"; const string digits = "123456789"; auto cols = digits; auto rows = letters; auto squares = cross(rows, cols); string[][] unitlist; You may want to use an appender here. It's more efficient than ~= , and lets you transform those foreach loops into one-liners :) auto app = appender(&unitlist); /+ foreach(c; cols){ unitlist ~= cross(rows, to!string(c)); } foreach(r; rows){ unitlist ~= cross(to!string(r), cols); } foreach(r; chunks(rows, 3)){ foreach(c; chunks(cols, 3)){ unitlist ~= cross(to!string(r),to!string(c)); } } +/ app.put(cols.map!(x => cross(rows, x.text))); app.put(rows.map!(x => cross(x.text, cols))); app.put(chunks(rows,3).map!(r => chunks(cols,3).map!(c => cross(r.text, c.text; string[][][string] units; string[][string] peers; foreach(s; squares){ units[s] = unitlist.filter!(x => any!(y => s==y)); \\line 37 } This one seems like it should be unitlist.filter!(x => x.any!(y => s==y)).array(); foreach(s; squares){ peers[s] = remove(chain(units[s]), s); \\line 41 } This one I don't understand. chain(units[s]) ? That's the same as units[s]. remove() returns a range, in this case string[][].
Re: Better idea for double list comprehension?
Thanks! auto app = appender(&unitlist); Ah, I'd been wondering if there was something like this. But why does it need unitlist's address? (Assume & has the same meaning as in C and C++.) This one seems like it should be unitlist.filter!(x => x.any!(y => s==y)).array(); Oh. Duh. But what is the .array() at the end doing? Allocating a new array for the results of the filter, since it's basically just a lazily computed range rather than actual storage for the results? foreach(s; squares){ peers[s] = remove(chain(units[s]), s); \\line 41 } This one I don't understand. chain(units[s]) ? That's the same as units[s]. remove() returns a range, in this case string[][]. I'm just trying to match what the python code was doing. In that case the line peers = dict((s, set(sum(units[s],[]))-set([s])) for s in squares) was using sum to concatenate a bunch of lists together and then remove the element. But I miscounted the parentheses and didn't notice the '-' was after the concatenated lists were tured into a set. The following code appears to do what I want, but the string temporary and appender are a bit ugly. Any suggestions on getting rid of them? foreach(s; squares){ string[] tmp; auto app2 = appender(&tmp); foreach(t; units[s]) {app2.put(t);} peers[s] = tmp.sort().uniq().filter!(a => a!=s).array(); }
Re: Better idea for double list comprehension?
to!string(c) ===> c.text That's more concise but I also think it's more confusing. I assume that to!string is doing the exact same thing, but I was hoping for something to do the appropriate implicit conversations. Especially to a range of length 1, though I can understand that kind of auto-magical conversion would be annoying in a number of important instances. I changed the code to this: import std.stdio : writeln; import std.range : chunks, chain; import std.algorithm; import std.array; import std.conv; auto cross(R1, R2)(R1 A, R2 B) { return cartesianProduct(A, B).map!(ab => ab[].text).array; } void main(){ const string letters = "ABCDEFGHI"; const string digits = "123456789"; auto cols = digits; auto rows = letters; auto squares = cross(rows, cols); string[][] unitlist; foreach(c; cols){ unitlist ~= cross(rows, to!string(c)); } foreach(r; rows){ unitlist ~= cross(to!string(r), cols); } foreach(r; chunks(rows, 3)){ foreach(c; chunks(cols, 3)){ unitlist ~= cross(to!string(r),to!string(c)); } } string[][][string] units; string[][string] peers; foreach(s; squares){ units[s] = unitlist.filter!(x => any!(y => s==y)); \\line 37 } foreach(s; squares){ peers[s] = remove(chain(units[s]), s); \\line 41 } } On dmd 2.064.2 (downloaded and installed today) on 64-bit linux I get the following errors: sudoku.d(37): Error: cannot resolve type for any!((y) => s == y) /home/cjordan1/dmd2/linux/bin64/../../src/phobos/std/algorithm.d(1381): Error: template instance sudoku.main.__lambda1!(string[]) error instantiating /home/cjordan1/dmd2/linux/bin64/../../src/phobos/std/algorithm.d(1369): instantiated from here: FilterResult!(__lambda1, string[][]) sudoku.d(37):instantiated from here: filter!(string[][]) /home/cjordan1/dmd2/linux/bin64/../../src/phobos/std/algorithm.d(1369): Error: template instance sudoku.main.FilterResult!(__lambda1, string[][]) error instantiating sudoku.d(37):instantiated from here: filter!(string[][]) sudoku.d(37): Error: template instance sudoku.main.filter!((x) => any!((y) => s == y)).filter!(string[][]) error instantiating sudoku.d(41): Error: cannot implicitly convert expression (remove(chain(units[s]), s)) of type string[][] to string[] Lines 37 and 41 are noted in the above code.
Re: Should formattedWrite take the outputrange by ref?
On Saturday, 18 January 2014 at 21:55:54 UTC, Tobias Pankrath wrote: I want to print a tree structure and need to keep track of the indention for different parts of the tree. My idea was to write a generic wrapper for an output range that outputs tabs when it encounters a newline. This wrapper has internal state and if I want to use formattedWrite with this wrapper than state changes don't propagate to the calling context because by value semantics. Short solution: I'm using a class now. Alternatively, pass a pointer: formattedWrite(&writer, ...)
Re: Should formattedWrite take the outputrange by ref?
On Saturday, 18 January 2014 at 22:58:59 UTC, bearophile wrote: monarch_dodra: *I* think it should. File a report, and I'll see what I can do about it. The problem with these kinds of things though might be breaking existing code... Given the frequency of bugs caused by such functions that require a pointer to the data, I think that a breaking change is the smaller problem. Bye, bearophile I actually didn't think that a ptr (to output range) would work. This way we can have best of both worlds and I'm happy with it.
Re: Should formattedWrite take the outputrange by ref?
On Saturday, 18 January 2014 at 21:55:54 UTC, Tobias Pankrath wrote: I want to print a tree structure and need to keep track of the indention for different parts of the tree. My idea was to write a generic wrapper for an output range that outputs tabs when it encounters a newline. This wrapper has internal state and if I want to use formattedWrite with this wrapper than state changes don't propagate to the calling context because by value semantics. Short solution: I'm using a class now. But shouldn't formattedWrite take it's output range by ref? Does anyone else have a use case for this and might this cause any problems? *I* think it should. File a report, and I'll see what I can do about it. The problem with these kinds of things though might be breaking existing code...
Re: Should formattedWrite take the outputrange by ref?
monarch_dodra: *I* think it should. File a report, and I'll see what I can do about it. The problem with these kinds of things though might be breaking existing code... Given the frequency of bugs caused by such functions that require a pointer to the data, I think that a breaking change is the smaller problem. Bye, bearophile
Re: Better idea for double list comprehension?
CJS: Unfortunately my current best attemp doesn't compile: What errors are you seeing? auto cross(R1, R2)(in R1 A, in R2 B){ Better to add a space before the open brace. Also you may want to remove "in" if you want to use cross() on lazy ranges. return cartesianProduct(A,B).map!(ab => ab[].text).array; And a space after the comma. string letters = "ABCDEFGHI"; string digits = "123456789"; And a enum/const/immutable for variables that don't need to change. unitlist ~= cross(rows, to!string(c)); to!string(c) ===> c.text units[s] = filter!(x=>any!(y=>(s==y)))(unitlist); Better to use UFCS here, don't forget spaces around operators: units[s] = unitlist.filter!(x => any!(y => (s == y))); And filter returns a lazy range, so perhaps that doesn't work. For the associative arrays I'm unsure I have the correct calls, but they looked reasonable. Any suggestions? Phobos needs a very handy set(). Bye, bearophile
Should formattedWrite take the outputrange by ref?
I want to print a tree structure and need to keep track of the indention for different parts of the tree. My idea was to write a generic wrapper for an output range that outputs tabs when it encounters a newline. This wrapper has internal state and if I want to use formattedWrite with this wrapper than state changes don't propagate to the calling context because by value semantics. Short solution: I'm using a class now. But shouldn't formattedWrite take it's output range by ref? Does anyone else have a use case for this and might this cause any problems?
Re: Better idea for double list comprehension?
units[s] = unitlist.filter!(x => any!(y => (s == y))); And you don't need a pair of ( ): units[s] = unitlist.filter!(x => any!(y => s == y)); And now you need to feed any with some range. Bye, bearophile
Re: Better idea for double list comprehension?
import std.stdio, std.conv, std.algorithm, std.array; string[] cross(in string A, in string B) { return cartesianProduct(A, B).map!(ab => ab[].text).array; } void main() { cross("ab", "12").writeln; } But note that currently cartesianProduct doesn't return the pairs in a natural order. cross() should be pure. Great. Here's a similar follow-up question. I'm trying to reproduce Peter Novig's Python code for solving Sudoku in D (http://norvig.com/sudoku.html). As a way to understand both his code and D/Phobos better. The entire code chunk I'm working on now is def cross(A, B): "Cross product of elements in A and elements in B." return [a+b for a in A for b in B] digits = '123456789' rows = 'ABCDEFGHI' cols = digits squares = cross(rows, cols) unitlist = ([cross(rows, c) for c in cols] + [cross(r, cols) for r in rows] + [cross(rs, cs) for rs in ('ABC','DEF','GHI') for cs in ('123','456','789')]) units = dict((s, [u for u in unitlist if s in u]) for s in squares) peers = dict((s, set(sum(units[s],[]))-set([s])) for s in squares) Unfortunately my current best attemp doesn't compile: import std.stdio : writeln; import std.range : chunks, chain; import std.algorithm; import std.array; import std.conv; auto cross(R1, R2)(in R1 A, in R2 B){ return cartesianProduct(A,B).map!(ab => ab[].text).array; } void main(){ string letters = "ABCDEFGHI"; string digits = "123456789"; auto cols = digits; auto rows = letters; auto squares = cross(rows, cols); string[][] unitlist; foreach(c; cols){ unitlist ~= cross(rows, to!string(c)); } foreach(r; rows){ unitlist ~= cross(to!string(r), cols); } foreach(r; chunks(rows, 3)){ foreach(c; chunks(cols, 3)){ unitlist ~= cross(to!string(r),to!string(c)); } } string[][][string] units; string[][string] peers; foreach(s; squares){ units[s] = filter!(x=>any!(y=>(s==y)))(unitlist); } foreach(s; squares){ peers[s] = remove(chain(units[s]), s); } } Up until units and peers are defined it works, but I find the to!string conversions ugly. Because of cross being templated I don't think they should be necessary. Taking the cartesian product of a string with a character seems like a reasonable request. Simialrly, so does taking the cartesian product of a string with a range of characters. For the associative arrays I'm unsure I have the correct calls, but they looked reasonable. Any suggestions?
Re: package.d imports
Hi! I made similar questions here a month ago, but also couldn't get definitive answers. I just sent a message about this to the main D forum. Let's see if we have better luck there :-) Cheers, LMB On Fri, Jan 17, 2014 at 5:39 PM, Lemonfiend wrote: > I think this is what you are looking for: http://dlang.org/changelog. >> html#import_package >> > > What an odd place to put it.. > > Too bad, it doesn't mention anything about calling the functions like in > my example, and why some do/don't work. I'd hoped for more. > >
Re: errors with filesystem operations
remove uses DeleteFile, but MSDN says To remove an empty directory, use the RemoveDirectory function. so remove probably won't work on directories.
Re: [Windows & DMD] No callstack when crash with Access violation reading location 0x00000000
Le 13/01/2014 22:47, Benjamin Thaut a écrit : Am 13.01.2014 21:52, schrieb Xavier Bigand: glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,9) glBindBuffer(GL_ARRAY_BUFFER,10) glEnableVertexAttribArray(0) glVertexAttribPointer(0,3,GL_FLOAT,false,12,) glBindBuffer(GL_ARRAY_BUFFER,11) glEnableVertexAttribArray(1) glVertexAttribPointer(1,4,GL_FLOAT,false,16,) glDrawElements(GL_LINE_LOOP,4,GL_UNSIGNED_INT,) GLSL=4 ->glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT) ->->glUseProgram(4) ->->glUniformMatrix4fv(0,1,false,[0.002497,0.00,0.00,0.00,0.00,-0.00,0.00,0.00,0.00,0.00,-0.01,0.00,-1.00,1.00,0.00,1.00]) ->glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,9) ->->glBindBuffer(GL_ARRAY_BUFFER,10) ->->glEnableVertexAttribArray(0) ->->glVertexAttribPointer(0,3,GL_FLOAT,false,12,) ->->glBindBuffer(GL_ARRAY_BUFFER,11) ->->glEnableVertexAttribArray(1) ->->glVertexAttribPointer(1,4,GL_FLOAT,false,16,) ->->glDrawElements(GL_LINE_LOOP,4,GL_UNSIGNED_INT,) GLSL=4 This extract seems to correspond of latest gl command called just before the crash after the window resize. It doesn't seems to have any error here. Yes this indeed looks correct. Maybe its even a bug in the driver. Because it happens right after the window resize graphic resource might got invalid and the driver would need to re-create them. The problem ist most likely that you use two array buffers, one for each attribute, instead of using one array buffer and interleaving the attribute (this is the usual way). I could bet, that if you switch over to the interleaved variant, the problem goes away. You could also try to make the three buffers slightly larger and specifiy different pointers to see which one actually causes the invalid read. So that the calls become: > ->glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,9) > ->->glBindBuffer(GL_ARRAY_BUFFER,10) > ->->glEnableVertexAttribArray(0) > ->->glVertexAttribPointer(0,3,GL_FLOAT,false,12,) > ->->glBindBuffer(GL_ARRAY_BUFFER,11) > ->->glEnableVertexAttribArray(1) > ->->glVertexAttribPointer(1,4,GL_FLOAT,false,16,0016) > ->->glDrawElements(GL_LINE_LOOP,4,GL_UNSIGNED_INT,0004) GLSL=4 You could then see from the access violation which of the three buffers the read attempt fails. You could also try to move the glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,9) right before the glDrawElements call. Kind Regards Benjamin Thaut I am not sure the issue come really from my code, cause it just works fine on ATI cards, I do something Nvidia drivers dislike. I tried to replace GL_LINE_LOOP by triangles, increase buffer size, put the GL_ELEMENT_ARRAY_BUFFER buffer type bind right before glDrawElements without success. Crash only append when I fill text mesh before those ones. So I need dig more.
Re: Better idea for double list comprehension?
CJS: I'm trying to write a D function that does the same as this Python function: def cross(A, B): "Cross product of elements in A and elements in B." return [a+b for a in A for b in B] where A and B are strings. (So cross("ab","12") is ["a1", "b1", "a2", "b2"]). One solution: import std.stdio, std.conv, std.algorithm, std.array; string[] cross(in string A, in string B) { return cartesianProduct(A, B).map!(ab => ab[].text).array; } void main() { cross("ab", "12").writeln; } But note that currently cartesianProduct doesn't return the pairs in a natural order. cross() should be pure. Bye, bearophile
Re: Array of pointers
Nodes are reference types in D, so probably you don't need to use a * for Node. Alternatively use a struct handled by pointer. "auto content;" can't compile, you need a type, or you have to template Node on T and use it for content. Bye, bearophile Youre right, it compiles now, and the object generated is of the same size. I'm still confusing with C. I have some experience with C experience, so I still have to learn tamplates. Thaks for the help. Arjan
Re: errors with filesystem operations
On Friday, 17 January 2014 at 12:52:09 UTC, Hugo Florentino wrote: On Fri, 17 Jan 2014 07:07:35 +, Kagamin wrote: Does it fail for that one directory only or for any directory? Interesting question. I would have to do more tests with odd names, but apparently both remove() and rename() have problems with directories with a blank name. In that case try a path with \\?\ prefix (unparsed path).
Re: Array of pointers
Arjan Fetahu: Since each Node connects to multiple others i came up with this solution. class Node { auto content; Node*[] nodes; //..constructor.. } Nodes are reference types in D, so probably you don't need to use a * for Node. Alternatively use a struct handled by pointer. "auto content;" can't compile, you need a type, or you have to template Node on T and use it for content. Bye, bearophile
Re: Array of pointers
Keep in mind that, unlike in c++, D classes are reference types: class Node { Node[] nodes; // This is valid } Structs are value types though, so using a struct in the above example is illegal. You mean: struct Node { Node[] nodes; } or struct Node { Node*[] nodes; } ? Works both. What's not working is this: struct Node { Node node; } I wanted to heap allocate Nodes which connect to each other via pointers. Since each Node connects to multiple others i came up with this solution. class Node { auto content; Node*[] nodes; //..constructor.. }
Re: Better idea for double list comprehension?
Hit the wrong key and posted too early. I finished the code sample below. My main question was for something prettier and more concise. I feel like the code below is long and not as pretty in comparison to the Python. Sometimes that's an unavoidable consequence of static typing, but I'm not sure that's the case here. On Saturday, 18 January 2014 at 05:40:56 UTC, CJS wrote: I'm trying to write a D function that does the same as this Python function: def cross(A, B): "Cross product of elements in A and elements in B." return [a+b for a in A for b in B] where A and B are strings. (So cross("ab","12") is ["a1", "b1", "a2", "b2"]). It's easy to get something that works the same in D, but I'd like to make it as simple and short as possible. The best I could come up with is string[] cross(string A, string B){ string[] grid; foreach(t; cartesianProduct(A,B)){ grid ~= (to!string(p[0]) ~ to!string(p[1])); } return grid; }
Better idea for double list comprehension?
I'm trying to write a D function that does the same as this Python function: def cross(A, B): "Cross product of elements in A and elements in B." return [a+b for a in A for b in B] where A and B are strings. (So cross("ab","12") is ["a1", "b1", "a2", "b2"]). It's easy to get something that works the same in D, but I'd like to make it as simple and short as possible. The best I could come up with is string[] cross(string A, string B){ string[] grid; foreach(t; cartesianProduct(A,B)){ grid ~= (to!string(p[0]) ~ to!string(p[1]));
Re: Better idea for double list comprehension?
On Saturday, 18 January 2014 at 07:56:15 UTC, Stanislav Blinov wrote: Although that won't give you a string[], but in a dchar[][]. ...but that is solvable: auto strings = array(cross("ab","12").map!"to!string(a)"()); Or maybe even by providing additional overload: auto cross(alias fun,R1,R2)(R1 a, R2 b) { return cross(a,b).map!fun(); } auto strings = array(cross!"to!string(a)"("ab","12"));
Re: Better idea for double list comprehension?
I'd say import std.algorithm; auto cross(R1,R2)(R1 a, R2 b) { return cartesianProduct(a,b).map!"[a[0]]~[a[1]]"(); } You can always: import std.array; auto strings = array(cross("ab","12")); Although that won't give you a string[], but in a dchar[][].
DMD linking fails because of missing _adCmp2 and _adEq2
I regularly rebuild and use DMD git master locally on Ubuntu 13.10. Yesterday my toolchain dmd fails to link all D programs with the error: Example compilation output from dmd /home/per/opt/x86_64-unknown-linux-gnu/dmd/bin/../lib/libphobos2.a(sections_linux_4c8_e6.o):src/rt/sections_linux.d:function _D2rt14sections_linux3DSO11__xopEqualsFKxS2rt14sections_linux3DSOKxS2rt14sections_linux3DSOZb: error: undefined reference to '_adEq2' /home/per/opt/x86_64-unknown-linux-gnu/dmd/bin/../lib/libphobos2.a(sections_linux_4c8_e6.o):src/rt/sections_linux.d:function _D2rt14sections_linux3DSO11__xopEqualsFKxS2rt14sections_linux3DSOKxS2rt14sections_linux3DSOZb: error: undefined reference to '_adEq2' /home/per/opt/x86_64-unknown-linux-gnu/dmd/bin/../lib/libphobos2.a(sections_linux_4c8_e6.o):src/rt/sections_linux.d:function _D2rt14sections_linux3DSO11__xopEqualsFKxS2rt14sections_linux3DSOKxS2rt14sections_linux3DSOZb: error: undefined reference to '_adEq2' /home/per/opt/x86_64-unknown-linux-gnu/dmd/bin/../lib/libphobos2.a(sections_linux_4c8_e6.o):src/rt/sections_linux.d:function _D2rt14sections_linux3DSO11__xopEqualsFKxS2rt14sections_linux3DSOKxS2rt14sections_linux3DSOZb: error: undefined reference to '_adEq2' collect2: error: ld returned 1 exit status When I grep for it only dmd binary matches this symbol, not libphobos. Both my dmd and phobos are up-to-date. I've tried both ld.bfd and ld.gold. What is wrong?
Study on hash associative arrays
Through Reddit I've found posts about hash-based associative arrays: http://bannalia.blogspot.it/2013/10/implementation-of-c-unordered.html http://bannalia.blogspot.it/2014/01/a-better-hash-table.html Those little images like this one are excellent at explaining in a short space the basic structure of a data structure: http://4.bp.blogspot.com/-jh0W64vfSt8/UsmZMel5gQI/AvU/k6ThAu4mL2M/s400/boost.multiindex_1.png I think the online documentation should have images like this one for AAs, and other data structures. Do you know what's the structure of the D built-in AAs, and are the ideas in those two posts useful to improve D AAs? Bye, bearophile
Re: Pure
On Wednesday, 8 January 2014 at 20:21:22 UTC, John Carter wrote: > Very well written, a pleasure to read. And very hard to translate! :) Leaping off the immediate topic of computer language D into the realm of human languages English and Turkish... With the Sapir–Whorf hypothesis in the back of my mind... What makes it harder to translate? Is there a human language in which these concepts would be more easily discussed? I was always fascinated by early translations (1980 and before era) of Japanese machine manuals... It was tempting to find the mistranslations funny, until I realised... * You could never remember the words. Your memory is fundamentally governed by the language you speak. Thus when you try remember (and relate to a colleague) a subtly garbled chunk of that language, your brain autocorrects it and refuses to reproduce the mistakes! * The differences indicated curious and subtle differences in thought processes of the original authors and translators. Not better or worse processes. Different. Interesting. Subtle. * The categories of mistakes made by, say German German to English translators, were very different. So I have always been fascinated by Sapir-Whorf, but it seems to be very subtle and nuanced and unexpected in practical effect. On Thu, Jan 9, 2014 at 8:26 AM, Ali Çehreli wrote: On 01/08/2014 11:09 AM, Paolo Invernizzi wrote: This one is a good introduction, or at least the best one I can remember: http://klickverbot.at/blog/2012/05/purity-in-d/ Very well written, a pleasure to read. And very hard to translate! :) In case a Turkish reader is interested, here is the translation: http://ddili.org/makale/saflik.html Ali On a small tangent, I believe the Sapir-Whorf thesis has been disproved. However, I definitely think there might be a similar effect of programming languages on programmers.
Re: Thread Building Blocks
It seems to be somewhat similar to std.parallelism (http://dlang.org/phobos/std_parallelism.html) I have seen that before, didn't know if there was anything closer with the task scheduler and worker threads described in the documentation for TBB, or if that was the closest thing. I see that it does have a TaskPool and worker threads within that, but they seem to be only using a shared queue and individual worker thread queues. So a task spawning another task does not really have some of the efficiency benefits that it does in TBB (where the worker threads maintain a dequeue instead). I also didn't see any mention of task stealing, but maybe it does that internally. Not sure. I can take a look at the code for it I suppose.
Re: A little DUB question
On Tuesday, 31 December 2013 at 10:35:46 UTC, thedeemon wrote: I've missed all the DUB discussions here and couldn't find the answer to my question in the docs, so here it is, very simple: I've got an app with one dependency stated in package.json as "dependencies": { "pegged": "~master" } When I build my app with dub build --build=release the app itself gets compiled in release mode, but the library it depends on (in this case Pegged) gets compiled in Debug, so the binary ends up 2-3 times larger than if I build everything myself without DUB. What is the right way to build everything in release using DUB here? Looks like a bug. In the meantime you can compile combined. $ dub --build=release --combined
Re: When is a class's destructor called?
On Sunday, 29 December 2013 at 10:16:33 UTC, ponce wrote: If you want deterministic destruction, you have plenty of choices: - scoped! - using structs instead - scope(exit) - RefCounted! - Unique! - ... Do you happen to know of any clever technique to make object, and everything that inherits from it, a referenced counted object?
Re: When is a class's destructor called?
Mike: How does the garbage collector know when something has gone out of scope The garbage collector doesn't know that. Look in Wikipedia how a Mark&Sweep GC works. Bye, bearophile
Re: When is a class's destructor called?
On 12/29/2013 04:00 AM, Mike wrote: On Sunday, 29 December 2013 at 10:16:33 UTC, ponce wrote: If you want deterministic destruction, you have plenty of choices: - scoped! - using structs instead - scope(exit) - RefCounted! - Unique! - ... Do you happen to know of any clever technique to make object, and everything that inherits from it, a referenced counted object? There is std.typecons.RefCounted: http://dlang.org/phobos/std_typecons.html#.RefCounted Ali
Re: When is a class's destructor called?
Ok, I understand that, but since I don't have a garbage collector, what must I implement to call the destructor when it goes out of scope? Another way of asking the question is: How does the garbage collector know when something has gone out of scope and is therefore safe to collect? And where is that implemented in the runtime? If you want deterministic destruction, you have plenty of choices: - scoped! - using structs instead - scope(exit) - RefCounted! - Unique! - ... Yet using classes for ressources is not composable. It's either: - using classes for the convenience and deal with resource release manually - using structs It's an open quesiton for me which choice is best.
Re: nextPermutation: why possible for dchar but not for char?
2. Why does nextPermutation hang up for empty arrays? I suppose that's a bug? I suppose so. Please file it. If it is deemed "illegal", at the very least, it should throw. My fault, i mis-used it. The right behavior for ranges of size 0 and 1 is checked explicitly in the unittests. Ivan Kazmenko.
Re: nextPermutation: why possible for dchar but not for char?
On Saturday, 28 December 2013 at 23:38:38 UTC, Ivan Kazmenko wrote: Ouch, is it an exception hard-coded into the language itself? I thought it's just the nextPermutation's parameter type restrictions which don't allow "char []"... No, a "char[]" is just a "char[]" as far as the language is concerned[1]. However, for the *phobos* range abstraction, (the front/popFront/empty) primitives, a char[] is a range of dchars. Once you've defined char[] as such a range, it affects all of phobos. It's critiqued every now and then, but overall, it has proven to increase code correctness, at the cost (sometimes) of rejecting code that might be incorrect. Long story short: If you want to handle UTF, you have to handle it *explicitly*. *I* think it is a good compromise. [1] the *only* place (AFAIK) that dmd looks at a string as a range of dchars is in a "foreach(dchar c; s)" loop. But even then, if you don't specify "dchar", then c will default to char.
Re: When is a class's destructor called?
Also destructors are not guaranteed to be run by D specification. It is perfectly legal to skip such cleanup step upon program termination. http://dlang.org/class.html#destructors : "The garbage collector is not guaranteed to run the destructor for all unreferenced objects. Furthermore, the order in which the garbage collector calls destructors for unreference objects is not specified. This means that when the garbage collector calls a destructor for an object of a class that has members that are references to garbage collected objects, those references may no longer be valid. This means that destructors cannot reference sub objects. This rule does not apply to auto objects or objects deleted with the DeleteExpression, as the destructor is not being run by the garbage collector, meaning all references are valid."
Re: nextPermutation: why possible for dchar but not for char?
On Saturday, 28 December 2013 at 23:07:21 UTC, monarch_dodra wrote: Also, the example at http://dlang.org/phobos/std_algorithm.html#nextPermutation is wrong: while (nextPermutation(a)) { } should in fact be do { } while (nextPermutation(a)); as above, or we miss the very first permutation. Noted. I'll try to fix that in the comming days. Or if anybody else submits the pull, I'll merge it (*hint* *hint*, *wink*) Here it is: https://github.com/D-Programming-Language/phobos/pull/1822 Or should it have been done in a separate branch?.. The bugtracker (http://d.puremagic.com/issues/) seems to be down at the moment, so there's no issue associated with it. Ivan Kazmenko.
A little DUB question
I've missed all the DUB discussions here and couldn't find the answer to my question in the docs, so here it is, very simple: I've got an app with one dependency stated in package.json as "dependencies": { "pegged": "~master" } When I build my app with dub build --build=release the app itself gets compiled in release mode, but the library it depends on (in this case Pegged) gets compiled in Debug, so the binary ends up 2-3 times larger than if I build everything myself without DUB. What is the right way to build everything in release using DUB here?
Re: extern(C) function declarations and extra keywords.
On 2013-12-28 22:47, Jeremy DeHaan wrote: Since the C functions can't access anything from D code save for what is passed through as parameters, can it be called pure? And if so, does the compiler know how to distinguish C and D in this instance and make it inherently pure? Does purity do anything in terms of speed/safety here? It can access global variables. -- /Jacob Carlborg
Re: When is a class's destructor called?
On Sunday, 29 December 2013 at 06:53:08 UTC, Mike Parker wrote: On 12/29/2013 2:03 PM, Mike wrote: x's destructor never gets called. What do I need to implement to have the destructor called when x goes out of scope? Class destructors are not called when an object goes out of scope. They are called by the garbage collector only when memory needs to be reclaimed or during the cleanup cycle during app shutdown. Ok, I understand that, but since I don't have a garbage collector, what must I implement to call the destructor when it goes out of scope? Another way of asking the question is: How does the garbage collector know when something has gone out of scope and is therefore safe to collect? And where is that implemented in the runtime?
Re: When is a class's destructor called?
On Sunday, 29 December 2013 at 06:58:03 UTC, Mike wrote: Ok, I understand that, but since I don't have a garbage collector, what must I implement to call the destructor when it goes out of scope? Patch compiler to make all classes scope classes. But that won't be D anymore.
Re: When is a class's destructor called?
Ali Çehreli: On 12/29/2013 04:00 AM, Mike: Do you happen to know of any clever technique to make object, and everything that inherits from it, a referenced counted object? There is std.typecons.RefCounted: http://dlang.org/phobos/std_typecons.html#.RefCounted I think it only works on a single object, not on the whole tree. (And I think RefCounted is not used often in D.) Bye, bearophile
Shared library ld issue?
So, these are the commands I put in: ../gdc/x86_64/gdc -c -fPIC -B ../gdc/x86_64 -I ../gdc/x86_64/phobos test.d This one worked fine, as expected. The problem is here: ../gdc/x86_64/gdc -lgphobos2 -shared -B ../gdc/x86_64 test.o -o test.so And this is what the problem outputs: ld: /lib/../lib64/libgphobos2.a(minfo.o): relocation R_X86_64_32 against `_D32TypeInfo_APxS6object10ModuleInfo6__initZ' can not be used when making a shared object; recompile with -fPIC /lib/../lib64/libgphobos2.a: error adding symbols: Bad value I'm obviously compiling with -fPIC. I've been googling this for hours straight and still don't know what to do, perhaps someone here could impart on me some knowledge?
Re: When is a class's destructor called?
On 12/29/2013 2:03 PM, Mike wrote: x's destructor never gets called. What do I need to implement to have the destructor called when x goes out of scope? Class destructors are not called when an object goes out of scope. They are called by the garbage collector only when memory needs to be reclaimed or during the cleanup cycle during app shutdown.
Re: nextPermutation: why possible for dchar but not for char?
On Saturday, 28 December 2013 at 23:05:54 UTC, monarch_dodra wrote: 1. This is a minimal example of trying the permutations of a character array. - import std.algorithm; void main () { char [] a; do { } while (nextPermutation(a)); } - This gives a compile error. However, it works when I change "char [] a" to "dchar [] a". Why? Because next permutation (AFAIK) works on ranges with *assignable* elements, and "char[]" is not such a range: It is a read-only range of dchars. Ouch, is it an exception hard-coded into the language itself? I thought it's just the nextPermutation's parameter type restrictions which don't allow "char []"... 2. Why does nextPermutation hang up for empty arrays? I suppose that's a bug? I suppose so. Please file it. If it is deemed "illegal", at the very least, it should throw. OK, will do that tomorrow (on Sunday). Also, the example at http://dlang.org/phobos/std_algorithm.html#nextPermutation is wrong: while (nextPermutation(a)) { } should in fact be do { } while (nextPermutation(a)); as above, or we miss the very first permutation. Noted. I'll try to fix that in the comming days. Or if anybody else submits the pull, I'll merge it (*hint* *hint*, *wink*) Hmm, I'll look into how hard is that for a start... Ivan Kazmenko.
When is a class's destructor called?
I'm trying to implement a very minimal D runtime for the ARM Cortex-M platform. I've been quite successful so far, but I'm now getting into reference types and I need to understand better what D does under the hood. I have a working malloc/free implementation, but don't have a garbage collector. I'm not yet sure if I want a garbage collector, so at the moment, I'm trying to implement something simple. Consider the following code modeled after the example at http://dlang.org/memory.html#newdelete: * class X { __gshared uint _x; new(size_t nBytes) { Trace.WriteLine("Constructing"); void* p; p = malloc(nBytes); if (p == null) { //TODO: //throw new OutOfMemoryError(); } return p; } ~this() { Trace.WriteLine("Destructor"); } delete(void* p) { if (p != null) { free(p); } Trace.WriteLine("Destroying"); } } void DoX() { X x = new X(); x._x = 123; Trace.WriteLine(x._x); //Why doesn't x's destructor get called here. } //My entry point void main() { DoX(); Trace.WriteLine("Done"); while(true) { } } ** The output is as follows: -- Constructing 56 Done x's destructor never gets called. What do I need to implement to have the destructor called when x goes out of scope? I'm using GDC 4.8 cross-compiled for arm-none-eabi on a Linux 64-bit host. Thanks, Mike
Re: nextPermutation: why possible for dchar but not for char?
On Saturday, 28 December 2013 at 22:55:39 UTC, Ivan Kazmenko wrote: Another quick question, two of them. 1. This is a minimal example of trying the permutations of a character array. - import std.algorithm; void main () { char [] a; do { } while (nextPermutation(a)); } - This gives a compile error. However, it works when I change "char [] a" to "dchar [] a". Why? I understand that permuting a char [] array might be wrong way to go when dealing with Unicode. But what if, at this point of the program, I am sure I'm dealing with ASCII and just want efficiency? Should I convert to ubyte [] somehow - what's the expected way then? Because next permutation (AFAIK) works on ranges with *assignable* elements, and "char[]" is not such a range: It is a read-only range of dchars. Arguably, the implementation *could* work for it, *even* while taking into consideration unicode (using the underlying UTF8 knowledge). You should file an ER for that. But currently, this is not the case, so you have to look for a workaround. The "cast (ubyte [])" works, but "to!(ubyte [])" fails at runtime, expecting a string representation of the array, not its raw contents. You can use "representation" to "conveniently" transform a string/wstring/dstring to its corresponding numeric type (ubyte/ushort/uint). That *should* work. "Unfortunatly", "to!T(string)" often does a parse. As convenient as it is, I think the added ambiguity makes it often wrong. 2. Why does nextPermutation hang up for empty arrays? I suppose that's a bug? I suppose so. Please file it. If it is deemed "illegal", at the very least, it should throw. Ivan Kazmenko.
Re: nextPermutation: why possible for dchar but not for char?
On Saturday, 28 December 2013 at 22:58:43 UTC, Ivan Kazmenko wrote: Also, the example at http://dlang.org/phobos/std_algorithm.html#nextPermutation is wrong: while (nextPermutation(a)) { } should in fact be do { } while (nextPermutation(a)); as above, or we miss the very first permutation. Noted. I'll try to fix that in the comming days. Or if anybody else submits the pull, I'll merge it (*hint* *hint*, *wink*)