Re: Passing array as an function argument.

2017-09-11 Thread wobbles via Digitalmars-d-learn

On Monday, 11 September 2017 at 12:20:08 UTC, Vino.B wrote:

On Monday, 11 September 2017 at 12:03:32 UTC, wobbles wrote:

On Monday, 11 September 2017 at 11:58:18 UTC, Vino.B wrote:

[...]




The type returned from Test1() is a `RangeT!(Array!string)`.

This is due to the `[]` on the end of `Fs[]`.

Remove the `[]` to just return a `Array!string`.


Hi,

 If i remove the `[]` at the end of `Fs[]` I am getting the 
same error, if i remove the `[]` from the file "auto t1 = 
Test1[];" the out is empty.


From,
Vino.B


This works:
https://dpaste.dzfl.pl/1fd9021739ad


Re: Passing array as an function argument.

2017-09-11 Thread wobbles via Digitalmars-d-learn

On Monday, 11 September 2017 at 11:58:18 UTC, Vino.B wrote:

Hi All,

  Can some one help me on how to pass a container array as a 
function argument , the below code throws an error,


Error: Error: function T3.Test2 (Array!string t1) is not 
callable using argument types (RangeT!(Array!string))


import std.stdio: writeln;
import std.container;

auto Test2 (Array!string t1) {
return t1;
}

auto Test1 () {
auto Fs = Array!string("C:\\Temp\\TEST1\\BACKUP", 
"C:\\Temp\\TEST2\\EXPORT");

return Fs[];
}
void main () {
auto t1 = Test1[];
Test2(t1);
}

From,
Vino.B




The type returned from Test1() is a `RangeT!(Array!string)`.

This is due to the `[]` on the end of `Fs[]`.

Remove the `[]` to just return a `Array!string`.


Re: [vibe.d] showing images

2016-10-26 Thread wobbles via Digitalmars-d-learn
On Wednesday, 26 October 2016 at 12:42:09 UTC, Nicholas Wilson 
wrote:

[...]


When you get the 404, do you see the contents of 
'writeln(images);' in your terminal?


Re: Your connection is not private

2016-10-01 Thread wobbles via Digitalmars-d-learn
On Saturday, 1 October 2016 at 03:21:05 UTC, rikki cattermole 
wrote:

On 01/10/2016 11:51 AM, Joel wrote:
I get this when I click Learn at the top of the screen in 
dlang. This is

on Chrome Mac (Sierra 10.12).


Yup, you need to be on https. Chrome just started warning when 
using http in the last build.


Would it be a good idea to have dlang.org always redirect to 
https:// ?


Re: vibe.d PaaS

2016-09-14 Thread wobbles via Digitalmars-d-learn
On Wednesday, 14 September 2016 at 16:03:50 UTC, Guillaume Piolat 
wrote:

On Wednesday, 14 September 2016 at 10:56:57 UTC, llaine wrote:
No PaaS service, but you can pretty simply use Heroku to 
deploy any vibe.d application.


Check the tour.dlang.io 
http://tour.dlang.io/tour/en/vibed/deploy-on-heroku where 
everything is explained :)


Thanks!


I've had success connecting vibe-d and heroku hosted postgresql 
dbs too :)


Re: vibe.d PaaS

2016-09-14 Thread wobbles via Digitalmars-d-learn
On Wednesday, 14 September 2016 at 09:01:11 UTC, Guillaume Piolat 
wrote:

Is there vibe.d hosting sold anywhere?


Not that I know, but any VPS you rent would be capable of hosting 
it.


I guess you don't want to deal with all of the other services 
you'd need? (nginx / security / dbs etc etc ?)


Re: Mysql-native with LAMPP

2016-09-12 Thread wobbles via Digitalmars-d-learn

On Monday, 12 September 2016 at 05:31:46 UTC, Geert wrote:

Hi all!

I tried the client driver for MySQL/MariaDB "mysql-native".

https://github.com/mysql-d/mysql-native

Everything works well with an individually installed version of 
MySql. But I would like to know if there is a way to make D 
programms work with LAMPP/XAMPP. I'm getting this error message 
while executing the program:


host=localhost;port=3306;user=root;pwd=MY_testPa550;db=testdb
Failed: 
std.socket.SocketOSException@/build/ldc/src/ldc/runtime/phobos/std/socket.d(2822): Unable to connect socket: Connection refused


You're sure mysql is running?


Re: Compiling vibe.d application for Amazon ec2 instance

2016-09-12 Thread wobbles via Digitalmars-d-learn

On Sunday, 11 September 2016 at 23:12:15 UTC, crimaniak wrote:

Hi all!

I made vibe-d application, and client give me already taken 
hosting for it on Amazon aws ec2, uname -a:
Linux ip-xxx-xx-xx-xx 4.4.11-23.53.amzn1.x86_64 #1 SMP Wed Jun 
1 22:22:50 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux


Compiled on my Ubuntu binary don't run because of different 
versions of libraries (on Amazon they older).


I can try to install dmd to ec2 instance but don't think this 
is good idea. I want to compile binary on my developing machine 
(may be in specific OS in VirtualBox).

How to resolve this problem by right way?

Can I get VirtualBox image of ec2 version of Linux and use it 
on my machine?
Can I compile all libraries used as static and make more 
independent binary?

Something else?


I would find out the AMI of the image you're going to be running 
on, and spin up a machine from that.

Install all dev tools there, and compile.

Then you'll be good to go.

You could even export the ec2 VM and run it locally in VirtualBox 
or something. I've never done it, but it's apparently possible.


Re: Get all files imported by a D source file

2016-09-09 Thread wobbles via Digitalmars-d-learn

On Thursday, 8 September 2016 at 07:20:52 UTC, Yuxuan Shui wrote:
On Thursday, 8 September 2016 at 06:33:00 UTC, Jacob Carlborg 
wrote:

On 2016-09-08 07:39, Yuxuan Shui wrote:

Hi,

I wonder if there's standardized way to gather which files 
are imported
by a source file. I know I can run "dmd -v" and look for 
lines start
with "import", but I don't know if this is the best way to do 
it.


You can use the "-deps" flag.


-deps is even noisier than just -v...


It's pretty noisy alright, but it's also pretty easy to read...

It also shows just how coupled phobos is.
I'm importing one single function (std.stdio.writefln), and all 
the dependencies are imported:

http://pastebin.com/DSC4JhBD




Re: Template not seeming to instantiate a second time with default alias parameter

2016-08-31 Thread wobbles via Digitalmars-d-learn

On Tuesday, 30 August 2016 at 21:35:29 UTC, ag0aep6g wrote:

On 08/30/2016 11:28 PM, wobbles wrote:

I'll have to try find a workaround for now :/


This seems to work and isn't too ugly:


class Node(T, alias func) {/*...*/}
alias Node(T) = Node!(T, (T t) => t*t);



Excellent - thanks for these.
This one will work for me :)

I was going to do something messy with a nested template and some 
static ifs. But, complicated things are complicated. This is much 
easier.

Thanks!


Re: Template not seeming to instantiate a second time with default alias parameter

2016-08-30 Thread wobbles via Digitalmars-d-learn

On Tuesday, 30 August 2016 at 20:55:20 UTC, ag0aep6g wrote:

On 08/30/2016 10:41 PM, wobbles wrote:

class Node(T, alias func = (T t => t*t))(){
//whatever
}

//instantiate
Node!(int) intNode;
Node!(float) floatNode;   // fails as lambda func expects an 
int.


Am I doing something wrong or is this a bug?


Proper test case:


class Node(T, alias func = (T t) => t*t)
{
void method() { func(T.init); }
}

//instantiate
Node!(int) intNode;
Node!(float) floatNode;   // fails as lambda func expects an 
int.



Looks like a bug to me. Similar to this:
https://issues.dlang.org/show_bug.cgi?id=14501


Yeah. Looks related.

I'll have to try find a workaround for now :/


Template not seeming to instantiate a second time with default alias parameter

2016-08-30 Thread wobbles via Digitalmars-d-learn

Hi,

Code here:
https://gist.github.com/grogancolin/066a8a8c105fa473dfee961e2481a30e

Basically, it seems when a template has an alias parameter like

class Node(T, alias func = (T t => t*t))(){
//whatever
}

//instantiate
Node!(int) intNode;
Node!(float) floatNode;   // fails as lambda func expects an int.

Am I doing something wrong or is this a bug?


Re: OpenGL Setup?

2016-06-16 Thread wobbles via Digitalmars-d-learn

On Thursday, 16 June 2016 at 19:52:58 UTC, OpenJelly wrote:
Last time I worked on anything OpenGL in D I was using a Linux 
machine, and I had to really bend over backward to get set up. 
I'm using Windows 7 at the moment and I'd like to work on some 
graphics stuff but I'm pretty lost...


I just want to install an IDE that's not prone to crashing and 
comes with standard features like D syntax highlighting, code 
completion, code folding, side bar with my project's directory, 
integrated console, bindable key commands (build (with dub), 
run, stop), and some debugging help doesn't hurt but I can get 
by without being able to set break points... and then I need to 
get the right libs and bindings in order nut half of them I 
can't figure out the instructions for.


What I've been trying to do for the past few hours is set up 
SublimeText3 with dub and get the derelictGLFW3 binding to 
work, but I can't even get dkit working, and I'd honestly 
rather be using code::blocks but I've had trouble getting D 
code completion working in that before, and while I could 
probably get SFML bindings to work (as their documentation 
caters to idiots like me), I don't really want to use it, I 
just want something small that handles an OpenGL window without 
the other stuff.


If anyone's got a solid setup and can explain to me like I'm 5 
how they got it all nice, that'd really help me out a lot. 
Thanks.


I notice the ST3 plugin was a bit... flaky the last time I tried 
it (admittedly about 6 months ago).


