Re: Endiannes & Splitting Values

2016-07-06 Thread Alex Parrill via Digitalmars-d-learn

On Wednesday, 6 July 2016 at 21:44:37 UTC, BitGuy wrote:
I'm trying to implement a feistel cipher that'll give the same 
results regardless of the endianness of the machine it runs on. 
To make the cipher I need to split a 64bit value into two 32bit 
values, mess with them, and then put them back together. I can 
think of a few ways to split a 64bit value with versions or the 
endianness functions in bitmanip but it all seems pretty messy 
for just wanting to split a value... I'm thinking maybe I can 
just cast and bitshift so I can forget about the endianness but 
I'm not really sure about the casting down rules and if that'd 
work?


Bitshifts and binary operators work the same regardless of 
endianness. Just shift by 32/mask  with 0x and cast.


It's only if you are accessing a value as a byte array that you 
have to worry about endianness.


Re: Dynamic array of objects

2016-06-27 Thread Alex Parrill via Digitalmars-d-learn

On Monday, 27 June 2016 at 22:00:15 UTC, gummybears wrote:

Hi,

Today thought lets learn D. I am writing a compiler for a 
language

and read D compiles very fast.
Switched my compiler from C++ to D and ran my test suite to use 
D.
Doing somethin wrong as creating array of objects gives me a 
segmentation fault


Example

import std.stdio;

class Pair {
  float x;
  float y;
  this() { x = 0; y = 0; }
}


void main() {
  Pair[] arr;

  // segmentation fault on next line
  arr = new Pair[](10);
  arr[0].x = 3;
  arr[0].y = 4;
  writef("arr[0] = (%f,%f)",arr[0].x,arr[0].y);
}


You've allocated an array of 10 objects but didn't put any 
objects into it, so each of the entries is null (since classes 
are reference types in D). The line after the allocation fails as 
you try to access a null object.


Either fill out the array with new objects (`arr[0] = new 
Pair()`), or convert Pair to a struct (structs are value types).


Re: arsd png bug

2016-06-20 Thread Alex Parrill via Digitalmars-d-learn

On Monday, 20 June 2016 at 21:39:45 UTC, Joerg Joergonson wrote:

1810:
case 3:
auto arr = data.dup;
foreach(i; 0 .. arr.length) {
auto prev = i < bpp ? 0 : arr[i - bpp];
if (i >= previousLine.length) break;
arr[i] += cast(ubyte)
	/*std.math.floor*/( cast(int) (prev + previousLine[i]) / 
2);

}


adding
if (i >= previousLine.length) break;

prevents some crashes and seems to work.


You'd probably get better results by filing an issue with the 
project's bug tracker [1]. Also by including a sample image that 
causes the crash.


[1]: https://github.com/adamdruppe/arsd/issues


Re: Strange Issues regarding aliases

2016-06-14 Thread Alex Parrill via Digitalmars-d-learn

On Tuesday, 14 June 2016 at 17:37:40 UTC, Joerg Joergonson wrote:
On Tuesday, 14 June 2016 at 17:34:42 UTC, Joerg Joergonson 
wrote:
This is how derelict does it, I simply moved them in to the 
class for simplicity.


I mean glad: http://glad.dav1d.de/


It seems that a loader is required for some reason and that 
possibly could be one or both of the problems.


You absolutely need a loader to load most opengl functions. They 
are not usually exposed in the shared object, as gl function 
pointers are tied to a specific opengl context.


You are trying to call function pointer types, which is invalid. 
You need to declare some variable with the type, load the 
function pointer into the variable (platform specific; there are 
plenty of tutorials on how to do this in C), and call that 
variable.



(Also I disagree that separating the opengl API based on what the 
symbol is is a step up from the "ancient and backwards flat 
access" way. Functions are, by neccessity, coupled to the types 
and enums they take. A better categorization would be based on 
version introduced or extension, iirc jogl does that)


Re: Fibers, what for?

2016-06-12 Thread Alex Parrill via Digitalmars-d-learn

On Sunday, 12 June 2016 at 08:38:03 UTC, chmike wrote:
Fibers don't need synchronization to access shared data. This 
removes the overhead of synchronization and simplifies 
"multitheaded" programming greatly.


This is misleading. Any sort of cooperative system needs 
synchronization when two or more tasks try to access the same 
data, whether those "tasks" are OS threads, fibers, different 
machines on a network, etc.


Fibers do make it easier, as no task can run in parallel with the 
current one and switching tasks is done explicitly via yield, 
effectively giving the current fiber exclusive access to the 
entire program state in between yields. But if you need to hold 
onto a resource across a yield, you will need the usual set of 
concurrency primitives, like locks.


(A practical example: making a commit using the Node.js libgit 
bindings involves several asynchronous steps, during which other 
tasks may access it. If you don't want anyone else messing with 
the Git repo while you are making a commit, you must protect the 
repo with a lock.)


Also note that Vibe.d, the largest fiber-based framework D has to 
offer, is capable of running several coroutines in parallel on 
multiple threads, meaning you must use the same level of 
synchronization as if you were using threads.


Re: Why can't I assign a mixin to an alias?

2016-06-10 Thread Alex Parrill via Digitalmars-d-learn

On Saturday, 11 June 2016 at 02:46:00 UTC, Adam D. Ruppe wrote:

On Saturday, 11 June 2016 at 02:33:46 UTC, Alex Parrill wrote:

Mixins are statements.


No, they're not. Well, yes they are [1], but there are also 
mixin expressions [2]. Not to be confused with the 
TemplateMixin[3], which is indeed always a statement.


1: http://dlang.org/spec/grammar.html#MixinExpression
2: http://dlang.org/spec/grammar.html#MixinStatement
3: http://dlang.org/spec/grammar.html#TemplateMixin


Huh, every time I've used mixins, I've always run into the issue 
in the OP, so I assumed they were statements. It definitely seems 
like a bug then.


Re: Why can't I assign a mixin to an alias?

2016-06-10 Thread Alex Parrill via Digitalmars-d-learn

On Friday, 10 June 2016 at 22:38:29 UTC, Dechcaudron wrote:

I have the following code:

private string getVariableSignalWrappersName(VarType)()
{
return VarType.stringof ~ "SignalWrappers";
}

void addVariableListener(VarType)(int variableIndex, void 
delegate(int, VarType))

{
	alias typeSignalWrappers = 
mixin(getVariableSignalWrappersName!VarType);

}

On compilation, the following error is issued:
Error: basic type expected, not mixin

Why should it be like that? I believe the compiler should not 
impose restrictions on what mixins can or cannot do :/


Mixins are statements. They cannot be a part of an expression.

The other two posts have demonstrated how to get around this.


Re: Parse File at compile time, but not embedded

2016-06-10 Thread Alex Parrill via Digitalmars-d-learn

On Thursday, 9 June 2016 at 22:02:44 UTC, Joerg Joergonson wrote:

On Tuesday, 7 June 2016 at 22:09:58 UTC, Alex Parrill wrote:
Accessing a SQL server at compile time seems like a huge abuse 
of CTFE (and I'm pretty sure it's impossible at the moment). 
Why do I need to install and set up a MySQL database in order 
to build your software?


Lol, who says you have access to my software? You know, the 
problem with assumptions is that they generally make no sense 
when you actually think about them.


By "I" I meant "someone new coming into the project", such as a 
new hire or someone that will be maintaining your program while 
you work on other things.


In any case, this is impossible. D has no such concept as 
"compile-time-only" values, so any usage of a value risks 
embedding it into the binary.


Re: Parse File at compile time, but not embedded

2016-06-07 Thread Alex Parrill via Digitalmars-d-learn

On Monday, 6 June 2016 at 21:57:20 UTC, Pie? wrote:

On Monday, 6 June 2016 at 21:31:32 UTC, Alex Parrill wrote:
But reading sensitive data at compile-time strikes me as 
dangerous, depending on your use case. If you are reading 
sensitive information at compile time, you are presumably 
going to include that information in your binary (otherwise 
why would you read it?), and your binary is not secure.


Not necessarily, You chased that rabbit quite far! The data 
your reading could contain sensitive information only used at 
compile time and not meant to embed. For example, the file 
could contain login and password to an SQL database that  you 
then connect, at compile time and retrieve that information the 
disregard the password(it is not needed at run time).


Accessing a SQL server at compile time seems like a huge abuse of 
CTFE (and I'm pretty sure it's impossible at the moment). Why do 
I need to install and set up a MySQL database in order to build 
your software?




Re: Error: mutable method isolated.graphics.g3d.model.Model.begin is not callable using a const object

2016-06-07 Thread Alex Parrill via Digitalmars-d-learn

On Monday, 6 June 2016 at 21:55:00 UTC, ag0aep6g wrote:

On 06/06/2016 11:25 PM, Alex Parrill wrote:
You might be able to get away with casting the const away, if 
you are

sure it won't modify the hash or equality check.


Casting away const and then mutating has undefined behavior. 
The compiler is free to assume that it doesn't happen.


Be aware that you're working outside of the specified language 
if you do it. You rely on the compiler producing code that 
works in your favor when it has no obligation to do so.


I don't think we should ever suggest relying on undefined 
behavior here in D.learn.


Yes, you are correct. I was mixing up C const rules with D.

Unfortunately there does not seem to be an easy solution to this 
problem. The best solution might be to use an array of pairs 
instead of a hash table, but that may have a performance impact.


Re: Enum that can be 0 or null

2016-06-07 Thread Alex Parrill via Digitalmars-d-learn

On Tuesday, 7 June 2016 at 04:31:56 UTC, ParticlePeter wrote:

On Monday, 6 June 2016 at 20:32:23 UTC, Alex Parrill wrote:
They'd be the same type, since you would define the vulkan 
functions to take these structures instead of pointer or 
integer types.


It relies on a lot of assumptions about the ABI that make a 
raw pointer work the same as a structure containing just one 
pointer, which is why I did not give it much consideration.


Is there a way to use opCast (just an idea, not working code) ?

private struct VK_HANDLE_HELPER {
const void * handle = null;
alias handle this;
T opCast(T)() if( is( T == uint64_t )) {
return 0uL;
}
}
const VK_NULL_HANDLE = VK_HANDLE_HELPER();



I don't think opCast gets called for implicit conversions; it 
only gets called for explicit casts. I'll test it later.


Re: Parse File at compile time, but not embedded

2016-06-06 Thread Alex Parrill via Digitalmars-d-learn

On Monday, 6 June 2016 at 17:31:52 UTC, Pie? wrote:
Is it possible to parse a file at compile time without 
embedding it into the binary?


I have a sort of "configuration" file that defines how to 
create some objects. I'd like to be able to read how to create 
them but not have that config file stick around in the binary.


e.g., (simple contrived example follows)

Config.txt
   x, my1
   y, my1
   z, my2


class my1 { }
class my2 { }

void parseConfig(A)
{

}

void main()
{
   parseConfig('Config.txt') // Effectively creates a mixin 
that mixes in auto x = new my1; auto y = new my1; auto z = new 
my2;

}


If parseConfig uses import('Config.txt') then config.txt will 
end up in the binary which I do not want. It would be easier to 
be able to use import and strip it out later if possible. 
Config.txt may contain secure information, which is why is 
doesn't belong in the binary.


Most compilers, I believe, will not embed a string if it is not 
used anywhere at runtime. DMD might not though, I'm not sure.


But reading sensitive data at compile-time strikes me as 
dangerous, depending on your use case. If you are reading 
sensitive information at compile time, you are presumably going 
to include that information in your binary (otherwise why would 
you read it?), and your binary is not secure.


Re: Error: mutable method isolated.graphics.g3d.model.Model.begin is not callable using a const object

