Re: automate tuple creation

2022-01-20 Thread bauss via Digitalmars-d-learn

On Thursday, 20 January 2022 at 04:00:59 UTC, forkit wrote:

On Thursday, 20 January 2022 at 00:30:44 UTC, H. S. Teoh wrote:


Do the id's have to be unique?


yep...



Don't make them random then, but use an incrementor.

If you can have ids that aren't integers then you could use uuids 
too.


https://dlang.org/phobos/std_uuid.html



Re: non-constant expression ["foo":5, "bar":10, "baz":2000]

2022-01-06 Thread bauss via Digitalmars-d-learn

On Thursday, 6 January 2022 at 16:01:40 UTC, HuskyNator wrote:

On Thursday, 6 January 2022 at 13:33:24 UTC, bauss wrote:
While not the exact same, there's a small work around here 
that can help in some cases:


```d
immutable long[string] aa;
shared static this() {
aa = [
  "foo": 5,
  "bar": 10,
  "baz": 2000
];
}
```


Thanks a lot!
I've tried it with static this() earlier, but the shared part 
fixes it for me.


The reason why it needs to be shared is because it's only 
executed once, where as just static this is executed for each 
thread.


Re: non-constant expression ["foo":5, "bar":10, "baz":2000]

2022-01-06 Thread bauss via Digitalmars-d-learn

On Thursday, 6 January 2022 at 12:04:12 UTC, HuskyNator wrote:
On Monday, 28 November 2016 at 14:41:44 UTC, Era Scarecrow 
wrote:
On Monday, 28 November 2016 at 09:06:34 UTC, Paolo Invernizzi 
wrote:
The point is that I was trying to avoid some cycle between 
modules, detected by 2.072. This bug leads to pollution in 
the use of static this only to workaround the limitation...


 Wasn't someone working on a Associative Array static type 
that could be created at CTFE and run at runtime?


I'm guessing there isn't.
Sadly still running into issues because of this :(


While not the exact same, there's a small work around here that 
can help in some cases:


```d
immutable long[string] aa;
shared static this() {
aa = [
  "foo": 5,
  "bar": 10,
  "baz": 2000
];
}
```


Re: Thread exits immediately with no reason.

2021-12-20 Thread bauss via Digitalmars-d-learn

On Tuesday, 21 December 2021 at 01:13:10 UTC, Ali Çehreli wrote:


Note: nothrow means "does not throw Exception". Errors can 
still be thrown.


Ali


Which sort of makes sense since they're in theory 
"unrecoverable", but the name is sort of misleading because of 
this minor detail. It should at the very least warn people about 
functions that may throw errors.


Re: Is it possible to do this with a template?

2021-12-17 Thread bauss via Digitalmars-d-learn

On Friday, 17 December 2021 at 08:59:19 UTC, rempas wrote:

On Friday, 17 December 2021 at 08:44:39 UTC, Mitacha wrote:


It isn't really about limitation of templates. You're trying 
to use mixin template and it's main purpose is to inject 
declarations. If you want to replace `is expression` with 
template you could use something like this:


```d
bool is_same(alias value, T)() {
return is(typeof(value) == T);
}

void main() {
int value = 10;
static if (is_same!(value, int)) {
writeln("it is true!");
} else {
writeln("it is false!");
}
}
```


Oh! That's nice! I didn't even knew it was possible to create 
template functions like this! Thanks!


Personally, I don't see any benefit with replacing that kind 
of `is expressions` with templates. Perhaps I'm missing 
something :)


The benefits are typing less code and make it more readable and 
easy on the eyes ;)


You can also do it as a normal template:

```d
template is_same(alias value, T)
{
enum is_same = is(typeof(value) == T);
}
```


Re: How to define property type to Array!struct?

2021-12-15 Thread bauss via Digitalmars-d-learn
On Wednesday, 15 December 2021 at 11:36:41 UTC, Manfred Nowak 
wrote:

On Tuesday, 14 December 2021 at 08:28:01 UTC, WebFreak001 wrote:
[...]
Alternatively, remove the template `()` from your `struct 
Header`


What is the semantic sense of a template having no parameters?

Although the documentation declares such a template to be 
syntactically correct, not a single example suggests a meaning.


In this case, nothing.

In other cases to only compile said "object" in specific 
conditions.


Re: How to loop through characters of a string in D language?

2021-12-12 Thread bauss via Digitalmars-d-learn

On Monday, 13 December 2021 at 05:46:06 UTC, forkit wrote:
On Saturday, 11 December 2021 at 09:25:37 UTC, Ola Fosheim 
Grøstad wrote:


```putchar(…)``` is too slow!




On planet Mars maybe, but here on earth, my computer can do 
about 4 billion ticks per second, and my entire program (using 
putchar) takes only 3084 ticks.


Can I borrow a couple of your ticks?


Re: How to loop through characters of a string in D language?

2021-12-08 Thread bauss via Digitalmars-d-learn

On Wednesday, 8 December 2021 at 11:23:45 UTC, BoQsc wrote:

Let's say I want to skip characters and build a new string.

The string example to loop/iterate:

```
import std.stdio;

void main()
{
string a="abc;def;ab";

}
```

The character I want to skip: `;`

Expected result:
```
abcdefab
```


string b = a.replace(";", "");


Re: How to deploy single exe application (?)

2021-11-30 Thread bauss via Digitalmars-d-learn

On Monday, 29 November 2021 at 14:58:07 UTC, Willem wrote:


Thanks again for all the responses. For now -- I am simply 
adding the DLL to the EXE and writing it out to the working 
directory.   Not elegant - but it does work.




If you intend to distribute it then becareful with this as it 
might trigger some (if not all) antiviruses under most 
configurations.


Re: what i don't like about dub

2021-11-23 Thread bauss via Digitalmars-d-learn

On Tuesday, 23 November 2021 at 10:19:29 UTC, Tejas wrote:

On Tuesday, 23 November 2021 at 07:06:17 UTC, bauss wrote:
On Tuesday, 23 November 2021 at 01:19:44 UTC, Alain De Vos 
wrote:

[...]


Well, it's not always possible to check such things without 
heavy performance cost. It can take a long time to verify 
whether something is already installed, as it could be 
unzipped in some obscure folder deep into many subfolders.


The solution here would probably be the ability to specify 
certain installations and their paths etc. within your 
project. It comes at almost no expense on running dub and the 
only real expense is users having to specify such 
installations.


Doesn't dub cache stuff that it downloads? If, however, the 
user is asking it to search the __entirety__ of their storage 
device(s) to check for some arbitrary folder where the package 
exists... Yeah that's a very though ask


Yes, dub caches everything it uses. Honestly I'd never want dub 
to search my device for files that might exist that it might need.


Re: what i don't like about dub

2021-11-22 Thread bauss via Digitalmars-d-learn

On Tuesday, 23 November 2021 at 01:19:44 UTC, Alain De Vos wrote:
What i don't like about dub is that is does not check which 
software is installed on the host.
Currentlu tck86 is installed on the host including header files 
& shared libraries.
But dub says let me just download my own personal version and i 
will compile it in your home directory

/home/myuser/.dub
There is something inherently wrong in doing so.

Note other package managers of different languages do the same 
thing.
dub should really check if something should really be 
downloaded.
Otherwise you end up in a library hell, in Gates words known as 
dll hell.


Well, it's not always possible to check such things without heavy 
performance cost. It can take a long time to verify whether 
something is already installed, as it could be unzipped in some 
obscure folder deep into many subfolders.


The solution here would probably be the ability to specify 
certain installations and their paths etc. within your project. 
It comes at almost no expense on running dub and the only real 
expense is users having to specify such installations.


Re: Null pointer in __vptr

2021-11-22 Thread bauss via Digitalmars-d-learn

On Friday, 19 November 2021 at 20:27:11 UTC, frame wrote:

On Friday, 19 November 2021 at 18:14:03 UTC, Adam D Ruppe wrote:

I've gotten that before as a result of a compiler bug... I had 
an abstract method that wasn't implemented but the compile 
time error got swallowed by a bug and thus the null method 
made its way to the binary.


You got it! It was an abstract class involved and the method 
signature was just wrong, but no compile error. Thanks!


Seems like it was only partially fixed then, specifically for 
missing abstract methods, but not whether the signature was 
correct or not.


Seems like a critical bug to me.


Re: Exceptions names list

2021-11-16 Thread bauss via Digitalmars-d-learn

On Monday, 15 November 2021 at 22:44:35 UTC, Ali Çehreli wrote:

On 11/15/21 2:28 PM, pascal111 wrote:
> I want to know where the list of exceptions names that
"throw" statement
> uses.

Such a list is not very useful. Normally all we need is 
Exception and occasionally one or two other specific types.




It's actually very useful when you want to throw exceptions 
yourself, because instead of writing your own custom exception 
then you could use an existing implementation.


Re: What is D's "__debugbreak()" equivalent?

2021-10-29 Thread bauss via Digitalmars-d-learn

On Friday, 29 October 2021 at 11:36:13 UTC, Adam D Ruppe wrote:

