Re: Comparing Exceptions and Errors

2022-06-06 Thread Sebastiaan Koppe via Digitalmars-d-learn

On Monday, 6 June 2022 at 04:59:05 UTC, Ola Fosheim Grøstad wrote:
For instance if a sort function fails, then you can call a 
slower sort function.


Or in terms of actors/tasks: if one actor-solver fails 
numerically, then you can recover and use a different 
actor-solver.


Those are not places where you would put an assert.

The only place to put an assert is when *you* know there is no 
recovery.


Like you have been arguing, there aren't many places like that.

So don't use it.

---

9 out of 10 times when I see an assert in code review I ask the 
author to reconsider. Often it only requires a little tweak.


I guess you could say I have found asserts to be misused.


Re: Comparing Exceptions and Errors

2022-06-05 Thread Sebastiaan Koppe via Digitalmars-d-learn

On Sunday, 5 June 2022 at 06:31:42 UTC, Ola Fosheim Grøstad wrote:

On Sunday, 5 June 2022 at 00:40:26 UTC, Ali Çehreli wrote:
That is not very probable in 100% @safe code. You are basically 
saying that D cannot compete with Go and other «safe» languages.


Go has panic. Other languages have similar constructs.

So D will never be able to provide actors and provide fault 
tolerance.


I guess it depends on the programmer.



Is the service in a usable state?


Yes, the actor code failed. The actor code change frequently, 
not the runtime kernel.


The actor code is free to call anything, including @system code.

How would the actor framework know when an error is due to a 
silly bug in an isolated function or if it is something more 
serious?


Re: Comparing Exceptions and Errors

2022-06-04 Thread Sebastiaan Koppe via Digitalmars-d-learn
On Saturday, 4 June 2022 at 17:17:13 UTC, Ola Fosheim Grøstad 
wrote:

Why can't Error unwind the stack properly?


It does normally, but it doesn't destruct objects when those are 
in `nothrow` functions.


Nothrow functions don't throw, so have no cleanup.

You could argue it is strange that assert throws...

In a not-miniscule service you can be pretty certain that some 
±1 bugs will be there, especially in a service that is 
receiving new features on a regular basis.


Most wont throw a Error though. And typical services have canary 
releases and rollback.


So you just fix it, which you have to do anyway.

Not saying its perfect, but if you only use asserts when you have 
to, and handle other things using the type system, it doesn't 
actually happen all that often.




Re: Comparing Exceptions and Errors

2022-06-04 Thread Sebastiaan Koppe via Digitalmars-d-learn
On Saturday, 4 June 2022 at 01:17:28 UTC, Steven Schveighoffer 
wrote:
If a thread does not catch an error and end the program, that's 
a defect in druntime I think. If it tries to rethrow the 
exception in the main thread (oh, man I have to check... Yeah, 
this is what it does), then it's entirely possible that the 
main thread will never even get to the `Error`!


Yes, for that reason, and others, people should not use that api.


If we are paranoid and want to do as little as possible, at 
least we should attempt to copy a string literal to stderr. 
Something like "Thread exiting with Error." And exit(1) right 
after that.


Yes, that is what it should do.


Probably yes.



Re: Comparing Exceptions and Errors

2022-06-04 Thread Sebastiaan Koppe via Digitalmars-d-learn
On Saturday, 4 June 2022 at 14:19:22 UTC, Ola Fosheim Grøstad 
wrote:
Also, what it is the purpose of @safe if you have to kill all 
threads? Such rigidity will just make Go look all the more 
attractive for service providers!


I agree with this, but given the current semantics there is 
nothing else to do but teardown everything upon first sight of 
Error.


The reasoning is simple: Error + nothrow will sidestep any RAII 
you may have. Since you cannot know what potentially wasn't 
destructed, the only safe course of action is to abandon ship.


Yes, in plenty of cases that is completely overkill.

Then again, programs should be written to not assert in the first 
place.


Considering most asserts I have seen are either due to a bad api 
or just laziness - and shouldn't have to exist in the first place 
- maybe it's not that bad.


Re: Improve a simple event handler

2022-01-17 Thread Sebastiaan Koppe via Digitalmars-d-learn

On Sunday, 16 January 2022 at 20:01:09 UTC, JN wrote:

On Saturday, 15 January 2022 at 23:15:16 UTC, JN wrote:


Is there some way I could improve this with some D features? 
My main gripes with it are:




Managed to dramatically simplify it to 10 lines of code with 
variadic templates.


```d
import std.stdio;

struct Event(T...)
{
void function(T)[] listeners;

void addListener(void function(T) handler)
{
listeners ~= handler;
}

void emit(T args)
{
foreach (listener; listeners)
{
listener(args);
}
}
}

void onResize(uint newWidth, uint newHeight)
{
writefln("Resized: %d %d", newWidth, newHeight);
}

void main()
{
Event!(uint, uint) windowResizeEvent;
windowResizeEvent.addListener();

windowResizeEvent.emit(1000, 2000);
}
```

I am very happy with this solution.


Looks good. But do note that with larger applications it 
inevitably becomes a ball of spaghetti, making it hard to 
understand why a certain widget behaves the way it does (or 
doesn't).


The other problem - already apparent in this small example - is 
the absence of `removeListener`. It is a very crucial and often 
overlooked part that often only gets written afterwards. The 
problem is that it ties into lifetime which is hard to bolt on.


For small things though, it works wonderfully.


Re: Make sure lifetime of helper structs is less than owning struct

2021-11-16 Thread Sebastiaan Koppe via Digitalmars-d-learn

On Monday, 15 November 2021 at 22:49:12 UTC, Ali Çehreli wrote:

Trying with it produces an error when 'new' is not used:

Error: reference to local variable `file` assigned to non-scope 
parameter `p` calling deneme.ByChunk.opAssign


The error is what the OP wanted, so that is expected.

Although, he did ask for it to be on the next line, but this is 
better since it points exactly to the line where he was escaping 
a reference to the scoped object.


I don't see how it solves the problem. Sebastiaan Koppe might 
have intended to allocate the object dynamically with 'new' as 
well?


No I didn't. Anything created with new has automatic lifetime. 
Here the OP wanted to (have the compiler) destroy the FileReader 
when it left the scope, while disallowing any use after free.


Re: Make sure lifetime of helper structs is less than owning struct

2021-11-15 Thread Sebastiaan Koppe via Digitalmars-d-learn

On Monday, 15 November 2021 at 15:56:57 UTC, WebFreak001 wrote:

is this currently possible or maybe possible with DIP1000?


Yes it is. But besides `-dip1000` and `@safe`, it requires the 
use of a pointer:


```D
@safe:

struct ByChunk {
FileReader* r;
void popFront() {}
}

struct FileReader {
ByChunk byChunk() return scope {
return ByChunk();
}
}

void main() {
ByChunk helper;
{
auto file = FileReader();
	helper = file.byChunk;  // Error: address of variable `file` 
assigned to `helper` with longer lifetime

}
helper.popFront;
}
```


Re: auto ref function parameter causes that non copyable struct is copied?

2021-11-10 Thread Sebastiaan Koppe via Digitalmars-d-learn

On Tuesday, 9 November 2021 at 19:30:20 UTC, tchaloupka wrote:

On Monday, 8 November 2021 at 23:26:39 UTC, tchaloupka wrote:

Bug or feature? :)


I've reported it in 
https://issues.dlang.org/show_bug.cgi?id=22498.


It doesn't copy. It just destructs the same object twice... Ouch.

Change the destructor to `~this() { printf("~this(%d)\n", n); n = 
12; }` and you'll see.


I have been looking at LDC's IR of this. `unwrap` takes a lvalue, 
but the compiler puts the object from `gen` on main's stack and 
gives a pointer to unwrap instead. `unwrap` is now the sole owner 
of the object, and calls the destructor before returning a ref to 
one of its fields.


I haven't figured out the interplay of features and optimizations 
here, but it looks like a leak. I would have expected @safe to 
catch this.


As you said in the bug, NVRO solves it (not sure why). As well as 
not passing a lvalue into `unwrap` in the first place.


Re: Threading challenge: calculate fib(45) while spinning

2021-10-16 Thread Sebastiaan Koppe via Digitalmars-d-learn

On Friday, 15 October 2021 at 03:35:44 UTC, jfondren wrote:
The book, "The Go Programming Language" has this simple 
goroutine example:


[...]


Here is a similar implementation using the concurrency library:

```d
import concurrency;
import concurrency.stream;
import concurrency.sender : justFrom;
import concurrency.operations : via, race;
import concurrency.thread : ThreadSender;
import core.time : msecs;
import std.stdio : writef, writefln, stdout;
import core.thread : Thread;

void main() @safe {
enum chars = `-\|/`;
auto spinner = infiniteStream(0)
.scan((int acc, int _) => acc + 1, 0)
.collect((int i) shared @trusted {
writef("\r%c", chars[i % chars.length]);
stdout.flush();
Thread.sleep(100.msecs);
})
.via(ThreadSender());

enum n = 45;
auto work = justFrom(() => fib(n));

auto result = race(spinner, work).syncWait.value;
writefln("\rFibonacci(%d) = %d", n, result.get);
}

int fib(int x) pure @safe @nogc {
if (x < 2)
return x;
return fib(x - 1) + fib(x - 2);
}
```

Go has language support so it is a bit unfair to compare it.

But this code will properly handle errors (in case `writef` or 
`flush` throws), and as well as having an explicit 
synchronization point so that the final `writeln` is always after 
the spinner is done.


Re: to compose or hack?

2021-07-07 Thread Sebastiaan Koppe via Digitalmars-d-learn
On Wednesday, 7 July 2021 at 13:30:28 UTC, Steven Schveighoffer 
wrote:

On 7/7/21 5:54 AM, rassoc wrote:
On Wednesday, 7 July 2021 at 01:44:20 UTC, Steven 
Schveighoffer wrote:
So I have this situation where I need to split a string, then 
where the splits are, insert a string to go between the 
elements making a new range, all without allocating 
(hopefully).




Without considering the more general case, isn't that just 
splitter-joiner?


No, splitter-joiner would make a range of characters, I want a 
range of strings.