2016-06-06 Thread Alex Parrill via Digitalmars-d-learn

On Monday, 6 June 2016 at 20:40:12 UTC, Begah wrote:
I have a pretty weird error : Error: mutable method 
isolated.graphics.g3d.model.Model.begin is not callable using a 
const object


[...]


It may infer const from the type of `this.instance`, which may be 
further modified if the method you are running this in is 
`const`. If you explicitly specify the type of the foreach loop 
variables, does it work?


Re: Enum that can be 0 or null

2016-06-06 Thread Alex Parrill via Digitalmars-d-learn

On Monday, 6 June 2016 at 18:43:33 UTC, ParticlePeter wrote:

On Saturday, 21 May 2016 at 06:36:53 UTC, tsbockman wrote:

...
As an example, if VK_NULL_HANDLE only ever needs to be 
assigned to opaque types on the D side (that is, types that 
serve only as an ID or address for communicating with the C 
side), you could do this:


private struct VkNullHandle { }
enum VK_NULL_HANDLE = VkNullHandle.init;

mixin template VkHandle(bool dispatchable) {
static if (dispatchable || (size_t.sizeof == 8))
void* bits = null;
else
ulong bits = 0;

this(typeof(this) that) {
this.bits = that.bits; }
this(VkNullHandle that) {
this.bits = typeof(this.bits).init; }

ref typeof(this) opAssign(typeof(this) that) {
this.bits = that.bits;
return this;
}
ref typeof(this) opAssign(VkNullHandle that) {
this.bits = typeof(this.bits).init;
return this;
}
}

struct VkDevice { mixin VkHandle!true; }
struct VkInstance { mixin VkHandle!true; }

struct VkFence { mixin VkHandle!false; }
struct VkSemaphore { mixin VkHandle!false; }


void main() {
VkInstance a = VK_NULL_HANDLE;
VkFence b = VK_NULL_HANDLE;
}

