Cmake dependency scanning

2020-09-27 Thread IGotD- via Digitalmars-d-learn
Do we have any D dependency scanning available for D in Cmake, 
just like the built in C/C++ dependency scanner which is handy, 
or do you have to use the option to compile everything into one 
module (--deps=full)?


I have some problems when there is a mix of inlining and calling 
the separately compiled version from the same module, obviously.


Re: Timeout around function call

2020-09-27 Thread drathier via Digitalmars-d-learn

On Wednesday, 23 September 2020 at 20:58:00 UTC, Imperatorn wrote:
On Wednesday, 23 September 2020 at 20:54:51 UTC, Imperatorn 
wrote:
On Wednesday, 23 September 2020 at 20:44:51 UTC, Ali Çehreli 
wrote:

On 9/23/20 1:19 PM, Imperatorn wrote:

> [...]
send a
> [...]
with timeout.

[...]


Sorry, I can't see the problem. Could you be more specific 
about what you want to achieve?


Oops, I meant to reply to drathier


I need to:

- call a side-effect-free fn with a huge argument that I don't 
want to copy; this argument is then returned mostly unmodified 
wrapped in a new value

- stop executing it if it runs for more than x seconds
- get the return value from it if it finishes within x seconds 
(99.9% of time time)

- let the main thread know what happened
- the main thread should block until the fn call returns
- the fn call should for sure stop executing before the main 
thread carries on
- the size and complexity of the fn makes it pretty much 
impossible to add timeout checks everywhere to make it exit 
nicely; I need to kill it to be sure I didn't miss a case






Re: I need "windowsx.d" Someone can send It to me?

2020-09-27 Thread Imperatorn via Digitalmars-d-learn

On Friday, 25 September 2020 at 15:03:56 UTC, Marcone wrote:
I need windowsx.d but for I don't know the reason is not in 
dmd. Someone that have it can send to me? I don't know convert 
windowsx.h to windowsx.d


I converting it using VisualD:
https://pastebin.com/jzwKRnKZ

Try it, maybe it works


Re: Safe to remove AA elements while iterating over it via .byKeyValue?

2020-09-27 Thread Per Nordlöw via Digitalmars-d-learn

On Sunday, 27 September 2020 at 14:23:11 UTC, H. S. Teoh wrote:
No.  Modifying a container while iterating over it is, in 
general, a bad idea (unless the container is designed to be 
used that way, but even then, such removal is generally 
restricted), because it often leads to highly counterintuitive 
results.  In the case of AA's, removing an element may lead to 
a rehashing, which reorders elements, and your iteration may 
miss some elements or repeat some elements or terminate 
prematurely. Even without a rehashing, you may encounter 
inconsistent behaviours, like some elements going "missing".


I believe it's high time we start thinking about detecting these 
violations at compile-time. I recall it's in the spec somewhere 
so we should start a deprecation process at least for AAs.


assert format of a string before a mixin

2020-09-27 Thread ddcovery via Digitalmars-d-learn
I have a "variation" of "unaryFun" that I name "unaryProp" that, 
basically, doesn't require to specify "a." at the beginning of 
the expression.



