Re: ioctl to set mixer volume

2021-04-16 Thread Boris Carvajal via Digitalmars-d-learn

On Saturday, 17 April 2021 at 00:05:41 UTC, Alain De Vos wrote:

After some fiddling i finally got it.
A d-lang program which sets my volume to zero.
```
import std.stdio;
import core.sys.posix.ioctl;
import core.stdc.config;
import core.stdc.stdio;
void main() {
writeln("Set vol to min");
char *mixerdev=cast(char *)"/dev/mixer";
char *mode=cast(char *)"rw";
int mixfd=(fopen(mixerdev,mode)).fileno;
writeln(mixfd);
c_ulong x=3221507328;
int left=0;
ioctl(mixfd,x, );
}
```
The function .fileno returns the "underlying handle" of the 
FILE "object".


Here you could avoid C stdio and just use posix functions like 
`core.sys.posix.fcntl

 : open` that returns a file descriptor directly.


Re: Does is(f == function) work?

2021-03-09 Thread Boris Carvajal via Digitalmars-d-learn

On Tuesday, 9 March 2021 at 11:58:45 UTC, Andrey Zherikov wrote:

On Tuesday, 9 March 2021 at 02:57:46 UTC, Adam D. Ruppe wrote:

try

is(typeof(f) == function)

it is kinda weird but that's the trick


Thanks!
Should it work for in this case as well?

alias f = (){};

writeln(typeof(f).stringof);// prints "void function() 
pure nothrow @nogc @safe"


writeln(is(typeof(f) == function)); // prints "false"


Not quite straightforward, but "void function()" is actually a 
pointer to function, you need to dereference it first:


is(typeof(*f) == function)


Re: How can I check if template variable parameter is iterable before handle it?

2021-02-21 Thread Boris Carvajal via Digitalmars-d-learn

On Sunday, 21 February 2021 at 11:58:11 UTC, Marcone wrote:

import std;

void foo(T)(T bar){
	static if (bar.isiterable()) // Need Somethin to check if bar 
is iterable.

{
// Execute it if bar is iterable.
foreach (i; bar)
{

}
}
else {
// Execute it if bar is NOT iterable.
}

}

void main(){
foo(1);
foo([1, 2, 3, 4, 5]);
}


https://dlang.org/library/std/traits/is_iterable.html

import std.traits : isIterable;