(DPaste: https://dpaste.dzfl.pl/8f4ce39a907f )

The above is typesafe, and can easily be made compatible with 
a typical C API, since C does no parameter-related name 
mangling.


In this case I don't see how it would be possible to use your 
VkDevice, etc. as argument to the C functions, as they are of 
different type, no?


They'd be the same type, since you would define the vulkan 
functions to take these structures instead of pointer or integer 
types.


It relies on a lot of assumptions about the ABI that make a raw 
pointer work the same as a structure containing just one pointer, 
which is why I did not give it much consideration.


Re: Emulate C's (polymorphic) NULL type

2016-06-06 Thread Alex Parrill via Digitalmars-d-learn

On Monday, 6 June 2016 at 18:33:36 UTC, ParticlePeter wrote:

On Monday, 6 June 2016 at 16:19:02 UTC, Alex Parrill wrote:

On Monday, 6 June 2016 at 09:43:23 UTC, ParticlePeter wrote:

In C NULL can be used as integer as well as null pointer.
Is there a way to create such a type in D?

The type should have only one value which is obviously 
(0/null).
A extern( C ) function should be able to take it as either 
one.


Overloaded enum pops into my mind as example:
enum NULL = 0;
enum NULL = null;


Is this possible somehow?


I already asked about this: 
https://forum.dlang.org/post/bnkqevhyxwdjjxsct...@forum.dlang.org


Tldr; doesn't seem to be possible without multiple alias this 
or using ABI hacks.


O.k., my web search didn't find that topic. The last reply 
looks promising, wouldn't that work?


That's the ABI hack I mentioned. It abuses the fact that on most 
hardware and compiled, a pointer and a structure containing a 
single pointer have the same binary representation. It will 
likely work, but it isn't guarenteed.


Re: Emulate C's (polymorphic) NULL type

2016-06-06 Thread Alex Parrill via Digitalmars-d-learn

On Monday, 6 June 2016 at 09:43:23 UTC, ParticlePeter wrote:

In C NULL can be used as integer as well as null pointer.
Is there a way to create such a type in D?

The type should have only one value which is obviously (0/null).
A extern( C ) function should be able to take it as either one.

Overloaded enum pops into my mind as example:
enum NULL = 0;
enum NULL = null;


Is this possible somehow?


I already asked about this: 
https://forum.dlang.org/post/bnkqevhyxwdjjxsct...@forum.dlang.org


Tldr; doesn't seem to be possible without multiple alias this or 
using ABI hacks.


Re: Why do some T.init evaluate to true while others to false?

2016-05-30 Thread Alex Parrill via Digitalmars-d-learn

On Friday, 27 May 2016 at 15:49:16 UTC, ArturG wrote:

On Friday, 27 May 2016 at 15:24:18 UTC, Adam D. Ruppe wrote:

On Friday, 27 May 2016 at 15:19:50 UTC, ArturG wrote:

yes but i have to check for that when some one does


Why? This is no different than if they set any of the other 
four billion possible values.


What do you mean?

operation on float.nan gives you a float.nan so why does the 
shortcut evaluate to true and not false wouldnt that make more 
sense?


NaN in IEEE 754 floating-point numbers (the floating-point number 
system most languages and processors use) is defined as a number 
with all exponent bits set and a non-zero mantissa. The mantissa 
value is the "NaN payload", and can be any value.


`is` does a binary comparison on floating-point numbers, so NaNs 
with different payloads will not be considered equal, as you have 
found out with `float.init !is float.nan`.


Re: Why simple code using Rebindable doesn't compile ?

2016-05-30 Thread Alex Parrill via Digitalmars-d-learn

On Monday, 30 May 2016 at 10:09:19 UTC, chmike wrote:

This code compile, but array appending doesn't work


alias Rebindable!(immutable(InfoImpl)) Info;

class InfoImpl
{
void foo() {}
static immutable(InfoImpl) info()
{
__gshared immutable InfoImpl x = new immutable InfoImpl;
return x;
}
}


void main()
{
Info t = Info.info;
Info[] a;
//a ~= Info.info; <--  KO Compiler Error
a ~= rebindable(Info.info); // Ok
}
-

Why can't info() return a Rebindable!(immutable(InfoImpl)) ?


What do you mean? `info` returns an `immutable(InfoImpl)`, not a 
`Rebindable!(immutable(InfoImpl))`. Rebindable doesn't apply 
itself to the return types of the methods of the return types 
(there's no reason to).


Re: Testing array ptr for offset 0...

2016-05-26 Thread Alex Parrill via Digitalmars-d-learn

On Thursday, 26 May 2016 at 07:51:46 UTC, Era Scarecrow wrote:

...


This smells like an XY problem [0]. Why exactly do you need the 
internal layout of the array structure?


The line "not having to make another array to keep track of 
lengths and then shorten them" is fairly vague. "Shortening" an 
array via slicing is basically free (it's just some integer 
arithmetic), but I'm not sure if that's what you meant.


[0]: 
http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem


Re: Enum that can be 0 or null

2016-05-20 Thread Alex Parrill via Digitalmars-d-learn

On Saturday, 21 May 2016 at 02:04:23 UTC, Mike Parker wrote:

On Saturday, 21 May 2016 at 01:09:42 UTC, Alex Parrill wrote:



Looks like my best bet is to mark it as deprecated and point 
them to Vk(Type).init instead.


I would prefer to do something like this:

enum VK_NULL_HANDLE_0 = 0;
enum VK_NULL_HANDLE_PTR = null;

Then document it clearly. Alias VK_NULL_HANDLE to one of them 
and keep it deprecated forever. Many users are not going to 
read the documentation on their own initiative, so the 
deprecation message telling them how to solve the problem will 
save you from responding to the same issue again and again and 
again.


Hm, I could do `VK_NULL_DISPATCHABLE_HANDLE = null` for the types 
that are always pointers and `VK_NULL_NONDISPATCHABLE_HANDLE = 
null ? IS_64BIT : 0` for types that are either pointers are 
integers depending on arch, but those names are a bit long. Your 
specific example wouldn't work.


Re: Enum that can be 0 or null

2016-05-20 Thread Alex Parrill via Digitalmars-d-learn

On Friday, 20 May 2016 at 22:10:51 UTC, tsbockman wrote:

Why do you need to?

Just use null for pointer types, and 0 for integers. D is not 
C; you aren't *supposed* to be able to just copy-paste any 
random C snippet into D and expect it to work without 
modification.


If that's not a satisfactory answer, please show some specific 
examples of code that you don't know how to make work without 
VK_NULL_HANDLE so that I can propose a workaround.


Because, as I mentioned in the OP, for VK_NULL_HANDLE to work 
like it does in C on 32-bit systems, it needs to be compatible 
with both pointer types (VkDevice, VkInstance, etc) and 64-bit 
integer types (VkFence, VkSemaphore, many others).


There is of course a workaround: since VK_NULL_HANDLE is always 
zero/null, Vk(Type).init will work as a replacement as long as 
you match up the types. But then people will try to use 
VK_NULL_HANDLE (as every C or C++ Vulkan tutorial or reference 
will instruct) and find out that either a) it doesn't work or b) 
it works fine on their 64 bit development system, but then cause 
a ton of errors when they try to compile their project for a 
32-bit system.


Looks like my best bet is to mark it as deprecated and point them 
to Vk(Type).init instead.


Enum that can be 0 or null

2016-05-20 Thread Alex Parrill via Digitalmars-d-learn
(How) can I make a constant that is either zero or null depending 
on how it is used?


Vulkan has a VK_NULL_HANDLE constant which in C is defined to be 
zero. It is used as a null object for several types of objects. 
In D however, zero is not implicitly convertible to a null 
pointer, and vice versa.


On 64 bit platforms, those types are all pointers, so there I can 
define VK_NULL_HANDLE as null. But on 32 bit platforms, some of 
the types are pointers and others are ulongs, and my definition 
of VK_NULL_HANDLE should be compatible with both.


Anyone have an idea on how to make this work?


Re: ErrorException thrown when errno is modified ?

2016-05-19 Thread Alex Parrill via Digitalmars-d-learn

On Thursday, 19 May 2016 at 13:05:19 UTC, chmike wrote:

Hello,

I'm planning to call some posix functions core.sys.posix that 
may set the errno value in case of error. e.g. read() or 
write().


Checking the std.exception documentation I see that 
ErrnoException may be thrown when errors setting errno may 
occur. Does this affect the posix calls ?


From what I saw in the code, it doesn't seam the case. Just 
making sure I'm correct.


ErrnoException is the exception thrown by errnoEnforce, which is 
a convenient function for checking system calls.


D links to the same Posix functions that C does; their behavior 
is exactly the same (ie they don't throw).


Re: Single-Allocation Variable-Sized Array

2016-05-18 Thread Alex Parrill via Digitalmars-d-learn

On Wednesday, 18 May 2016 at 21:28:56 UTC, Nordlöw wrote:
What's the preferred way in D to implement single-allocation 
variable-sized arrays such as


/** Single-Allocation Array. */
struct ArrayN
{
ubyte length;  // <= maxLength
size room; // allocated length
ubyte[0] data; // `room` number of bytes follows
}

where insertion/deletion typically is done via

ArrayN* pushBack(ArrayN*, ubyte element);
ArrayN* popBack(ArrayN*);

which, when needed, will reallocate a new larger/smaller 
`ArrayN`


?

Further, what's the official name for this structure?


In C it's called a variable-length struct or object. I don't 
think D implements them, but this could probably work:


struct Foo {
size_t len;

ubyte[] data() @property {
auto thisptr = cast(ubyte*)();
return thisptr[Foo.sizeof..(Foo.sizeof+len)];
}
}



Re: parameter pack to inputRange

2016-05-09 Thread Alex Parrill via Digitalmars-d-learn

On Sunday, 8 May 2016 at 14:11:31 UTC, Ali Çehreli wrote:
I like Alex Parrill's only() solution but it allocates a 
dynamic array as well by doing the equivalent of [args] in the 
guts of its implementation.


No it does not.

The constructor does `this.data = [values];`, but `this.data` is 
a fixed-sized array, which is stored in the structure itself. No 
allocation needs to happen (it should be the same as the foreach 
loop in your implementation).


You guys are just re-inventing `only`.


Re: parameter pack to inputRange

2016-05-06 Thread Alex Parrill via Digitalmars-d-learn

On Friday, 6 May 2016 at 05:00:48 UTC, Erik Smith wrote:
Is there an existing way to adapt a parameter pack to an input 
range? I would like to construct an array with it.  Example:


void run(A...) (A args) {
 Array!int a(toInputRange(args));
}


Use std.range.only: http://dlang.org/phobos/std_range.html#only

void run(A...)(A args) {
auto rng = only(args);
// ...
}


Re: what's the right way to get char* from string?

2016-05-05 Thread Alex Parrill via Digitalmars-d-learn

On Thursday, 5 May 2016 at 07:49:46 UTC, aki wrote:

extern (C) int strcmp(char* string1, char* string2);


This signature of strcmp is incorrect. strcmp accepts const char* 
arguments [1], which in D would be written as const(char)*. The 
immutable(char)* values returned from toStringz are implicitly 
convertible to const(char)* and are therefore useable as-is as 
arguments to strcmp.


import std.string;
extern (C) int strcmp(const(char)* string1, const(char)* string2);
auto v = strcmp(somestring1.toStringz, somestring2.toStringz);

[1] http://linux.die.net/man/3/strcmp


Re: what is equivalent to template template

2016-05-03 Thread Alex Parrill via Digitalmars-d-learn

On Tuesday, 3 May 2016 at 21:31:35 UTC, Erik Smith wrote:
C++ has template templates.  I'm not sure how to achieve the 
same effect where (in example below) the template function 
myVariadic is passed to another function.


void myVaridatic(A...)(A a) {}

static void call(alias F,A...)(F f,A a) {
f(a);
}

void foo() {
call(myVaridatic,1,2,3);
}


You're close.

An `alias` template parameter can be any symbol, including a 
template. But you can't pass in a template as a runtime 
parameter, so having `F f` in your parameters list is wrong 
(there's nothing to pass anyway; you already have the template, 
which is F).


static void call(alias F, A...)(A a) {
F(a);
}

Then instantiate and call the `call` function with the template 
you want:


call!myVariadict(1,2,3);


Re: constructed variadic call

2016-05-03 Thread Alex Parrill via Digitalmars-d-learn

On Monday, 2 May 2016 at 18:22:52 UTC, Erik Smith wrote:
Is there way to construct an "argument pack" from a non-static 
array (like the switch below)?  I need to transport a variadic 
call through a void*.


switch (a.length) {
  case 1: foo(a[1]); break;
  case 2: foo(a[1], a[2]); break;
  case 3: foo(a[1], a[2], a[3]); break;
...
}


I don't think it's possible to call a vararg function whose 
number of arguments is only known at runtime, for the same 
reasons it is impossible in C [1].


Your switch statement is probably the best you can do, other than 
rewriting the API to not use varargs (which, depending on what 
the function is doing, I would recommend). You can possibly use 
string mixins or static foreach to avoid repeating the case 
clauses.


[1] Populating a va_list: 
http://stackoverflow.com/questions/988290/populating-a-va-list


Re: Garbage Collector : Ignoring a reference

2016-04-26 Thread Alex Parrill via Digitalmars-d-learn

On Tuesday, 26 April 2016 at 09:07:59 UTC, Begah wrote:
I am trying to create an asset manager for my textures. I had 
the idea ( it may be a wrong idea ) to create a hashmap of my 
textures with a string as the key. When the program request a 
texture, it firts check if it is in the hashmap and then 
returns if it is :


[...]


What you want are "weak references". I don't think D supports 
them yet.


Re: Handling arbitrary char ranges

2016-04-20 Thread Alex Parrill via Digitalmars-d-learn

On Wednesday, 20 April 2016 at 22:44:37 UTC, ag0aep6g wrote:

On 20.04.2016 23:59, Alex Parrill wrote:

On Wednesday, 20 April 2016 at 17:09:29 UTC, Matt Kline wrote:

[...]


First, you can't assign anything to a void[], for the same 
reason you
can't dereference a void*. This includes the slice assignment 
that you
are trying to do in `buf[0..minLen] = 
remainingData[0..minLen];`.


Not true. You can assign any dynamic array to a void[].


That's not assigning the elements of a void[]; it's just changing 
what the slice points to and adjusting the length, like doing 
`void* ptr = someOtherPtr;`


Regarding vector notation, the spec doesn't seem to mention how 
it interacts with void[], but dmd accepts this no problem:


int[] i = [1, 2, 3];
auto v = new void[](3 * int.sizeof);
v[] = i[];



It only seems to work on arrays, not arbitrary ranges, sliceable 
or not. Though see below.



[...]
Second, don't use slicing on ranges (unless you need it). Not 
all ranges

support it...


As far as I see, the slicing code is guarded by `static if 
(isArray!T)`. Arrays support slicing.


[...]

Instead, use a loop (or maybe `put`) to fill the array.


That's what done in the `else` path, no?


Yes, I did not see the static if condition, my bad.


Third, don't treat text as bytes; encode your characters.

 auto schema = EncodingScheme.create("utf-8");
 auto range = chain("hello", " ", "world").map!(ch => 
cast(char) ch);


 auto buf = new ubyte[](100);
 auto currentPos = buf;
 while(!range.empty && schema.encodedLength(range.front) <=
currentPos.length) {
 auto written = schema.encode(range.front, currentPos);
 currentPos = currentPos[written..$];
 range.popFront();
 }
 buf = buf[0..buf.length - currentPos.length];


You're "converting" chars to UTF-8 here, right? That's a nop. 
char is a UTF-8 code unit already.


It can be either chars, wchars, or dchars.

(PS there ought to be a range in Phobos that encodes each 
character,

something like map maybe)


std.utf.byChar and friends:

https://dlang.org/phobos/std_utf.html#.byChar


byChar would work. byWChar and byDChar might cause endian-ness 
issues.


Re: Handling arbitrary char ranges

2016-04-20 Thread Alex Parrill via Digitalmars-d-learn

On Wednesday, 20 April 2016 at 17:09:29 UTC, Matt Kline wrote:

[...]


First, you can't assign anything to a void[], for the same reason 
you can't dereference a void*. This includes the slice assignment 
that you are trying to do in `buf[0..minLen] = 
remainingData[0..minLen];`.


Cast the buffer to a `ubyte[]` buffer first, then you can assign 
bytes to it.


auto bytebuf = cast(ubyte[]) buf;
bytebuf[0] = 123;

Second, don't use slicing on ranges (unless you need it). Not all 
ranges support it...


auto buf = [1,2,3];
auto rng = filter!(x => x != 1)(buf);
pragma(msg, hasSlicing!(typeof(rng))); // false

... and even ranges that support it don't support assigning to an 
array by slice:


auto buf = new int[](3);
	buf[] = only(1,2,3)[]; // cannot implicitly convert expression 
(only(1, 2, 3).opSlice()) of type OnlyResult!(int, 3u) to int[]


Instead, use a loop (or maybe `put`) to fill the array.

Third, don't treat text as bytes; encode your characters.

auto schema = EncodingScheme.create("utf-8");
	auto range = chain("hello", " ", "world").map!(ch => cast(char) 
ch);


auto buf = new ubyte[](100);
auto currentPos = buf;
	while(!range.empty && schema.encodedLength(range.front) <= 
currentPos.length) {

auto written = schema.encode(range.front, currentPos);
currentPos = currentPos[written..$];
range.popFront();
}
buf = buf[0..buf.length - currentPos.length];

(PS there ought to be a range in Phobos that encodes each 
character, something like map maybe)


Re: VariantPointer

2016-04-20 Thread Alex Parrill via Digitalmars-d-learn

On Wednesday, 20 April 2016 at 13:41:27 UTC, Nordlöw wrote:

At

https://github.com/nordlow/phobos-next/blob/master/src/variant_pointer.d

I've implemented a pointer-only version of Variant called 
VariantPointer.


I plan to use it to construct light-weight polymorphism in trie 
containers for D I'm currently writing.


VariantPointer uses the top N-bits (N currently 8) to encode 
the type pointed to be the untyped-pointer encoded in the 64-N 
bits lower bits.


My question is:

It safe to assume that `typeBits` most significant bits of a 
pointer on a 64-bit system are always zero?


Note that I didn't want to use the lower bits because I'm 
currently unsure whether I need to represent stack-pointers 
aswell.


Linux seems to reject mmap requests at or above 0x800, 
though the vsyscall page is at 0xff60 near the end of 
the virtual memory space. So it might work on Linux.


As for the GC, you're probably out of luck. Adding a global mask 
option is unlikely to work well if multiple libraries use it.


Re: Shallow copy object when type is know

2016-04-20 Thread Alex Parrill via Digitalmars-d-learn

On Wednesday, 20 April 2016 at 12:32:48 UTC, Tofu Ninja wrote:
Is there a way to shallow copy an object when the type is 
known? I cant seem to figure out if there is a standard way. I 
can't just implement a copy function for the class, I need a 
generic solution.


A generic class copy function would require accessing private 
fields, so a clean per-attribute class copy is impossible. Doing 
a bitwise copy might work except for the synchronization mutex 
pointer.


Can you elaborate on why you need this?


Re: Handling arbitrary char ranges

2016-04-20 Thread Alex Parrill via Digitalmars-d-learn

On Wednesday, 20 April 2016 at 17:09:29 UTC, Matt Kline wrote:
I'm doing some work with a REST API, and I wrote a simple 
utility function that sets an HTTP's onSend callback to send a 
string:


[...]


IO functions usually work with octets, not characters, so an 
extra encoding step is needed. For encoding character arrays to 
UTF-#, there's std.string.representation, and std.encoding might 
have something for arbitrary ranges.


Avoid slicing ranges; not all ranges support it. If you 
absolutely need it (you don't here) then add hasSlicing to the 
constraint.


isSomeChar can tell you if a type (like the ranges element type) 
is a character.


Re: .opAssign disabled without @disable

2016-04-16 Thread Alex Parrill via Digitalmars-d-learn

On Saturday, 16 April 2016 at 11:48:56 UTC, denizzzka wrote:

Hi!

DMD and LDC2 complain about disabled opAssign, but I am not 
used @disable and depend package "gfm" also isn't uses @disable.


...


Try removing the const from this line:

debug private const bool isLeafNode = false;

I suspect that D is disabling whole-structure assignment since 
allowing it would mean that the constant `isLeafNode` could be 
changed.


Re: Lazy evaluation of function pointers.

2016-04-10 Thread Alex Parrill via Digitalmars-d-learn

On Sunday, 10 April 2016 at 18:08:58 UTC, Ryan Frame wrote:

Greetings.

The following code works:

void main() {
passfunc();
}

void passfunc(void function(string) f) {
f("Hello");
}

void func(string str) {
import std.stdio : writeln;
writeln(str);
}

Now if I change passfunc's signature to "void passfunc(lazy 
void function(string) f)" I would get the compiler error 
"Delegate f () is not callable using argument types (string)". 
I can lazily pass a void function() -- it seems that there is 
only a problem when the function contains parameters.


The only difference should be when the pointer is evaluated, so 
why does lazy evaluation matter here?


Thank you for your time
--Ryan


A parameter declared as `lazy T` has the type `T delegate()`, 
which, when called, evaluates the expression that was passed into 
the function.


So effectively, this:

void foo(lazy int x) { auto i = x(); }
foo(a+b);

Is the same as this:

void foo(int delegate() x) { auto i = x(); }
foo(() => a+b);

T in your case is `void function(string)`. So you can do `auto 
func = f()` to get the function you passed in. It's not very 
useful in your example to lazily evaluate getting a function 
pointer, considering it's usually a constant expression after 
compiling.


Re: Fiber and Thread Communication

2016-04-08 Thread Alex Parrill via Digitalmars-d-learn

On Friday, 8 April 2016 at 14:08:39 UTC, Nordlöw wrote:


So a TId can represent either a thread or a fiber?


It represents a "logical thread", which currently consists of 
coroutines or OS threads but could theoretically be extended to, 
say, other processes or even other machines.


Re: __traits(compiles) and template instantiation

2016-04-07 Thread Alex Parrill via Digitalmars-d-learn

On Thursday, 7 April 2016 at 20:31:12 UTC, jmh530 wrote:
I've been playing around with __traits and I find myself 
confused on one aspect. In the code below, I was testing 
whether some templates would compile given types. For the most 
part it works as I would expect.


I think I get why the third one works with foo!(int). My guess 
is that it assumed that U is the same as T and both are int. 
However, that wouldn't make sense with the last one where I use 
bar!(int). In that one it's basically ignoring the second 
template constraint. So I don't understand what's going on for 
that last line to compile. To confirm I wasn't crazy, I get an 
error with

alias bar_ = bar!(int);



import std.traits : isNumeric;
import std.range : isInputRange;

void foo(T, U)(T x, U y) if (isNumeric!T && isNumeric!U) { }

void bar(T, U)(T x, U y) if (isNumeric!T && isInputRange!U) { }

void main()
{
assert(__traits(compiles, foo!(int, int))); //I get this
assert(!__traits(compiles, foo!(bool, bool)));  //I get this
assert(__traits(compiles, foo!(int)));  //I think I get this
assert(__traits(compiles, bar!(int, int[])));   //I get this
assert(!__traits(compiles, bar!(int, int)));//I get this
assert(__traits(compiles, bar!(int)));  //I don't get this
}


Neither the third nor sixth lines should be true.

alias wrongfoo = foo!int; /* Error: template instance foo!int 
does not match template declaration foo(T, U)(T x, U y) if 
(isNumeric!T && isNumeric!U) */

alias rightfoo = foo!(int, int); /* ok */

File a DMD bug.

(Also, you can use static assert here to check the assertions at 
build-time instead of run-time)


Re: Best properly way to destroy a 2 dimensional array?

2016-04-06 Thread Alex Parrill via Digitalmars-d-learn

On Wednesday, 6 April 2016 at 23:14:10 UTC, Jonathan Villa wrote:

On Wednesday, 6 April 2016 at 21:33:14 UTC, Alex Parrill wrote:

My general idea is first to get the predicted quantity of 
combinations


Seems like you already know; your OP says you have 2^n 
combinations.



so I can divide and parallelize them.


std.parallelism.parallel can do this for you, and works on ranges.

http://dlang.org/phobos/std_parallelism.html#.parallel

What do you think can be the problem with the lack of 
deallocation?


Don't know exactly. destroy just runs the destructors, it doesn't 
free any memory. Since the arrays are still in scope, it might 
not be able to free them.


Re: Putting things in an enum's scope

2016-04-06 Thread Alex Parrill via Digitalmars-d-learn

On Wednesday, 6 April 2016 at 13:59:42 UTC, pineapple wrote:
Is there any way in D to define static methods or members 
within an enum's scope, as one might do in Java? It can 
sometimes help with code organization. For example, this is 
something that coming from Java I'd have expected to be valid 
but isn't:


enum SomeEnum{
NORTH, SOUTH, EAST, WEST;

static int examplestaticmethod(in int x){
return x + 2;
}
}

int z = SomeEnum.examplestaticmethod(2);


You can use UFCS:

enum SomeEnum { NORTH, ... }

int examplestaticmethod(in SomeEnum e) { return e+2; }

SomeEnum.NORTH.examplestaticmethod();


Re: Best properly way to destroy a 2 dimensional array?

2016-04-06 Thread Alex Parrill via Digitalmars-d-learn

On Wednesday, 6 April 2016 at 19:54:32 UTC, Jonathan Villa wrote:
I wrote a little program that given some number it generates a 
list of different combinations (represented by a ubyte array), 
so in the end my function with name GenerateCombinations(int x) 
returns a ubyte[][] (list of arrays of ubytes).


...


Why not make a range instead? No need to reserve memory for the 
entire array if you can compute the elements as-needed.


If you really want an array, std.experimental.allocator will let 
you manually allocate/release objects.


Re: What's the rationale for considering "0x1.max" as invalid ?

2016-04-06 Thread Alex Parrill via Digitalmars-d-learn

On Tuesday, 5 April 2016 at 21:40:59 UTC, Basile B. wrote:

On Tuesday, 5 April 2016 at 21:10:47 UTC, Basile B. wrote:

On Tuesday, 5 April 2016 at 20:56:54 UTC, Alex Parrill wrote:

On Tuesday, 5 April 2016 at 19:00:43 UTC, Basile B. wrote:

0x1.max // exponent expected in hex float
0x1 .max // OK
1.max // OK

What's the ambiguity when it's an hex literal ?


It's potentially ambiguous with hexadecimal floating point 
numbers


0xdeadbeef.p5 // hex float or hex int + method?

dlang.org/spec/lex.html#HexFloat


Yes but it's pointless to allow the decimal separator to be 
followed by the exponent:


void main()
{
import std.stdio;
writeln( typeof(0x1p5).stringof ); // double
writeln( typeof(0x1.p5).stringof ); // double
}


I mean that the rule could be: the decimal separator must be 
followed by a second group of digits. The second group of 
digits must be followed by an exponent. The first group of 
digits can be followed by an exponent.


0x1.0p5 // valid
0xp5 // valid
0x1.p5 // invalid (p is not a hex digit)
0x1.ap5 // valid


Looks like that's how it works for decimal floats; I.e. 1.e5 is 
an int and property lookup, while 1.0e5 is 10f. Curiously, 1. 
Is 1.0.


I agree that floats should be parsed consistently. For now, you 
can do (0x1).max or typeof(0x1).max.


Re: What is the best way to store bitarray (blob) for pasting in database?

2016-04-06 Thread Alex Parrill via Digitalmars-d-learn

On Wednesday, 6 April 2016 at 12:56:39 UTC, Suliman wrote:

I have next task.
There is PostgreSQL DB. With field like: id, mydata.

mydata - is binary blob. It can be 10MB or even more.

I need load all data from PostgreSQL to SQLLite.

I decided ti create struct that and fill it with data. And then 
do INSERT operation in sqllite.


But I do not know is it's good way, and if it's ok what data 
type should I use for blob (binary data).


struct MyData
{
string  id;
string  mydata; // what datatype I should use here??
}   

MyData [] mydata;

MyData md;


while (rs.next())
{

 md.id = to!string(rs.getString(1));
 md.mydata = to!string(rs.getString(2)); //??

 mydata ~= md;
}



stmtLite.executeUpdate(`insert into MySyncData(id,mydata) 
values(md.id,md.data)`); //ddbc driver

is it's normal way to insert data?


Blobs are byte arrays, so they should be ubyte[]. They shouldn't 
be strings, which are explicitly text only.


Re: What's the rationale for considering "0x1.max" as invalid ?

2016-04-05 Thread Alex Parrill via Digitalmars-d-learn

On Tuesday, 5 April 2016 at 19:00:43 UTC, Basile B. wrote:

0x1.max // exponent expected in hex float
0x1 .max // OK
1.max // OK

What's the ambiguity when it's an hex literal ?


It's potentially ambiguous with hexadecimal floating point numbers

0xdeadbeef.p5 // hex float or hex int + method?

dlang.org/spec/lex.html#HexFloat


Re: Need help with delegates and vibed

2016-03-19 Thread Alex Parrill via Digitalmars-d-learn

On Saturday, 19 March 2016 at 19:53:01 UTC, Suliman wrote:

Thanks! I am understand a little bit better, but not all.

```
shared static this()
{
auto settings = new HTTPServerSettings;
settings.port = 8080;

listenHTTP(settings, );
}

void handleRequest(HTTPServerRequest req,
   HTTPServerResponse res)
{
if (req.path == "/")
res.writeBody("Hello, World!", "text/plain");
}
```
https://github.com/rejectedsoftware/vibe.d/blob/master/source/vibe/http/server.d#L104
I expected to see in listenHTTP() function some processing but 
it's simply get args and then do return:

return listenHTTP(...)

Could you explain why it's do so?

--
Where is constructor of this class? 
http://vibed.org/api/vibe.http.client/HTTPClientRequest


How I should use it if have only docs, and do not have 
examples? (I am trying understand how to use docs without 
cope-past examples)


The function is overloaded; it's calling the main implementation 
at line 77 after transforming the arguments.


The constructor for HTTPClientRequest is likely undocumented 
because you should not construct it yourself; vibe.d constructs 
it and passes it to the function you register with listenHTTP.


Re: Error: constructor Foo.this default constructor for structs only allowed with @disable, no body, and no parameters

2016-03-07 Thread Alex Parrill via Digitalmars-d-learn

On Monday, 7 March 2016 at 13:23:58 UTC, Nicholas Wilson wrote:
I'm not quite sure what this error is saying. Is it that the 
only struct constructor that can have no parameters is @disable 
this(){} ?


Yes, this is exactly right. You cannot have a structure with a 
default constructor, except with @disable.


You can, however, specify the initial values of fields, as in 
your second example. Note that you can use typeof on the variable 
you are currently declaring.


VkFenceCreateInfo CI = 
typeof(CI)(cast(typeof(CI.sType))StructureType.eFenceCreateInfo, 
null, 0);




Re: std.range: Lockstep vs. Zip

2016-03-03 Thread Alex Parrill via Digitalmars-d-learn

On Wednesday, 2 March 2016 at 08:51:07 UTC, Manuel Maier wrote:

Hi there,

I was wondering why I should ever prefer std.range.lockstep 
over std.range.zip. In my (very limited) tests std.range.zip 
offered the same functionality as std.range.lockstep, i.e. I 
was able to iterate using `foreach(key, value; 
std.range.zip(...)) {}` which, according to the docs, is what 
std.range.lockstep was supposed to be designed for. On top of 
that, std.range.zip is capable of producing a 
RandomAccessRange, but std.range.lockstep only produces 
something with opApply.


Cheers
zip uses the InputRange protocol, and bundles up all the values 
in a Tuple.


lockstep uses the opApply protocol, and doesn't bundle the values.

Lockstep is useful for foreach loops since you don't need to 
unpack a tuple, but zip is compatible with all of the std.range 
and std.algorithm functions that take ranges.


Re: Combining template conditions and contracts?

2016-02-29 Thread Alex Parrill via Digitalmars-d-learn

On Monday, 29 February 2016 at 14:38:52 UTC, Ozan wrote:

Is it possible to combine  template conditions and contracts?
Like in the following


T square_root(T)(T x)  if (isBasicType!T) {
in
{
assert(x >= 0);
}
out (result)
{
assert((result * result) <= x && (result+1) * (result+1) > 
x);

}
body
{
return cast(long)std.math.sqrt(cast(real)x);
}

Compiler says no. Maybe it's a missunderstanding from my side..

Thanks & regards, Ozan


You have a spare { after the template constraint in your sample


Re: Why file.exists of relative path on Linux always return false?

2016-02-29 Thread Alex Parrill via Digitalmars-d-learn

On Monday, 29 February 2016 at 14:50:51 UTC, Suliman wrote:

I am trying to check relative path on Linux for exists.

import std.stdio;
import std.path;
import std.file;
import std.string;



string mypath = "~/Documents/imgs";

void main()
{
 if(!mypath.exists)
{
writeln(mypath, " do not exists");
}

 if(!mypath.exists)
{
writeln(mypath, " do not exists");
}

 if("/home/dima/Documents/imgs".exists)
{
writeln("/home/dima/Documents/imgs");
writeln("Dir exists");
}

}

~/Documents/imgs always return "do not exists". But full path: 
"/home/dima/Documents/imgs" is "Dir exists".


Why? It's same paths!


~ is expanded by your shell. It is not a relative path, and 
system calls do not recognize it (same with environmental 
variables).


See also 
http://stackoverflow.com/questions/3616595/why-mkdir-fails-to-work-with-tilde


Re: C Macro deeper meaning?

2016-01-31 Thread Alex Parrill via Digitalmars-d-learn

On Sunday, 31 January 2016 at 02:58:28 UTC, Andrew Edwards wrote:

If I understand correctly, this piece of code:
enum NOTUSED(v) do { (void)(1 ? (void)0 : ( (void)(v) ) ); 
} while(0)


can be converted to the following in D:

void notUsed(T)(T v) { return cast(void)0; };

since it always returns cast(void)0 regardless of the input.

But it cannot be that simple, so what am I missing?

Thanks,
Andrew Edwards


Might want to change the function argument to `ref T v`, as 
struct postblits might run otherwise. Probably no reason to 
`return` either.


Re: Nothrow front() when not empty()

2016-01-06 Thread Alex Parrill via Digitalmars-d-learn

On Wednesday, 6 January 2016 at 14:17:51 UTC, anonymous wrote:

try return !haystack.empty && pred(haystack.front);


Might want to use std.exception.assumeWontThrow instead

return assumeWontThrow(!haystack.empty && 
pred(haystack.front));


http://dlang.org/phobos/std_exception.html#.assumeWontThrow


Re: link to C++ function in a namespace whose name is a D keyword

2016-01-06 Thread Alex Parrill via Digitalmars-d-learn
On Wednesday, 6 January 2016 at 18:35:07 UTC, Carl Sturtivant 
wrote:

Hello,

From D I want to call e.g.

/* C++ prototype */
namespace ns {
int try(int x);
}

without writing a C or C++ wrapper.

Presumably the following D doesn't work, because it doesn't 
mangle the name as if it's in the namespace ns.


pragma(mangle, "try") extern(C++, ns) int try_(int x);

So how to I get correct mangling here?


Isn't try a C++ keyword though? Wouldn't that make it impossible 
to use in an identifier?


Re: reduce a BitArray[]

2015-12-29 Thread Alex Parrill via Digitalmars-d-learn

On Tuesday, 29 December 2015 at 09:26:31 UTC, Alex wrote:
The problem is, that the last line with the reduce does not 
compile. Why?


If you get an error, it is imperative that you tell us what it is.

For the record, this code:

import std.bitmanip;
import std.stdio;
import std.algorithm;

void main() {

		BitArray[] arr7 = [BitArray([0, 1, 0, 1, 0, 1]), BitArray([0, 
1, 0, 0, 0, 0]), BitArray([0, 1, 0, 1, 0, 0]), BitArray([0, 1, 0, 
1, 0, 0])];


BitArray common = BitArray([1,1,1,1,1,1]);
foreach(BitArray ba; arr7)
{
common &=  ba;
}
writeln("common2: ", common);

writeln("common1: ", reduce!((a,b) => a & b)(arr7));
}

Gives me the error:

/opt/compilers/dmd2/include/std/algorithm/iteration.d(2570): 
Error: variable f868.main.F!(__lambda1).e cannot be declared to 
be a function
/opt/compilers/dmd2/include/std/meta.d(546): Error: template 
instance f868.main.F!(__lambda1) error instantiating
/opt/compilers/dmd2/include/std/algorithm/iteration.d(2477):  
  instantiated from here: staticMap!(ReduceSeedType, __lambda1)
/d486/f868.d(16):instantiated from here: 
reduce!(BitArray[])
/d486/f868.d(16): Error: template std.algorithm.iteration.reduce 
cannot deduce function from argument types !((a, b) => a & 
b)(BitArray[]), candidates are:
/opt/compilers/dmd2/include/std/algorithm/iteration.d(2451):  
  std.algorithm.iteration.reduce(fun...) if (fun.length >= 1)


On 2.069.1 (dpaste: http://dpaste.dzfl.pl/8d7652e7ebeb). I don't 
have time ATM to diagnose it further. It definitely shouldn't be 
that cryptic of an error message.


Re: argument type const char* can pass string, buf why const wchar* can not pass wstring

2015-12-26 Thread Alex Parrill via Digitalmars-d-learn

On Sunday, 27 December 2015 at 03:34:18 UTC, riki wrote:

void ccf(const char* str){}
void cwf(const wchar* str){}

void main()
{
ccf("aaa");//ok
cwf("xxx"w); // error and why ?
}


Unrelated to your error, but those functions should probably take 
a `string` and `wstring` respectively instead.


Re: Convert to string an enum item

2015-12-23 Thread Alex Parrill via Digitalmars-d-learn

On Wednesday, 23 December 2015 at 13:11:28 UTC, tcak wrote:

[code]
import std.stdio;
import std.conv;

enum Values: ubyte{ One = 1, Two = 2 }

void main(){
writeln( std.conv.to!string( Values.One ) );
}
[/code]

Output is "One".

casting works, but to be able to cast correctly, I need to tell 
compiler that it is "ubyte".


Isn't there any NON-HACKISH solution to print out the value of 
enum item? And do not decrease the performance as well please. 
It runs on web server.




So you want the enum's integer value? Try casting it to an 
integer.


writeln(cast(ubyte) Values.One);


Re: Why should file names intended for executables be valid identifiers?

2015-12-17 Thread Alex Parrill via Digitalmars-d-learn
On Tuesday, 15 December 2015 at 03:31:18 UTC, Shriramana Sharma 
wrote:
I expect it should not be difficult for the compiler to see 
that this D file is not a module being imported by anything 
else or even being compiled to a library which would need to be 
later imported. In which case, why does it insist that the file 
should be given a valid module name?


All files in D are modules. The only thing special about the 
"main" module is that it exports a function called `main`, which 
druntime calls at startup.


It's like asking why you need to have a class in Java that only 
contains `public static void main(...)`, instead of just having 
the main function itself; it's simply how D is designed, and it 
reduces the number of special cases.


Though after compiling, module names are irrelevant; you can name 
the binary whatever you want: `dmd -o whatever-filename.exe 
my_module.d`


Name mangling is irrelevant; you can't have a dash in the module 
name because it would make certain code ambiguous (ex. 
`foo.my-module.bar`: is one module field reference or a 
subtraction between two field references?)


Re: deep copying / .dup / template object.dup cannot deduce function from argument types

2015-12-13 Thread Alex Parrill via Digitalmars-d-learn
On Sunday, 13 December 2015 at 18:54:24 UTC, Robert M. Münch 
wrote:

Hi, I just wanted to naively copy an object and used:

a = myobj.dup;

and get the following error messages:

source/app.d(191): Error: template object.dup cannot deduce 
function from argument types !()(BlockV), candidates are:
/Library/D/dmd/src/druntime/import/object.d(1872):
object.dup(T : V[K], K, V)(T aa)
/Library/D/dmd/src/druntime/import/object.d(1908):
object.dup(T : V[K], K, V)(T* aa)
/Library/D/dmd/src/druntime/import/object.d(3246):
object.dup(T)(T[] a) if (!is(const(T) : T))
/Library/D/dmd/src/druntime/import/object.d(3262):
object.dup(T)(const(T)[] a) if (is(const(T) : T))
/Library/D/dmd/src/druntime/import/object.d(3273):
object.dup(T : void)(const(T)[] a)


Hmm... so, is .dup not the way to go?

And, am I correct, that a deep-copy needs to be hand coded?


`dup` is an array method; it only works on arrays.

Structs are value types, so `a = b` will "duplicate" a struct. 
For classes, you will need to define your own clone function.


Re: How do you create an opengl window with DerelictOrg?

2015-12-07 Thread Alex Parrill via Digitalmars-d-learn

On Monday, 7 December 2015 at 21:33:57 UTC, Enjoys Math wrote:

I've seen these:
https://github.com/DerelictOrg?page=1

BUt not sure how to use them, examples?


Derelict is just bindings for other libraries, for using C 
libraries with D. Pick a library that does windows management (I 
use GLFW, but I also see SFML and SDL), find the docs for them.


Re: AA struct hashing bug?

2015-12-07 Thread Alex Parrill via Digitalmars-d-learn

On Monday, 7 December 2015 at 18:48:18 UTC, Random D user wrote:

struct Foo
{
this( int k )
{
a = k;
}
int a;
}

Foo foo;
int[ Foo ] map;

map[ foo ] = 1;  // Crash! bug?

// This also crashes. I believe crash above makes a call like 
this (or similar) in the rt.

//auto h = typeid( foo ).getHash(  ); // Crash!

win64 & dmd 2.69.2


Also works on DMD v2.069.2 on XUbuntu Linux x64. I can try it on 
Windows later.


Exact code I tested:

struct Foo
{
this( int k )
{
a = k;
}
int a;
}

void main() {
Foo foo;
int[ Foo ] map;

map[ foo ] = 1;
}



Re: mutex usage problem?

2015-12-02 Thread Alex Parrill via Digitalmars-d-learn

On Wednesday, 2 December 2015 at 13:55:02 UTC, Ish wrote:
The following code does core dump (compiled with gdc). Pointers 
will be appreciated.

import std.stdio;
import std.conv;
import std.math;
import std.concurrency;
import core.thread;
import core.sync.mutex;

enum count = 5;
__gshared double rslt = 0.0;
__gshared Mutex mutex;

void term(immutable(int)* nterm) {
double r;
auto n = to!double(*nterm);
r = 4.0*pow(-1.0, *nterm)/(2.0*n + 1);
writefln("%s: %6.6f.", *nterm, r);
mutex.lock();
   rslt = rslt + r;
mutex.unlock();
}


void main() {

foreach (i; 0 .. count) {
int* jm = new int;
*jm = i;
immutable int *j = cast(immutable) jm;
Tid tid = spawn(, j);
}

thread_joinAll();
writefln("Result: %6.9f.", rslt);
}

-ish


You never initialize Mutex, so it is a null pointer when you call 
`mutex.lock`.


Also, no point in passing a pointer here; just pass `i` instead 
of `j`.


Re: std.socket replacement

2015-11-29 Thread Alex Parrill via Digitalmars-d-learn

On Sunday, 29 November 2015 at 09:12:14 UTC, tired_eyes wrote:

On Sunday, 29 November 2015 at 09:05:37 UTC, tcak wrote:

On Sunday, 29 November 2015 at 08:56:30 UTC, tired_eyes wrote:
I was a bit surprised to see that std.socket is deprecated as 
of 2.069. Just curious, what's wrong with it? And what should 
I use as a replacement? I know there is vibe.socket, but I 
don't want to include fullstack web framework as a dependency 
just to make some HTTP reqests.


I also don't see any proposed replacements in a review queue. 
Will std.socket and std.socketstream be just thrown away?


I would say "WTF" at first, then checked the documentation, 
but don't see anything

about deprecation. My current whole business relies on that.


Wow, sorry, I meant std.stream and std.socketstream, not 
std.socket and std.socketstream


std.stream, and the stream interface in general, is deprecated in 
favor of ranges, which are more generic and flexible.


Re: Password Storage

2015-11-26 Thread Alex Parrill via Digitalmars-d-learn

On Friday, 27 November 2015 at 00:17:34 UTC, brian wrote:
I'm starting to build a small web-based application where I 
would like to authenticate users, and hence need to store 
passwords.


After reading this:
http://blog.codinghorror.com/youre-probably-storing-passwords-incorrectly/
and many other posts that I zombie-surfed to from that page, 
I'm now fearful of doing this badly. :(


My reading of that post was that I should be storing things as:

hash = md5('salty-' + password)

So when a user tries to authenticate, I need to:
1) validate the user id
2) find the unique "salt" I generated for that user when they 
registered
3) pre- or post-pend the salt to the password entered 
(apparently there is a difference??)

4) md5 the lot
5) check this md5(salt+password) against what I have stored.