On Friday, 29 October 2021 at 09:32:07 UTC, bauss wrote:

} else version(D_InlineAsm_X86_64) {


just fyi but `int 3;` works just as well in 32 bit as 64


Yeah, that's why I noted that there's also D_InlineAsm_X86 but I 
just didn't bother adding it.


Re: What is D's "__debugbreak()" equivalent?

2021-10-29 Thread bauss via Digitalmars-d-learn

On Thursday, 28 October 2021 at 09:54:44 UTC, Dennis wrote:

On Wednesday, 27 October 2021 at 16:54:49 UTC, Simon wrote:

What is the equivalent in D?


With LDC, you have:

```D
import ldc.intrinsics: llvm_debugtrap;
```

Combining that with previous answers, you can make something 
like this:

```D
void debugbreak() nothrow @nogc @trusted {
version(D_InlineAsm_X86_64) {
asm nothrow @nogc {
int 3;
}
} else version(LDC) {
import ldc.intrinsics: llvm_debugtrap;
llvm_debugtrap();
} else {
assert(0); // No `breakPoint` for this compiler configuration
}
}
```


Shouldn't it be this instead, unless D_InlineAsm_X86_64 isn't 
available for ldc?


There's also D_InlineAsm_X86 btw.

```D
void debugbreak() nothrow @nogc @trusted {
version(LDC) {
import ldc.intrinsics: llvm_debugtrap;
llvm_debugtrap();
} else version(D_InlineAsm_X86_64) {
asm nothrow @nogc {
int 3;
}
} else {
assert(0); // No `breakPoint` for this compiler configuration
}
}
```


Re: Error: Could not open 'libcmt.lib'

2021-10-27 Thread bauss via Digitalmars-d-learn

On Monday, 25 October 2021 at 14:43:06 UTC, Willem wrote:
Just starting out new with D.  Up until now I have been using 
Python and a bit of OCaml.


Error when linking: "lld-link: error: could not open 
'libcmt.lib': no such file or directory"


What I did:  I installed the complete D setup in my Windows 10 
PC -- including VS 2019.


From the command line "C:\D\dmd2vars64.bat" I was able to 
creating a simple program with "dub init hello"


When executing it with "dub run hello" I get following error:

"lld-link: error: could not open 'libcmt.lib': no such file or 
directory"


However -- running "dub run --arch=x86" did work

dmd --version
DMD64 D Compiler v2.098.0-dirty

dub --version
DUB version 1.27.0, built on Oct 10 2021

Searching the forum it appear to be related to MS runtimes... 
but I have not yet been able to resolve it. Any suggestions 
would be greatly appreciated.


Many Thanks.


C++ runtime needs to be installed I believe.


Re: TimeoutException for connecting to MySQL using a hunt-entity.

2021-10-27 Thread bauss via Digitalmars-d-learn

On Monday, 25 October 2021 at 12:54:32 UTC, greenbyte wrote:

On Monday, 25 October 2021 at 07:45:26 UTC, Imperatorn wrote:

On Friday, 22 October 2021 at 11:42:34 UTC, greenbyte wrote:

Hi, all!

I use the hunt-entity library to work with MySQL. I get the 
hunt.Exceptions.TimeoutException: "Timeout in 30 secs" when 
trying to connect. I configured MySQL and ran the code from 
the instructions https://github.com/huntlabs/hunt-entity


MySQL:
mysql Ver 8.0.27 for Linux on x86_64 (MySQL Community Server 
- GPL)


DUB:
version 1.25.0, built on Apr 23 2021

In dub.json enabled "hunt-entity": "~>2.7.3"


And also of course triple check your credentials etc.


Yes. When credentials don't match, I have AccessDenied 
exception.


Are you able to connect to the mysql using something else like a 
heidisql?


Just to isolate whether the issue is mysql configuration or an 
actual problem with the package.


Re: std.zip expand: memory allocation failed

2021-10-27 Thread bauss via Digitalmars-d-learn
On Tuesday, 26 October 2021 at 13:43:36 UTC, Steven Schveighoffer 
wrote:

On 10/26/21 2:32 AM, bauss wrote:

On Monday, 25 October 2021 at 22:38:38 UTC, Imperatorn wrote:
On Monday, 25 October 2021 at 20:50:40 UTC, Steven 
Schveighoffer wrote:

On 10/24/21 8:00 AM, Selim Ozel wrote:

It turns out my computer was literally running out of 
memory as the file was getting unzipped. For some reason  
to uncompress a 1-gig file with uncompressed size of 4-gig, 
Zip Archive of D-Lang tries to use more than 16 gig of RAM. 
I don't know why. Maybe I missed something. I use a Windows 
10, DMD v2.091 with x86_mscoff.


Wait, x86 is 32-bit. Max address space is 4GB. So maybe it 
was just trying to use 4GB and running out of memory?


-Steve


Good catch, but still, should it use so much memory?


Definitely not. It shouldn't use a lot of memory when 
unzipping as it should be done in chunks!


You guys aren't getting it:

```
ubyte[] expand(ArchiveMember de);
Decompress the contents of a member.
Fills in properties extractVersion, flags, compressionMethod, 
time, crc32, compressedSize, expandedSize, expandedData[], 
name[], extra[].

```

Where is it supposed to store that `ubyte[]`?

-Steve


It's not supposed, but a new implementation can utilize something 
like a stream.


Re: std.zip expand: memory allocation failed

2021-10-26 Thread bauss via Digitalmars-d-learn

On Monday, 25 October 2021 at 22:38:38 UTC, Imperatorn wrote:
On Monday, 25 October 2021 at 20:50:40 UTC, Steven 
Schveighoffer wrote:

On 10/24/21 8:00 AM, Selim Ozel wrote:

It turns out my computer was literally running out of memory 
as the file was getting unzipped. For some reason  to 
uncompress a 1-gig file with uncompressed size of 4-gig, Zip 
Archive of D-Lang tries to use more than 16 gig of RAM. I 
don't know why. Maybe I missed something. I use a Windows 10, 
DMD v2.091 with x86_mscoff.


Wait, x86 is 32-bit. Max address space is 4GB. So maybe it was 
just trying to use 4GB and running out of memory?


-Steve


Good catch, but still, should it use so much memory?


Definitely not. It shouldn't use a lot of memory when unzipping 
as it should be done in chunks!


Re: Why do we have Dmain?

2021-10-25 Thread bauss via Digitalmars-d-learn

On Monday, 25 October 2021 at 07:49:44 UTC, user1234 wrote:


so with the D main you're directly in the the D "domain". In 
theory from that point, you don't need to ever use `strlen` for 
example.


Not just that, but you shouldn't use it at all, rather you can't 
use it!


You might be able to call it, but it won't work as expected 
because strings are not zero-terminated in D, unless the string 
is a literal.


strlen looks for \0, so using it for a string that isn't 
zero-terminated is asking for trouble.


Re: TimeoutException for connecting to MySQL using a hunt-entity.

2021-10-25 Thread bauss via Digitalmars-d-learn

On Sunday, 24 October 2021 at 20:58:22 UTC, greenbyte wrote:

On Friday, 22 October 2021 at 11:51:03 UTC, WebFreak001 wrote:

On Friday, 22 October 2021 at 11:42:34 UTC, greenbyte wrote:

Hi, all!

I use the hunt-entity library to work with MySQL. I get the 
hunt.Exceptions.TimeoutException: "Timeout in 30 secs" when 
trying to connect. I configured MySQL and ran the code from 
the instructions https://github.com/huntlabs/hunt-entity


MySQL:
mysql Ver 8.0.27 for Linux on x86_64 (MySQL Community Server 
- GPL)


DUB:
version 1.25.0, built on Apr 23 2021

In dub.json enabled "hunt-entity": "~>2.7.3"


From the error message you posted it seems like it's failing 
to connect. Did you check that the IP address and port you are 
connecting to are correct? In case of localhost, try 127.0.0.1 
instead of "localhost"


Yes, I did.


Did you check your firewall configuration and that you're allowed 
to establish a connection to the port?


Re: __traits(compiles) is true with warnings as errors

2021-10-14 Thread bauss via Digitalmars-d-learn

On Thursday, 14 October 2021 at 05:41:01 UTC, Tejas wrote:
On Wednesday, 13 October 2021 at 17:58:23 UTC, Jonathan Levi 
wrote:
When dmd is passed the "-w" tag, it "treats warnings as 
errors" but not with the "__traits(compiles)" expression.  Is 
this the intended action?


This code should compile even with "-w", but it does not.

int i;
static if (__traits(compiles,i += 5.2))
i += 5.2;


`pragma(msg, __traits(compiles,i += 5.2))` is `true`, even 
though it will stop the compiler.


My specific use case, where I am hindered by this, is with a 
guarded template function akin to this:


void fun(T,U)(ref T a, const U b)
if (__traits(compiles, a += b))
{
a += b;
}

I think this is a bug.  The Docs for __traits compiles state 
"Returns a bool true if all of the arguments compile . . ." 
which is not holding true.


But it _is_ compiling, just with a warning.

If you wish to force the code to compile, you can manually cast 
it to prevent the compiler from erroring out:

```d

void main(){
int i;
static if (__traits(compiles,i += 5.2))
i += cast(int)5.2;
}
```

Or in general:

```d
void fun(T,U)(ref T a, const U b)
 if (__traits(compiles, a += b))
 {
 a += cast(T)b;
 }
```

It seems the `__traits(compiles, ..)` feature was designed to 
operate independent of the command line flags passed to the D 
compiler.


I don't know if that's a bug or not though; best wait for 
someone more experienced to chime in.


__traits(compiles) just checks whether the arguments given are 
semantically correct. The given arguments in the example of OP 
are technically semantically correct and that's why it returns 
true.


What could be useful is a new trait (to not break existing code) 
like __traits(warning, ...) which does the same as 
__traits(compiles) but also checks whether the arguments would 
cause a warning by the compiler. OR __traits(compiles, ..., true) 
where true means aggressive (warnings as error) and false or 
nothing means the default behavior we have today.


The default behavior can't or shouldn't change as existing code 
that relies on it could break and the problem here is that the 
failure could be silent as you don't get an error message unless 
your specific use-case relies on the arguments compiling, but in 
a lot of cases it's used optionally to create branching.




Re: Linker error

2021-10-12 Thread bauss via Digitalmars-d-learn

On Tuesday, 12 October 2021 at 00:01:25 UTC, jfondren wrote:
On Monday, 11 October 2021 at 23:43:17 UTC, Ruby The Roobster 
wrote:

package mixin template move__() {
	pragma(inline) package void mv(Point moveby, ref Skeleton 
tomove)	{

foreach(i;tomove.faces) {
foreach(k;i.lines)  {
foreach(j;k.mid_points) {
j += moveby;
}
k.start += moveby;
k.stop += moveby;
}
i.center += moveby;
}
tomove.center += moveby;
}
}


It compiles if this `pragma(inline)` is removed.


Not to mention there is no point in marking mv with either 
pragma(inline) or package.


It's mixed into the function move(), which means it cannot be 
accessed outside of the function anyway, so that makes package 
unnecessary.


Inline will probably do nothing as the inline really just tells 
the compiler it should inline if it can or wants to, it's not a 
guarantee and it probably can't inline the function in this case.


Re: How to "stringnify"?

2021-10-11 Thread bauss via Digitalmars-d-learn

On Sunday, 10 October 2021 at 09:51:27 UTC, rempas wrote:

On Sunday, 10 October 2021 at 08:48:21 UTC, Imperatorn wrote:


For simple stuff you have .stringof


Thanks!


Just remember .stringof is not "literal" as in there are certain 
expression that won't return exactly what you're trying to 
"stringify" ex. aliases etc. will actually return what they're an 
alias of etc. there are many other exceptions too.


In general it will return just what you write, but not in all 
cases.


Re: Mutually recursive template expansion

2021-10-04 Thread bauss via Digitalmars-d-learn

On Friday, 1 October 2021 at 14:26:39 UTC, jfondren wrote:

On Friday, 1 October 2021 at 14:03:06 UTC, Stephen wrote:

This code should work should mutual recursion be supported.


It still wouldn't work, because structs are value types and 
it's impossible to say how large either struct is:


Error: struct `mutualrec.Ar` no size because of forward 
reference


With s/struct/class/ it still wouldn't work because this is a 
mixin problem rather than a problem of template mutual 
recursion:


```d
mixin(q{ class Ar { Br b; } });
mixin(q{ class Br { Ar b; } });
```

mutualrec2.d-mixin-1(1): Error: undefined identifier `Br`, did 
you mean class `Ar`?


This seems like a surprising limitation of mixin, though, which 
isn't highlighted by the spec.


Actually it is covered by the spec.

See:

https://dlang.org/spec/expression.html#mixin_expressions

It clearly says:

```
Each AssignExpression in the ArgumentList is evaluated at compile 
time

```

Which means that Br cannot be used in Ar since it cannot be 
evaluated at compile time during the mixin of Ar.


Re: Why sometimes stacktraces are printed and sometimes not?

2021-09-30 Thread bauss via Digitalmars-d-learn
On Wednesday, 29 September 2021 at 12:15:30 UTC, Steven 
Schveighoffer wrote:

On 9/29/21 6:57 AM, JN wrote:
What makes the difference on whether a crash stacktrace gets 
printed or not?


Sometimes I get a nice clean stacktrace with line numbers, 
sometimes all I get is "segmentation fault error -1265436346" 
(pseudo example) and I need to run under debugger to get the 
crash location.


segmentation faults are memory access errors. It means you are 
accessing a memory address that is not valid for your 
application. If you are accessing the wrong memory, it means 
something is terribly wrong in your program.


Note that on Windows in 32-bit mode, I believe you get a stack 
trace. On Linux, there is the undocumented 
`etc.linux.memoryhandler` which allows you to register an 
error-throwing signal handler.


Signals are not really easy to deal with in terms of properly 
throwing an exception. This only works on Linux, so I don't 
know if it's possible to port to other OSes. I've also found 
sometimes that it doesn't work right, so I only enable it when 
I am debugging.


-Steve


You might also mention that even if you had a stacktrace where 
the error happened, that's usually not where the error was 
caused. It's most likely a completely different place in the code.


The only time where you somewhat can be sure where it happens is 
when you try to access ex. a reference type that hasn't been 
instantiated.


That's why in languages like C# you don't get a segfault/access 
violation, but you get a NullReferenceException.


It's not a concept D has, so it defaults to segfault/access 
violation.


Which means you're in really deep water when you encounter one 
because you have no idea what caused it and where it was caused.


Re: What is the meaning of @future ?

2021-09-17 Thread bauss via Digitalmars-d-learn

On Thursday, 16 September 2021 at 20:53:34 UTC, Elmar wrote:

Hello D community.

I was browsing the `__traits` keywords and I found `isFuture` 
whose descriptions says something about `@future`-annotated 
variables.


[link](https://dlang.org/spec/traits.html#isFuture)

I didn't find anything about `@future` for the D programming 
language. I only found that this annotation is used in Apex to 
denote futures (a.k.a. promises) as programming concept.


Is this something which exists, existed, was abandoned early as 
an idea? I remember I had read that D uses a "fiber" library to 
provide coroutines and such.


Maybe somebody knows an answer for this.


It's just another "useless" attribute that the language has added 
before fixing any of the real problems :)


Basically it reserves a symbol for the future.

It's similar to creating ex. an empty function that throws an 
error or something like "Not implemented"


While I understand why it was added and what purpose it serves 
then I fail to see why that  was prioritized over actual issues.


It's solving an almost non-existing issue.


Re: Is this a compiler aliasing bug?

2021-09-17 Thread bauss via Digitalmars-d-learn

On Friday, 17 September 2021 at 09:44:53 UTC, Chris Katko wrote:
I'm debugging some code I wrote back in 2017 and a bounding box 
collision detection kept giving spurious answers till I 
resorted to assuming nothing and dumped every variable and 
alias.


I kept getting results like it was checking against itself, and 
of course, that would result in finding a collision. So I threw 
an assert in to check if it was identical objects (as in an 
error outside this function), and it didn't fire off. It 
appears (unless my eyes are deceiving me?) that variable 
aliases themselves are broken.


$ dmd --version
DMD64 D Compiler v2.098.0-beta.2

code:

```d
class drawable_object_t obj;

bool is_colliding_with(drawable_object_t obj) //was a class 
member

{
assert(this != obj);  //does not fire off

alias x1 = x;
alias y1 = y;
alias w1 = w;
alias h1 = h;

alias x2 = obj.x;
alias y2 = obj.y;
alias w2 = obj.w;
alias h2 = obj.h;

writeln("x1: ", x1, " y1: ", y1, " w1: ", w1, " h1: ", h1);
writeln("x2: ", x2, " y2: ", y2, " w2: ", w2, " h2: ", h2);

writeln("x1: ", x, " y1: ", y, " w1: ", w, " h1: ", h);
	writeln("x2: ", obj.x, " y2: ", obj.y, " w2: ", obj.w, " h2: 
", obj.h);

}
/*
output:

x1: 50 y1: 81 w1: 5 h1: 6
x2: 50 y2: 81 w2: 5 h2: 6   <
x1: 50 y1: 81 w1: 5 h1: 6
x2: 200 y2: 86.54 w2: 26 h2: 16 <
*/
```

The arrows point to the dependency. The top two sets of numbers 
should _not_ be identical.


It's not a bug because "obj.x" referes to the same symbol that is 
"this.x"


Alias will create an alias for a symbol, not an expression or the 
like.


So

obj.x is the same as this.x and in that case the alias will refer 
to the same thing.


The problem here is that the function is local to the class, so 
the alias will always refer to the class members directly and not 
the passed instance.


You really shouldn't use alias like this anyway and should just 
use auto, if it's because you want to save typing.


It shouldn't have any impact at all tbh.


Re: GC seems to crash my C-code function

2021-09-16 Thread bauss via Digitalmars-d-learn

On Thursday, 16 September 2021 at 11:35:27 UTC, frame wrote:

On Thursday, 16 September 2021 at 11:11:56 UTC, bauss wrote:

On Thursday, 16 September 2021 at 11:06:04 UTC, frame wrote:

On Thursday, 16 September 2021 at 10:48:19 UTC, bauss wrote:



Use toStringz and not .ptr.

Or append \0 to your string.


Stupid me should really know that already, thanks =)
Of course I have dup'ed the \0 from the string away...