Just lift each item in a range then:

```d
import std;

auto foo(string s, string sp, string j) @nogc {
 return s.splitter(sp).map!(i => only(i)).joiner(only(j));
}

void main() {
 foo("ab,cd,ef,gh", ",", "##").writeln; // => ["ab", "##", 
"cd", "##", "ef", "##", "gh"]

}
```


Re: GC memory fragmentation

2021-04-12 Thread Sebastiaan Koppe via Digitalmars-d-learn

On Sunday, 11 April 2021 at 09:10:22 UTC, tchaloupka wrote:

Hi,
we're using vibe-d (on Linux) for a long running REST API 
server and have problem with constantly growing memory until 
system kills it with OOM killer.


[...]

But this is very bad for performance so we've prolonged the 
interval for example to 30 seconds and now memory still goes up 
(not that dramatically but still).


[...]

So it wastes a lot of free space which it can't return back to 
OS for some reason.


Can these numbers be caused by memory fragmentation? There is 
probably a lot of small allocations (postgresql query, result 
processing and REST API json serialization).


We have similar problems, we see memory usage alternate between 
plateauing and then slowly growing. Until it hits the configured 
maximum memory for that job and the orchestrator kills it (we run 
multiple instances and have good failover).


I have reduced the problem by refactoring some of our gc usage, 
but the problem still persists.


On side-note, it would also be good if the GC can be aware of the 
max memory it is allotted so that it knows it needs to do more 
aggressive collections when nearing it.


Re: C++ or D?

2020-12-31 Thread Sebastiaan Koppe via Digitalmars-d-learn
On Thursday, 31 December 2020 at 16:03:54 UTC, Ola Fosheim 
Grøstad wrote:
On Thursday, 31 December 2020 at 14:56:37 UTC, Sebastiaan Koppe 
wrote:
It could take a few years indeed, but what will D do in that 
same time window?


What would you like to see?


For shared to mean something.
Stackless coroutines.
Compile-time lifetime management, i.e. better ways to define 
ownership.


Re: C++ or D?

2020-12-31 Thread Sebastiaan Koppe via Digitalmars-d-learn

On Thursday, 31 December 2020 at 09:57:01 UTC, Imperatorn wrote:

On Thursday, 31 December 2020 at 07:32:31 UTC, RSY wrote:
Sorry for the spam, but this is because of people like him 
that people like me (i discovered D recently) that can't be 
aware of why D is a great language


They diminish all arguments that makes D better than 
alternatives



You guys have to help me fight that kind of behavior, because 
it doesn't help D, as if it was their goal, do they want to 
make sure D doesn't eat specific market share, so some other 
language can? fishy fishy


But they should be aware that C++ *as a language* has a long 
way to go before it gets all the features etc that D has. Maybe 
2023, maybe 2027, who knows. Maybe that's fine for them, but 
not for me.


Au contraire; I find that C++ has modernised relatively 
successful and has a lot of great proposals in the pipeline. Of 
course they may all get rejected, but even if only some of them 
get accepted, C++ starts to have a leg up on D in my opinion.


It could take a few years indeed, but what will D do in that same 
time window?


Re: Writing a really fast lexer

2020-12-12 Thread Sebastiaan Koppe via Digitalmars-d-learn

On Saturday, 12 December 2020 at 18:15:11 UTC, vnr wrote:
Yes, I know Pegged, it's a really interesting parser generator 
engine, nevertheless, the grammar of what I would like to 
analyse is not a PEG. But I am also curious to know the 
performances of this tool for very large inputs.


The performance of pegged isn't great. Neither memory nor cpu 
wise. In many cases that is fine though, but if you are 
performance sensitive, you should look elsewhere.


I did a full JS grammar in pegged, but switched to a handwritten 
one when I realised its poor performance.


Re: Help on asdf json module

2020-10-25 Thread Sebastiaan Koppe via Digitalmars-d-learn

On Sunday, 25 October 2020 at 06:05:27 UTC, Vino wrote:

Hi All,

   Currently we are testing various json module such as 
"std.json, std_data_json, vibe.data.json and asdf", the below 
code works perfectely while use  "std_data_json or 
vibe.data.json" but not working as expected when we use "asdf" 
and throwing the below error, hence request your help on the 
same.


The API's are different. You can't just expect one to work with 
the api of the other.


Asdf is a bit more strict in that you have to specify whether you 
intent to iterate a json object (with `.byKeyValue()`) or a json 
array (with `.byElement()`).


Also the way you fetch values out of it is different. There is 
`.get!T(default)` that requires a default value in case it is 
empty (undefined), or `cast(T)field` if you assume there is a 
value and want an exception throw if not.




/+dub.sdl:
dependency "asdf" version="~>0.6.6"
+/
import std.stdio: writeln;
import asdf;
import std.conv: to;

void main()
{
 string apidata = 
`{"items":[{"name":"T10","hostname":"test1","type":[{"typeValue":"TD,d...@dev.com,DEVt"},{"typeno":"000"}]},{"name":"T11","hostname":"test2","type":[{"typeValue":"TF,q...@qas.com,QAS"},{"typeno":"100"}]},{"name":"T11","hostname":"test3","type":[{"typeValue":"TP,p...@prd.com,PRD"},{"typeno":"101"}]}]}`;

 auto jv = parseJson(apidata);
 foreach(j; jv["items"].byElement()){
writeln(j["name"].get!string("default"));
 }
}


Re: A scheduled control signal with fibers?

2020-09-25 Thread Sebastiaan Koppe via Digitalmars-d-learn
On Friday, 25 September 2020 at 13:08:16 UTC, Sebastiaan Koppe 
wrote:

On Friday, 25 September 2020 at 11:58:53 UTC, Ferhat Kurtulmuş
How can I implement schedulePWMSignalToValve(pwmval, 
afterNmilliseconds ) using fibers?


No need for fibers per se.


Can also use https://code.dlang.org/packages/timingwheels


Re: A scheduled control signal with fibers?

2020-09-25 Thread Sebastiaan Koppe via Digitalmars-d-learn
On Friday, 25 September 2020 at 11:58:53 UTC, Ferhat Kurtulmuş 
wrote:

int main(){
...

while(true){

int pwmval = getFlameIntensityViaImageProcessing();

sendPWMSignalToValfe(pwmval); // I need this streamed 
ctrl signal to the valfe with a delayed time shift


// a possible solution:
// enum afterNmilliseconds = 1500;

// schedulePWMSignalToValve(pwmval, afterNmilliseconds 
);


...
}
...
}

How can I implement schedulePWMSignalToValve(pwmval, 
afterNmilliseconds ) using fibers?


Thanks in advance.


No need for fibers per se.

You can run 2 threads. One that produces {time: now + 1500.msecs, 
value: getFlameIntensityViaImageProcessing} objects and one that 
consumes those and basically waits until each's msg.time < now 
and then sendPWMSignalToValfe(msg.value). You would basically 
rely on std.concurrency's MessageBox to do the queuing. Although 
you could do that manually as well.


Could also run it on 1 thread if you don't mind there being a 
jitter of however long getFlameIntensityViaImageProcessing takes, 
but you will need a queue.


Re: SIGUSR1 in clock_nanosleep()? how to isolate this issue?

2020-08-21 Thread Sebastiaan Koppe via Digitalmars-d-learn

On Thursday, 20 August 2020 at 18:58:43 UTC, mw wrote:

Hi,

I run into an issue: it's SIGUSR1 in clock_nanosleep()

[...]

Anyone has some suggestions on how to isolate this issue?

Thanks.


Try "handle SIGUSR1 nostop noprint" and "handle SIGUSR2 nostop 
noprint" in gdb.


Re: Vibe.d and NodeJs with Express

2020-07-12 Thread Sebastiaan Koppe via Digitalmars-d-learn

On Sunday, 12 July 2020 at 10:01:54 UTC, greatsam4sure wrote:
I am thinking of building an App with Vibe. D or NodeJS but my 
topmost priority is speed and ease of development due to third 
party libraries integration.


How much speed do you need? I doubt you really need every last 
millisecond, at which point ease of development takes over.  
Instead it might be better to look at which third party libraries 
you need. D has got most you need but you might end up needing 
something which isn't there. If you are ready to code that 
yourself then go for D for sure.


My question is can I eat my cake and have it if I go with Dlang 
and Vibe. D. I have being able to use jQuery and bootstrap with 
vibe. D and it work well.


If the app stays small that can work but you can also look at 
something a bit more modern. Angular, react, vue or svelte, there 
are plenty to pick from.


My believe is that most JavaScript library will work with Vibe. 
D out of the box.


Of course. You just end up writing an rest or graphql backend in 
D and connect it to a frontend.


Re: Web Assembly, struct to JavaScript Object and back

2020-06-24 Thread Sebastiaan Koppe via Digitalmars-d-learn

On Tuesday, 23 June 2020 at 18:15:25 UTC, tirithen wrote:

Anyone that has something similar working with struct objects?


Passing anything besides int/double/bool between JS and wasm is 
hard work.


Currently the ABI generated by LDC is so that arguments besides 
int/double/bool (and array/delegates are special too) are passed 
by pointer.


So if you want to call a wasm function that expects a struct, you 
instead pass a pointer to wasm memory where you have encoded that 
struct.


Similarly if you want to call a js function with rich objects you 
have to do some handling on the JS side.


Return values other than int/double/bool from wasm functions are 
special and it is expected that the function is called with a 
pointer as first argument.


There are a few gotcha but this basically describes it.

In https://github.com/skoppe/spasm I am using this approach as 
well. Except I don't actually move D struct to and from JS, 
instead only references to JS objects, strings, delegates, unions 
and arrays. Same principle applies though.


Re: called copy constructor in foreach with ref on Range

2020-06-23 Thread Sebastiaan Koppe via Digitalmars-d-learn

On Tuesday, 23 June 2020 at 07:30:29 UTC, Stanislav Blinov wrote:

On Tuesday, 23 June 2020 at 05:24:37 UTC, H. S. Teoh wrote:
I'm also wondering what's the motivation behind supporting 
non-copyable ranges, and whether it's worth the effort and 
inevitable complications to support it if it's a rare use-case.
 Do you have any compelling use-case in mind, that might make 
