Re: Any sample how to use Sqlite-d?
On Wednesday, 17 January 2018 at 13:36:26 UTC, Marc wrote: I was looking for a library to use SQLite with D, found this (https://code.dlang.org/packages/sqlite-d) but it has no documentation or code example. I looked into files in the source code and wrote this: Database db = Database(name); auto table = db.table(tableName); auto rows = table.findRows!(format!"(id,date) => id == %s"(id)); (i'm aware of sql injection above) but it doesnt work, it seems the library has changed. If happen to that library author see this, would be very helpful. Also have a look at https://github.com/biozic/d2sqlite3 (documentation: http://biozic.github.io/d2sqlite3/d2sqlite3.html).
Re: Playing arround with mixin - alias?
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;`?
Re: How to get the type of a derived class in a method of its base class?
On Sunday, 19 February 2017 at 07:52:13 UTC, Max Samukha wrote: class A { this(T = this)() { static assert(is(T == B)); } } class B { } auto b = new B; Here, T becomes A, which may be reasonable but is completely useless. Is there a way to obtain the type of the class (or class instance reference) the method is called on? Not at compile time: class A { this() { assert(typeid(this) == typeid(B)); } } class B : A { } auto b = new B;
Re: Converting multiple inheritance code into C ++ for D language
On Saturday, 18 February 2017 at 19:05:14 UTC, Jean Cesar wrote: This is exactly what I want this code I did to understand how would apply multiple inheritance in D, C # also process using interfaces but the difference from C # to D is that C # already in the base class you have to define it as interface. .. OK, but I guess you are aware that in this code, using interfaces and the pseudo-multiple-inheritance is pointless! You could just ditch them and use regular methods :)
Re: Converting multiple inheritance code into C ++ for D language
On Saturday, 18 February 2017 at 12:56:51 UTC, wiki wrote: On Saturday, 18 February 2017 at 09:33:25 UTC, biozic wrote: A mixin can be used to provide an base implementation for the methods of an interface, along with data members, so that you don't have to define it in every class that implements the interface. An example : https://dpaste.dzfl.pl/b656851e5c51 I tried to use it in the same way but I did not understand correctly because to simulate, alias in this code I had already defined the classes as interfaces but I did not understand how these constructors should be declared for later use .. There are multiple typos problems with your code. For me, the main problem would be that this code is using OOP the wrong way, but maybe this code doesn't represent what you actually want to do... Anyway, see a corrected version below. import std.stdio; class Test1 { protected string _msg1; this(string msg1) { _msg1 = msg1; } } // No semicolon interface Test2 { // Interfaces can't have data members // This template could actually be out of the interface. // I just put it here because it's more clear that it's related to Test2. mixin template Impl() { protected string _msg2; // Data member is inside the template // This function is not a constructor. Only the class implementing // the interface will have one. void thisTest2(string msg2) { _msg2 = msg2; } } } interface Test3 { mixin template Impl() { protected string _msg3; void thisTest3(string msg3) { _msg3 = msg3; } } } class Test4 : Test1, Test2, Test3 { mixin Test2.Impl; mixin Test3.Impl; string _msg4; this(string msg1, string msg2, string msg3, string msg4) { super(msg1); // Calls the constructor of Test1 thisTest2(msg2); // Use interface Test2 thisTest3(msg3); // Use interface Test3 this._msg4 = msg4; // Test4 implementation } void show() // Don't use override here { writeln(_msg1, _msg2, _msg3, _msg4); } } void main() { auto teste = new Test4("\n\tTeste1 ", "Teste2 ", "Teste3 ", "Teste4"); teste.show(); // No explicit return is required }
Re: Converting multiple inheritance code into C ++ for D language
On Friday, 17 February 2017 at 23:35:33 UTC, Jean Cesar wrote: On Friday, 17 February 2017 at 23:31:41 UTC, Adam D. Ruppe wrote: On Friday, 17 February 2017 at 23:11:25 UTC, Jean Cesar wrote: so I changed the code to use interface but how would I do so I could use the constructor in the same way as such a C ++ code? Interfaces + mixin templates give you something very similar to multiple inheritance. You can have named functions in the mixin templates that do the work of the constructor, then call them from the real constructor. Yes I saw here that it uses interface to make multiple inheritance just like C#, but I did not understand what would this mixing? A mixin can be used to provide an base implementation for the methods of an interface, along with data members, so that you don't have to define it in every class that implements the interface. An example : https://dpaste.dzfl.pl/b656851e5c51
Re: Why is for() less efficient than foreach?
On Friday, 10 February 2017 at 12:39:50 UTC, Bastiaan Veelo wrote: void foreach_loop() { foreach(n, elem; d[]) elem = a[n] * b[n] / c[n]; } It's fast because the result of the operation (elem) is discarded on each iteration, so it is probably optimized away. Try: ``` void foreach_loop() { foreach(n, ref elem; d[]) elem = a[n] * b[n] / c[n]; } ``` You can also do: ``` d = a[] * b[] / c[]; ``` with no loop statement at all.
Re: embedding a library in Windows
On Monday, 30 January 2017 at 17:25:13 UTC, Nestor wrote: On Monday, 30 January 2017 at 16:40:47 UTC, biozic wrote: As an alternative, you could build an object file from Sqlite's source code (e.g. the amalgamation file from Sqlite's website) with a C compiler. Then you just build your D application with: dmd app.d sqlite3.d sqlite3.o[bj] No dll. Sqlite statically linked. You could also try https://code.dlang.org/packages/d2sqlite3 with option "--all-included". This wasn't tested much though. I tried to compile a static library with MinGW (which is the one I have at hand, v4.8.1) with this command: gcc -static -c sqlite3.c However: D:\prj\sqltest2\source>dmd app.d database.d sqlite.d sqlite3.o Error: unrecognized file extension o Sorry, I never used Mingw32. It's either an incompatible object file format, or dmd only accepts .obj extensions, or both... You could also use the dmc compiler (http://ftp.digitalmars.com/dmc.zip). Or see kinke's answer about using the MS compiler.
Re: embedding a library in Windows
On Monday, 30 January 2017 at 16:40:47 UTC, biozic wrote: You could also try https://code.dlang.org/packages/d2sqlite3 with option "--all-included". This wasn't tested much though. Sorry, this uses a dll on Windows.
Re: embedding a library in Windows
On Monday, 30 January 2017 at 13:00:15 UTC, Nestor wrote: Hi, In Windows, is it possible embed a dll library into an application (in this particular case, sqlite3.dll)? Notice I don't mean storing the resource in the application to extract it at runtime, but rather to produce a static self-contained application. If it's possible, please provide a brief howto. Thanks in advance. As an alternative, you could build an object file from Sqlite's source code (e.g. the amalgamation file from Sqlite's website) with a C compiler. Then you just build your D application with: dmd app.d sqlite3.d sqlite3.o[bj] No dll. Sqlite statically linked. You could also try https://code.dlang.org/packages/d2sqlite3 with option "--all-included". This wasn't tested much though.
Re: Convert duration to years?
On Sunday, 15 January 2017 at 14:20:04 UTC, Nestor wrote: On Sunday, 15 January 2017 at 14:04:39 UTC, Nestor wrote: ... For example, take a baby born in february 29 of year 2000 (leap year). In february 28 of 2001 that baby was one day short to one year. Family can make a concession and celebrate birthdays in february 28 of non-leap years, but march 1 is the actual day when the year of life completes. Which one to choose? On second thought, if a baby was born in march 1 of 1999 (non-leap year), in march 1 of 2000 (leap year) the age would have been one year plus one day (because of february 29). No. A baby born on March 1st 1999 is just "one year old" on March 1st 2000, as it also is on March 2nd or any day after during the same year. So perhaps the best thing is to always perform a "relaxed" calculation. I guess the problem of people born on February 29th is really application-dependent, and it also depends on the use of the calculated age. A social web app: users probably would like to see their age change on the 28th of non-leap years. A regulation-aware software: just follow what the law says. Etc.
Re: Convert duration to years?
On Sunday, 15 January 2017 at 08:40:37 UTC, Nestor wrote: I cleaned up the function a little, but it still feels like a hack: uint getAge(uint , uint mm, uint dd) { import std.datetime; SysTime t = Clock.currTime; ubyte correction = 0; if( (t.month < mm) || ( (t.month == mm) && (t.day < dd) ) ) correction += 1; return (t.year - - correction); } Isn't there anything better? It doesn't feel like a hack to me, because it's simple and correct code that comply with the common definition of a person's age. The only inaccuracy I can think of is about people born on February 29th...
Re: Separate IP parts
On Saturday, 10 December 2016 at 03:51:34 UTC, brocolis wrote: How do I separate IP parts with dlang? I found this very cool trick, with C++: http://stackoverflow.com/a/5328190 std::string ip ="192.168.1.54"; std::stringstream s(ip); int a,b,c,d; //to store the 4 ints char ch; //to temporarily store the '.' s >> a >> ch >> b >> ch >> c >> ch >> d; std::cout << a << " " << b << " " << c << " "<< d; I wonder what's the equivalent D code. This would do the same. I wouldn't say it's a trick. import std.format : formattedRead; import std.stdio : writefln; string ipAddr = "192.168.1.54"; int a, b, c, d; formattedRead(ipAddr, "%d.%d.%d.%d", &a, &b, &c, &d); writefln("%s %s %s %s", a, b, c, d);
Re: Binding to C - Arrays and Access Violation
On Tuesday, 2 February 2016 at 22:56:28 UTC, jmh530 wrote: I'm working on generating a binding to a C library. I've got the .h file converted and can call some parts of the library with no errors. However, I have reached a stumbling block in a critical part. The library requires passing function pointers to various functions in the library. When I try to run these functions, I get an Access Violation error. I enabled additional DMD warnings, which helped pinpoint the issue. My D code calls a C function. One of the parameters to the C function is a function pointer to a D function. This D function (below) is one that I copied from the C library's tutorial. I only slightly changed the signature. This function is eventually called in other functions in the C library. double myfunc(uint n, const double* x, double* grad, void* my_func_data) { if (grad) { grad[0] = 0.0; grad[1] = 0.5 / sqrt(x[1]); } return sqrt(x[1]); } The line (though likely the next will too) that causes a problem is grad[0] = 0.0; Thus, as it is an Access Violation, I'm guessing the issue is with accessing elements of arrays in the D function from the C function. I don't know. When I try to call the D function in D, it works, but I have to refer to x and grad as x.ptr and grad.ptr. I'm not sure how to go about fixing this... Is grad allocated in the D code? If so, it could have been collected because the GC lost track of its use when passing to and from the C code. Or is grad owned by the C code? If so, either there is a bug in the library or it's misused, because its memory has been freed/has never been allocated/has gone out of scope.
Re: opIndex overload for slice not working...
On Monday, 25 January 2016 at 06:37:13 UTC, Enjoys Math wrote: class V(T) { public: this() {} V opIndex(size_t i, size_t j) { writeln("Hello, foo!"); return this; } } main() { auto v = new V!int(); auto u = v[3..4];// ERROR } Error: no [] operator overload for type the_module.V!int You're mixing slicing and indexing. Use *opSlice* to support i..j slicing notation. --- import std.stdio; class V(T) { public: this() {} V opIndex(size_t i, size_t j) { writeln("Indexing"); return this; } V opSlice(size_t i, size_t j) { writeln("Slicing"); return this; } } void main() { auto v = new V!int(); auto w = v[3, 4]; // Indexing auto u = v[3..4]; // Slicing } ---
Re: core.time Duration how to get units in double/float format?
On Sunday, 17 January 2016 at 14:43:26 UTC, Borislav Kosharov wrote: Seeing that TickDuration is being deprecated and that I should use Duration instead, I faced a problem. I need to get total seconds like a float. Using .total!"seconds" returns a long and if the duration is less than 1 second I get 0. My question is whats the right way to do it. Because I saw that TickDuration has a to!("seconds", float) method, but Duration doesn't have one. I can convert Duration to TickDuration and call to but seeing that its deprecated makes me think there is a better way. Why not just use a smaller granularity for Duration.total and convert the result? duration.total!"nsecs" / cast(float) 1e9
Re: Passing functions as template parameter and assigning default values to them
On Sunday, 21 June 2015 at 09:34:51 UTC, kerdemdemir wrote: Hi, I need to find the index of maximum element so my code: int indexOfMax(R)(R range) { alias Type = typeof(range.front().re); > I don't like .re here Type max = 0; size_t maxIndex = 0; foreach ( index,elem; range ) { if ( elem.re > max )-> And also here { max = elem.re; maxIndex = index; } } return maxIndex; } Since my range contains Complex!double types I have to add ".re" for current implementation. But I want to be more generic. Like how std.algorithm.map is. Like: range.map!(a => a.re). So what I want to achive is : indexOfMax!(a => a.re)(complexRange); > implement algorithm on a.re indexOfMax(intRange); -> if a function is not given act like (a => a) Any advice with template function parameters or mixins will make me happy. Regards Erdem You can use a template alias parameter with a default value that is your default lambda: int indexOfMax(alias fun = a => a, R)(R range) { // Use `fun` here like a function. } -- Nico
Re: std.random question
On Sunday, 3 May 2015 at 09:28:40 UTC, Dennis Ritchie wrote: On Sunday, 3 May 2015 at 09:04:07 UTC, tired_eyes wrote: On Sunday, 3 May 2015 at 08:48:52 UTC, Dennis Ritchie wrote: On Sunday, 3 May 2015 at 08:42:57 UTC, tired_eyes wrote: Feels pretty silly, but I can't compile this: import std.random; auto i = uniform(0, 10); DMD spits this: /usr/include/dmd/phobos/std/random.d(1188): Error: static variable initialized cannot be read at compile time /usr/include/dmd/phobos/std/random.d(1231):called from here: rndGen() /usr/include/dmd/phobos/std/random.d(1231):called from here: uniform(a, b, rndGen()) Perhaps I'm missing something obvious? dmd 2.067.1, openSUSE 13.2 x64 void main() { import std.random; auto i = uniform(0, 10); } Not so simple, unfortunately. Actual code: import std.random; struct Mystruct { auto id = uniform(0, 10); } void main() { // wahtever } ..and no luck. I think it is a bug: No. The aboc code defines a field of Mystruct calld 'id', with a type inferred from the static initializer expression 'uniform(0, 10)'. The problem is that a static initializer is... static! So the expression must be evaluated at compile-time. The uniform generator from std.random cannot be used at compile-time, thus the error. You could do: --- import std.random; struct Mystruct { int id; static opCall() { Mystruct s; s.id = uniform(0, 10); return s; } } void main() { auto s = Mystruct(); // whatever } ---
Re: Factory pattern in D
On Friday, 1 May 2015 at 11:20:32 UTC, Chris wrote: On Friday, 1 May 2015 at 11:11:28 UTC, biozic wrote: On Friday, 1 May 2015 at 11:01:29 UTC, Chris wrote: Thinking about it, T factory(T)() { return T(); } is better suited for a factory (with static type checks). But then I don't know what factory!X() provides that X() alone doesn't. Just cleaner code with type checks T factory(T)() { static if (is (T == A) || (is (T == B))) return T(); else assert(0, "Type "~T.stringof~" is not supported"); } and then you could have auto getType(string type = "")() { static if (type == "A") return factory!A(); else static if (type == "B") return factroy!B(); else return factory!A(); // default } in order to separate the logic, i.e. the factory produces the type and performs all the type checks, whereas `getType` is the interface for the user. A "factory" that produces a *type* could be: -- template checked(T) { static if (is (T == A) || (is (T == B))) alias checked = T; else static assert(0, "Type "~T.stringof~" is not supported"); } --
Re: Factory pattern in D
On Friday, 1 May 2015 at 11:01:29 UTC, Chris wrote: On Friday, 1 May 2015 at 10:47:22 UTC, Chris wrote: On Friday, 1 May 2015 at 10:46:20 UTC, Chris wrote: On Friday, 1 May 2015 at 10:27:16 UTC, biozic wrote: On Friday, 1 May 2015 at 10:12:36 UTC, Chris wrote: On Friday, 1 May 2015 at 10:04:46 UTC, Namespace wrote: How about this: struct A { int x = 42; } struct B { int x = 7; } T factory(T)() { return T(); } void main() { auto a = factory!(A); } That's what I was looking for, I just couldn't get it right. Thanks. Rikki: I wanted to avoid classes and interfaces. This might be a bit more useful: --- struct A { int x = 42; } struct B { int x = 7; } auto factory(string type = "")() { static if (type == "A") return A(); else static if (type == "B") return B(); else return A(); // default } void main() { auto a = factory!"A"; auto b = factory!"B"; auto x = factory; } --- Duh, I tried `static if` yesterday and I still got "Error: mismatched function return type inference of B and A". Now it works! Sure, I must have overlooked something. Sometimes it's better to go home and call it a day than to try to get something to work. And thanks, by the way! Thinking about it, T factory(T)() { return T(); } is better suited for a factory (with static type checks). But then I don't know what factory!X() provides that X() alone doesn't. This aside, how would I get something to load dynamically? It's either "mismatched function return type" or (with type check) "variable X cannot be read at compile time": void main(string[] args) { auto type = args[1]; auto myType = factory!type(); } So it's back to classes/interfaces again? H. Indeed. Runtime polymorphism is based on classes and interfaces. The struct and template solutions can only make "compile-time factories".
Re: Factory pattern in D
On Friday, 1 May 2015 at 10:12:36 UTC, Chris wrote: On Friday, 1 May 2015 at 10:04:46 UTC, Namespace wrote: How about this: struct A { int x = 42; } struct B { int x = 7; } T factory(T)() { return T(); } void main() { auto a = factory!(A); } That's what I was looking for, I just couldn't get it right. Thanks. Rikki: I wanted to avoid classes and interfaces. This might be a bit more useful: --- struct A { int x = 42; } struct B { int x = 7; } auto factory(string type = "")() { static if (type == "A") return A(); else static if (type == "B") return B(); else return A(); // default } void main() { auto a = factory!"A"; auto b = factory!"B"; auto x = factory; } ---
Re: Return data from different types of conditional operation
On Thursday, 23 April 2015 at 10:26:09 UTC, rumbu wrote: On Thursday, 23 April 2015 at 10:06:45 UTC, John Colvin wrote: On Thursday, 23 April 2015 at 09:48:21 UTC, Dennis Ritchie wrote: Hi, Why the program can not return different types of data from the conditional operator? - import std.stdio; auto foo() { if (true) { return 0; } else return "true"; } void main() { writeln(foo); } import std.variant, std.stdio; auto foo() { if (true) return Variant(0); else return Variant("Hello"); } void main() { foo.writeln; } If 'true' is known at compile time, it works: auto foo() { static if (true) { return 0; } else return "true"; } Yes, but auto foo() { static if (true) { return 0; } else this(statment) is [not.parsed]; } so it's not just working around a problem of returned type inference.
Re: std.array.split - Template instantiating error
On Saturday, 18 April 2015 at 08:08:41 UTC, nrgyzer wrote: Hi, I've the following source: import std.array : split; import std.stdio : writeln; void main() { string myString = "Hello World"; string[] splitted = myString.split(" "); } But when I compile the code above, I'm getting the following error: Error: template instance std.array.split!(string, string) error instantiating. I'm using the latest version of dmd (2.067.0), but I cannot figure out what I'm doing wrong :(. How to solve the problem? Thanks in advance! Works for me with DMD 2.067.0 on OSX: ["Hello", "World"]
Re: writefln patterns with mismatching compile-time known number of arguments
On Sunday, 12 April 2015 at 21:34:21 UTC, H. S. Teoh wrote: On Sun, Apr 12, 2015 at 02:33:03PM +, ketmar via Digitalmars-d-learn wrote: On Sun, 12 Apr 2015 14:18:21 +, JR wrote: > But the compiler has all the pieces of information needed to > see > it's wrong, doesn't it? no, it doesn't. compiler doesn't know about `std.format.format` and it's special abilities. while it is possible to add such checks to the compiler, it will introduce interdependency between compiler and phobos, which is not desirable. writing CTFE `writef` version is possible without template bloat in binary, but it will take more memory in compile time and slows compilation. there were talks about having `writef!"fmt"(args)` in phobos, but nobody took that task yet. It's not hard to write a CTFE version of writef/writeln/etc., that takes the format argument at compile-time, since std.format itself is already CTFE-able. Except for floating-point values (at least).
Structs as template parameters: weird error message
The code below doesn't compile. Why this error message? --- struct Item { int i; } struct Params { Item* item; this(int i) { item = new Item(i); // line 9 } } struct Foo(Params params) {} enum foo = Foo!(Params(1)); --- test.d(9): Error: Item(1) is not an lvalue