But still I don't know why it works if the GC is off?


Did you see my second response?


Yes, but as I mentioned this pointer data isn't hold outside 
the function and the GC collect runs after data is processed, 
not in between. This pointer should be fully stack allocated 
and also newly generated each time the function is called, so I 
see no impact by the GC?


But GC collecting works now without issues.


My guess is something is undefined behavior in the C code, idk 
really


Re: GC seems to crash my C-code function

2021-09-16 Thread bauss via Digitalmars-d-learn

On Thursday, 16 September 2021 at 11:06:04 UTC, frame wrote:

On Thursday, 16 September 2021 at 10:48:19 UTC, bauss wrote:



Use toStringz and not .ptr.

Or append \0 to your string.


Stupid me should really know that already, thanks =)
Of course I have dup'ed the \0 from the string away...

But still I don't know why it works if the GC is off?


Did you see my second response?


Re: GC seems to crash my C-code function

2021-09-16 Thread bauss via Digitalmars-d-learn

On Thursday, 16 September 2021 at 10:48:19 UTC, bauss wrote:

On Thursday, 16 September 2021 at 10:28:37 UTC, frame wrote:
I have C-code translated in D that acts sometimes incorrect if 
the GC has made some collect. I would like to know why.


- Code runs correct if the GC collections are off
- There are no allocations within the C-translated-code except 
`throw new` (but they are not called)
- All allocations made in C-translated-code are still 
calloc/malloc `ed
- Even if I disable the GC before calling the function and 
just enable it after there will be an incorrect result
- Data passed to the function belongs to a struct and the 
function is called in a member function and is always correct


The main public function accepts a char* and returns a char*. 
Signature is like this:

```d
char* fun(ref int, ref int, size_t, const char*, out int, out 
int, out int, uint);

```
Input paramter gets the pointer from char[] `.ptr` property 
(and length must be supplied too).



I didn't want to change the code much so I have some piece 
like that:

```d
// const char *s2 = "!\"#$%&'()*+,-./:;<=>?@[\\]^_";
char* s2 = "!\"#$%&'()*+,-./:;<=>?@[\\]^_".dup.ptr;
```
Could this cause the issue? But the pointer is not used 
outside the function where it's created.


Use toStringz and not .ptr.

Or append \0 to your string.


Also see the documentation for "toStringz" which has this:

```
Important Note: When passing a char* to a C function, and the C 
function keeps it around for any reason, make sure that you keep 
a reference to it in your D code. Otherwise, it may become 
invalid during a garbage collection cycle and cause a nasty bug 
when the C code tries to use it.

```

It probably should tell that somewhere else too.


Re: GC seems to crash my C-code function

2021-09-16 Thread bauss via Digitalmars-d-learn

On Thursday, 16 September 2021 at 10:28:37 UTC, frame wrote:
I have C-code translated in D that acts sometimes incorrect if 
the GC has made some collect. I would like to know why.


- Code runs correct if the GC collections are off
- There are no allocations within the C-translated-code except 
`throw new` (but they are not called)
- All allocations made in C-translated-code are still 
calloc/malloc `ed
- Even if I disable the GC before calling the function and just 
enable it after there will be an incorrect result
- Data passed to the function belongs to a struct and the 
function is called in a member function and is always correct


The main public function accepts a char* and returns a char*. 
Signature is like this:

```d
char* fun(ref int, ref int, size_t, const char*, out int, out 
int, out int, uint);

```
Input paramter gets the pointer from char[] `.ptr` property 
(and length must be supplied too).



I didn't want to change the code much so I have some piece like 
that:

```d
// const char *s2 = "!\"#$%&'()*+,-./:;<=>?@[\\]^_";
char* s2 = "!\"#$%&'()*+,-./:;<=>?@[\\]^_".dup.ptr;
```
Could this cause the issue? But the pointer is not used outside 
the function where it's created.


Use toStringz and not .ptr.

Or append \0 to your string.


Re: GDC - program runs in one thread, DMD - in 4 threads, why?

2021-09-10 Thread bauss via Digitalmars-d-learn

On Friday, 10 September 2021 at 12:46:36 UTC, eugene wrote:
On Friday, 10 September 2021 at 12:10:58 UTC, Adam D Ruppe 
wrote:

btw why do the threads cause you trouble?


Well... probably it is subjective thing -
just do not 'like' when a program is doing something
that is not explicitly in it's source (I am C coder, you 
guessed).


More specifically - I have event driven state machine engine
(reactor pattern, written in C), which I have been using
over recent 5 years in various data acquisition and
network client/servers programs. All these programs
by their nature are single-threaded, since
'event/message driven' + 'state machines' combination gives me 
very

high-grained concurrency within single thread
(and I don't like fibers/greenlets/coroutines).

Recently I tried to re-implement that engine in D
(I also tried Rust and C#, but D appeared to be less 
'problematic').

I can give a link to sources of those echo-client/server pair
if someone is interested (but there is a 'little' problem
remained - when compliled with dmd, it sometimes crashes
upon receiving SIGINT).


Well the program you're writing is still single-threaded.

The GC only uses the other threads when sweeping so the program 
flow will still be single-threaded and the exact same.


It's just used to speed-up the GC.


Re: GDC - program runs in one thread, DMD - in 4 threads, why?

2021-09-10 Thread bauss via Digitalmars-d-learn

On Friday, 10 September 2021 at 10:39:48 UTC, Basile B. wrote:

On Friday, 10 September 2021 at 09:27:49 UTC, eugene wrote:

Here is test program (which is using DList aggressively)
[...]
Can this (really unwanted) behavior be disabled in DMD?
I do not want to have multiple threads,
a program (real program, not the test above) has to be 
single-threaded.


system used:
@dexp ~ $ cat /etc/debian_version
8.11


most recent dmd has a GC that collect in threads. it can be 
tuned but I dont find the documentation for this right now.


Here's the specific change:

https://dlang.org/changelog/2.087.0.html#gc_parallel

```
GC now marks the heap with multiple threads

The garbage collector now uses available CPU cores to mark the 
heap faster. This reduces pause times for a collection 
considerably.


By default, the GC uses all available logical cores of your CPU. 
This might affect your application if it has threads that are not 
suspended during the mark phase of the collection. You can 
configure the number of additional threads used for marking by 
DRT option parallel to the GC configuration, e.g. by passing 
--DRT-gcopt=parallel:2 on the command line. A value of 0 disables 
parallel marking completely.


As usual, you can also embed the configuration into the 
application by redefining rt_options, e.g.


extern(C) __gshared string[] rt_options = [ "gcopt=parallel:0" ];
```

__

So for OP what you want to use is:

```d
--DRT-gcopt=parallel:0
```


Re: Ali's Book - Programming in D

2021-09-10 Thread bauss via Digitalmars-d-learn

On Friday, 10 September 2021 at 10:46:25 UTC, Ron Tarrant wrote:
I guess this is mainly a question for Ali, but if anyone else 
knows the answer, please jump in...


If I were to buy a paperback copy of "Programming in D: 
Tutorial & Reference" from Amazon (this link: 
https://www.amazon.ca/Programming-Tutorial-Reference-Ali-Cehreli/dp/1515074609/ref=sr_1_1?dchild=1=programming+in+d%3A+tutorial+and+reference=1631270580=8-1) would I be getting the 2021 edition or an earlier one?


If I can't get the latest edition from Amazon, is there a place 
where I can get it?


Thanks.


I'm going to assume it's not the latest edition considering the 
specifications says this:


Publisher ‏ : ‎ CreateSpace Independent Publishing Platform; 1st 
edition (Aug. 19 2015)


But I could be wrong, perhaps Ali himself can answer it better 
than anyone else.


Re: Looking to get typeof parseXML return value

2021-09-07 Thread bauss via Digitalmars-d-learn

On Tuesday, 7 September 2021 at 08:27:33 UTC, JN wrote:

On Tuesday, 7 September 2021 at 04:13:08 UTC, Chris Piker wrote:
Like almost all new users to D I'm tripping over how to save 
and pass around variables since nothing has an understandable 
type anymore and you can't use "auto" for *class member* 
storage types.


I struggle with this often. Templated types that pretty much 
require you to use auto look nice on the paper and in samples, 
but once you try to integrate them into a larger project, it 
can get messy.


I agree with this, that's why I avoid templates anywhere they're 
not necessary and wrap everything in structs/classes with little 
to no template parameters.


Templates gets messy soon because you often end up 
overengineering trivial problems.


Re: Module import incompatibility

2021-08-31 Thread bauss via Digitalmars-d-learn

On Tuesday, 31 August 2021 at 12:26:28 UTC, frame wrote:

I'm sure it was asked before but can't find the thread:

How to deal best with an older library that uses the same class 
name as module name?

I get a lot of

`Error: module ABC from file ...ABC.d must be imported with 
'import ABC'`


Do I need to rename all modules?


The problem is that the file doesn't have a module statement so 
the compiler tries to resolve the module name from the import but 
is unable to resolve that properly.


The fix here is the module must have a module statement but since 
it's a library then you probably need to go into said library and 
fix it manually.


There's really no other fix I believe.


Re: vibe.d: is it possible to use bare HTML with the functionalty of DIET templates ?

2021-08-31 Thread bauss via Digitalmars-d-learn

On Tuesday, 31 August 2021 at 00:09:14 UTC, someone wrote:
Regarding vibe.d I think I'll give it a try (maybe placing it 
behind nginx at first) since I do really got a good 
first-impression ... kudos to the developers/maintainers :)