this worthwhile?


This compelling use case is staring at us from comments in this 
very thread.


I am a bit on the fence about having input ranges be 
non-copyable. Initially I liked the idea very much; I am a big 
fan of 'unique' semantics.


But just because most people don't expect hot/destructive reads, 
doesn't mean we should impose such a hard restriction on input 
ranges. There are use cases for popping from an input range from 
different places. An obvious one would be parsing data from the 
network, where you pass the input range into helper functions 
that parse sub-sections of the data.


They can be made to work for sure, but it doesn't make it cleaner.

On the other hand, most of the time, non-copyable is exactly what 
you need...


Re: how to achieve C's Token Pasting (##) Operator to generate variable name in D?

2020-05-31 Thread Sebastiaan Koppe via Digitalmars-d-learn

On Saturday, 30 May 2020 at 23:39:31 UTC, mw wrote:

Am I doing the right thing in D? any improvement you'd suggest?

e.g. I don't quite like have to put the type and var name in 
the quotes as string:


  mixin(RW!("int", "x"));

Is there a better way to achieve this? esp. for the type `int`, 
is there any way I don't have to quote it as string?


Thanks.


This would also be an option.

```
import std;

class Point {
struct Inner {
int x;
double y;
}
private Inner inner;
Point opDispatch(string name, T)(T value) {
mixin("inner."~name~" = value;");
return this;
}
auto opDispatch(string name)() {
mixin("return inner."~name~";");
}
}
void main()
{
Point b = new Point();
b.x(4).y(5.0);
writeln(b.x);
}
```


Re: D and Async I/O

2020-05-18 Thread Sebastiaan Koppe via Digitalmars-d-learn

On Thursday, 14 May 2020 at 09:36:33 UTC, Russel Winder wrote:
Whilst C frameworks use callbacks and trampolines, high level 
languages seem to be basing things on futures – or things that 
are effectively isomorphic to futures.


What I find most lacking is proper cancellation. Also, futures 
are eager.


Concurrency and parallelism will never be solved problems I 
suspect, but I think there is a fairly good consensus now on 
what is state of the art.


I haven't found a language that ticks all the boxes. Kotlin comes 
close.


I think there are a lot of lessons to be learned from all the 
efforts in the programming community.


We should:

- get stackless coroutines
- get structured concurrency
- steal as many idea from the C++'s executors proposal
(http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/p0443r13.html)


I am not convinced C++ has the best "state of the art" in this 
respect – after all it is just copying what JVM languages have 
had for ages, and Rust updated for modern native code languages.


I am not sure you have read the proposal. Initially I brushed it 
off, but upon closer inspection I realised there are some gems in 
there.


Re: D and Async I/O

2020-05-12 Thread Sebastiaan Koppe via Digitalmars-d-learn

On Tuesday, 12 May 2020 at 09:23:40 UTC, Russel Winder wrote:
On Mon, 2020-05-11 at 19:34 +0200, Jacob Carlborg via 
Digitalmars-d-learn wrote:

On 2020-05-11 16:44, Russel Winder wrote:

> Crickey, a third option. This wil increase my dithering! ;-)

Forth: Mecca [1] :)

[1] https://github.com/weka-io/mecca


Hummm… it seems everyone who needed async activity and 
particularly I/O in D has written their own. Mostly along with 
all their own data structures and algorithms library.


Yeah it is a shame, but you see it in almost every language. 
Probably means concurrency and io isn't a fully solved problem 
yet.


I keep trying to come back to D for GTK+ working, but in the 
end I keep going back to Python and Rust because D has no 
futures, and no added extras over GtkD auto translation of the 
GTK+ API to make it D-y in the way gtk-rs make GTK+ Rust-y.


Sorry for the apparent gloom, I just felt the need to tell it 
how I feel.


I think there are a lot of lessons to be learned from all the 
efforts in the programming community.


We should:

- get stackless coroutines
- get structured concurrency
- steal as many idea from the C++'s executors proposal 
(http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/p0443r13.html)


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

2020-03-17 Thread Sebastiaan Koppe via Digitalmars-d-learn
On Tuesday, 17 March 2020 at 18:55:08 UTC, Steven Schveighoffer 
wrote:
He's done a lot of stuff in Scratch. I taught him and a whole 
group of other homeschoolers a class on javascript and this 
year (up until this whole virus thing) we were working in 
Roblox (lua). So far I try to make the lessons not so much 
about the language or the environment, but the code concepts.


I don't really love the scratch methodology of dumbing down 
everything, I feel like it limits too much and doesn't help you 
enough to learn necessarily the parts of programming that 
transfer to all other programming languages. Yes, it has loops, 
yes it has data (though it's really convoluted), but it's not 
going to transfer to real-world coding. It looks like gamemaker 
is along the same lines "write games without ever having to 
code" seems like it defeats the purpose of what I'm trying to 
do ;)




Dont trust that marketing, there is actually decent scripting in 
gamemaker, which you'll need if you get creative.


Plus plenty of good example games that are also quite playable.



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

2020-03-17 Thread Sebastiaan Koppe via Digitalmars-d-learn
On Tuesday, 17 March 2020 at 15:38:55 UTC, Steven Schveighoffer 
wrote:
It's not something I'm intending to create professionally, 
really the impetus is my son wanting to do more significant 
game coding.


-Steve


How old is he?

I find something simple like gamemaker works well with 12-16 olds.


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

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


No resources but I remember the serpent framework mentioned on 
this forum here recently. It looks pretty decent.


https://github.com/lispysnake/serpent



Re: Idiomatic way to express errors without resorting to exceptions

2020-03-07 Thread Sebastiaan Koppe via Digitalmars-d-learn

On Saturday, 7 March 2020 at 15:44:38 UTC, Arine wrote:
I feel as though that's it's greatest weakness. It makes the 
check whether there is or isn't a value hidden. The case when 
there isn't a value should be handled explicitly, not 
implicitly. Propogating a None value isn't useful and is 
computationally demanding as each subsequent call will need to 
do a check to see if it has a value as it results in an 
optional type (for binary operators). So something like `a + b 
* c` is now much more expensive than it appears. This is 
exactly the kind of abuse of operator overloading that the 
feature is shunned for.


What can I say? If you don't like the semantics, don't use it. I 
have found value in it.


Anyways not sure what you mean here with the code below. If 
"first" here returns an optional type, you can't call 
"doSomething" like that without first checking if the value 
exists. Optional just doesn't allow it and Nullable will throw 
an exception.


```
list.first.doSomething(); // error
```


You are right. Nowadays you need a `.oc` call in between. Also, 
doSomething cannot be a free-standing function (sadly).


Re: Idiomatic way to express errors without resorting to exceptions

2020-02-29 Thread Sebastiaan Koppe via Digitalmars-d-learn

On Saturday, 29 February 2020 at 13:40:11 UTC, Adnan wrote:
On Saturday, 29 February 2020 at 13:03:21 UTC, Sebastiaan Koppe 
wrote:

On Saturday, 29 February 2020 at 12:50:59 UTC, Adnan wrote:
* Option!T from the optional package: Has even worse problem 
IMO. Not only it allows None + int but also it returns a 
`[]`. This API is not to my liking. You could say well 
Haskell has fmap for Optional etc, and I am aware of that, so 
does Rust with map etc. But I am talking about basic things: 
like `+`.


I would argue it is one of its strengths.


Doesn't that pretty much defeat the entire purpose of 
type-guarding a potentially error/absent value?


Like I said, I don't use optionals when I care about errors. That 
is not what they are designed for.


If I want to type-guard potential errors I will use SumType!(T, 
Error). It forces you to handle both cases, either at compile 
time (with the match template), or at runtime (with the tryMatch 
template).


The power of optionals, however, lies in the following:

```
list.first.doSomething();
```

Here doSomething will only be called when the list contains at 
least one item. Here I don't care about cases where the list is 
empty, I just want to doSomething if it isn't.


Re: Idiomatic way to express errors without resorting to exceptions

2020-02-29 Thread Sebastiaan Koppe via Digitalmars-d-learn

On Saturday, 29 February 2020 at 12:50:59 UTC, Adnan wrote:
* Option!T from the optional package: Has even worse problem 
IMO. Not only it allows None + int but also it returns a `[]`. 
This API is not to my liking. You could say well Haskell has 
fmap for Optional etc, and I am aware of that, so does Rust 
with map etc. But I am talking about basic things: like `+`.


I would argue it is one of its strengths.

Regardless, I don't think option/nullable/maybe is a good type 
for errors. Rather you should use something like SumType!(T, 
Error), or any other 'either' type.


Re: Some impressions/notes from a new D programmer

2020-02-12 Thread Sebastiaan Koppe via Digitalmars-d-learn
On Wednesday, 12 February 2020 at 18:39:36 UTC, Steven 
Schveighoffer wrote:

On 2/12/20 10:52 AM, mark wrote:

I also think you split into more HTML files which I prefer.


FYI, dlang.org has a secondary version of the docs which splits 
the documents up more:


https://dlang.org/library/index.html

I can't find a link to it directly from the main page though...