So for each user, I need to store in my database:
UserName/UserID
Salt
Hashed_Password

Can the developers in the room confirm if this is the correct 
approach?

Are there examples of betters ways of doing this?

Regards
Brian


Do not use MD5 or SHA for hashing passwords. Use PBKDF2, bcrypt, 
or maybe scrypt. There should be C libraries available for those 
algorithms; use them.


More info: 
http://security.stackexchange.com/questions/211/how-to-securely-hash-passwords/31846#31846


Re: Password Storage

2015-11-26 Thread Alex Parrill via Digitalmars-d-learn

On Friday, 27 November 2015 at 00:50:25 UTC, brian wrote:


Thanks for the blatant faux pas.
I wasn't going to use MD5, I just meant "hash it somehow", 
which was not apparent from my question. My bad.


Algorithm aside, the rest of that approach seems sensible then?

The hash implementation was probably going to be a part 2 of 
this question.
I'd use dcrypt (https://github.com/puzzlehawk/dcrypt) to keep 
all the d-goodness, but according to the author, that's not 
"production ready" yet.
In lieu of that, I'll have a gander at those libraries you 
mentioned.


Yea. I've used bcrypt a few times; it's usually just using the 
hash function to hash the passwords, then the check function to 
check them, and that's it (bcrypt stores the salt along with the 
password).