I like the idea of having D at my disposal within a web page, 
actually, it is a terrific feature to say the least.


What I do not like (even a bit) are the pseudo-HTML DIET 
templates. I can understand they can make life easy for some, 
but I am not the guy having any trouble writing 
well-good-structured HTML/XHTML/XML/etc to begin with, nor I am 
the kind of guy grunting because I will be forced to write 
closing tags and the like.


That being said, my specific question is:

Can I use vibe.d *without* DIET templates manually writing say, 
XHTML 1.1 pages, *while having D* at my disposal with the - 
prefixes I have seen so far ?


I mean, I am almost sure I can write D functions returning text 
and making my web page on-the-fly, but this is not what I have 
in mind, I would like to have an actual text file for a web 
page with the aforementioned - prefixes to actually hook D code 
leveraging the pre-compiled feature of DIET templates.


You might be interested in https://yuraiweb.org/

Even though it's a work in progress then you should be able to 
get by just fine with the basics for now.


Re: vibe.d community/forum/whatever ?

2021-08-30 Thread bauss via Digitalmars-d-learn

On Monday, 30 August 2021 at 02:39:06 UTC, someone wrote:

https://forum.rejectedsoftware.com/groups/rejectedsoftware.vibed/

I've been reading vibe.d tour and some documentation today to 
get some first impressions. https://vibed.org/community pointed 
to the link above ... but it seems it is full of crap.


Just use these forums as pretty much the same people are here 
that are in the vibe.d community.


Re: foreach() behavior on ranges

2021-08-25 Thread bauss via Digitalmars-d-learn
On Tuesday, 24 August 2021 at 19:06:44 UTC, Alexandru Ermicioi 
wrote:

On Tuesday, 24 August 2021 at 09:15:23 UTC, bauss wrote:


A range should be a struct always and thus its state is copied 
when the foreach loop is created.


Actually the range contracts don't mention that it needs to be 
a by value type. It can also be a reference type, i.e. a class.




Of course it doesn't disallow classes but it's generally advised 
that you use structs and that's what you want in 99% of the 
cases. It's usually a red flag when a range starts being a 
reference type.




Re: foreach() behavior on ranges

2021-08-24 Thread bauss via Digitalmars-d-learn

On Tuesday, 24 August 2021 at 08:36:18 UTC, frame wrote:
Consider a simple input range that can be iterated with 
empty(), front() and popFront(). That is comfortable to use 
with foreach() but what if the foreach loop will be cancelled? 
If a range isn't depleted yet and continued it will supply the 
same data twice on front() in the next use of foreach().


For some reason, foreach() does not call popFront() on a break 
or continue statement. There is no way to detect it except the 
range itself tracks its status and does an implicit popFront() 
if needed - but then this whole interface is some kind of 
useless.


There is opApply() on the other hand that is designed for 
foreach() and informs via non-0-result if the loop is cancelled 
- but this means that every range must implement it if the 
range should work in foreach() correctly?


This is very inconsistent. Either foreach() should deny usage 
of ranges that have no opApply() method or there should be a 
reset() or cancel() method in the interfaces that may be called 
by foreach() if they are implemented.


How do you handle that issue? Are your ranges designed to have 
this bug or do you implement opApply() always?


A range should be a struct always and thus its state is copied 
when the foreach loop is created.


Which means the state resets every time the loop is initiated.

If your range uses some internal state that isn't able to be 
copied then or your ranges are not structs then your ranges are 
inherently incorrect.


This is what a foreach loop on a range actually compiles to:

```d
for (auto copy = range; !copy.empty; copy.popFront())
{
...
}
```

This is easily evident in this example:

https://run.dlang.io/is/YFuWHn

Which prints:
1
2
1
2
3
4
5

Unless I'm misunderstanding your concern?


Re: Associative Array with double[][]

2021-07-22 Thread bauss via Digitalmars-d-learn

On Thursday, 22 July 2021 at 03:13:14 UTC, seany wrote:
I have a perimeter of a shape, given by a `double [][]` . I 
want to keep the lengths of various diagonals in another 
associative array.


So,

/// define some associative array to keep track of 
diagonals here..


auto perimeter = new double[][] (0,0);

/// --- fill up perimeter here ---

for(int i = 0; i < perimeter.length; i++) {
  for ( int j = 0; j < perimeter.length; j++) {

   fill up the associative array here

  }
}


So, I would like to do this:

double[ double[][]] diagonalLengths;
auto perimeter = new double[][] (0,0);

/// --- fill up perimeter here ---

for(int i = 0; i < perimeter.length; i++) {
  for ( int j = 0; j < perimeter.length; j++) {

  auto diag_point_i = perimeter[i];
  auto diag_point_j = perimeter[j];

  diagonalLengths [ [diag_point_i, diag_point_j]] = 
calculate_length (i,j);


  }
}


This is necessary, as further processing will change the 
indices of the points in the perimeter. I can't therefore use ` 
diagonalLengths [ [i,j]] = calculate_length (i,j);`


However, trying to do this is resulting to :

`test.d(29): Error: associative arrays can only be assigned 
values with immutable keys, not `double[][]`


What are my options now?  Do I have to convert the array which 
i plan to use as a key to a struct and define opEquals and 
toHash?


Are there automatic hashing mechanisms for this?

If there are multiple possibilities, what is the fastest in 
terms of memory? Thank you.


A possible but not that beautiful solution would be using string 
keys.


And then using UFC to make a "toKey" function that takes your 
double[][] as parameter.


To do this the first change would be your associative array has 
to be changed to:


```d
double[string] diagonalLengths;
```

The next change would be adding the "toKey" function, something 
like this should work:


```d
string asKey(double[][] d)
{
import std.algorithm : map;
import std.array : array, join;
import std.conv : to;

return d.map!(e => e.map!(i => 
i.to!string).join("_")).array.join(":");

}
```

The last change would be accessing the associative array you 
simply do it like this:


```d
diagonalLengths [ [diag_point_i, diag_point_j].asKey]
```

As you can see the only change in your logic is just adding the 
.asKey function call.


It's of course not gonna be fast or anything but it's functional.


Re: How to Fix Weird Build Failure with "-release" but OK with "-debug"?

2021-07-21 Thread bauss via Digitalmars-d-learn

On Wednesday, 21 July 2021 at 03:25:03 UTC, apz28 wrote:

VisualD project - Any hint to work around

DMD version:
DMD32 D Compiler v2.096.0-rc.1-dirty
Copyright (C) 1999-2021 by The D Language Foundation, All 
Rights Reserved written by Walter Bright


Failed Build Command line:
dmd -release -m32mscoff -O -inline -dip25 -dip1000 
-preview=fixAliasThis -X -Xf"Win32\Release\db_library.json" -c 
-of"Win32\Release\db_library.obj" 
@Win32\Release\db_library.build.rsp


with below error message:
..\..\pham\db\db_skdatabase.d(140): Error: null dereference in 
function 
_D4pham2db10fbdatabase7FbArray__T13readArrayImplTbZQsMFNfCQCeQCc8database12DbNameColumnZAb
..\..\pham\db\db_skdatabase.d(139): Error: null dereference in 
function 
_D4pham2db10fbdatabase7FbArray__T13readArrayImplTbZQsMFNfCQCeQCc8database12DbNameColumnZAb
Error: null dereference in function 
_D4pham2db10fbdatabase7FbArray__T13readArrayImplTbZQsMFNfCQCeQCc8database12DbNameColumnZAb
..\..\pham\db\db_skdatabase.d(138): Error: null dereference in 
function 
_D4pham2db10fbdatabase7FbArray__T13readArrayImplTbZQsMFNfCQCeQCc8database12DbNameColumnZAb


The problem here is not actually -release but -O.

-O will check for null derefences in your code when using @safe I 
believe.


I didn't inspect your code much further, as I'm short on time 
right now, but you should have a starting point now at least.


Re: Method definition

2021-07-21 Thread bauss via Digitalmars-d-learn

On Wednesday, 21 July 2021 at 12:08:21 UTC, Tim Gunesh wrote:
Is it possible to define methods outside the class in C ++ 
style? Something like this:


```d
class Parent{
   void Print();
}

void Parent.Print(){
   writeln("Hello, D!");
}
```


No and it doesn't make much sense to do so.

The reason why you have to do in C++ is because of header files 
and source files are separate.


Since D uses modules then definition and implementation doesn't 
have to be separated.


Re: Can static variables in methods be local for each object?

2021-07-21 Thread bauss via Digitalmars-d-learn

On Tuesday, 20 July 2021 at 15:59:30 UTC, Dukc wrote:

On Tuesday, 20 July 2021 at 09:24:07 UTC, Mark Lagodych wrote:
Is there a way to make myvar local to each instance of `X` 
without making it a variable of `X`? Just curious.


Yes.

```d
import std.stdio;

class X {
int x(int param) {
static int[typeof(this)] myvar;

if (param == 0) return myvar.get(this, 1234);
else return myvar[this] = param;
}

}

void main()
{
X x1 = new X;
X x2 = new X;

x1.x(0).writeln; //1234
x2.x(0).writeln; //1234

x1.x(17).writeln; //17
x2.x(0).writeln; //1234

x1.x(0).writeln; //17
x2.x(0).writeln; //1234
}
```

However, this is definitely not recommended. When you are 
calling a function with any particular object and argument set, 
you want it to do the same thing and return the same result, 
regardless of what's called before. Otherwise you're making 
debugging much more difficult than it needs to be.


This means that `static` variables should generally be used 
only for two things:
1: data that is only set at the beginning of the program, or at 
first use, and then left to the initial value.
2: caching results of expensive computation. Even this is a bit 
controversal, as it's easy to screw up - often it's just better 
to split the function in two, and let the caller to cache the 
results.


In this case, consider passing `myvar` explicitly:

```d
import std.stdio;

class X {
int x(int param, ref int[typeof(this)] myvar) {
if (param == 0) return myvar.get(this, 1234);
else return myvar[this] = param;
}

}

void main()
{
X x1 = new X;
X x2 = new X;
int[X] myvar;

x1.x(17, myvar).writeln; //17
x2.x(0, myvar).writeln; //1234

x1.x(0, myvar).writeln; //17
x2.x(0, myvar).writeln; //1234

myvar = null; //Forget all calls made so far
x1.x(0, myvar).writeln; //1234
x2.x(0, myvar).writeln; //1234
}
```


Wait, that's not too shabby to use the this pointer for a key to 
an AA.


It isn't really a single static variable however, but rather an 
AA that contains the static variables.


Re: Can static variables in methods be local for each object?

2021-07-20 Thread bauss via Digitalmars-d-learn

On Tuesday, 20 July 2021 at 09:24:07 UTC, Mark Lagodych wrote:

Let's say I have this code:
```d
import std.stdio;

class X {

int x(int param) {
static int myvar = 1234;

if (param == 0) return myvar;
else { myvar = param; return myvar; }
}

}

void main()
{
X x1 = new X;
X x2 = new X;

x1.x(0).writeln;
x2.x(0).writeln;

x1.x(17).writeln;
x2.x(0).writeln;
}
```

Is there a way to make myvar local to each instance of `X` 
without making it a variable of `X`? Just curious.


The only way I can think of is something like this:

```
import std.stdio;

interface X
{
int x(int param);
}

class XImpl(size_t n = 0) : X {
int x(int param) {
static int myvar = 1234;

if (param == 0) return myvar;
else { myvar = param; return myvar; }
}

}

void main()
{
X x1 = new XImpl!1;
X x2 = new XImpl!2;

x1.x(0).writeln;
x2.x(0).writeln;

x1.x(17).writeln;
x2.x(0).writeln;
}
```

Of course it's not entirely what you want but yeah I think that's 
about the closest to a solution that isn't overcomplicated.


Re: float price; if (price == float.nan) { // initialized } else { // uninitialized } ... valid ?

2021-07-08 Thread bauss via Digitalmars-d-learn

On Wednesday, 30 June 2021 at 16:41:40 UTC, someone wrote:

On Wednesday, 30 June 2021 at 16:24:38 UTC, Andre Pany wrote:

Side note: in case you want to work with money, you may 
consider using a specific data type like 
https://code.dlang.org/packages/money instead of float/double.


Yes, I've seen it, and in a previous-unrelated post I commented 
I am planning to use it (or something similar) because floats 
and currency are a horrible combo. I am not using it right now 
because I want to learn the language and encountering 
situations like this one helps me a lot, otherwise, I would 
have never noted such NaN behavior -to me, there are a lots of 
things that could fly under the radar at this moment. And by 
the way, looking at the code, money seems a quite simple 
non-nonsense implementation making it a solid candidate :)


