Re: extern(C) enum

2017-09-17 Thread Mike Parker via Digitalmars-d-learn

On Monday, 18 September 2017 at 02:04:49 UTC, bitwise wrote:

On Monday, 18 September 2017 at 00:12:49 UTC, Mike Parker wrote:

On Sunday, 17 September 2017 at 19:16:06 UTC, bitwise wrote:

[...]


I've been maintaining bindings to multiple C libraries 
(including Freetype 2 bindings) for 13 years now. I have never 
encountered an issue with an enum size mismatch. That's not to 
say I never will.


For which platforms?

I would have to actually go through the specs for each compiler 
of each platform to make sure before I felt comfortable 
accepting that int-sized enums were defacto standard.


I would be worried about iOS, for example.

The following code will run fine on Windows, but crash on iOS 
due to the misaligned access:


char data[8];
int i = 0x;
int* p = (int*)&data[1];
*p++ = i;
*p++ = i;
*p++ = i;

I remember this issue presenting due to a poorly written 
serializer I used once (no idea who wrote it ;) and it makes me 
wonder what kind of other subtle differences there may be.


I think there may be a few (clang and gcc?) different choices 
of compiler for Android NDK as well.


I know for certain that Derelict packages have been used on 
Windows, Linux, OS X, FreeBSD, and Android. I'm unsure about iOS. 
But I'm fairly confident that enums are int there just like they 
are everywhere else.





Re: extern(C) enum

2017-09-17 Thread bitwise via Digitalmars-d-learn

On Monday, 18 September 2017 at 00:12:49 UTC, Mike Parker wrote:

On Sunday, 17 September 2017 at 19:16:06 UTC, bitwise wrote:

[...]


I've been maintaining bindings to multiple C libraries 
(including Freetype 2 bindings) for 13 years now. I have never 
encountered an issue with an enum size mismatch. That's not to 
say I never will.


For which platforms?

I would have to actually go through the specs for each compiler 
of each platform to make sure before I felt comfortable accepting 
that int-sized enums were defacto standard.


I would be worried about iOS, for example.

The following code will run fine on Windows, but crash on iOS due 
to the misaligned access:


char data[8];
int i = 0x;
int* p = (int*)&data[1];
*p++ = i;
*p++ = i;
*p++ = i;

I remember this issue presenting due to a poorly written 
serializer I used once (no idea who wrote it ;) and it makes me 
wonder what kind of other subtle differences there may be.


I think there may be a few (clang and gcc?) different choices of 
compiler for Android NDK as well.





Re: Propagating constness through function results

2017-09-17 Thread Steven Schveighoffer via Digitalmars-d-learn

On 9/17/17 5:37 PM, David Zhang wrote:

Nevermind! I rediscovered the `inout`attribute.


Correct, inout applied to the function is actually applying to the 
'this' parameter. Same as const or immutable functions as well.




Though if I may say so, I have no idea how `inout` is supposed to 
indicate "whatever the constness of a".




What inout does is look at the mutability of the parameter and transfer 
it to the mutability of the return type.


-Steve


Re: Looking for instructions on how to make a Derelict library

2017-09-17 Thread Matt Jones via Digitalmars-d-learn

On Monday, 18 September 2017 at 00:21:23 UTC, Mike Parker wrote:



See the D wiki for links to articles that show how to translate 
C headers.




I've been reading the DerelictSDL2 source code. I think I have a 
handle on it. I'll have to look more at the wiki too.


Thanks.


Re: Looking for instructions on how to make a Derelict library

2017-09-17 Thread Mike Parker via Digitalmars-d-learn

On Sunday, 17 September 2017 at 21:15:08 UTC, Matt Jones wrote:

Hey everyone,

I wanted to make a version of SQlite3 that uses Derelict to 
load the sqlite3 DLL when I'm ready. I can't find any 
instructions for how to make a basic Derelict style library. I 
looked around at http://derelictorg.github.io/, but could not 
find anything. Does anyone have any?


Thanks.


Just look at the existing Derelict packages. For a normal C 
library like sqlite3, it's pretty straightforward -- declare 
function pointers to ever public function in the API, translate 
all the types, convert any macros to D functions, and create a 
loader that extends derelict.util.SharedLibLoader and overrides 
loadSymbols. Examples: DerelictLua, DerelictODE, DerelictFT.