This version is based on ddox 
(http://code.dlang.org/packages/ddox)


-Steve


There is also devdocs.io

It has many languages and frameworks. The beauty is that it 
caches in local storage so searches are super fast and it is also 
available offline.


Their d version lags a tiny bit, but that is fine.


Re: Does D have an equvalent of: if (auto = expr; expr)

2020-02-07 Thread Sebastiaan Koppe via Digitalmars-d-learn

On Friday, 7 February 2020 at 08:52:44 UTC, mark wrote:

Some languages support this kind of thing:

if ((var x = expression) > 50)
  print(x, " is > 50")

Is there anything similar in D?


Yes and no.

It only works for bools or things that convert to bool.

You might have seen:

string[string] dict;
if (auto p = "key" in dict) {
  writeln(*p);
}

That works because the 'in' operator on aa's returns a pointer, 
which can be compared to bool.


Re: Mix struct types in the same array

2019-12-18 Thread Sebastiaan Koppe via Digitalmars-d-learn

On Wednesday, 18 December 2019 at 22:00:20 UTC, tirithen wrote:
I want to have a array/list/queue of instances of various 
struct types that represent events. How can I achieve that? 
With classes I would have interfaces I guess, but I want to use 
structs if possible as they seem less complex (and faster?).


Can I wrap each struct with in another struct called something 
like Entry that in turn can contain the event struct some how, 
or will that just move the problem?


If you know all types up front you can use the Sumtype library on 
code.dlang.org


Re: Troubleshooting DUB invocations

2019-11-19 Thread Sebastiaan Koppe via Digitalmars-d-learn

On Tuesday, 19 November 2019 at 12:06:36 UTC, Dukc wrote:
On Monday, 18 November 2019 at 19:35:13 UTC, Sebastiaan Koppe 
wrote:
Well yes. But that is just the way things worked up until now, 
ldc and dub just pick the host machine.


Luckily there is the new dub `--arch` argument that can take a 
llvm triple, in our case wasm32-unknown-unknown-wasm. This 
causes dub not to add the `--no-as-needed`.


That was news to me - I thought everything was always being 
compiled to WASM.


Well it is, but some versions from the host were still set. E.g. 
version(linux).


Except, that it also passes the triple upwards the dependency 
tree. Now all the dependencies of spasm get compiled targeting 
wasm. This is a good thing, except that the optional package 
which spasm depends on fails to compile with it. There is a 
newer version that fixes the configuration, but that one fails 
because of the `from.std` import idiom (it imports the std 
package from phobos which doesn't recognise wasm and fails 
with "Unknown OS").


I have sometimes thought that perhaps a static assert isn't the 
best thing to use for unimplemented features in Phobos, 
precisely because of this issue. A @disabled function stub 
would serve better, unless I'm missing something.


Either way, as long as there is a clear way to debug why it ended 
up there. Unlike what we have now where you need to dig endlessly.


"ending up"? If it's like what getting Phobos to work has been 
for me, you're continuing the game, not ending up playing it ;D.


Yeah it is a pain, and since wasm/betterc isn't tested (or 
barely), anyone is free to break it. E.g. the recent change to 
the std.range.chain function, which suddenly wasn't betterC 
anymore...


Another workaround that you can use right now is by adding the 
`--build-mode=allAtOnce` argument to dub. It effectively gets 
you the old behaviour. It is what I am using in my CI to get 
it to go green again.


Do not hurry more than you want -I already got my 
extract-dub-failure workaround working.


Sure, but stuff just needs to work. I updated the BUILDING.md 
file in spasm as well.


Re: Troubleshooting DUB invocations

2019-11-18 Thread Sebastiaan Koppe via Digitalmars-d-learn

On Wednesday, 13 November 2019 at 18:10:15 UTC, Dukc wrote:
On Wednesday, 13 November 2019 at 15:41:01 UTC, Sebastiaan 
Koppe wrote:
It has been on the back of my mind since 1.18-beta came out. I 
am going to reserve a little time tomorrow to work on it.


Regarding that, perhaps I can save you a bit trouble if you 
also try to get 1.19 working: if you get compile errors related 
to SortedRange, the fix is 
https://github.com/dlang/phobos/pull/7266.


I have had some time today to look into this. About the 
--no-as-needed:


TL;DR: add `--build-mode=allAtOnce` to the dub command.

Kinke made some changes in dub to facilitate separate linking for 
ldc. I am not aware of all the details but the major benefit is 
that it allows cross compilation with dub and ldc.


Because of the separate linking the --no-as-needed turned up. As 
far as I can see it is only needed when compiling for linux.


Which brings up the question, why linux? Aren't we compiling for 
wasm?


Well yes. But that is just the way things worked up until now, 
ldc and dub just pick the host machine.


Luckily there is the new dub `--arch` argument that can take a 
llvm triple, in our case wasm32-unknown-unknown-wasm. This causes 
dub not to add the `--no-as-needed`.


Except, that it also passes the triple upwards the dependency 
tree. Now all the dependencies of spasm get compiled targeting 
wasm. This is a good thing, except that the optional package 
which spasm depends on fails to compile with it. There is a newer 
version that fixes the configuration, but that one fails because 
of the `from.std` import idiom (it imports the std package from 
phobos which doesn't recognise wasm and fails with "Unknown OS").


In the end it is all caused by phobos and druntime not knowing 
anything about wasm. Which I am currently working on behind the 
scenes to fix.


In the meantime I am going to make a PR for the optional package 
to avoid the `from.std` idiom. Although I might end up playing 
whack-a-mole here, as there might be more dependencies that need 
a fix now.


Another workaround that you can use right now is by adding the 
`--build-mode=allAtOnce` argument to dub. It effectively gets you 
the old behaviour. It is what I am using in my CI to get it to go 
green again.


Re: Troubleshooting DUB invocations

2019-11-13 Thread Sebastiaan Koppe via Digitalmars-d-learn

On Tuesday, 12 November 2019 at 16:44:06 UTC, Dukc wrote:
When trying to compile a project including newest Spasm (DUB 
package) using the newest LDC via DUB, the result is:

```
lld: error: unknown argument: --no-as-needed
```

I then ran DUB with -v switch and it turned out the invocation 
contained `-L--no-as-needed` as first of all the -L arguments. 
The trouble is, how do I know what causes DUB to add that 
argument to the invocation? I could find no reason in 
`dub.` files of either my package, Spasm or any 
package in Spasm dependency tree.


I have seen this error as well. I actually test a few ldc 
versions on the CI, and I always test latest.


Currently anything higher than 1.17 is not supported, although it 
would probably require a small change.


Except for the fact that -mtriple gets propagated starting from 
1.18 to all dependencies (which is a good thing). This causes 
issues for some of the dependencies since they have no idea what 
wasm is.


It has been on the back of my mind since 1.18-beta came out. I am 
going to reserve a little time tomorrow to work on it.


Thanks for digging as far as you have.


Re: Dub and gitsubmodules

2019-11-06 Thread Sebastiaan Koppe via Digitalmars-d-learn

Thanks for the replies!


Dub and gitsubmodules

2019-11-04 Thread Sebastiaan Koppe via Digitalmars-d-learn
Does anyone know a reliable way of having a dub package that 
contains git submodules and is to be used as a dependency?


I am looking for a way to ensure the submodules are initialised 
before a build.


Re: Alternative to C++ macro in D

2019-11-03 Thread Sebastiaan Koppe via Digitalmars-d-learn
On Sunday, 3 November 2019 at 16:55:36 UTC, Vinod K Chandran 
wrote:

int main() {
log("Trying to avoid the visual clutter aused by closing 
curly braces") ;

string myStr = "Now, code looks more elegant" ;
log(myStr) ;
wait ;
end
How can i do this in D ? Especially the " #define end }; ". 
I've tried " alias end = } " but didn't worked.


You can't. D deliberately doesn't have a preprocessor. `#define 
end };` is one of the reasons.


Re: Mixin and introspection ordering

2019-10-16 Thread Sebastiaan Koppe via Digitalmars-d-learn

On Tuesday, 15 October 2019 at 19:50:33 UTC, Paul Backus wrote:
On Tuesday, 15 October 2019 at 19:19:58 UTC, Sebastiaan Koppe 
wrote:
You would expect 2 to print `tuple(a)` as well, but it 
doesn't. Don't know if it is a bug.


Any time you use a construct that mutates the AST (template 
mixin, string mixin, static if, static foreach), it's possible 
to catch it in both "before" and "after" states. For example:


This can cause some "interesting" things to happen when using 
templates like the ones in std.traits to do reflection, since 
the result of template instantiation is cached:


Wth the simple examples in this thread it can even be excused. 
However, when the mixin and the introspection are part of 
something larger it is no longer easily apparent.


I myself spend 30min wondering why it didn't work. And I wrote it 
myself.


Do we want to be able to catch things in their 'before' state? Or 
is it a bug?


Mixin and introspection ordering

2019-10-15 Thread Sebastiaan Koppe via Digitalmars-d-learn
Sometimes ordering is important when combining mixins and 
introspection, this is another such case:


```
import std.traits;

enum myuda;

mixin template Slot(string name) {
mixin("@myuda int "~name~";");
}

struct OuterOption {
mixin Slot!"a";
}

struct App {
pragma(msg, getSymbolsByUDA!(OuterOption, myuda).stringof); 
// 1. prints 'tuple(a)'
//  pragma(msg, getSymbolsByUDA!(InnerOption, myuda).stringof); 
// 2. prints '()'

struct InnerOption {
mixin Slot!"a";
}
pragma(msg, getSymbolsByUDA!(InnerOption, myuda).stringof); 
// 3. prints 'tuple(a)'

}
```

You would expect 2 to print `tuple(a)` as well, but it doesn't. 
Don't know if it is a bug.


Re: How to use xargs to remove whitespaces (Dub executable path)

2019-09-04 Thread Sebastiaan Koppe via Digitalmars-d-learn

On Wednesday, 4 September 2019 at 05:52:12 UTC, Andre Pany wrote:

Hi,

I try to get the executable path from a dub package using this 
command:


dub describe dscanner --data=target-path,target-name 
--data-list | xargs


But the output always contains a space between target-path and 
target-name:

/home/user/.dub/packages/dscanner-0.8.0/dscanner/bin/ dscanner

How can I get the full path without a space on a debian system 
in a 1 liner?


Kind regards
André


What about this?
dub describe scanner --data=target-path,target-name --data-list 
--data-0 | tr -d '\0'


or if you have jq installed:
dub describe dscanner | jq '.targets[0].buildSettings | 
"\(.targetPath)/\(.targetName)"'


Re: How should I sort a doubly linked list the D way?

2019-08-13 Thread Sebastiaan Koppe via Digitalmars-d-learn

On Tuesday, 13 August 2019 at 18:28:35 UTC, Ali Çehreli wrote:

On Tuesday, 13 August 2019 at 14:04:45 UTC, Sebastiaan Koppe
> wrote:
> Convert the nodes into an D array, sort the array with 
> nodes.sort!"a.x < b.x" and then iterate the array and repair 
> the next/prev pointers.


If possible, I would go further and ditch the linked list 
altogether: Just append the nodes to an array and then sort the 
array. It has been shown in research, conference presentations, 
and in personal code to be the fasted option is most (or all) 
cases.




Yeah, very likely. Although in this case there already is an 
array; it's going to be close :)


Re: How should I sort a doubly linked list the D way?

2019-08-13 Thread Sebastiaan Koppe via Digitalmars-d-learn
On Tuesday, 13 August 2019 at 09:48:52 UTC, Mirjam Akkersdijk 
wrote:
and I would like to sort based on Node.t, how should I tackle 
it, preferably without resorting to C libraries?


Convert the nodes into an D array, sort the array with 
nodes.sort!"a.x < b.x" and then iterate the array and repair the 
next/prev pointers.


Re: vibe / self contained standalone executable?

2019-07-28 Thread Sebastiaan Koppe via Digitalmars-d-learn

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

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

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


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


Haven't tested it, but something like this:

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

void handleRequest(scope HTTPServerRequest req, scope 
HTTPServerResponse res)

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

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

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

runApplication();
}
---

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


Re: vibe / self contained standalone executable?

2019-07-28 Thread Sebastiaan Koppe via Digitalmars-d-learn

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


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


Re: can not find the error: Error: TypeInfo cannot be used with -betterC

2019-07-17 Thread Sebastiaan Koppe via Digitalmars-d-learn

On Wednesday, 17 July 2019 at 15:52:39 UTC, Newbie2019 wrote:

when build my project with -betterC, it throw this error:

Error: TypeInfo cannot be used with -betterC

There is no location information about it,  how can I find what 
code cause this ?


With ldc I often use -v to get the verbose output of the 
compiler. It will output what module it is compiling and in what 
stage. Often the module right before the error is the one you'll 
need to examine. I know, it stinks.


Most often it is one of: arrays, ~=, typeid, throw, new, toString.


Re: Reading .pem files for secured

2019-06-06 Thread Sebastiaan Koppe via Digitalmars-d-learn

On Thursday, 6 June 2019 at 11:08:18 UTC, Dukc wrote:
We were both wrong :-). It turned out that the correct way to 
initialize a SecureD RSA private key is to feed contents of 
.pem in without ANY processing.


Ah, they made it even easier :)