Thanks for the tip Andre !


What you actually should do when working with money which is what 
a lot of banking solutions etc. do is working with cents only in 
2 decimal places.


So 25.98 would be represented as 2598.

It makes sure that you’ll never have rounding errors or floating 
point representations that are wrong.


Re: float price; if (price == float.nan) { // initialized } else { // uninitialized } ... valid ?

2021-07-08 Thread bauss via Digitalmars-d-learn

On Wednesday, 30 June 2021 at 16:19:35 UTC, someone wrote:

On Wednesday, 30 June 2021 at 10:38:05 UTC, jmh530 wrote:


You've never given something away for free?


... more often than usual LoL

Now, seriously, something for free has not a price = 0, it has 
NO price, that's what null is for; we use zero for the lack of 
null.


Actually a price can be 0, say if you have a sale that gives 100 
% off then the price doesn’t magically disappear. It could be 
that the 100 % off is only for specific people or businesses. Or 
that they pay fees instead of the price of a product, in which 
case there’s a fee price but a product with the price of 0 
because otherwise you’ll have accounting problems since you can’t 
make accounting on records without prices, because mathematically 
that makes no sense.


vibe.d and video files?

2020-09-17 Thread bauss via Digitalmars-d-learn

Does vibe.d not work properly with ex. mp4 files?

I have a consistent issues that it will only play part of video 
files in the browser.


As if it won't "stream" the rest of the video.

Is that a problem with vibe.d or is it some configuration that 
needs to be enabled?


Re: vibe.d and my first web service

2020-07-19 Thread bauss via Digitalmars-d-learn

On Saturday, 18 July 2020 at 17:23:06 UTC, Mr. Backup wrote:

On Saturday, 18 July 2020 at 12:16:09 UTC, Andre Pany wrote:

On Saturday, 18 July 2020 at 09:10:04 UTC, Mr. Backup wrote:

[...]


I assume you are using vibe.d 0.8.4 or older. Please check 
whether adding this to dub.json solves your problem:


​"versions": [ "VibeHighEventPriority" ]

(Restart your pc)

Vibe.d 0.9 0 will be released soon. I hope it will work out of 
the box there.


Kind regards
Andre


Thank you, it really works. But I dont feel good from it. There 
are many warnings during compiling. I will rather try to create 
my own web service only based on standard library. And 
hunt-http looks pretty good too.


The deprecation warnings are fine, it's just due to changes in 
DMD. They will eventually be fixed and ruled out as well.


They don't really do anything.

hunt-http is not really stable compared to vibe.d and there 
aren't much documentation either as it's in the beginning 
development phase I believe.


I use vibe.d in production with thousands of users on my sites 
and everything works just fine so don't worry about it. vibe.d is 
fairly stable.


Re: Vibe.d and NodeJs with Express

2020-07-14 Thread bauss via Digitalmars-d-learn

On Sunday, 12 July 2020 at 19:16:32 UTC, aberba wrote:
3) packages, now it might be better though. But I've always 
felt that there's not a lot of people using D for complete web 
dev projects...



I'm one of the few but then again I don't use a lot of external 
packages either other than what vibe.d really depends on.


I implement most things I need myself; mostly because when I find 
someone that has a package for what I need it's either too 
abstract, too generic or isn't really "simple" to implement.


Re: constructing labels for static foreach inside switch inside foreach

2020-07-07 Thread bauss via Digitalmars-d-learn
On Wednesday, 8 July 2020 at 02:06:01 UTC, Steven Schveighoffer 
wrote:
OK, so I have a situation where I'm foreaching over a 
compile-time list of types. Inside the loop, I'm using a second 
loop over a set of input.


Inside that loop, I'm using a switch on the input, and inside 
the switch, I'm foreaching over the type's members, to 
construct a switch that can handle member names (this is for 
serialization).


If I encounter a certain name, then I want to break out of the 
inner loop (it's a while loop)


So naturally, I have to use break statements with labels like:

innerloop:
while(haveMoreData)
   switchstmt:
   switch(nextDataElement) {
  static foreach(name; __traits(allMembers, T)) {
  case name:
 ... // handle it
 break switchstmt;
  }
  case "STOP":
 break innerloop;
   }

Seems simple enough, except that this inner portion is 
unrolled, and if I have more than one type to run this on, I 
already have an "innerloop" label defined.


Is there a way to define a label using a mixin or something? or 
do I have to wrap this in a function?


Is there another way to approach this?

-Steve


Unfortunately mixin does not support labels so I don't think you 
can do what you want to do.


Kind of surprised me tbh


Re: I want Sublime 3 D auto import !

2020-06-03 Thread bauss via Digitalmars-d-learn

On Wednesday, 3 June 2020 at 11:54:57 UTC, Виталий Фадеев wrote:

On Tuesday, 2 June 2020 at 20:08:09 UTC, bauss wrote:
What happens if you have the same symbol in multiple modules? 
Ex. two libraries that implement symbols with same name.




First module will inserted.


Is there a way to be selective?


I want it too! :)


And what about keyboard shortcut?


A specially for you !

Sublime 3 / Preferences / Key bindings:
[
{ "keys": ["alt+a"], "command": "dlang_auto_import" },
]


Thanks, that's great!


Re: I want Sublime 3 D auto import !

2020-06-02 Thread bauss via Digitalmars-d-learn

On Tuesday, 2 June 2020 at 06:00:10 UTC, Виталий Фадеев wrote:

On Monday, 1 June 2020 at 18:55:03 UTC, Paul Backus wrote:

On Monday, 1 June 2020 at 16:18:44 UTC, Виталий Фадеев wrote:


I do it!

https://github.com/vitalfadeev/SublimeDlangAutoImport


What happens if you have the same symbol in multiple modules? Ex. 
two libraries that implement symbols with same name.


Is there a way to be selective? And what about keyboard shortcut?


Re: How to get the pointer of "this" ?

2020-05-26 Thread bauss via Digitalmars-d-learn

On Tuesday, 26 May 2020 at 12:08:29 UTC, Johannes Loher wrote:

On Tuesday, 26 May 2020 at 11:44:58 UTC, Vinod K Chandran wrote:

On Monday, 25 May 2020 at 16:39:30 UTC, Mike Parker wrote:

On Monday, 25 May 2020 at 08:39:23 UTC, John Burton wrote:


I believe that in D *this* is a reference to the
object and not a pointer like in C++.
So I think that writing  might be what you need?


No. A class reference is a pointer under the hood. Getting 
its address will result in a pointer to the reference 
variable itself, not to the class instance. When passing a 
reference to a C API, casting it directly to the C type is 
correct.


Try this code. This will reproduce the same error.
import std.stdio : log = writeln;



void main() {
 log("Let's check whether 'this' is an lvalue or not.");
 Button btn = new Button("A button");
}

class Button {
this(string btntext){
mtext = btntext;
log("button created with the name , ", btntext);
log();
}
private:
string mt
}

It doesn't compile, the line

string mt

should be

string mtext;

instead. Indeed, we get a compiler error:

Error: this is not an lvalue and cannot be modified.

The problem is in line 11: You are trying to get the address of 
`this`. But `this` is an lvalue, so it does not have an address 
you could take. It becomes mir clear that this doesn’t work if 
you consider other lvalues, like literals:


int* = &1; // doesn’t compile, can’t take the address of an 
lvalue.


In this code example, the correct thing to do is to simply not 
take the address but pass `this` to `writeln`. That compiles 
and results in the following output:


Let's check whether 'this' is an lvalue or not.
button created with the name , A button
onlineapp.Button

(The module is onlineapp because I ran it in run.dlang.io)

I don't know what the correct thing would be in your original 
code though.

You can just do this to get around it:

 auto button = this;
 log();



Re: How to get the pointer of "this" ?

2020-05-25 Thread bauss via Digitalmars-d-learn

On Monday, 25 May 2020 at 17:14:13 UTC, Vinod K Chandran wrote:

On Monday, 25 May 2020 at 16:54:11 UTC, Mike Parker wrote:

On Monday, 25 May 2020 at 16:26:31 UTC, Vinod K Chandran wrote:


[...]


The error has nothing to do with taking a pointer to `this`. 
It's suggesting that somewhere in your code you're attempting 
to use the `this` reference like an lvalue, e.g. making an 
assignment to it. I don't see anywhere that you're doing that. 
Glancing through the code, I don't see anywhere that you're 
doing that (and unfortunately this is not a minimal example 
because of dependencies on some of your other modules, so I 
can't compile it myself).


[...]


Hi @Mike Parker,
Thank you for your valuable suggestions. I will sure follow 
them. Well, the  exact line number where the error showing is 
the one with the "SetWindowSubclass" function.  In pastebin, 
the line number is 124.


Need to see the Control  class too.

I think the problem might be something you're referencing from 
there but need to be sure.


Re: How to get the pointer of "this" ?

2020-05-24 Thread bauss via Digitalmars-d-learn

On Sunday, 24 May 2020 at 17:05:16 UTC, Vinod K Chandran wrote:

Hi all,
I have a class like this.
class Button : Control {
...
HWND createButton(){
...
		SetWindowSubclass(this.mHandle, SUBCLASSPROC(), 
UINT_PTR(subClsID), cast(DWORD_PTR) this);

}
}

But compiler says that - "Error: 'this' is not an lvalue and 
cannot be modified"
I've seen many cpp code which uses pointer to 'this' as the 
last parameter in SetWindowSubclass(). Is there something wrong 
with my approach ?


I think your issue might be elsewhere because casting this should 
be fine and it should not complain about that in your given code.


At least you should be able to pass this to another function or 
even cast it.


Please show the full code and the full error which gives you the 
stacktrace of where it's called and from where.


Re: Variable "i" can not be read at compile time

2020-05-24 Thread bauss via Digitalmars-d-learn

On Sunday, 24 May 2020 at 17:13:23 UTC, data pulverizer wrote:

On Sunday, 24 May 2020 at 16:57:54 UTC, ag0aep6g wrote:

On 24.05.20 18:34, data pulverizer wrote:
Since `kernel` is a `Tuple`, you can only access it with 
compile-time constant indices.


But your loop variable `i` is not a compile-time constant, 
it's being calculated at run time. What's more, it depends on 
`results.length` which is also not a compile-time constant. 
But `results.length` is the same as `kernels.length`. And 
being the length of a `Tuple`, that one is a compile-time 
constant.


So you can rewrite your loop as a `static foreach` (which is 
evaluated during compile-time) using `kernels.length` instead 
of `results.length`:


static foreach (i; 1 .. kernels.length)
{
results[i] = bench(kernels[i], n, verbose);
}


Thank you very much. I though that if I used a `static foreach` 
loop D would attempt to run the calculation `bench()` at 
compile time rather than at run time but it doesn't which is 
good. So `static foreach` allows you to index at compile time 
and if its scope runs at run time it is run time and if at 
compile time it is compile time evaluated?


You can see static foreach as unrolling a compile-time loop to a 
set of runtime-expressions.


Ex.

static foreach (i; 0 .. 10)
{
writeln(i);
}

Actually just becomes

writeln(0);
writeln(1);
writeln(2);
writeln(3);
writeln(4);
writeln(5);
writeln(6);
writeln(7);
writeln(8);
writeln(9);

- It creates no scope, whatsoever either. However doing

static foreach ()
{{
...
}}

Will create a scope per iteration.


Re: Using Vibe.d for not HTTP

2020-05-24 Thread bauss via Digitalmars-d-learn

On Sunday, 24 May 2020 at 08:10:33 UTC, Russel Winder wrote:

Hi,

Clearly Vibe.d is mostly for people doing HTTP and HTTPS stuff. 
Yet it claims to be able to support TCP and UDP working with 
other protocols. However, all the serious examples are 
HTTP/HTTPS related. All the TCP and UDP examples are basically 
trivial and thus useless to me for learning.


I am hoping I have just missed the page/example that does 
something more than just echo for a TCP server. If I haven't, 
is ther an example somewhere people know of that I can look at?


My problem is that I am not sure how to do a read/write system 
that is not

just echo using the "connection.write(connection)" trick.


Here is a quick example that I took from some old code I had:

I cannot guarantee that it works as it was written for an older 
version of vibe about 3 years ago.


I have not structured it either and just put all snippets 
together here.


listeners = [listenTCP(port, , ip)];

or

listeners = listenTCP(port, );

void handleConnections(TCPConnection connection) {
   ...
}

auto buf = new ubyte[amount];

connection.read(temp);

connection.write(buf);

Then of course you need to handle all that in the way your 
server/client operates.


How you implement it is of course just in similar fashion to 
general socket servers.


You read N bytes until you have received all bytes for the 
specific packet.


Then you can write your packets back afterwards.

Someone can correct me if I am wrong but I believe you can yield 
from the handlers in vibe.d


So if you haven't received all data yet you can yield between 
each call to read until all bytes have been received.


I will admit I have not used sockets in vibe.d for a very long 
time though.


Re: Distinguish between a null array and an empty array

2020-05-24 Thread bauss via Digitalmars-d-learn

On Sunday, 24 May 2020 at 12:26:42 UTC, ag0aep6g wrote:

On 24.05.20 14:12, bauss wrote:

Is there a way to do that?

Since the following are both true:

int[] a = null;
int[] b = [];

assert(a is null);
assert(!a.length);

assert(b is null);
assert(!b.length);

What I would like is to tell that b is an empty array and a is 
a null array.


No way. `null` and `[]` are the same thing for arrays. (Ulike 
`""` for strings which has a non-null `.ptr`.)


You can distinguish `null` from other (non-null, non-`[]`) 
empty arrays. For example:



int[] b = [1, 2, 3];
b = b[0 .. 0];

assert(b !is null);
assert(!b.length);



Dang, that sucks there is no proper way and I would say that's a 
big flaw of D.


Because what I need it for is for some data serialization but if 
the value is an empty array then it should be present and if it's 
null then it should not be present.


Since null is used to say "ignore this" in the data serialization.

Oh well.


Re: Distinguish between a null array and an empty array

2020-05-24 Thread bauss via Digitalmars-d-learn

On Sunday, 24 May 2020 at 12:12:31 UTC, bauss wrote:

Is there a way to do that?

Since the following are both true:

int[] a = null;
int[] b = [];

assert(a is null);
assert(!a.length);

assert(b is null);
assert(!b.length);

What I would like is to tell that b is an empty array and a is 
a null array.


I'm aware that D is special in that they're equal here BUT in my 
use-case I must absolutely handle them differently.


Distinguish between a null array and an empty array

2020-05-24 Thread bauss via Digitalmars-d-learn

Is there a way to do that?

Since the following are both true:

int[] a = null;
int[] b = [];

assert(a is null);
assert(!a.length);

assert(b is null);
assert(!b.length);

What I would like is to tell that b is an empty array and a is a 
null array.


Re: Learning Vibe.d

2020-05-23 Thread bauss via Digitalmars-d-learn

On Saturday, 23 May 2020 at 17:57:22 UTC, Russel Winder wrote:
On Sat, 2020-05-23 at 16:56 +, bauss via 
Digitalmars-d-learn wrote: […]


Had similar experiences on non-windows platforms.


I forgot to mention I was on Linux (Debian Sid).

I am (sort of) pleased it isn't just me – definitely unhappy it 
has happened

to others as well.


I think the solution is just to kill the pid.


Killing from the command line is not really an option as the 
process is used in integration tests.


I guess I'll have to send the process SIGKILL rather than 
SIGTERM, which is a bit annoying.


Yes, when I saw it happening then I thought it was probably just 
me.


Since it's not then perhaps an issue should be reported for vibe.d


Re: Learning Vibe.d

2020-05-23 Thread bauss via Digitalmars-d-learn

On Saturday, 23 May 2020 at 15:47:59 UTC, Russel Winder wrote:

Hi,

I thought I would try and do the async version of my mock 
AVR850 using the vibe.d TCP stuff. This is not HTTP, it is 
proper networking! ;-)