void foo(T)(T bar){
static if (isIterable!T)
{
...


Re: Constructor called instead of opAssign()

2021-02-16 Thread Boris Carvajal via Digitalmars-d-learn

On Sunday, 14 February 2021 at 08:46:34 UTC, frame wrote:

The first instance is in A - and why opAssign then works there?


Sorry I didn't pay too much attention.

It seems the detection of first assignment only happens when the 
field and constructor have the same parent, so it doesn't work 
either if the field is from a base or derived class (your case by 
means of casting 'this').


I don't think this is intended rather it appears to be a 
bug/deficiency in the constructor flow analysis of DMD, which 
from what I'm reading is very rudimentary.


Re: Constructor called instead of opAssign()

2021-02-14 Thread Boris Carvajal via Digitalmars-d-learn

On Sunday, 14 February 2021 at 07:09:20 UTC, frame wrote:
Although x is well initialized by A by calling opAssign(), the 
compiler doesn't care and calls the S!T ctor() on B again and 
opAssign() is ignored. Is this a bug or a rule?


It's a rule described here: 
https://dlang.org/spec/struct.html#field-init


"In a constructor body ... the first instance of field assignment 
is its initialization."


If you assign a second time, it will use the opAssign method.


Re: How to profile compile times of a source code?

2021-01-31 Thread Boris Carvajal via Digitalmars-d-learn

On Sunday, 31 January 2021 at 16:13:24 UTC, Anonymouse wrote:

On Sunday, 31 January 2021 at 12:31:59 UTC, Johan Engelen wrote:
Try LDC 1.25 (now in beta testing) with --ftime-trace. Clang 
has the same option, so you can read more about it online in 
that context. Be sure to check out the related commandline 
flags.
I recommend the Tracy UI to look at traces, because it is by 
far the fastest viewer of large traces. 
https://github.com/wolfpld/tracy


-Johan


Does ldc produce traces in a format that Tracy supports? I 
can't seem to open the generated *.time-trace files with it. 
(tracy 0.7.5-1 installed from Arch Linux AUR.)


Use the 'import-chrome' tool bundled in Tracy to convert it.


Re: DMD: invalid UTF character `\U0000d800`

2020-11-09 Thread Boris Carvajal via Digitalmars-d-learn

On Sunday, 8 November 2020 at 10:47:34 UTC, Per Nordlöw wrote:

Can I just do, for instance,

cast(dchar)0xd8000

for

`\Ud800`

to accomplish this?


There's also:

dchar(0xd8000)


Re: Bind C++ class to DLang : undefined reference to `Canvas::Foo()'

2020-07-13 Thread Boris Carvajal via Digitalmars-d-learn

On Monday, 13 July 2020 at 16:17:55 UTC, zoujiaqing wrote:

On Monday, 13 July 2020 at 12:57:52 UTC, Adam D. Ruppe wrote:

On Monday, 13 July 2020 at 09:34:35 UTC, zoujiaqing wrote:

# dmd source/main.d Canvas.o -L-lstdc++ && ./main
[1]49078 segmentation fault  ./main


On my computer I got this warning out of the compiler:

libstdc++ std::__cxx11::basic_string is not yet supported; the 
struct contains an interior pointer which breaks D move 
semantics!



sounds like it might be a known limitation.


Thanks Adam, but D link to C++ very hard?


Can you try passing -D_GLIBCXX_USE_CXX11_ABI=0 to g++ and 
-version=_GLIBCXX_USE_CXX98_ABI to dmd.


That comes from: 
https://dlang.org/changelog/2.088.0.html#std_string


C++11 ABI is currently not supported.


Re: final switch problem

2020-06-13 Thread Boris Carvajal via Digitalmars-d-learn

On Saturday, 13 June 2020 at 09:02:21 UTC, John Chapman wrote:
Is this a bug or have I made a mistake? This worked a few days 
ago and I haven't changed my setup since then.


https://issues.dlang.org/show_bug.cgi?id=19548

Your code triggers it by using "-debug" option on 
https://run.dlang.io/ using DMD


Re: Postblit segfault.

2020-06-01 Thread Boris Carvajal via Digitalmars-d-learn

On Monday, 1 June 2020 at 06:35:36 UTC, MaoKo wrote:

Hello, I don't understand why this code segfault on


Reduced to:

import std.stdio;

struct S {}

void main() {
  S[1] s;
  writeln(s);
}


Re: Is it possible to write some class members in another module ?

2020-05-19 Thread Boris Carvajal via Digitalmars-d-learn

On Tuesday, 19 May 2020 at 22:01:03 UTC, Vinod K Chandran wrote:

Hi all,
Is it possible to write some class members in another module ? 
I have class with a lot of member variables.(probably 50+) I 
would like to write them (Not all, but some of them) in a 
special module for the sake of maintenance.


You can use Template Mixins to add variable declarations in 
others scope.


https://dlang.org/spec/template-mixin.html


Re: Linear array to matrix

2020-04-04 Thread Boris Carvajal via Digitalmars-d-learn
On Saturday, 4 April 2020 at 09:25:14 UTC, Giovanni Di Maria 
wrote:

Hi.
Is there a Built-in function (no code, only a built-in function)
that transform a linear array to a Matrix?

For example:

From

[10,20,30,40,50,60,70,80,90,100,110,120];


To

[
[10,20,30],
[40,50,60],
[70,80,90],
[100,110,120]
];

Thank You very much
Cheers.
Giovanni


If you're really sure about the array and matrix dimensions/types.
You can use a cast:

int[] a = [10,20,30,40,50,60,70,80,90,100,110,120];

    int[3][] m1 = cast(int[3][]) a;
    writeln(m1);

A better way is using the function chunks;

import std.range;

    auto m2 = a.chunks(3);
    writeln(m2);



Re: need help to get member function const address

2020-03-19 Thread Boris Carvajal via Digitalmars-d-learn
On Thursday, 19 March 2020 at 14:43:53 UTC, Steven Schveighoffer 
wrote:
I think this is an invalid limitation, you should file an issue 
at https://issues.dlang.org


essentially, with your sample A struct:

const f1 =  // OK
const f2 =  // Error, not constant expression

Both these should be valid,  is not a delegate, but a 
function pointer.


-Steve


https://issues.dlang.org/show_bug.cgi?id=20687
https://github.com/dlang/dmd/pull/10946


Re: need help to get member function const address

2020-03-19 Thread Boris Carvajal via Digitalmars-d-learn

On Thursday, 19 March 2020 at 04:30:32 UTC, Calvin P wrote:

I use this code to get member function address on runtime:

=
struct A {
   this(){};
}
auto ctor = (&__traits(getMember, A.init,"__ctor")).funcptr;
=


my question is, how to get it in compile time like static 
function address


You asked the same question two days ago.
Check the reply.
https://forum.dlang.org/post/r4ohd3$2e94$1...@digitalmars.com

You can assemble a delegate with an struct pointer or class 
reference and a function member pointer.


Re: Using std.net.curl

2020-02-28 Thread Boris Carvajal via Digitalmars-d-learn
On Saturday, 29 February 2020 at 03:53:37 UTC, David Anderson 
wrote:


I want to capture that text in a variable, but the upload 
function returns void. How can I get the text returned by the 
web server to be stored in a variable?


import std;

auto updata = read("inputfile");
auto dldata = put("https://postman-echo.com/put;, updata);
writeln(dldata);


Re: How to get to body of HTTP 500 error with std.net.curl.get()?

2020-02-15 Thread Boris Carvajal via Digitalmars-d-learn

On Friday, 14 February 2020 at 00:24:27 UTC, Gregor Mückl wrote:

Hi!

I am trying to write a client for pretty... well... creatively 
designed web API. The server gives HTTP status 500 replies if 
the requests are malformed, but the actual error message is 
hidden in the body of the reply (an XML document!). 
std.net.curl.get() throws an exception in this case. But I 
would like to get the body to process the error message within. 
How can I do that?


Thanks in advance,
Gregor


It seems you can't, that simple get wrapper is very limited.
Better create you own get function, example:

import std;

ushort get(string url, ref ubyte[] content)
{
auto cont = appender();
auto http = HTTP();
http.method = HTTP.Method.get;
http.url = url;
http.onReceive = (ubyte[] data)
{
cont ~= data;
return data.length;
};
HTTP.StatusLine status;
http.onReceiveStatusLine = (HTTP.StatusLine s) { status = s; 
};

http.perform();
return status.code;
}

void main()
{
ubyte[] data;
auto scode = get("http://dlang.org/asdf;, data);
if (scode == 404)
{
// data has the body
...
}


Re: static foreach over enum symbols

2020-02-15 Thread Boris Carvajal via Digitalmars-d-learn

On Friday, 14 February 2020 at 22:24:14 UTC, Ben Jones wrote:

Hi all,

I'm getting unexpected results while trying to process symbols 
from a module, some of which are enums.


Depending on whether or not I comment out the first static 
foreach loop below, fullyQualifiedName gives me different 
results in the second loop.


Looking more in detail it seems there is another peculiarity 
happening here, it could be that a template instance get reused 
(issue 14501). Not sure if it's really a bug or by design.



https://issues.dlang.org/show_bug.cgi?id=14501


Re: static foreach over enum symbols

2020-02-15 Thread Boris Carvajal via Digitalmars-d-learn

On Friday, 14 February 2020 at 22:24:14 UTC, Ben Jones wrote:

Hi all,

I'm getting unexpected results while trying to process symbols 
from a module, some of which are enums.


Depending on whether or not I comment out the first static 
foreach loop below, fullyQualifiedName gives me different 
results in the second loop.


In either case, I'm surprised I can't grab the UDAs in the 
second static foreach loop.  Any ideas what's going on?


Test case:
---a.d---
module a;

@Object
enum x = "hello";

@Object
enum y = "goodbye";

@Object
struct z{}


---main.d---

template symbols(alias Mod){
import std.meta;
alias toSymbol(alias T) = __traits(getMember, Mod, T);
alias symbols = staticMap!(toSymbol, __traits(allMembers, 
Mod));

}


void main(){
import std.traits;
import std.meta;
import a;
//commenting this out changes the results below
static foreach(sym; symbols!a){
pragma(msg, fullyQualifiedName!sym);
pragma(msg, __traits(getAttributes, sym));
}

pragma(msg, "\nget with UDAs\n");
pragma(msg, getSymbolsByUDA!(a, Object));
alias udaSyms = getSymbolsByUDA!(a, Object);
pragma(msg, staticMap!(fullyQualifiedName, udaSyms));
static foreach(us; udaSyms){
pragma(msg, fullyQualifiedName!us);
pragma(msg, __traits(getAttributes, us));
}
}

---

annotated output of dmd main.d:

with the first loop commented out:

get with UDAs

tuple("hello", "goodbye", (z))
tuple("a.x", "a.y", "a.z")
a.x
tuple()  //why is the UDA gone?
a.y
tuple()
a.z
tuple((Object))


and with the first loop:

object
tuple()
main.main.sym  //it's not a.x anymore, it's the name of the 
local var for static foreach?

tuple()
main.main.sym
tuple()
a.z
tuple((Object))

get with UDAs

tuple("hello", "goodbye", (z))
tuple("main.main.sym", "main.main.sym", "a.z") //and the 
results are changed here too?

main.main.sym
tuple()
main.main.sym
tuple()
a.z
tuple((Object))


From language spec [1]: "the name of the static foreach variable 
is bound to the i-th entry of the sequence, either as an enum 
variable declaration (for constants) or an alias declaration (for 
symbols).


Enums are treated differently, so your 'sym' is not an alias to 
the original enum but an enum itself with the same value. Because 
of that, fullyQualifiedName or any template with alias argument 
will just get the sym temporary not the enum from the symbols 
tuple.



This code should work:

static foreach(i, _; symbols!a){
 pragma(msg, fullyQualifiedName!(symbols!a[i]));
 // or manually aliased, but you need to use regular 
foreach or {{ }} to avoid redefinitions.

 alias sym = symbols!a[i];
 pragma(msg, fullyQualifiedName!sym);
  }


[1] https://dlang.org/spec/version.html#staticforeach


Re: Assoc array init

2020-02-04 Thread Boris Carvajal via Digitalmars-d-learn

On Tuesday, 4 February 2020 at 07:52:05 UTC, JN wrote:

int[int] a = [5: 7];

void main()
{
}


This fails because apparently [5: 7] is a "non-const 
expression". How? Why?


Yes, I know I can just init in a static this() section, but 
that feels like a bad workaround.


AFAIK is not implemented.
https://dlang.org/spec/hash-map.html#static_initialization


Re: module ... conflicts with package name ...

2020-02-03 Thread Boris Carvajal via Digitalmars-d-learn
On Monday, 3 February 2020 at 16:35:06 UTC, Steven Schveighoffer 
wrote:
I can't reproduce with a small example. Before I try and go 
through the process to reduce this, just wanted to see if 
anyone knows about this.


-Steve


I've made a few changes to the package.d import code, one is 
pending. If you can reduce it to a test case I'll check it 
promptly.


Re: How add resource.res in RDMD

2020-02-02 Thread Boris Carvajal via Digitalmars-d-learn

On Monday, 3 February 2020 at 03:03:20 UTC, Marcone wrote:

On Sunday, 2 February 2020 at 06:03:06 UTC, Marcone wrote:
I like use rdmd when I am programming. But I need that the 
program use resource file becouse I am creating program with 
gui win32api. How can I add resource when use rdmd?


No one knows how add resource .res file in rdmd?


Just pass the .res file before your .d source, like:

rdmd myresource.res main.d

Of course first you need to compile the .rc file with rc.exe 
program from the Visual Studio toolchain or windres.exe of Mingw.


Re: Defining an alias to an overloaded function

2020-01-20 Thread Boris Carvajal via Digitalmars-d-learn

On Monday, 20 January 2020 at 22:02:54 UTC, olvy wrote:
I'm learning D, and as an exercise, I'm trying to define a 
HashSet that would be a wrapper around an associative array 
with some dummy value type.


This seems to work:

...
struct RangeImpl(T) {
alias byKeyRetType = 
typeof(byKey!(int[T])((int[T]).init));

byKeyRetType keyRange;
this(ref int[T] d) {
keyRange = d.byKey;
}
bool empty() {
return keyRange.empty;
}
...
}

RangeImpl!T opSlice() {
return RangeImpl!T(_dict);
}
}

void main()
{
...
if (h[].all!(nn => nn < 5)) {
writeln("less than 5");
}



Re: CTFE and assoc array

2020-01-18 Thread Boris Carvajal via Digitalmars-d-learn

On Saturday, 18 January 2020 at 20:54:20 UTC, Andrey wrote:

Hello,

Why this doesn't work?


import std;

struct Qwezzz
{
shared static this()
{
qaz = qazMap;
}

enum qazMap = ["rrr": "vv", "hty": "4ft6"];
static immutable string[string] qaz;
}

void main()
{
enum sorted = Qwezzz.qaz.keys.sort();
}


The variable "qaz" is static immutable and doesn't work in CTFE.


There 3 issues here:

1. "shared static this()" is a runtime construct.

2. You can't initialize a static AA right now
https://dlang.org/spec/hash-map.html#static_initialization
Only "aa = null;" works.

3. CT and RT AA internals are different.

But you can get a workaround, more info
https://forum.dlang.org/post/egrcolfiqpuplahpo...@forum.dlang.org


Re: import/format tools?

2020-01-18 Thread Boris Carvajal via Digitalmars-d-learn

On Saturday, 18 January 2020 at 09:33:34 UTC, mark wrote:
Is there a tool that will sort imports (e.g., as per the style 
guide), and that will also add the specific names used?


D-Scanner[1] will warn you about non sorted imports

You need to set imports_sortedness="enabled" on your dscanner.ini 
file.

then:
dscanner --styleCheck 

Also, is there a D source formatting tool (ideally with options 
to set a max line length and choice of braces style)?


Check dfmt[2]

Is there any runtime (or compiletime) cost to just listing 
imports at the start of a file without listing the specific 
functions?


AFAIK there is no difference at least for now. The imported 
module have to be loaded and parsed completely, on the other hand 
selective imports don't pollute the symbol table.



Is there any advantage to doing imports inside functions,


Yes, if you do the import inside a template and this is not 
instantiated the import never happens and you save precious 
compilation time, the same with function templates. This is 
really important, if you look at phobos code you can see the 
tendency to reduce to the very specific case the import statement.



or to listing specific imports?


It's always better to import more specific modules vs complete 
packages like importing std.algorithm.sorting instead of 
std.algorithm but there are a lot of stuff required between some 
modules that we are talking about milliseconds of difference, 
however using D you get used to fast compile times that you lose 
patience if the thing takes longer than one second.


[1] https://github.com/dlang-community/D-Scanner
[2] https://github.com/dlang-community/dfmt


Re: Get memory used by current process at specific point in time

2020-01-16 Thread Boris Carvajal via Digitalmars-d-learn

On Sunday, 12 January 2020 at 13:58:18 UTC, Per Nordlöw wrote:
Is there a druntime/phobos function for getting the amount of 
memory (both, stack, malloc, and GC) being used by the current 
process?


At least for the GC I remember using GC.stats and GC.profileStats 
to get some info.


https://dlang.org/phobos/core_memory.html#.GC


Re: template instantiation problems

2020-01-14 Thread Boris Carvajal via Digitalmars-d-learn

On Friday, 10 January 2020 at 18:31:59 UTC, ag0aep6g wrote:


import m1 = foo.baz;
import m2 = foo;
alias p = __traits(parent, m1);

pragma(msg, m1.stringof); /* "module baz", ok */
pragma(msg, m2.stringof); /* "module foo", ok */
pragma(msg, p.stringof); /* "package foo", ok */

enum e(alias thing) = thing.stringof;

pragma(msg, e!m1); /* "module baz", ok */
pragma(msg, e!m2); /* "module foo", ok */
pragma(msg, e!p); /* "module foo", wat?? */



Thanks for your test case.

https://github.com/dlang/dmd/pull/10724



Re: PHP to D Conversion

2019-10-19 Thread Boris Carvajal via Digitalmars-d-learn

On Saturday, 19 October 2019 at 19:08:45 UTC, Vino wrote:

On Friday, 18 October 2019 at 14:56:05 UTC, Andre Pany wrote:

On Friday, 18 October 2019 at 09:21:46 UTC, Vino wrote:

On Friday, 18 October 2019 at 09:17:24 UTC, Vino wrote:

[...]


And now getting the error : Program exited with code 
-1073741819


Hi,

Maybe port 8080 is blocked, because there is an instance of 
your application running on the background. Just check by 
changing the port in the source code.


Kind regards
Andre


Hi Andre,

  Tried with different ports still no luck getting this error : 
Program exited with code -1073741819.


From,
Vino.B


Your program is crashing probably because you are dereferencing a 
null/ dangling pointer.
Build your program in debug mode and run it in a debugger, that 
way you will get a backtrace telling you the exactly line of the 
code when it happens.


Re: Vibe.d Error

2019-10-18 Thread Boris Carvajal via Digitalmars-d-learn

On Friday, 18 October 2019 at 08:06:30 UTC, Vino wrote:
  I tried install vibe.d in SUSE linux 12 SP2 and facing the 
below error, tried the options as per the link 
https://github.com/vibe-d/vibe.d/issues/1748, still no luck and 
the lib's are installed in the server




Read the last section of the readme 
https://github.com/vibe-d/vibe.d/blob/master/README.md#switching-between-openssl-versions


SUSE 12 use openssl 1.0.x version but Vibe.d is trying to link to 
1.1, try putting in your dub file:


subConfiguration "vibe-d:tls" "openssl-1.0"


Re: How to find what is causing a closure allocation

2019-10-02 Thread Boris Carvajal via Digitalmars-d-learn

On Wednesday, 2 October 2019 at 15:19:43 UTC, John Colvin wrote:
I have a function that allocates a closure somewhere in it (as 
shown by the result of -profile=gc).


I can't make the function nogc as it calls a lot of other GC 
using code.


profilegc.log only gives me the line number of the function 
signature, which doesn't give me any hint as to where in the 
function the closure is allocated.


Anyone have any nice tricks to help narrow this down.


This hack seems to show the detailed info of @nogc also in normal 
code.



diff --git a/src/dmd/func.d b/src/dmd/func.d
index 832cd0bf7..e1fad8cdc 100644
--- a/src/dmd/func.d
+++ b/src/dmd/func.d
@@ -1975,7 +1975,7 @@ extern (C++) class FuncDeclaration : 
Declaration

 else
 {
 printGCUsage(loc, "using closure causes GC 
allocation");

-return false;
+//return false;
 }

 FuncDeclarations a;




Re: Inspecting __traits(isDeprecated) and deprecation warnings

2019-09-25 Thread Boris Carvajal via Digitalmars-d-learn

On Wednesday, 25 September 2019 at 14:20:00 UTC, Anonymouse wrote:
I added some deprecations in my project and am going through my 
templates trying to silence the warnings that suddenly popped 
up. This template works, but it triggers deprecation warnings 
when I am actively trying to avoid them.


This code seems to work for classes too and even with DMD "-de" 
compiler switch.


template isMemberDeprecated(T, string name)
{
enum isMemberDeprecated = mixin(q{__traits(isDeprecated, }, 
T, ".", name, q{)});

}

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




Re: Why is the fPIC switch missing?

2019-09-23 Thread Boris Carvajal via Digitalmars-d-learn

On Monday, 23 September 2019 at 01:31:03 UTC, Emmanuelle wrote:
Hello. My problem is exactly what it says on the title: my dmd 
(windows 7, x64) doesn't seem to have -fPIC:


I think it's not needed. The generated code on Windows is always 
position independent.


Still, DMD should warn about it and keep compiling like GCC, not 
fail miserably.


Re: Throwing from a lambda isn't supported by the compiler

2019-09-09 Thread Boris Carvajal via Digitalmars-d-learn

On Monday, 9 September 2019 at 09:14:08 UTC, Andre Pany wrote:

Hi,

I noticed, that I cannot throw from the lambda expression:
  Error: expression expected, not throw
but have to use the longer syntax () {throw new Exception();}

---
void foo(void function() e){}

void main()
{
foo(
() => throw new Exception()
);
}
---

The shorter lambda syntax would be more readable in my case.
Is there a reason why it isn't allowed or should I create an
enhancement request?

Kind regards
André


Well, the shorthand syntax "=>" implies a return, but you can 
only return an expression and throw is a statement.


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


Re: Function called twice

2019-08-02 Thread Boris Carvajal via Digitalmars-d-learn

On Friday, 2 August 2019 at 21:44:28 UTC, Jordan Wilson wrote:

Hello,

I don't quite understand why isEven is called twice in the 2nd 
example?


auto isEven(int n) {
n.writeln;
return (n % 2) == 0;
}

void main() {

auto z = [1,2,3];

// outputs 1 2 3
z.map!(a => tuple!("number")(a))
 .filter!(a => a.number.isEven)
 .array;

// outputs 1 2 2 3
z.map!(a => tuple!("number","iseven")(a, a.isEven))
 .filter!(a => a.iseven)
 .array;

return;
}

Thanks,

Jordan


The way map is designed is to call its predicate on each front 
call and filter calls it twice with the number 2.

https://github.com/dlang/phobos/blob/master/std/algorithm/iteration.d#L604

You can use "cache" to avoid the double front call on any range.

z.map!(a => tuple!("number","iseven")(a, a.isEven))
 .cache
 .filter!(a => a.iseven)
 .array;



Re: Why does a switch break cause a segmentation fault

2019-07-23 Thread Boris Carvajal via Digitalmars-d-learn

On Tuesday, 23 July 2019 at 08:04:07 UTC, adamgoldberg wrote:

On Tuesday, 23 July 2019 at 00:01:09 UTC, Exil wrote:

On Monday, 22 July 2019 at 22:05:17 UTC, adamgoldberg wrote:
Hey, I just happened to be writing a program in D an stumbled 
upon a bug, that causes it to terminate after receiving a 
SEGV signal, nothing wierd so far but it looks everything I 
tried shows it is the break statement inside of a switch.
It seems to have a relatively random chance of occuring, and 
also somewhat dependant on the compiler, and build mode used.
I'm short on time so instead of rewriting my SO post I will 
just link it.


Here! 
https://stackoverflow.com/questions/57153617/random-segmentation-fault-in-d-lang-on-switch-break


Hope someone can help!


Could be the statement in the actual switch(), which is 
accessing a pointer "codecpar".


switch (stream.codecpar.codec_type)
^

This could be null and you aren't checking for it. I find that 
D sometimes doesn't have the correct line numbers for debug 
info, even when not doing an optimized build. So it could 
really be anything in that function.


The root cause could be a lot of things though, some bad 
codegen or otherwise. Could add a check to make sure though.


I ran the program after adding

   enforce (stream.codecpar != null);

and nothing changed, and by nothing I mean that DMD in debug 
mode still doesnt crash but DMD in release does (like 70% of 
the time), I think its more important to address that issue 
because I can't seem to find any explenation of this behaviour, 
yet it occurs.


The struct AVStream is different on the D side (avformat.d) than 
the original C header, at least on my PC using ffmpeg 4.1.4.


So instead of getting codecpar member we get some unrelated data 
and dereferencing it can crash the program.


I tried using the DPP project, it errors out but the generated 
file is almost there, just commenting 1 line and changing some 
not found type pointer member to void pointer I got a working 
example with your same code.


Here is the updated struct part, the program will run fine with 
this layout.


struct AVStream
{
int index;
int id;
AVCodecContext* codec;
void* priv_data;
AVRational time_base;
c_long start_time;
c_long duration;
c_long nb_frames;
int disposition;
AVDiscard discard;
AVRational sample_aspect_ratio;
AVDictionary* metadata;
AVRational avg_frame_rate;
AVPacket attached_pic;
AVPacketSideData* side_data;
int nb_side_data;
int event_flags;
AVRational r_frame_rate;
char* recommended_encoder_configuration;
AVCodecParameters* codecpar;
static struct _Anonymous_9
{
c_long last_dts;
c_long duration_gcd;
int duration_count;
c_long rfps_duration_sum;
double[399]** duration_error;
c_long codec_info_duration;
c_long codec_info_duration_fields;
int frame_delay_evidence;
int found_decoder;
c_long last_duration;
c_long fps_first_dts;
int fps_first_dts_idx;
c_long fps_last_dts;
int fps_last_dts_idx;
}
_Anonymous_9 _anonymous_10;
auto last_dts() @property @nogc pure nothrow { return 
_anonymous_10.last_dts; }
void last_dts(_T_)(auto ref _T_ val) @property @nogc pure 
nothrow { _anonymous_10.last_dts = val; }
auto duration_gcd() @property @nogc pure nothrow { return 
_anonymous_10.duration_gcd; }
void duration_gcd(_T_)(auto ref _T_ val) @property @nogc 
pure nothrow { _anonymous_10.duration_gcd = val; }
auto duration_count() @property @nogc pure nothrow { 
return _anonymous_10.duration_count; }
void duration_count(_T_)(auto ref _T_ val) @property 
@nogc pure nothrow { _anonymous_10.duration_count = val; }
auto rfps_duration_sum() @property @nogc pure nothrow { 
return _anonymous_10.rfps_duration_sum; }
void rfps_duration_sum(_T_)(auto ref _T_ val) @property 
@nogc pure nothrow { _anonymous_10.rfps_duration_sum = val; }
auto duration_error() @property @nogc pure nothrow { 
return _anonymous_10.duration_error; }
void duration_error(_T_)(auto ref _T_ val) @property 
@nogc pure nothrow { _anonymous_10.duration_error = val; }
auto codec_info_duration() @property @nogc pure nothrow { 
return _anonymous_10.codec_info_duration; }
void codec_info_duration(_T_)(auto ref _T_ val) @property 
@nogc pure nothrow { _anonymous_10.codec_info_duration = val; }
auto codec_info_duration_fields() @property @nogc pure 
nothrow { return _anonymous_10.codec_info_duration_fields; }
void codec_info_duration_fields(_T_)(auto ref _T_ val) 
@property @nogc pure nothrow { 
_anonymous_10.codec_info_duration_fields = val; }
auto frame_delay_evidence() @property 

Re: Is this a new bug ?

2019-07-20 Thread Boris Carvajal via Digitalmars-d-learn

On Saturday, 20 July 2019 at 09:01:47 UTC, Newbie2019 wrote:

On Saturday, 20 July 2019 at 09:01:21 UTC, Newbie2019 wrote:
I want to cast std.stdio : writefln into pure function 
pointer, so I can call it from debug pure function.  is there 
a way to work around the pure check for call  writefln ?


nothrow check, not pure.


Use try and catch around writefln.

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


Re: OPTLINK : Warning 9: Unknown Option : OUT

2019-07-16 Thread Boris Carvajal via Digitalmars-d-learn

On Tuesday, 16 July 2019 at 09:07:03 UTC, Anonymouse wrote:
This works for the reduced test program but not for my whole 
project. If you wouldn't mind trying it:


git clone https://github.com/zorael/kameloso.git && cd 
kameloso && dub test


(Windows 10, dmd 2.087 with your sed substitution)

I'll try dustmiting it later tonight.


The debugger exposes a crash in memchr from C runtime.

In file messaging.d line 216 called from the unittest just below


if (emoteTarget.beginsWithOneOf(state.client.server.chantypes))


chantypes.ptr is null. However chantypes.length is 1 so you are 
assigning something invalid to it.



grep -nr "chantypes = " kameloso/


shows this place as something to care about
kameloso/source/kameloso/irc/parsing.d:1983:   chantypes = value;



Re: OPTLINK : Warning 9: Unknown Option : OUT

2019-07-15 Thread Boris Carvajal via Digitalmars-d-learn

On Monday, 15 July 2019 at 11:48:13 UTC, Anonymouse wrote:

I built it with:

dub fetch digger
dub run digger -- build "stable + druntime#2675"


I have not touched any digger.ini. The only one I can find is 
digger.ini.sample.


sc.ini and dub output at:

https://pastebin.com/jPnh4yEA


dub test was invoked with:
dub test 
--compiler=C:/cygwin/home/zorael/work/result/bin/dmd.exe -v


I seem to get the same errors from a Cygwin terminal as from a 
cmd one.


I'll give you another option if you just need that fix.
Patch your phobos64.lib in the original dmd install directory 
using cygwin and sed, just run this exact command on cygwin 
prompt, editing the path to your case:


sed -bi 's/%zu): /%llu):/' /c/d/dmd2/windows/lib64/phobos64.lib

you can patch the 32bit libs if you need them.
Then just run dub without "--compiler=" option to use your 
original dmd.


Re: Windows segfault, need brief help

2019-07-14 Thread Boris Carvajal via Digitalmars-d-learn

On Saturday, 13 July 2019 at 16:39:51 UTC, Anonymouse wrote:


Thank you!

Filed as https://issues.dlang.org/show_bug.cgi?id=20048.


https://github.com/dlang/druntime/pull/2675


Re: Windows segfault, need brief help

2019-07-13 Thread Boris Carvajal via Digitalmars-d-learn

On Friday, 12 July 2019 at 22:46:11 UTC, Anonymouse wrote:
I'm suddenly getting segfaults when running tests on Windows. 
It works fine on Linux. I reduced it to a few lines (plus a 
dependency) with dustmite, but they don't really make sense[1]. 
Nevertheless they do trigger the segfault.


Can someone with Windows 10 and dmd 2.087.0 try the following 
and see if it crashes please?


git clone https://github.com/zorael/tests -b wintestcrash && 
cd tests && dub test


I can reproduce it on Win10/x64 (qemu).
But it's really hard to debug on windows (at least with dmd and 
no V.Studio), I could only get a readable backtrace with "WinDbg 
Preview" debugger:


[0x0]   msvcr100!_output_l + 0x41e
[0x1]   msvcr100!printf + 0x7c
[0x2]   test!int 
core.runtime.runModuleUnitTests().__foreachbody1(object.ModuleInfo*) + 0xd1
[0x3]   test!int object.ModuleInfo.opApply(scope int 
delegate(object.ModuleInfo*)).__lambda2(immutable(object.ModuleInfo*)) + 0x27
[0x4]   test!int rt.minfo.moduleinfos_apply(scope int 
delegate(immutable(object.ModuleInfo*))).__foreachbody2(ref 
rt.sections_win64.SectionGroup) + 0x54
[0x5]   test!int rt.minfo.moduleinfos_apply(scope int 
delegate(immutable(object.ModuleInfo*))) + 0x1f
[0x6]   test!int object.ModuleInfo.opApply(scope int 
delegate(object.ModuleInfo*)) + 0x27

[0x7]   test!runModuleUnitTests + 0xfe
...
msvcr100!_output_l+0x41e:
`62e0346e 443811   cmp  byte ptr [rcx],r10b 
ds:`0010=??

Registers are: rcx = 0x0010, r10 = 0x
it seems like ( str[i] == '\0')

So the program try to print from an invalid pointer and the 
StackTrace/Throwable object is somewhat related.


Re: How to mixin finction name?

2019-04-14 Thread Boris Carvajal via Digitalmars-d-learn

On Sunday, 14 April 2019 at 12:00:38 UTC, Andrey wrote:

On Sunday, 14 April 2019 at 11:44:16 UTC, Boris Carvajal wrote:

On Sunday, 14 April 2019 at 10:07:30 UTC, Andrey wrote:

I want to mixin only name - not the full function code.


I think you can't do a partial statement in a mixin.
But this works by declaring pointers to functions and assigning a 
function literal to them.


import std.stdio;
void main()
{
    auto dg = (uint i){ writeln('a' , " - ", i); };
     enum letters = ['A', 'B', 'C'];
     static foreach(ch; letters)
 {
         mixin("void function(uint i) print" ~ ch ~ ";");
         dg = (uint i){ writeln(ch , " - ", i); };
         mixin("print" ~ ch ~ " = dg;");
     }

 printA(1);
 printB(2);
 printC(3);
}


Re: How to mixin finction name?

2019-04-14 Thread Boris Carvajal via Digitalmars-d-learn

On Sunday, 14 April 2019 at 10:07:30 UTC, Andrey wrote:
Create some function in loop and use it. But I don't know how 
to mixin names?



import std.stdio;
void main()
{
 enum letters = ['A', 'B', 'C'];
 static foreach(ch; letters)
 {
 mixin("void print" ~ ch ~ "(uint i) { writeln('" ~ ch ~ 
"', \" - \", i); }");

 }

 printA(1);
 printB(2);
 printC(3);
}


Re: Issues with std.net.curl on Win 10 x64

2019-03-25 Thread Boris Carvajal via Digitalmars-d-learn

On Monday, 25 March 2019 at 16:25:37 UTC, cptgrok wrote:
Am I doing something wrong or is there some issue with curl or 
something else? I'm pretty new to D and I'm not sure if I need 
to go right down to raw sockets and re-invent the wheel or if 
there is some other library that can help. If I get this 
working, it could potentially save myself and many others hours 
per week.


There is a limit of 50 concurrent messages per thread [1] in 
byLineAsync also the transmitBuffers argument takes part in.
So using multiple byLineAsync at same time/thread is going to 
block the process, I'm not sure if this is a bug or is by design.


You could use download() in a parallel foreach, something like 
this:


import std.stdio;
import std.parallelism;
import std.net.curl;
import std.typecons;

void main()
{
auto connections = 3; // 3 parallel downloads
defaultPoolThreads(connections - 1);
auto retries = 4; // try up to 4 times if it fails
auto logList = [
tuple("dlang.org", "log1.txt"), 
tuple("dlang.org", "log2.txt"),
tuple("dlang.org", "log3.txt"), 
tuple("dlang.org", "log4.txt"),
tuple("dlang.org", "log5.txt"), 
tuple("dlang.org", "log6.txt")];


foreach (log; parallel(logList, 1))
{
HTTP conn = HTTP();

foreach (i; 0 .. retries)
{
try
{
writeln("Downloading ", log[0]);
download(log[0], log[1], conn);

if(conn.statusLine.code == 200)
{
writeln("File ", log[1], " created.");
break;
}
}
catch (CurlException e)
{
writeln("Retrying ", log[0]);
}
}
}
}

[1] 
https://github.com/dlang/phobos/blob/master/std/net/curl.d#L1679