You can also add support for static bindings by versioning out 
the function declarations and the loader in favor or normal 
function declarations. Examples: DerelictSDL2, DerelictGLFW3, 
DerelictAL.


See the D wiki for links to articles that show how to translate C 
headers.


Re: extern(C) enum

2017-09-17 Thread Mike Parker via Digitalmars-d-learn

On Sunday, 17 September 2017 at 19:16:06 UTC, bitwise wrote:

On Sunday, 17 September 2017 at 18:44:47 UTC, nkm1 wrote:

On Sunday, 17 September 2017 at 17:06:10 UTC, bitwise wrote:

[...]


Just put the burden on the users then. It's implementation 
defined, so they are in position to figure it out...


This isn't something that can really be done with bindings, 
which are important for D to start really picking up speed.


If someone goes to code.dlang.org and decides to download some 
FreeType2 bindings, they should just work. The memory 
corruption bugs that could occur due to binary incompatibility 
with some random copy of the original C library would be 
extremely hard to diagnose. They would also undermine the 
memory safety that a lot of people depend on when using D.




I've been maintaining bindings to multiple C libraries (including 
Freetype 2 bindings) for 13 years now. I have never encountered 
an issue with an enum size mismatch. That's not to say I never 
will.


I would say it's something you just don't have worry about. If, 
at some future time, any C compiler on any platform decides to 
start treating enums as something other than int or uint by 
default, then we can report a bug for D and fix it.




Re: Is there further documentation of core.atomic.MemoryOrder?

2017-09-17 Thread Johan Engelen via Digitalmars-d-learn