Problem one is that vibe.d sever processes never seem to 
terminate.


I am using runApplication or more likely runEventLoop in my 
main but it never returns. Starting the server from the command 
line, I Ctrl+C the process and get the message:


[main() INF] Received signal 2. Shutting down.

but whilst I get a command line prompt, the process is not 
terminated.


This is a bit of a blocker so help very much required.


Had similar experiences on non-windows platforms.

I think the solution is just to kill the pid.


std.container.array pointer

2020-05-23 Thread bauss via Digitalmars-d-learn

Is it possible to have a pointer to a nogc array?

Like for regular arrays you can just do .ptr

How would you do the same for a nogc array?

The reason is I need to read different types of values from a 
nogc byte array.


Ex. reading an int at offset 12 of the array.

With normal arrays it can be done like this:

auto i = (*(cast(int*)(arr.ptr + 12)));

--

Perhaps there is some function that can be used instead of using 
pointers to do this? I can't seem to find anything in phobos but 
it probably exist.


It must have as little overhead as possible though. Hence why I'm 
using pointers for the normal arrays.


to but nothrow?

2020-05-22 Thread bauss via Digitalmars-d-learn
Is there anyway to use the "to" template from std.conv but as 
nothrow?


Having it throw exceptions is not always acceptable because it's 
generally expensive.


Something that attempted to convert would be far more fesible.

Is there anything like that?

Ex. from C# there's int.TryParse etc.

Those all return booleans for whether the conversion was 
successful or not.


Like what would the equivalent of this be:

```
if (int.TryParse("1234", out int number))
{
// Use number ...
}
```

Sure I can do:

```
bool tryParse(From,To)(From fromValue, out To toValue)
{
try
{
toValue = fromValue.to!To;
return true;
}
catch (ConvException e)
{
toValue = To.init;
return false;
}
}
```

But that does not seem like an efficient approach.


Re: D and Async I/O

2020-05-11 Thread bauss via Digitalmars-d-learn

On Monday, 11 May 2020 at 14:02:54 UTC, Russel Winder wrote:
OK, so I need to create an asynchronous TCP server (not HTTP or 
HTTPS, this is

a real server ;-) ).

I think the normal response is "Use Vibe.d". However, recently 
I see Hunt is an alternative. Has anyone any way of choosing 
between the two?




vibe.d is much more mature than Hunt, that would be my take on it.

Also Hunt lacks documentation etc.

I notice that Hunt uses it's own library eschewing all of 
Phobos. Is this an

indicator that Phobos is not suitable for networking activity?


std.socket is terrible, so yes that is an indicator.

You can't even wrap something up fast in it either.

Basically it's low-level while not being low-level at the same 
time. You have to handle __everything__ yourself pretty much.


Re: Why does indexing a string inside of a recursive call yield a different result?

2020-05-10 Thread bauss via Digitalmars-d-learn

On Sunday, 10 May 2020 at 10:02:18 UTC, Adnan wrote:



In my naive implementation of edit-distance finder, I have to 
check whether the last characters of two strings match:


ulong editDistance(const string a, const string b) {
if (a.length == 0)
return b.length;
if (b.length == 0)
return a.length;

const auto delt = a[$ - 1] == b[$ - 1] ? 0 : 1;

import std.algorithm : min;

return min(
editDistance(a[0 .. $ - 1], b[0 .. $ - 1]) + delt,
editDistance(a, b[0 .. $ - 1]) + 1,
editDistance(a[0 .. $ - 1], b) + 1
);
}

This yields the expected results but if I replace delt with its 
definition it always returns 1 on non-empty strings:


ulong editDistance(const string a, const string b) {
if (a.length == 0)
return b.length;
if (b.length == 0)
return a.length;

//const auto delt = a[$ - 1] == b[$ - 1] ? 0 : 1;

import std.algorithm : min;

return min(
editDistance(a[0 .. $ - 1], b[0 .. $ - 1]) + a[$ - 1] 
== b[$ - 1] ? 0 : 1, //delt,

editDistance(a, b[0 .. $ - 1]) + 1,
editDistance(a[0 .. $ - 1], b) + 1
);
}

Why does this result change?


Wrap the ternary condition into parenthesis.

editDistance(a[0 .. $ - 1], b[0 .. $ - 1]) + (a[$ - 1]

== b[$ - 1] ? 0 : 1)




Re: Is is a Bug or just me?

2020-05-09 Thread bauss via Digitalmars-d-learn

On Friday, 8 May 2020 at 14:16:10 UTC, foerdi wrote:

Hi d community,

I got a strange behavior since dmd 2.090 (dmd 2.089 is the last 
working version).


See this reduced code: https://run.dlang.io/is/yoyHXC

I would expect that foo() returns 2.
My guess in foo is: The return value of val is saved locally as 
a ref int and then the destructor of S is called (set the local 
cache to 0). Now the ref value is dereferenced and returned.


Now I am unsure if this is a bug or an undefined behavior that 
I don't know.
If this is a bug, then I don't know how to call it for the bug 
tracker.


I hope you can help me with this problem.

PS: This is only tested on my Linux system and on run.dlang.io.

- foerdi


Gets even weirder because this fixes it LOL???

int foo()
out { }
do
{
return bar.val;
}

What the??


Re: Get months / years between two dates.

2020-05-09 Thread bauss via Digitalmars-d-learn

On Thursday, 7 May 2020 at 11:40:36 UTC, WebFreak001 wrote:

On Wednesday, 6 May 2020 at 19:51:01 UTC, bauss wrote:

How do you exactly do that?

Like if I have two dates as std.datetime.DateTime

How will I get the months or years between the two dates?

I was surprised to learn that Duration does not support them 
and only has weeks, days etc. but not months or years.


I can't seem to find any standard way of doing it.

Will I have to calculate that myself or? I feel like that's a 
big thing missing if it's not there already.


My use-case is simple. I need to calculate years/months since 
a specific date has happened.


A month doesn't have a specific amount days/weeks so "what is a 
month" cannot be answered from just the duration alone. You can 
use SysTime.diffMonths or DateTime.diffMonths to calculate the 
number of months between two dates. Years are always 12 months 
so you don't have to worry there and can just divide by 12


If you also want days or weeks, you will need to calculate that 
yourself afterwards


Yah if you saw my second reply that's what I said I found.

It did exactly what I needed it for.

What I was hoping for originally was that the duration had some 
"date" knowledge but that was just me being optimistic but as 
diffMonths solves the problem then there is no issue.


Re: Get months / years between two dates.

2020-05-06 Thread bauss via Digitalmars-d-learn

On Wednesday, 6 May 2020 at 19:58:59 UTC, Adam D. Ruppe wrote:

On Wednesday, 6 May 2020 at 19:51:01 UTC, bauss wrote:

How will I get the months or years between the two dates?


What's the length of a month or a year? That's the tricky part 
- they have variable lengths. So a difference of one month is 
not super precise.


You could probably just do days / 365 or days / 30 to get a 
reasonable approximation but that's why the library doesn't 
give you an easy pre-made answer.


I actually found something. I can't rely on "approximation" 
unfortunately.


DateTime apparently has a "diffMonths" function that can be used.


Get months / years between two dates.

2020-05-06 Thread bauss via Digitalmars-d-learn

How do you exactly do that?

Like if I have two dates as std.datetime.DateTime

How will I get the months or years between the two dates?

I was surprised to learn that Duration does not support them and 
only has weeks, days etc. but not months or years.


I can't seem to find any standard way of doing it.

Will I have to calculate that myself or? I feel like that's a big 
thing missing if it's not there already.


My use-case is simple. I need to calculate years/months since a 
specific date has happened.


Re: .get refuses to work on associative array

2020-04-15 Thread bauss via Digitalmars-d-learn

On Wednesday, 15 April 2020 at 22:09:32 UTC, H. S. Teoh wrote:
On Wed, Apr 15, 2020 at 09:46:58PM +, p.shkadzko via 
Digitalmars-d-learn wrote:
I am quite confused by the following exception during dub 
build:


> dub build --single demo.d --compiler=ldc2 --force
Performing "debug" build using ldc2 for x86_64.
demo ~master: building configuration "application"...
demo.d(221,20): Error: template object.get cannot deduce 
function from
argument types !()(double[string], string, string), candidates 
are:

C:\ldc2-1.20.0-windows-x64\bin\..\import\object.d(2645,10):
get(K,
V)(inout(V[K]) aa, K key, lazy inout(V) defaultValue)
C:\ldc2-1.20.0-windows-x64\bin\..\import\object.d(2652,10):
get(K,
V)(inout(V[K])* aa, K key, lazy inout(V) defaultValue)

