Nice example for operator overload resulting in readable linear algebra expressions
I just want to share a view lines of code. The availability of operator overloading can result in very short and precise code for linear algebra. To test/explore it a little I just modified the alias this example: ``` #!/usr/bin/env rdmd struct Point { double[2] p; // Forward all undefined symbols to p alias p this; auto opBinary(string op)(Point rhs) { static if (op == "+") { Point ret; ret[0] = p[0] + rhs.p[0]; ret[1] = p[1] + rhs.p[1]; return ret; } else static if (op == "-") { Point ret; ret[0] = p[0] - rhs.p[0]; ret[1] = p[1] - rhs.p[1]; return ret; } else static if (op == "*") return p[0] * rhs.p[0] + p[1] * rhs.p[1]; else static assert(0, "Operator " ~ op ~ " not implemented"); } } void main() { import std.stdio;// : writefln,write; // Point behaves like a `double[2]` ... Point p1, p2; p1 = [2, 1], p2 = [1, 1]; // ... but with extended functionality writef("p1*(p1 + p2) = %s*(%s + %s) =", p1, p1, p2); write(p1 * (p1 + p2)); // compare this to code without operator overload: } ``` Compare: ``p1 * (p1 + p2)`` to something with a structure like ``dot(p1,(add(p1,p2)).`` (With the Dlangs UFCS it might become: ``p1.dot(p1.add(p2))`` )
Re: writeln the struct from the alis this Example from the home page
On Thursday, 18 November 2021 at 16:08:22 UTC, Paul Backus wrote: On Thursday, 18 November 2021 at 13:51:42 UTC, Martin Tschierschke wrote: [...] You can define a `toString` method, like this: ```d string toString() { import std.conv; return p.to!string; } ``` You can find more information about `toString` in the documentation here: https://dlang.org/phobos/std_format_write.html By the way, the reason your original version does not work is that `p` is `private`, so `writeln` cannot access it. If you change `p` to be `public`, it will work without a `toString` method. Thank you, just removing ``private `` and it worked!
writeln the struct from the alis this Example from the home page
Hello, if you take the example from the home page, with the additional last line: ```d struct Point { private double[2] p; // Forward all undefined symbols to p alias p this; double dot(Point rhs) { return p[0] * rhs.p[0] + p[1] * rhs.p[1]; } } void main() { import std.stdio : writeln; // Point behaves like a `double[2]` ... Point p1, p2; p1 = [2, 1], p2 = [1, 1]; assert(p1[$ - 1] == 1); // ... but with extended functionality writeln("p1 dot p2 = ", p1.dot(p2)); // additional line: writeln(p1); // is not possible ! } ``` /usr/include/dmd/phobos/std/format.d(3193): Error: no [] operator overload for type Point .. ... How to define, that for Point the same formatting should be used as for double[2] ?
Re: Idiomatic D code to avoid or detect devision by zero
On Monday, 3 August 2020 at 15:33:54 UTC, Dominikus Dittes Scherkl wrote: [...] For really long expressions you could also split it on multiple lines: c = (b_expression == 0) ? (d_longer_expression) : (a_expression/b_expression); +1 looks clean!
Re: Idiomatic D code to avoid or detect devision by zero
On Friday, 31 July 2020 at 14:18:15 UTC, Steven Schveighoffer wrote: On 7/31/20 9:55 AM, Martin Tschierschke wrote: What would be the idiomatic way to write a floating point division occuring inside a loop and handle the case of division by zero. c = a/b; // b might be zero sometimes, than set c to an other value (d). (In the moment I check the divisor being zero or not, with an if-than-else structure, but I find it ugly and so I ask here.) c = b == 0 ? d : a/b; I don't think a function would be shorter or clearer... c = div(a, b, d); Alternatively, you could use a type to effect the behavior you want. -Steve Thanks, for the hints. I find the ? : - expressions sometimes hard to reed, especially when a and b are not so simple expressions. I prefer putting additional bracket around: c = (b_expression == 0) ? (d_longer_expression) : (a_expression/b_expression); ???
Re: Idiomatic D code to avoid or detect devision by zero
On Friday, 31 July 2020 at 15:19:25 UTC, Andrea Fontana wrote: On Friday, 31 July 2020 at 13:55:18 UTC, Martin Tschierschke wrote: What would be the idiomatic way to write a floating point division occuring inside a loop and handle the case of division by zero. c = a/b; // b might be zero sometimes, than set c to an other value (d). (In the moment I check the divisor being zero or not, with an if-than-else structure, but I find it ugly and so I ask here.) You should give a look at: https://dlang.org/phobos/std_experimental_checkedint.html You can try with checked!Throw and catch exceptions, for example. Andrea Thanks, I will look at it.
Idiomatic D code to avoid or detect devision by zero
What would be the idiomatic way to write a floating point division occuring inside a loop and handle the case of division by zero. c = a/b; // b might be zero sometimes, than set c to an other value (d). (In the moment I check the divisor being zero or not, with an if-than-else structure, but I find it ugly and so I ask here.)
Re: Compare string with German umlauts
On Monday, 18 May 2020 at 14:28:33 UTC, Steven Schveighoffer wrote: What you need is to normalize the data for comparison: https://dlang.org/phobos/std_uni.html#normalize For more reference: https://en.wikipedia.org/wiki/Combining_character -Steve I checked it again but could not reproduce the original error, it somehow seems that my compare string contained another error. But nevertheless good to know how to deal with encoding errors!
Re: Compare string with German umlauts
On Monday, 18 May 2020 at 14:28:33 UTC, Steven Schveighoffer wrote: On 5/18/20 9:44 AM, Martin Tschierschke wrote: [...] using == on strings is going to compare the exact bits for equality. In unicode, things can be encoded differently to make the same grapheme. For example, ö is a code unit that is the o with a diaeresis (U+00F6). But you could encode it with 2 code points -- a standard o, and then an diaeresis combining character (U+006F, U+0308) What you need is to normalize the data for comparison: https://dlang.org/phobos/std_uni.html#normalize Thank you, I will check that.
Re: Compare string with German umlauts
On Monday, 18 May 2020 at 14:22:31 UTC, WebFreak001 wrote: [...] It solved the problem, but what is the right way to use umlauts (encode them) inside the program? Your code should have already worked like that, assuming your input file is a UTF-8 file. Check with an editor like Notepad++ or Visual Studio Code what the actual encoding of your text file is. In D all strings you specify in source are UTF-8 bytes in the end and a byte-by-byte comparison like with your line == "..." will cause it to fail if line is not UTF-8. Thank you, I will check your hints!
Compare string with German umlauts
Hi, I have to find a certain line in a file, with a text containing umlauts. How do you do this? The following was not working: foreach(i,line; file){ if(line=="My text with ö oe, ä ae or ü"){ writeln("found it at line",i) } } I ended up using line.canFind("with part of the text without umlaut"). It solved the problem, but what is the right way to use umlauts (encode them) inside the program?
Deprecation message from phobos compiling a vibe.d app.
When building my small vibe.d app I am getting this messages twice: /usr/include/dmd/phobos/std/range/primitives.d(174,38): Deprecation: alias byKeyValue this is deprecated - Iterate over .byKeyValue instead. /usr/include/dmd/phobos/std/range/primitives.d(176,27): Deprecation: alias byKeyValue this is deprecated - Iterate over .byKeyValue instead. /usr/include/dmd/phobos/std/range/primitives.d(174,38): Deprecation: alias byKeyValue this is deprecated - Iterate over .byKeyValue instead. /usr/include/dmd/phobos/std/range/primitives.d(176,27): Deprecation: alias byKeyValue this is deprecated - Iterate over .byKeyValue instead. Unfortunately I don't know what is triggering this and what to do about. The build is working, so it is more a question of elegance.
Re: Meta question - what about moving the D - Learn Forum to a seperate StackExchange platform?
On Friday, 18 October 2019 at 13:38:11 UTC, Ron Tarrant wrote: On Friday, 18 October 2019 at 07:35:21 UTC, Martin Tschierschke wrote: I very often end with a solution found on one of the StackExchange forums like > StackOverflow or AskUbuntu etc. I have found that StackExchange does often have answers, but I can't say I like asking questions on there, especially if the question is almost-the-same-but-not-the-same as a question asked earlier. In cases like this, I've been told that the previous answer applies to my question, even when it doesn't. In one instance, a moderator closed my question without reading the details in order to find out that, no, it's not the same question at all... and then refuse to reopen the question when I point this out. So, although I'll continue to use StackExchange as an historical resource, I would rather not depend on it for getting answers to new questions. This is why I am for an own D Learn Forum, the process is (partly) described here: https://meta.stackexchange.com/questions/76974/how-can-i-propose-a-new-site The moderators of this should come from this forum community, if this can not be achieved, I am against a move, too.
Re: Meta question - what about moving the D - Learn Forum to a seperate StackExchange platform?
On Friday, 18 October 2019 at 12:41:53 UTC, Paolo Invernizzi wrote: On Friday, 18 October 2019 at 11:45:33 UTC, Seb wrote: On Friday, 18 October 2019 at 10:55:59 UTC, Martin Tschierschke wrote: [...] In the state of the D survey, there were more people in favor of StackOverflow than D.learn, but to be fair the majority voted for "I don't care" https://rawgit.com/wilzbach/state-of-d/master/report.html Maybe it's possible to simply add an up/down vote functionality to the forum only, just keeping the compatibility with the newsgroup ... It's a win/win solution! +1 It may help in the DIP discussions, too! You can just see if an argument for or against a change, is accepted by the majority of thread readers or not. And you can highlight those up-voted arguments to get an better impression about the outcome of the discussion in total.
Re: Meta question - what about moving the D - Learn Forum to a seperate StackExchange platform?
On Friday, 18 October 2019 at 12:51:35 UTC, bachmeier wrote: On Friday, 18 October 2019 at 07:35:21 UTC, Martin Tschierschke wrote: If I search for what ever, not related to D, I very often end with a solution found on one of the StackExchange forums like StackOverflow or AskUbuntu etc. The main advantage is, that all answers can be classified (up/down voted, moderated etc.) This is much better than finding something in the D-Learn Forum where it is difficult to see, if several answers are given are they still valid, especially if they are some years old. I know that this was asked in the D survey and I think it should be on the table again. If we unite for this idea, it should be possible to start an own "DExchange" sub platform. Best regards mt. You can already ask questions on SO. What you are proposing is to close this forum, require registration to ask a question, and let JavaScript developers close questions and treat new users rudely. That doesn't seem like a good idea. The fact that most questions get asked here rather than on SO now suggests that there isn't much demand for SO. I am not for moving just to StackOverflow, but to make an own "DExchange" / "AskD" or what ever named learn platform with and inside the StackExchange [1] technology. This should keep D users together and would avoid mixing with other languages. But I am not sure if this is really achievable for us. [1] https://stackexchange.com/sites#
Re: Meta question - what about moving the D - Learn Forum to a seperate StackExchange platform?
On Friday, 18 October 2019 at 10:23:28 UTC, jmh530 wrote: On Friday, 18 October 2019 at 07:35:21 UTC, Martin Tschierschke wrote: [snip] I think this is something that's been proposed before, but most people are happy with just asking a question here and usually people are pretty good about helping out with answers when possible. Yes, it works as it is, but it is not the best solution to share know how. And if I just think: Hey, your answer is good, in the mailinglist / forum / newsgroup setup it is impossible to easily vote for it and get a count of this votes. I think it is possible to extended the web front end of the forum in this direction and automatically map an '+1' or '-1' comment (in a single line) to a counter which will be displayed beside the commented post. But this is reinventing the wheel... I am just sad, that many very good questions and answers given in the forum are not so easy to find as they should.
Meta question - what about moving the D - Learn Forum to a seperate StackExchange platform?
If I search for what ever, not related to D, I very often end with a solution found on one of the StackExchange forums like StackOverflow or AskUbuntu etc. The main advantage is, that all answers can be classified (up/down voted, moderated etc.) This is much better than finding something in the D-Learn Forum where it is difficult to see, if several answers are given are they still valid, especially if they are some years old. I know that this was asked in the D survey and I think it should be on the table again. If we unite for this idea, it should be possible to start an own "DExchange" sub platform. Best regards mt.
Re: DUB and ddoc - howto?
On Friday, 28 June 2019 at 13:03:17 UTC, Daniel Kozak wrote: Did you try dub build --help? Oh, thank you! I just looked at dub --help | grep -i doc ... and several other places...
DUB and ddoc - howto?
A very simple question, is there an example how to generate documentation with dub? (like dmd -D) My internet search was not successful.
Re: [vibe-d/dub] Lin
On Friday, 7 September 2018 at 16:37:18 UTC, MamoKupe wrote: On Friday, 7 September 2018 at 16:20:40 UTC, MamoKupe wrote: marcinan@marcinan-PC ~/Pulpit/d $ dub init bibe Package recipe format (sdl/json) [json]: d Invalid format, "d", enter either "sdl" or "json". Package recipe format (sdl/json) [json]: Name [bibe]: Description [A minimal D application.]: Author name [Marcin]: License [proprietary]: Copyright string [Copyright © 2018, Marcin]: Add dependency (leave empty to skip) []: vibe-d Added dependency vibe-d ~>0.8.4 /usr/bin/ld: cannot find -lssl /usr/bin/ld: cannot find -lcrypto collect2: error: ld returned 1 exit status Error: linker exited with status 1 /usr/bin/dmd failed with exit code 1. On linux Mint with DUB version 1.11.0, built on Sep 1 2018 sudo apt-get install libssl-dev Solved linking problem for now. Yes, but this should be detected by dub before compilation as a missing dependency not after. Someone told, that is is possible by adding the right params to dub.sdl/.json. As an traditional error most "lets try vibe.d"-people see, I would like to ask for changing this. Regards mt.
Re: Determine if CTFE or RT
On Monday, 25 June 2018 at 08:05:53 UTC, Mr.Bingo wrote: On Monday, 25 June 2018 at 07:02:24 UTC, Jonathan M Davis wrote: On Monday, June 25, 2018 05:47:30 Mr.Bingo via Digitalmars-d-learn wrote: The problem then, if D can't arbitrarily use ctfe, means that there should be a way to force ctfe optionally! If you want to use CTFE, then give an enum the value of the expression you want calculated. If you want to do it in place, then use a template such as template ctfe(alias exp) { enum ctfe = exp; } so that you get stuff like func(ctfe!(foo(42))). I would be extremely surprised if the compiler is ever changed to just try CTFE just in case it will work as an optimization. That would make it harder for the programmer to understand what's going on, and it would balloon compilation times. If you want to write up a DIP on the topic and argue for rules on how CTFE could and should function with the compiler deciding to try CTFE on some basis rather than it only being done when it must be done, then you're free to do so. https://github.com/dlang/DIPs But I expect that you will be sorely disappointed if you ever expect the compiler to start doing CTFE as an optimization. It's trivial to trigger it explicitly on your own, and compilation time is valued far too much to waste it on attempting CTFE when in the vast majority of cases, it's going to fail. And it's worked quite well thus far to have it work only cases when it's actually needed - especially with how easy it is to make arbitrary code run during CTFE simply by doing something like using an enum. - Jonathan M Davis You still don't get it! It is not trivial! It is impossible to trigger it! You are focused far too much on the optimization side when it is only an application that takes advantage of the ability for rtfe to become ctfe when told, if it is possible. I don't know how to make this any simpler, sorry... I guess we'll end it here. I am not sure that I understood it right, but there is a way to detect the status of a parameter: My question was different, but I wished to get a ctRegex! or regex used depending on the expression: import std.regex:replaceAll,ctRegex,regex; auto reg(alias var)(){ static if (__traits(compiles, {enum ctfeFmt = var;}) ){ // "Promotion" to compile time value enum ctfeReg = var ; pragma(msg, "ctRegex used"); return(ctRegex!ctfeReg); }else{ return(regex(var)); pragma(msg,"regex used"); } } } So now I can always use reg!("") and let the compiler decide. To speed up compilation I made an additional switch, that when using DMD (for development) alway the runtime version is used. The trick is to use the alias var in the declaration and check if it can be assigned to enum. The only thing is now, that you now always use the !() compile time parameter to call the function. Even, when in the end is translated to an runtime call. reg!("") and not reg("...").
Re: Convert a huge SQL file to CSV
On Friday, 1 June 2018 at 09:49:23 UTC, biocyberman wrote: I need to convert a compressed 17GB SQL dump to CSV. A workable solution is to create a temporary mysql database, import the dump, query by python, and export. But i wonder if there is something someway in D to parse the SQL file directly and query and export the data. I imagine this will envolve both parsing and querying because the data is stored in several tables. I am in the process of downloading the dump now so I can’t give excerpt of the data. You don't need python: https://michaelrigart.be/export-directly-mysql-csv/ SELECT field1, field2 FROM table1 INTO OUTFILE '/path/to/file.csv' FIELDS TERMINATED BY ',' ENCLOSED BY '"' FIELDS ESCAPED BY '\' LINES TERMINATED BY '\n'; Most important: INTO OUTFILE : here you state the path where you want MySQL to store the CSV file. Keep in mind that the path needs to be writeable for the MySQL user You can write a parser for SQL in D, but even if the import into mysql would take some time, it's only compute time and not yours. Regards mt.
Re: Why The D Style constants are written in camelCase?
On Wednesday, 9 May 2018 at 11:52:11 UTC, Jonathan M Davis wrote: On Wednesday, May 09, 2018 09:38:14 BoQsc via Digitalmars-d-learn wrote: [...] Every language makes its own choices with regards to how it goes about things, some of which are purely subjective. [...] - Jonathan M Davis Just a thank you, for your patient and well written explanations!
Re: Parse .eml files
On Thursday, 12 April 2018 at 00:00:04 UTC, bachmeier wrote: On Wednesday, 11 April 2018 at 15:20:08 UTC, Martin Tschierschke wrote: My question in the moment is, how do I invoke Thunderbird to display a certain single mail (or maildir) file? How do I use Thunderbird as the client, to show, to answer or to forward these mails. An alternative would be to use a browser based mailer? Handling all attachments is an other purpose. Can you use executeShell and call Thunderbird from the command line? Something like executeShell("thunderbird -compose \"subject='My Christmas Gift',body='Please send me a new car',to='sa...@claus.net'") http://kb.mozillazine.org/Command_line_arguments_%28Thunderbird%29 Thank you, especially for the Link! There I saw, that attachment with a local file is possible. So It should be possible to invoke Thunderbird with the extracted elements of an existing email.
Re: Parse .eml files
On Wednesday, 11 April 2018 at 02:37:39 UTC, bachmeier wrote: On Monday, 9 April 2018 at 19:17:20 UTC, Adam D. Ruppe wrote: [...] I had a chance to try this out and it worked without a problem. I did have to download color.d in addition to the other dependencies you listed. In the event that Google brings someone here, this is a complete working program: import std.file, std.stdio, std.string; import arsd.email; void main(string[] args) { string[] f = std.file.readText(args[1]).splitLines(); auto em = new IncomingEmailMessage(f); writeln("From: ", em.from); writeln("To: ", em.to); writeln("Subject: ", em.subject); writeln(em.textMessageBody); } Compile with dmd *.d -ofreademail And run ./reademail 'email message.eml' Very cool, I was looking for something similar, thank you both for sharing! My goal is to store mails in a mysql table with fulltext index, connected to a existing old crm solution via the email address as a foreign key. My question in the moment is, how do I invoke Thunderbird to display a certain single mail (or maildir) file? How do I use Thunderbird as the client, to show, to answer or to forward these mails. An alternative would be to use a browser based mailer? Handling all attachments is an other purpose.
Re: #import mapi.h
On Friday, 23 March 2018 at 01:12:58 UTC, Mike Parker wrote: On Thursday, 22 March 2018 at 21:45:40 UTC, Martin Tschierschke wrote: On Thursday, 22 March 2018 at 17:42:46 UTC, Paul Backus wrote: On Wednesday, 21 March 2018 at 16:22:45 UTC, Martin Tschierschke wrote: Is there an step by step introduction how to convert a C header of an external lib into the right extern(C){} block? In addition to what others have said, I found the following article on the D Wiki useful: https://wiki.dlang.org/D_binding_for_C Thank you, this one is very good! If you have Learning D, chapter 9 is all about interface D with C. I will look at it! I have seen your hint already, you have mentioned it in the beginning of your blogpost. The discussion in an other thread [1] about direct integration of an C/C++ preprocessor into the D complier(s) is very interesting, I think this will push the adoption of the language, because you just can start immediately to use D as a replacement for C or C++. It is very fascinating to see how D is evolving all the time. Now I hope that with the survey and more donations the D Foundation get the ability to push this even more. [1] https://forum.dlang.org/post/hvanbsyrydsxpizlt...@forum.dlang.org
Re: #import mapi.h
On Thursday, 22 March 2018 at 17:42:46 UTC, Paul Backus wrote: On Wednesday, 21 March 2018 at 16:22:45 UTC, Martin Tschierschke wrote: Is there an step by step introduction how to convert a C header of an external lib into the right extern(C){} block? In addition to what others have said, I found the following article on the D Wiki useful: https://wiki.dlang.org/D_binding_for_C Thank you, this one is very good!
Re: #import mapi.h
On Thursday, 22 March 2018 at 12:53:23 UTC, Martin Tschierschke wrote: On Wednesday, 21 March 2018 at 17:12:07 UTC, Timoses wrote: [...] I got it, my first mini test with C bindings! Important missing at first: (stderr) import core.stdc.stdio : stderr, FILE; and use of toStringz inside: mapi_query(dbh, toStringz(q) ) After installing monetdb and starting the server with: https://www.monetdb.org/Documentation/UserGuide/Tutorial My minimal version of the example compiled with dmd app.d -I /usr/local/lib/libmapi.so (My dub.json is still incomplete so the linking failed.) Here is the code: (only the minimum of mapi.h is icluded!) ``` std.stdio; import std.string; /* interfacing winth monetdb #include mapi.h */ /* minimum to run code of example at: https://www.monetdb.org/Documentation/Manuals/SQLreference/Programming/MAPI */ import core.stdc.stdio : stderr,FILE; import core.stdc.stdlib; struct MapiStruct; alias Mapi = MapiStruct*; struct MapiStatement; alias MapiHdl = MapiStatement*; enum MOK = 0 ; alias MapiMsg = int; extern(System){ Mapi mapi_connect(const char* host, int port, const char* username, const char* password, const char* lang, const char* dbname); MapiHdl mapi_query(Mapi mid, const char *cmd); int mapi_fetch_row(MapiHdl hdl); char *mapi_fetch_field(MapiHdl hdl, int fnr); MapiMsg mapi_error(Mapi mid); MapiMsg mapi_explain(Mapi mid, FILE* fd); MapiMsg mapi_destroy(Mapi mid); MapiMsg mapi_close_handle(MapiHdl hdl); MapiMsg mapi_explain_result(MapiHdl hdl, FILE* fd); MapiMsg mapi_next_result(MapiHdl hdl); MapiMsg mapi_explain_query(MapiHdl hdl, FILE* fd); char *mapi_result_error(MapiHdl hdl); } void die(Mapi dbh, MapiHdl hdl) { if (hdl != null) { mapi_explain_query(hdl, stderr); do { if (mapi_result_error(hdl) != null) mapi_explain_result(hdl, stderr); } while (mapi_next_result(hdl) == 1); mapi_close_handle(hdl); mapi_destroy(dbh); } else if (dbh != null) { mapi_explain(dbh, stderr); mapi_destroy(dbh); } else { fprintf(stderr, "command failed\n"); } exit(-1); } MapiHdl query(Mapi dbh, string q) { MapiHdl ret = null; if ((ret = mapi_query(dbh, toStringz(q) )) == null || mapi_error(dbh) != MOK) die(dbh, ret); return(ret); } void update(Mapi dbh, string q) { MapiHdl ret = query(dbh, q); if (mapi_close_handle(ret) != MOK) die(dbh, ret); } void main() { auto dbh = mapi_connect("localhost", 5, "monetdb", "monetdb", "sql", "voc"); writeln("DB-connect"); update(dbh, "CREATE TABLE emp (name VARCHAR(20), age INT)"); writeln("create"); update(dbh, "INSERT INTO emp VALUES ('John', 23)"); update(dbh, "INSERT INTO emp VALUES ('Mary', 22)"); auto hdl = query(dbh, "SELECT * FROM emp"); while (mapi_fetch_row(hdl)) { auto name = mapi_fetch_field(hdl, 0); auto age = mapi_fetch_field(hdl, 1); printf("%s is %s\n", name, age); } } ``` Will try to make a complete binding available later...
Re: #import mapi.h
On Wednesday, 21 March 2018 at 17:12:07 UTC, Timoses wrote: On Wednesday, 21 March 2018 at 16:22:45 UTC, Martin Tschierschke wrote: Is there an step by step introduction how to convert a C header of an external lib into the right extern(C){} block? A blog post or tutorial, or chapter in a D book? (I have those from Packt Publishing) While googling I found this: https://dlang.org/blog/2017/12/05/interfacing-d-with-c-getting-started/ Haven't read it yet, but might give you some more insight. For automatic conversion I stumbled across Dstep which I so far like a lot: https://github.com/jacob-carlborg/dstep Thank you! I will have a look at both, an Mike Parker is pointing to his book, too, so now together with the post from "nkm1" I should be able to make it! @ketmar, I learned C but the counter of years from that time was stored in a nibble and so I got an overflow...error :-)
Re: #import mapi.h
On Wednesday, 21 March 2018 at 18:42:43 UTC, nkm1 wrote: On Wednesday, 21 March 2018 at 16:22:45 UTC, Martin Tschierschke wrote: [...] The easiest thing to do is to write a wrapper in C. The wrapper will include all necessary headers and provide some easy to use functions that you can call from D. Of course, you'll need to use a C compiler to compile it. Anyway, this header looks very straightforwar, no particular tricks with the preprocessor. It should be something like this (untested, obviously): [...] Thank you! Especially this was a missing link: struct MapiStruct; alias Mapi = MapiStruct*;
#import mapi.h
Is there an step by step introduction how to convert a C header of an external lib into the right extern(C){} block? A blog post or tutorial, or chapter in a D book? (I have those from Packt Publishing) (Especially I am trying to get this used with D: Montetdb C-API https://www.monetdb.org/Documentation/Manuals/SQLreference/Programming/MAPI With: https://github.com/snaga/monetdb/blob/master/clients/mapilib/mapi.h) The page: https://dlang.org/spec/interfaceToC.html is known, but not detailed enough for me.
Re: What's the proper way to add a local file dependence to dub?
On Monday, 12 March 2018 at 09:38:41 UTC, Martin Tschierschke wrote: On Sunday, 4 March 2018 at 16:46:56 UTC, Marc wrote: [...] I did it this sway: the part of dub.json: "dependencies": { [...] "mylib":{ "versions": "~master", "path": "/home/mt/d/mylib" } }, In spite of using a version directly after the used lib, you give two parameters "versions" : "~master" and "path": "/path_to_your_lib/" Works well. And in ...mylib/dub.json you just add: "targetType": "library", on the top-level, and place your dir.d in ...mylib/source/
Re: What's the proper way to add a local file dependence to dub?
On Sunday, 4 March 2018 at 16:46:56 UTC, Marc wrote: then copy it to sources folder? let's say I have a small library folder at C:\mylibrary\D where I want to use dir.d from it. How do I add that file dependence to dub? But I do not want to that file be passed directly to dmd, I want to that file be copied to application's source folder (so it's easy to distribuite, with the dependences together as possible) then compiled. So, what I want to some extension is dub work with loca files. Is this possible to do solely with dub? I know I can easily write a script to run before dub which copies the dependence files from C:\mylibrary to application's source but I'm looking for a more elegant approach as possible; I'm afraid of rewriting a makefile-like soon (I find cmake/make/makefiles just ugly). I did it this sway: the part of dub.json: "dependencies": { "diet-ng": "~>1.4", "vibe-d:tls": "~>0.8.0", "vibe-d:http": "~>0.8", "mysql-d": "~>0.3", "mylib":{ "versions": "~master", "path": "/home/mt/d/mylib" } }, In spite of using a version directly after the used lib, you give two parameters "versions" : "~master" and "path": "/path_to_your_lib/" Works well.
Re: dmd-2.078.2 problems with Ubuntu 17.10 32Bit
On Wednesday, 14 February 2018 at 11:23:48 UTC, Andrea Fontana wrote: On Wednesday, 14 February 2018 at 11:16:25 UTC, Martin Tschierschke wrote: Ok, good to know! I started with 16.04 and made the initial mistake to take the 32 Bit version, do you use 32 or 64 Bit? 64bit of course! Andrea After this info, I made the step to change to Ubuntu 17.10 64 Bit. And - it works! But the installation via apt-get is not working without the steps already mentioned in the post before! (s/http/https/ and manually import of the public key) This (from https://dlang.org/download.html) is outdated for 17.10. sudo wget http://master.dl.sourceforge.net/project/d-apt/files/d-apt.list -O /etc/apt/sources.list.d/d-apt.list sudo apt-get update && sudo apt-get -y --allow-unauthenticated install --reinstall d-apt-keyring sudo apt-get update && sudo apt-get install dmd-compiler dub
Re: rdmd main.d leads to Segmentation fault
On Wednesday, 14 February 2018 at 10:28:51 UTC, Kagamin wrote: On Tuesday, 13 February 2018 at 06:53:46 UTC, Martin Tschierschke wrote: I am unfamiliar with debugging (gdb etc.) so any hint would be appreciated! https://issues.dlang.org/show_bug.cgi?id=18350 - maybe adjust bug severity. I added a comment and increased prio, OK to do it like this? I may post my gdb results in the MET evening later, should I?
Re: dmd-2.078.2 problems with Ubuntu 17.10 32Bit
On Wednesday, 14 February 2018 at 10:57:47 UTC, Andrea Fontana wrote: On Tuesday, 13 February 2018 at 22:21:18 UTC, Martin Tschierschke wrote: I will downgrade to 16.04., the dist-upgrade to 17.10 was a mistake, resulting in problems with startx and newer kernels so I have to use 4.10. In my experience dist-upgrade are long and messy :) Usually I create a partition on disk; install a fresh (K)ubuntu on that partition; move data / config from old partition to new; delete (or backup) old partition. I have both kubuntu 17.04 and 17.10 and dmd works fine. Andrea Ok, good to know! I started with 16.04 and made the initial mistake to take the 32 Bit version, do you use 32 or 64 Bit?
Re: dmd-2.078.2 problems with Ubuntu 17.10 32Bit
On Tuesday, 13 February 2018 at 21:25:44 UTC, Jordi Sayol wrote: El 13/02/18 a les 08:03, Martin Tschierschke via Digitalmars-d-learn ha escrit: On Monday, 12 February 2018 at 21:18:01 UTC, Jordi Sayol wrote: El 12/02/18 a les 21:56, Martin Tschierschke via Digitalmars-d-learn ha escrit: I just started to play around with D again on my notebook at home and realized, that I have a broken installation. Even the minimal D "hello world" throws an error at execution. Speicherzugriffsfehler (Speicherabzug geschrieben) aka. core dump Compiling with ldc2 still works. Any hint? d-apt <http://d-apt.sourceforge.net/> After setting ulimit -c unlimited to get the core dumped, I took a look with gdb, to find a hint, now realizing, that it is probably the same problem as here: https://forum.dlang.org/thread/jjaynewwdsyntyehv...@forum.dlang.org?page=1 A fresh install from d-apt on Ubuntu 16.04 32-bit, and everything worked fine. I tried a lot, there is special bug new on ubuntu 17.10 in /etc/apt/sources.list.d/d-apt.list !!! I had to change http://... to https:// Before that I imported the key with sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys EBCF975E5BA24D5E I am not sure if this was necessary, probably not. Than I was able to call sudo apt-get update && sudo apt-get -y --allow-unauthenticated install --reinstall d-apt-keyring && sudo apt-get update and install with sudo apt-get install dmd-compiler dub But unfortunately still the same core dump. Is there anyone using Ubuntu 17.10 32 Bit? I will downgrade to 16.04., the dist-upgrade to 17.10 was a mistake, resulting in problems with startx and newer kernels so I have to use 4.10.
Re: dmd-2.078.2 problems with Ubuntu 17.10 32Bit
On Monday, 12 February 2018 at 21:18:01 UTC, Jordi Sayol wrote: El 12/02/18 a les 21:56, Martin Tschierschke via Digitalmars-d-learn ha escrit: I just started to play around with D again on my notebook at home and realized, that I have a broken installation. Even the minimal D "hello world" throws an error at execution. Speicherzugriffsfehler (Speicherabzug geschrieben) aka. core dump Compiling with ldc2 still works. Any hint? d-apt <http://d-apt.sourceforge.net/> After setting ulimit -c unlimited to get the core dumped, I took a look with gdb, to find a hint, now realizing, that it is probably the same problem as here: https://forum.dlang.org/thread/jjaynewwdsyntyehv...@forum.dlang.org?page=1
Re: rdmd main.d leads to Segmentation fault
On Sunday, 4 February 2018 at 11:50:05 UTC, Timoses wrote: On Thursday, 1 February 2018 at 09:01:34 UTC, Kagamin wrote: On Wednesday, 31 January 2018 at 16:59:15 UTC, Timoses wrote: And I would need to do what about it? Sorry, I'm not familiar with assembly code stuff in detail. You can try to see if it works on another distro or version. It does work on debian jessie. Stretch failed.. It looks like I have the same issue, I got: gdb hiworld core Core was generated by `./hiworld'. Program terminated with signal SIGSEGV, Segmentation fault. #0 0x800fbf73 in _d_dso_registry () ldc2 is working. My system: Ubuntu 17.10 32 Bit 4.10.0-37-generic #41-Ubuntu SMP Fri Oct 6 20:20:00 UTC 2017 i686 i686 i686 GNU/Linux (No problems on our office system Ubuntu 16.04 64Bit, too) I tried older DMD (from 2017 and 2016!), because I already used DMD on this system, but I got the same same effect. I am unfamiliar with debugging (gdb etc.) so any hint would be appreciated!
Re: dmd-2.078.2 problems with Ubuntu 17.10 32Bit
On Monday, 12 February 2018 at 21:08:30 UTC, Seb wrote: On Monday, 12 February 2018 at 20:56:11 UTC, Martin Tschierschke wrote: I just started to play around with D again on my notebook at home and realized, that I have a broken installation. Even the minimal D "hello world" throws an error at execution. Speicherzugriffsfehler (Speicherabzug geschrieben) aka. core dump Compiling with ldc2 still works. Any hint? How did you install DMD? It's probably related to this. I recommend using the official releases: curl https://dlang.org/install.sh | bash -s dmd See also: https://dlang.org/install.html I did so, and after that, I tried to install via dpkg -i *.deb, than I tried to use an older version... without success, maybe I first have to clean up? But how to deinstall best?
dmd-2.078.2 problems with Ubuntu 17.10 32Bit
I just started to play around with D again on my notebook at home and realized, that I have a broken installation. Even the minimal D "hello world" throws an error at execution. Speicherzugriffsfehler (Speicherabzug geschrieben) aka. core dump Compiling with ldc2 still works. Any hint?
Re: How to proceed with learning to code Windows desktop applications?
On Thursday, 1 February 2018 at 09:18:30 UTC, I Lindström wrote: [...] And thank you all for your ideas and suggestions. I'll try some out and see what works. I found this useful: https://github.com/adamdruppe/arsd/blob/master/simpledisplay.d
Last post from me not displayed on web frontend?
This post is to try if it works now. But I got an answer from Adam... Thank you.
Parsing mbox file to display with vibe.d
Hello, Parsing mbox file (/var/spool/mail/... on a Ubuntu machine) and splitting to a range or array of mail objects. Has anyone done this with D? please give me hint. (DUB, git, this forum?) Or should I start with formail (-s) as a subprocess? (At first step, I want to run a vibe.d server to display all Cron Messages which I will forward to one special account to view them in a browser. At first I thought about setting up Squirrel Mail or something similar for the job, but then by simply splitting the mbox and displaying the content in a html-table I might get what I need. ) Regards mt.
Re: Most convenient way to write a loop with fixed length and no need for the index?
On Friday, 30 June 2017 at 08:19:07 UTC, Anton Fediushin wrote: On Friday, 30 June 2017 at 07:44:45 UTC, Martin Tschierschke wrote: What do I have to do, to make this work? iota(number).each!...command_x(a...);command_y(b...);command_z(c..)) You can use it like this: iota(10).each!((x) { command1(); command2(); ... }); I missed this syntax! Or there is a short syntax (lambda): iota(10).each!((x) => command1()); See http://dlang.org/spec/expression.html#Lambda for more info about lambdas. Or is there something like number.times!{} possible? You can write your own function. It is simple. void times(alias fun)(size_t i) { foreach(unused;0..i) fun(); } and use it like this: 10.times!({ writeln("yaaay"); }); Thank You! Ali and Anton! D is so cool! :D ps. This post was written but not send... on June 30...
Re: Should `dub run` prints its output to STDERR?
On Saturday, 9 September 2017 at 05:58:59 UTC, Ali Çehreli wrote: On 09/08/2017 09:51 PM, Ky-Anh Huynh wrote: > When I execute a program thanks to dub, `dub` also prints its > information to STDOUT: Try dub's --quiet command line switch. Ali Can I configure this also in dub.json (dub.sdl)? Specially --parallel switch?
Re: Compare times: file modification time
On Wednesday, 2 August 2017 at 13:32:46 UTC, Adam D. Ruppe wrote: On Wednesday, 2 August 2017 at 13:25:25 UTC, Martin Tschierschke wrote: I get a SysTime, how to check if it is older than an interval (1 day)? D/Phobos idiomatically? if(Clock.currTime - timeLastModified("aa.d") > 1.days) { // older } Thank you Adam. So simple!
Compare times: file modification time
With import std.file:timeLastModified; auto time = timeLastModified(source); I get a SysTime, how to check if it is older than an interval (1 day)? D/Phobos idiomatically? (Currently I am using (Clock.currTime().toUnixTime-time.toUnixTime)< 60*60*24)). Regards mt.
Re: Compile Time versus Run Time
On Monday, 31 July 2017 at 15:57:28 UTC, Anonymouse wrote: On Monday, 31 July 2017 at 15:46:47 UTC, inevzxui wrote: On Monday, 31 July 2017 at 15:43:21 UTC, Martin Tschierschke wrote: [...] But the parameters are not checked at compile-time unless you specifically pass the pattern string as a template parameter. I think its immutability implicitly converting it into a template parameter is what's what he's talking about. import std.stdio; void main(string[] args) { writefln!"%s"(); // compile-time assert writefln("%s"); // runtime exception, though everything needed for a compile-time assert was inferable during compilation } This is exactly the "use case", I thought about: How to avoid runtime errors, if at compile time the problem might be detected.
Compile Time versus Run Time
As a rookie in D programming I try to understand the power of templated functions with compile time parameters. With DMD 2.074 a compile time format (auto output = format!("Print this %s")(var);) was introduced, now we all know that very many of this format strings are immutable, so wouldn't it be cool to automatically detect this and use the compile time version? Without the need to think about it and to use an other syntax? Is this theoretically possible? Regards mt.
howto touch a file - setTimes
When I tried to set the atime and mtime of a file (f) via: import std.datetime; auto time = Clock.currTime(); setTimes(f,time,time); I get "Operation not permitted." This is caused on linux by the rule, that if you are not the owner of the file you may only set the mtime of a file to current time. A simple "touch filename" in terminal works. Any hint? Do I have to use execute("touch filename")?
Re: how to harvest the results of tasks from a taskpool?
On Wednesday, 5 July 2017 at 13:55:22 UTC, Martin wrote: Hi, i have a coulpe of different machines with MySQL Servers running on it. Now, i want to execute queries for all Databases at the same time and collect the Result to process it. I am new to the parallelism - so maybe i understand something totaly wrong. What i tring is something like this: { auto tPool = new TaskPool(); forach(server ; servers) { auto task = task!queryWorker(query); tPool.put(task); } tPool.finish(true); //> how to collect the results now? <--- } row[] queryWorker(string query) { //rows = result of the query return rows; } btw.. how to markup code in this forum? I tested a much simpler approach with the following setup/structure?: // a shared array of results where each result is again an array; Rows results[]; // using parallel foreach foreach(i,server;servers.parallel){ result[i] = request(server).array;; } Now every array of rows is accessible in result[]? Tested this construct with parallel curl requests: time ./parallel_curl Site www.dlang.org. Page has length:31607 Site forum.dlang.org. Page has length:24358 Site code.dlang.org. Page has length:36477 Site www.google.com. Page has length:10628 real0m0.836s user0m0.137s sys 0m0.034s Without parallel: real0m2.424s user0m0.722s sys 0m0.209s This is the code: import std.stdio; import std.net.curl; import std.parallelism; void main() { enum string[] tospider = ["www.dlang.org","forum.dlang.org","code.dlang.org","www.google.com"]; char[][tospider.length] results; foreach(i,site;tospider.parallel){ results[i] = get(site); } foreach(i,e;results){ writeln("Site ", tospider[i],". Page has length:",e.length); } } Will try to use this approach to collect some elastic seach results and look if it speeds up on an 8 core machine.
Re: Need simple sound
On Wednesday, 5 July 2017 at 10:19:54 UTC, Sebastiaan Koppe wrote: On Wednesday, 5 July 2017 at 09:43:05 UTC, Martin Tschierschke wrote: On Wednesday, 5 July 2017 at 07:21:45 UTC, Sebastiaan Koppe wrote: On Wednesday, 5 July 2017 at 05:34:37 UTC, FoxyBrown wrote: On Tuesday, 4 July 2017 at 20:37:44 UTC, Sebastiaan Koppe wrote: Portaudio is simple as well. And nice cross platform. are there any bindings? Sure, see http://code.dlang.org/packages/portaudio Sorry, for that question but now, as I have several different options - all not 'overdocumented' - so what would be the shortest possible D program waiting for input and playing a sound from a file in parallel? Something short like the single-file dub example...? #!/usr/bin/env dub /+ dub.sdl: name "hello" +/ void main() { writef("Do you like the music?"); char[] answer; answer = readln(); writef("This was your Answer: ", answer); } This one plays a wav file. Couldn't get dub to do single-file on it. It kept giving linker errors. (Took example from https://github.com/v--/portaudio/blob/master/examples/pa_test.d) [...] Lerror: stderr.writefln("error %s", to!string(Pa_GetErrorText(err))); return 1; } Thank you! Without the error handling it would be quite simple :-) So, the following process starts the music in main, it is just to clarify the process for me: In main: //1 PaStream* stream; Sound input = decodeWAV("FILE.wav"); auto audio = Audio(input); Pa_Initialize(); Pa_OpenDefaultStream(&stream,...input...&callback,&audio); //2 Pa_StartStream(stream); //3 Pa_StopStream(stream); Pa_CloseStream(stream); For my purpose I will try to encapsulate it all in 3 additional own methods on top of it: //1 auto myinput = InitWav("File.wav"); //2 PlaySound(myinput,volume=default, length=max_length); //3 StopSound(myinput); With a new Struct myinput to handle input,audio and stream. Thank you all for your help!
Re: Need simple sound
On Wednesday, 5 July 2017 at 07:21:45 UTC, Sebastiaan Koppe wrote: On Wednesday, 5 July 2017 at 05:34:37 UTC, FoxyBrown wrote: On Tuesday, 4 July 2017 at 20:37:44 UTC, Sebastiaan Koppe wrote: Portaudio is simple as well. And nice cross platform. are there any bindings? Sure, see http://code.dlang.org/packages/portaudio Sorry, for that question but now, as I have several different options - all not 'overdocumented' - so what would be the shortest possible D program waiting for input and playing a sound from a file in parallel? Something short like the single-file dub example...? #!/usr/bin/env dub /+ dub.sdl: name "hello" +/ void main() { writef("Do you like the music?"); char[] answer; answer = readln(); writef("This was your Answer: ", answer); }
Re: Need simple sound
On Tuesday, 4 July 2017 at 11:59:33 UTC, Vladimir Panteleev wrote: On Monday, 3 July 2017 at 10:40:03 UTC, Martin Tschierschke wrote: On Monday, 3 July 2017 at 09:24:35 UTC, Guillaume Piolat wrote: On Monday, 3 July 2017 at 08:55:20 UTC, Martin Tschierschke wrote: Hello for a simple game I would like to add some very simple sound, not much different than the beeps of "PAC Man". Is there anything I can use for this? DerelictSDL supports the loading of SDL_mixer, which makes it very practical. Thank you for the hint, a short google search was not so successful, can you give me an additional hint / link? I think I would have to produce a time series of a sinus for example and to play it? Here's a program that plays some square waves: https://dump.thecybershadow.net/9db4fcd7b004e5dfccf537e49cbb72a6/test.d Cool, will try!
Re: Need simple sound
On Monday, 3 July 2017 at 09:24:35 UTC, Guillaume Piolat wrote: On Monday, 3 July 2017 at 08:55:20 UTC, Martin Tschierschke wrote: Hello for a simple game I would like to add some very simple sound, not much different than the beeps of "PAC Man". Is there anything I can use for this? DerelictSDL supports the loading of SDL_mixer, which makes it very practical. Thank you for the hint, a short google search was not so successful, can you give me an additional hint / link? I think I would have to produce a time series of a sinus for example and to play it?
Need simple sound
Hello for a simple game I would like to add some very simple sound, not much different than the beeps of "PAC Man". Is there anything I can use for this?
Re: mysql-native + vibe.d example
On Friday, 30 June 2017 at 00:52:28 UTC, crimaniak wrote: Hi! Moving my project from mysql-lited to mysql-native I faced the problem with null pointer error inside of mysql-native: [...] It seems I am doing something wrong so myself-native fails to detect it in isValid(). So I search for example how to use mysql-native in real multi-threaded vibe.d application with usage of MySQLPool. Please do not point me to basic example provided with package because it is single thread. Thanks. Sorry, can not help, but would be very interested to learn how to do a real multi-threaded vibe.d with mysql So if you find a solution, please make an simplified example for vibe.d documentation! Sönke might include it into vibe.d docs.
Most convenient way to write a loop with fixed length and no need for the index?
What do I have to do, to make this work? iota(number).each!...command_x(a...);command_y(b...);command_z(c..)) ^? how to write the lambda? Similar to the ruby (1..number).each{ commands...} Don't want to write the following, because the index i is not used inside the loop and this should be clear when reading it: for (i=0;i
Re: How to add class in DIET template
On Friday, 23 June 2017 at 06:59:22 UTC, Suliman wrote: I need to get external variable and make class by it's value - string mystr = "lng-" ~ language; - foreach(i, line; arrayOfLines ) li code.mystr #{line} I need to get HTML code like this: some D code But class name become "mystr" and I am getting: some D code How to fix it? You can use the html syntax for the class parameter, the funny/nice thing is, that mystr can be used directly without "#{}" around. code(class=mystr) #{line} works.
Re: Operator Overloading + / ~
On Monday, 19 June 2017 at 12:22:43 UTC, ketmar wrote: Martin Tschierschke wrote: Just a thought it might be useful for cut-n-paste when porting code: Would it be possible to define an operator overloading for '+'-Operator for strings to work as append? (like ~). I understand, that '~' is in general a better choice than '+', so this is of more theoretical interest. It is clear to me, that when I define my own string type this is possible. Regards mt. nope. it is not possible to overload operators for built-in types (and string is just an aliased array). Thank you for lightning fast response :-)
Operator Overloading + / ~
Just a thought it might be useful for cut-n-paste when porting code: Would it be possible to define an operator overloading for '+'-Operator for strings to work as append? (like ~). I understand, that '~' is in general a better choice than '+', so this is of more theoretical interest. It is clear to me, that when I define my own string type this is possible. Regards mt.
Re: Playing arround with mixin - alias?
On Friday, 21 April 2017 at 11:58:13 UTC, Martin Tschierschke wrote: On Friday, 21 April 2017 at 10:31:46 UTC, ketmar wrote: biozic wrote: I thought way to complicated: Just define the string at top: enum exho="auto mixinter(string x)(){return mixin(interp!x);} auto exho(string x)(){return mixin(\"writeln(\"~interp!x~\")\");}"; Then use: mixin(exho); exho!"${name} you are app. ${age*365} days old"; In your scope!
Re: Playing arround with mixin - alias?
On Friday, 21 April 2017 at 10:31:46 UTC, ketmar wrote: biozic wrote: On Friday, 21 April 2017 at 09:42:33 UTC, ketmar wrote: Martin Tschierschke wrote: Is it possible to define an alias for something like mixin(import("local_function_file.d")); to write only use_local_function; which will be translated to: mixin(import("local_function_file.d")); (this additionally needs the file local_function_file.d in source/ + -J./source as parameter for dmd aka. dflags "-J./source" in dub.sdl) Regards mt. nope. the best you can get is `mixin use_local_function;`. Would there be an advantage compared to a simple `import local_function_file;`? i doubt so. So my "solution" on how to get a short cut for using: writeln(mixin(interp!"${name} you are app. ${age*365} days old")); // first place in source/exho.d the following code: auto mixinter(string x)(){return mixin(interp!x);} auto exho(string x)(){return mixin("writeln("~interp!x~")");} later compile this with -J./source source/app.d: import scriptlike; auto insert(string name)(){return import(name);} alias insert!"exho.d" use_exho; void main() { auto name = userInput!string("Please enter your name"); auto age = userInput!int("And your age"); //Now you can write in every scope you need it: mixin(use_exho); exho!"${name} you are app. ${age*365} days old"; // Which looks little nicer than: // writeln(mixin(interp!"${name} you are app. ${age*365} days old")); // or if you need the result in a var: mixin(use_exho); auto var = mixinter!"${name} you are app. ${age*365} days old"; writeln(var); } you may even name the alias just exho and write: alias insert!"exho.d" exho; mixin(exho); exho!"${name} you are app. ${age*365} days old"; (exho was derived from shell echo with mi_x_in)
Playing arround with mixin - alias?
Is it possible to define an alias for something like mixin(import("local_function_file.d")); to write only use_local_function; which will be translated to: mixin(import("local_function_file.d")); (this additionally needs the file local_function_file.d in source/ + -J./source as parameter for dmd aka. dflags "-J./source" in dub.sdl) Regards mt.
Re: ndslice summary please
On Thursday, 13 April 2017 at 08:47:16 UTC, Ali Çehreli wrote: I haven't played with ndslice nor followed its deprecation discussions. Could someone summarize it for us please. Also, is it still used outside Phobos or is Ilya or someone else rewriting it? Ali We should additionally mention sometimes, that the naming of ndslice is derived from ndarray and this is from N-dimensional Array. No one searching for N - dimensional Array OR Matrix will find ndslice, without this info easily. Just try a google search: "dlang n dimesional array" Regards mt.
CTFE using of replaceAll from std.regex posible?
Hello, when trying to process an string at compile time with ... auto reg = ctRegex!`as\ [a-z]+`; enum replaced = replaceAll(call,reg,""); I get: /usr/include/dmd/phobos/std/regex/package.d(708,34): Error: malloc cannot be interpreted at compile time, because it has no available source code /usr/include/dmd/phobos/std/regex/package.d(708,27): called from here: enforce(malloc(size), delegate const(char)[]() => "malloc failed", "/usr/include/dmd/phobos/std/regex/package.d", 708LU) /usr/include/dmd/phobos/std/regex/package.d(832,34): called from here: ((RegexMatch!(string, BacktrackingMatcher) __slRegex3165 = RegexMatch(BacktrackingMatcher(Regex(null, null, null, 0u, 0u, 0u, 0u, 0u, null, null, null, ShiftOr(null, 0u, 0u)), null, Input(null, 0LU), 0LU, '\U', false, 0u, 0u, 0LU, null, null, null, null), null, Captures(null, 0, null, , 0u, 0u, 0u, null), null);) , __slRegex3165).this(input, re) /usr/include/dmd/phobos/std/regex/package.d(1049,48): called from here: matchMany(input, re) /usr/include/dmd/phobos/std/regex/package.d(906,26): called from here: matchAll(input, re) /usr/include/dmd/phobos/std/regex/package.d(1345,69): called from here: replaceAllWith(input, re) src/app.d(13,29):called from here: replaceAll(call, reg, "") It there a way to use "replaceAll" at compile time? Regards mt.
Re: Getting nice print of struct for debugging
On Saturday, 25 February 2017 at 01:30:09 UTC, Minty Fresh wrote: On Saturday, 25 February 2017 at 01:27:09 UTC, Minty Fresh wrote: On Wednesday, 22 February 2017 at 11:18:15 UTC, Martin Tschierschke wrote: [...] Since structs are Plain-old Data and don't do inheritance, the best option is a template mixin. ie. template mixin PrettyPrint { string toString() { // . . . } } From there, you can mix it into any struct you want. struct MyStruct { mixin PrettyPrint; } If you're familiar with Rails, this is similar to a Concern. Errata on that. Should actually be declared as: mixin template PrettyPrint() This is why I shouldn't make posts from my phone. Thank you, but this solution from Kevin Brogan, is an good alternative, to add a special dump function globally, so no need to modify the struct definitions. https://forum.dlang.org/post/yewavntuyutdvejwj...@forum.dlang.org His solution: import std.traits; void main() { WSADATA wsa; dump!wsa; } void dump(alias variable)() { writeln("\nDumping ",typeid(typeof(variable)),":\n"); writeln(variable.stringof, " = \n{"); foreach(member; FieldNameTuple!(typeof(variable))) { writeln("\t", member, ": ", mixin("variable."~member) ); } writeln("}\n"); }
Re: Getting nice print of struct for debugging
On Tuesday, 21 February 2017 at 14:02:54 UTC, Jacob Carlborg wrote: [...] Yes, this works, I would say this is the simplest: MyStruct s; foreach (index, name ; FieldNameTuple!MyStruct) writefln("%s: %s", name, s.tupleof[index]); If you want something more close to "send" in Ruby, you need to use a string mixin, like this: foreach (name ; FieldNameTuple!MyStruct) writefln("%s: %s", name, mixin("s." ~ name)); The string mixin example works for methods, opDispatch and similar as well. The tupleof example, the first one, works only for fields. Exactly what I was looking for, **thank you!** Both ways of accessing the struct elements are very interesting, giving an impression what is possible with D. Is it possible to overwrite "toString" for all structs in one step? Regards mt.
Re: Getting nice print of struct for debugging
On Monday, 20 February 2017 at 16:18:58 UTC, Paul Backus wrote: On Monday, 20 February 2017 at 16:04:17 UTC, Martin Tschierschke wrote: Hello, I have a little program where I am filling a struct with values from an regex match. Now I want to display the content of the struct for debugging purpose. I believe the easiest way to do this is to define a custom toString member function for your struct. For example: struct MyStruct { int x; double y; string s; string toString() { import std.format: format; return "MyStruct(x: %d, y: %f, s: \"%s\")".format(x, y, s); } } void main() { import std.stdio: writeln; MyStruct foo; foo.x =2; foo.y = 3.14; foo.s = "the quick brown fox"; writeln(foo); // Prints MyStruct(x: 2, y: 3.14, s: "the quick brown fox") } Good suggestion, thank you! Then the definition is near the struct definition and I do not need to care about what to call, just writeln(myvar); cool!
Getting nice print of struct for debugging
Hello, I have a little program where I am filling a struct with values from an regex match. Now I want to display the content of the struct for debugging purpose. If struct is named MyStruct I can print a list of the field names with: foreach(fieldname;FieldNameTuple!MyStruct){writef("%s ",fieldname);} If myvar is of type MyStruct how can I make a table like: fieldname_1: value_1 fieldname_2: value_2 . . fieldname_n: value_n Is there a way to do this with a single expression in D. Similar to a ruby call myvar.send(fieldname) to get the value from fieldname inside a loop? write(myvar); sure is working directly but I want to get the field names displayed, too. (A work around might be work with the format("%s",myvar) string and extract the values with an index?) Regards mt.
Re: Vibe.d help
On Friday, 23 September 2016 at 21:32:59 UTC, Gestalt Theory wrote: On Thursday, 22 September 2016 at 09:14:46 UTC, Martin Tschierschke wrote: On Thursday, 22 September 2016 at 01:38:12 UTC, Gestalt Theory wrote: 3. How to serve static files properly? sendFile(req, res, Path(req.path)); Does the trick inside the handler. @5. There is a solution, hopefully I can find the link and post it later. Any news on this? Sorry, I have problems to find the right link: It is mentioned here: http://vibed.org/features -> Integrated load balancing (bottom of page) And here you find the part for template caching, an option with in the new template engine: ->Experimental HTML template caching https://github.com/rejectedsoftware/diet-ng But the best place to ask would be in the vibe.d forum, where Sönke is able and willing to help! http://vibed.org/ -> http://forum.rejectedsoftware.com/ Regards mt.
Re: Vibe.d help
On Thursday, 22 September 2016 at 01:38:12 UTC, Gestalt Theory wrote: 1. I get this error when trying to run a project in VS. dub doesn't give the error. First-chance exception: core.exception.AssertError free() called with null array. at vibe-d-0.7.26\source\vibe\utils\memory.d(110) It constantly pops up then I get an access violation and crash. 2. Many vibe.d HTTP Server options seem not to be implemented. Is this still the case? e.g., http://vibed.org/api/vibe.http.server/HTTPServerSettings.maxRequestTime 3. How to serve static files properly? void images(HTTPServerRequest req, HTTPServerResponse res) { writeln("images Request"); write("Path = "); writeln(req.fullURL); // Somehow reship request out } ... router.get("/images/*", &images); I would like to be able to serve them but also log or redirect if possible. The messages are written. I tried to also serve directly and it didn't work, which is why I used a handler in the first place. router.get("/images/*", serveStaticFiles("images/")); I imagine the path is not correct. I am on windows and created an images sub dir in the projects(same depth as views, etc) but the images were not served. I didn't want to hard code this path, maybe it should be? [...] 5. Many other frameworks seem to support "hot swapping" of files while the sever is running rather than having to recompile. Recompiling the diet templates/project is slow and requires restarting the server and all that. Is there any way to get vibe.d to automatically monitor the projects folder or templates for changes and then somehow recompile and update/etc? Thanks. Just to point 3. I hope I can give a hint, the problem is, that the match is not the * but /images/*, so router.get("/images/*", serveStaticFiles("images/")) will look in PROJECTHOME/images/images/ for the file. For my .css files located in PROJECTHOME/public/styles/ I used: router.get("/styles/*", serveStaticFiles("public/")) if you put your images in PROJECTHOME/public/images router.get("/images/*", serveStaticFiles("public/")); should work. @5. There is a solution, hopefully I can find the link and post it later.
Re: Can vibe d leverage existing web technologies?
On Thursday, 15 September 2016 at 20:56:19 UTC, Intersteller wrote: On Thursday, 15 September 2016 at 14:31:28 UTC, Martin Tschierschke wrote: On Tuesday, 13 September 2016 at 23:45:18 UTC, Intersteller wrote: vibe.d does not have much lateral support as the most commons web technologies do. Can vibe.d leverage pre-existing techs such as php, ruby/rails, etc? Starting from scratch and having to build a robust and secure framework is really not the way to go. A good way to mix different technologies is to use a Apache or nginx proxy on the same server, so you can start using vibe.d for some parts and keep the rest at its place. Regards mt. How is this done? How can it be done smoothly? I'm not sure how to partition the work load. While, say, some pages might be served from php, and others from vibe2, etc, it seems like it would be nightmare to maintain consistency and interactivity. First you need to run vibe.d and the .php part on the same data (mysql for example). Lets say you have a special feature - like latest news, than you build the rendering of this with vibe.d and the rendering of the single news are still in php. Than you may move this to vibe.d later and keep only your back end, for editing the content in php. So the most read pages are served by vibe first. The "only" problem is you have to build your layout twice, in php and as diet template. :-( An other option might be, to start with the admin back end, where layout is not so critical and add additional features like statistics or a special dashboard? Regards mt.
Re: vibe.d PaaS
On Wednesday, 14 September 2016 at 09:01:11 UTC, Guillaume Piolat wrote: Is there vibe.d hosting sold anywhere? I am using this one: https://www.menkisys.de/ in the moment vibe.d only for tests. But with an Rails web service, using a small parser for email with attached pdf, written in D, it is only 5 Euro/month for a virtual machine running ubuntu. Oh, it seams they only offer support in German language(?)... Regards mt.
Re: Can vibe d leverage existing web technologies?
On Tuesday, 13 September 2016 at 23:45:18 UTC, Intersteller wrote: vibe.d does not have much lateral support as the most commons web technologies do. Can vibe.d leverage pre-existing techs such as php, ruby/rails, etc? Starting from scratch and having to build a robust and secure framework is really not the way to go. A good way to mix different technologies is to use a Apache or nginx proxy on the same server, so you can start using vibe.d for some parts and keep the rest at its place. Regards mt.
Re: C binding with D function
On Thursday, 4 August 2016 at 12:14:48 UTC, Adam D. Ruppe wrote: On Thursday, 4 August 2016 at 10:36:05 UTC, llaine wrote: Any idea how can I call them ? Just like any other function. Consider this: [...] Compile [...] hi from D, Ruby user! Thank you a lot!!! I want to use some vibe.d rendering inside Ruby on Rails, this gives me a god starting point, for my experiments. Regards mt.
Re: full path to source file __FILE__
On Thursday, 21 July 2016 at 19:54:34 UTC, Jonathan Marler wrote: Is there a way to get the full path of the current source file? Something like: __FILE_FULL_PATH__ I'm asking because I'm rewriting a batch script in D, meant to be ran with rdmd. However, the script needs to know it's own path. The original batch script uses the %~dp0 variable for this, but I'm at a loss on how to do this in D. Since rdmd compiles the executable to the %TEMP% directory, thisExePath won't work. BATCH - echo "Directory of this script is " %~dp0 What about using a wrapper around rdmd, so the program is executed with an additional parameter or an environment variable containing "FULL_PATH". When I started with D, I "accidentaly" wrote my own replacement script for rdmd compiling xyz.d with dmd to xyz or calling xyz depending on the modification times of the files. Regards mt.
Re: Best way to convert Apachelog Datetime 01/Jan/2016:02:25:10 -> 2016-01-01 02:25:10 MySQL-Datetime Format
On Wednesday, 8 June 2016 at 10:42:19 UTC, Martin Tschierschke wrote: I know there are easy ways to handle this, anyone with a code snippet for me? I found this solution, letting the MySQL engine do the work: SELECT STR_TO_DATE('26/Apr/2011:13:21:58', '%d/%b/%Y:%H:%i:%S'); https://www.experts-exchange.com/questions/26992776/convert-apache-log-date-time-to-mysql.html Maybe there is an other short solution using the std.datetime and or https://code.dlang.org/packages/dateparser ?
Best way to convert Apachelog Datetime 01/Jan/2016:02:25:10 -> 2016-01-01 02:25:10 MySQL-Datetime Format
I know there are easy ways to handle this, anyone with a code snippet for me? I would use two regex first to make 01,02,03... from Jan,Feb,.. and second to split the result. best regards mt.
Re: parsing HTML for a web robot (crawler) like application
On Wednesday, 23 March 2016 at 09:06:37 UTC, Rene Zwanenburg wrote: [...] Adam's dom.d will get you pretty far. I believe it can also handle documents that aren't completely well-formed. https://github.com/adamdruppe/arsd/blob/master/dom.d Thank you! This forum has an incredible fast auto responder ;-)
parsing HTML for a web robot (crawler) like application
Hello! I want to set up a web robot to detect changes on certain web pages or sites. Any hint to similar projects or libraries at dub or git to look at, before starting to develop my own RegExp for parsing? Best regards mt.
Re: Memory Efficient HashSet
On Wednesday, 9 March 2016 at 22:31:50 UTC, Nordlöw wrote: [...] foreach (const i; iota(0, n)) { x[i] = true; // indicate that it's stored } import std.stdio : writeln, readln; writeln("Press return: "); readln; } consumes 842.m MiB on my Ubuntu. The consumption with Google's sparsehash unordered_set is about 50 MiB. May be the discussion associated with this post, can give help??? https://forum.dlang.org/post/mailman.217.1457590242.26339.digitalmars-d-b...@puremagic.com I tried your little program and played around. I tried x.rehash, but this resulted in even more memory consumption. 80 bytes for 4 bytes key and one bit storage seams a lot. With smaller n it comes down to app. 60 Bytes. With how many data sets at the end, you will have to deal?
Re: Speed up `dub`.
On Monday, 7 March 2016 at 09:18:37 UTC, ciechowoj wrote: I'm using `dub` to build project. And every time I run `dub` it seems to check if dependencies are up to date, which takes some time. Is there a way to switch of that checking? Or any other way to speed up building process? It really slows down my modify-compile-check iteration time. A few hours ago dub.pm alias code.dlang.org was down or slow, so I used: $> dub --skip-registry=all build might be thats the reason?
Error in DUB Package Page - how to notify the Editor?
What about the idea to allow discussion entries/threads to be linked to dub package entries? So they appear in DUB and in a additional section of this forum? So vibe.d for example comes with his own forum that is good, but a solution for all would be nicer? So coming back to my first question: How to notify the author about errors, with out the need for searching for him elsewhere ? Regards mt.
Re: Size of Compiled Program
On Monday, 4 January 2016 at 14:01:18 UTC, Basile B. wrote: On Monday, 4 January 2016 at 13:49:03 UTC, Martin Tschierschke wrote: [...] - if debug info are generated this increases the size. - if bounds checking is turned off there is some code generated for each array operation - if contracts are not off there is a lot of assertion that will be generated see also some clues here: http://forum.dlang.org/post/mailman.20.1441974998.22025.digitalmars-d-le...@puremagic.com Ah, thank you for that Link!
Re: Size of Compiled Program
On Monday, 4 January 2016 at 14:51:59 UTC, Adam D. Ruppe wrote: On Monday, 4 January 2016 at 13:49:03 UTC, Martin Tschierschke wrote: When I was writing a small speed test - D versus Ruby The smallest possible ruby program has about ~5 MB of dependencies, outside the operating system (the ruby runtime itself). The D program has none. It carries its runtime with it, which makes the executable a bit larger to compensate but helps compatibility with other computers because the user doesn't have to hunt down obscure D runtime packages. Oh, thats interesting. When I tried to run the compiled "prime" on my notebook, with the "same" Ubuntu release, I got an error, may be its 32 not 64 Bit? Any hint?
Re: Size of Compiled Program
On Monday, 4 January 2016 at 14:16:54 UTC, Marc Schütz wrote: On Monday, 4 January 2016 at 13:49:03 UTC, Martin Tschierschke wrote: When I was writing a small speed test - D versus Ruby, calculating the first n prime numbers, I realized, that for small n Ruby may be faster, than compiling and executing with D. But for n = 1,000,000 D outperforms Ruby by app. 10x. Looking at the size of my prime executable, it was around 800 kB with DMD and even with optimization and "gdc -Os" > 1 MB. Why is such a short program resulting in a so big binary? That's probably basic these compilers statically link the runtime (and standard?) libraries by default. Compiling your program with `ldc2 -O3`, I get a binary of 28K, and stripping gets it down to 17K. Ok, I will try ldc2, too.
Size of Compiled Program
When I was writing a small speed test - D versus Ruby, calculating the first n prime numbers, I realized, that for small n Ruby may be faster, than compiling and executing with D. But for n = 1,000,000 D outperforms Ruby by app. 10x. Looking at the size of my prime executable, it was around 800 kB with DMD and even with optimization and "gdc -Os" > 1 MB. Why is such a short program resulting in a so big binary? - import std.stdio; import std.conv; int[] prime; // Dynamic Array of Prime // Ist n durch eine der zahlen in prime teilbar? bool teilbar(int n){ for(auto i=0; prime[i]*prime[i]<=n ; i++){ if (n%prime[i]==0) return true; } return false; } void main(string[] args) // first parameter number of primes to calculate { auto anzahl = 10; // default prime ~= 2; // first element of the array if(args.length==2){ anzahl = to!int(args[1]);} auto pruefe=1; while (prime.length <= anzahl){ pruefe+=2; if(!teilbar(pruefe)){ write(" ",pruefe); prime ~= pruefe; // append the array } } write("\n das wars...:",prime.length); }
Re: Deit Editor
On Friday, 1 January 2016 at 00:14:08 UTC, Jason Jeffory wrote: Vibe.d uses deit files for html generation. Seems nice but haven't dived into it(just removes a but of nonsense and allows code integration for dynamic generation... sounds great!!). But what about visual editing? It's nice to be ale to see the layout of the page directly without all the hassle of toggling back and forth between a browser and code editor. Also, there is the issue of syntax highlighting, code validation, etc... I came across this http://stackoverflow.com/questions/16080350/using-jade-with-wysiwyg-markdown-to-allow-users-to-edit-content Any ideas to make life easier? (isn't that what it's all about?) There was an answer pointing to https://www.npmjs.org/package/html2jade and this to http://html2jade.aaron-powell.com/, which allows you to convert online HTML to JADE. So you can make your HTML layout on an traditional way and get the jade code.
Re: Deit variable referencing
On Saturday, 2 January 2016 at 00:15:32 UTC, Jason Jeffory wrote: Ok, So Deit allows D code inside html... looks great. But how do external variables work? If I create a variable in the server(such as a class), can an html file access it easily? (not having to jump through hoops) doctype html html head title D string interpolations test body - import std.algorithm : min; p Four items ahead: - foreach( i; 0 .. 4 ) - auto num = i+1; p Item #{ num + extvar } //- Unescaped output p Prints 8: !{ min(10, 2*6, 8) } here, extvar is a int located somewhere else(other deit html file that has ran(hopefully) or vibe.d project that created it. (Obviously there has to be a way to get extvar) E.g., If deit can have a special variable called context that each html file can access and along with the vibe.d project, then we can easily pass the variable. doctype html html head title D string interpolations test body - import std.algorithm : min; p Four items ahead: - foreach( i; 0 .. 4 ) - auto num = i+1; p Item #{ num + (int)context["extvar"] } //- Unescaped output p Prints 8: !{ min(10, 2*6, 8) } or whatever I am a very new at this, but I think "the solution" is to call res.render! with all alias names you need. Defining int extvar =... before; you use: res.render!("your-template.dt",extvar,..) hope this helps. Regards mt.
Re: Question about mysql-d Object
On Tuesday, 8 December 2015 at 15:14:06 UTC, Daniel Kozak wrote: [...] >> A nested loop, did not worked either: >> >> foreach(row;rows){ >> foreach(field;row){ >> writeln(field);} >> } [...] Now I took a work around, getting the field names in a separate mysql-request, but they should be available in the row object, too? rows.fieldNames() this one is better result type is string[] Thank you!!!
Re: Question about mysql-d Object
On Monday, 7 December 2015 at 16:11:19 UTC, Daniel Kozak wrote: On Monday, 7 December 2015 at 14:40:12 UTC, Martin Tschierschke wrote: When I do the following: auto mysql = new Mysql("localhost", 3306, "mt", "", "verwaltung"); auto rows = mysql.query("select field from my_table limit 50"); foreach(row;rows){ writeln(row["field"]);} // second time same loop foreach(row;rows){ writeln(row["field"]);} [...] A nested loop, did not worked either: foreach(row;rows){ foreach(field;row){ writeln(field);} } Which other ways to access the elements of rows do I have? [...] what if you make array from it: import std.array: array; auto rows = mysql.query("select field from my_table limit 50").array; Thank you both for your answers! This worked, for the first part of my question. Now I took a work around, getting the field names in a separate mysql-request, but they should be available in the row object, too?
Question about mysql-d Object
When I do the following: auto mysql = new Mysql("localhost", 3306, "mt", "", "verwaltung"); auto rows = mysql.query("select field from my_table limit 50"); foreach(row;rows){ writeln(row["field"]);} // second time same loop foreach(row;rows){ writeln(row["field"]);} I only get the output of the first loop (50 lines), probably this is a feature not a bug, but what kind of Object is rows? A nested loop, did not worked either: foreach(row;rows){ foreach(field;row){ writeln(field);} } Which other ways to access the elements of rows do I have? Sorry, but I am very new on D, (it may be the best language available, I don't know yet, but it is really the most interesting!) thank you!