Re: Reading .pem files for secured

2019-05-31 Thread Sebastiaan Koppe via Digitalmars-d-learn

On Friday, 31 May 2019 at 10:35:46 UTC, Dukc wrote:
The key pair needs to be persistant between, so I made a 
4096-bit private key with OpenSSL, stored in .pem file. Then I 
constructed a public key from the private one, again with 
OpenSSL. It seemed strange to me that I could generate a public 
key afterwards with the private key, instead of having to do 
both at the same time. I just thought that perhaps crypto is 
somehow cryptic enough to do that.


The public key can always be constructed from the private key.

But then came a problem that I need to feed the key from .pem 
to initialize RSA class.


Just base64 decode the PEM data (without the ) and feed it to 
RSA.this(ubyte[] publicKey). Ought to be that simple.


Disclaimer: I have only used openssl directly. No experience with 
SecureD.


Re: OT - Git training Lon/HK and book recommendation on taste in programming

2019-05-01 Thread Sebastiaan Koppe via Digitalmars-d-learn

On Wednesday, 1 May 2019 at 09:51:01 UTC, Laeeth Isharc wrote:

Hi.

First question - can anyone recommend git / Gitlab training 
providers in HK and London?  Two distinct audiences - highly 
intelligent people that may or may not really program, and 
experienced developers with a finance background that could 
benefit from knowing how to use git properly (finance is often 
in the dark ages).


Can't recommend anyone in particular, but I would recommend to do 
some interactive challenges at some point. Instruqt is a good 
one. It has a section on git. 
https://instruqt.com/public/topics/getting-started-with-git . It 
is fun and can give you insights who is picking up the material 
and who is lagging behind.


Second question.  Lots of people these days start to program to 
solve their problems at work but they may never have been shown 
the basic principles of design, structuring and maintenance of 
their code.  If I could give them one book (and a few YouTube 
links) what should it be ?


'Code Complete' is always good. And there are plenty of MIT 
courses online of course, like: 
https://www.youtube.com/watch?v=ytpJdnlu9ug=PLUl4u3cNGP63WbdFxL8giv4yhgdMGaZNA (6.0001 Introduction to Computer Science and Programming in Python. Fall 2016). Also, there are ones from the 80's, they have a certain quality, a certain rigor that I fail to find in more recent lectures.


Re: Operator Overloading with multiple return types

2019-03-15 Thread Sebastiaan Koppe via Digitalmars-d-learn

On Friday, 15 March 2019 at 21:35:12 UTC, eXodiquas wrote:

Is there any way to achive this behaivour with D2?


Yep. Just make the return type in the function declaration 
`auto`. You are then free to return a different type in each 
static branch.


Re: AliasSeq in UDA

2019-03-10 Thread Sebastiaan Koppe via Digitalmars-d-learn

On Sunday, 10 March 2019 at 16:46:43 UTC, Basile B. wrote:
Yes I see. I've refined a bit the test case and maybe I'll took 
a look this week.


Cool. Is it normal to create a testcase that doesn't depend on 
phobos? I suppose it is needed for it to be included in dmd's 
testcases.




Re: AliasSeq in UDA

2019-03-10 Thread Sebastiaan Koppe via Digitalmars-d-learn

On Sunday, 10 March 2019 at 13:41:32 UTC, Basile B. wrote:

It looks like a bug, a "reject-valid" one.
Try the same code with

enum A = 0;

and it work, despite of B being still opaque. The problem may 
be related to the fact the enum A in the orginal code is opaque 
and has not type.


Thanks. The example I posted was a reduced case, but I can still 
use your trick to fool the compiler.


The following is more real:

---

import std.meta;

enum A; enum B; enum Dummy = 0; // <- Dummy needs to be 0

struct Param(alias T) {}

@AliasSeq!(Dummy,Param!A,Param!B) // <- Here Dummy is needed
struct Foo {}

pragma(msg, __traits(getAttributes, Foo));

void main() {}

---

I have created an issue: 
https://issues.dlang.org/show_bug.cgi?id=19728


AliasSeq in UDA

2019-03-10 Thread Sebastiaan Koppe via Digitalmars-d-learn
The compiler complains about `cannot form tuple of tuples` 
whenever I try to put an AliasSeq in a UDA and try to use it.


You would expect the compiler to expand it. Is this a bug?

---

import std.meta;

enum A; enum B;

@AliasSeq!(A,B) // <-- Error: cannot form tuple of tuples
struct Foo {}

pragma(msg, __traits(getAttributes, Foo)); // <- must be present 
(error happens only when queried)


void main() {}

---

link to run.dlang.io: 
https://run.dlang.io/gist/cd5cd94d8ce5327e8a7d5ad77f1d15b8


Re: Phobos in BetterC

2019-03-09 Thread Sebastiaan Koppe via Digitalmars-d-learn

On Saturday, 9 March 2019 at 17:14:37 UTC, 9il wrote:
It was fixed to be used in BetterC. If it still does not work 
you can open an issue and ping me (@9il).


That is awesome. I suppose support for betterC is only from v3 
upwards?


Re: Phobos in BetterC

2019-03-09 Thread Sebastiaan Koppe via Digitalmars-d-learn

On Friday, 8 March 2019 at 09:24:25 UTC, Vasyl Teliman wrote:

Also I would to know what parts of Phobos are available there
(e.g. std.traits, std.typecons...).


There is no clear rule on which phobos packages work and which 
don't. It all depends on what underlying features the phobos 
package uses. Here is the list of what's not allowed in betterC:


- Garbage Collection
- TypeInfo and ModuleInfo
- Classes
- Built-in threading (e.g. core.thread)
- Dynamic arrays (though slices of static arrays work) and 
associative arrays

- Exceptions
- synchronized and core.sync
- Static module constructors or destructors

Generally anything meta/compile-time works. Packages like 
std.traits / std.meta / std.range / std.algorithm are not an 
issue. You would expect std.typecons.tuple to work as well, but 
it doesn't.


If you are doing ctfe, then you are in for a bummer. Because the 
same restrictions apply there as well. There is supposed to be a 
workaround by including the ctfe file in question via -I on the 
command line, but I could never make it work in dub.