The code that causes it:

"""
void main(string[] args) {

double[string] scores = calculateScores("test.txt");
double score = scores.get("hello", 0.0); // <-- exception
}
"""

It works if I just do "double score = scores["hello"];"
Both dmd and ldc2 throw this exception.
Is it a bug?


Are you sure the error is on the line you indicated? The error 
message
claims that your argument types are (double[string], string, 
string),

but your code clearly has argument types (double[sting], string,
double).  Are you sure dub is compiling the source file(s) you 
think

it's compiling?  Which source file(s) are shown by `dub -v`?


T


It also says line 221. In which case he should be able to track 
it down to line 221 and see where the error is.


Re: Swedish letters fuck up parsing into SQL querry

2020-03-23 Thread bauss via Digitalmars-d-learn

On Monday, 23 March 2020 at 14:26:46 UTC, Anders S wrote:

On Monday, 23 March 2020 at 13:53:50 UTC, Adam D. Ruppe wrote:
My first thought is to!string(cellTab[CellIndex].name) is 
wrong, if it is a char[20] you should be scanning it to find 
the length and slicing. Maybe [0 .. name.indexOf("\0")] or 
whatever.


You also shouldn't be building a query by concatenation.


Hi, thks

do you mean I should loop through each pos till 
strlen(cellTab[CellIndex].name) to find "\0"?


How do you suggest I do the querry build then?


This is open to sql injection.

I thought we were rid of this in this day and age.

Use prepared statements.




Re: Best way to learn 2d games with D?

2020-03-17 Thread bauss via Digitalmars-d-learn

On Tuesday, 17 March 2020 at 23:09:32 UTC, Dennis wrote:
On Tuesday, 17 March 2020 at 22:47:43 UTC, Sebastiaan Koppe 
wrote:
Dont trust that marketing, there is actually decent scripting 
in gamemaker, which you'll need if you get creative.


Second that. GameMaker is how I got into programming at age 12, 
and look where I ended up ;)


Similar for me but not GameMaker but RPG Maker.


Re: Best way to learn 2d games with D?

2020-03-15 Thread bauss via Digitalmars-d-learn

On Monday, 16 March 2020 at 02:52:56 UTC, Mike Parker wrote:

On Sunday, 15 March 2020 at 18:14:44 UTC, bauss wrote:



I would recommend using Derelict and SDL with D since it's the 
most mature.




Please don't recommend Derelict to anyone :-) bindbc-sdl is 
what folks should be using now. I'm not maintaining Derelict 
anymore.


Haven't even heard of that!

Does it work in similar fashion?


Re: Best way to learn 2d games with D?

2020-03-15 Thread bauss via Digitalmars-d-learn
On Sunday, 15 March 2020 at 17:58:58 UTC, Steven Schveighoffer 
wrote:
I want to try and learn how to write 2d games. I'd prefer to do 
it with D.


I've found a ton of tutorials on learning 2d gaming with other 
languages. Is there a place to look that uses D for learning? 
Should I just start with another language and then migrate to D 
later? Anyone recommend any specific tutorial/book?


-Steve


The theory is the same in any language ex. if you can write a 2d 
game in C++ chances are you can do it in D as well but you could 
probably apply the same theory to C, Java, Python etc.


So for D what you really need to be familiar with, is just the 
library you're using.


The theory for a 2d game is rather simple though.

You have a loop on the main thread (or ui thread) and within that 
you handle events, clear the screen, draw the graphics and repeat 
pretty much.


I would recommend using Derelict and SDL with D since it's the 
most mature.


There's DSFML but it's dead and doesn't support the latest 
version of SFML.


You could also try SFML through Derelict but SDL just seems more 
stable tbh.


TBH. if you have any experience with GUI engines then applying 
that to writing a game is pretty much the same.


A player, monster, NPC etc. is just a sprite (which is pretty 
much just an image.) it has a size, position etc. and you just 
manipulate that based on the events you receive in your main loop 
etc.


I don't think there's currently any good or complete tutorials on 
game development in D, much less 2d game development. There's a 
lot of "dead" libraries etc.


If you can get a SDL application running and at the very least 
showing a window then I won't mind helping you in the right 
direction.


It should be trivial using the guides available at the derelict 
docs.





Re: D create many thread

2020-02-06 Thread bauss via Digitalmars-d-learn

On Thursday, 6 February 2020 at 22:00:26 UTC, tchaloupka wrote:
On Wednesday, 5 February 2020 at 13:05:59 UTC, Eko Wahyudin 
wrote:

Hi all,

I'm create a small (hallo world) application, with DMD.
But my program create 7 annoying threads when create an empty 
class.




If you don't want the parallel sweep enabled for your app, you 
can turn it of ie with:


```
extern(C) __gshared string[] rt_options = [ "gcopt=parallel:0" 
];

```

Or in various other ways as described in mentioned 
documentation: https://dlang.org/spec/garbage.html#gc_config


Why are we doing it like that? That's the least user-friendly 
method of configuring the GC I have ever seen.


Re: How do I fix my failed PRs?

2020-02-02 Thread bauss via Digitalmars-d-learn
On Sunday, 2 February 2020 at 12:49:31 UTC, MoonlightSentinel 
wrote:

On Sunday, 2 February 2020 at 08:54:02 UTC, mark wrote:
However, four have not been accepted, apparently for technical 
reasons. But I don't understand what's wrong or what I need to 
do to fix them. (I'm not very knowledgeable about github.)


The Travis log suggest that your PRs contain some whitespace 
errors:


The command "grep -nr --include \*.md '\s$' . ; test $? -eq 1" 
exited with 1


You could try to execute the ggrep command locally to identify 
lines containing possible errors.


PS: Feel free to comment on your PR directly s.t. 
reviewers/bypassers can see that you could use some assistance.


Since he just edited markdown files then it shouldn't matter.


Re: How do I fix my failed PRs?

2020-02-02 Thread bauss via Digitalmars-d-learn

On Sunday, 2 February 2020 at 08:54:02 UTC, mark wrote:
I've done quite a few small corrections/improvements to the 
D-tour's English. Almost all have been accepted.


However, four have not been accepted, apparently for technical 
reasons. But I don't understand what's wrong or what I need to 
do to fix them. (I'm not very knowledgeable about github.)


These are the ones that are held up:

https://github.com/dlang-tour/english/pull/336
https://github.com/dlang-tour/english/pull/335
https://github.com/dlang-tour/english/pull/328
https://github.com/dlang-tour/english/pull/316


I would create an issue there


Re: Constant GC allocations when sending large messages to threads?

2020-01-31 Thread bauss via Digitalmars-d-learn

On Friday, 31 January 2020 at 07:14:30 UTC, cc wrote:
On Wednesday, 29 January 2020 at 21:10:53 UTC, Steven 
Schveighoffer wrote:
I'm pretty sure std.concurrency uses Variant to pass message 
data, which boxes when it gets over a certain size. You are 
probably crossing that threshold.


The allocations should level out eventually when the GC starts 
collecting them.


-Steve


Is there a way to pre-allocate a buffer or something to be 
used?  Ideally I'd like to avoid too many garbage collections 
happening, in my application these thread messages happen 
almost every frame and are quickly adding up to 100s of 
kilobytes in allocations every few seconds.


You can just allocate non-GC memory.


Re: format with floating points GC allocating in DMD 2.090

2020-01-31 Thread bauss via Digitalmars-d-learn

On Friday, 31 January 2020 at 07:20:17 UTC, cc wrote:

char[4096] buf;
writeln(GC.stats.usedSize);
foreach (i; 0 .. 10) {
sformat(buf, "%f", 1.234f);
writeln(GC.stats.usedSize);
}

Output with DMD32 D Compiler v2.089.1-dirty (Win10 x64):
16
16
16
...

Output with DMD32 D Compiler v2.090.0-dirty:
16
848
1664
2480
3296
4112
4944
5760
6576
7392
8208


Report it as a bug because it's definitely a bug and there was 
changes to the GC in 2.090.0


Re: How change window Backgound Color when press a Button when using "ResEdit Resource Editor" to design?

2020-01-29 Thread bauss via Digitalmars-d-learn

On Thursday, 30 January 2020 at 03:49:29 UTC, Marcone wrote:
I created a GUI using "ResEdit Resource Editor" and embeded to 
Dlang using this code above. Now I want to change the window 
Backgound Color when press a Button. How can I make it?





You need to handle WM_ERASEBKGND

And then you can set it using CreateSolidBrush and 
SetClassLongPtr with GCLP_HBRBACKGROUND


Re: Blog Post #0096: Hardware III - Keyboard and Mouse

2019-12-31 Thread bauss via Digitalmars-d-learn

On Tuesday, 31 December 2019 at 09:27:44 UTC, Ron Tarrant wrote:
This week's post wraps up the year by looking at how to access 
keyboard and mouse events through the hardware Seat. You'll 
find it here: 
https://gtkdcoding.com/2019/12/31/0096-hardware-iii-keyboard-pointer.html


Have a happy New Year, everybody. May 2020 put things into 
perspective for us all.


Happy new year and thank you for your gtkd blogs :)


Re: D vs Java which is more powerful

2019-11-16 Thread bauss via Digitalmars-d-learn
On Saturday, 16 November 2019 at 07:24:50 UTC, GreatSam4sure 
wrote:
According to this [1] a person that java is much more powerful 
than D. I am really surprised at this claim. Is this true? 
Because I believe D much more powerful than Java.



I will really appreciate detail analysis



1.https://forum.dlang.org/thread/lnrhskowvyighdnzb...@forum.dlang.org


Java as a language in itself is not more powerful than D 
regardless of opinions.


D as a language on its own is probably the most powerful language 
because of the way templates and metaprogramming works, CTFE etc. 
there's just no equivalent really. The closest to a competitor 
language-wise is Nim.


However that being said 

Java excels far more than D in its framework, available packages 
and library ports but that's because Java is more popular and has 
been one of the most popular languages far longer than D has. D 
is not even popular compared to Java.


D cannot and probably won't ever match the ecosystem of Java but 
that doesn't mean Java is the better choice. It all comes down to 
use-cases.


You can't really say any language is better than another because 
each language has pros and cons. They're all tools and should be 
used respectively.


Ex. you can see Java as a hammer and D is a screwdriver.

A lot of people fail to realize that each language is a tool and 
not a toolbox.


Re: Is there any writeln like functions without GC?

2019-11-11 Thread bauss via Digitalmars-d-learn
On Saturday, 9 November 2019 at 22:03:03 UTC, Ferhat Kurtulmuş 
wrote:

On Thursday, 31 October 2019 at 03:56:56 UTC, lili wrote:

Hi:
   why writeln need GC?


Upon this post, I thought writing a gc-free writeln would be a 
good learning practice. Although it is not a feature-complete 
one, it was a lot of fun to do it :)


https://github.com/aferust/stringnogc


If you wanted to follow the standard of D then you didn't need a 
string type. Since it doesn't really exist in D.


string is just an alias for immutable(char)[]

So what you want is to use this:
https://dlang.org/phobos/std_container_array.html


Re: Blog Post #0062: Cairo Load & Display Images

2019-08-17 Thread bauss via Digitalmars-d-learn

On Saturday, 17 August 2019 at 19:22:54 UTC, Ron Tarrant wrote:

On Friday, 16 August 2019 at 12:44:15 UTC, bauss wrote:

Amazing! You might be able to answer me something, whether you 
could use gtkd solely for image manipulation using ex. Pixbuf? 
or would it only work with the internals of gtkd? Like can you 
manipulate the image and save it to disk etc.


Those are very good questions, bauss. I haven't dug in that 
deep yet, but I see no reason why Cairo couldn't be used to 
build a full-featured paint, manipulation, or structured 
drawing application. But it won't only be about Pixbufs. The 
Cairo Context seems to be where all the action is as far as 
drawing routines go.


Over the next few months, off and on, I'll be exploring stuff 
like that. I'm still working on getting through all the unsexy 
stuff first (the basic widgets) but every once in a while, I 
just have to let my hair down and do something that's a bit 
more complex.


