Re: The difference between the dates in years

2024-02-10 Thread Alexander Zhirov via Digitalmars-d-learn
On Saturday, 10 February 2024 at 18:12:07 UTC, Alexander Zhirov 
wrote:

On Saturday, 10 February 2024 at 16:03:32 UTC, H. S. Teoh wrote:
On Sat, Feb 10, 2024 at 03:53:09PM +, Alexander Zhirov via 
Digitalmars-d-learn wrote:
Is it possible to calculate the difference between dates in 
years using regular means? Something like that



```
writeln(Date(1999, 3, 1).diffMonths(Date(1999, 1, 1)));
```

At the same time, keep in mind that the month and day matter, 
because the difference between the year, taking into account 
the month that has not come, will be less.


My abilities are not yet enough to figure it out more 
elegantly.


IIRC you can just subtract two DateTime's to get a Duration 
that you can then convert into whatever units you want.  Only 
thing is, in this case conversion to months may not work 
because months don't have a fixed duration (they can vary from 
28 days to 31 days) so there is no "correct" way of computing 
it, you need to program it yourself according to the exact 
calculation you want.



T


I did it this way, but there will be an inaccuracy, since 
somewhere there may be 366 days, and somewhere 365


```
auto d = cast(Date)Clock.currTime() - 
Date.fromISOExtString("2001-02-01");

writeln(d.total!"days"().to!int / 365);
```


```
int getDiffYears(string date) {
auto currentDate = cast(Date)Clock.currTime();
auto startDate = Date.fromISOExtString(date);
auto currentDay = currentDate.dayOfYear;
auto startDay = startDate.dayOfYear;
auto currentMonth = currentDate.month;
auto startMonth = startDate.month;
auto diffDays = currentDate - startDate;
auto diffYears = diffDays.total!"days"().to!int / 365;

	return currentMonth >= startMonth && currentDay >= startDay ? 
diffYears : diffYears - 1;

}
```


Re: The difference between the dates in years

2024-02-10 Thread Alexander Zhirov via Digitalmars-d-learn

On Saturday, 10 February 2024 at 16:03:32 UTC, H. S. Teoh wrote:
On Sat, Feb 10, 2024 at 03:53:09PM +, Alexander Zhirov via 
Digitalmars-d-learn wrote:
Is it possible to calculate the difference between dates in 
years using regular means? Something like that



```
writeln(Date(1999, 3, 1).diffMonths(Date(1999, 1, 1)));
```

At the same time, keep in mind that the month and day matter, 
because the difference between the year, taking into account 
the month that has not come, will be less.


My abilities are not yet enough to figure it out more 
elegantly.


IIRC you can just subtract two DateTime's to get a Duration 
that you can then convert into whatever units you want.  Only 
thing is, in this case conversion to months may not work 
because months don't have a fixed duration (they can vary from 
28 days to 31 days) so there is no "correct" way of computing 
it, you need to program it yourself according to the exact 
calculation you want.



T


I did it this way, but there will be an inaccuracy, since 
somewhere there may be 366 days, and somewhere 365


```
auto d = cast(Date)Clock.currTime() - 
Date.fromISOExtString("2001-02-01");

writeln(d.total!"days"().to!int / 365);
```


The difference between the dates in years

2024-02-10 Thread Alexander Zhirov via Digitalmars-d-learn
Is it possible to calculate the difference between dates in years 
using regular means? Something like that



```
writeln(Date(1999, 3, 1).diffMonths(Date(1999, 1, 1)));
```

At the same time, keep in mind that the month and day matter, 
because the difference between the year, taking into account the 
month that has not come, will be less.


My abilities are not yet enough to figure it out more elegantly.


Re: Vibe D: Get access to files

2024-02-09 Thread Alexander Zhirov via Digitalmars-d-learn
In the files, dt specified the path to the files from the root 
`/style.css` and now, with any path from the root, files are 
loaded into the page, instead of `style.css`. My mistake.


Re: How to get the client's MAC address in Vibe

2024-02-09 Thread Alexander Zhirov via Digitalmars-d-learn

On Thursday, 8 February 2024 at 01:05:57 UTC, Mengu wrote:
On Wednesday, 7 February 2024 at 22:16:54 UTC, Alexander Zhirov 
wrote:
Is there a way to identify a client by MAC address when using 
the Vibe library?
The `NetworkAddress` 
[structure](https://vibed.org/api/vibe.core.net/NetworkAddress) does not provide such features. Or did I miss something?


That doesn't have anything to do with the server side if I am 
not mistaken as you should receive that via the browser that 
actually allows you to receive the mac address -via an 
extension- or some private API exposed by the browser.


I don't know the use case but you may be better off with 
browser fingerprinting if you'd like to have a unique way of 
identifying the visitors. Or, if it's a local network, maybe 
you can use tcpdump/libpcap.


It is at the packet level to monitor the address. Not at all what 
I would like. Thanks for the tip:)


Re: How to get the client's MAC address in Vibe