If you encounter something that doesn't work, there are a couple 
of options. Sometimes the function you are trying to use is 
betterC compatible but is inside a package that isn't. Just 
extract it into a separate file. At other times it is because the 
struct has a toString method, or throws an exception. Again, copy 
the relevant part, rip out the toString method and/or replace the 
exception with an assert (of course, after you make sure the 
assert doesn't get triggered). There might also be the option to 
use @nogc exceptions (dip 1008), but I am not sure.


If all that isn't possible, you will have to rewrite the thing in 
question.


Re: pragma mangle on extern(C) in function body

2019-01-16 Thread Sebastiaan Koppe via Digitalmars-d-learn
On Wednesday, 16 January 2019 at 19:59:02 UTC, Steven 
Schveighoffer wrote:
I'm guessing it's a missed case in the compiler, and not 
intentionally omitted.


-Steve


The workaround is quite silly. Seems like a parser issue.

---
pragma(mangle, "Foo")
extern(C) void foo();

mixin template T()
{
pragma(mangle, "Bar")
extern(C) void bar();
}

void main() {
mixin T!();// Hurrah!
}
---



Re: pragma mangle on extern(C) in function body

2019-01-16 Thread Sebastiaan Koppe via Digitalmars-d-learn
On Wednesday, 16 January 2019 at 19:41:04 UTC, Sebastiaan Koppe 
wrote:
While it is perfectly ok to define an extern(C) function in a 
function method, I can't seem to get pragma(mangle, "...") on 
it to work.


---
pragma(mangle, "Foo")// Ok
extern(C) void foo();

void main() {
pragma(mangle, "Bar")// Error
extern(C) void bar();
}
---

Any idea why?


See also:

https://issues.dlang.org/show_bug.cgi?id=15843
https://issues.dlang.org/show_bug.cgi?id=17638
https://issues.dlang.org/show_bug.cgi?id=19149


pragma mangle on extern(C) in function body

2019-01-16 Thread Sebastiaan Koppe via Digitalmars-d-learn
While it is perfectly ok to define an extern(C) function in a 
function method, I can't seem to get pragma(mangle, "...") on it 
to work.


---
pragma(mangle, "Foo")// Ok
extern(C) void foo();

void main() {
pragma(mangle, "Bar")// Error
extern(C) void bar();
}
---

Any idea why?


Re: Why does nobody seem to think that `null` is a serious problem in D?

2018-12-01 Thread Sebastiaan Koppe via Digitalmars-d-learn
On Saturday, 1 December 2018 at 20:41:53 UTC, Sebastiaan Koppe 
wrote:
Since the compiler can prove which branch is taken, the analyse 
has to assume both are.


*can't*


Re: Why does nobody seem to think that `null` is a serious problem in D?

2018-12-01 Thread Sebastiaan Koppe via Digitalmars-d-learn

On Saturday, 1 December 2018 at 19:02:54 UTC, H. S. Teoh wrote:
But that's precisely the problem. It's not always possible to 
tell whether a variable has been initialized. E.g.:


int func(int x) {
int *p;

if (solveRiemannHypothesis()) {
p = 
}

...

if (solveArtinsConjecture()) {
*p++;
}
return x;
}


If you are willing to loose some precision you can still analyse 
this. Google abstract interpretation.


For instance, after the first if the value of p is ( || null). 
Since the compiler can prove which branch is taken, the analyse 
has to assume both are.


Inside the second if, p gets dereferenced, but since p is ( || 
null) - that is, it might be null - that is a compile time error.


The take away is that you don't need to know what code path will 
be taken, you just combine both states.


Re: How do I use null in a struct?

2018-11-10 Thread Sebastiaan Koppe via Digitalmars-d-learn

On Saturday, 10 November 2018 at 19:42:47 UTC, Václav Kozák wrote:
I'm making a Rest API with vibe.d and I have a struct User. 
Sometimes I need to return only a few of the fields. So for 
example: return User(1, null, "John", null, null, ...);
If I do this, an error occurs: cannot implicitly convert 
expression null of type typeof(null) to ...

Thanks.


You can use Optional like drug said, or you can use the @optional 
attribute [1].


@optional will leave the field in its .init state, whereas with 
Optional its easier to detect the null state.


[1] http://vibed.org/api/vibe.data.serialization/optional


Re: Need help with calling a list of functions

2018-11-04 Thread Sebastiaan Koppe via Digitalmars-d-learn

On Sunday, 4 November 2018 at 01:17:01 UTC, Luigi wrote:
I need to call a function that can create a function from an 
array of functions and calls them in reverse order.  I am 
learning D any help would be


That sounds a lot like std.functional.compose



Re: Template/mixin ideas?

2018-10-05 Thread Sebastiaan Koppe via Digitalmars-d-learn

On Thursday, 4 October 2018 at 01:12:04 UTC, Chris Katko wrote:
The mixin part wouldn't be slowed by strings, right? So the 
"slowness" is the invokation part which changes strings and 
forces GC allocations, I guess?

Yep, that is right.


What's the alternative to using strings... for strings?
During the concatenation phase you'll use an Appender. Afterwards 
you retrieve the resulting string from the appender. It is very 
similar to a StringBuilder in other languages.


See std.array.appender


Re: Template/mixin ideas?

2018-10-03 Thread Sebastiaan Koppe via Digitalmars-d-learn

On Wednesday, 3 October 2018 at 11:01:53 UTC, Chris Katko wrote:
I've got this simple task but I'm trying to perfect it as best 
I can to learn something in the process.


I have Linux terminal ASCII codes for coloring terminal output.

string red(string) { /* ... */ }

"Hello world".red => "\033[31mHello World\033[0m"

which translates to "[red]Hello World[reset to normal text]".

I have to do some slight trickery so I can chain them. But it 
all works fine. __The function is the same__ no matter what 
kind of color, bold, etc attribute I want. The only difference 
is the tag/prefix string.


So I have a table (or enum):
enum colors{
 reset = "\033[0m",
 red = "\033[31m",
 bold = "\033[1m" //...
 }

Absolute perfection would be some way to add a single line to 
that enum (or table) and magically get a new function. I add 
"blue" with its prefix code to the enum and immediately I can 
do:


"hello world".blue

Add yellow = "\033..." and I can do:

"hello world".bold.yellow

It's an interesting problem. Right now, I made a generic 
version that accepts the prefix code string directly called 
"color()" and red() translates to a call to color with the red 
string. blue() does the same. And so on. But it's still plenty 
of boiler plate. I do that so I don't have 80+ functions all a 
half-page long--which would be a nightmare to verify.


It's surely nothing mission critical. But I wonder if I can 
distill this simple problem down further, I may be able to 
learn some tricks for later problems.


Thanks.


A combination of static introspection with string mixins does the 
trick:


---
enum colors {
reset = "\033[0m",
red = "\033[31m"
}

auto GenerateColorFuncs() {
string result;
static foreach(c; __traits(allMembers, colors))
result ~= "auto "~c~"(string str) { return colors."~c~" ~ 
str ~ colors.reset; }";

return result;
}

mixin(GenerateColorFuncs());

void main()
{
import std.stdio;
writeln("bla".red);
}
---

Although you might want to replace the string concatenation with 
something more performant if used a lot.


Re: Template return type?

2018-10-03 Thread Sebastiaan Koppe via Digitalmars-d-learn
On Wednesday, 3 October 2018 at 10:01:02 UTC, Andrea Fontana 
wrote:

On Wednesday, 3 October 2018 at 09:37:29 UTC, JN wrote:
int i = returnDefault!int(); obviously works, but the point is 
I would like to skip the explicit type.


See: 
https://forum.dlang.org/post/ufhibwmouxpivjylq...@forum.dlang.org


See also:
https://forum.dlang.org/post/qmmjiofwmzqzdsgmv...@forum.dlang.org


Re: vibe.d error

2018-09-28 Thread Sebastiaan Koppe via Digitalmars-d-learn
On Thursday, 27 September 2018 at 17:37:43 UTC, hridyansh thakur 
wrote:

[snip]


What version of dmd do you use?


Re: tupleof function parameters?

2018-08-28 Thread Sebastiaan Koppe via Digitalmars-d-learn

On Tuesday, 28 August 2018 at 06:11:35 UTC, Jon Degenhardt wrote:
The goal is to write the argument list once and use it to 
create both the function and the Tuple alias. That way I could 
create a large number of these function / arglist tuple pairs 
with less brittleness.


--Jon


I would probably use a combination of std.traits.Parameters and 
std.traits.ParameterIdentifierTuple.


Parameters returns a tuple of types and ParameterIdentifierTuple 
returns a tuple of strings. Maybe you'll need to implement a 
staticZip to interleave both tuples to get the result you want. 
(although I remember seeing one somewhere).


Re: UDA on double nested struct

2018-08-20 Thread Sebastiaan Koppe via Digitalmars-d-learn

On Monday, 20 August 2018 at 16:27:55 UTC, Basile B. wrote:
Hello, it works fine here. Maybe there was another error that 
you removed when you have minimized the example. See 
https://run.dlang.io/is/ZrW7kI, that says that the example 
works since 2.068.2. Although that are are possibility that it 
was broken before a patch release, since only latest path of a 
minor release is tested on the site, in which case updating the 
compiler would fix the issue.


Wow, that is really nice, running all compilers at once. Thanks 
for showing that.


Anyway, I found out that the problem was that the `Hover` struct 
was named `hover` in my code. See https://run.dlang.io/is/3dLli6


In that case the inner hover takes precedence over the enum 
hover. Is that wanted behaviour? I would at minimum expect an 
ambiguity error.


UDA on double nested struct

2018-08-20 Thread Sebastiaan Koppe via Digitalmars-d-learn
Hey, I am trying to get UDAs from a doubly nested struct, to no 
avail:


code
---
import std.traits : hasUDA;
enum hover;

struct Style {
  struct Root {
auto margin = "10px";
auto backgroundColor = "white";
@hover struct Hover {
  auto backgroundColor = "gray";
}
  }
}
pragma(msg, hasUDA!(Style.Root.Hover, hover));
---

returns false. Bug or no? (Yes, I am generating css at compile 
time.)


Putting it on Root or on Style works as intended;


Re: ?? How to subscribe to Multicast Broadcasts ??

2018-08-18 Thread Sebastiaan Koppe via Digitalmars-d-learn

On Monday, 13 August 2018 at 01:12:16 UTC, Joe wrote:

Please Please Please Help, I am desperate!

Many Thanks in Advance for your time & attention,
-joe


I implemented multicast support in vibe.d, I hope looking at the 
source can help you:


https://github.com/vibe-d/vibe.d/blob/master/core/vibe/core/drivers/libevent2.d#L1129

Also, shouldn't both sending and receiving ports be the same?

Where I use it I call addMembership and then canBroadcast on a 
vibed socket, and it has worked for me.


It wouldn't be difficult to port that back to std.socket.


Re: Cannot make LDC use LTO when called via DUB

2017-09-25 Thread Sebastiaan Koppe via Digitalmars-d-learn

Neither

dflags-dmd "-xxx"
dflags-posix-dmd "-xxx"
dflags-linux-dmd "-xxx"

has any effect on my build (in dub.sdl).


I didn't know dflags-* was a thing, and I can't find it in docs 
either.


Maybe you are looking for

dflags "..." platform="..."


Re: Is there any threadsafe queue?

2017-09-14 Thread Sebastiaan Koppe via Digitalmars-d-learn

On Wednesday, 13 September 2017 at 22:54:06 UTC, Seb wrote:

https://code.dlang.org/packages/lock-free


That package has a single-reader single-writer queue, exactly 
what the OP asked for.





Re: How to make http requests to unix socket?

2017-08-12 Thread Sebastiaan Koppe via Digitalmars-d-learn