I don't know if I'd trust dcrypt yet. No offence to the authors, 
but I doubt that it has gone through the review that more popular 
C libraries have.


Re: Exit with code xx

2015-11-25 Thread Alex Parrill via Digitalmars-d-learn

On Wednesday, 25 November 2015 at 16:11:09 UTC, Ozan wrote:

Hi

Is there any overview, list, wiki about what's behind runtime 
errors like

"Program exited with code -11"?

Okay, I made a mistake...but it's better to know where and what 
kind?


Thanks & Regards,
Ozan


You know about process exit codes right? On Linux, a negative 
exit code means that the process exited due to a signal. Signal 
11 is SIGSEGV, aka a segmentation fault.


Run your binary in a debugger (ex. gdb) and find out where it's 
causing the error.


Re: template this and traits getOverloads issue.

2015-11-20 Thread Alex Parrill via Digitalmars-d-learn
Alternatively, you can use a static method and pass in the 
instance.


Note that `new B` will print A's members twice, because A's 
constructor is always called and `__traits(allMembers, B)` 
includes A's members.


---

import std.stdio;

mixin template Bug()
{
import std.traits;
static void bug(T)(T t)
{
writeln(">", T.stringof);
foreach(member; __traits(allMembers, T))
foreach(overload; __traits(getOverloads, T, member))
{
auto dg = 
writeln(member);
}
}
}