2024-02-09 Thread Alexander Zhirov via Digitalmars-d-learn
On Thursday, 8 February 2024 at 14:21:13 UTC, Steven 
Schveighoffer wrote:
On Wednesday, 7 February 2024 at 22:16:54 UTC, Alexander Zhirov 
wrote:
Is there a way to identify a client by MAC address when using 
the Vibe library?
The `NetworkAddress` 
[structure](https://vibed.org/api/vibe.core.net/NetworkAddress) does not provide such features. Or did I miss something?


Mac is a hardware address. By the time the packets get to your 
server, that info is long gone. Even if you could get it, it 
likely is the MAC address of your router, not the peer.


-Steve


You are right, information is lost at the packet level and 
nothing reaches the browser anymore. I will look for another way. 
Thanks!


How to get the client's MAC address in Vibe

2024-02-07 Thread Alexander Zhirov via Digitalmars-d-learn
Is there a way to identify a client by MAC address when using the 
Vibe library?
The `NetworkAddress` 
[structure](https://vibed.org/api/vibe.core.net/NetworkAddress) 
does not provide such features. Or did I miss something?


Re: Search for the dialog library

2023-10-15 Thread Alexander Zhirov via Digitalmars-d-learn

On Sunday, 15 October 2023 at 21:46:44 UTC, Dmitry Ponyatov wrote:
Maybe it's time to port the old warm tubby Turbo Vision into 
the glorious D lang?


https://github.com/magiblot/tvision


Since there was a conversation about the implementation of the 
wrapper, it is easier to write a wrapper for the `dialog` 
library, in fact, which is probably what I will do.


I'll share a link here a little later. If anyone wants to help, 
it will be very cool! I think this library can be useful to many 
people.


Search for the dialog library

2023-10-14 Thread Alexander Zhirov via Digitalmars-d-learn
Colleagues, tell me, please, is there any library on D for 
drawing 
[dialog](https://invisible-island.net/dialog/images/dialog.png) 
boxes using the dialog library, like in Python 
[pythondialog](https://pypi.org/project/pythondialog/)?


Re: Redirecting standard streams in Windows

2023-07-19 Thread Alexander Zhirov via Digitalmars-d-learn

On Wednesday, 19 July 2023 at 00:13:04 UTC, Adam D Ruppe wrote:

How does the cat program know what the encoding of the file is?

Try opening it in notepad or something and specifying the 
encoding. I betcha it is perfectly fine.


Strange. Everything works correctly on the command line. And the 
file redirection works and `2>&1` works. But in PowerShell it 
gives errors. Moreover, PowerShell reacts to `FILE_TYPE_PIPE`, 
and CMD reacts to `FILE_TYPE_DISK`.


Re: Redirecting standard streams in Windows

2023-07-18 Thread Alexander Zhirov via Digitalmars-d-learn

On Tuesday, 18 July 2023 at 22:09:40 UTC, Adam D Ruppe wrote:
You need to use WriteFile when it is redirected, which you can 
detect with GetFileType to see if it is a character device or 
not.


The redirection issue has been resolved. Another one has now 
emerged. Since I have unicode, I need to write 2 bytes each, 
which is exactly what happens. In this regard, incorrect output 
to the file. How to convert it otherwise? Or does it not depend 
on the output?


```d
import core.sys.windows.windows;
import std.stdio;
import std.utf;

void main() {
wstring str = "Это тестовый текст";
HANDLE h_stderr = GetStdHandle(STD_ERROR_HANDLE);
switch (GetFileType(h_stderr)) {
case FILE_TYPE_CHAR:
WriteConsoleW(h_stderr, str.ptr, 
cast(DWORD)str.length, NULL, NULL);

break;
case FILE_TYPE_PIPE:
auto utf_str = str.toUTF8;
WriteFile(h_stderr, utf_str.ptr, 
cast(DWORD)utf_str.length, NULL, NULL);

break;
default:
}
}
```

output:

```sh
PS C:\dlang\test> dmd.exe .\app.d
PS C:\dlang\test> .\app.exe
Это тестовый текст
PS C:\dlang\test> .\app.exe 2> .\stderr.txt
PS C:\dlang\test> cat .\stderr.txt
.\app.exe : ╨н╤В╨╛ ╤В╨╡╤Б╤В╨╛╨▓╤Л╨╣ ╤В╨╡╨║╤Б╤В
строка:1 знак:1
+ .\app.exe 2> .\stderr.txt
+ ~
+ CategoryInfo  : NotSpecified: (╨н╤В╨╛ 
╤В╨╡╤Б╤В╨╛╨▓╤Л╨╣ ╤В╨╡╨║╤Б╤В:String) [], RemoteException

+ FullyQualifiedErrorId : NativeCommandError


```



Re: Redirecting standard streams in Windows

2023-07-18 Thread Alexander Zhirov via Digitalmars-d-learn

On Tuesday, 18 July 2023 at 22:12:17 UTC, Alexander Zhirov wrote:

with threads


streams*


Re: Redirecting standard streams in Windows

2023-07-18 Thread Alexander Zhirov via Digitalmars-d-learn

On Tuesday, 18 July 2023 at 22:09:40 UTC, Adam D Ruppe wrote:
On Tuesday, 18 July 2023 at 21:31:54 UTC, Alexander Zhirov 
wrote:

HANDLE h_stdout = GetStdHandle(STD_OUTPUT_HANDLE);
WriteConsoleW(h_stderr, str.ptr, cast(DWORD)str.length, 
NULL, NULL);



If you checked the return value of this call, you'd find it 
fails since WriteConsole only works if the output is, in fact, 
a console.


You need to use WriteFile when it is redirected, which you can 
detect with GetFileType to see if it is a character device or 
not.


Just found 
[this](https://stackoverflow.com/questions/45805785/why-cant-i-redirect-output-from-writeconsole) on the net. Hmm... I didn't know that Windows has its own nuances in working with threads. Thanks for the tip.


Redirecting standard streams in Windows

2023-07-18 Thread Alexander Zhirov via Digitalmars-d-learn
I'm trying to redirect unicode in the windows console, but when 
redirecting, empty files are created. If i do it without 
redirects, then the text is displayed correctly in the console:


```d
import core.sys.windows.windows;
import std.stdio;

void main() {
wstring str = "Just text...";
HANDLE h_stderr = GetStdHandle(STD_ERROR_HANDLE);
HANDLE h_stdout = GetStdHandle(STD_OUTPUT_HANDLE);
WriteConsoleW(h_stderr, str.ptr, cast(DWORD)str.length, NULL, 
NULL);
WriteConsoleW(h_stdout, str.ptr, cast(DWORD)str.length, NULL, 
NULL);

}
```

```sh
.\app.exe 1> stdout.txt 2> stderr.txt
```


Re: Initializing an associative array into a variable when it is created

2023-07-16 Thread Alexander Zhirov via Digitalmars-d-learn

On Sunday, 16 July 2023 at 11:16:55 UTC, Danilo wrote:

Would a static constructor be okay? This way the static data
is not initialized at every `new` and object creation is faster.


Alternatively, i can think about your proposal. At the moment, I 
have solved my problem using the following method:


```d
@property string[][string] arr() {
return [
"one": ["abc", "def"],
"two": ["ghi", "jkl"],
"three": ["mno", "pqr"]
];
}
```

I don't know how true it will be considered. After all, the 
function creates an array every time it is called, which is not 
correct.


Re: Initializing an associative array into a variable when it is created

2023-07-16 Thread Alexander Zhirov via Digitalmars-d-learn

On Saturday, 15 July 2023 at 23:34:22 UTC, Danilo wrote:

Works fine, if you add a semicolon at the end.


I'm sorry. I didn't put the question quite correctly. Yes, this 
is how the array is initialized. I'm trying to describe it all in 
a class. I.e. I need to create a variable in the class that will 
be initialized when creating an object. I understand that it 
needs to be described in the constructor. But is there really no 
other way to immediately point a static array to a variable?





Initializing an associative array into a variable when it is created

2023-07-15 Thread Alexander Zhirov via Digitalmars-d-learn
I still don't understand how to make this entry correct. I have a 
static array that I want to use exactly as an array (the 
structure doesn't quite fit):


```d
string[][string] arr = [
"one": ["abc", "def"],
"two": ["ghi", "jkl"],
"three": ["mno", "pqr"]
]
```

There are the same number of elements everywhere (in the internal 
array).


Re: Logging logs in Windows

2023-04-18 Thread Alexander Zhirov via Digitalmars-d-learn
On Tuesday, 18 April 2023 at 12:08:35 UTC, Richard (Rikki) Andrew 
Cattermole wrote:
Sounds like a simple case of not linking against the right 
library:


https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-reporteventa

Library Advapi32.lib
DLL Advapi32.dll

Should be as simple as adding advapi32 to your libs directive.


Yes, you were right, it helped. [I will know that there is a 
footnote at the bottom with a 
description](https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-reporteventa#requirements)


Re: Logging logs in Windows

2023-04-18 Thread Alexander Zhirov via Digitalmars-d-learn
On Saturday, 4 February 2023 at 14:48:55 UTC, Richard (Rikki) 
Andrew Cattermole wrote:
I.e. here are my functions for syslog and Windows Event log (I 
won't copy it all, it won't be helpful & the file log function 
is giant compared).


```d
void syslog() {
version (Posix) {
import core.sys.posix.syslog : syslog;

syslog(prioritySyslogForLevels[level], 
unsafeTextMessageComposite.ptr);

}
}

void windowsEvents() {
version (Windows) {
import core.sys.windows.windows : 
ReportEventA, WORD, DWORD, EVENTLOG_INFORMATION_TYPE,
EVENTLOG_WARNING_TYPE, 
EVENTLOG_ERROR_TYPE;


static WORD[] WTypes = [
EVENTLOG_INFORMATION_TYPE, 
EVENTLOG_INFORMATION_TYPE, EVENTLOG_WARNING_TYPE,
EVENTLOG_ERROR_TYPE, 
EVENTLOG_ERROR_TYPE, EVENTLOG_ERROR_TYPE

];

static DWORD[] dwEventID = [0, 0, 0, 0, 0, 
0];

const(char)*[2] messages = [
ModuleLine2.ptr,

cast(char*)unsafeTextMessageComposite.ptr + 
unsafeDateTime.length + ModuleLine.length

];

ReportEventA(windowsEventHandle, 
WTypes[level], 0, dwEventID[level], cast(void*)null, 2, 0,

[0], cast(void*)null);
}
}
```

Note: you also need to setup an event source on Windows i.e.

```d
import core.sys.windows.windows : RegisterEventSourceA;
windowsEventHandle = RegisterEventSourceA(null, 
cast(char*)processName.ptr);

```

and to close it:

```d
import core.sys.windows.windows : DeregisterEventSource;
DeregisterEventSource(windowsEventHandle);
```


I tried to make a simple recording, but when compiling, he swears 
at linking.


```d
import core.sys.windows.windows;

void writeToEventLog(LPCSTR pszSrcName, LPCSTR message) {
HANDLE hEventLog = RegisterEventSourceA(NULL, pszSrcName);
ReportEventA(hEventLog, EVENTLOG_ERROR_TYPE, 0, 0, NULL, 1, 
0, , NULL);

DeregisterEventSource(hEventLog);
}

void main() {
writeToEventLog("test", "This is test message");
}
```

```ps
PS C:\sources\d-journals> dub
Starting Performing "debug" build using 
C:\D\dmd2\windows\bin64\dmd.exe for x86_64.
Building d-journals ~master: building configuration 
[application]

 Linking d-journals
lld-link: error: undefined symbol: RegisterEventSourceA

referenced by C:\sources\d-journals\source\app.d:4
  
C:\Users\alexander\AppData\Local\dub\cache\d-journals\~master\build\application-debug-windows-x86_64-dmd_v2.102.0-dirty-92393AAC9FC80DD3A486D7D072118EACA853FFECDE2EEAA8920EDA92F0620E60\d-journals.obj:(_D3app15writeToEventLogFPxaQdZv)


lld-link: error: undefined symbol: ReportEventA

referenced by C:\sources\d-journals\source\app.d:5
  
C:\Users\alexander\AppData\Local\dub\cache\d-journals\~master\build\application-debug-windows-x86_64-dmd_v2.102.0-dirty-92393AAC9FC80DD3A486D7D072118EACA853FFECDE2EEAA8920EDA92F0620E60\d-journals.obj:(_D3app15writeToEventLogFPxaQdZv)


lld-link: error: undefined symbol: DeregisterEventSource

referenced by C:\sources\d-journals\source\app.d:6
  
C:\Users\alexander\AppData\Local\dub\cache\d-journals\~master\build\application-debug-windows-x86_64-dmd_v2.102.0-dirty-92393AAC9FC80DD3A486D7D072118EACA853FFECDE2EEAA8920EDA92F0620E60\d-journals.obj:(_D3app15writeToEventLogFPxaQdZv)

Error: linker exited with status 1
Error C:\D\dmd2\windows\bin64\dmd.exe failed with exit code 1.
```

What could I have missed?


undefined reference to "main"

2023-04-05 Thread Alexander Zhirov via Digitalmars-d-learn
How to compile the example given in the book correctly? When 
compiling, an error occurs that the main function is missing. If 
I replace `shared static this()` with `void main()', then 
everything starts. What does the compilation string in `dub` and 
`dmd` look like correctly?


```d
import vibe.d;

shared static this()
{
  auto settings = new HTTPServerSettings;
  settings.port = 8080;
  settings.bindAddresses = ["::1", "127.0.0.1"];
  listenHTTP(settings, );

  logInfo("Please open http://127.0.0.1:8080/ in your browser.");
}

void hello(HTTPServerRequest req, HTTPServerResponse res)
{
  res.writeBody("Hello, World!");
}
```


Re: Convert binary to UUID from LDAP

2023-03-28 Thread Alexander Zhirov via Digitalmars-d-learn

On Tuesday, 28 March 2023 at 13:18:59 UTC, Kagamin wrote:
This guid is (int,short,short,byte[8]) in little endian byte 
order. So if you want to convert it to big endian, you'll need 
to swap bytes in those int and two shorts.

```
ubyte[] guid=...
int* g1=cast(int*)guid.ptr;
*g1=bswap(*g1);
```


Yes, therefore, my option remains more correct rather than 
directly converting to UUID, since it does not correspond to the 
value specified in LDAP. Therefore, it is necessary to do byte 
permutations.


Re: Convert binary to UUID from LDAP

2023-03-28 Thread Alexander Zhirov via Digitalmars-d-learn

On Tuesday, 28 March 2023 at 08:15:03 UTC, Alexander Zhirov wrote:

So far it has been possible to convert like this



The idea was borrowed from 
[here](https://elixirforum.com/t/using-active-directory-guid-with-ecto-uuid-field/15904).


Re: Convert binary to UUID from LDAP

2023-03-28 Thread Alexander Zhirov via Digitalmars-d-learn

On Tuesday, 28 March 2023 at 05:26:08 UTC, Alexander Zhirov wrote:
When converting to HEX, I get the string 
`121F4C264DED5E41A33F445B0A1CAE32`, in which some values are 
reversed. I found ways on the Internet to transform the 
permutation method into the desired result, but most likely it 
will be a crutch rather than the right solution to lead to the 
final result `264c1f12-ed4d-415e-a33f-445b0a1cae32`.


So far it has been possible to convert like this

```d
{
writeln(value.attributes["objectGUID"][0].toUUID);
}

UUID toUUID(const char[] objectGUID)
{
if(objectGUID.length != 16)
throw new Exception("objectGUID does not match the 
length");


auto arr = (cast(ubyte[])objectGUID).array;

auto part1 = arr[0 .. 4].reverse;
auto part2 = arr[4 .. 6].reverse;
auto part3 = arr[6 .. 8].reverse;
auto part4 = arr[8 .. 10];
auto part5 = arr[10 .. $];

string hex =
toHexString(part1) ~ '-' ~
toHexString(part2) ~ '-' ~
toHexString(part3) ~ '-' ~
toHexString(part4) ~ '-' ~
toHexString(part5);

return cast(UUID)hex;
}
```


Re: Convert binary to UUID from LDAP

2023-03-27 Thread Alexander Zhirov via Digitalmars-d-learn

On Monday, 27 March 2023 at 18:39:19 UTC, Alexander Zhirov wrote:
I mean get the UUID data type itself. Just using
[this example](https://dlang.org/phobos/std_uuid.html#.UUID) 
`cast(ubyte[16])ubyte[]` will not work, conversion error.


```d
writeln(toHexString(cast(ubyte[])value.attributes["objectGUID"][0]));
```

When converting to HEX, I get the string 
`121F4C264DED5E41A33F445B0A1CAE32`, in which some values are 
reversed. I found ways on the Internet to transform the 
permutation method into the desired result, but most likely it 
will be a crutch rather than the right solution to lead to the 
final result `264c1f12-ed4d-415e-a33f-445b0a1cae32`.




Re: Convert binary to UUID from LDAP

2023-03-27 Thread Alexander Zhirov via Digitalmars-d-learn
On Tuesday, 28 March 2023 at 00:51:43 UTC, Steven Schveighoffer 
wrote:

auto uuid = UUID(*cast(ubyte[16]*)youruuiddata.ptr);


```d
ubyte[] arr = cast(ubyte[])value.attributes["objectGUID"][0].dup;
writeln(UUID(cast(ubyte[16])arr.ptr));
```

`Error: cannot cast expression 'cast(ubyte*)arr' of type 'ubyte*' 
to 'ubyte[16]'`


No, it's not possible to transform. The array is initially 
`immutable(char[])`.




Re: Convert binary to UUID from LDAP

2023-03-27 Thread Alexander Zhirov via Digitalmars-d-learn

On Monday, 27 March 2023 at 18:33:46 UTC, novice2 wrote:

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

```
void main(){
import std.stdio: writeln;
import std.format: format;
ubyte[] a = [159, 199, 22, 163, 13, 74, 145, 73, 158, 
112, 7, 192, 12, 193, 7, 194];

string b = format("%(%.2X%)",a);
writeln(b);
}
```


Yes, the same result. I probably didn't write my post quite 
correctly. I mean get the UUID data type itself. Just using [this 
example](https://dlang.org/phobos/std_uuid.html#.UUID) 
`cast(ubyte[16])ubyte[]` will not work, conversion error.


Convert binary to UUID from LDAP

2023-03-27 Thread Alexander Zhirov via Digitalmars-d-learn
I get `objectGUID` data from LDAP as binary data. I need to 
convert `ubyte[]` data into a readable `UUID`. As far as I 
understand, it is possible to do this via `toHexString()`, but I 
have reached a dead end. Is there a way to make it more elegant, 
like [this 
technique](https://dlang.org/phobos/std_uuid.html#.UUID)?


```
ubyte[] => [159, 199, 22, 163, 13, 74, 145, 73, 158, 112, 7, 192, 
12, 193, 7, 194]

hex => 9FC716A30D4A91499E7007C00CC107C2
```


Re: Implicit type conversion depending on assignment

2023-03-24 Thread Alexander Zhirov via Digitalmars-d-learn

On Friday, 24 March 2023 at 09:46:26 UTC, Jacob Shtokolov wrote:
BTW, you can also `alias this` your struct value and then use 
`std.conv : to` for casting, if you don't need specific casting 
rules.


I don't quite understand what you mean? Could you show me an 
example?




Re: Implicit type conversion depending on assignment

2023-03-23 Thread Alexander Zhirov via Digitalmars-d-learn
On Thursday, 23 March 2023 at 14:36:11 UTC, Alexander Zhirov 
wrote:

I wanted WITHOUT explicit casting.


I also have thoughts about using 
[templates](https://dlang.org/spec/template.html#this_rtti), but 
I don't have enough experience yet how to implement it.




Re: Implicit type conversion depending on assignment

2023-03-23 Thread Alexander Zhirov via Digitalmars-d-learn

On Thursday, 23 March 2023 at 14:19:31 UTC, user1234 wrote:

omg, let's rewrite this...


I meant something like that. But you can't do that. I wanted 
WITHOUT explicit casting.


```d
struct MyVal
{
private string value;

@property auto toString(T)()
{
return value.to!T;
}

alias toString this;
}

auto a = MyVal("100");
auto b = MyVal("11.2");

int myInt   = a;
float myFloat   = b;
```




Re: Implicit type conversion depending on assignment

2023-03-23 Thread Alexander Zhirov via Digitalmars-d-learn
On Thursday, 23 March 2023 at 13:38:51 UTC, Alexander Zhirov 
wrote:
Is it possible to convert such records inside the structure to 
the assigned type?


```d
struct MyVal
{
string value;
// Here it would be possible to use an alias to this, but 
it can only be used 1 time

}

auto a = MyVal("100");
auto b = MyVal("11.2");

int MyInt = a;// Implicitly convert to target type
float myFloat = b;// Implicitly convert to target type
```


Here is an [example from the 
documentation](https://dlang.org/spec/struct.html#alias-this), 
but for "several" types, for example, with a cast check and a 
return of the default value.


Implicit type conversion depending on assignment

2023-03-23 Thread Alexander Zhirov via Digitalmars-d-learn
Is it possible to convert such records inside the structure to 
the assigned type?


```d
struct MyVal
{
string value;
// Here it would be possible to use an alias to this, but it 
can only be used 1 time

}

auto a = MyVal("100");
auto b = MyVal("11.2");

int MyInt = a;// Implicitly convert to target type
float myFloat = b;// Implicitly convert to target type
```


Re: Formatted date

2023-03-22 Thread Alexander Zhirov via Digitalmars-d-learn
On Wednesday, 22 March 2023 at 17:53:39 UTC, Steven Schveighoffer 
wrote:
D's datetime intentionally does not tackle formatting -- it's a 
huge undertaking.


There is an option on code.dlang.org: 
https://code.dlang.org/packages/datefmt


-Steve


I'll try it tomorrow, thanks!


Formatted date

2023-03-22 Thread Alexander Zhirov via Digitalmars-d-learn
Tell me, how can I use such a date conversion mechanism? I didn't 
find 
[something](https://www.php.net/manual/en/datetime.format.php) 
similar on the forum.


Convert date from received time

```
Clock.currTime().toSimpleString()
```

So that i can get a more readable look:

`2023-Mar-22 16:53:42.2507395` => `2023.03.22 16:53:42`


Re: Sort Associative Array by Key

2023-02-08 Thread Alexander Zhirov via Digitalmars-d-learn

foo.byPair
 .array
 .sort!((a, b) => a.key < b.key)
 .map!(a => a.value);


Is it possible to specify in `map` to return the result `[a.key] 
= a.value`? To make the result look like `[key:[val], key:[val]]`


Re: Comparison of multidimensional associative arrays

2023-02-08 Thread Alexander Zhirov via Digitalmars-d-learn

On Wednesday, 8 February 2023 at 19:32:22 UTC, Ali Çehreli wrote:

This should do it:
[...]


Yes, it works! I'll try it tomorrow on a large array of data. 
Thank you very much!
This turns out to be a simple loop with a comparison of the 
existence of a key (whether it is included in an array or not) 
and a comparison of an existing array as a value with another 
array by this key. I wonder if can add this to lambda? In one 
line.





Re: Comparison of multidimensional associative arrays

2023-02-08 Thread Alexander Zhirov via Digitalmars-d-learn

On Wednesday, 8 February 2023 at 18:57:00 UTC, Anonymouse wrote:
Can you explain how you determine how/if two entries are 
different?


I apologize. I have not written, in fact, what I need to get.

Array `A`

```d
[
4:["id":"4", "deleted":"f", "name":"6.2"],
3:["id":"3", "deleted":"f", "name":"5.6_hwlister"],
2:["id":"2", "deleted":"t", "name":"6.2"],
1:["id":"1", "deleted":"f", "name":"5.6"]
]
```

Array `B`

```d
[
6:["id":"6", "deleted":"f", "name":"6.2_test"],
5:["id":"5", "deleted":"f", "name":"5.6_test"],
4:["id":"4", "deleted":"f", "name":"6.2_hwlister"],
3:["id":"3", "deleted":"f", "name":"5.6_hwlister"],
2:["id":"2", "deleted":"f", "name":"6.2"],
1:["id":"1", "deleted":"f", "name":"5.6"]
]
```

Diff:

```d
[
6:["id":"6", "deleted":"f", "name":"6.2_test"],
5:["id":"5", "deleted":"f", "name":"5.6_test"],
4:["id":"4", "deleted":"f", "name":"6.2_hwlister"],
2:["id":"2", "deleted":"f", "name":"6.2"]
]
```

That is, the result is arrays of table B that are missing OR not 
equal to arrays in table A.


Re: Comparison of multidimensional associative arrays

2023-02-08 Thread Alexander Zhirov via Digitalmars-d-learn

On Wednesday, 8 February 2023 at 18:08:40 UTC, Ali Çehreli wrote:
Just because this sounds complicated, I hope the data structure 
can be designed differently to be more friendly to this 
operation. (?)


Ali


This is the result of an SQL query. Roughly speaking, I need to 
compare the result of queries from two different databases and 
find different ones. The tables are the same, the only difference 
is in the content.


Comparison of multidimensional associative arrays

2023-02-08 Thread Alexander Zhirov via Digitalmars-d-learn
Not an easy task for me, maybe you can advise your compact 
solution. There are two associative arrays of type 
`string[string][int]`. It is necessary to find the differences 
and return them when comparing:


```d
[
6:["id":"6", "deleted":"f", "name":"6.2_test"],
5:["id":"5", "deleted":"f", "name":"5.6_test"],
4:["id":"4", "deleted":"f", "name":"6.2_hwlister"],
3:["id":"3", "deleted":"f", "name":"5.6_hwlister"],
2:["id":"2", "deleted":"f", "name":"6.2"],
1:["id":"1", "deleted":"f", "name":"5.6"]
]

[
4:["id":"4", "deleted":"f", "name":"6.2_hwlister"],
3:["id":"3", "deleted":"f", "name":"5.6_hwlister"],
2:["id":"2", "deleted":"f", "name":"6.2"],
1:["id":"1", "deleted":"f", "name":"5.6"]
]
```


Re: compile: link dynamic OR static library in Windows

2023-02-06 Thread Alexander Zhirov via Digitalmars-d-learn
On Monday, 6 February 2023 at 08:23:37 UTC, Richard (Rikki) 
Andrew Cattermole wrote:

[...]


Yes, your solution works. I apologize for my inattention. I 
should have checked earlier in your way. Most likely Adam has a 
[problem](https://github.com/adamdruppe/arsd/issues/364) with 
linking in the library.





Re: compile: link dynamic OR static library in Windows

2023-02-05 Thread Alexander Zhirov via Digitalmars-d-learn
On Monday, 6 February 2023 at 06:59:09 UTC, Richard (Rikki) 
Andrew Cattermole wrote:

On other platforms the -Lfile I think would work.

On Windows you have to link against the import library not DLL 
directly.


You can pass it to the compiler:

$ dmd -i "-L/LIBPATH:C:\Program Files\PostgreSQL\15\lib" pq.lib 
app.d


Should work. Sorry, I should have revisted this from the get 
go, rather than just tinkering with what others were posting.


It doesn't work anyway...

Is it possible to collect all this from under mingw so that the 
linker is not Microsoft, but `ld'?


Re: compile: link dynamic OR static library in Windows

2023-02-05 Thread Alexander Zhirov via Digitalmars-d-learn
On Monday, 6 February 2023 at 05:45:35 UTC, Richard (Rikki) 
Andrew Cattermole wrote:

Ah doh, MSVC link doesn't use -L.

$ dmd -i "-L/LIBPATH:C:\Program Files\PostgreSQL\15\lib" -Llpq 
app.d


I think that is the option you want.

Worst case scenario just copy the files to your working 
directory and it should find it without the additional search 
path.


He doesn't want to anyway. I have already put the library in the 
source code folder. But it still pulls up the `*.obj` format for 
some reason.


```sh
C:\sources\pxe-restore\source>ls
app.d  app.obj  arsd  azh  libpq.lib  pkg

C:\sources\pxe-restore\source>dmd -i "-L/LIBPATH:C:\Program 
Files\PostgreSQL\15\lib" -Llpq app.d
LINK : fatal error LNK1181: не удается открыть входной файл 
"lpq.obj"

Error: linker exited with status 1181

C:\sources\pxe-restore\source>dmd -i 
"-L/LIBPATH:C:\sources\pxe-restore\source" -Llpq app.d
LINK : fatal error LNK1181: не удается открыть входной файл 
"lpq.obj"

Error: linker exited with status 1181
```


Re: compile: link dynamic OR static library in Windows

2023-02-05 Thread Alexander Zhirov via Digitalmars-d-learn
On Monday, 6 February 2023 at 05:20:33 UTC, Richard (Rikki) 
Andrew Cattermole wrote:

Source files go after flags.

$ dmd -i -L'-LC:\Program Files\PostgreSQL\15\lib' -Llpq app.d


For some reason, the `obj` file is link instead of the library.

```sh
C:\sources\pxe-restore\source>dmd -L'-LC:\Program\ 
Files\PostgreSQL\15\lib' -Llpq -i app.d

Error: cannot find input file `Files\PostgreSQL\15\lib'.d`
import path[0] = C:\D\dmd2\windows\bin64\..\..\src\phobos
import path[1] = C:\D\dmd2\windows\bin64\..\..\src\druntime\import

C:\sources\pxe-restore\source>dmd -L'-L"C:\Program\ 
Files\PostgreSQL\15\lib"' -Llpq -i app.d
LINK : fatal error LNK1104: не удается открыть файл 
"'-LC:\Program\ Files\PostgreSQL\15\lib'.obj"

Error: linker exited with status 1104
```


Re: compile: link dynamic OR static library in Windows

2023-02-05 Thread Alexander Zhirov via Digitalmars-d-learn

On Sunday, 5 February 2023 at 13:37:16 UTC, user1234 wrote:

try

```
dmd -i app.d -L'-LC:\Program Files\PostgreSQL\15\lib' -Llpq
```

the first linker command gives a search path, the second a 
libname.


It doesn't work

```sh
C:\sources\pxe-restore\source>dmd -i app.d -L'-LC:\Program 
Files\PostgreSQL\15\lib' -Llpq

Error: cannot find input file `Files\PostgreSQL\15\lib'.d`
import path[0] = C:\D\dmd2\windows\bin64\..\..\src\phobos
import path[1] = C:\D\dmd2\windows\bin64\..\..\src\druntime\import

C:\sources\pxe-restore\source>dmd -i app.d -L'-L"C:\Program 
Files\PostgreSQL\15\lib"'
LINK : fatal error LNK1104: не удается открыть файл 
"'-LC:\Program Files\PostgreSQL\15\lib'.obj"

Error: linker exited with status 1104

C:\sources\pxe-restore\source>dmd -i app.d -L-L'C:\Program 
Files\PostgreSQL\15\lib'

Error: cannot find input file `Files\PostgreSQL\15\lib'.d`
import path[0] = C:\D\dmd2\windows\bin64\..\..\src\phobos
import path[1] = C:\D\dmd2\windows\bin64\..\..\src\druntime\import
```


Re: compile: link dynamic OR static library in Windows

2023-02-05 Thread Alexander Zhirov via Digitalmars-d-learn
On Saturday, 4 February 2023 at 15:56:41 UTC, Richard (Rikki) 
Andrew Cattermole wrote:

On Windows you don't link directly against a DLL.

You link against a static library (.lib) of the same name.

The binding doesn't change between a static library and a 
shared library as long as you're linking during the compilation 
sequence and not during runtime.


I don't understand why the compiler doesn't see the library.

```sh
User@WIN-D3SHRBHN7F6 MINGW64 /home/user/pxe-restore/source
# ls -la "C:\Program Files\PostgreSQL\15\lib\libpq.lib"
-rw-r--r-- 1 User Отсутствует 37002 Nov  9 06:45 'C:\Program 
Files\PostgreSQL\15\lib\libpq.lib'


User@WIN-D3SHRBHN7F6 MINGW64 /home/user/pxe-restore/source
# dmd -i app.d -L'C:\Program Files\PostgreSQL\15\lib\libpq.lib'
lld-link: error: could not open 'pq.lib': no such file or 
directory

Error: linker exited with status 1
```


Re: compile: link dynamic OR static library in Windows

2023-02-04 Thread Alexander Zhirov via Digitalmars-d-learn
On Saturday, 4 February 2023 at 17:02:11 UTC, Ferhat Kurtulmuş 
wrote:
On Windows, dub's default behavior is to search for "foo.lib", 
usually compiled with Visual Studio C/C++ compilers. However, 
you have mingw-compiled "libfoo.a". I would not use 
MinGW-compiled libs with d compilers. I don't know how d 
compilers improved to support it, but in the past, I 
experienced ABI compatibility issues with d and MinGW.


I can't link to the library `*.a` and I don't understand why?

```sh
PS C:\sources\pxe-restore\source> dmd -i app.d 
C:\msys64\home\user\postgresql-15.1\installed\mingw64\lib\libpq.a

Error: unrecognized file extension a
```

Is there any way to convert the library `dll` to `lib`? Without 
using Visual Studio?


On Saturday, 4 February 2023 at 17:02:11 UTC, Ferhat Kurtulmuş 
wrote:
you will also need definitions of the functions in your d code 
like `extern(C) void fooDB();`. I am not sure how 
[importC](https://dlang.org/spec/importc.html) is usable with 
PostgreSQL. In addition, there are some bindings in the dub 
registry https://code.dlang.org/search?q=PostgreSQL.


At this stage, everything is fine. I'm using a project that I 
build on Linux without any problems. All connections are set up 
there.


compile: link dynamic OR static library in Windows

2023-02-04 Thread Alexander Zhirov via Digitalmars-d-learn
I have never programmed in Windows, so I don't quite understand 
how to link the library correctly. I have a compiled Postgres 
library from under mingw. There is both a static library `*.a` 
and a dynamic library `*.dll`. I don't understand how to compile 
my project correctly at all. I tried to do everything through dub 
first.json, then I realized that the idea was too rash and 
decided to compile a simple project through the CLI. In the end , 
here 's what happened:


```sh
PS C:\sources\pxe-restore\source> dmd -i app.d 
-LC:\msys64\home\user\postgresql-15.1\installed\mingw64\lib\libpq.dll
lld-link: error: 
C:\msys64\home\user\postgresql-15.1\installed\mingw64\lib\libpq.dll: bad file type. Did you specify a DLL instead of an import library?
lld-link: error: could not open 'pq.lib': no such file or 
directory

Error: linker exited with status 1
```

After Googling a bit, I came across [this 
page](https://wiki.dlang.org/Win32_DLLs_in_D#Using_a_D_class_from_a_DLL). Do I really need to rewrite the header of the Postgres library to use it in my project?


Do I need to list all the functions called from the library? Or 
is there a way to somehow attach it in a more civilized way 
through a simple `dmd`?


Re: Logging logs in Windows

2023-02-04 Thread Alexander Zhirov via Digitalmars-d-learn
On Saturday, 4 February 2023 at 14:48:55 UTC, Richard (Rikki) 
Andrew Cattermole wrote:

I.e. here are my functions for syslog and Windows Event log


I'll try to check. Thank you very much!



Re: Logging logs in Windows

2023-02-04 Thread Alexander Zhirov via Digitalmars-d-learn
On Friday, 3 February 2023 at 18:02:59 UTC, Richard (Rikki) 
Andrew Cattermole wrote:

Here is a starting point that I myself have used in the past:


I understand that programming under Windows is a shame for a 
programmer, but is there really no ready-made solution for using 
the system log in Windows?


Re: Logging logs in Windows

2023-02-03 Thread Alexander Zhirov via Digitalmars-d-learn
On Friday, 3 February 2023 at 16:00:55 UTC, Richard (Rikki) 
Andrew Cattermole wrote:
Yes syslog is not available on Windows as that is a Posix API. 
All of your calls to syslog should be guarded by a version for 
Posix.


Is there an analogue for Windows? And is it possible to implement 
it with the similarity of directives, as in C?


Logging logs in Windows

2023-02-03 Thread Alexander Zhirov via Digitalmars-d-learn
I wrote a small utility in Linux. I want to build it for Windows. 
He swears at some parts of the code like this:


```powershell
C:\sources\pxe-restore>dub build -b release
Starting Performing "release" build using dmd for x86_64.
Building pxe-restore ~master: building configuration 
[application]
source\azh\log.d(3,8): Error: module `core.sys.posix.syslog` 
import `syslog` not found
source\azh\query.d(7,8): Error: module `core.sys.posix.syslog` 
import `LOG_NOTICE` not found
source\azh\query.d(7,8): Error: module `core.sys.posix.syslog` 
import `LOG_ERR` not found
source\azh\query.d(7,8): Error: module `core.sys.posix.syslog` 
import `LOG_INFO` not found
source\azh\query.d(7,8): Error: module `core.sys.posix.syslog` 
import `LOG_WARNING` not found
source\app.d(12,8): Error: module `core.sys.posix.syslog` import 
`LOG_NOTICE` not found
source\app.d(12,8): Error: module `core.sys.posix.syslog` import 
`LOG_ERR` not found
source\app.d(12,8): Error: module `core.sys.posix.syslog` import 
`LOG_INFO` not found
source\app.d(12,8): Error: module `core.sys.posix.syslog` import 
`LOG_WARNING` not found

Error dmd failed with exit code 1.
```

A small fragment of the code used:

```d
...
import core.sys.posix.syslog : LOG_NOTICE, LOG_ERR, LOG_INFO, 
LOG_WARNING;

import core.sys.posix.syslog : syslog;
...
void log(int priority, string message)
{
syslog(priority, (message ~ "\0").ptr);
}
...
```


Re: Get the class name without casting the type

2022-11-15 Thread Alexander Zhirov via Digitalmars-d-learn

On Tuesday, 15 November 2022 at 14:26:22 UTC, Imperatorn wrote:
Side-note, you don't override interface members, you implement 
them.


My knowledge of D is still modest, most likely, I just didn't 
know that override with interfaces can not be used. Thanks for 
the hint!


Re: Get the class name without casting the type

2022-11-15 Thread Alexander Zhirov via Digitalmars-d-learn

On Tuesday, 15 November 2022 at 14:09:01 UTC, bauss wrote:
If you cast to Object and use classinfo.name then you get the 
expected result of B.


Thanks! 



Re: Get the class name without casting the type

2022-11-15 Thread Alexander Zhirov via Digitalmars-d-learn

On Tuesday, 15 November 2022 at 12:25:22 UTC, Hipreme wrote:

You can do it as `val.classinfo.name`


Yes, I have already done so, but the result is the same, actually 
:)


```d
app.A: It's ok!
app.A: It's ok!
app.A: It's ok!
```


Get the class name without casting the type

2022-11-15 Thread Alexander Zhirov via Digitalmars-d-learn

Is there any way to get the name of class B?

```d
interface A {
string text();
}

class B : A {
override string text() {
return ": It's ok!";
}
}

void main() {
A[] a = cast(A[]) new B[3];
B b = new B();
fill(a, b);
foreach (val ; a) {
writeln(typeof(val).stringof, val.text());
}
}
```

Output:

```sh
A: It's ok!
A: It's ok!
A: It's ok!
```


Re: Removing an element from an array

2022-11-10 Thread Alexander Zhirov via Digitalmars-d-learn
On Friday, 11 November 2022 at 05:36:37 UTC, Alexander Zhirov 
wrote:
On Friday, 11 November 2022 at 00:02:09 UTC, Alexander Zhirov 
wrote:

```d
import std.algorithm;
arr = arr.remove(arr.countUntil(fragment));
```


And will this method work?

```d
A[] arr;
A fragment = new A;
...
remove(current => current == fragment)(arr);
```


And it will be even more accurate so as not to cause an error:

```d
A[] arr;
A fragment = new A;
...
arr = remove(current => current == fragment)(arr);
```


Re: Removing an element from an array

2022-11-10 Thread Alexander Zhirov via Digitalmars-d-learn
On Friday, 11 November 2022 at 00:02:09 UTC, Alexander Zhirov 
wrote:

```d
import std.algorithm;
arr = arr.remove(arr.countUntil(fragment));
```


And will this method work?

```d
A[] arr;
A fragment = new A;
...
remove(current => current == fragment)(arr);
```


Re: Removing an element from an array

2022-11-10 Thread Alexander Zhirov via Digitalmars-d-learn

On Thursday, 10 November 2022 at 23:36:29 UTC, H. S. Teoh wrote:
On Thu, Nov 10, 2022 at 11:26:45PM +, Alexander Zhirov via 
Digitalmars-d-learn wrote:
I have an array of self-written class `A`. I'm sorry for my 
tactlessness, but I'm confused about the modules. How do I 
correctly find a specific object `fragment` inside the array 
and delete it? I don't quite understand which modules to use 
to do this optimally.


```d
A[] arr;
A fragment = new A;
...
arr.remove(fragment);  // Something like
```


I would do something like this:

// Warning: untested code
import std.algorithm;
arr = arr.remove(arr.countUntil(fragment));


T


As always - simple and compact. Thank you:)


Removing an element from an array

2022-11-10 Thread Alexander Zhirov via Digitalmars-d-learn
I have an array of self-written class `A`. I'm sorry for my 
tactlessness, but I'm confused about the modules. How do I 
correctly find a specific object `fragment` inside the array and 
delete it? I don't quite understand which modules to use to do 
this optimally.


```d
A[] arr;
A fragment = new A;
...
arr.remove(fragment);  // Something like
```

In the pros, I would do it this way, for example via lambda

```c++
arr.erase(std::find_if(arr.cbegin(), arr.cend(), [&](const 
std::reference_wrapper )

{
return () == 
}));
```


Re: Passing a string by reference

2022-11-08 Thread Alexander Zhirov via Digitalmars-d-learn

On Tuesday, 8 November 2022 at 13:05:09 UTC, Ali Çehreli wrote:
Yes. Classes are reference types in D. Class variables are 
implemented as pointers. Their default value is null.


Ali


Thanks! 


Re: Passing a string by reference

2022-11-08 Thread Alexander Zhirov via Digitalmars-d-learn

Thanks for answers!

On Tuesday, 8 November 2022 at 12:43:47 UTC, Adam D Ruppe wrote:
You should almost never use `ref string`. Just use plain 
`string`.


So it's always working with thick pointers?

nope, an object isn't created there at all. you should use `new 
C`.


If I create just `A c`, then is it an empty pointer?


Passing a string by reference

2022-11-08 Thread Alexander Zhirov via Digitalmars-d-learn
Do I understand correctly that in order for me to pass a string 
when creating an object, I must pass it by value? And if I have a 
variable containing a string, can I pass it by reference?


Should I always do constructor overloading for a type and a 
reference to it?
In the case of the variable `c`, a drop occurs. Why? An object is 
not being created on the stack?


```d
import std.stdio : writeln;

class A
{
private string str = "base";

this(ref string str)
{
writeln("type reference string");
this.str = str;
}

this(string str)
{
writeln("type string");
this.str = str;
}

this() {}

void print()
{
writeln(str);
}
}

void main()
{
auto a = new A("Hello, World!"); // this type string
a.print();
string text = "New string";
auto b = new A(text); // this type reference string
b.print();
A c;
c.print();  // segmentation fault! Why not "base"?
}

```


Re: Write binary data as a file

2022-08-02 Thread Alexander Zhirov via Digitalmars-d-learn

On Tuesday, 2 August 2022 at 15:30:13 UTC, Adam D Ruppe wrote:
On Tuesday, 2 August 2022 at 11:10:27 UTC, Alexander Zhirov 
wrote:

As a result, I get only a set of text data.


my database layer is doing to!string(that_ubyte) which is 
wrong. gonna see about pushing a fix


It's decided! After the fix, everything works! Thank you very 
much!


Write binary data as a file

2022-08-02 Thread Alexander Zhirov via Digitalmars-d-learn
I'm trying to write a mechanism for writing and reading from 
Postgres.
Using the Adama D. Ruppe library. I write data to Postgres in the 
form of this code:

```d
ubyte[] bytes = cast(ubyte[])read("myFile");
PostgresResult resultQuery = cast(PostgresResult) 
db.query("insert into amts.t_client_xrdp_settings (pid_client, 
settings_file) values (?, ?)", id, bytes);

assert(resultQuery !is null);
```
Data appears in the database. Now I'm trying to do the reverse 
process. Get data from Postgres and create a file:

```d
auto result = db.query("select tcxs.settings_file as dbfile from 
amts.t_client_xrdp_settings tcxs where tcxs.pid_client = ?", id);

ubyte[] bytes = cast(ubyte[])result.front()["dbfile"];
write("newFile", bytes);
```
As a result, I get only a set of text data.
I am sure that my mechanism lacks refinement. It remains only to 
find out which one.


Re: Build for i586

2022-07-29 Thread Alexander Zhirov via Digitalmars-d-learn

On Thursday, 28 July 2022 at 06:01:17 UTC, Alexander Zhirov wrote:
I did a topic a [little 
earlier](https://forum.dlang.org/thread/hfzsnagofrnlmynyz...@forum.dlang.org) about compiling a compiler for processor Geode LX800.
The bottom line is that I have a processor on which I want to 
compile the program, is an i586 architecture.


Yes, I did it!

I have an `i686` host with a `GCC 5.3.0` compiler. The build path 
is `/root/source`.


1. Using `GCC 5.3.0`, I built `GCC 9.5.0` in an `i686` environment
```sh
mkdir /root/source/gcc && cd /root/source/gcc
wget 
https://ftp.mpi-inf.mpg.de/mirrors/gnu/mirror/gcc.gnu.org/pub/gcc/releases/gcc-9.5.0/gcc-9.5.0.tar.gz

tar xf gcc-9.5.0.tar.gz -C source
cd source
./contrib/download_prerequisites
mkdir /root/source/gcc/build && cd /root/source/gcc/build
../source/configure --prefix=$PWD/../install --enable-shared 
--enable-threads=posix --enable-__cxa_atexit --enable-clocale=gnu 
--enable-languages=c,c++

make -j16
make install
```
2. Using `GCC 9.5.0`, I built `LLVM 10.0.1` in an `i686` 
environment

```sh
mkdir /root/source/llvm && cd /root/source/llvm
wget 
https://github.com/llvm/llvm-project/releases/download/llvmorg-10.0.1/llvm-project-10.0.1.tar.xz

tar xf llvm-project-10.0.1.tar.xz -C source
mkdir /root/source/llvm/build && cd /root/source/llvm/build
export CC=/root/source/gcc/install/bin/gcc
export CXX=/root/source/gcc/gcc-install/bin/g++
cmake ../source -DCMAKE_BUILD_TYPE=Release 
-DCMAKE_INSTALL_PREFIX=$PWD/../install 
-DLLVM_TARGETS_TO_BUILD='X86' -DCOMPILER_RT_INCLUDE_TESTS=OFF 
-DLLVM_INCLUDE_TESTS=OFF

make -j16
make install
```
3. Downloaded the `DMD 2.086.1` compiler (since this version runs 
on the `Geode LX800` processor without any problems)
4. Copied all this to an external HDD and connected it to my 
`Geode LX800 i586`
5. Using `GCC 9.5.0`, `LLVM 10.0.1` and `DMD 2.086.1`, I built 
`LDC 2.100.1` on `Geode LX800 i586`

```sh
mkdir -p ~/ldc/build && cd ~/ldc
git clone --recursive https://github.com/ldc-developers/ldc.git 
source

cd build
export PATH=:$PATH
cmake ../source -DCMAKE_BUILD_TYPE=Release 
-DCMAKE_INSTALL_PREFIX=$PWD/../install 
-DLLVM_ROOT_DIR= 
-DD_COMPILER=

make
make install
```
6. Then, through `ldc-build-runtime`, I rebuilt the libraries for 
`i586`

```sh
ldc-build-runtime --dFlags="-mcpu=i586" --cFlags="-march=i586"
```

When performing the actions, I may have connected the necessary 
paths to `LD_LIBRARY_PATH` (I don't remember ).


Now `LDC` with the flag `-mcpu=i586` compiles the binaries I need 
at the output and the architecture fully supports them!


```sh
~ # ldc2 --version
LDC - the LLVM D compiler (1.30.0-git-32f5a35):
  based on DMD v2.100.1 and LLVM 10.0.1
  built with DMD32 D Compiler v2.086.1
  Default target: i686-pc-linux-gnu
  Host CPU: geode
  http://dlang.org - http://wiki.dlang.org/LDC

  Registered Targets:
x86- 32-bit X86: Pentium-Pro and above
x86-64 - 64-bit X86: EM64T and AMD64
```

Thank you so much for your help!

**As a result, the reassembly of the `runtime` and `phobos` 
libraries helped. Would it be cool to figure out how to rebuild 
the `DMD` library for `i586`?**


Re: Build for i586

2022-07-28 Thread Alexander Zhirov via Digitalmars-d-learn

On Thursday, 28 July 2022 at 16:02:11 UTC, kdevel wrote:
On Thursday, 28 July 2022 at 15:25:00 UTC, Alexander Zhirov 
wrote:

On Thursday, 28 July 2022 at 13:16:26 UTC, kdevel wrote:
On Thursday, 28 July 2022 at 12:45:51 UTC, Alexander Zhirov 
wrote:

[...]
I have already downloaded the latest GCC sources, nothing 
compiles anyway.


How did you manage to get hold of this compiler?

```
/root/usr/program/gcc/9.5.0/install/bin/cc
```


Where does this compiler come from?


This is an unpacked archive from an official source from the GNU 
website


https://ftp.mpi-inf.mpg.de/mirrors/gnu/mirror/gcc.gnu.org/pub/gcc/releases/gcc-9.5.0/


Re: Build for i586

2022-07-28 Thread Alexander Zhirov via Digitalmars-d-learn

On Thursday, 28 July 2022 at 13:16:26 UTC, kdevel wrote:
On Thursday, 28 July 2022 at 12:45:51 UTC, Alexander Zhirov 
wrote:

[...]
I have already downloaded the latest GCC sources, nothing 
compiles anyway.


How did you manage to get hold of this compiler?

```
/root/usr/program/gcc/9.5.0/install/bin/cc
```


Everything falls on the same error.

```sh
checking for suffix of object files... configure: error: in 
`/home/thinstation/source/gcc/12.1.0/build/i586-pc-linux-gnu/libgcc':
configure: error: cannot compute suffix of object files: 
cannot compile

See `config.log' for more details


Have you looked into config.log? The errors are frequently 
located in the second half of the output.


In general, nothing happened. I've already tried everything. Here 
is the result, posted [here](https://pastebin.com/76gnneKZ).


Re: Build for i586

2022-07-28 Thread Alexander Zhirov via Digitalmars-d-learn

On Thursday, 28 July 2022 at 11:40:09 UTC, kdevel wrote:
On Thursday, 28 July 2022 at 10:39:06 UTC, Alexander Zhirov 
wrote:

[...]

I don't understand what I need to do.


You wrote

At first I thought that I needed to rebuild the GCC 
compiler for the i586
architecture. I downloaded GCC 9.5.0 and started the 
installation:


Then you wrote that this process failed. In your next post you 
quoted some code from the shell:


```
# /root/usr/program/gcc/9.5.0/install/bin/cc app.o -o app 
-L/root/usr/program/ldc/1.30/install/lib -lphobos2-ldc -ldrun
time-ldc -Wl,--gc-sections -lrt -ldl -lpthread -lm -m32 
-march=geode

# ./app
Illegal instruction
```

I read this as if you eventually succeeded in compiling your 
GCC 9.5.0. If you repeat that build but use the switch


```
--with-arch-32=pentium3
```

in the configure command your generated GCC 9.5.0 will compile 
32-Bit code for the pentium3. I mean instead of


```
# ../source/configure --prefix=$PWD/../install_i586 
--enable-shared --enable-threads=posix --enable-__cxa_atexit 
--enable-clocale=gnu --enable-languages=c,c++,d 
--target=i586-pc-linux-gnu --disable-multilib 
--with-multilib-list=m32

```

type

```
# ../source/configure --prefix=$PWD/../install_i586 
--enable-shared --enable-threads=posix --enable-__cxa_atexit 
--enable-clocale=gnu --enable-languages=c,c++,d 
--target=i586-pc-linux-gnu --disable-multilib 
--with-multilib-list=m32 --with-arch-32=pentium3

```


I have already downloaded the latest GCC sources, nothing 
compiles anyway. Everything falls on the same error.


```sh
checking for suffix of object files... configure: error: in 
`/home/thinstation/source/gcc/12.1.0/build/i586-pc-linux-gnu/libgcc':
configure: error: cannot compute suffix of object files: cannot 
compile

See `config.log' for more details
make[1]: *** [Makefile:16026: configure-target-libgcc] Error 1
make[1]: *** Waiting for unfinished jobs
```


Re: Build for i586

2022-07-28 Thread Alexander Zhirov via Digitalmars-d-learn

On Thursday, 28 July 2022 at 10:26:36 UTC, kdevel wrote:
On Thursday, 28 July 2022 at 06:12:49 UTC, Alexander Zhirov 
wrote:
On Thursday, 28 July 2022 at 06:01:17 UTC, Alexander Zhirov 
wrote:

```sh
/root/usr/program/gcc/9.5.0/install/bin/cc app.o -o app 
-L/root/usr/program/ldc/1.30/install/lib -lphobos2-ldc 
-ldruntime-ldc -Wl,--gc-sections -lrt -ldl -lpthread -lm -m32

```


So you eventually built GCC 9.5.0? I have used the

```
   --with-arch-32=pentium3
```

option in the configure step for compiling GCC 12.1.0. The 
build gdc

generates codes which successfully runs on my Pentium III.


The only thing I did (but it still didn't work) was I 
[built](https://wiki.dlang.org/Building_under_Posix#Building_DMD) 
a `dmd` compiler:


```sh
root@host ~/program # dmd --version
DMD32 D Compiler v2.100.1-3-g76e3b4137
Copyright (C) 1999-2022 by The D Language Foundation, All Rights 
Reserved written by Walter Bright


root@host ~/program # dmd -mcpu=native app.d -v
predefs   DigitalMars LittleEndian D_Version2 all Posix ELFv1 
linux CRuntime_Glibc CppRuntime_Gcc D_InlineAsm D_InlineAsm_X86 
X86 D_PIC assert D_PreConditions D_PostConditions D_Invariants 
D_ModuleInfo D_Exceptions D_TypeInfo D_HardFloat

binarydmd
version   v2.100.1-3-g76e3b4137
config/root/usr/program/dmd/2.100.1/usr/bin/dmd.conf
DFLAGS
-I/root/usr/program/dmd/2.100.1/usr/bin/../include/dmd/druntime/import -I/root/usr/program/dmd/2.100.1/usr/bin/../include/dmd/phobos -L-L/root/usr/program/dmd/2.100.1/usr/bin/../lib -L--export-dynamic -fPIC

parse app
importall app
importobject
(/root/usr/program/dmd/2.100.1/usr/bin/../include/dmd/druntime/import/object.d)

...
function  std.typecons.Tuple!(uint, "data", uint, 
"count").Tuple.opCmp!(const(Tuple!(uint, "data", uint, 
"count"))).opCmp
cc app.o -o app -m32 -Xlinker --export-dynamic 
-L/root/usr/program/dmd/2.100.1/usr/bin/../lib -Xlinker -Bstatic 
-lphobos2 -Xlinker -Bdynamic -lpthread -lm -lrt -ldl


root@host ~/program # ./app
Illegal instruction
```


Re: Build for i586

2022-07-28 Thread Alexander Zhirov via Digitalmars-d-learn

On Thursday, 28 July 2022 at 10:26:36 UTC, kdevel wrote:
On Thursday, 28 July 2022 at 06:12:49 UTC, Alexander Zhirov 
wrote:
On Thursday, 28 July 2022 at 06:01:17 UTC, Alexander Zhirov 
wrote:

```sh
/root/usr/program/gcc/9.5.0/install/bin/cc app.o -o app 
-L/root/usr/program/ldc/1.30/install/lib -lphobos2-ldc 
-ldruntime-ldc -Wl,--gc-sections -lrt -ldl -lpthread -lm -m32

```


So you eventually built GCC 9.5.0? I have used the

```
   --with-arch-32=pentium3
```

option in the configure step for compiling GCC 12.1.0. The 
build gdc

generates codes which successfully runs on my Pentium III.


I don't understand what I need to do.


Re: Build for i586

2022-07-28 Thread Alexander Zhirov via Digitalmars-d-learn

On Thursday, 28 July 2022 at 07:16:13 UTC, user1234 wrote:
that would be something like `--mcpu=i686 --mattrs=-mmx,-sse` 
and maybe more to be sure.


Fails...

```sh
# ldc2 --mcpu=i686 --mattr=-mmx,-sse app.d
# ./app
Illegal instruction
```


Re: Build for i586

2022-07-28 Thread Alexander Zhirov via Digitalmars-d-learn

On Thursday, 28 July 2022 at 06:01:17 UTC, Alexander Zhirov wrote:

```sh
/root/usr/program/gcc/9.5.0/install/bin/cc app.o -o app 
-L/root/usr/program/ldc/1.30/install/lib -lphobos2-ldc 
-ldruntime-ldc -Wl,--gc-sections -lrt -ldl -lpthread -lm -m32

```


Even tried with such a flag separately, it still doesn't work:

```sh
# /root/usr/program/gcc/9.5.0/install/bin/cc app.o -o app 
-L/root/usr/program/ldc/1.30/install/lib -lphobos2-ldc -ldrun
time-ldc -Wl,--gc-sections -lrt -ldl -lpthread -lm -m32 
-march=geode

# ./app
Illegal instruction
```

I also tried with `i586` and `pentium` - the result is the same.


Build for i586

2022-07-28 Thread Alexander Zhirov via Digitalmars-d-learn
I did a topic a [little 
earlier](https://forum.dlang.org/thread/hfzsnagofrnlmynyz...@forum.dlang.org) about compiling a compiler for processor Geode LX800.
The bottom line is that I have a processor on which I want to 
compile the program, is an i586 architecture.


The [official 
documentation](https://www.amd.com/system/files/TechDocs/33234H_LX_databook.pdf) says that "*... the core is a combination of Intel Pentium ® processor, AMD Athlon™ processor, and AMD Geode LX processor specific instructions.*" - this means that the processor architecture is **<** `i686`. And judging by the fact that Linux gives a description when calling `uname`:


```sh
# uname -m
i586
```

This suggests that the processor is CLEARLY `i586`.
The problem is that I can't assemble the software I need for this 
processor, since it is automatically assembled for `i686`.

What have I done?
I built an `ldc` compiler on this machine:

```sh
# ldc2 --version
LDC - the LLVM D compiler (1.30.0-git-32f5a35):
  based on DMD v2.100.1 and LLVM 10.0.1
  built with DMD32 D Compiler v2.086.1
  Default target: i686-pc-linux-gnu
  Host CPU: geode
  http://dlang.org - http://wiki.dlang.org/LDC

  Registered Targets:
x86- 32-bit X86: Pentium-Pro and above
x86-64 - 64-bit X86: EM64T and AMD64
```

And when I try to compile the program through it, I create a 
binary file, but when I start it outputs **Illegal instruction**:


```sh
# ldc2 app.d
# ./app
Illegal instruction
```

Here's using the `mcpu` flag:

```sh
# ldc2 --mcpu=i586 app.d -v
binary/mnt/disc/sdb/part1/program/ldc/1.30/install/bin/ldc2
version   1.30.0-git-32f5a35 (DMD v2.100.1, LLVM 10.0.1)
config
/mnt/disc/sdb/part1/program/ldc/1.30/install/etc/ldc2.conf 
(i686-pc-linux-gnu)
predefs   LDC all D_Version2 assert D_PreConditions 
D_PostConditions D_Invariants D_ModuleInfo D_Exceptions 
D_TypeInfo X86 D_InlineAsm_X86 D_HardFloat LittleEndian D_PIC 
linux Posix CRuntime_Glibc CppRuntime_Gcc LDC_LLVM_1000

parse app
importall app
importobject
(/root/usr/program/ldc/1.30/install/include/d/object.d)
importcore.attribute
(/root/usr/program/ldc/1.30/install/include/d/core/attribute.d)
importldc.attributes
(/root/usr/program/ldc/1.30/install/include/d/ldc/attributes.d)
importcore.internal.hash
(/root/usr/program/ldc/1.30/install/include/d/core/internal/hash.d)
importcore.internal.traits  
(/root/usr/program/ldc/1.30/install/include/d/core/internal/traits.d)
importcore.internal.entrypoint  
(/root/usr/program/ldc/1.30/install/include/d/core/internal/entrypoint.d)
importcore.internal.array.appending 
(/root/usr/program/ldc/1.30/install/include/d/core/internal/array/appending.d)
importcore.internal.array.comparison
(/root/usr/program/ldc/1.30/install/include/d/core/internal/array/comparison.d)
importcore.internal.array.equality  
(/root/usr/program/ldc/1.30/install/include/d/core/internal/array/equality.d)
importcore.internal.array.casting   
(/root/usr/program/ldc/1.30/install/include/d/core/internal/array/casting.d)
importcore.internal.array.concatenation 
(/root/usr/program/ldc/1.30/install/include/d/core/internal/array/concatenation.d)
importcore.internal.array.construction  
(/root/usr/program/ldc/1.30/install/include/d/core/internal/array/construction.d)
importcore.internal.array.capacity  
(/root/usr/program/ldc/1.30/install/include/d/core/internal/array/capacity.d)
importcore.internal.dassert 
(/root/usr/program/ldc/1.30/install/include/d/core/internal/dassert.d)
importcore.atomic   
(/root/usr/program/ldc/1.30/install/include/d/core/atomic.d)
importcore.internal.attributes  
(/root/usr/program/ldc/1.30/install/include/d/core/internal/attributes.d)
importcore.internal.atomic  
(/root/usr/program/ldc/1.30/install/include/d/core/internal/atomic.d)
importldc.intrinsics
(/root/usr/program/ldc/1.30/install/include/d/ldc/intrinsics.di)
importcore.internal.destruction 
(/root/usr/program/ldc/1.30/install/include/d/core/internal/destruction.d)
importcore.internal.moving  
(/root/usr/program/ldc/1.30/install/include/d/core/internal/moving.d)
importcore.internal.postblit
(/root/usr/program/ldc/1.30/install/include/d/core/internal/postblit.d)
importcore.internal.switch_ 
(/root/usr/program/ldc/1.30/install/include/d/core/internal/switch_.d)
importcore.lifetime 
(/root/usr/program/ldc/1.30/install/include/d/core/lifetime.d)
importcore.builtins 
(/root/usr/program/ldc/1.30/install/include/d/core/builtins.d)

semantic  app
entry main  app.d
semantic2 app
semantic3 app
importstd.stdio 
(/root/usr/program/ldc/1.30/install/include/d/std/stdio.d)
importcore.stdc.stddef  
(/root/usr/program/ldc/1.30/install/include/d/core/stdc/stddef.d)
importstd.algorithm.mutation
(/root/usr/program/ldc/1.30/install/include/d/std/algorithm/mutation.d)
importstd.traits
(/root/usr/program/ldc/1.30/install/include/d/std/traits.d)
import

Re: Choosing the correct compiler version

2022-07-25 Thread Alexander Zhirov via Digitalmars-d-learn

On Thursday, 21 July 2022 at 05:44:41 UTC, Alexander Zhirov wrote:

I will report on the successes a little later.


Result:

I downloaded and unpacked the binary version of the `dmd` 
compiler version 
[2.097.2](http://downloads.dlang.org/releases/2021/dmd.2.097.2.linux.tar.xz), which runs without problems with my `glibc` set.


Then I compiled the `GCC` compiler version 9.5.0 from the source 
code:

```sh
wget 
https://ftp.mpi-inf.mpg.de/mirrors/gnu/mirror/gcc.gnu.org/pub/gcc/releases/gcc-9.5.0/gcc-9.5.0.tar.gz

mkdir build-gcc && cd build-gcc
../gcc-9.5.0/configure --prefix=$PWD/../install-gcc 
--enable-shared --enable-threads=posix --enable-__cxa_atexit 
--enable-clocale=gnu --enable-languages=c,c++

make -j16
make install
```

Then I built `LLVM` using this compiler, according to the 
instructions on the [LDC 
website](https://wiki.dlang.org/Building_LDC_from_source#Building_LLVM_from_source):

```sh
export CC=/root/source/gcc/gcc-install/bin/gcc
export CXX=/root/source/gcc/gcc-install/bin/g++
mkdir build-llvm && cd build-llvm
cmake ../llvm-10.0.1.src -DCMAKE_BUILD_TYPE=Release 
-DCMAKE_INSTALL_PREFIX=$PWD/../install-llvm 
-DLLVM_BINUTILS_INCDIR=/usr/include -DLLVM_TARGETS_TO_BUILD='X86' 
-DCOMPILER_RT_INCLUDE_TESTS=OFF -DLLVM_INCLUDE_TESTS=OFF

make -j16
make install
```

And then I built the `ldc` compiler myself, also according to the 
instructions on the 
[website](https://wiki.dlang.org/Building_LDC_from_source#Building_LDC_from_source):

```sh
git clone --recursive https://github.com/ldc-developers/ldc.git
mkdir build-ldc && cd build-ldc
cmake ../ldc -DCMAKE_BUILD_TYPE=Release 
-DCMAKE_INSTALL_PREFIX=$PWD/../install-ldc 
-DLLVM_ROOT_DIR= 
-DD_COMPILER=

make -j16
make install
```

As a result, I built the `ldc` compiler for my `x32` machine:

```sh
# ldc2 --version
LDC - the LLVM D compiler (1.30.0):
  based on DMD v2.100.1 and LLVM 10.0.1
  built with DMD32 D Compiler v2.097.2
  Default target: i686-pc-linux-gnu
  Host CPU: broadwell
  http://dlang.org - http://wiki.dlang.org/LDC

  Registered Targets:
x86- 32-bit X86: Pentium-Pro and above
x86-64 - 64-bit X86: EM64T and AMD64
```

I hope my guide will be useful to someone who will face the same 
task. Thank you for your help!


Re: Choosing the correct compiler version

2022-07-20 Thread Alexander Zhirov via Digitalmars-d-learn

On Tuesday, 19 July 2022 at 23:19:28 UTC, jfondren wrote:
Finding an old version that works on your machine will be very 
easy, but for example the random 2016 build that I grabbed was 
also too old to build dmd master, so you want to prefer a newer 
build that still works. It's not necessary to build dmd master 
though: in the worst case, you should be able check out interim 
releases (look at 'git tag --list', then 'git checkout 
v2.094.0' for example), build those, then used them to build a 
newer release.


Yes, you were right! I managed to launch the 2020 version. Now 
I'm trying to build `ldc2`. I will report on the successes a 
little later. Thanks!


Re: Choosing the correct compiler version

2022-07-19 Thread Alexander Zhirov via Digitalmars-d-learn

On Tuesday, 19 July 2022 at 15:28:44 UTC, Alexander Zhirov wrote:
I'm trying to install dmd with my hands in order to build ldc2 
from the sources, but I can't:


I need to build a compiler under x32 in order to compile a 
program for the same machine.


```sh
dmd2/src/dmd# make -f posix.mak
posix.mak:42: = DEPRECATION NOTICE =
posix.mak:43: = DEPRECATION: posix.mak is deprecated. Please 
use src/build.d instead.

posix.mak:44: ==
dmd -of../generated/build -g build.d
dmd: /lib/libc.so.6: version `GLIBC_2.28' not found (required by 
dmd)

posix.mak:111: recipe for target '../generated/build' failed
make: *** [../generated/build] Error 1
```


Choosing the correct compiler version

2022-07-19 Thread Alexander Zhirov via Digitalmars-d-learn

Hello everyone
I want to install the `ldc2` compiler on a specific machine 
`i586`:


```sh
~ $ strings /lib/libc.so.6 | grep GLIBC
GLIBC_2.0
GLIBC_2.1
GLIBC_2.1.1
GLIBC_2.1.2
GLIBC_2.1.3
GLIBC_2.2
GLIBC_2.2.1
GLIBC_2.2.2
GLIBC_2.2.3
GLIBC_2.2.4
GLIBC_2.2.6
GLIBC_2.3
GLIBC_2.3.2
GLIBC_2.3.3
GLIBC_2.3.4
GLIBC_2.4
GLIBC_2.5
GLIBC_2.6
GLIBC_2.7
GLIBC_2.8
GLIBC_2.9
GLIBC_2.10
GLIBC_2.11
GLIBC_2.12
GLIBC_2.13
GLIBC_2.14
GLIBC_2.15
GLIBC_2.16
GLIBC_2.17
GLIBC_2.18
GLIBC_2.22
GLIBC_2.23
GLIBC_PRIVATE
```

I'm trying to install dmd with my hands in order to build ldc2 
from the sources, but I can't:


```sh
~ $ dmd --version
dmd: /lib/libc.so.6: version `GLIBC_2.28' not found (required by 
dmd)

```

Please tell me which version for the current configuration I can 
use?


Execute the Shell command and continue executing the algorithm

2022-05-30 Thread Alexander Zhirov via Digitalmars-d-learn
I want to run a command in the background during the execution of 
the algorithm, and without waiting for its actual execution, 
because it is "infinite", while continuing the execution of the 
algorithm and then, knowing the ID of the previously launched 
command, kill the process. So far I have done so:


```d
// Here a long program is launched, as an example `sleep`
executeShell("(sleep 1 && echo \"SLEEP\" >> log) &");

while (!interrupted)
{
// some algorithm is executed here, for example `echo`
executeShell("(echo \"OK\" >> log) &");
if (here is my condition termination of the program)
{
// Here is the termination of the running program
}
Thread.sleep(1.seconds);
}
```

How to organize such an algorithm correctly?


Why is the compiled file size so huge?

2022-05-27 Thread Alexander Zhirov via Digitalmars-d-learn
I'm trying to compile a file that weighs 3 kilobytes. I'm also 
linking a self-written dynamic library. I don't understand why 
the resulting executable file is so huge? After all, all 
libraries are present:


```sh
-rwxr-xr-x 1 root root 6.3M May 27 13:39 app
-rw-r--r-- 1 root root 2.9K May 27 12:57 app.d
-rw-r--r-- 1 root root  25K May 27 13:39 app.o
```

```sh
ldc2 -O app.d -L-lpq -L-lX11 -L-lXrandr -L-lm -L-lmira
```

```sh
linux-vdso.so.1 (0x7fff3a5bf000)
libpq.so.5 => /usr/lib/libpq.so.5 (0x7fe89f8a7000)
libX11.so.6 => /usr/lib/libX11.so.6 (0x7fe89f763000)
libXrandr.so.2 => /usr/lib/libXrandr.so.2 (0x7fe89f756000)
libm.so.6 => /lib/libm.so.6 (0x7fe89f611000)
libmira.so => /usr/lib/libmira.so (0x7fe89f4c7000)
libpthread.so.0 => /lib/libpthread.so.0 (0x7fe89f4a6000)
librt.so.1 => /lib/librt.so.1 (0x7fe89f499000)
libdl.so.2 => /lib/libdl.so.2 (0x7fe89f493000)
libgcc_s.so.1 => /usr/lib/libgcc_s.so.1 (0x7fe89f479000)
libc.so.6 => /lib/libc.so.6 (0x7fe89f2af000)
	/lib64/ld-linux-x86-64.so.2 => /lib/ld-linux-x86-64.so.2 
(0x7fe89f91b000)

libxcb.so.1 => /usr/lib/libxcb.so.1 (0x7fe89f284000)
libXau.so.6 => /usr/lib/libXau.so.6 (0x7fe89f27f000)
libXdmcp.so.6 => /usr/lib/libXdmcp.so.6 (0x7fe89f275000)
libbsd.so.0 => /usr/lib/libbsd.so.0 (0x7fe89f25c000)
libXext.so.6 => /usr/lib/libXext.so.6 (0x7fe89f247000)
libXrender.so.1 => /usr/lib/libXrender.so.1 (0x7fe89f23a000)
	libphobos2-ldc-shared.so.99 => 
/root/dlang/ldc-1.29.0/bin/../lib/libphobos2-ldc-shared.so.99 
(0x7fe89ed89000)
	libdruntime-ldc-shared.so.99 => 
/root/dlang/ldc-1.29.0/bin/../lib/libdruntime-ldc-shared.so.99 
(0x7fe89ec3b000)

(dmd-2.100.0)
```


Re: Sleep in a cycle

2022-05-22 Thread Alexander Zhirov via Digitalmars-d-learn
My schoolboy mistake. Thank you, 
[Adam](https://forum.dlang.org/post/mbbampewwcrkkltjl...@forum.dlang.org)!


On Saturday, 21 May 2022 at 11:17:04 UTC, Alain De Vos wrote:

Or you could capture a sigint and close the file then.


Yes, exactly, I was thinking in this direction. Probably not 
quite correctly implemented in practice.


Sleep in a cycle

2022-05-20 Thread Alexander Zhirov via Digitalmars-d-learn
I have a loop spinning, I want to pause in it in order to repeat 
the next iteration. An error is displayed during compilation.


```d
import std.stdio;
import modules.monitors; //my module
import core.thread;

int main(string[] args)
{
string path = "mswitch.log";
if (args.length > 1)
{
path = args[1];
}
auto file = File(path, "w");

auto monitors = getMonitorsInfo();
file.writeln(monitors);

while (true)
{
setPrimaryMonitor(monitors[1].name);
file.writeln("-- Switch monitors --");
swapMonitors(monitors[0].name, monitors[1].name, 
Relation.right_of);

monitors = getMonitorsInfo();
file.writeln(monitors);

Thread.sleep(dur!("seconds")(10));
}

file.close();

return 0;
}

```

Result build:

```sh
$ dub
Performing "debug" build using /usr/bin/ldc2 for x86_64.
mswitch ~master: building configuration "application"...
Running pre-build commands...
source/app.d(32,5): Warning: statement is not reachable
source/app.d(34,5): Warning: statement is not reachable
source/app.d(32,5): Warning: statement is not reachable
source/app.d(34,5): Warning: statement is not reachable
Error: warnings are treated as errors
   Use -wi if you wish to treat warnings only as 
informational.

/usr/bin/ldc2 failed with exit code 1.
```

Is there any way to pause to slow down the cycle?


Re: Including C sources in a DUB project

2022-05-10 Thread Alexander Zhirov via Digitalmars-d-learn

On Wednesday, 11 May 2022 at 05:11:10 UTC, Alexander Zhirov wrote:


dub.settings.json


It's written about it [here](https://dub.pm/settings)


Re: Including C sources in a DUB project

2022-05-10 Thread Alexander Zhirov via Digitalmars-d-learn

On Tuesday, 10 May 2022 at 22:12:52 UTC, Dennis wrote:
It depends on whether your DMD or LDC installation comes first 
in your PATH environment variable. Both ship with a `dub` 
executable that uses their compiler as default.


I came across something else like this. Created a 
`dub.settings.json` file in the dub project, but still requires 
`dmd`:


```sh
$ dub
Performing "debug" build using dmd for x86_64.
app ~master: building configuration "application"...
Running pre-build commands...
Error: unrecognized switch '-Os'
   run `dmd` to print the compiler manual
   run `dmd -man` to open browser on manual
dmd failed with exit code 1.
```

*dub.settings.json*:

```js
{
"defaultArchitecture": "x86_64",
"defaultCompiler": "ldc"
}
```


Re: Including C sources in a DUB project

2022-05-10 Thread Alexander Zhirov via Digitalmars-d-learn

On Tuesday, 10 May 2022 at 19:13:21 UTC, Dennis wrote:
It has an example directory: 
https://github.com/dlang/dub/tree/master/examples


And if there are two compilers in the system - `dmd` and `ldc`, 
which compiler chooses `dub.json`? And how do I specify the 
specific compiler I want?




Re: Including C sources in a DUB project

2022-05-09 Thread Alexander Zhirov via Digitalmars-d-learn

On Friday, 6 May 2022 at 11:31:27 UTC, Alexander Zhirov wrote:

Does anyone have examples of such a configuration?


I managed to do it like this:

```js
{
"name": "app",
"authors": [
"Alexander Zhirov"
],
"description": "MyProgram",
"dflags": [
"-i"
],
"libs": [
"pq"
],
"preBuildCommands": [
"gcc -Os -c c/*.c -o obj/ip_addresses.o"
],
"sourceFiles": [
"obj/*.o"
]
}
```


Re: Including C sources in a DUB project

2022-05-06 Thread Alexander Zhirov via Digitalmars-d-learn

On Thursday, 5 May 2022 at 06:05:55 UTC, Alexander Zhirov wrote:
It turns out to compile everything manually, but I would like 
to do it all through the dub project.


Does anyone have examples of such a configuration?


Re: Using regular expressions when reading a file

2022-05-06 Thread Alexander Zhirov via Digitalmars-d-learn

On Friday, 6 May 2022 at 05:40:52 UTC, forkit wrote:

auto myTuple = line.split(" = ");


Well, only if as a strict form :)



Re: Using regular expressions when reading a file

2022-05-05 Thread Alexander Zhirov via Digitalmars-d-learn

On Thursday, 5 May 2022 at 19:19:26 UTC, Ali Çehreli wrote:
Couldn't help myself from improving. :) The following regex 
works in my Linux console. No issues with '\n'. (?) It also 
allows for leading and trailing spaces:


import std.regex;
import std.stdio;
import std.algorithm;
import std.array;
import std.typecons;
import std.functional;

void main() {
  auto p_property = regex(r"^ *(\w+) *= *(\w+) *$");
  const properties = File("settings.conf")
 .byLineCopy
 .map!(line => matchFirst(line, p_property))
 .filter!(not!empty) // OR: .filter!(m => 
!m.empty)

 .map!(m => tuple(m[1], m[2]))
 .assocArray;

  writeln(properties);
}


It will need to be sorted out with a fresh head.  Thanks!



Re: Using regular expressions when reading a file

2022-05-05 Thread Alexander Zhirov via Digitalmars-d-learn

On Thursday, 5 May 2022 at 18:58:41 UTC, H. S. Teoh wrote:
You don't have to. Just add a `$` to the end of your regex, and 
it should match the newline. If you put it outside the capture 
parentheses, it will not be included in the value.


In fact, it turned out to be much easier. It was just necessary 
to use the `m` flag instead of the `s` flag:


```d
auto p_property = regex(r"^(\w+) *= *(.+)", "m");
```



Re: Using regular expressions when reading a file

2022-05-05 Thread Alexander Zhirov via Digitalmars-d-learn

On Thursday, 5 May 2022 at 18:15:28 UTC, H. S. Teoh wrote:

auto m = matchFirst(line, p_property);


Yes, it looks more attractive. Thanks! I just don't quite 
understand how `matchFirst` works. I seem to have read the 
[description](https://dlang.org/phobos/std_regex.html#Captures), 
but I can't understand something.


And yet I have to manually remove the line break:
```sh
["host":"192.168.100.236\n", "dbname":"belpig\n", 
"user":"postgres", "port":"5432\n"]

```


Using regular expressions when reading a file

2022-05-05 Thread Alexander Zhirov via Digitalmars-d-learn
I want to use a configuration file with external settings. I'm 
trying to use regular expressions to read the `Property = Value` 
settings. I would like to do it all more beautifully. Is there 
any way to get rid of the line break character? How much does 
everything look "right"?


**settings.conf:**

```sh
host = 127.0.0.1
port = 5432
dbname = database
user = postgres
```

**code:**

```d
auto file = File("settings.conf", "r");
string[string] properties;
auto p_property = regex(r"^\w+ *= *.+", "s");
while (!file.eof())
{
  string line = file.readln();
  auto m = matchAll(line, p_property);
  if (!m.empty())
  {
string property = matchAll(line, regex(r"^\w+", "m")).hit;
string value = replaceAll(line, regex(r"^\w+ *= *", "m"), "");
properties[property] = value;
  }
}
file.close();
writeln(properties);
```

**output:**

```sh
["host":"127.0.0.1\n", "dbname":"mydb\n", "user":"postgres", 
"port":"5432\n"]

```


Re: Including C sources in a DUB project

2022-05-05 Thread Alexander Zhirov via Digitalmars-d-learn

On Thursday, 5 May 2022 at 16:23:18 UTC, H. S. Teoh wrote:

I don't know how to do it using dub, but you could use 
pragma(lib) in

one (or more) of your source files as a workaround:

pragma(lib, "m");
pragma(lib, "X11");
pragma(lib, "Xrandr");


I remember a long time ago, when I first started learning D, I 
set up a project in dub.json so that he compiled the sources 
written in C, linked the necessary libraries and then assembled 
the project in D along with the C object files. How to do it now 
- I have already forgotten.





Including C sources in a DUB project

2022-05-05 Thread Alexander Zhirov via Digitalmars-d-learn
I'm sure there is such a topic on the forum, but after scrolling 
through the search, I didn't find anything. The bottom line is 
that I want to enable compilation of C sources in DUB and then 
build the project with the connection of libraries. I would like 
to see an example of such a `dub.json` project.


Enable libraries (flags) `-lm`, `-lX11`, `-lXrandr`.


```sh
{
"name" : "test",
"description" : "Test project",
"dependencies" : {
}
}
```

It turns out to compile everything manually, but I would like to 
do it all through the dub project.



```sh
.
├── dub.json
└── src
├── app.d
└── main.c
```


Re: How do I get the screen resolution?

2022-04-28 Thread Alexander Zhirov via Digitalmars-d-learn
On Thursday, 28 April 2022 at 22:51:02 UTC, Christopher Katko 
wrote:



Are you sure about that?


Well, if we're talking about programming, then most likely I need 
to work with something like this :)


https://en.wikipedia.org/wiki/Display_Data_Channel

And how to do it - I can't find.


How do I get the screen resolution?

2022-04-28 Thread Alexander Zhirov via Digitalmars-d-learn

Are there any methods to get the screen resolution?
On C/C++ from under X11, it is not possible to do this on the 
command line via SSH, since the display is not defined. And is it 
possible to do this somehow by means of D, pulling out the system 
resolution of the installed display?


Re: Library for image editing and text insertion

2022-04-27 Thread Alexander Zhirov via Digitalmars-d-learn

On Wednesday, 27 April 2022 at 17:07:54 UTC, matheus wrote:

I think in the first time running any D compiler, it should 
blink in the terminal in Yellow/Pink or whatever color you 
like, and show some info like: Are you starting a new project 
any need some libs? Do you know about arsd? If not then go to: 
https://github.com/adamdruppe/arsd. :)


Hahaha  This is the truth! I totally agree!


Re: Library for image editing and text insertion

2022-04-27 Thread Alexander Zhirov via Digitalmars-d-learn
On Wednesday, 27 April 2022 at 16:37:21 UTC, Alexander Zhirov 
wrote:

On Wednesday, 27 April 2022 at 16:07:53 UTC, Adam D Ruppe wrote:


How small did it get?

```sh
dmd: 3136896 byte
ldc:  223952 byte
```


but uses libraries ldc-shared.so

```sh
linux-vdso.so.1 (0x7ffef5d2d000)
libphobos2-ldc-shared.so.99 => 
/usr/lib64/libphobos2-ldc-shared.so.99 (0x7f667e9ee000)
libdruntime-ldc-shared.so.99 => 
/usr/lib64/libdruntime-ldc-shared.so.99 (0x7f667e8ac000)

libm.so.6 => /usr/lib64/libm.so.6 (0x7f667e7c5000)
libgcc_s.so.1 => /usr/lib64/libgcc_s.so.1 
(0x7f667e7a9000)

libc.so.6 => /usr/lib64/libc.so.6 (0x7f667e589000)
/usr/lib64/ld-linux-x86-64.so.2 (0x7f667eebe000)
```

And if without using dynamic libraries, it weighs `1219776` bytes

```sh
linux-vdso.so.1 (0x7ffca9ad)
librt.so.1 => /lib/librt.so.1 (0x7f6240fc4000)
libdl.so.2 => /lib/libdl.so.2 (0x7f6240fbe000)
libpthread.so.0 => /lib/libpthread.so.0 (0x7f6240f9d000)
libm.so.6 => /lib/libm.so.6 (0x7f6240e58000)
libgcc_s.so.1 => /usr/lib/libgcc_s.so.1 (0x7f6240e3e000)
libc.so.6 => /lib/libc.so.6 (0x7f6240c74000)
	/lib64/ld-linux-x86-64.so.2 => /lib/ld-linux-x86-64.so.2 
(0x7f6240ff7000)

```


Re: Library for image editing and text insertion

2022-04-27 Thread Alexander Zhirov via Digitalmars-d-learn

On Wednesday, 27 April 2022 at 16:07:53 UTC, Adam D Ruppe wrote:


How small did it get?

```sh
dmd: 3136896 byte
ldc:  223952 byte
```

And with my libs if you import the other ones like `arsd.png` 
or `arsd.jpeg` directly instead of `arsd.image` that MIGHT help 
trim it down by removing support for other formats.  I'm not 
sure though, none of them are especially big but it might add 
up.


Yes, just now, on your advice, I did so. The size has become a 
little smaller! 





Re: Library for image editing and text insertion

2022-04-27 Thread Alexander Zhirov via Digitalmars-d-learn

On Wednesday, 27 April 2022 at 11:59:20 UTC, Bastiaan Veelo wrote:


Or use LDC.


Gorgeous! LDC has compressed my code at times! Thanks again to 
everyone for help! Special thanks to **Adam Ruppe**


Re: Library for image editing and text insertion

2022-04-27 Thread Alexander Zhirov via Digitalmars-d-learn
On Wednesday, 27 April 2022 at 08:29:27 UTC, Alexander Zhirov 
wrote:
On Wednesday, 27 April 2022 at 07:42:31 UTC, Alexander Zhirov 
wrote:

On Wednesday, 27 April 2022 at 00:03:25 UTC, Adam Ruppe wrote:

Sample code would be:

1) How to write to jpeg correctly?


That's how I managed to write to jpeg:

```d
writeJpeg("dst.jpg", tci);
```

Now I would like to reduce the size of the executable file and it 
would be great at all!





  1   2   >