On Friday, 11 August 2017 at 18:39:54 UTC, dvnguyen wrote:
How to make http requests to unix socket? For example, in 
Docker engine api,


curl --unix-socket /var/run/docker.sock 
http:/v1.24/containers/json


I made a pull request a year ago or so to have vibe-d's 
requestHttp to support unix sockets. Call it like this 
`requestHTTP("https+unix://%2Fvar%2Frun%2Fdocker.sock/containers/create`.
You will need to set some vibe-d tls things to accept the 
connection.


Sönke just upgraded vibe-core/event-core to support it as well if 
I remember it correctly (so you can also use vibe 8.x with 
vibe-core).


As for endpoints which return streams (like 
containers/"~id~"/logs?stdout=1=1=1), Docker 
multiplexes stdout/stderr over http with chunked 
transfer-encoding.
The protocol is a 8 byte Header + Frame. The last four bytes in 
the Header is an uint32 representing the frame size. The first 
byte is either 1 -> stdout or 2 -> stderr, which designates the 
type of the stream in the following frame.


Re: Idiomatic way of writing nested loops?

2017-07-17 Thread Sebastiaan Koppe via Digitalmars-d-learn

On Monday, 17 July 2017 at 11:55:47 UTC, Anton Fediushin wrote:
Thank you! I knew it is in the library! So, `parallel` will 
work just fine with this function, isn't it?


Yes


Re: Idiomatic way of writing nested loops?

2017-07-17 Thread Sebastiaan Koppe via Digitalmars-d-learn

On Monday, 17 July 2017 at 11:07:35 UTC, Anton Fediushin wrote:
Hello! What is the best way of rewriting this code in idiomatic 
D manner?


https://dlang.org/phobos/std_algorithm_setops.html#.cartesianProduct


Re: Need simple sound

2017-07-07 Thread Sebastiaan Koppe via Digitalmars-d-learn

On Thursday, 6 July 2017 at 20:36:08 UTC, FoxyBrown wrote:
Heres a better version that automatically generates a class 
wrapping the portaudio.dll. Need portaudio.di(possibly renamed 
to portaudio.d and imported). Still same problem as original 
though.


While you are at it. Please also write compile time C 
preprocessor. (He said half jokingly.)


I tried your example. Unfortunately my windows dev setup is so 
far beyond repair, I could not get it to run. I am sorry but I 
can't help you.


Re: Need simple sound

2017-07-06 Thread Sebastiaan Koppe via Digitalmars-d-learn

On Thursday, 6 July 2017 at 13:28:26 UTC, FoxyBrown wrote:
On Wednesday, 5 July 2017 at 07:21:45 UTC, Sebastiaan Koppe 
wrote:

Sure, see http://code.dlang.org/packages/portaudio


So, after a bit of work I can get port audio to work but the 
callback never seems to be called(no audio, never hits bp). 
Shows all the devices and seems to run fine otherwise. Tried 
all the devices I I have. The default stream doesn't work 
either.


The example I posted earlier did work on my Mac.

I will try your example + dll loader on Windows later today. Nice 
loader btw.


Re: Need simple sound

2017-07-06 Thread Sebastiaan Koppe via Digitalmars-d-learn

On Thursday, 6 July 2017 at 10:47:53 UTC, FoxyBrown wrote:
On Wednesday, 5 July 2017 at 07:21:45 UTC, Sebastiaan Koppe 
wrote:

On Wednesday, 5 July 2017 at 05:34:37 UTC, FoxyBrown wrote:
On Tuesday, 4 July 2017 at 20:37:44 UTC, Sebastiaan Koppe 
wrote:

Portaudio is simple as well. And nice cross platform.


are there any bindings?


Sure, see http://code.dlang.org/packages/portaudio


I can't seem to get this to work. Are there any windows dll's 
or libs that work that are not outdated?


I have found dlls here 
https://github.com/spatialaudio/portaudio-binaries


Re: unittest-cov - results?

2017-07-06 Thread Sebastiaan Koppe via Digitalmars-d-learn

On Wednesday, 5 July 2017 at 19:01:06 UTC, Jonathan M Davis wrote:
I ran into a bug in dub not all that long ago where the tests 
in the module with main in it weren't actually being run even 
though the other tests were. (which reminds me, I should verify 
that again and report it).


- Jonathan M Davis


Noticed it as well couple of months ago. I think dub just skips 
the mainSourceFile defined in the dub.sdl (default: source/app.d) 
to avoid having 2 mains.


It is annoying especially for small projects where you would only 
have app.d. Especially if you don't have a clue what is going on.


Re: Need simple sound

2017-07-05 Thread Sebastiaan Koppe via Digitalmars-d-learn
On Wednesday, 5 July 2017 at 09:43:05 UTC, Martin Tschierschke 
wrote:
On Wednesday, 5 July 2017 at 07:21:45 UTC, Sebastiaan Koppe 
wrote:

On Wednesday, 5 July 2017 at 05:34:37 UTC, FoxyBrown wrote:
On Tuesday, 4 July 2017 at 20:37:44 UTC, Sebastiaan Koppe 
wrote:

Portaudio is simple as well. And nice cross platform.


are there any bindings?


Sure, see http://code.dlang.org/packages/portaudio


Sorry, for that question but now, as I have several different 
options -
all not 'overdocumented' -  so what would be the shortest 
possible D program waiting for input and playing a sound from a 
file in parallel?


Something short like the single-file dub example...?

#!/usr/bin/env dub
/+ dub.sdl:
name "hello"
+/
void main() {

 writef("Do you like the music?");
  char[] answer;
  answer = readln();
  writef("This was your Answer: ", answer);

}