template unaryProp(alias propName)
{
  static assert(is(typeof(propName) : string), "Sorry, propName 
must be an string");

  auto unaryProp(ElementType)(auto ref ElementType a)
  {
return mixin("a." ~ propName);
  }
}

assert( "hello".unaryProp!"length" == 5 );



Problem is I need to check that "propName" is a valid property 
name at compile time



i.e. checking this Regex expression
`^[a-zA-Z_]*[a-zA-Z0-9_]*[a-zA-Z][a-zA-Z0-9_]*$`



Is there any way to check a regular expression at compile time?




Re: A scheduled control signal with fibers?

2020-09-27 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Sunday, 27 September 2020 at 16:39:45 UTC, Ali Çehreli wrote:

On 9/27/20 6:33 AM, Ferhat Kurtulmuş wrote:

> [...]
Kurtulmuş wrote:
>> [...]
wrote:
> [...]
processing
>  [...]

How many flame threads do you need? I thought one image 
processor and one flame thrower, no? Even if you have a dozen 
of each, main can start only the image processing threads and 
then each image processor can start its own flame thrower. 
Then, each pair will have an owner and a worker.


[...]


Thank you Ali (Bey). I will take those into account when 
finalizing my code. Your comments helped a lot!


Re: conflicting alias in package module

2020-09-27 Thread Steven Schveighoffer via Digitalmars-d-learn

On 9/27/20 1:17 AM, 60rntogo wrote:

On Sunday, 27 September 2020 at 03:33:20 UTC, Mike Parker wrote:

package.d is for your external interface.


Fair enough, thanks.


This isn't an issue with package, it's an issue with a circular dependency.

You are importing yourself and trying alias something to itself before 
that is defined, which has a conflict.


-Steve


How to hide a function return type in order to wrap several functions into an associated array?

2020-09-27 Thread tastyminerals via Digitalmars-d-learn
This is rather a generic implementation question not necessarily 
related to D but I'd like to get some opinions.
I have a collection of functions that all have the same input, a 
string. The output however is different and depending on what the 
function does it can be ulong, double or bool. The problem is 
that for each line of text I'd like to apply all these functions, 
collect the results and write them into some file. For example,


auto numberOfPunctChars(string text)
{
const ulong cnt = text.filter!(c => c.isPunctuation).count;
return Feature!ulong("numberOfPunctChars", cnt);
}


auto ratioOfDigitsToChars(string text)
{
const double digits = numberOfDigitChars(text).val.to!double;
const double alphas = numberOfAlphaChars(text).val.to!double;
const double ratio = digits / (alphas > 0 ? alphas : digits);
return Feature!double("ratioOfDigitsToChars", ratio);
}

auto hasUnbalancedParens(string text)
{
const bool isBalanced = balancedParens(text, '(', ')') && 
balancedParens(text, '[', ']');

return Feature!bool("hasUnbalancedParens", !isBalanced);
}

As you can see, I created a templated Feature struct. This does 
not help much because I also want to create an associative array 
of ["functionName": ]. How can I define such 
an array when "Feature!T function(string)[string] allFuns" 
requires defining T beforehand and using auto is not possible?


I was thinking of having a Feature struct with 3 fiels of ulong, 
double and bool members but then each Feature init would look 
ugly imho "Feature("name", null, 1.5, null)". There should be a 
another way.




Re: AA with class keys compared with identity instead of opEquals

2020-09-27 Thread Per Nordlöw via Digitalmars-d-learn

On Sunday, 27 September 2020 at 18:39:10 UTC, Per Nordlöw wrote:
How do I defined an AA with class as key where keys are 
compared using `is` instead of `opEquals`? Do I have to store 
the key as a `void*`?


I got a good answer at 
https://dlang.slack.com/archives/C1ZDHBB2S/p1601234030016700


Re: AA with class keys compared with identity instead of opEquals

2020-09-27 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Sunday, 27 September 2020 at 19:37:10 UTC, Per Nordlöw wrote:

On Sunday, 27 September 2020 at 18:39:10 UTC, Per Nordlöw wrote:
How do I defined an AA with class as key where keys are 
compared using `is` instead of `opEquals`? Do I have to store 
the key as a `void*`?


I got a good answer at 
https://dlang.slack.com/archives/C1ZDHBB2S/p1601234030016700


Sorry I did not understand what you meant. It would be better if 
you share the answer here. I found this also 
https://dlang.org/library/std/traits/key_type.html, but I dont 
know if it is related.


Re: conflicting alias in package module

2020-09-27 Thread Steven Schveighoffer via Digitalmars-d-learn

On 9/26/20 9:45 AM, Steven Schveighoffer wrote:

On 9/26/20 3:33 AM, 60rntogo wrote:
and this is an error: "struct pack.foo.Foo at source/pack/foo.d(3,1) 
conflicts with alias pack.bar.Foo at source/pack/bar.d(3,8)". I seems 
like the import in package.d sees Foo both in pack.foo and pack.bar, 
but I don't understand why this happens since the import in bar.d is 
private, isn't it?


A selective import is equivalent to aliasing (to the public) the symbol 
as if it were defined in that scope.


Just in case someone comes along and reads this, I was wrong about this. 
It's not a public import.


-Steve


Re: How to hide a function return type in order to wrap several functions into an associated array?

2020-09-27 Thread Ali Çehreli via Digitalmars-d-learn

On 9/27/20 11:54 AM, tastyminerals wrote:

> I have a collection of functions that all have the same input, a string.
> The output however is different and depending on what the function does
> it can be ulong, double or bool.

The following approach overcomes the different return type issue by 
creating delegates that take string and return string:


auto numberOfPunctChars(string text) {
  return 42;
}

auto ratioOfDigitsToChars(string text) {
  return 1.5;
}

auto hasUnbalancedParens(string text) {
  return true;
}

struct FeatureSet {
  alias TakesString = string delegate(string);
  TakesString[] features;

  void register(Func)(Func func) {
// Here, we convert from a function returning any type
// to a delegate returning string:
features ~= (string s) {
  import std.conv : text;
  return func(s).text;
};
  }

  // Here, we apply all feature delegates and put the outputs
  // into the provided output range.
  void apply(O)(ref O outputRange, string s) {
import std.format : formattedWrite;
import std.algorithm : map;
outputRange.formattedWrite!"%-(%s\n%|%)"(features.map!(f => f(s)));
  }
}

void main() {
  auto featureSet = FeatureSet();

  featureSet.register();
  featureSet.register();
  featureSet.register();

  // lockingTextWriter() just makes an output range from
  // an output stream.
  import std.stdio;
  auto output = stdout.lockingTextWriter;
  featureSet.apply(output, "hello world");

  // As another example, you can use an Appender as well:
  import std.array : Appender;
  auto app = Appender!(char[])();
  featureSet.apply(app, "goodbye moon");
  writefln!"Appender's content:\n%s"(app.data);
}

Ali



Re: assert format of a string before a mixin

2020-09-27 Thread Adam D. Ruppe via Digitalmars-d-learn

On Sunday, 27 September 2020 at 21:38:43 UTC, ddcovery wrote:

i.e. checking this Regex expression
`^[a-zA-Z_]*[a-zA-Z0-9_]*[a-zA-Z][a-zA-Z0-9_]*$`



Is there any way to check a regular expression at compile time?


Not really and I'd actually suggest not trying because even if it 
did work, it'd probably be very slow.


But that regex there is pretty easy to translate to a little 
hand-written loop function that would do the job runtime, ctfe 
both and do it quickly.


Re: assert format of a string before a mixin

2020-09-27 Thread ddcovery via Digitalmars-d-learn

On Sunday, 27 September 2020 at 21:41:25 UTC, Adam D. Ruppe wrote:

On Sunday, 27 September 2020 at 21:38:43 UTC, ddcovery wrote:

i.e. checking this Regex expression
`^[a-zA-Z_]*[a-zA-Z0-9_]*[a-zA-Z][a-zA-Z0-9_]*$`



Is there any way to check a regular expression at compile time?


Not really and I'd actually suggest not trying because even if 
it did work, it'd probably be very slow.


But that regex there is pretty easy to translate to a little 
hand-written loop function that would do the job runtime, ctfe 
both and do it quickly.


Thanks Adam.


AA with class keys compared with identity instead of opEquals

2020-09-27 Thread Per Nordlöw via Digitalmars-d-learn
How do I defined an AA with class as key where keys are compared 
using `is` instead of `opEquals`? Do I have to store the key as a 
`void*`?


Re: AA with class keys compared with identity instead of opEquals

2020-09-27 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Sunday, 27 September 2020 at 18:39:10 UTC, Per Nordlöw wrote:
How do I defined an AA with class as key where keys are 
compared using `is` instead of `opEquals`? Do I have to store 
the key as a `void*`?


By looking at object.d and aaA.d of druntime, I d say you don't 
need to use void*. Object class has required infrastructure ready 
for using classes aa keys (have not tried though). Object class 
has both toHash and opEquals already implemented.





Re: AA with class keys compared with identity instead of opEquals

2020-09-27 Thread Per Nordlöw via Digitalmars-d-learn
On Sunday, 27 September 2020 at 18:56:15 UTC, Ferhat Kurtulmuş 
wrote:
By looking at object.d and aaA.d of druntime, I d say you don't 
need to use void*. Object class has required infrastructure 
ready for using classes aa keys (have not tried though). Object 
class has both toHash and opEquals already implemented.


That's gonna be much slower. And I need key's to be checked for 
equivalence ,not equality.


Re: How to hide a function return type in order to wrap several functions into an associated array?

2020-09-27 Thread Paul Backus via Digitalmars-d-learn

On Sunday, 27 September 2020 at 18:54:11 UTC, tastyminerals wrote:
This is rather a generic implementation question not 
necessarily related to D but I'd like to get some opinions.
I have a collection of functions that all have the same input, 
a string. The output however is different and depending on what 
the function does it can be ulong, double or bool. The problem 
is that for each line of text I'd like to apply all these 
functions, collect the results and write them into some file. 
For example,


[...]

As you can see, I created a templated Feature struct. This does 
not help much because I also want to create an associative 
array of ["functionName": ]. How can I 
define such an array when "Feature!T function(string)[string] 
allFuns" requires defining T beforehand and using auto is not 
possible?


I was thinking of having a Feature struct with 3 fiels of 
ulong, double and bool members but then each Feature init would 
look ugly imho "Feature("name", null, 1.5, null)". There should 
be a another way.


You can use an Algebraic [1] or SumType [2] for this:

alias Feature = SumType!(ulong, double, bool);

Feature numberOfPunctChars(string text)
{
// ...
return Feature(cnt);
}

Feature ratioOfDigitsToChars(string text)
{
// ...
return Feature(ratio);
}

Feature hasUnbalancedParens(string text)
{
// ...
return Feature(!isBalanced);
}

[1] 
http://dpldocs.info/experimental-docs/std.variant.Algebraic.html

[2] https://code.dlang.org/packages/sumtype


Re: I need "windowsx.d" Someone can send It to me?

2020-09-27 Thread Imperatorn via Digitalmars-d-learn

On Friday, 25 September 2020 at 15:03:56 UTC, Marcone wrote:
I need windowsx.d but for I don't know the reason is not in 
dmd. Someone that have it can send to me? I don't know convert 
windowsx.h to windowsx.d


https://wiki.dlang.org/Bindings#Binding_generators


Re: I need "windowsx.d" Someone can send It to me?

2020-09-27 Thread Imperatorn via Digitalmars-d-learn

On Friday, 25 September 2020 at 15:03:56 UTC, Marcone wrote:
I need windowsx.d but for I don't know the reason is not in 
dmd. Someone that have it can send to me? I don't know convert 
windowsx.h to windowsx.d


You don't want to just include it?

https://atilaoncode.blog/2018/04/09/include-c-headers-in-d-code/


Re: I need "windowsx.d" Someone can send It to me?

2020-09-27 Thread Andre Pany via Digitalmars-d-learn

On Sunday, 27 September 2020 at 07:55:56 UTC, Imperatorn wrote:

On Friday, 25 September 2020 at 15:03:56 UTC, Marcone wrote:
I need windowsx.d but for I don't know the reason is not in 
dmd. Someone that have it can send to me? I don't know convert 
windowsx.h to windowsx.d


You don't want to just include it?

https://atilaoncode.blog/2018/04/09/include-c-headers-in-d-code/


Dpp is not able to translate macros (maybe in the future). Macros 
needs to be translated manually.


Kind regards
Andre


Re: Struct initializer in UDA

2020-09-27 Thread realhet via Digitalmars-d-learn

On Sunday, 27 September 2020 at 11:59:49 UTC, Anonymouse wrote:

On Sunday, 27 September 2020 at 10:17:39 UTC, realhet wrote:
On Saturday, 26 September 2020 at 17:13:17 UTC, Anonymouse 
wrote:

On Saturday, 26 September 2020 at 16:05:58 UTC, realhet wrote:


That looks the closes to the python named parameters or the 
struct initializer.


For my use case this opDispatch trick seems to be more flexible 
than the named-parameters thing:


@(FieldProps().range(-360, 360).format("%.2f").caption("Turret 
rotation").unit("deg")) float alpha = 0;


for example if I use the name: "logRange" it can also set the 
isLogarithmic flag as a side effect to true inside the FieldProps 
struct. Just by choosing a slightly different name.


With this idealized format it would be not possible:
@FieldProps{ range: {-360, 360}, format:"%.2f", caption:"Turret 
rotation", unit:"deg"} float alpha = 0;


The more work inside the struct is not a problem, because I'm 
willing to use it from 1000 places. Also __traits(allMembers) can 
help.


Thank you!


Re: Methods for expanding class in another class/struct

2020-09-27 Thread IGotD- via Digitalmars-d-learn

On Saturday, 26 September 2020 at 11:30:23 UTC, k2aj wrote:


It does work, the problem is that scoped returns a Voldemort 
type, so you have to use 
typeof(scoped!SomeClass(someConstructorArgs)) to declare a 
field. Gets really annoying when doing it with any class that 
doesn't have a zero-argument constructor, especially in generic 
code.


class Foo {}

class Bar {
typeof(scoped!Foo()) foo;
this() {
foo = scoped!Foo();
}
}


Thanks, so what we really need is a new scope template that 
declares the the variables in the class and possible a template 
for running the constructor?


Re: A scheduled control signal with fibers?

2020-09-27 Thread Ali Çehreli via Digitalmars-d-learn

On 9/27/20 3:06 AM, Ferhat Kurtulmuş wrote:

> __gshared DList!Entry queue;
> __gshared bool shouldRun = true;

Have you considered passing messages with std.concurrency.send() and 
std.concurrency.receive() and friends? You wouldn't need 'queue' because 
all of your threads already have mail boxes to send messages to each other.


> void worker() {
>  while(shouldRun){
>  auto r = queue[];
>  if(!r.empty && queue.back.st < Clock.currTime){
>  writeln(queue.back); // consume the value
> sendPWMSignalToValfe(pwmval)
>  queue.popLastOf(r);
>  }
>  }
> }

It's not clear whether it's only in your test code but busy-waiting like 
that will make your CPU very warm. :) Since requests cannot pass each 
other, your worker thread should have something like the following in 
that loop:


import core.thread;

  Thread.sleep(duration);

Depending on how accurate the operating system honors your sleep 
requests (e.g. is it real-time?), you may want to sleep less than 
'duration' and then busy-wait the rest of the duration. Similar to the 
difference between spinForce() and yieldForce() of std.parallelism (I 
understand that your solution should not involve std.parallelism):


  https://dlang.org/phobos/std_parallelism.html#.Task.spinForce

As an improvement when defining durations, you don't need to "hide" 
units in comments:


// enum afterNmilliseconds = 1500;

// Instead:
enum after = 1500.msecs;

msecs and friends are defined in core.time:

  https://dlang.org/phobos/core_time.html#.dur

Ali




Re: Struct initializer in UDA

2020-09-27 Thread Anonymouse via Digitalmars-d-learn

On Sunday, 27 September 2020 at 10:17:39 UTC, realhet wrote:
On Saturday, 26 September 2020 at 17:13:17 UTC, Anonymouse 
wrote:

On Saturday, 26 September 2020 at 16:05:58 UTC, realhet wrote:
The closest I can get is @(S.init.c(9).f(42)) with use of 
opDispatch, which is easier to read but still ugly.


All I can get is that the
- an identifier of a member is stronger than the opDispatch. -> 
Error: function expected before (), not S(0, 0).c of type int
- and if I prefix it with '_' it ruins toString. -> Error: no 
property toString for type onlineapp.S



import std.stdio, std.range, std.algorithm, std.traits, 
std.meta, std.conv, std.string, std.uni, std.meta, 
std.functional, std.exception;


struct S{
int a, b;

auto opDispatch(string name, T)(T value)
if(name.startsWith("_"))
{
mixin(name[1..$], "= value;");
return this;
}
}

void main(){
S.init._a(5).writeln;
}


Now I'm more confused, as the compiler completely ignores the 
if(name.startsWith("_")) constraint o.O


It works if you specialise opDispatch to take an int parameter 
instead of a type T. It smells like a bug but I don't know enough 
to say.


I used two opDispatches to be able to avoid having to use _a and 
_b, and std.algorithm.comparison.among to constrain them.


struct S{
private int _a, _b;

auto opDispatch(string name)(int value)
if (name.among("a", "b"))
{
mixin("_", name, "= value;");
return this;
}

auto opDispatch(string name)()
if (name.among("a", "b"))
{
mixin("return _", name, ";");
}
}

void main(){
S.init.a(123).b(456).writeln;
S().b(456).a(123).writeln;  // Alternative syntax, may not 
work if opCall is defined

}

It's brittle in that you have to update and sync the two 
among("a", "b") constraints every time you add or remove a field, 
but I can't seem to get the names by introspection without it 
endlessly recursing over opDispatch again.


Re: A scheduled control signal with fibers?

2020-09-27 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Sunday, 27 September 2020 at 10:40:25 UTC, Ali Çehreli wrote:

On 9/27/20 3:06 AM, Ferhat Kurtulmuş wrote:

> __gshared DList!Entry queue;
> __gshared bool shouldRun = true;

Have you considered passing messages with 
std.concurrency.send() and std.concurrency.receive() and 
friends? You wouldn't need 'queue' because all of your threads 
already have mail boxes to send messages to each other.


> void worker() {
>  while(shouldRun){
>  auto r = queue[];
>  if(!r.empty && queue.back.st < Clock.currTime){
>  writeln(queue.back); // consume the value
> sendPWMSignalToValfe(pwmval)
>  queue.popLastOf(r);
>  }
>  }
> }

It's not clear whether it's only in your test code but 
busy-waiting like that will make your CPU very warm. :) Since 
requests cannot pass each other, your worker thread should have 
something like the following in that loop:


import core.thread;

  Thread.sleep(duration);

Depending on how accurate the operating system honors your 
sleep requests (e.g. is it real-time?), you may want to sleep 
less than 'duration' and then busy-wait the rest of the 
duration. Similar to the difference between spinForce() and 
yieldForce() of std.parallelism (I understand that your 
solution should not involve std.parallelism):


  https://dlang.org/phobos/std_parallelism.html#.Task.spinForce

As an improvement when defining durations, you don't need to 
"hide" units in comments:


// enum afterNmilliseconds = 1500;

// Instead:
enum after = 1500.msecs;

msecs and friends are defined in core.time:

  https://dlang.org/phobos/core_time.html#.dur

Ali


Yes, this solution requires less code and obviously less system 
resources.


void main() {

while (true) {
int v;

"type your value: ".write;
readf(" %d", );

if(v==0){
break;
}

auto childTid = spawn(, thisTid);
send(childTid, v);
}

writeln("main is done.");
}

static void spawnedFunc(Tid ownerTid)
{
receive((int v){
Thread.sleep(1500.msecs);
writeln(v);
});
}

However, there is a big problem now. If I change my main like 
below, numbers are not written at the correct order after 1.5 
seconds?


void main() {
foreach (v; 0..10){
auto childTid = spawn(, thisTid);
send(childTid, v);
}
writeln("main is done.");
}



Re: A scheduled control signal with fibers?

2020-09-27 Thread Ferhat Kurtulmuş via Digitalmars-d-learn
On Friday, 25 September 2020 at 13:37:09 UTC, Steven 
Schveighoffer wrote:


Given the rate and the number of concurrent tasks, I'd say 
threads.


-Steve


Here is my testable and minimal code using 1 extra thread. Thank 
you all!


import core.thread;

import std.stdio;
import std.concurrency;
import std.container.dlist;
import std.datetime;
import std.datetime.systime;

__gshared DList!Entry queue;
__gshared bool shouldRun = true;

struct Entry {
SysTime st;
int val;
}

void main() {

spawn();

while (true) {
int v;

"enter your value: ".write; // 
getFlameIntensityViaImageProcessing()

readf(" %d", );

if(v==0){
shouldRun = false;
break;
}


queue.insertFront(Entry(Clock.currTime + 1500.msecs, v));
}

writeln("main is done.");
}

void worker() {
while(shouldRun){
auto r = queue[];
if(!r.empty && queue.back.st < Clock.currTime){
writeln(queue.back); // consume the value 
sendPWMSignalToValfe(pwmval)

queue.popLastOf(r);
}
}
}


Re: Struct initializer in UDA

2020-09-27 Thread realhet via Digitalmars-d-learn

On Saturday, 26 September 2020 at 17:13:17 UTC, Anonymouse wrote:

On Saturday, 26 September 2020 at 16:05:58 UTC, realhet wrote:
The closest I can get is @(S.init.c(9).f(42)) with use of 
opDispatch, which is easier to read but still ugly.


All I can get is that the
- an identifier of a member is stronger than the opDispatch. -> 
Error: function expected before (), not S(0, 0).c of type int
- and if I prefix it with '_' it ruins toString. -> Error: no 
property toString for type onlineapp.S



import std.stdio, std.range, std.algorithm, std.traits, std.meta, 
std.conv, std.string, std.uni, std.meta, std.functional, 
std.exception;


struct S{
int a, b;

auto opDispatch(string name, T)(T value)
if(name.startsWith("_"))
{
mixin(name[1..$], "= value;");
return this;
}
}

void main(){
S.init._a(5).writeln;
}


Now I'm more confused, as the compiler completely ignores the 
if(name.startsWith("_")) constraint o.O


Re: A scheduled control signal with fibers?

2020-09-27 Thread Ferhat Kurtulmuş via Digitalmars-d-learn

On Sunday, 27 September 2020 at 10:40:25 UTC, Ali Çehreli wrote:

On 9/27/20 3:06 AM, Ferhat Kurtulmuş wrote:


Have you considered passing messages with 
std.concurrency.send() and std.concurrency.receive() and 
friends? You wouldn't need 'queue' because all of your threads 
already have mail boxes to send messages to each other.


I remember that your book covers passing messages with send(). 
Probably I will rewrite it using that mechanism, you are right, I 
noticed that when I run the code I can hear the boosted noise of 
my desktop fan.


As an improvement when defining durations, you don't need to 
"hide" units in comments:


// enum afterNmilliseconds = 1500;

// Instead:
enum after = 1500.msecs;

msecs and friends are defined in core.time:

  https://dlang.org/phobos/core_time.html#.dur


Thank you for the tip. That was just a preudo-code to explain my 
situation.


Thanks a lot.
Ferhat




Re: A scheduled control signal with fibers?

2020-09-27 Thread Imperatorn via Digitalmars-d-learn
On Sunday, 27 September 2020 at 10:52:58 UTC, Ferhat Kurtulmuş 
wrote:

On Sunday, 27 September 2020 at 10:40:25 UTC, Ali Çehreli wrote:

[...]



[...]


I remember that your book covers passing messages with send(). 
Probably I will rewrite it using that mechanism, you are right, 
I noticed that when I run the code I can hear the boosted noise 
of my desktop fan.



  [...]


Thank you for the tip. That was just a preudo-code to explain 
my situation.


Thanks a lot.
Ferhat


The actor model is under-rated imho


Re: I need "windowsx.d" Someone can send It to me?

2020-09-27 Thread Denis Feklushkin via Digitalmars-d-learn

On Friday, 25 September 2020 at 15:03:56 UTC, Marcone wrote:
I need windowsx.d but for I don't know the reason is not in 
dmd. Someone that have it can send to me? I don't know convert 
windowsx.h to windowsx.d


Maybe it is already available on code.dlang.org?


Safe to remove AA elements while iterating over it via .byKeyValue?

2020-09-27 Thread Per Nordlöw via Digitalmars-d-learn
Is it safe to remove AA-elements from an `aa` I'm iterating over 
via aa.byKeyValue?


I'm currently doing this:

foreach (ref kv; aa.byKeyValue)
{
if (pred(kv.key))
aa.remove(kv.key); // ok?
}
if (aa.length == 0)
aa = null;

Is there a better way?


Re: A scheduled control signal with fibers?

2020-09-27 Thread Ali Çehreli via Digitalmars-d-learn

On 9/27/20 6:33 AM, Ferhat Kurtulmuş wrote:

> On Sunday, 27 September 2020 at 12:05:13 UTC, Ferhat Kurtulmuş wrote:
>> On Sunday, 27 September 2020 at 10:40:25 UTC, Ali Çehreli wrote:
>>> On 9/27/20 3:06 AM, Ferhat Kurtulmuş wrote:
>
> Oh, It will work fine if I imitate my time-consuming image processing
> like this.
> I think it is Ok now.
>
> import std.stdio;
> import std.concurrency;
> import core.thread;
>
> void main() {
>  foreach (v; 0..10){
>  auto childTid = spawn(, thisTid);

How many flame threads do you need? I thought one image processor and 
one flame thrower, no? Even if you have a dozen of each, main can start 
only the image processing threads and then each image processor can 
start its own flame thrower. Then, each pair will have an owner and a 
worker.


You don't need to send thisTid because every thread already has an 
ownerTid defined:


  auto childTid = spawn();

>  Thread.sleep(10.msecs); // imitate image processing
>  send(childTid, v);

UFCS makes it nicer:

  childTid.send(v);

>
>  }
>  writeln("main is done.");
> }
>
> static void spawnedFunc(Tid ownerTid)

To repeat, you already have a valid ownerTid in this thread. Just remove 
the parameter.


> {
>  receive((int v){
>  Thread.sleep(1500.msecs);

I think you should sleep less than that to work at the exact expected 
time. Otherwise, an unknown amount of time has already passed when this 
thread is woken up again.


Instead of sleeping 1500, something like this may be needed:

  - This thread looks at the time to figure out how long to sleep e.g. 
sometimes 1400 msecs

  - Sleeps that amount
  - Fires when it wakes up

However, you can not expect to be waken up exactly at 1400 msecs later. 
If timing precision is really important, I recommend running some 
statistics to see how much off your thread is when it wakes up. 
Depending on the statistics, I would sleep less than the expected amount 
and then burn the CPU until it's the exact time. But maybe precision is 
not that important; so, forget that idea. :)


>  writeln(v);
>  });
> }

One more thing: It is common for the workers to die with an exception 
(sometimes with Error). You must catch it (including Error) by the 
worker thread and report it somehow e.g. with a special exception. 
Otherwise, nobody will know what happened.


This reminds me: If you start the worker with spawnLinked() instead of 
spawn(), the owner will get a LinkTerminated message if a thread dies. 
That's another way of detecting that failure.


Ali




Array Slicing

2020-09-27 Thread DMon via Digitalmars-d-learn
Are these in the Specification or Phobos? I figured them out a 
few days ago. These are from my snippet journal on arrays and 
there may be more.


void main()
{
int[5] a = [1, 2, 3, 4, 5];
int[5][3] b = [[6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 
17, 18, 19, 20]];

int[5] c;

// This:
writeln(a[1..4][0]);
writeln(b[0][1..4]);
writeln(b[1][1..4][2]);
//writeln(b[0..1][1..3]); // Range violation.
//writeln(a[$-2..$-3]); // NG.
writeln(a[$-3..$-2])

// And, this:
c[0..5] = a[0..$-0]
writeln(c);
}

My apologizes, if any if these are noted or wrong.



Re: Safe to remove AA elements while iterating over it via .byKeyValue?

2020-09-27 Thread Imperatorn via Digitalmars-d-learn

On Sunday, 27 September 2020 at 13:02:04 UTC, Per Nordlöw wrote:
Is it safe to remove AA-elements from an `aa` I'm iterating 
over via aa.byKeyValue?


I'm currently doing this:

foreach (ref kv; aa.byKeyValue)
{
if (pred(kv.key))
aa.remove(kv.key); // ok?
}
if (aa.length == 0)
aa = null;

Is there a better way?


What you could do is find all matches (pred) and remove range of 
indices


Re: Safe to remove AA elements while iterating over it via .byKeyValue?

2020-09-27 Thread H. S. Teoh via Digitalmars-d-learn
On Sun, Sep 27, 2020 at 01:02:04PM +, Per Nordlöw via Digitalmars-d-learn 
wrote:
> Is it safe to remove AA-elements from an `aa` I'm iterating over via
> aa.byKeyValue?

No.  Modifying a container while iterating over it is, in general, a bad
idea (unless the container is designed to be used that way, but even
then, such removal is generally restricted), because it often leads to
highly counterintuitive results.  In the case of AA's, removing an
element may lead to a rehashing, which reorders elements, and your
iteration may miss some elements or repeat some elements or terminate
prematurely. Even without a rehashing, you may encounter inconsistent
behaviours, like some elements going "missing".

You probably want to build a list of keys to remove, then remove them
after the iteration instead.


T

-- 
Why can't you just be a nonconformist like everyone else? -- YHL


Re: Array Slicing

2020-09-27 Thread H. S. Teoh via Digitalmars-d-learn
On Sun, Sep 27, 2020 at 01:59:07PM +, DMon via Digitalmars-d-learn wrote:
> Are these in the Specification or Phobos?

See: https://dlang.org/articles/d-array-article.html


T

-- 
Государство делает вид, что платит нам зарплату, а мы делаем вид, что работаем.


Re: Safe to remove AA elements while iterating over it via .byKeyValue?

2020-09-27 Thread Imperatorn via Digitalmars-d-learn

On Sunday, 27 September 2020 at 13:02:04 UTC, Per Nordlöw wrote:
Is it safe to remove AA-elements from an `aa` I'm iterating 
over via aa.byKeyValue?


I'm currently doing this:

foreach (ref kv; aa.byKeyValue)
{
if (pred(kv.key))
aa.remove(kv.key); // ok?
}
if (aa.length == 0)
aa = null;

Is there a better way?


Normally this is not advisable since you're modifying the 
iterated source.


Same thing in C#, there it's a compiler error.


Re: A scheduled control signal with fibers?

2020-09-27 Thread Ferhat Kurtulmuş via Digitalmars-d-learn
On Sunday, 27 September 2020 at 12:05:13 UTC, Ferhat Kurtulmuş 
wrote:

On Sunday, 27 September 2020 at 10:40:25 UTC, Ali Çehreli wrote:

On 9/27/20 3:06 AM, Ferhat Kurtulmuş wrote:


Oh, It will work fine if I imitate my time-consuming image 
processing like this.

I think it is Ok now.

import std.stdio;
import std.concurrency;
import core.thread;

void main() {
foreach (v; 0..10){
auto childTid = spawn(, thisTid);
Thread.sleep(10.msecs); // imitate image processing
send(childTid, v);

}
writeln("main is done.");
}

static void spawnedFunc(Tid ownerTid)
{
receive((int v){
Thread.sleep(1500.msecs);
writeln(v);
});
}


Re: Safe to remove AA elements while iterating over it via .byKeyValue?

2020-09-27 Thread Anonymouse via Digitalmars-d-learn

On Sunday, 27 September 2020 at 13:02:04 UTC, Per Nordlöw wrote:
Is it safe to remove AA-elements from an `aa` I'm iterating 
over via aa.byKeyValue?


I'm currently doing this:

foreach (ref kv; aa.byKeyValue)
{
if (pred(kv.key))
aa.remove(kv.key); // ok?
}
if (aa.length == 0)
aa = null;

Is there a better way?


The boring way is to store an array of the spent keys and remove 
afterwards.


KeyType!(typeof(aa))[] garbage;
garbage.reserve(aa.length);

foreach (ref kv; aa.byKeyValue)
{
if (pred(kv.key))
garbage ~= kv.key;
}

foreach (const key; garbage)
{
aa.remove(key);
}

This works with normal arrays too (and 
std.algorithm.mutation.remove), if you foreach_reverse the 
garbage array.