After the basic image and drawing stuff is covered, I'll be 
digging into simple animation and how to tame the Timeout. 
Then, after a short side-trip to finish off MVC and do some 
more base-level widgets such as the Toolbar, Statusbar, and 
Expander, there's another Cairo miniseries coming up that 
covers nodes and noodles, something I've wanted to dig into for 
several years.


Thanks for reading and thanks for the kind words.


Thank you for the answer.

I'll take a look at it myself sometime in the near future and see 
what I can come up with and if I can figure it out :)


Also thank you for these blog posts. I enjoy reading them, also 
the MVC ones.


Re: Blog Post #0062: Cairo Load & Display Images

2019-08-16 Thread bauss via Digitalmars-d-learn

On Friday, 16 August 2019 at 11:42:01 UTC, Ron Tarrant wrote:
Continuing on with Cairo, this post covers loading and 
displaying three types of image (including a structured 
drawing) using two different load-n-display methods.


As an extra bonus, you'll see a photo of my cat, Bob, and three 
of the seven guitars I've found in my building's recycle room 
over the last year.


https://gtkdcoding.com/2019/08/16/0062-cairo-vi-load-display-images.html


Amazing! You might be able to answer me something, whether you 
could use gtkd solely for image manipulation using ex. Pixbuf? or 
would it only work with the internals of gtkd? Like can you 
manipulate the image and save it to disk etc.




Re: Cannot take the .keys of shared AA. Is this a regression in 2.087 or a feature?

2019-08-15 Thread bauss via Digitalmars-d-learn
On Thursday, 15 August 2019 at 19:51:30 UTC, Jonathan M Davis 
wrote:
n Thursday, August 15, 2019 11:33:06 AM MDT Piotr Mitana via 
Digitalmars-d- learn wrote:

Code:

import std;

shared(string[string]) dict;

void main()
{
 dict.keys;
}

Error:

/dlang/dmd/linux/bin64/../../src/druntime/import/object.d(3417):
Error: cannot implicitly convert expression aa of type
shared(string[string]) to const(shared(string)[string])
onlineapp.d(7): Error: template instance
`object.keys!(shared(string[string]), shared(string), string)`
error instantiating

Before D 2.087 it compiled - is this a regression?


Not being able to implicitly convert to const is a bit odd, but 
arguably, nothing should ever be called on a shared AA anyway. 
If an operation isn't thread-safe, then it shouldn't work with 
shared. To use a shared object safely, you have to protect 
access to it with a mutex or some other synchronization 
mechanism, after which you would normally cast away shared to 
operate on the object as thread-local while the lock is in 
place and then release the lock when you're done (also making 
sure that no thread-local references exist when the lock is 
released). Because keys is not at all thread-safe, I'd strongly 
argue that it should not work on a shared AA, and if it does, 
that's a bug.


- Jonathan M Davis


D really needs some official thread-safe implementations of 
containers, hashmaps etc.


Re: Speed of Random Numbers

2019-08-03 Thread bauss via Digitalmars-d-learn
On Saturday, 3 August 2019 at 17:47:46 UTC, Giovanni Di Maria 
wrote:
On Saturday, 3 August 2019 at 17:44:44 UTC, lithium iodate 
wrote:
On Saturday, 3 August 2019 at 16:35:34 UTC, Giovanni Di Maria 
wrote:

[...]


First off you could try to use a faster RNG engine than the 
default. The easiest way is to define a variable containing it 
and passing it to the functions each time.


auto rng = Xorshift(1234);
randomNumber = uniform!uint(rng);

This basic change approximately halved the 5 seconds your 
original example needs on my computer.
Another simple approach that I have tried is simply hashing 
the iterator using a fast hash function.
With xxHash32 I got the time down to 0.25 seconds. I also 
tried xxHash64 and FNV1a but they were not faster in my quick 
test.




Thank you very much Lithium Iodate
Now i will try it.
I let know you.
Thank you
Giovanni


If it doesn't matter if it's predictable or not then you could 
easily make your own simple random generator with would give 
"random" results.


Of course in general it's not usable:

import std.stdio;

class Random
{
private:
uint _seed;
uint _interval;

T abs(T)(T x)
{
T y = x > 0 ? T.max : cast(T)0;

return (x ^ y) - y;
}

public:
this()
{
import core.stdc.time;

_seed = cast(uint)time(null);
_interval = (_seed - 20559);
}

T next(T)(T max)
{
auto value = cast(T)(abs(_interval) % T.max);

_interval -= (_interval / 10) * _seed;

return value;
}
}

void main()
{
auto random = new Random;

foreach (_; 0 .. 1000)
{
auto result = random.next!ubyte(255);
writeln(result);
}
}




Re: Is there a way to adjust lookup paths for modules during compilation?

2019-07-31 Thread bauss via Digitalmars-d-learn

On Wednesday, 31 July 2019 at 17:29:58 UTC, Andrey Zherikov wrote:
I want my program to add some directories into module lookup 
process (like adding -I dmd options). List of directories is 
known at compile time but the choice of what exact directories 
to add depends on `-version` parameter.

Is there a way to achieve this in code?

I can actually do this by creating scripts like 
'build-version1', 'build-version2' but I'm looking for a way to 
avoid this.


Your best bet is actually not relying on CTFE since IO is very 
restricted at CTFE in D.


Ex. you can only import files that are specified by you.

The best thing you can do is have a file that lists every file 
you need to be able to read at CTFE.


Re: vibe / self contained standalone executable?

2019-07-28 Thread bauss via Digitalmars-d-learn

On Sunday, 28 July 2019 at 18:54:37 UTC, Sebastiaan Koppe wrote:

On Sunday, 28 July 2019 at 14:42:48 UTC, Robert M. Münch wrote:

On 2019-07-28 14:14:06 +, Sebastiaan Koppe said:

I am using 
https://dlang.org/spec/expression.html#import_expressions for 
text files. Don't know if it works on binary files as well.


And this works than good together with the vibe framework? So, 
it's not requiring or forcing one to use files or databases?


Haven't tested it, but something like this:

---
import vibe.core.core : runApplication;
import vibe.http.server;

void handleRequest(scope HTTPServerRequest req, scope 
HTTPServerResponse res)

{
if (req.path == "/file.txt")
res.writeBody(import("file.txt"), "text/plain");
}

void main()
{
auto settings = new HTTPServerSettings;
settings.port = 8080;
settings.bindAddresses = ["::1", "127.0.0.1"];

auto l = listenHTTP(settings, );
scope (exit) l.stopListening();

runApplication();
}
---

Of course you may want to use the router or the rest generator 
for this. See the examples in the repo.


Doing it like that is kinda pointless though because you can just 
serve static files.


http://vibed.org/api/vibe.http.fileserver/serveStaticFiles


Re: vibe / self contained standalone executable?

2019-07-28 Thread bauss via Digitalmars-d-learn

On Sunday, 28 July 2019 at 14:14:06 UTC, Sebastiaan Koppe wrote:

On Sunday, 28 July 2019 at 13:45:50 UTC, Robert M. Münch wrote:
Is it possible to pack a complete "web-app" (serving web-pages 
and providing REST API) into a single executable so that no 
other files need to be accessed and everything is servered 
from something like a "virtual filesystem" which is in memory 
only?


I am using 
https://dlang.org/spec/expression.html#import_expressions for 
text files. Don't know if it works on binary files as well.


It works on anything since it just loads in the data (as text I 
think?) from the file. But you can just convert it to a buffer 
etc.


Re: Is betterC affect to compile time?

2019-07-25 Thread bauss via Digitalmars-d-learn

On Thursday, 25 July 2019 at 18:06:02 UTC, Jonathan Marler wrote:

On Thursday, 25 July 2019 at 12:46:48 UTC, Oleg B wrote:
On Thursday, 25 July 2019 at 12:34:15 UTC, rikki cattermole 
wrote:

Those restrictions don't stop at runtime.


It's vary sad.

What reason for such restrictions? It's fundamental idea or 
temporary implementation?


Yes it is very sad.  It's an implementation thing.  I can guess 
as to a couple reasons why it doesn't work, but I think there's 
a few big ones that contribute to not being able to use certain 
features at compile-time without having it introduce things at 
runtime.


Anything you do at compile-time should never produce anything at 
runtime UNLESS it's a field created or something created using 
mixin.


D's betterC is pretty useless if you can't use D to its fullest 
at compile-time regardless of whether you're compiling with 
betterC or not.


It takes the one thing away from D that it does better than other 
languages, which is CTFE and metaprogramming.


Re: Mixin mangled name

2019-07-02 Thread bauss via Digitalmars-d-learn

On Monday, 1 July 2019 at 23:52:49 UTC, Andrey wrote:

Hello,
Is it possible to mixin in code a mangled name of some entity 
so that compiler didn't emit undefined symbol error? For 
example mangled function name or template parameter?


Perhaps: https://dlang.org/spec/pragma.html#mangle


Re: dll

2019-06-27 Thread bauss via Digitalmars-d-learn

On Thursday, 27 June 2019 at 16:56:00 UTC, fred wrote:

https://forum.dlang.org/thread/osnema$d5s$1...@digitalmars.com

dll support is it ok now?
i cant find the docs on thatm


Not much better.


Re: Create empty SList or DList.

2019-06-26 Thread bauss via Digitalmars-d-learn

On Wednesday, 26 June 2019 at 19:06:24 UTC, drug wrote:

26.06.2019 20:39, bauss пишет:

auto stack = SList!int(0);
stack.removeFront();

Then something that just allowed you to do:
auto stack = SList!int;


this compiles:
```
auto stack = SList!int();
```


Maybe something else triggered it for me but I kept getting an 
error message like "not initialized with a value" or something 
like that .


I can't reproduce it right now though.


Create empty SList or DList.

2019-06-26 Thread bauss via Digitalmars-d-learn
Is there a way to achieve that instead of something hacky like 
adding an initialized element and then removing it.


Ex. instead of:

auto stack = SList!int(0);
stack.removeFront();

Then something that just allowed you to do:
auto stack = SList!int; // Not allowed.

---

I feel like this makes containers like that a big hassle in D 
because you may not wanna initialize the elements of them right 
away.


Re: bug in compiles?

2019-04-11 Thread bauss via Digitalmars-d-learn

On Thursday, 11 April 2019 at 18:13:48 UTC, Alex wrote:

The following code works when I comment out the static if

//static if (__traits(compiles, __traits(getAttributes, T)))
   static foreach(a;  __traits(getAttributes, T)) Attributes ~=


There seems to be absolutely no reason why this code would fail 
with the static if but pass without it but in the first case I 
get no attributes because the __traits compiles fails.




__traits(compiles, __traits(getAttributes, T))

vs

__traits(getAttributes, T)

How could it not compile in the first case and yet work in the 
foreach?


T is a local variable name passed to this code, which does 
generally return an

error when used in certain ways:


int x;

Code!x; // Basically the code at the top

if I try to do too much with x I get `cannot use local `x` as a 
parameter to a non-global template`. Usually when I try to pass 
T to another template I get this error.



But some things work. But I can't for the life of me understand 
why compiles is failing but the foreach loop is working.



The problem is that I am using compiles quite often and either 
I'm misusing it or it's got some bugs in it that worry me 
because maybe they are silently failing?


Note that I get no errors in my code and I do get the 
attributes so it is technically working.


It would be really nice to know why the compiles is failing, 
e.g.,


pragma(compilesmsg, __traits(getAttributes, T)) spits out the 
error.


Must be something else in your code because it works fine for me 
with this shortened example.


https://run.dlang.io/is/o8xESB


Re: Iterate/sort associative array by value?

2019-04-07 Thread bauss via Digitalmars-d-learn

On Sunday, 7 April 2019 at 16:44:01 UTC, Robert M. Münch wrote:

On 2019-04-07 16:24:52 +, Cym13 said:

You could use sort to gather the indexes in order then 
traverse from there:


 aa.byKey.array.sort!((a, b) => aa[a]

That doesn't work: Error: no property array for type Result


With a wrapper caching that order and making it transparent as 
well as update on insertion (which should be in log(n) since 
you know have an ordered list of indexes, you can use 
dichotomy to update the indexes without walking all your AA 
again) I think you could have a nice little container. However 
if double entry is necessary maybe a simpler 2D array would be 
easier to work with?


At the point where I need this sorted array, nothing will 
change it. It's a log output. So, not necessary to make things 
more complex.


Import std.array


  1   2   3   4   5   >