class A
{
mixin Bug;
this(){bug!A(this);}
void foo(){}
}

class B: A
{
this(){bug!B(this);}
void bar(){}
void bar(uint a){}
}

void main(){
new A;
new B;
}


Re: template this and traits getOverloads issue.

2015-11-20 Thread Alex Parrill via Digitalmars-d-learn

On Friday, 20 November 2015 at 14:01:13 UTC, BBasile wrote:

Background:
===

http://stackoverflow.com/questions/33764540/warning-about-overriden-methods-when-using-a-mixin

Why this horrible trick has to be used:
===

cast this as (T) in a function template that's been mixed in an 
ancestor is not always usable, unless I miss something:



import std.stdio;

mixin template Bug()
{
import std.traits;
void bug(T)()
{
foreach(member; __traits(allMembers, T))
foreach(overload; __traits(getOverloads, T, member))
{
auto dg = 
writeln(member);
}
}
}

class A
{
mixin Bug;
this(){bug!A;}
void foo(){}
}

class B: A
{
void bar(){}
void bar(uint a){}
this(){bug!B;}
}

void main(){
new A;
new B;
}




a.d(11,27): Error: this for bar needs to be type B not type a.A
a.d(11,27): Error: this for bar needs to be type B not type a.A
a.d(11,27): Error: this for this needs to be type B not type a.A



everything that can be done to avoid the compilations errors 
will also prevent "bar" to be written in the output (because a 
B will never be analyzed). The "only" fix I see is like in the 
stack overflow answer: statically check if the mixin methods 
are already there and remix the mixin in each descendant, so 
that the getOverloads traits works on the right 'this'.


What do you think ? is it a bug ?


Templates are not virtual, which is why you might be running into 
issues here; bug thinks it's being called on an `A` object.


But you don't need a template for this case; mixin templates have 
access to `this`:


---
import std.stdio;

mixin template Bug()
{
import std.traits;
override void bug()
{
foreach(member; __traits(allMembers, typeof(this)))
foreach(overload; __traits(getOverloads, 
typeof(this), member))

{
auto dg = 
writeln(member);
}
}
}

// Interface to allow for mixin template to use `override` 
without worrying if

// `bug` is the first implementation or not.
interface IF {
void bug();
}

class A : IF
{
mixin Bug;
this(){bug();}
void foo(){}
}

class B: A
{
mixin Bug; // need mixin on B now to override `bug` for the 
new class

void bar(){}
void bar(uint a){}
}

void main(){
new A;
new B;
}


Re: scope keyword

2015-11-20 Thread Alex Parrill via Digitalmars-d-learn
On Thursday, 19 November 2015 at 23:16:04 UTC, Spacen Jasset 
wrote:
I thought scope was deprecated, but I see that this is still 
here: http://dlang.org/attribute.html#scope


Is it just the uses on classes and local variables that are 
discouraged, but the use in a function signature will continue? 
in == const scope?


The usage of scope as a variable storage modifier to allocate 
classes on the stack is deprecated, and replaced with 
std.typecons.scoped.


The usage of scope as a parameter attribute is not deprecated, 
and is used to indicate that references to the parameter will not 
escape through this function call (ex. the function won't store 
the parameter in a global variable), though the only thing it 
affects at the moment is delegates.


Re: AliasSeq + isExpression type specialization behavior

2015-11-10 Thread Alex Parrill via Digitalmars-d-learn

On Monday, 9 November 2015 at 22:41:50 UTC, Brian Schott wrote:

Given the following code:
```
import std.meta;

static assert(is(char : dchar));
static assert(is(AliasSeq!(int, char) : AliasSeq!(int, char)));
static assert(is(AliasSeq!(int, char) : AliasSeq!(int, dchar)));
```

The third static assert fails. Should it, given that the first 
and second pass?


`:` in `is` is for testing whether the left type is implicitly 
convertible to the right type. `char` is implicitly convertible 
to `dchar` by promoting it. But `AliasSeq`s are collections; 
they're only implicitly convertible to themselves.


Re: @property

2015-11-09 Thread Alex Parrill via Digitalmars-d-learn

On Monday, 9 November 2015 at 21:56:22 UTC, Fyodor Ustinov wrote:

Hi!

Why do need "@proprety" if everything works without it?

WBR,
Fyodor.


Check out the following code:


struct Test {
int foo() {
return 2;
}
int bar() @property {
return 2;
}
}

	pragma(msg, typeof(Test.foo)); // Prints int(); i.e. a 
zero-argument function that returns an int

pragma(msg, typeof(Test.bar)); // Prints int; i.e. a plain int

AFAIK when @property was introduced, it was expected that after a 
deprecation period, calling non-property functions without 
parenthesis would be invalid, but I don't think that panned out. 
It's still good for documentation.


Re: phobos: What type to use instead of File when doing I/O on streams?

2015-11-09 Thread Alex Parrill via Digitalmars-d-learn

On Monday, 9 November 2015 at 19:42:53 UTC, J.Frank wrote:

On Monday, 9 November 2015 at 18:44:00 UTC, Alex Parrill wrote:
Ranges are streams. file.byLine(Copy) and byChunk are 
effectively streams that are ranges.


I might be wrong, but from what I read so far I don't think 
that "ranges are streams":


- Can you read an arbitrary length of bytes from a range? 
(Reading by line in my code was just an example.) The only way 
I see is to make it a byte range. But then reading n bytes 
would result in n calls to popFront(), which is out of the 
question for performance reasons. Is this correct?


`myrange.take(array_size).array`

front/popFront are very good candidates for optimization; the 
compiler should be able to inline them, removing all of the 
overhead (GCD and LDC will likely be better at this than DMD, 
though).



- Can you flush() a range?

- Can you use select() on a range?



No, but you can't do either to anything other than file 
descriptors anyway (at least on Linux, dunno about Windows), so 
you may as well pass in a File.


Re: phobos: What type to use instead of File when doing I/O on streams?

2015-11-09 Thread Alex Parrill via Digitalmars-d-learn

On Monday, 9 November 2015 at 18:18:19 UTC, J.Frank wrote:

On Monday, 9 November 2015 at 14:48:35 UTC, Ali Çehreli wrote:

import std.stdio;
import std.range;

void foo(I, O)(I in_stream, O out_stream)
if (isInputRange!I &&
isOutputRange!(O, ElementType!I)) {

// in_stream.seek(3); // compile error - good :)

foreach (element; in_stream) {
out_stream.put(element);
}
}

void main(string[] args)
{
// Also consider .byLine, which is faster and risky
foo(stdin.byLineCopy,
stdout.lockingTextWriter);
}

Ali


Uhm... no. That's not a solution to my problem. Ranges are not 
(I/O-)streams.


Ranges are streams. file.byLine(Copy) and byChunk are effectively 
streams that are ranges.


The only problem with implementing your code in ranges is that 
`splitter` requires a forward range, which file-backed ranges 
aren't. Otherwise you could do 
`file.byChunk(4096).joiner.drop(3).splitter('\n')` to get a 
"stream" of lines.


Re: Split range that has no length or slice?

2015-11-09 Thread Alex Parrill via Digitalmars-d-learn

On Monday, 9 November 2015 at 15:23:21 UTC, Spacen Jasset wrote:

On Monday, 9 November 2015 at 14:58:19 UTC, Adam D. Ruppe wrote:
File has a .byLine and .byLineCopy method you could use to 
just get lines from it.


Ah yes. but unfortunately I don't want to do that. I want to 
pass a range into my print function. i.e. Sometimes it may not 
be a File, it might be from a string.


Looks like it's not possible without adaptor code. I would 
suggest File should have a range function on it to return a 
range, for that matter byLine and byChunk probably shouldn't 
even be associated with file at all IMHO.


The `.byLine` and `.byLineCopy` functions return ranges. Use 
those.


Re: Split range that has no length or slice?

2015-11-09 Thread Alex Parrill via Digitalmars-d-learn

On Monday, 9 November 2015 at 17:56:14 UTC, Alex Parrill wrote:

On Monday, 9 November 2015 at 15:23:21 UTC, Spacen Jasset wrote:
On Monday, 9 November 2015 at 14:58:19 UTC, Adam D. Ruppe 
wrote:
File has a .byLine and .byLineCopy method you could use to 
just get lines from it.