On Wednesday, 13 September 2017 at 14:40:55 UTC, Nathan S. wrote:
Is there a formal description of "hoist-load", "hoist-store", 
"sink-load", and "sink-store" as used in 
core.atomic.MemoryOrder 
(https://dlang.org/library/core/atomic/memory_order.html)?


You can read this:
https://llvm.org/docs/Atomics.html#atomic-orderings

And use this:
```
static if (ms == MemoryOrder.acq) {
enum _ordering = AtomicOrdering.Acquire;
} else static if (ms == MemoryOrder.rel) {
enum _ordering = AtomicOrdering.Release;
} else static if (ms == MemoryOrder.seq) {
enum _ordering = 
AtomicOrdering.SequentiallyConsistent;

} else static if (ms == MemoryOrder.raw) {
enum _ordering = AtomicOrdering.Monotonic;
}
```

-Johan


Re: Propagating constness through function results

2017-09-17 Thread David Zhang via Digitalmars-d-learn

Nevermind! I rediscovered the `inout`attribute.

Though if I may say so, I have no idea how `inout` is supposed to 
indicate "whatever the constness of a".




Re: Propagating constness through function results

2017-09-17 Thread David Zhang via Digitalmars-d-learn

On Sunday, 17 September 2017 at 21:18:08 UTC, David  Zhang wrote:

Hi,

I have a class `Image`, and I have a function called 
`getSubImage(Rect bounds)`. What I can't figure out is how to 
get the result of `getSubImage()` to take on the constness of 
the backing image.


ie.
//The Image class is really just a view over a buffer 
that's managed elsewhere

const(Image).getSubImage(...) -> const(Image)

Image.getSubImage(...) -> Image

I tried to do this with `inout`, but that requires that a 
parameter in the function be `inout`. I don't suppose I could 
somehow declare `this` to be inout?


Thanks


I am aware that you can duplicate the method, but it seems a bit 
unwieldy and excessive.


Re: Access Violation when passing the result of a C function directly to a D function?

2017-09-17 Thread Johan Engelen via Digitalmars-d-learn
On Friday, 15 September 2017 at 04:01:13 UTC, Timothy Foster 
wrote:

I've been calling it like so:

ErrorFMOD(FMOD_System_Create(&system), "Error Creating System: 
");


Making the calls without my helper function doesn't cause an 
Access Violation.

Calling it like this is the only thing that seems to fix it:

auto result = FMOD_System_Create(&system);
ErrorFMOD(result, "Error Creating System: ");

Is this a known issue, or am I required to save the result of a 
C function to variable before passing it into another function 
or?


This is very strange and you are certainly not required to save 
the result in a temp variable first.
Do you have a small but full testcase that we can look at? (did 
you try with another compiler, LDC or GDC?)
(note that debug information may be off, so the crash may happen 
in a different location from where it is reported to happen)


-Johan



Propagating constness through function results

2017-09-17 Thread David Zhang via Digitalmars-d-learn

Hi,

I have a class `Image`, and I have a function called 
`getSubImage(Rect bounds)`. What I can't figure out is how to get 
the result of `getSubImage()` to take on the constness of the 
backing image.


ie.
//The Image class is really just a view over a buffer that's 
managed elsewhere

const(Image).getSubImage(...) -> const(Image)

Image.getSubImage(...) -> Image

I tried to do this with `inout`, but that requires that a 
parameter in the function be `inout`. I don't suppose I could 
somehow declare `this` to be inout?


Thanks


Looking for instructions on how to make a Derelict library

2017-09-17 Thread Matt Jones via Digitalmars-d-learn

Hey everyone,

I wanted to make a version of SQlite3 that uses Derelict to load 
the sqlite3 DLL when I'm ready. I can't find any instructions for 
how to make a basic Derelict style library. I looked around at 
http://derelictorg.github.io/, but could not find anything. Does 
anyone have any?


Thanks.


Re: What is the canonical way to subclass Thread and make it pauseable?

2017-09-17 Thread Enjoys Math via Digitalmars-d-learn

On Sunday, 17 September 2017 at 19:57:05 UTC, Enjoys Math wrote:


How do you write a pauseable Thread?

Thanks.



This seems to work:


module data_rates_thread;

import core.thread;
import std.datetime;


class DataRatesThread : Thread
{
private:
uint loopSleep;
bool paused;

public:
this(uint loopSleep) {
super(& run);
this.loopSleep = loopSleep;
paused = true;
}

void pause() {
paused = true;
}

void start() {
paused = false;
super.start();
}

private:
void run() {
import std.stdio;
int k = 0;

while (! paused) {
writeln(k);
k ++;
if (loopSleep != 0)
sleep(dur!"msecs"(loopSleep));
}


}
}


Which is not the best way to pause and resume, but it works for 
my application.


What is the canonical way to subclass Thread and make it pauseable?

2017-09-17 Thread Enjoys Math via Digitalmars-d-learn


How do you write a pauseable Thread?

Thanks.


Re: extern(C) enum

2017-09-17 Thread bitwise via Digitalmars-d-learn

On Sunday, 17 September 2017 at 18:44:47 UTC, nkm1 wrote:

On Sunday, 17 September 2017 at 17:06:10 UTC, bitwise wrote:

[...]


Just put the burden on the users then. It's implementation 
defined, so they are in position to figure it out...


This isn't something that can really be done with bindings, which 
are important for D to start really picking up speed.


If someone goes to code.dlang.org and decides to download some 
FreeType2 bindings, they should just work. The memory corruption 
bugs that could occur due to binary incompatibility with some 
random copy of the original C library would be extremely hard to 
diagnose. They would also undermine the memory safety that a lot 
of people depend on when using D.


for example, gcc: "Normally, the type is unsigned int if there 
are no negative values in the enumeration, otherwise int. If 
-fshort-enums is specified, then if there are negative values 
it is the first of signed char, short and int that can 
represent all the values, otherwise it is the first of unsigned 
char, unsigned short and unsigned int that can represent all 
the values. On some targets, -fshort-enums is the default; this 
is determined by the ABI."

https://gcc.gnu.org/onlinedocs/gcc-6.4.0/gcc/Structures-unions-enumerations-and-bit-fields-implementation.html#Structures-unions-enumerations-and-bit-fields-implementation

msvc++: "A variable declared as enum is an int."
https://docs.microsoft.com/en-us/cpp/c-language/enum-type


I was starting to think along these lines as well. With respect 
to the above, I'm wondering if something like this could be done:


`
template NativeEnumBase(long minValue, long maxValue)
{
static if(platform A)
{
static if(minValue < 0) // need signed?
{
static if(maxValue > int.max) // need long?
alias NativeEnumBase = long;
else
alias NativeEnumBase = int;
}
else
{
static if(maxValue > uint.max) // need long?
alias NativeEnumBase = ulong;
else
alias NativeEnumBase = uint;
}
}
else static if(platform B)
{
// etc...
alias NativeEnumBase = long;
}
else {
static assert("unsupported compiler");
}
}

enum Some_C_Enum_ : NativeEnumBase!(-1, 2)
{
SCE_INVALID = -1,
SCE_ZERO = 0,
SCE_ONE = 1,
SCE_TWO = 2,
}
`

So the question is, is there a way from inside D code to 
determine what the native enum size would be for a given set of 
min and max enum values? While C and C++ do not specify enum 
size, are there platform or compiler level specifications we 
could rely on?


It's probably pretty safe to assume it's an int; people who 
play tricks with "-fshort-enums" deserve what's coming to them 
:)


Agreed ;)