I ended up settling on vim with a few plugins (and live without 
auto-complete, it's not that important for me), but when I was 
using GUI text editors, I settled on VS Code with the code-d 
plugin. Its autocomplete etc worked pretty much out of the box 
for me.


https://code.visualstudio.com/
https://marketplace.visualstudio.com/items?itemName=webfreak.code-d

Make sure you follow the 'dependencies' section of code-d through 
though to get your env set up. It worked outta the box for me, on 
both windows and linux.


You can get VS Code to compile via ctrl+B (I think that was the 
shortcut) but you've to make a modification to a json file to 
tell it to do it.


If you need more help let me know and I'll write up something 
proper for you.


Cheers!


Re: Recommended coding convention for combining unix and windows code ?

2016-06-07 Thread wobbles via Digitalmars-d-learn

On Tuesday, 7 June 2016 at 15:33:57 UTC, chmike wrote:

Hello

I'm writing some code that I want to be portable across Posix 
and Windows.


What is the recommended code convention for such type of code ?

80% of the class implementation is the same for both OS.

Should I write the following and copy past the 80%

version( Windows ) {
import core.sys.windows;
class MyInfo {...}
} else version( Posix ) {
import core.sys.posix;
class MyInfo {...}
} else {
static assert(false, "Unsupported platform");
}

or should I do it the C way with multiple embedded static if... 
?


version( Windows ) {
import core.sys.windows;
} else {  //Posix
import core.sys.posix;
}

class MyInfo {
...
static if(windows) {
enum Value {...}
} static else {  //Posix
enum Value {...}
}
...
}


I did something similar, and went with the c-style version (x) 
inside each code block.


Have a look here for how it looks.
https://github.com/grogancolin/dexpect/blob/master/source/dexpect.d



Re: execute bash?

2016-04-10 Thread wobbles via Digitalmars-d-learn

On Sunday, 10 April 2016 at 00:47:28 UTC, Puming wrote:

On Saturday, 9 April 2016 at 08:56:17 UTC, wobbles wrote:

On Friday, 8 April 2016 at 23:06:06 UTC, Puming wrote:

On Friday, 8 April 2016 at 18:23:32 UTC, wobbles wrote:

On Friday, 8 April 2016 at 16:07:13 UTC, Adam D. Ruppe wrote:

On Friday, 8 April 2016 at 15:20:09 UTC, Puming wrote:
I tried with signal, but didn't catch SIGTTOU, it seems 
that spawnProcess with `bash -i -c` will signal with 
SIGTTIN.


Oh, surely because it wants to be interactive and is thus 
waiting for user input from the terminal..


You might need to rig up a pseudo terminal that the bash 
can talk to. That's getting to be a pain though.


You could run it through dexpect to get the effect of a 
pseudo terminal.


https://github.com/grogancolin/dexpect


Looked in the code, it is exacly what I need! Thanks.

Also it has spawnInPty


Cool. Any questions on using it let me know. I'm all for a bit 
of feedback also!


I tried dexpect, now it works for the bash emulation!


Good - glad it works!


But there are still some issues:


Bad - but to be expected :)

1. Spawn's data is a string, so it stores ALL data, but Expect 
class does not have a clear() method, so the data piles up and 
takes memory.


Yeah, this was something I came across too but didn't have the 
time to fix it.
My plan is to have the Expect class take an OutputRange, and all 
output is then sent to that Range. The only data that it keeps 
track of then is the data just before and since the latest 
'expect' call.


2. There seems to be a visible lag for each send->read cycle. I 
haven't look in the details to find where, but it feels not as 
smooth as ssh does.


I have added a good few Thread.sleep function calls in the send / 
read calls. This is because it seemed to crash out when there was 
nothing there and I needed something quick to get it working at 
the time. There must be a better way of handling this though.
Also, I suspect I've added way too many sleep calls so I should 
do a bit of work on this!


3. when hiting 'vim a.file' on the command, things go messy. 
Have you got these interactive commands work in dexpect?


Yeah, dexpect won't be handling something like vim. As Adam said, 
it sends lots of signals / commands to the terminal to tell it 
how to draw the window. Dexpect just cares about reading the data 
sent to/from the process, not what any of that data means.


My wish list for the Expect class ( or design a separate class, 
like BashProxy ):


1. Fully proxy for a bash shell.
2. Result data are separated for each command. So I can easily 
search for hitorical sent commands or results.


This would be cool. I'll have a think about how to go about it!


But for now it works fine for my needs.
I'll try to improve it when I get major parts of my repl lib 
done.


Also, pull requests are welcome :)



Re: execute bash?

2016-04-09 Thread wobbles via Digitalmars-d-learn

On Friday, 8 April 2016 at 23:06:06 UTC, Puming wrote:

On Friday, 8 April 2016 at 18:23:32 UTC, wobbles wrote:

On Friday, 8 April 2016 at 16:07:13 UTC, Adam D. Ruppe wrote:

On Friday, 8 April 2016 at 15:20:09 UTC, Puming wrote:
I tried with signal, but didn't catch SIGTTOU, it seems that 
spawnProcess with `bash -i -c` will signal with SIGTTIN.


Oh, surely because it wants to be interactive and is thus 
waiting for user input from the terminal..


You might need to rig up a pseudo terminal that the bash can 
talk to. That's getting to be a pain though.


You could run it through dexpect to get the effect of a pseudo 
terminal.


https://github.com/grogancolin/dexpect


Looked in the code, it is exacly what I need! Thanks.

Also it has spawnInPty


Cool. Any questions on using it let me know. I'm all for a bit of 
feedback also!


Re: execute bash?

2016-04-08 Thread wobbles via Digitalmars-d-learn

On Friday, 8 April 2016 at 16:07:13 UTC, Adam D. Ruppe wrote:

On Friday, 8 April 2016 at 15:20:09 UTC, Puming wrote:
I tried with signal, but didn't catch SIGTTOU, it seems that 
spawnProcess with `bash -i -c` will signal with SIGTTIN.


Oh, surely because it wants to be interactive and is thus 
waiting for user input from the terminal..


You might need to rig up a pseudo terminal that the bash can 
talk to. That's getting to be a pain though.


You could run it through dexpect to get the effect of a pseudo 
terminal.


https://github.com/grogancolin/dexpect




Re: Does something like std.algorithm.iteration:splitter with multiple seperators exist?

2016-03-28 Thread wobbles via Digitalmars-d-learn

On Sunday, 27 March 2016 at 07:45:00 UTC, ParticlePeter wrote:

On Wednesday, 23 March 2016 at 20:00:55 UTC, wobbles wrote:

[...]


Thanks Wobbles, I took your approach. There were some minor 
issues, here is a working version:


[...]


Great, thanks for fixing it up!


Re: Does something like std.algorithm.iteration:splitter with multiple seperators exist?

2016-03-23 Thread wobbles via Digitalmars-d-learn

On Wednesday, 23 March 2016 at 11:57:49 UTC, ParticlePeter wrote:
I need to parse an ascii with multiple tokens. The tokens can 
be seen as keys. After every token there is a bunch of lines 
belonging to that token, the values.

The order of tokens is unknown.

I would like to read the file in as a whole string, and split 
the string with:

splitter(fileString, [token1, token2, ... tokenN]);

And would like to get a range of strings each starting with 
tokenX and ending before the next token.


Does something like this exist?

I know how to parse the string line by line and create new 
strings and append the appropriate lines, but I don't know how 
to do this with a lazy result range and new allocations.


This isn't tested, but this is my first thought:

void main(){
string testString = "this:is:a-test;"
foreach(str; testString.multiSlice([":","-",";"]))
   writefln("Got: %s", str);
}

auto multiSlice(string string, string[] delims){
   struct MultiSliceRange{
string m_str;
string[] m_delims;
bool empty(){
   return m_str.length == 0;
}

void popFront(){
   auto idx = findNextIndex;
   m_str = m_str[idx..$];
   return;
}

string front(){
auto idx = findNextIndex;
return m_str[0..idx];
}
private long findNextIndex(){
long foundIndex=-1;
foreach(delim; m_delims){
if(m_str.canFind(delim)){
if(foundIndex == -1 || m_str.indexOf(delim) 
>= 0)){

 foundIndex = m_str.indexOf(delim);
}
}
}
return foundIndex;
}
   }

   return MultiSliceRange(string, delims);
}