Ah yes. but unfortunately I don't want to do that. I want to 
pass a range into my print function. i.e. Sometimes it may not 
be a File, it might be from a string.


Looks like it's not possible without adaptor code. I would 
suggest File should have a range function on it to return a 
range, for that matter byLine and byChunk probably shouldn't 
even be associated with file at all IMHO.


The `.byLine` and `.byLineCopy` functions return ranges. Use 
those.


Scratch that, just read your post.

Ideally, something like 
`file.byChunk(4096).joiner.splitter('\n')` would work. The issue 
is that the byChunk ranges aren't forward or sliceable ranges 
(which makes sense).


Theoretically, it should be possible to implement `splitter` with 
a plain input range, but it would require that the sub-range that 
`splitter.front` returns be invalidated when calling 
`splitter.popFront`.


Re: phobos: What type to use instead of File when doing I/O on streams?

2015-11-08 Thread Alex Parrill via Digitalmars-d-learn

On Sunday, 8 November 2015 at 20:47:08 UTC, J.Frank wrote:

Hello again,

I'm a bit puzzled by the "File" type. Looking at the 
implementation, it seems that all I/O functions were stuffed 
into a single class^H^H^H^H^Hstruct.
What I expected to find is some kind of "Stream" class (with 
read(), write(), eof()), which is extended by a "File" class 
(with seek(), mmap(), etc.).


So, assuming my program reads from stdin and is supposed to 
work on a file as well as on a pipe (which is not seekable) - 
how can I make the compiler bark when I accidently use 
stdin.seek()?


Am I missing something here, too?


Use ubyte/char input ranges. Post what you're trying to do if you 
want an example.


Re: parallel

2015-11-05 Thread Alex Parrill via Digitalmars-d-learn

On Thursday, 5 November 2015 at 20:30:05 UTC, Handyman wrote:
Seems that 4 cores go all out on first 4 dishes, then 1 core 
deals with the last dish.  With 4 cores I expect diner is ready 
after 5/4 = 1.25 secs though.  What did I do wrong?


The first four dishes get scheduled, all of them sleep for 1 
second in parallel, then complete at roughly the same time. One 
second has passed.


Now there's one dish left. It gets scheduled, sleeps for 1 
second, and finishes (the other threads remain idle). Two seconds 
have passed.


Re: Default method implementations in interfaces?

2015-10-23 Thread Alex Parrill via Digitalmars-d-learn

On Friday, 23 October 2015 at 14:58:43 UTC, pineapple wrote:
Is it possible to have default method implementations in 
interfaces à la Java in D? Or some equivalent that allows 
multiple inheritance without a bunch of identical copypasted 
method bodies?


Use template mixins: http://dlang.org/template-mixin.html

interface MyInterface {
void foo();
int bar();
}

mixin template MyInterfaceDefaultImpl() {
void foo() {
// put code here
}
int bar() {
// put code here
}
}

class MyClass : MyInterface {
mixin MyInterfaceDefaultImpl!(); // Similar to inserting the 
body of `MyInterfaceDefaultImpl` at this point.
mixin MyOtherInterfaceDefaultImpl!(); // Can put any amount 
of them here.

}


Re: dynamic get from variantArray() data table

2015-10-13 Thread Alex Parrill via Digitalmars-d-learn
On Tuesday, 13 October 2015 at 15:17:15 UTC, data pulverizer 
wrote:

Hi,

I am trying to use variantArray() as a data table object to 
hold columns each of which is an array of a specific type. I 
need to be able to get values from data table but I am having 
problems ...



import std.stdio; // i/o
import std.variant; // type variations

void main(){
  // Columns of the table
  string[] names = ["walter", "paul", "jeff", "andrie"];
  int[] age = [55, 62, 27, 52];
  string[] language = ["D", "Haskell", "Julia", "D"];
  Variant[] dt = variantArray(names, age, language);

  foreach(col; dt){
foreach(el; col){
  // here I try a kind of dynamic cast operator
  auto x = el.get!(type(el)); // gives error
  write(x);
}
write("\n");
  }
}

data_table.d(37): Error: cannot infer type for el
data_table.d(38): Error: undefined identifier 'el'

Help

DP


You're trying to iterate over a `Variant`, which isn't 
implemented.


You don't want to use a variant here anyway; you should use a 
struct or tuple for each entry in the table.




import std.typecons;

alias Entry = Tuple!(string, int, string);

void main() {
auto table = [Entry("walter", 55, "D"), Entry("paul", 62, 
"Haskell"), ... ]; // complete array

foreach(entry; table) {
writeln(entry.expand);
}
}



Re: dynamic get from variantArray() data table

2015-10-13 Thread Alex Parrill via Digitalmars-d-learn
On Tuesday, 13 October 2015 at 16:22:36 UTC, data pulverizer 
wrote:
Thanks for the suggestion Alex, however I need the dynamic 
behaviour properties of variantArray(), writing a struct each 
time would be undesirable.


Perhaps I could boil down the question to something like, is 
there a way of writing


auto x = dt[0][0];
auto y = x.get!(x.type - or whatever); // to get the actual 
value of x rather than .VariantN! ... type


For some kind of auto cast back to basic type.


The problem is that you can't do `x.get!(x.type)`, because the 
type of the expression must be known at compile time, but 
`x.type` is a runtime value. You'd have to create a branch for 
each type that `x.type` might be.


But again, unless you are dealing with a truly dynamic layout 
(and not a bunch of fixed layouts), there's better options. For 
example, you can use `std.range.zip` to iterate through each 
column array in lockstep, returning tuples for each element.



foreach(entry; zip(names, ages, languages)) {
write(entry.expand);
}




Re: What difference between std.typecons.Tuple and std.meta.AliasSeq

2015-09-20 Thread Alex Parrill via Digitalmars-d-learn

On Sunday, 20 September 2015 at 18:10:49 UTC, Suliman wrote:
Sometimes it's hard to understand the D philosophy, for example 
now I can't understand diffrence between std.typecons.Tuple and 
std.meta.AliasSeq. I know that in language like Python there is 
spatial data type named tuple like:

tup1 = ('physics', 'chemistry', 1997, 2000);

But what in D? That was Tuples module, but it's look like it 
was renamed to 
http://forum.dlang.org/thread/mnhfhs$2b9o$1...@digitalmars.com


But look like std.typecons.Tuple and std.meta.AliasSeq are 
exists. So I really can't understand what and how I should to 
use that's all.


std.typecons.Tuple is more like Python's tuples. It effectively 
defines a struct with one field per type in the tuple definition, 
and only holds values.


std.meta.AliasSeq (aka std.typetuple.TypeTuple) is a compile-time 
construct, used mostly with templates, and is more like a list. 
They can hold types, values, or symbol aliases, but only exist 
during compilation (though you can declare a variable using an 
AliasSeq containing only types; I think this acts like defining 
one variable for each type in the seq).


Re: [Code Example for Beginners (like me)] Sockets with Fibers

2015-09-18 Thread Alex Parrill via Digitalmars-d-learn

On Friday, 18 September 2015 at 07:58:10 UTC, ddos wrote:

hello!

yesterday i got curious about how fibers work, and if the can 
be used as a replacement in network programming. so i started 
hacking a small example together, which is hopefully useful to 
other D beginners too :)


http://pastebin.com/Xg4GJbKE


Two things:

In the line `string s = (cast(immutable(char)*)buf)[0..len];`, 
the cast to immutable is unsafe, as `buf` is modified on the next 
iteration and so the slice into it is not actually immutable. 
`writeln` can take a regular `char[]` fine, so you can just drop 
the immutable; otherwise you can do 
`cast(string)((buf[0..len]).idup)`.


Also, using select/poll/epoll would be better than looping and 
sleeping. std.socket includes a SocketSet class for doing this 
(though the API for it is kinda bad).


Re: char[] ported from C to char[0] in the D core library

2015-09-09 Thread Alex Parrill via Digitalmars-d-learn

On Wednesday, 9 September 2015 at 16:49:39 UTC, badlink wrote:
The struct core.sys.linux.sys.inotify.inotify_event contains 
the field "char[0] name" which corresponds to "char name[]" in 
C.


Why it has been translated to "char[0]" ?
For me "char*" would have been more appropriate.


It's a flexible array member [1], not a pointer. Changing it to 
`char*` would make it incompatible with the C functions using it.


[1]: https://en.wikipedia.org/wiki/Flexible_array_member


Re: Abstractioning away main/winMain

2015-09-04 Thread Alex Parrill via Digitalmars-d-learn

On Saturday, 5 September 2015 at 02:29:05 UTC, Prudence wrote:

If I use functions instead of delegates it works.

I suppose the problem then is that the delegate can't create a 
fat pointer when used in a static context. (i.e., why the 
functions work)


The question is, then, Can I construct a delegate manually and 
supply my own context pointer?


e.g.,
class X { }

void foo() { }

constructDelegate(, new X()) // Creates a void delegate() 
with context X


How would the X instance get passed in?

You could try this:

class X {}
void foo(X x) {}

auto x = new X();
auto dg = () => foo(x);



Re: MmFile : Is this std.mmFile BUG?

2015-08-26 Thread Alex Parrill via Digitalmars-d-learn
On Wednesday, 26 August 2015 at 15:49:23 UTC, Junichi Nakata 
wrote:

Hi, all.
I have a question.
When 'testdic' file does' t exist, something  wrong.

---
import std.mmFile;

int main() {
  auto x = new MmFile(testdic,MmFile.Mode.readWrite,0,null);
  return 0;
}

---
OSX 10.10.3 ,
DMD64 D Compiler v2.069-devel-d0327d9

After testdic file (size=0) was made, Segmentation Fault: 11 .

I don't know whether this code is typical use.
Is this Phobos BUG? or BY DESIGN?


Note that mmap-ing a zero-length range is invalid on Linux. Dunno 
about OSX; it shouldn't segfault though.


Re: Adding UDA at compile time

2015-08-26 Thread Alex Parrill via Digitalmars-d-learn
On Wednesday, 26 August 2015 at 14:29:30 UTC, Andrea Fontana 
wrote:


__traits(setAttributes, ...)

It would be useful, for example, if I have a list of functions 
to mark. Let's say


enum toExport = [oldFunction, thisToo];
foreach(d; toExport) __traits(setAttributes, ...);


Lots of compile-time information is fixed after the symbol is 
defined, making it effectively immutable. There's not, for 
example, a `__traits(setType, var)`.


If you want to apply a UDA to many functions at once, you can use 
the block syntax:


@(hello) {
void foo1() {}
void foo2() {}
}

// or alternatively

@(hello):

void foo3() {}
void foo4() {}

Also if you're talking about the `export` keyword, then that's 
not a UDA.




Re: Adding UDA at compile time

2015-08-26 Thread Alex Parrill via Digitalmars-d-learn
On Wednesday, 26 August 2015 at 08:19:04 UTC, Andrea Fontana 
wrote:
I wonder if there's a way to add UDA to functions at 
compile-time (so I can read later from other parts of 
application).


Andrea


What do you mean? UDAs are already specified at compile time.


@(hello)
void foo() {

}

static assert(__traits(getAttributes, foo)[0] == hello);



Re: Promises/A+ spec implementations?

2015-08-19 Thread Alex Parrill via Digitalmars-d-learn
On Wednesday, 19 August 2015 at 04:18:03 UTC, Alexander J. 
Vincent wrote:
Hi, folks.  Over ten years ago I had some interest in the D 
language.  I'm starting to think about it again...