OpIndex/OpIndexAssign strange order of execution

2017-09-17 Thread SrMordred via Digitalmars-d-learn

struct Test{
@property int value(){
writeln("property value : ", _value);
return _value;
}
int _value;
Test opIndex( string index )
{
writeln( "opIndex : index : ", index );
return this;
}

Test opIndexAssign(int value, string index )
{
writeln( "opIndexAssign : value : ", value, " , index : 
", index );

this._value = value;
return this;
}
}

Test t;
t["a"] = 100;
t["b"]["c"] = t["a"].value;

//OUTPUT:
opIndexAssign : index : a , value : 100
opIndex : index : b
opIndex : index : a
property value : 100
opIndexAssign : index : c , value : 100

//EXPECTED OUTPUT
opIndexAssign : index : a , value : 100
opIndex : index : a
property value : 100
opIndex : index : b
opIndexAssign : index : c , value : 100

Is this right?

I find unexpected this mix of operations on left and right side 
of an equal operator.




Re: How to Skip some field/word in formattRead?

2017-09-17 Thread kdevel via Digitalmars-d-learn

On Sunday, 17 September 2017 at 13:53:26 UTC, Ky-Anh Huynh wrote:
Is it possible to read just the second word from an input 
string and skip all others?


"one two three".formattedRead!("%s %s", _, saveme)


---
   import std.range;
   auto saveme = "one two three".split.array [2];
---



Re: extern(C) enum

2017-09-17 Thread nkm1 via Digitalmars-d-learn

On Sunday, 17 September 2017 at 17:06:10 UTC, bitwise wrote:
I don't really see a way to deal with this aside from branching 
the entire library and inserting something like 
'FT_SIZE_REQUEST_TYPE__FORCE_INT = 0x' into every enum 
incase the devs used it in a struct.


Just put the burden on the users then. It's implementation 
defined, so they are in position to figure it out...


for example, gcc: "Normally, the type is unsigned int if there 
are no negative values in the enumeration, otherwise int. If 
-fshort-enums is specified, then if there are negative values it 
is the first of signed char, short and int that can represent all 
the values, otherwise it is the first of unsigned char, unsigned 
short and unsigned int that can represent all the values. On some 
targets, -fshort-enums is the default; this is determined by the 
ABI."

https://gcc.gnu.org/onlinedocs/gcc-6.4.0/gcc/Structures-unions-enumerations-and-bit-fields-implementation.html#Structures-unions-enumerations-and-bit-fields-implementation

msvc++: "A variable declared as enum is an int."
https://docs.microsoft.com/en-us/cpp/c-language/enum-type

It's probably pretty safe to assume it's an int; people who play 
tricks with "-fshort-enums" deserve what's coming to them :)


Re: extern(C) enum

2017-09-17 Thread bitwise via Digitalmars-d-learn

On Saturday, 16 September 2017 at 12:34:58 UTC, nkm1 wrote:
On Saturday, 16 September 2017 at 03:06:24 UTC, Timothy Foster 
wrote:

[...]


[...]


So it appears I'm screwed then.

Example:

typedef enum FT_Size_Request_Type_
{
FT_SIZE_REQUEST_TYPE_NOMINAL,
FT_SIZE_REQUEST_TYPE_REAL_DIM,
FT_SIZE_REQUEST_TYPE_BBOX,
FT_SIZE_REQUEST_TYPE_CELL,
FT_SIZE_REQUEST_TYPE_SCALES,

FT_SIZE_REQUEST_TYPE_MAX

} FT_Size_Request_Type;

typedef struct FT_Size_RequestRec_
{
FT_Size_Request_Type  type;
FT_Long   width;
FT_Long   height;
FT_UInt   horiResolution;
FT_UInt   vertResolution;

} FT_Size_RequestRec;


FT_Size_Request_Type_ could be represented by char. Maybe the 
compiler makes it an int, maybe not.


Maybe the compiler makes 'FT_Size_Request_Type_' char sized, but 
then pads 'FT_Size_RequestRec_' to align 'width' to 4 bytes...or 
maybe not.


Maybe a member of 'FT_Size_Request_Type_' sits right before a 
char or bool in some struct..so can't rely on padding.


I don't really see a way to deal with this aside from branching 
the entire library and inserting something like 
'FT_SIZE_REQUEST_TYPE__FORCE_INT = 0x' into every enum 
incase the devs used it in a struct.





Re: Forwarding Uncopyable Static Array Elements

2017-09-17 Thread Nordlöw via Digitalmars-d-learn

On Sunday, 17 September 2017 at 13:00:04 UTC, Nordlöw wrote:

How can

T[n] asStatic(T, size_t n)(T[n] arr)
{
import std.traits : isCopyable;
static if (isCopyable!T)
{
return arr;
}
else
{
static assert(false, "TODO support forwarding of 
uncopyable elements");

}
}

be extended to support uncopyable element types?


This works for me

T[n] asStatic(T, size_t n)(T[n] x)
{
import std.traits : isCopyable;
static if (isCopyable!T)
{
return x;
}
else
{
T[n] y = void;

// TODO why doesn't this work here?
// import std.algorithm.mutation : moveEmplaceAll;
// moveEmplaceAll(x[], y[]);

foreach (const ix, ref value; x)
{
import std.algorithm.mutation : move;
move(value, y[ix]);
}

return y;
}
}

Why does `moveEmplaceAll` error here?


How to Skip some field/word in formattRead?

2017-09-17 Thread Ky-Anh Huynh via Digitalmars-d-learn

Hi,

Is it possible to read just the second word from an input string 
and skip all others?


"one two three".formattedRead!("%s %s", _, saveme)

The point is I want to skip the first/third word (`one`, `third`) 
and read the second word (`two`) into the variable `saveme`. For 
now I have to declare temporary reference


string _;
"one two three".formattedRead!("%s %s %s", _, saveme, _);

Well, `_` is acceptable; in my example, the value of `_` would be 
`three[\n]`


Is there any better/cleaner way?

Thanks for your reading.


Re: Internal error mixing templates and CTFE

2017-09-17 Thread David Bennett via Digitalmars-d-learn

On Friday, 15 September 2017 at 15:48:10 UTC, Stefan Koch wrote:

are you using ucent ?


Not that I know of, the code above is the full code (not sure 
what's used internally for string literals).


I was using dmd 2.076 from the apt repo but the error also 
happens in LDC 1.3[1].


Is there an easy way for me to test newCTFE?

The reduced version to get the same error is:

```
struct Content{string[] parts;}

void main(){
enum Content content = {};
content.parts ~= "";
}
```

Strange (for a CTFE noob like me anyway) thing is the following 
code produces no error or warning. (obviously it doesn't do what 
it looks like it does)


```
struct Content{
string[] parts;
void add(string s)(){
parts ~= "Part: "~s;
}
}

void main(){
enum Content content = {};
content.add!("Header")();
}
```

I would have thought both the code in the OP and the above two 
codes should produce a warning pointing out that using a compile 
time value like that has no useful effect. As this would be 
useful information for noobs like me...


Actually now that I think about it there could be a "valid" use.. 
ie if the add function set global state... does this even work... 
(checks) ... yes it does... so I guess a warning cant really 
happen then.



[1] Here is the LDC backtrace:

ldc2: /build/ldc-6CClyQ/ldc-1.3.0/gen/dvalue.cpp:43: llvm::Value* 
DtoLVal(DValue*): Assertion `lval' failed.
#0 0x7f1d568658a8 
llvm::sys::PrintStackTrace(llvm::raw_ostream&) 
(/usr/lib/x86_64-linux-gnu/libLLVM-4.0.so.1+0x76e8a8)
#1 0x7f1d56863786 llvm::sys::RunSignalHandlers() 
(/usr/lib/x86_64-linux-gnu/libLLVM-4.0.so.1+0x76c786)
#2 0x7f1d568638e5 
(/usr/lib/x86_64-linux-gnu/libLLVM-4.0.so.1+0x76c8e5)
#3 0x7f1d55ce2670 __restore_rt 
(/lib/x86_64-linux-gnu/libpthread.so.0+0x11670)
#4 0x7f1d5509977f gsignal 
/build/glibc-mXZSwJ/glibc-2.24/signal/../sysdeps/unix/sysv/linux/raise.c:58:0
#5 0x7f1d5509b37a abort 
/build/glibc-mXZSwJ/glibc-2.24/stdlib/abort.c:91:0
#6 0x7f1d55091b47 __assert_fail_base 
/build/glibc-mXZSwJ/glibc-2.24/assert/assert.c:92:0

#7 0x7f1d55091bf2 (/lib/x86_64-linux-gnu/libc.so.6+0x2dbf2)
#8 0x5644df8d2310 (ldc2+0x3cb310)
...
#25 0x5644df909370 (ldc2+0x402370)
#26 0x7f1d550843f1 __libc_start_main 
/build/glibc-mXZSwJ/glibc-2.24/csu/../csu/libc-start.c:325:0

#27 0x5644df6538ea (ldc2+0x14c8ea)
Aborted (core dumped)
ldc2 failed with exit code 134.




Re: Error 16: Index Range error while building examples from D Web development

2017-09-17 Thread Nicholas Wilson via Digitalmars-d-learn

On Sunday, 17 September 2017 at 11:42:16 UTC, kerdemdemir wrote:

Hi,

Thanks its price dropped to 10 Euros I bought the the D Web 
Development book and I were trying to build some examples.
The example in Chapter3 called noteapp4 is giving me this error 
:


[...]


Optlink bug I guess?

try using -ms32coff (? check dmd's help) or -m64, they will both 
use the MS linker (which is hopefully bug free :) )


Forwarding Uncopyable Static Array Elements

2017-09-17 Thread Nordlöw via Digitalmars-d-learn

How can

T[n] asStatic(T, size_t n)(T[n] arr)
{
import std.traits : isCopyable;
static if (isCopyable!T)
{
return arr;
}
else
{
static assert(false, "TODO support forwarding of 
uncopyable elements");

}
}

be extended to support uncopyable element types?


Re: Forwarding Uncopyable Static Array Elements

2017-09-17 Thread Nordlöw via Digitalmars-d-learn

On Sunday, 17 September 2017 at 13:00:04 UTC, Nordlöw wrote:

How can

...

be extended to support uncopyable element types?


That is, when `T` is uncopyable.


Error 16: Index Range error while building examples from D Web development

2017-09-17 Thread kerdemdemir via Digitalmars-d-learn

Hi,

Thanks its price dropped to 10 Euros I bought the the D Web 
Development book and I were trying to build some examples.

The example in Chapter3 called noteapp4 is giving me this error :

Performing "debug" build using dmd for x86.
noteapp4 ~master: building configuration "application"...
C:\Users\Erdem\AppData\Roaming\dub\packages\vibe-d-0.7.32\vibe-d\source\vibe\http\server.d(286,33):
 Deprecation: alias diet.traits.FilterCallback is deprecated - Use 
SafeFilterCallback instead.
Compiling Diet HTML template create.dt...
Compiling Diet HTML template listnotes.dt...
Linking...
OPTLINK (R) for Win32  Release 8.00.17
Copyright (C) Digital Mars 1989-2013  All rights reserved.
http://www.digitalmars.com/ctg/optlink.html
.dub\build\application-debug-windows-x86-dmd_2075-102ED5AC10E8F023CF2D8D690787ADD9\noteapp4.obj(noteapp4)
  Offset 23F7EH Record Type 009D
 Error 16: Index Range
Error: linker exited with status 1
dmd failed with exit code 1.

Meanwhile hello world example compiling. I am on windows 10 and

C:\D\dmd2\windows\bin>dmd.exe --version
DMD32 D Compiler v2.075.0


Do you guys have any idea about what I am doing wrong?

Thanks


Re: Gtk toArray List funkiness

2017-09-17 Thread Mike Wey via Digitalmars-d-learn

On 16-09-17 23:08, Joseph wrote:

On Saturday, 16 September 2017 at 20:54:21 UTC, Mike Wey wrote:

On 16-09-17 20:58, Joseph wrote:


https://github.com/gtkd-developers/GtkD/blob/master/demos/gtkD/TestWindow/TestWindow.d 




has the code

foreach ( int i, string selection ; fs.getSelections())
{
   writeln("File(s) selected [%d] %s",i,selection);
}

which is invalid for the demo, but

foreach ( int i, string selection ; 
fd.getFilenames().toArray!(string,?))

{
   writeln("File(s) selected [%d] %s",i,selection);
}

results in some funky code. Gives errors in ObjectG about uint when 
setting ? to string, string* or void* or even uint:


GtkD\generated\gtkd\gobject\ObjectG.d(172): Error: incompatible types 
for ((obj) is (null)): 'uint' and 'typeof(null)'
GtkD\generated\gtkd\glib\ListSG.d(98): Error: template instance 
gobject.ObjectG.ObjectG.getDObject!(string, string, uint) error 
instantiating

test.d(91):    instantiated from here: toArray!(string, uint)
test.d(93): Error: invalid foreach aggregate `fd.getFilenames()`, 
define opApply(), range primitives, or use .tupleof


without specifying ? it assumes it's a tuple, which seems wrong?



 public T[] toArray(T, TC = typeof(T.tupleof[0]))()
 {
 T[] arr = new T[length()];
 ListSG list = this;
 size_t count;

 while(list !is null && count < arr.length)
 {
 arr[count] = ObjectG.getDObject!(T)(cast(TC)list.data);
 list = list.next();
 count++;
 }

 return arr;
 }


 foreach ( int i, Value 
selection ; fd.getFilenames().toArray!(Value)())

{
   writeln("File(s) selected [%d] %s",i,selection.getString);
}

crashes ;/

I'm not sure what types are what and it changes depending on the 
input. I think Value is the wrong type to use but string doesn't work 
so...


ListG and ListSG are missing an toArray overload for string. And 
getFilenames returns a list of strings.


I've added a string overload for toArray: 
https://github.com/gtkd-developers/GtkD/commit/ba20490b38e502a4d281226572c83c662a700858 




 public ListSG getFilenames()
 {
     auto p = gtk_file_chooser_get_filenames(getFileChooserStruct());

     if(p is null)
     {
     return null;
     }

     return new ListSG(cast(GSList*) p, true);
 }

Doesn't return a list of strings? That was the first thing I tried and 
the foreach loop wouldn't work over it because it was a ListSG.


Thanks.



getFilenames returns a singly linked list of C strings, ie the data 
member is a char*.


With the changes in master you can use toArray!string() to get an array 
of strings out of it.


Or you can loop over the list:

```
auto list = fd.getFilenames();
string[] files;

while ( list.next !is null )
{
files ~= to!string(cast(char*)list.data);
list = list.next;
}
```

--
Mike Wey


Re: How to list all process directories under /proc/

2017-09-17 Thread Ky-Anh Huynh via Digitalmars-d-learn

On Sunday, 17 September 2017 at 08:32:24 UTC, Ky-Anh Huynh wrote:


My bad. Range doesn't support. The correct pattern is

[code]
  foreach (string fstatm; dirEntries("/proc/", "[0123456789]*", 
SpanMode.shallow)) {

writefln("pid %s", fstatm);
  }
[/code]

Is there a way to make this simpler?


The official documentation here 
https://dlang.org/phobos/std_path.html#.globMatch refers to the 
wiki page https://en.wikipedia.org/wiki/Glob_%28programming%29 . 
However I think the popular glob rules (man 7 glob) are not 
supported.


Re: Temporarily adding -vgc to a DUB build

2017-09-17 Thread Igor via Digitalmars-d-learn
On Sunday, 17 September 2017 at 01:50:08 UTC, Nicholas Wilson 
wrote:

On Saturday, 16 September 2017 at 21:45:34 UTC, Nordlöw wrote:

How do I temporarily enable -vgc when building my app with DUB?

I've tried

DFLAGS=-vgc /usr/bin/dub build --build=unittest

but it doesn't seem to have any effect as it doesn't rebuild 
directly after the call


/usr/bin/dub build --build=unittest

I'm using DUB version 1.5.0

Or is adding a new build configuration, say unittest-vgc, the 
only way to accomplish this?


Setting the dflags in the dub.json should work.

This is what I use for dcompute:

{
...
"dflags" : ["-mdcompute-targets=cuda-210" ,"-oq", 
"-betterC"],

...
}

so just change those flags to "-vgc" should do the trick.


You can also just execute:

export DFLAGS=-vgc

before running dub. That should work since as far as I know 
"export" is needed to make env var visible to other processes 
started from the same shell session.


Re: How to list all process directories under /proc/

2017-09-17 Thread Ky-Anh Huynh via Digitalmars-d-learn

On Sunday, 17 September 2017 at 08:15:58 UTC, Ky-Anh Huynh wrote:

Hi,

I want to list all processes by scanning /proc/. The following 
code doesn't work


[code]
  foreach (string fstatm; dirEntries("/proc/", "[0-9]*", 
SpanMode.shallow)) {

writefln("pid %s", fstatm);
  }
[/code]

as it only list a few entries before exiting

[code]
pid /proc/9
pid /proc/935
pid /proc/9146
pid /proc/9149
pid /proc/9150
pid /proc/9151
pid /proc/9756
pid /proc/9759
pid /proc/9760
pid /proc/9761
[/code]

I don't want to use `SpanMode.depth` or `SpanMode.breadth` 
because it will scan so deeply and there would be a permission 
problem.


Any ideas?

Thanks a lot


My bad. Range doesn't support. The correct pattern is

[code]
  foreach (string fstatm; dirEntries("/proc/", "[0123456789]*", 
SpanMode.shallow)) {

writefln("pid %s", fstatm);
  }
[/code]

Is there a way to make this simpler?





How to list all process directories under /proc/

2017-09-17 Thread Ky-Anh Huynh via Digitalmars-d-learn

Hi,

I want to list all processes by scanning /proc/. The following 
code doesn't work


[code]
  foreach (string fstatm; dirEntries("/proc/", "[0-9]*", 
SpanMode.shallow)) {

writefln("pid %s", fstatm);
  }
[/code]

as it only list a few entries before exiting

[code]
pid /proc/9
pid /proc/935
pid /proc/9146
pid /proc/9149
pid /proc/9150
pid /proc/9151
pid /proc/9756
pid /proc/9759
pid /proc/9760
pid /proc/9761
[/code]

I don't want to use `SpanMode.depth` or `SpanMode.breadth` 
because it will scan so deeply and there would be a permission 
problem.


Any ideas?

Thanks a lot



Using Parallel prints duplicates nor misses.

2017-09-17 Thread Vino.B via Digitalmars-d-learn

Hi,

 Request your help, the below code sometime prints duplicate and 
some time miss the entry. due to which any code written below the 
line "foreach (d; parallel(dFiles[], 1))" are some time 
duplicated and some time not executed(skips). tired adding sort 
and uniq to the writeln but no luck.



Code:
import std.algorithm: filter, map, sort, uniq;
import std.container;
import std.file: SpanMode, dirEntries, isDir;
import std.stdio: writeln;
import std.parallelism: parallel;

void main () {
  	auto SizeDirlst = Array!string ("C:\\Temp\\TEAM\\BACKUP", 
"C:\\Temp\\TEAM\\EXPORT");

foreach (FFs; SizeDirlst[]) {
	auto dFiles = Array!string ((dirEntries(FFs, 
SpanMode.shallow).filter!(a => a.isDir))[].map!(a => a.name));

foreach (d; parallel(dFiles[], 1)) { writeln(d); }
}
}

Output 1:

C:\Temp\TEAM\BACKUP\dir1
C:\Temp\TEAM\BACKUP\DND3
C:\Temp\TEAM\BACKUP\dir2  - Duplicate
C:\Temp\TEAM\BACKUP\dir2  - Duplicate
C:\Temp\TEAM\EXPORT\DND6

Output 2:
C:\Temp\TEAM\BACKUP\dir1
C:\Temp\TEAM\BACKUP\DND3
C:\Temp\TEAM\BACKUP\dir2  - Duplicate
C:\Temp\TEAM\BACKUP\dir2  - Duplicate


C:\Temp\TEAM\EXPORT\DND6  - Missing

From,
Vino.B