Again, totally untested, but I think logically it should work. ( 
No D compiler on this machine so it mightn't even compile :] )


Re: Enabling Only Top-Level Unittests

2016-03-21 Thread wobbles via Digitalmars-d-learn

On Monday, 21 March 2016 at 10:37:31 UTC, ZombineDev wrote:

On Monday, 21 March 2016 at 10:29:36 UTC, Nordlöw wrote:
I want to enable unittests only at the top-level of a module 
compilation.


If I have a module

top.d

that imports

dep1.d
dep2.d
...

which all contain unittests, how do I compile top.d with only 
the unittests for top.d enabled?


I think the easiest solution is to use 
http://dlang.org/spec/traits.html#getUnitTests and to run the 
tests you want manually.


This is quite annoying I feel.

There probably should be an option for the -unittest flag to only 
compile unittests for the source files I'm passing in, and not 
any of the tests in the -I import paths.


Re: Speed of csvReader

2016-01-21 Thread wobbles via Digitalmars-d-learn
On Thursday, 21 January 2016 at 15:17:08 UTC, data pulverizer 
wrote:

On Thursday, 21 January 2016 at 14:56:13 UTC, Saurabh Das wrote:
On Thursday, 21 January 2016 at 14:32:52 UTC, Saurabh Das 
wrote:

[...]


Actually since you're aiming for speed, this might be better:

sw.start();
auto records = 
File("Acquisition_2009Q2.txt").byChunk(1024*1024).joiner.map!(a => cast(dchar)a).csvReader!row_type('|').array

sw.stop();

Please do verify that the end result is the same - I'm not 
100% confident of the cast.


Thanks,
Saurabh


@Saurabh I have tried your latest suggestion and the time 
reduces fractionally to:


Time (s): 6.345

the previous suggestion actually increased the time

@Edwin van Leeuwen The csvReader is what takes the most time, 
the readText takes 0.229 s


Interesting that reading a file is so slow.

Your timings from R, is that including reading the file also?


Re: core.time Duration how to get units in double/float format?

2016-01-19 Thread wobbles via Digitalmars-d-learn
On Tuesday, 19 January 2016 at 14:07:50 UTC, Borislav Kosharov 
wrote:
On Monday, 18 January 2016 at 12:46:31 UTC, Jonathan M Davis 
wrote:

[...]


I want to use float time in a game where I call the update 
method passing the delta time as float seconds. It's more easy 
to multiply the dt with a speed constant meaning how much the 
object will move after 1 second. Such float delta time is used 
in many game engines and it's somewhat standart way of doing 
it. Also the method you wrote returns a string and I need a 
float to multiply it with a number.

Thanks for the reply anyway


Checkout out how DSFML handles this.
You simply pass around a Clock object that you can restart every 
frame using


clock.restart();

You then call your update function with 
update(Clock.getElapsedTime());
Then in each objects update(Time t) method you just get the time 
in whatever unit you want. Works pretty well.


http://www.dsfml.com/


Re: Balanced match with std.regex

2015-12-15 Thread wobbles via Digitalmars-d-learn

On Tuesday, 15 December 2015 at 02:35:34 UTC, Xinok wrote:

On Tuesday, 15 December 2015 at 01:29:39 UTC, Jakob Ovrum wrote:

Thanks, that makes sense.

String manipulation in D without regex is pretty nice anyway, 
so it's not a big loss.


There is a library named Pegged which can match against 
balanced parens:


https://github.com/PhilippeSigaud/Pegged


Pegged is amazeballs.
Can build some v cool things with it. Particularly with some CTFE 
abuse!


Re: String interpolation

2015-11-10 Thread wobbles via Digitalmars-d-learn

On Tuesday, 10 November 2015 at 10:21:32 UTC, tired_eyes wrote:

Hi,
The only example of string interpolation I've found so far is 
on Rosetta Code:


void main() {
import std.stdio, std.string;

"Mary had a %s lamb.".format("little").writeln;
"Mary had a %2$s %1$s lamb.".format("little", 
"white").writeln;

}

Is this a "proper" way of string interpolation in D? This looks 
a little clumsy. Are there any better approaches? Quick 
skimming through the docs didn't give anything.


Whats clumsy about it?

If it's the style (excessive use of UFCS), I'd have to agree with 
you.

Could easily have been written as:
   format("Mary had a %s lamb", "little");

which I personally think is more readable...


Re: String interpolation

2015-11-10 Thread wobbles via Digitalmars-d-learn

On Tuesday, 10 November 2015 at 10:41:52 UTC, tired_eyes wrote:
On Tuesday, 10 November 2015 at 10:33:30 UTC, Tobias Pankrath 
wrote:

On Tuesday, 10 November 2015 at 10:21:32 UTC, tired_eyes wrote:

[...]


std.string.format and std.format are the standard options. 
What are you missing?


Ruby:
a = 1
b = 4
puts "The number #{a} is less than #{b}"

PHP:
$a = 1;
$b = 4;
echo "The number $a is less than $b";

D:
???


int a = 1;
int b = 4;
writefln("The number %s is less than %s", a, b);


Re: foreach loop

2015-11-03 Thread wobbles via Digitalmars-d-learn

On Tuesday, 3 November 2015 at 15:10:43 UTC, wobbles wrote:

On Tuesday, 3 November 2015 at 15:06:00 UTC, Namal wrote:
On Tuesday, 3 November 2015 at 14:52:19 UTC, Adam D. Ruppe 
wrote:

On Tuesday, 3 November 2015 at 14:47:14 UTC, Namal wrote:

[...]


for many of them it is as simple as:

foreach(index, element; array) { }


Thank you. I am still struggling with the functional ways of 
D. Now how could I write this foreach loop the functional way?


bool[] arr = [ture, false, ture, ...];

int count;
foreach(i;arr){

  if(!i)
count++;
}
writeln(count);


writefln("Count is: %s", arr
  .filter!(a => a==true)
  .sum);

// Note: std.algorithm.sum is the same as
// std.algorithm.reduce!((a,b)=a+b);


Oh, I realise now you were counting the number of 'false' values.
I counted the true values - so the filter line is wrong here.


Re: foreach loop

2015-11-03 Thread wobbles via Digitalmars-d-learn

On Tuesday, 3 November 2015 at 15:06:00 UTC, Namal wrote:
On Tuesday, 3 November 2015 at 14:52:19 UTC, Adam D. Ruppe 
wrote:

On Tuesday, 3 November 2015 at 14:47:14 UTC, Namal wrote:
I remember it is possible to get the index for each element 
in the foreach loop, but I forgot how to do it. Can you help 
me out please. Thx.


for many of them it is as simple as:

foreach(index, element; array) { }


Thank you. I am still struggling with the functional ways of D. 
Now how could I write this foreach loop the functional way?


bool[] arr = [ture, false, ture, ...];

int count;
foreach(i;arr){

  if(!i)
count++;
}
writeln(count);


writefln("Count is: %s", arr
  .filter!(a => a==true)
  .sum);

// Note: std.algorithm.sum is the same as
// std.algorithm.reduce!((a,b)=a+b);


Re: foreach loop

2015-11-03 Thread wobbles via Digitalmars-d-learn
On Tuesday, 3 November 2015 at 15:42:16 UTC, Edwin van Leeuwen 
wrote:

On Tuesday, 3 November 2015 at 15:29:31 UTC, Namal wrote:

writefln("Count is: %s", arr
  .filter!(a => a==true)
  .sum);

// Note: std.algorithm.sum is the same as
// std.algorithm.reduce!((a,b)=a+b);




Shouldn't you be using walkLength instead of sum, since you are 
counting the left over values?


import std.range : walkLength;
writefln("Count is: %s", arr
  .filter!(a => a==false)
  .walkLength);


That would work also yes.
Be interesting to know which is more efficient actually - I 
suspect they're very similar.


Re: foreach loop

2015-11-03 Thread wobbles via Digitalmars-d-learn

On Tuesday, 3 November 2015 at 14:47:14 UTC, Namal wrote:

Hello guys,

I remember it is possible to get the index for each element in 
the foreach loop, but I forgot how to do it. Can you help me 
out please. Thx.


auto arr = ["Hello", "World"];

foreach(int idx, string str; arr){
   writefln("%s = %s", idx, str);
}


Re: Mac IDE with Intellisense

2015-09-28 Thread wobbles via Digitalmars-d-learn
On Sunday, 27 September 2015 at 22:55:38 UTC, Johannes Loher 
wrote:
On Saturday, 26 September 2015 at 18:27:52 UTC, Mike McKee 
wrote:

On Saturday, 26 September 2015 at 10:31:13 UTC, wobbles wrote:

Have you installed dkit for sublime?


As in?

https://github.com/yazd/DKit

Looks like it's alpha and doesn't run on Mac? No homebrew 
install?


I'm using this and it works great. It uses dcd, so you need to 
install that first (via homebrew). As DKit it is a sublime text 
plugin, you don't install it via homebrew. Usually you'd 
install sublime packages via Package Control, but sadly DKit is 
not in the repositories yet. There is an issue about that 
already (https://github.com/yazd/DKit/issues/18). So instead, 
you install the package manually (just follow the instrcutions 
in the readme).


I don't know where you got the idea it doesn't work on OS X, it 
works like a charm for me.


Yeah, me too (on linux and windows). I used to try out quite a 
few of the D IDEs (Mono-d, DDT, Visual D etc) but this one plugin 
has replaced them all. For now at least...




Re: Mac IDE with Intellisense

2015-09-26 Thread wobbles via Digitalmars-d-learn

On Saturday, 26 September 2015 at 09:17:10 UTC, Mike McKee wrote:
I've tried Sublime Text 3 editor on the Mac, but even it 
doesn't seem to have the D2 language in it yet (only D), and 
doesn't have intellisense for components in the imports that I 
do, even after saving the file after adding the import 
statements.


What OSX editor do you recommend that would have intellisense?

In all reality, I don't like intellisense -- it's annoying. 
However, I need it because the documentation for me is still a 
little hard to read and hard for me to search for a class 
method here or there. For instance, I was doing 
toHexString(myByteArray) instead of simply doing 
myByteArray.toHexString(). (That was on an md5 example, by the 
way.) Intellisense would have helped me realize this.


Have you installed dkit for sublime?


Re: how do I check if a member of a T has a member ?

2015-09-13 Thread wobbles via Digitalmars-d-learn

On Sunday, 13 September 2015 at 16:46:54 UTC, Laeeth Isharc wrote:
can I check if a member of a T has a member without using a 
mixin?


hid_t createDataType(T)()
if (__traits(isSame, TemplateOf!(T), PriceBar))
{
auto tid=H5T.create(H5TClass.Compound,T.sizeof);
	enum offsetof(alias type, string field) = mixin(type.stringof 
~"."~field~".offsetof");
	H5T.insert(tid, "date", offsetof!(T,"date"), 
createDataType!(KalDate));

static if(hasMember!(T,"open"))

H5T.insert(tid,"open",offsetof!(T,"open"),mapDtoHDF5Type("double"));
}

I would like to check if date has a member called second.

Thanks.


Use __traits(compiles, date.second)?


Re: Is D suitable for my latest project?

2015-09-08 Thread wobbles via Digitalmars-d-learn

On Tuesday, 8 September 2015 at 19:30:16 UTC, chris stevens wrote:

On Sunday, 6 September 2015 at 14:45:45 UTC, BBasile wrote:
You have Object.factory for this. You can also use a custom 
factory based on string comparison. (with some: static 
if(condition) return new This; else static if(otherCondition) 
return new That; etc).


I just had a look at Object.factory and this isn't actually 
what I wanted. I was looking for something that would allow me 
to create new (previously undefined) classes in D at runtime 
that I could then use with Object.factory to create instances 
of.


I think I can do this with Variants and dynamic, is this 
possible? Or is there another way?


"Previously undefined". As far as I know, this is impossible in 
D. Thr compiler has to know how much memory to allocate/request 
and it has to know that at compiletime (else it wouldn't be the 
compiler!)


This functionality in Java/C# is possible because it's running on 
a vm that allows special instructions to make the vm compile and 
make available a class dynamically (and by extension, slowly)


Re: Can we get a video tutorial?

2015-09-03 Thread wobbles via Digitalmars-d-learn

On Thursday, 3 September 2015 at 19:13:35 UTC, Stephen wrote:
On Wednesday, 2 September 2015 at 01:15:28 UTC, Mike Parker 
wrote:

* What was previously said *


Ok, so, I am running Windows 10, I have installed VS 2015, I 
have installed DMD 1 and 2 (I know I only need 2 but it 
shouldn't hurt to have both), I have installed VisualD, and I 
have installed DUB with it's installer. (All of these installed 
successfully and work)


So, I'm trying to install gtkD but get "Error: module 
MainWindow is in file 'gtk/MainWindow.d' which cannot be read" 
when I try to run the program. No idea what this means, how to 
fix it, or what step I missed.


What I'd like is for someone to either make a tut of how to get 
from no Dlang on their computer to having a package working in 
a program, or for someone to help me and I'll try to make one 
later.


So, can you show your projects dub.json?



Re: How to test if a double has no fraction part

2015-09-03 Thread wobbles via Digitalmars-d-learn

On Thursday, 3 September 2015 at 12:51:42 UTC, Namal wrote:
Interesting, in contrary to C++ it saves the integral part in 
the dummy variable. Doing this I noticed if I try to write a 
double variable in the console it gives me only the integral 
part. I only did it with writeln so far. How can I print out a 
double variable with a precision of 2 for instance? I tried it 
with writefln("%d", d)

It compiles but crashes.


I believe .2 will print it precision two.
writefln("%.2s", d)

More info here:
   http://dlang.org/phobos/std_format.html#formattedWrite


Re: reading file byLine

2015-09-02 Thread wobbles via Digitalmars-d-learn

On Wednesday, 2 September 2015 at 21:53:20 UTC, Namal wrote:
Thx guys, this helped alot. The next thing I want to do is read 
the file line by line and split the stream into words. I found 
this example of code that seems to do sort of something like 
it. How can I modyfy it so I can store the words in an array of 
strings? Is a => a.length the iterator range?



import std.algorithm, std.stdio, std.string;
// Count words in a file using ranges.
void main()
{
auto file = File("file.txt"); // Open for reading
const wordCount = file.byLine()// Read lines
  .map!split   // Split into 
words
  .map!(a => a.length) // Count words 
per line
  .sum();  // Total word 
count

writeln(wordCount);
}



I would do what you want like this

auto file = File("file.txt");
auto words = file.byLine()   // you've all lines in  range
 .map!(a => a.split); // read each line, 
splitting it into words
 // now you've a range, where 
each element is an array of words


The map!(a => a.split) line simply maps each element to the 
return value of a.split - this is the predicate.


The a => a.split syntax is a lambda expression that tells map 
what to do on each element.


Re: How to get BaseEnumType?

2015-08-31 Thread wobbles via Digitalmars-d-learn

On Monday, 31 August 2015 at 08:10:35 UTC, wobbles wrote:

On Monday, 31 August 2015 at 07:55:53 UTC, drug wrote:

import std.stdio;
import std.traits;
void main(){
static if(isSomeString!Foo){
writefln("String: %s", Foo.A);
}
static if(isScalarType!Bar){
writefln("Integer: %s", Bar.A);
}
static if(isSomeString!Bar){
writefln("String: %s", Foo.A); // wont print // 
Bar.A

}
static if(isScalarType!Foo){
writefln("Integer: %s", Bar.A); // wont print 
// Foo.A

}
}

enum Foo { A="a", B = "b" }
enum Bar { A=1, B=2 }


My copy paste got the better of me. The print messages in the 
last two static ifs shoudl be Bar.A and Foo.A respectively :)


Re: How to get BaseEnumType?

2015-08-31 Thread wobbles via Digitalmars-d-learn

On Monday, 31 August 2015 at 07:55:53 UTC, drug wrote:

Hello
I need to get the type to which I can cast the enum for using 
with foreign library. For example:

```
enum Foo { A = "a", B = "b", }
enum Bar { A = 123, B = 432, }

static assert(is(BaseEnumType!Foo == string));
static assert(is(BaseEnumType!Bar == int));

I guess there is simple answer somewhere but I failed to find 
it yet.


In std.traits there is the required isX funcitons.

import std.stdio;
import std.traits;
void main(){
static if(isSomeString!Foo){
writefln("String: %s", Foo.A);
}
static if(isScalarType!Bar){
writefln("Integer: %s", Bar.A);
}
static if(isSomeString!Bar){
writefln("String: %s", Foo.A); // wont print
}
static if(isScalarType!Foo){
writefln("Integer: %s", Bar.A); // wont print
}
}

enum Foo { A="a", B = "b" }
enum Bar { A=1, B=2 }



How to get the current Timezone

2015-08-28 Thread wobbles via Digitalmars-d-learn

From the docs in std.datetime, I figured I could write:

Clock.currTime.timezone().name()

to get the timezone this system is in. However, it just returns 
an empty string.

Anyone know how to get the timezone of the machine easily?

Thanks!


Re: automatically verifying code samples in phobos docs

2015-08-20 Thread wobbles via Digitalmars-d-learn

On Thursday, 20 August 2015 at 06:28:44 UTC, Jacob Carlborg wrote:

On 2015-08-20 01:41, Laeeth Isharc wrote:

[...]


Just use a documented unit tests block:

///
unittest
{
// code goes here
}

It will be run as part of the unit tests and it will be 
included when generating the documentation.


Although I don't have a good solution for the code in dlang.org 
that's not part of the Phobos/druntime documentation.



[...]


char[] is mutable while string is not. Someone else can have a 
reference to the same data and change it will it's typed as 
string, breaking the type system.


Will AutoProtocol().idup not make this work?
Make an immutable copy of whatever AutoProtocol() returns, which 
should be then immutable char[] (i.e. string)


Re: dmd.conf... again

2015-08-12 Thread wobbles via Digitalmars-d-learn

On Wednesday, 12 August 2015 at 14:05:57 UTC, Atila Neves wrote:

On Wednesday, 12 August 2015 at 13:46:24 UTC, wobbles wrote:
On Wednesday, 12 August 2015 at 13:00:45 UTC, Atila Neves 
wrote:
On Wednesday, 12 August 2015 at 12:40:49 UTC, Adam D. Ruppe 
wrote:

[...]


I downloaded the zip, added linux/bin64 to PATH, tried 
compiling a hello world and got:


usr/bin/ld: cannot find -l:libphobos2.a

That's when I started trying to set the configuration but 
nothing seems to work.


Atila


Have you run dmd from the directory you unzipped it to?
libphobos2.a is in there I think, so ld wouldn't be able to 
find it.


Just did, didn't work. Tried it from lib64 and lib32 as well, 
nothing.


Atila


Hmm, I'll setup a VM later this evening to test, see if I can 
figure it out. This really should be easier.




Re: Convert a hex color string into r,g,b components.

2015-08-12 Thread wobbles via Digitalmars-d-learn

On Tuesday, 11 August 2015 at 22:11:51 UTC, Marcin Szymczak wrote:

I would really love to solve this problem using ranges, because 
i am learning how to use them. Unfortunately even such a simple 
task seems so hard for me ;(


I think writing a simple function to parse a string into a Color 
would be best here.


Color parseRGBString(string theString){
if(theString.length != 7)
throw new Exception(Error. Cannot parse to 
color:  ~ theString);

return Color(
to!ubyte(theString[1..3], 16),
to!ubyte(theString[3..5], 16),
to!ubyte(theString[5..7], 16)
);
}

I could probably do more to ensure that the string actually does 
represent a color (e.g. Check if no char is  F etc).


Also, using ranges isn't always required, theres no such thing as 
a too simple solution, as long as it works!


You can use this in a range then, e.g. say the user passes in 
lots of strings to your program, you can


listOfColors.map!(a = a.parseRGBString); // and now you have a 
lazily evaluated list of Color objects.


Re: dmd.conf... again

2015-08-12 Thread wobbles via Digitalmars-d-learn

On Wednesday, 12 August 2015 at 13:00:45 UTC, Atila Neves wrote:
On Wednesday, 12 August 2015 at 12:40:49 UTC, Adam D. Ruppe 
wrote:
On Wednesday, 12 August 2015 at 12:16:50 UTC, Atila Neves 
wrote:
I'm trying to use dmd on a VM where I don't have root 
privileges (don't ask). I can't copy dmd.conf to /etc.


If you use the dmd zip, everything just works when you just 
unzip it and use it all in-place. No need to move or copy 
files anywhere, no need for root.


I downloaded the zip, added linux/bin64 to PATH, tried 
compiling a hello world and got:


usr/bin/ld: cannot find -l:libphobos2.a

That's when I started trying to set the configuration but 
nothing seems to work.


Atila


Have you run dmd from the directory you unzipped it to?
libphobos2.a is in there I think, so ld wouldn't be able to find 
it.


Re: Yes or No Options

2015-07-28 Thread wobbles via Digitalmars-d-learn

On Monday, 27 July 2015 at 18:23:57 UTC, Alex wrote:

On Monday, 27 July 2015 at 17:31:08 UTC, Ali Çehreli wrote:

On 07/27/2015 08:50 AM, Alex wrote:

 a book that I bought

The program looks a lot like one of the exercises in this 
chapter:


  http://ddili.org/ders/d.en/if.html

You didn't actually pay for it, right? Because it is free. :)

Ali




Yes! I am really sorry. I did not buy it. Thanks for this book, 
it is really cool to learn and understandable even for people 
like me that have never had any contact with programming!


Good on you to pick it up and learn. It's a very interesting 
field once you get past the initial learning curve!


Be sure to continue to ask questions here, I find most people 
here are very willing to help newbies :)


Re: oauth, Twitter, and std.net.curl

2015-06-15 Thread wobbles via Digitalmars-d-learn

On Monday, 15 June 2015 at 14:41:32 UTC, Taylor Gronka wrote:

Hello,

I've picked up a web design project, and I would love to use 
vibe.d/dlang. I need to use oauth to search on a number of web 
api's, such as searching for Twitter tweets.


I tried using Adam's oauth (Thanks!). However, it doesn't 
appear support the validation needed for searching Twitter.

https://github.com/adamdruppe/arsd/blob/master/oauth.d


Now I'm looking at std.net.curl, and this is my thought: is 
HTTP.addRequestHeader(key, val) able to set the oauth 
authentication headers? It would look a bit odd, but if 
something like this works, then it wouldn't be difficult to 
code for each set of headers specifically:


auto client = HTTP(https://api.twitter.com;); // not sure 
if https should be set here or somewhere else

string bearerUrl = https://api.twitter.com/oauth2/token;;
client.addRequestHeader(Authorization, Basic 
eHZ6MWV2RlM0d0VFUFRHRUZQSEJvZzpMOHFxOVBaeVJnNmllS0dFS2hab2xHQzB2SldMdzhpRUo4OERSZHlPZw);

client.postData(grant_type=client_credentials);
client.perform();

(The above example is based on Step 2 of this page)
https://dev.twitter.com/oauth/application-only


Of course, the oauth headers look a bit different, but I 
imagine it being something like this:
client.addRequestHeader(Authorization, OAuth2 token: 
\string\, tokensecret: \string\, appkey, \string\ ...);

\\ not sure if that's how to escape quotes in dlang


Can I get some guidance on this? I would really like to use 
dlang, but I can't afford to be stuck on this for too long. I'd 
be happy to try and write a modification of Adam's code, but I 
lack experience, so it's a slow process for me.


I'd also be happy to write up little tutorials/blogposts about 
how I accomplish various tasks.


Thanks,


You can use vibe.d to send requests rather than going the 
lowlevel curl library.


Check out the requestHTTP method [1]
From code I've written in the past, your setup looks correct.

This is some vibe.d code I've used to get a refresh token from 
Youtube (I know it's different from twitter, but the idea is the 
same)


YoutubeToken is a local struct that contains the access_token we 
need to perform searches/post videos etc in any subsequent 
requests.


/**
 * Returns a new YoutubeToken
 */
public YoutubeToken getRefreshToken(){
string url = https://accounts.google.com/o/oauth2/token;;

string postBody = 
client_id=$CLIENT_ID$client_secret=$CLIENT_SECRET$refresh_token=$REFRESH_TOKEN$grant_type=$GRANT_TYPE$

.replaceMap(
[
$CLIENT_ID$ : credentials.clientID,
$CLIENT_SECRET$ : credentials.clientSecret,
$REFRESH_TOKEN$ : credentials.refreshToken,
$GRANT_TYPE$ : refresh_token
]
);

logInfo(Getting new refresh token with URL: %s and postBody: 
%s, url, postBody);


auto response = requestHTTP(url,
(scope req){
req.method = HTTPMethod.POST;
req.contentType = application/x-www-form-urlencoded;
req.writeBody(cast(ubyte[])postBody);
}).bodyReader.readAllUTF8().parseJsonString;

return YoutubeToken(response[access_token].get!string, 
response[expires_in].get!long, 
response[token_type].get!string );

}


[1] http://vibed.org/api/vibe.http.client/requestHTTP


Re: oauth, Twitter, and std.net.curl

2015-06-15 Thread wobbles via Digitalmars-d-learn

On Monday, 15 June 2015 at 15:23:43 UTC, Taylor Gronka wrote:

You two are phenomenal! Thanks!


Oh, replaceMap is a custom funciton I wrote too...
Eases replacing multiple values in a string with 1 function call.

I wont pretend that it's fast as it allocates a lot of memory :)

public string replaceMap(string str, string[string] keys){
import std.array;
foreach(key, val; keys){
str = str.replace(key, val);
}
return str;
}


Re: Casting MapResult

2015-06-15 Thread wobbles via Digitalmars-d-learn

On Monday, 15 June 2015 at 15:10:24 UTC, jmh530 wrote:

snip
float[] exp(float[] x) {
auto y = x.map!(a = exp(a));
cast(float[]) y;
return y;
}




Also, I dont think your functions will work?
Your recursively calling exp in your map, but with a 'float' 
instead of 'float[]'.


Re: Template problem - if arg[0]==something; call arg[1];

2015-05-28 Thread wobbles via Digitalmars-d-learn

On Wednesday, 27 May 2015 at 22:49:50 UTC, ketmar wrote:

On Wed, 27 May 2015 22:49:18 +, ketmar wrote:


   i.e. `constructCases~(Aliases[2..$])`

`constructCases!(Aliases[2..$])`, of course ;-)


Only getting back to this now...

Doesnt seem to work, I think I might rethink it and write a 
function (A usual function, rather than a Template). Easier for 
me to get my puny brain around it!


Template problem - if arg[0]==something; call arg[1];

2015-05-27 Thread wobbles via Digitalmars-d-learn

I have some code that I'd really like to template-ize.

Currently, I've the same construct all over my code, repeated(yet 
slightly different) about 15 times.

Too much for me, and I'd like to make it into a template.

This is a sample of my current code:
http://dpaste.dzfl.pl/76814846898e

I essentially want to change the
string helper(){
snip
foreach(child; toSpawn.children){
switch(child.name){
case NameOfArg1:
str ~= FunctionToCall1;
break;
case NameOfArg2:
str ~= FunctionToCall2;
break;
snip
}
function to something like:

handleParseTreeHelper!( string NameOfArg1, delegate 
FunctionToCall1,
string NameOfArg2, delegate 
FunctionToCall2 );


Any idears?


Re: Writing to two files at once

2015-05-21 Thread wobbles via Digitalmars-d-learn

On Thursday, 21 May 2015 at 21:02:42 UTC, Ali Çehreli wrote:

On 05/21/2015 01:56 PM, wobbles wrote:

What I ended up doing was creating an OutputRange that 
contains the

files I want to write to.
On OutputRange.put I simply print to print to all the files.


Just like MultiFile example here: :)

  http://ddili.org/ders/d.en/ranges.html#ix_ranges.OutputRange

Ali


Yeah!
This is my implementation:
public struct OutputSink{
File[] files;
@property void addFile(File f){ files ~= f; }
@property File[] file(){ return files; }

void put(Args...)(string fmt, Args args){
foreach(file; files)
file.writefln(fmt, args);
}
}

I'll remember to look in your book next time I need something 
simple :)


Re: Writing to two files at once

2015-05-21 Thread wobbles via Digitalmars-d-learn

On Thursday, 21 May 2015 at 20:15:29 UTC, wobbles wrote:

On Thursday, 21 May 2015 at 20:06:08 UTC, wobbles wrote:

I would like to write to two files at once.

If user specifies verbose flag, output should write to both 
stdout and the programs standard output file.


Any ideas?


I should add, I'm using a library that already writes it's 
output to a std.stdout.File that I can provide it, so my 
thinking is I need a std.stdout.File that points at both stdout 
and some arbitrary file location.


Tricky I think...


What I ended up doing was creating an OutputRange that contains 
the files I want to write to.

On OutputRange.put I simply print to print to all the files.

Means I had to edit the underlying library, but that's OK as I 
own it, and this seems more robust anyway :)


Re: Writing to two files at once

2015-05-21 Thread wobbles via Digitalmars-d-learn

On Thursday, 21 May 2015 at 21:00:15 UTC, Cassio Butrico wrote:
If I understand right you want to redirect the output to a file 
by a flag , another file type , video printer is it?


I think by video printer you mean the console?
If so, yes.

I believe I've solved it anyway, see Ali and my answer above.
Thanks!


Writing to two files at once

2015-05-21 Thread wobbles via Digitalmars-d-learn

I would like to write to two files at once.

If user specifies verbose flag, output should write to both 
stdout and the programs standard output file.


Any ideas?


Re: Writing to two files at once

2015-05-21 Thread wobbles via Digitalmars-d-learn

On Thursday, 21 May 2015 at 20:06:08 UTC, wobbles wrote:

I would like to write to two files at once.

If user specifies verbose flag, output should write to both 
stdout and the programs standard output file.


Any ideas?


I should add, I'm using a library that already writes it's output 
to a std.stdout.File that I can provide it, so my thinking is I 
need a std.stdout.File that points at both stdout and some 
arbitrary file location.


Tricky I think...


Re: Spawning a console in Windows (similar to forkpty on linux)

2015-05-11 Thread wobbles via Digitalmars-d-learn

On Saturday, 9 May 2015 at 23:32:49 UTC, Adam D. Ruppe wrote:

On Saturday, 9 May 2015 at 13:00:01 UTC, wobbles wrote:
On Linux, I'm able to edit a file descriptor after I've 
created it to tell it to read/write asynchronously, I cant 
seem to find anything similar on windows however.


Asynchronous I/O on Windows is called Overlapped I/O. It is a 
bit involved to use though, especially since D by default 
doesn't come with all the necessary headers. You can download 
the win32 api bindings or you can just declare the bits as 
needed.


My terminal emulator uses overlapped I/O and a spawned process 
(and on Linux, it uses forkpty!) to talk to ssh on Windows.


https://github.com/adamdruppe/terminal-emulator/blob/master/terminalemulator.d

I had to write a function to make an async pipe, then spawn a 
process using them, then get and send data. I also declared all 
the needed functions myself.


A lot of code to go through but it is a working example... a 
few things to look for are MyCreatePipeEx, CreateProcess, the 
word 'overlapped', ReadFileEx, and the simpledisplay.d library 
it imports also uses SleepEx which lets other things trigger.


Thanks adam, this is very helpful!


Spawning a console in Windows (similar to forkpty on linux)

2015-05-09 Thread wobbles via Digitalmars-d-learn
This isn't specifically a D question, but seeing as it's for a D 
library I figure it can go here :)


On Windows, I want to be able to spawn a console and then 
interact with its stdin/out asynchronously, similar to how 
forkpty [1] works on linux.


I'm improving my dexpect library [2] to work with windows 
machines and this bit has me stumped. There doesnt seem to be 
much info about it that I can find (though my google-fu mightn't 
be good enough!!)


I'm sure theres someone here who knows something?

Thanks!

[1] http://linux.die.net/man/3/forkpty
[2] https://github.com/grogancolin/dexpect


Re: Spawning a console in Windows (similar to forkpty on linux)

2015-05-09 Thread wobbles via Digitalmars-d-learn

On Saturday, 9 May 2015 at 12:25:32 UTC, wobbles wrote:

On Saturday, 9 May 2015 at 12:16:52 UTC, Rikki Cattermole wrote:

On 10/05/2015 12:13 a.m., wobbles wrote:
This isn't specifically a D question, but seeing as it's for 
a D library

I figure it can go here :)

On Windows, I want to be able to spawn a console and then 
interact with
its stdin/out asynchronously, similar to how forkpty [1] 
works on linux.


I'm improving my dexpect library [2] to work with windows 
machines and
this bit has me stumped. There doesnt seem to be much info 
about it that

I can find (though my google-fu mightn't be good enough!!)

I'm sure theres someone here who knows something?

Thanks!

[1] http://linux.die.net/man/3/forkpty
[2] https://github.com/grogancolin/dexpect


Did you try creating a new process which is cmd?
Because std.process should be able to handle the IO part.


I have, but they all block i/o and so I cant continually read 
from its output :/


What I mean is, if the cmd.exe hasnt flushed it's output, my 
cmdPid.stdout.readln (or whatever) will block until it does. I 
dont really want this.


I guess I need to make another thread to do this so I wont block 
the main thread?


Re: Spawning a console in Windows (similar to forkpty on linux)

2015-05-09 Thread wobbles via Digitalmars-d-learn

On Saturday, 9 May 2015 at 12:16:52 UTC, Rikki Cattermole wrote:

On 10/05/2015 12:13 a.m., wobbles wrote:
This isn't specifically a D question, but seeing as it's for a 
D library

I figure it can go here :)

On Windows, I want to be able to spawn a console and then 
interact with
its stdin/out asynchronously, similar to how forkpty [1] works 
on linux.


I'm improving my dexpect library [2] to work with windows 
machines and
this bit has me stumped. There doesnt seem to be much info 
about it that

I can find (though my google-fu mightn't be good enough!!)

I'm sure theres someone here who knows something?

Thanks!

[1] http://linux.die.net/man/3/forkpty
[2] https://github.com/grogancolin/dexpect


Did you try creating a new process which is cmd?
Because std.process should be able to handle the IO part.


I have, but they all block i/o and so I cant continually read 
from its output :/


Re: Spawning a console in Windows (similar to forkpty on linux)

2015-05-09 Thread wobbles via Digitalmars-d-learn

On Saturday, 9 May 2015 at 12:48:16 UTC, Kagamin wrote:

On Saturday, 9 May 2015 at 12:26:58 UTC, wobbles wrote:
What I mean is, if the cmd.exe hasnt flushed it's output, my 
cmdPid.stdout.readln (or whatever) will block until it does. I 
dont really want this.


Are you sure cmd is the culprit? It should have sensible 
buffering. Also do you want just a console window or also a 
command interpreter attached to it?


My windows knowledge isnt marvelous, but I believe I'll need the 
interpreter attached.


Just as an example of running cmd through std.process, running 
this on my system:

auto pipes = pipeShell(cmd.exe);
write(pipes.stdout.readln);
write(pipes.stdout.readln);
write(pipes.stdout.readln);
return;
will print
`
Microsoft Windows [Version 6.3.9600]
(c) 2013 Microsoft Corporation. All rights reserved.

`
and then exits.

However, adding another write line before the return; will 
cause the program to hang there, waiting for the cmd.exe process 
to flush it's next line.


On Linux, I'm able to edit a file descriptor after I've created 
it to tell it to read/write asynchronously, I cant seem to find 
anything similar on windows however.


Re: Spawning a console in Windows (similar to forkpty on linux)

2015-05-09 Thread wobbles via Digitalmars-d-learn

On Saturday, 9 May 2015 at 13:00:01 UTC, wobbles wrote:

On Saturday, 9 May 2015 at 12:48:16 UTC, Kagamin wrote:

On Saturday, 9 May 2015 at 12:26:58 UTC, wobbles wrote:
What I mean is, if the cmd.exe hasnt flushed it's output, my 
cmdPid.stdout.readln (or whatever) will block until it does. 
I dont really want this.


Are you sure cmd is the culprit? It should have sensible 
buffering. Also do you want just a console window or also a 
command interpreter attached to it?


My windows knowledge isnt marvelous, but I believe I'll need 
the interpreter attached.


Just as an example of running cmd through std.process, running 
this on my system:

auto pipes = pipeShell(cmd.exe);
write(pipes.stdout.readln);
write(pipes.stdout.readln);
write(pipes.stdout.readln);
return;
will print
`
Microsoft Windows [Version 6.3.9600]
(c) 2013 Microsoft Corporation. All rights reserved.

`
and then exits.

However, adding another write line before the return; will 
cause the program to hang there, waiting for the cmd.exe 
process to flush it's next line.


On Linux, I'm able to edit a file descriptor after I've created 
it to tell it to read/write asynchronously, I cant seem to find 
anything similar on windows however.


Spoke too soon. Looks like this is what I need:
http://www.codeproject.com/Articles/534/An-Introduction-to-Processes-Asynchronous-Process


Re: vibed: how to use pure HTML instead of template engine?

2015-05-07 Thread wobbles via Digitalmars-d-learn

On Thursday, 7 May 2015 at 08:25:30 UTC, Suliman wrote:

You're not setting a port.

add:
settings.port = 8080;

before listenHTTP();

then it'll work.


It's do not help :(


You're sure?

My app.d is:
import std.stdio;
import vibe.d;

shared static this(){
auto router = new URLRouter;

router.get(*, serveStaticFiles(./public/));

auto settings = new HTTPServerSettings;
settings.port = 8080;

listenHTTP(settings, router);
}

And i have a file
public/index.html
html
body
h1 Hi /h1
/body
/html

When I navigate to localhost:8080 i can see a big Hi.


Re: vibed: how to use pure HTML instead of template engine?

2015-05-07 Thread wobbles via Digitalmars-d-learn

On Thursday, 7 May 2015 at 09:08:53 UTC, wobbles wrote:

On Thursday, 7 May 2015 at 08:25:30 UTC, Suliman wrote:

You're not setting a port.

add:
settings.port = 8080;

before listenHTTP();

then it'll work.


It's do not help :(


You're sure?

My app.d is:
import std.stdio;
import vibe.d;

shared static this(){
auto router = new URLRouter;

router.get(*, serveStaticFiles(./public/));

auto settings = new HTTPServerSettings;
settings.port = 8080;

listenHTTP(settings, router);
}

And i have a file
public/index.html
html
body
h1 Hi /h1
/body
/html

When I navigate to localhost:8080 i can see a big Hi.


I see you have you're function called setupServer()

Are you using the vibe default main or you're own main function? 
It's possible you're not setting up the event loop correctly.


At - http://vibed.org/docs search for The main function and 
you'll see how to set it up correctly.


Re: vibed: how to use pure HTML instead of template engine?

2015-05-07 Thread wobbles via Digitalmars-d-learn

On Thursday, 7 May 2015 at 08:09:50 UTC, Suliman wrote:

Is next example is enough to serv simple index.html page?

void setupServer()
{
auto router = new URLRouter;
// add other routes here
router.get(*, serveStaticFiles(public/));

auto settings = new HTTPServerSettings;
listenHTTP(settings, router);
}

After it's run I open localhost:8080 but browser say that can't 
connect to the page.


You're not setting a port.

add:
settings.port = 8080;

before listenHTTP();

then it'll work.


Re: Linker command

2015-05-06 Thread wobbles via Digitalmars-d-learn

On Monday, 4 May 2015 at 20:34:32 UTC, Paul wrote:
Can some one tell me what this linker command means (or point 
me at some docs) please:


dmd example.d -L-L. $@

AFAIK $@ is 'all the supplied arguments' so I don't understand 
what it achieves.


(it's from the DAllegro5 example program, on Linux).

Cheers,

Paul


I'm guessing this command is to be called from a script 
somewhere. So then it will just pass all the arguments passed to 
that script to dmd.


Cant really tell without more info on how it's called, but that's 
what it'll do.


Re: getopt helpWanted

2015-04-30 Thread wobbles via Digitalmars-d-learn

On Wednesday, 29 April 2015 at 22:02:29 UTC, novice2 wrote:

Hello.

Help me please to understand, how to show usage help to user, 
who enter wrong options?

For example, user not provided required filename.
I want to show error message, and program usage help text.
But likely getopt don't provide help text until valid options 
will be parsed.


Reduced code:
///
import std.stdio: writefln;
import std.getopt;

void main (string[] args)
{
  string fname;
  GetoptResult helpInfo;

  try
  {
helpInfo = getopt(
  args,
  std.getopt.config.required, file|f, File name, 
fname);


writefln(Options parsed: fname=%s, fname);
  }
  catch(Exception e)
  {
writefln(\nERROR: %s, e.msg);
defaultGetoptPrinter(Program usage:, helpInfo.options);
  }
}
///

Output:
ERROR: Required option file|fwas not supplied
Program usage:


Also, I suggest you look at docopt:
http://code.dlang.org/packages/docopt

It makes the whole parsing of CLI arguments very nice and easy.


Re: dub building is extremely slow

2015-04-30 Thread wobbles via Digitalmars-d-learn

On Thursday, 30 April 2015 at 03:00:36 UTC, zhmt wrote:

On Thursday, 30 April 2015 at 02:02:50 UTC, zhmt wrote:
dub build is running on centos7. It works well until today, It 
becomes very slow suddenly. It will take minuties per 
compilation, there is 10 files in project.


Has anyone experienced this?


It is because:
The dub will connect to some website to check version of 
packages,but the destination website is limited by my gov,so... 
the compilation is slowed.


solution:

shutdown the network of pc.


Try running with --nodeps (or --no-deps on phone so cant check).
It will make dub stop contacting the network.


Re: Possible to write a classic fizzbuzz example using a UFCS chain?

2015-04-28 Thread wobbles via Digitalmars-d-learn

On Tuesday, 28 April 2015 at 11:04:12 UTC, w0rp wrote:
On Tuesday, 28 April 2015 at 10:46:54 UTC, Gary Willoughby 
wrote:

After reading the following thread:

http://forum.dlang.org/thread/nczgumcdfystcjqyb...@forum.dlang.org

I wondered if it was possible to write a classic fizzbuzz[1] 
example using a UFCS chain? I've tried and failed.


[1]: http://en.wikipedia.org/wiki/Fizz_buzz


You can do this.

import std.range : iota;
import std.algorithm : map, each;
import std.typecons : Tuple, tuple;
import std.stdio : writeln;

Tuple!(size_t, string) fizzbuzz(size_t number) {
if (number % 3 == 0) {
if (number % 5 == 0) {
return tuple(number, fizzbuzz);
} else {
return tuple(number, fizz);
}
} else if (number % 5 == 0) {
return tuple(number, buzz);
}

return tuple(number, );
}

void main(string[] argv) {
iota(1, 101)
.map!fizzbuzz
.each!(x = writeln(x[0], : , x[1]));
}

The desired output may vary, depending on variations of 
FizzBuzz. (Some want the number always in the output, some 
don't.) You could maybe do crazy ternary expressions instead of 
writing a function, or put it directly in there as a lambda, 
but both just look ugly, and you might as well just write a 
function for it.


Crazy ternary experessions:

void main(){
%s.writefln(
iota(1, 100, 1)
.map!(a = a%3==0 ? (a%5==0? fizzbuzz : fizz)
: a%5==0 ? buzz : a.to!string));
}


Re: Return data from different types of conditional operation

2015-04-23 Thread wobbles via Digitalmars-d-learn

On Thursday, 23 April 2015 at 09:48:21 UTC, Dennis Ritchie wrote:

Hi,
Why the program can not return different types of data from the 
conditional operator?


-
import std.stdio;

auto foo() {

if (true) {
return 0;
} else
return true;
}

void main() {

writeln(foo);
}


Because 0 is an int and true is a string.
They're totally different types, and in a statically typed 
language like D, that just wont work.


Re: DMD 64 bit on Windows

2015-04-14 Thread wobbles via Digitalmars-d-learn

On Tuesday, 14 April 2015 at 01:31:27 UTC, Etienne wrote:
I'm currently experiencing Out Of Memory errors when compiling 
in DMD on Windows


Has anyone found a way to compile a DMD x86_64 compiler on 
Windows?


I've been having this same issue.
Over-use of CTFE is what's causing it on my part, to fix it, I've 
had to split my CTFE functions out into a seperate runtime tool 
(to make use of GC goodness. See people, GC is good! :))


The tool will print the code that my CTFE functions would 
normally generate to a file, and then use import to get it back 
into my main application.


Bit of a mess, but it works.

Dunno if this will help with your situation, as not sure if CTFE 
is causing it.


Managing memory usage at Compile Time with DMD

2015-04-09 Thread wobbles via Digitalmars-d-learn
So, I'm writing a poker AI bot. The idea was to generate a lookup 
table of all the poker hands using CTFE so runtime can be as 
quick as possible (as the bot has a very small amount of time to 
act).


There are a LOT of calculations though, many millions of 
combinations.


During complation, this is consuming inordinate amounts of 
memory, 16GB+ (which is all the RAM on my machine + some swap 
space).


I'm wondering is there any techniques to freeing some memory used 
by the compiler so it can be reused?

Are malloc and free usable at compile time maybe?

Another possibilty I was looking at was to write a tool that will 
spit out all combinations at runtime, and then import these back 
into the bot at compile time to build a lookup table that way.


Thanks!


Re: Managing memory usage at Compile Time with DMD

2015-04-09 Thread wobbles via Digitalmars-d-learn

On Thursday, 9 April 2015 at 10:04:09 UTC, John Colvin wrote:

On Thursday, 9 April 2015 at 09:49:39 UTC, wobbles wrote:
Another possibilty I was looking at was to write a tool that 
will spit out all combinations at runtime, and then import 
these back into the bot at compile time to build a lookup 
table that way.


Thanks!


This is definitely a better idea. I would probably load them at 
runtime instead, it scales better.


But if the compiler knows about all the values at compile time, 
it will be able to optimise things better than at runtime?


Cheers folks!
Will get to writing this now.


Re: Generating all combinations of length X in an array

2015-04-08 Thread wobbles via Digitalmars-d-learn

On Wednesday, 8 April 2015 at 11:08:00 UTC, wobbles wrote:

On Wednesday, 8 April 2015 at 10:54:45 UTC, bearophile wrote:

wobbles:

While trying to generate all combinations of length X in an 
array,

I came across the question on stackoverflow. [1]

Theres a couple good answers there, but one that caught my 
eye shows a C# code snippet that is quite nice and short:


Often short code is not the best code.

Take a look at the versions here, the usable one is the third:
http://rosettacode.org/wiki/Combinations#D

Bye,
bearophile


Ah, excellent! Dunno why I didnt think of rosettacode before.

Is the 3rd version usable at compile time?

Thanks, all the D stuff on rosettacode is an excellent resource!


Have just tested, it is!


Generating all combinations of length X in an array

2015-04-08 Thread wobbles via Digitalmars-d-learn

Hi folks,

While trying to generate all combinations of length X in an array,
I came across the question on stackoverflow. [1]

Theres a couple good answers there, but one that caught my eye 
shows a C# code snippet that is quite nice and short:


public static IEnumerableIEnumerableT CombinationsT(this 
IEnumerableT elements, int k)

{
  return k == 0 ? new[] { new T[0] } :
elements.SelectMany((e, i) =
  elements.Skip(i + 1).Combinations(k - 1).Select(c = (new[] 
{e}).Concat(c)));

}


I spent a couple hours trying to translate this to D, but couldnt 
get my head around the SelectMany statement.
I think it's analogous to std.algorithm.map, but it seems quite 
difficult to mimic the behaviour using map.


Anyone with more knowledge and/or skills like to have a crack?

Thanks!

[1] 
http://stackoverflow.com/questions/127704/algorithm-to-return-all-combinations-of-k-elements-from-n


Re: Generating all combinations of length X in an array

2015-04-08 Thread wobbles via Digitalmars-d-learn

On Wednesday, 8 April 2015 at 10:54:45 UTC, bearophile wrote:

wobbles:

While trying to generate all combinations of length X in an 
array,

I came across the question on stackoverflow. [1]

Theres a couple good answers there, but one that caught my eye 
shows a C# code snippet that is quite nice and short:


Often short code is not the best code.

Take a look at the versions here, the usable one is the third:
http://rosettacode.org/wiki/Combinations#D

Bye,
bearophile


Ah, excellent! Dunno why I didnt think of rosettacode before.

Is the 3rd version usable at compile time?

Thanks, all the D stuff on rosettacode is an excellent resource!


Re: Windows - std.process - Setting env variables from D

2015-03-30 Thread wobbles via Digitalmars-d-learn

On Monday, 30 March 2015 at 12:54:28 UTC, Adam D. Ruppe wrote:

On Monday, 30 March 2015 at 12:28:19 UTC, wobbles wrote:

Any solutions that people know of?


You can't from an exe, it is a limitation of the operating 
system (same on Linux btw, environment variable inheritance is 
always from parent to child, never from child to parent). The 
reason batch files can do it is that they don't run in a 
separate process, they just run a batch of commands inside the 
shell itself.


https://msdn.microsoft.com/en-us/library/windows/desktop/ms682009%28v=vs.85%29.aspx

Altering the environment variables of a child process during 
process creation is the only way one process can directly 
change the environment variables of another process. A process 
can never directly change the environment variables of another 
process that is not a child of that process.


If you're an administrator, you could poke the system-wide 
variables in the registry and tell the processes to reload 
them: 
https://msdn.microsoft.com/en-us/library/windows/desktop/ms682653%28v=vs.85%29.aspx


but of course, changing system-wide registry entries affects 
way more than just your parent shell!




If you need to change a parent shell variable, the only way is 
to do it from a batch file. You could perhaps run a .bat which 
sets the variable and calls your exe to help it do some work.

Thanks Adam,

Yeah, I knew it was the case in Linux, I just figured as 'set' 
worked in a batch file that it must be possible in Windows.


I think what I'm going to do is have my D program output the 
commands as strings that are required to set the ENV variables in 
the parent and then have a batch file to run the program, get its 
output and run the commands outputted from the D program.
Can also have a bash file to do the same (using the source 
command).


This is for setting up a build system we're using, and is 
normally run via Jenkins, so running it in a kind of ugly way 
doesnt really matter.


We're currently maintaining two seperate scripts to do this work, 
I'm trying to consolidate them. Maintaining one large-ish D 
script to do this work and 2 mini scripts to call them should be 
easier to maintain than 2 large bash/batch scripts.


Thanks!


Windows - std.process - Setting env variables from D

2015-03-30 Thread wobbles via Digitalmars-d-learn
I'm trying to set environment variables that will be visible when 
my D program exits.
It is possible in a windows batch file using the set command 
(like set VAR=VALUE )


However, running this in D using:

import std.process;
import std.stdio;

void main(){

auto pid1 = spawnShell(`set VAR=VALUE`);
pid1.wait();
auto pid2 = spawnShell(`set`);
pid2.wait();
}


however, upon exit, there is no VAR=VALUE in the environment.

Using std.process.environment[VAR]= VALUE; doesnt store the 
variable in the parent either.


Any solutions that people know of?


Re: Windows - std.process - Setting env variables from D

2015-03-30 Thread wobbles via Digitalmars-d-learn

On Monday, 30 March 2015 at 14:14:50 UTC, Laeeth Isharc wrote:

On Monday, 30 March 2015 at 13:29:06 UTC, wobbles wrote:

On Monday, 30 March 2015 at 12:54:28 UTC, Adam D. Ruppe wrote:

On Monday, 30 March 2015 at 12:28:19 UTC, wobbles wrote:

Any solutions that people know of?


You can't from an exe, it is a limitation of the operating 
system (same on Linux btw, environment variable inheritance 
is always from parent to child, never from child to parent). 
The reason batch files can do it is that they don't run in a 
separate process, they just run a batch of commands inside 
the shell itself.


https://msdn.microsoft.com/en-us/library/windows/desktop/ms682009%28v=vs.85%29.aspx

Altering the environment variables of a child process during 
process creation is the only way one process can directly 
change the environment variables of another process. A 
process can never directly change the environment variables 
of another process that is not a child of that process.


If you're an administrator, you could poke the system-wide 
variables in the registry and tell the processes to reload 
them: 
https://msdn.microsoft.com/en-us/library/windows/desktop/ms682653%28v=vs.85%29.aspx


but of course, changing system-wide registry entries affects 
way more than just your parent shell!




If you need to change a parent shell variable, the only way 
is to do it from a batch file. You could perhaps run a .bat 
which sets the variable and calls your exe to help it do some 
work.

Thanks Adam,

Yeah, I knew it was the case in Linux, I just figured as 'set' 
worked in a batch file that it must be possible in Windows.


I think what I'm going to do is have my D program output the 
commands as strings that are required to set the ENV variables 
in the parent and then have a batch file to run the program, 
get its output and run the commands outputted from the D 
program.
Can also have a bash file to do the same (using the source 
command).


This is for setting up a build system we're using, and is 
normally run via Jenkins, so running it in a kind of ugly way 
doesnt really matter.


We're currently maintaining two seperate scripts to do this 
work, I'm trying to consolidate them. Maintaining one 
large-ish D script to do this work and 2 mini scripts to call 
them should be easier to maintain than 2 large bash/batch 
scripts.


Thanks!


You tried setx, and it didn't work ?  Or you don't want to set 
permanent environmental variables


Yep, correct. Don't want them to be permanent. The systems have
to be clean for other tests at all times, so they need to be on a
shell by shell basis sadly.


Re: OPTLINK Error 45 Too Much DEBUG Data for Old CodeView format

2015-03-23 Thread wobbles via Digitalmars-d-learn

On Sunday, 22 March 2015 at 15:29:00 UTC, Koi wrote:


thank you Etienne, after i replaced dmd's link.exe my project 
compiles successfully in debug-mode again.


i'll add this info in my todo-after-installing-DMD.txt just 
in case.


On Sunday, 22 March 2015 at 14:29:14 UTC, Etienne wrote:

This is due to a high amount of symbols in your code.

I fixed this almost a year ago in the optlink repository:

https://github.com/DigitalMars/optlink/pull/15

You should be able to download it on the digitalmars.com 
website under:


Digital Mars C/C++ Compiler Version 8.57 (3662658 bytes)

The link.exe file in the bin folder is up-to-date.



Maybe this should be distributed in the DMD installer?


Re: enum and static if

2015-03-11 Thread wobbles via Digitalmars-d-learn

On Wednesday, 11 March 2015 at 14:34:32 UTC, ketmar wrote:

On Wed, 11 Mar 2015 13:48:45 +, Namespace wrote:


This code does not work:


enum Test {
 Foo,
static if (__VERSION__ = 2067)
 Bar,
}
 Quatz
}


Any chance that this could work?


nope. `static if` is statement, so it works only where 
statement is

allowed. the same is true for `version`. this is by design.


You can do something like
static if (__VERSION__ = 2067)
enum Test{ ... }
else
enum Test{ ... }

as a workaround?


Re: Dub + Optlink == ???

2015-03-09 Thread wobbles via Digitalmars-d-learn

On Sunday, 8 March 2015 at 23:05:53 UTC, David Held wrote:

On 3/8/2015 3:55 PM, David Held wrote:
Since DDT (Eclipse plugin) uses Dub, I am trying to convert 
the DWT

build instructions into Dub.  Here is my current attempt:

{
name : foo,
description : foo,
importPaths : [ d:/workspace/dwt/imp ],
stringImportPaths : [
D:/workspace/dwt/org.eclipse.swt.win32.win32.x86/res ],
lflags : [
   -L+D:/workspace/dwt/lib,
   -L/SUBSYSTEM:WINDOWS:4.0
],
libs : [
   org.eclipse.swt.win32.win32.x86,
   dwt-base
]
}
[...]


Figured it out.  Even though lflags is a string[], the strings 
get concatenated with no spaces. :/  This works:


lflags : [
   -L+..\\dwt\\lib\\ -L/SUBSYSTEM:WINDOWS:4.0
],

Dave


Seems like a bug on dubs part?


Re: Opening temporary files for std.process.spawnProcess input/output

2015-02-26 Thread wobbles via Digitalmars-d-learn

On Wednesday, 25 February 2015 at 19:09:16 UTC, Ali Çehreli wrote:

On 02/25/2015 05:56 AM, wobbles wrote:

 Hi,
 Any reason why the following wont work?

 void main(string[] args)
 {
  auto pidIn = File.tmpfile();
  auto pidOut = File.tmpfile();
  auto pid = spawnProcess([ls, ./], pidIn, pidOut,
 std.stdio.stdout, null, Config.newEnv);

  if(wait(pid) == 0)
  writefln(%s, pidOut.readln());
 }

 The pidOut.readln() throws this exception:
 object.Exception@/usr/include/dmd/phobos/std/stdio.d(1377):
Attempt to
 read from an unopened file.

 I figured tmpfile() would be open for read/write by default?
 Also, theres no way to pass in args to File.tmpfile() to make
them
 read/write.

 Any ideas?

It looks like the file is closed when spawnProcess is finished. 
I don't know whether it is done by spawnProcess explicitly or 
whether it is a behavior for temporary files.


How about using a pipe? The following works:

import std.stdio;
import std.process;

void main(string[] args)
{
auto pidIn = File.tmpfile();
auto pidOut = pipe();
auto pid = spawnProcess([ls, ./ ],
pidIn, pidOut.writeEnd,
std.stdio.stdout, null, 
Config.newEnv);


if(wait(pid) == 0)
writeln(pidOut.readEnd.byLine);
}

Ali


This works, Thanks folks!


Opening temporary files for std.process.spawnProcess input/output

2015-02-25 Thread wobbles via Digitalmars-d-learn

Hi,
Any reason why the following wont work?

void main(string[] args)
{
auto pidIn = File.tmpfile();
auto pidOut = File.tmpfile();
auto pid = spawnProcess([ls, ./], pidIn, pidOut, 
std.stdio.stdout, null, Config.newEnv);


if(wait(pid) == 0)
writefln(%s, pidOut.readln());
}

The pidOut.readln() throws this exception:
object.Exception@/usr/include/dmd/phobos/std/stdio.d(1377): 
Attempt to read from an unopened file.


I figured tmpfile() would be open for read/write by default?
Also, theres no way to pass in args to File.tmpfile() to make 
them read/write.


Any ideas?



Re: Static method of inner class needs this

2015-02-09 Thread wobbles via Digitalmars-d-learn

On Monday, 9 February 2015 at 07:32:33 UTC, rumbu wrote:

class Outer
{
class Inner
{
static Inner createInner()
{
return new Inner(); //need 'this' to access member 
this

}
}
}

Is this a bug?

If Inner is not nested, it works as expected:

class Inner
{
static Inner createInner()
{
return new Inner()
}
}

D version: 2.066.1


In the first case, is there an Inner that is visible outside of 
Outer?
If so, the compiler wont know which one your talking about, so 
need to specify with this.


Re: Question about Allocating

2015-01-26 Thread wobbles via Digitalmars-d-learn

On Monday, 26 January 2015 at 07:52:06 UTC, Gan wrote:
I've been working on my game and am getting some pretty gnarly 
memory problems. I think it's how I'm allocating.


Sometimes when I use variables I can do Color(255, 255, 255). 
But why is that different than new Color(255, 255, 255)?

Same when I'm making arrays. new int[](0) vs [].


What's the difference?


Color(255, 255, 255) will return Color.
new Color(255, 255, 255) will return Color*.
The difference is the * is stored in general purpose memory and 
is allocated at runtime, meaning the GC will come into play.


Allocating without the new keyword makes the compiler set aside 
the correct amount of memory for the object at compile time, thus 
avoiding requesting new memory from the OS at runtime.


Theres a bit about it in ali's book that may help: 
http://ddili.org/ders/d.en/class.html


Re: Dub / Derelict confusion

2014-11-19 Thread wobbles via Digitalmars-d-learn

On Wednesday, 19 November 2014 at 09:12:52 UTC, Paul wrote:
I would like to create a simple program using SDL. I've read 
this page 
http://dblog.aldacron.net/derelict-help/using-derelict/ and 
this one http://code.dlang.org/about and decided that using 
'dub' would be the sensible option for a beginner so I 
downloaded the dub executable and put it in the same directory 
as my source file 'test.d'.


As per the example at the above url, I created a dub.json file 
in the same directory with contents as so:


dependencies: {
derelict-sdl2:~1.0.0,
derelict-gl3:~master,
}

If I have the relevant import statements in test.d, am I right 
in thinking I can use dub to build my program (not just 
download and build the derelict libraries)? The command dub 
build test.d gives me a 'failed to load package' error.


I'm using 32 bit Linux.

Any help appreciated :D

Paul



Dub will download and build the D packages from code.dlang.org.

However, some D packages require you to download compiled
libraries they link to for your syste. (or build them yourself
from source)

For sdl2 on linux, you need to go to:
https://www.libsdl.org/download-2.0.php and download the source.
Compile those libs using ($ ./configure; make; make install;)
Put them into a place your linker can find (usually /usr/lib/
iirc).

I believe that should work for you!


Re: Dub / Derelict confusion

2014-11-19 Thread wobbles via Digitalmars-d-learn

Put them into a place your linker can find (usually /usr/lib/
iirc).


I forgot, I'm pretty sure make install does that step for you.