I've been using Mozilla's Promises implementations for quite a 
while, now, and they're surprisingly nice to work with.  They 
are the next generation beyond the callback function patterns I 
learned in JavaScript.  I've been thinking that writing a 
Promises/A+ library for D would be a good task for a relatively 
inexperienced D programmer.  I didn't see any Promises/A+ 
implementations in the standard library or on code.dlang.org.


Now, whether I write that library or someone else beats me to 
it, I don't really care right now.  I'm interested in doing it, 
but my time is extremely limited.  I'm mainly posting this as a 
request to get a Promises/A+ library started, and for me to 
observe the process of crafting a library.  If someone wants to 
be a mentor for me on this, answering direct questions, that'd 
be great.


The spec for Promises/A+ is at https://promisesaplus.com/ . 
Mozilla's Bobby Holley recently wrote a good blog post about a 
MozPromise implementation which includes supporting 
multithreading (a concept I don't fully understand how to write 
for, yet) and cancelling a Promise (which isn't in the spec, 
but makes sense for Mozilla's purposes).  That blog post is at 
http://bholley.net/blog/2015/mozpromise.html .


Finally, I had an old login to this forum (kb7iuj), which I've 
long forgotten the password for.  I did see that there's no 
password recovery support, so could someone just terminate that 
login for good?


IMO the 'next' generation of async is fibers/coroutines, not 
promises. Vibe.d is a great example; the code looks exactly like 
a normal synchronous function (including try/catch!), but is 
asynchronous behind the scenes.


See also vibe.d's feature page [1] and examples [2]

There's also C#'s async/await, but that's a syntax feature and I 
don't know how they work.


[1]: http://vibed.org/features#fibers
[2]: http://vibed.org/docs



Re: D Classes Passed By Reference or Value?

2015-08-16 Thread Alex Parrill via Digitalmars-d-learn

On Sunday, 16 August 2015 at 22:31:02 UTC, Brandon Ragland wrote:
Hi All, I'm a bit confused as to how Classes in D are passed in 
arguments and returns.


Take this for example:

class MyClass{
int x = 2;
}

And then in app.d

ref MyClass doStuff(){
MyClass mc = new MyClass() // Heap allocation, using new
return mc;
}

The above fails, as escaping reference to local variable 
however, this was created using new Not understanding what 
the deal is, this should be a valid heap allocated object, and 
therefore, why can I not pass this by reference? I don't want 
this to be a local variable...


So this begs the question: Are Classes (Objects) passed by 
reference already?


-Brandon


Classes are reference types, a la Java/C#.

class MyClass {
int x = 5;
}

void main() {
auto c1 = new MyClass();
auto c2 = c1;
c1.x = 123;
assert(c2.x == 123);
}



Re: D Classes Passed By Reference or Value?

2015-08-16 Thread Alex Parrill via Digitalmars-d-learn

On Sunday, 16 August 2015 at 22:31:02 UTC, Brandon Ragland wrote:

ref MyClass doStuff(){
MyClass mc = new MyClass() // Heap allocation, using new
return mc;
}



This attempts to return a reference to the _variable_ `mc`, not a 
reference to the class. Just remove `ref` from the function 
signature.


Re: Dynamic array and foreach loop

2015-08-09 Thread Alex Parrill via Digitalmars-d-learn

On Sunday, 9 August 2015 at 15:37:23 UTC, Binarydepth wrote:


So I should use the REF like this ?

import std.stdio : writeln;
void main() {
immutable a=5;
int[a] Arr;
foreach(num; 0..a)  {
Arr[num] = num;
}
foreach(num, ref ele; Arr)  {
writeln(Arr[ele]+1);//Using the REF
}
}


No. `ele` is the array element; reindexing the array with it is 
incorrect. `ref` just means that you can assign back to the array 
(like `ele = 123; assert(Arr[num] == 123);`); it's unnecessary 
here though.




Re: Removing elements from dynamic array

2015-08-09 Thread Alex Parrill via Digitalmars-d-learn

On Sunday, 9 August 2015 at 15:30:32 UTC, Reflexive wrote:
I wrote import std.algorithm.remove ;, and I dont have any 
longer any error. But, it dont want to remove the item. Here is 
the source, the problem is in the shuffle() method :


...


Why not just use std.random.shuffle [1]?

import std.random;

void shuffle() {
randomShuffle(this.sabotarray);
}

(Also, this is more of a style opinion, but please don't define 
all your variables up front; define them when they're first used. 
The other way IMO has too much cognitive load, and you can't use 
`auto` in many cases)


[1]: http://dlang.org/phobos/std_random.html#.randomShuffle


Re: Thread communication

2015-08-05 Thread Alex Parrill via Digitalmars-d-learn

On Wednesday, 5 August 2015 at 14:31:20 UTC, Marc Schütz wrote:
Maybe we can lift this restriction if we know that the thread's 
main function is pure and takes no references to mutable data, 
because then it can by definition never mess up the program's 
state.


That'd be a pretty useless thread; how would it communicate 
results back to the main thread (or wherever it should go)?




Re: GLU in DerelictOrg

2015-07-24 Thread Alex Parrill via Digitalmars-d-learn

On Friday, 24 July 2015 at 12:56:29 UTC, Spacen Jasset wrote:
Thanks Mike, that's fair enough. I shall just implement the 
functions I need I think until such time as I end up using the 
newer OpenGL 3 stuff.


If you want, you can steal from Mesa's GLU implementation here: 
http://cgit.freedesktop.org/mesa/glu/


Re: Thread pools

2015-07-22 Thread Alex Parrill via Digitalmars-d-learn

On Wednesday, 22 July 2015 at 14:28:48 UTC, Chris wrote:
What would be the best way to manage different threads (spawned 
via std.concurrency), e.g. to tell them to stop at once, once a 
new command comes in? A thread pool? How would that look like 
in D? I feel my knowledge of D threads is still a bit limited.


`std.parallelism` includes a TaskPool class [1] and a taskPool 
property [2], but they spawn their own threads.


I'm not sure why you need a thread pool to tell std.concurrency 
threads to stop; why not send a stop message to each of them?


[1]: http://dlang.org/phobos/std_parallelism.html#.TaskPool
[2]: http://dlang.org/phobos/std_parallelism.html#.taskPool


Re: GLU in DerelictOrg

2015-07-21 Thread Alex Parrill via Digitalmars-d-learn

On Tuesday, 21 July 2015 at 14:51:47 UTC, John Colvin wrote:
Isn't glu considered legacy these days? I think it's entirely 
OpenGL 2.x. For the maths stuff see 
http://code.dlang.org/packages/gl3n


Yep. It still uses immediate mode, GL matrix functions, and all 
sorts of other stuff removed in OpenGL 3.1+ core.


Re: How do i sanitize a string for database query?

2015-07-21 Thread Alex Parrill via Digitalmars-d-learn

On Tuesday, 21 July 2015 at 18:55:53 UTC, ddos wrote:

On Tuesday, 21 July 2015 at 17:58:55 UTC, Gary Willoughby wrote:

On Tuesday, 21 July 2015 at 17:23:30 UTC, ddos wrote:

How do i sanitize a string for database query?
Is there some builtin function?

thx :)


Use prepared statements instead.

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


thx for reminding me of prepared statements
this is ok for preventing an sql injection i guess, but still 
my insert would fail.

maybe i should have specified what i want to achieve:

i have a plugin for a call of duty gameserver, this plugin is 
able to ban players from the server by inserting name/ip/etc.. 
into a sql database. it is priority that the insert never 
fails. e.g. name could contain a ' which lets my insert fail.


No it won't. The actual contents of your query parameters are 
irrelevant and are stored as-is; that's the entire point of using 
query parameters.


Example using d2sqlite3:

auto db = Database(:memory:);
auto stmt = db.prepare(INSERT INTO banned VALUES (?);)
stmt.bindAll(O'chucks);
stmt.execute(); // works fine



Re: Fixed Length Array Syntax in extern(C) Function Signatures

2015-07-09 Thread Alex Parrill via Digitalmars-d-learn

On Thursday, 9 July 2015 at 17:11:36 UTC, Per Nordlöw wrote:

On Thursday, 9 July 2015 at 16:12:27 UTC, Timon Gehr wrote:

No. You'll need explicit pass by reference on the D side.


So, how should I modify my call to `image_copy` with respect to 
the four first parameters?


In C, array parameters are the same as pointers; i.e. `foo(T[] 
arg)` is the same as `foo(T* arg)` [1].


You should just be able to replace `[4]` with `*` in the 
arguments.


[1]: http://stackoverflow.com/a/5573741/646619


Re: Correctly implementing a bidirectional range on a linked list?

2015-07-06 Thread Alex Parrill via Digitalmars-d-learn

On Monday, 6 July 2015 at 20:50:19 UTC, Gary Willoughby wrote:
The problem is when I call the save method of the forward range 
interface I don't get a copy I only get another view to the 
same state. So when i remove nodes from the original list the 
range becomes invalid.




This is why modifying a sequence while iterating over it is 
generally forbidden; there's no good way to make it work. You 
could duplicate the entire list for each range, but that's 
expensive for the usual case of simply reading the list.


Forward ranges don't require that ranges be independent of the 
data they iterate over [1]:



Saving a range is not duplicating it; in the example above, r1
and r2 still refer to the same underlying data. They just
navigate that data independently.


IMO your implementation is fine.

[1]: 
http://dlang.org/phobos/std_range_primitives.html#isForwardRange


Re: Coercing ranges to the same type

2015-07-06 Thread Alex Parrill via Digitalmars-d-learn

On Monday, 6 July 2015 at 19:46:51 UTC, Matt Kline wrote:
Say I'm trying to expand an array of file and directory paths 
(such as ones given as command line args) into a range of file 
paths I can iterate over. A simplified example might be:


auto getEntries(string[] paths, bool recursive)
{
auto files = paths.filter!(p = p.isFile);

if (recursive) {
auto expandedDirs = paths
.filter!(p = p.isDir)
.map!(p = dirEntries(p, SpanMode.depth, false))
.joiner
.map!(de = de.name); // back to strings

return chain(files, expandedDirs);
}
else {
return files;
}
}

Even though both return statements return a range of strings, 
this doesn't compile because the result of `chain` is a 
different type than the result of `filter`. Is there some 
generic range I could coerce both ranges to in order to have 
the same return type and make this work? .array is a 
non-starter since it throws out the ranges' laziness.


They aren't actually the same types; one is a 
`FilterRange!(string[])`; the other a `ChainRange!(string[], 
MapRange!(...))`. Since they're structs, there's no runtime 
polymorphism.


You can either make `recursive` a template argument (`auto 
getEntries(bool recursive)(string[] paths)`) with `static if` if 
you know at compile time when to recurse or not, or use a class 
wrapper in std.range.interface [1].


[1]: http://dlang.org/phobos/std_range_interfaces.html


Re: Array operations, dynamic arrays and length

2015-07-01 Thread Alex Parrill via Digitalmars-d-learn

On Tuesday, 30 June 2015 at 22:37:34 UTC, ixid wrote:

int[] a = [1,1,1,1];
int[] b = [1,1,1,1];
int[] c;

c[] = a[] - b[];

c.writeln;

This outputs []. This feels wrong, it feels like something that 
should have exploded or set the length to 4. If the lengths of 
a and b are mismatched it throws an exception. It also throws 
an exception if a dynamic array is longer or a static array is 
not the same length but is happy when a dynamic array is 
shorter. Is this intended behaviour and if so why?


I don't think this is a bug.

Since you don't initialize `c` to anything, it defaults to an 
empty slice. Array [] operations apply to each element of a 
slice, but `c` doesn't have any elements, so it does nothing.


Change `int[] c;` to `int[] c = new int[4];` and it works.


  1   2   >