This one plays a wav file. Couldn't get dub to do single-file on 
it. It kept giving linker errors. (Took example from 
https://github.com/v--/portaudio/blob/master/examples/pa_test.d)


**dub.sdl
name "audio"
description "plays audio file"
authors "Sebastiaan Koppe"
dependency "portaudio" version="==1.0.0"
dependency "wave-d" version="~>1.0.6"

configuration "executable" {
  mainSourceFile "audio.d"
  targetType "executable"
}

**audio.d
import std.stdio;
import waved;
import deimos.portaudio;
import std.conv, std.stdio;
import std.algorithm : min;

struct Audio {
float* samples;
size_t frames;
size_t position;
}

extern(C) int callback(const(void)* inputBuffer, void* 
outputBuffer,

 size_t framesPerBuffer,
 const(PaStreamCallbackTimeInfo)* 
timeInfo,

 PaStreamCallbackFlags statusFlags,
 void *userData)
{
auto pout = cast(float*)outputBuffer;
Audio* audio = cast(Audio*)userData;

enum vol = 0.2f;
size_t frames = min(audio.frames - audio.position, 
framesPerBuffer);


foreach(i; 0 .. frames)
*pout++ = vol * audio.samples[i + audio.position];
foreach(i; frames .. framesPerBuffer)
*pout++ = 0;

audio.position += framesPerBuffer;
return frames == framesPerBuffer ? paContinue : paComplete;
}

int main()
{
PaStream* stream;
PaError err;

Sound input = decodeWAV("my_wav_file.wav");
string answer;

auto audio = Audio(input.samples.ptr, input.samples.length);

if ((err = Pa_Initialize()) != paNoError) goto Lerror;

if ((err = Pa_OpenDefaultStream(,
0,
input.channels,
paFloat32,
cast(double)input.sampleRate,
paFramesPerBufferUnspecified,
,
))
!= paNoError) goto Lerror;

if ((err = Pa_StartStream(stream)) != paNoError) goto Lerror;

writef("Do you like the music?");
answer = readln();
writefln("This was your Answer: %s", answer);

if ((err = Pa_StopStream(stream)) != paNoError) goto Lerror;
if ((err = Pa_CloseStream(stream)) != paNoError) goto Lerror;
if ((err = Pa_Terminate()) != paNoError) goto Lerror;

return 0;
 Lerror:
stderr.writefln("error %s", to!string(Pa_GetErrorText(err)));
return 1;
}


Re: Need simple sound

2017-07-05 Thread Sebastiaan Koppe via Digitalmars-d-learn

On Wednesday, 5 July 2017 at 05:34:37 UTC, FoxyBrown wrote:

On Tuesday, 4 July 2017 at 20:37:44 UTC, Sebastiaan Koppe wrote:

Portaudio is simple as well. And nice cross platform.


are there any bindings?


Sure, see http://code.dlang.org/packages/portaudio


Re: Need simple sound

2017-07-04 Thread Sebastiaan Koppe via Digitalmars-d-learn
On Monday, 3 July 2017 at 08:55:20 UTC, Martin Tschierschke 
wrote:
Hello for a simple game I would like to add some very simple 
sound, not much different than the beeps of "PAC Man". Is there 
anything I can use for this?


Portaudio is simple as well. And nice cross platform.


Re: Deprecated std.c.*.socket and missing replacement

2017-06-27 Thread Sebastiaan Koppe via Digitalmars-d-learn
On Tuesday, 27 June 2017 at 19:22:02 UTC, Steven Schveighoffer 
wrote:
Just delete the duplicate symbol, and add public imports of the 
other module symbols.


e.g.:

public import core.sys.posix.netinet.in_: IP_ADD_MEMBERSHIP;

-Steve


Great. Will do.


Re: Deprecated std.c.*.socket and missing replacement

2017-06-27 Thread Sebastiaan Koppe via Digitalmars-d-learn

On Tuesday, 27 June 2017 at 17:58:29 UTC, Jonathan M Davis wrote:
Why would you need to remove anything from Phobos? The enum in 
question is in a deprecated module. All that should need to 
happen is that the enum be added to the appropriate module in 
druntime, and then any code that uses it can import it from 
there.


- Jonathan M Davis


Except that the deprecated module (std.c.posix.socket) imports 
the module where I would like to add them 
(core.sys.posix.netinet.in_), resulting in duplicated symbols. 
Therefor they need to be removed.




Re: Deprecated std.c.*.socket and missing replacement

2017-06-27 Thread Sebastiaan Koppe via Digitalmars-d-learn

On Tuesday, 27 June 2017 at 11:16:17 UTC, Jonathan M Davis wrote:
Create a PR to add it to druntime and/or define it in your own 
code.


- Jonathan M Davis


Creating a PR sounds reasonable. But I would have to create one 
PR to remove them from phobos and one PR to add them to druntime, 
right? (I need to remove them since the phobos socket modules 
import the druntime ones, create duplicates if not removed)


I see that std.c.windows.winsock simply publicly imports 
core.sys.windows.winsock2, that looks like a good approach.


Deprecated std.c.*.socket and missing replacement

2017-06-27 Thread Sebastiaan Koppe via Digitalmars-d-learn
I am building a multicast application, and I am using the 
std.c.*.socket modules to provide the definition of the 
IP_ADD_MEMBERSHIP constant.


These modules are marked as deprecated telling me to look in 
core.sys.posix.* instead.


I grepped the complete sourcetree, but nowhere is the 
IP_ADD_MEMBERSHIP constant defined other than in the deprecated 
modules.


What to do?


Re: Dub and unit-threaded import problem

2016-03-05 Thread Sebastiaan Koppe via Digitalmars-d-learn

On Saturday, 5 March 2016 at 15:05:50 UTC, Casey wrote:

{
"name": "unittest",
"preBuildCommands": [
"dub run unit-threaded -c gen_ut_main -- -f  bin/ut.d"
],
"mainSourceFile": "bin/ut.d",
"excludedSourceFiles": ["source/app.d"],
"dependences": {
"unit-threaded": "~>0.6.3"
}
}


If dub is complaining about not finding bin/ut.d, You need a 
"importPaths": ["bin"] in there. Dub by default only looks in the 
source folder, and it cannot find `bin/ut.d` in `./source`. If 
that is the case you also need to remove the `source` part from 
the excludedSourceFiles.


Here is a config that works for me

{
"name": "unittest",
"preBuildCommands": ["dub run unit-threaded -c gen_ut_main -- 
-f bin/ut.d"],

"importPaths": ["bin"],
"mainSourceFile": "bin/ut.d",
"excludedSourceFiles": ["app.d"],
"dependencies": {
"unit-threaded": "~>0.6.3"
}
}


Re: Coverage

2016-02-16 Thread Sebastiaan Koppe via Digitalmars-d-learn
On Tuesday, 16 February 2016 at 12:35:38 UTC, Leandro Motta 
Barros wrote:
You probably already though of it, but: can't you create a 
unittest that calls your code as many times as desired, passing 
different input each time?


That is a viable option yes. I will probably end up doing it like 
that.


I don't like it though. Since the input is pretty big, it would 
need to be kept in an external file. And I don't like my 
unittests reading files. Plus they aren't really unittests 
either. Oh well. Moving on.


Coverage

2016-02-16 Thread Sebastiaan Koppe via Digitalmars-d-learn

I currently run dmd's coverage on my unittests.

But now I also want to execute my program with different inputs 
and then merge all that coverage info from each run.


Any chance there is something for that?


Re: htod question

2016-01-23 Thread Sebastiaan Koppe via Digitalmars-d-learn
On Friday, 22 January 2016 at 01:04:50 UTC, Dibyendu Majumdar 
wrote:
On Friday, 22 January 2016 at 01:03:09 UTC, Dibyendu Majumdar 
wrote:

On Friday, 22 January 2016 at 00:52:59 UTC, W.J. wrote:

Counter question: What's so bad about the D std library ?


I am trying to create bindings for existing C library so I was 
trying to use htod for that.


The library includes various C header files ... causing htod to 
fail


Yeah, htod often requires preparing the files your trying to 
convert. Often removing macro's and the like. Its a manual 
process, and it can get dirty.


Re: Is this a feature?

2016-01-21 Thread Sebastiaan Koppe via Digitalmars-d-learn

On Thursday, 21 January 2016 at 14:39:43 UTC, Adam D. Ruppe wrote:
On Thursday, 21 January 2016 at 14:35:09 UTC, Sebastiaan Koppe 
wrote:
	static if (!is(SomethingUndefined!moreUndefined[0] : 
UndefinedThing))


Yes, the is expression returns false for undefined things 
because they aren't types. The standard library uses this in a 
lot of places to test for undefined functions, like checking 
for features in ranges. (The is expression has been around a 
lot longer than __traits btw)


Thanks. I reckoned as much. Can be handy in places. But I just 
spend some time figuring out that I was missing an import...


Is this a feature?

2016-01-21 Thread Sebastiaan Koppe via Digitalmars-d-learn

module undefined;

unittest
{
	static if (!is(SomethingUndefined!moreUndefined[0] : 
UndefinedThing))

{
pragma(msg,"This will compile just fine!");
}
}


Re: Reset all Members of a Aggregate Instance

2015-12-03 Thread Sebastiaan Koppe via Digitalmars-d-learn

On Thursday, 3 December 2015 at 21:13:59 UTC, Nordlöw wrote:
Need to assert that not a function and mutability 
(std.traits.isMutable)


Yeah you need to do that.


Re: Reset all Members of a Aggregate Instance

2015-12-03 Thread Sebastiaan Koppe via Digitalmars-d-learn

Haven't compiled but it should look something like this:

foreach(member; __traits(allMembers, typeof(c)))
__traits(getMember, c, member) = typeof(__traits(getMember, 
c, member)).init;




Re: vibe.d-example illustrating Dynamic Textual Web-Interface

2015-12-01 Thread Sebastiaan Koppe via Digitalmars-d-learn

On Tuesday, 1 December 2015 at 07:04:25 UTC, Sönke Ludwig wrote:

Am 30.11.2015 um 11:08 schrieb Nordlöw:
Does anybody have a similar vibe.d-project to be inspired 
from, in this

regard?


This would be more targeted to the web interface generator 
(vibe.web.web), which is not affected by the changes mentioned 
above, but the interface is pretty similar. For a very simple 
example, you can have a look at this:

https://github.com/rejectedsoftware/vibe.d/tree/master/examples/web_ajax


I have seen a lot of sites using this approach. I feel that once 
complexity increases (more dynamics, popups, real-time 
validation, spa) it runs into some maintenance issues.


Let me elaborate. In the beginning all html is generated on the 
server. Then more features are added and slowly more html is 
generated/manipulated in the client. Now you have this 
split-brain were html is generated both on the server and the 
client, but both in different languages, with different template 
engines. To put it simply, it doesn't scale well.


The solution would be to shift the generation of html to the 
client (for example see trello, digital ocean, etc.). The only 
issue there is that the first page load takes longer. This can be 
solved by rendering the first page on the server. With nodeJS 
this is easy since you can reuse the same code, with D this is a 
little harder.


Re: Can't understand how to do server response with vibed

2015-11-30 Thread Sebastiaan Koppe via Digitalmars-d-learn

On Sunday, 29 November 2015 at 07:37:56 UTC, Suliman wrote:
On Saturday, 28 November 2015 at 23:21:21 UTC, Sebastiaan Koppe 
wrote:

On Saturday, 28 November 2015 at 19:05:59 UTC, Suliman wrote:
And also I can't understand difference between 
HTTPClientRequest and HTTPServerRequest


If the application (vibe.d) makes a request, it is the client. 
If the request is made to your application, it is the server.


In your case your angular app is the client, and your vibe.d 
app is the server. Therefor, HTTPServer(Request|Response).


Could you explain me about: HTTPServerRequest and HTTPRequest. 
I can't understand difference.


No idea. Probably HTTPRequest provides common functionality for 
both HTTPServerRequest and HTTPClientRequest. Just guessing.


Re: vibe.d-example illustrating Dynamic Textual Web-Interface

2015-11-30 Thread Sebastiaan Koppe via Digitalmars-d-learn

On Monday, 30 November 2015 at 10:08:17 UTC, Nordlöw wrote:

Can somebody please show a enlightening example of, so called,

"revamp of the REST interface generator"

added to release 0.7.26 at:

http://vibed.org/blog/posts/vibe-release-0.7.26

I want to use vibe.d to add a modern dynamic web-interface to 
my knowledge graph I'm currently developing.


More specifically I would like an interface that makes rich use 
of dynamic HTML. When the user changes the contents of a 
search/command-line text-field the client logic shall on the 
fly (after a certain delay) lookup related information with 
vibe.d-server and present the user with relevant hits or 
completions in a another part of page (HTML div-block).


Does anybody have a similar vibe.d-project to be inspired from, 
in this regard?


I have written a mpd (Music Player Daemon) client in D and just 
finished the web app (bar a couple of features).


All of the rendering is done on the client and only json data is 
transmitted between server and web app. Just finished the 
WebSocket part so if anybody changes the music/volume/playlist, 
all clients update the interface.


The code could use a cleanup/refactoring but everything is 
working.


The D parts of interest are the MpdApiInterface1 and MpdApi1 
classes in source/app.d


For the JS parts you can start with source/index.js, but its full 
of ES6 classes and react code. So that might not be your cup of 
tea. In index.js there are mainly React Classes (basically html 
renderers) and React Container Classes (basically code handling 
input changes).


In the source/actions folder there are some js files that call 
the server and modify state (volume/song). In the source/stores 
folder, some js files that only retrieve data.


The js architecture if influenced by react/flux/facebook's, but I 
am toying with it to see what fits for me. Specifically I rely a 
lot on RxJS for the observables.


For the project I decided to put js and d files in the same 
folders. That might not have been a good idea. Also dub has some 
issues with one of the D dependencies that I haven't updated in 
months.


Code can be found here: https://bitbucket.org/skoppe/mpc/src


Re: vibe.d-example illustrating Dynamic Textual Web-Interface

2015-11-30 Thread Sebastiaan Koppe via Digitalmars-d-learn

On Monday, 30 November 2015 at 20:23:48 UTC, David DeWitt wrote:
Have you looked at Redux and Webpack?  I am working on a Redux 
example and we have switched to Webpack and Redux at work and 
it is nice.


I know about both yes. Webpack would probably beat browserify, 
but I haven't gotten the time to migrate myself. Their hot code 
reloading looks good though.


Isn't redux the client side for GraphQL? I followed it a bit but 
it being so fresh, decided to wait.


A GraphQL interface generator for vibe.d would be nice.


  1   2   >