Re: randomIO, std.file, core.stdc.stdio

2016-07-26 Thread Charles Hixson via Digitalmars-d-learn

On 07/26/2016 12:53 PM, Adam D. Ruppe via Digitalmars-d-learn wrote:

On Tuesday, 26 July 2016 at 19:30:35 UTC, Charles Hixson wrote:
It looks as if the entire file is stored in memory, which is not at 
all what I want, but I also can't really believe that's what's going on.



It is just mapped to virtual memory without actually being loaded into 
physical memory, so when you access the array it returns, the kernel 
loads a page of the file into memory, but it doesn't do that until it 
actually has to.


Think of it as being like this:

struct MagicFile {
ubyte[] opIndex(size_t idx) {
  auto buffer = new ubyte[](some_block_length);
  fseek(fp, idx, SEEK_SET);
  fread(buffer.ptr, buffer.length, 1);
  return buffer;
}
}


And something analogous for writing, but instead of being done with 
overloaded operators in D, it is done with the MMU hardware by the 
kernel (and the kernel also does smarter buffering than this little 
example).



A part of the problem is that I don't want this to be a process with 
an arbitrarily high memory use.


The kernel will automatically handle physical memory usage too, 
similarly to a page file. If you haven't read a portion of the file 
recently, it will discard that page, since it can always read it again 
off disk if needed, but if you do have memory to spare, it will keep 
the data in memory for faster access later.



So basically the operating system handles a lot of the details which 
makes it efficient.



Growing a memory mapped file is a bit tricky though, you need to unmap 
and remap. Since it is an OS concept, you can always look for C or C++ 
examples too, like herE: 
http://stackoverflow.com/questions/4460507/appending-to-a-memory-mapped-file/4461462#4461462
O, dear.  It was sounding like such an excellent approach until this 
last paragraph, but growing the file is going to be one of the common 
operations.  (Certainly at first.)  It sounds as if that means the file 
needs to be closed and re-opened for extensions.  And I quote from 
https://www.gnu.org/software/libc/manual/html_node/Memory_002dmapped-I_002fO.html: 
Function: /void */ *mremap* /(void *address, size_t length, size_t 
new_length, int flag)/


   Preliminary: | MT-Safe | AS-Safe | AC-Safe | See POSIX Safety
   Concepts
   
.


   This function can be used to change the size of an existing memory
   area. address and length must cover a region entirely mapped in the
   same |mmap| statement. A new mapping with the same characteristics
   will be returned with the length new_length.

...
This function is only available on a few systems. Except for performing 
optional optimizations one should not rely on this function.


END
So I'm probably better off sticking to using a seek based i/o system.


Re: Remove stuff from a template mixin

2016-07-26 Thread Gorge Jingale via Digitalmars-d-learn

On Tuesday, 26 July 2016 at 22:23:37 UTC, Jerry wrote:

On Tuesday, 26 July 2016 at 19:02:32 UTC, Gorge Jingale wrote:
I might want to actually use Add internally in B so I can add 
some elements behind the scenes, I do not want to expose it to 
the outside world though.


There are no way to remove things from an template directly. 
But you could however generate a new type which does not carry 
the specified members.


This requires two steps:
*The member filtering part
*Generation part

For the masking part take a look at
https://forum.dlang.org/post/nn8gj8$6s5$1...@digitalmars.com

What you basicly do is that you iterate the members and based 
on some condition filters out the members you don't want.


Then for generating you have to handle functions and fields.
For fields a string concatenated with other strings fields is 
probably good enough.

Something like this:
 "typeof(" ~ fullyQualifiedName!Aggregate ~ "." ~ 
memberName ~ ") " ~ member;"


That seems like a lot of work just to remove some elements. 
Creating a whole new template. I think using additive composition 
would be easier and more directly(a few lines of code to split 
the template), and I guess is the more natural way.


Re: Why D isn't the next "big thing" already

2016-07-26 Thread Gorge Jingale via Digitalmars-d-learn

On Tuesday, 26 July 2016 at 15:11:00 UTC, llaine wrote:

Hi guys,

I'm using D since a few month now and I was wondering why 
people don't jump onto it that much and why it isn't the "big 
thing" already.


Everybody is into javascript nowadays, but IMO even for doing 
web I found Vibe.d more interesting and efficient than node.js 
for example.


I agree that you have to be pragmatic and choose the right 
tools for the right jobs but I would be interested to have 
other opinion on thoses questions.


I think it is because D has some fundamental problems. It is a 
risk to use software that is not proven to be safe, effective, 
and easy to use. The fact there are so many bugs(and many are big 
blockes) in D says something about D, it matters not how fast 
they are fixed.


It forces you in to a certain mold. All that power it has is 
attractive, but much of it is hot air if you can't get it off the 
ground in any serious professional way.  The larger the project 
one works on the more likely one will run in to bugs, the more 
complex the language is the slower it understand the problems, 
and the more limited tools one has, the slower it is.


So, D has many things going against it compared with well 
establish languages.  Because businesses care about the $$$, it 
matters what they use. D covers a lot more ground than almost any 
other compiler out their but it doesn't cover any of it will 
except in a few cases(the things that make it attractive). So, 
you can see D as a sort of dried up waste land desert with a few 
nice palm trees growing here and there and a few scorpions. C++, 
say, is a very lush forest with many tree dwelling monkeys. Which 
environment would you rather use? Sure, there is potential in the 
desert, it has nice hot sand, so if you like that, you'll be in 
paradise... also if you like palm trees(and most people in the D 
forum like palm trees... or scorpions, they can be a tasty treat 
every now and then).


Ok, maybe a bit exaggerated, but point is most people don't like 
the desert and D is like a desert, but not as extreme. To 
actually prove why would require about 158 MIT students, a 10M$ 
grant, and a time machine. Do you have any of that?







Re: randomIO, std.file, core.stdc.stdio

2016-07-26 Thread ketmar via Digitalmars-d-learn

On Tuesday, 26 July 2016 at 16:35:26 UTC, Charles Hixson wrote:
That's sort of what I have in mind, but I want to do what in 
Fortran would be (would have been?) called record I/O, except 
that I want a file header that specifies a few things like 
magic number, records allocated, head of free list, etc.  In 
practice I don't see any need for record size not known at 
compile time...except that if there are different
versions of the program, they might include different things, 
so, e.g., the size of the file header might need to be variable.


it looks like you want a serialization library. there are some: 
http://wiki.dlang.org/Serialization_Libraries


Re: Why D isn't the next "big thing" already

2016-07-26 Thread tsbockman via Digitalmars-d-learn

On Tuesday, 26 July 2016 at 15:11:00 UTC, llaine wrote:
I'm using D since a few month now and I was wondering why 
people don't jump onto it that much and why it isn't the "big 
thing" already.


D2 is under active development. Bugs get fixed, bottlenecks get 
optimized, and features get added or improved constantly.


These changes don't usually seem like a big deal from one release 
to the next, but they add up quickly. Compared to what we have 
now, D2 was (in my opinion) unfinished junk a few years ago. The 
quality has improved a lot since then, but it will take time for 
the bad taste left in many people's mouthes by the unstable, 
incomplete early builds to be forgotten.


This is a common problem for open source projects: the dev team 
is naturally more enthusiastic about the project than others, and 
also feels pressure to market it in order to attract testers, 
contributors, and donors. The result is that the product is 
declared "ready" before it really is by the standards of 
outsiders. People get fooled by the hype, try a half-baked build, 
and sour on the project.


As long as the dev team continues to solve D2's problems faster 
than they're adding new ones, I expect that adoption will 
continue to increase.


Re: Remove stuff from a template mixin

2016-07-26 Thread Jerry via Digitalmars-d-learn

On Tuesday, 26 July 2016 at 19:02:32 UTC, Gorge Jingale wrote:
I might want to actually use Add internally in B so I can add 
some elements behind the scenes, I do not want to expose it to 
the outside world though.


There are no way to remove things from an template directly. But 
you could however generate a new type which does not carry the 
specified members.


This requires two steps:
*The member filtering part
*Generation part

For the masking part take a look at
https://forum.dlang.org/post/nn8gj8$6s5$1...@digitalmars.com

What you basicly do is that you iterate the members and based on 
some condition filters out the members you don't want.


Then for generating you have to handle functions and fields.
For fields a string concatenated with other strings fields is 
probably good enough.

Something like this:
 "typeof(" ~ fullyQualifiedName!Aggregate ~ "." ~ memberName 
~ ") " ~ member;"





Re: Search elemnt in Compile-time Argument List of strings

2016-07-26 Thread Steven Schveighoffer via Digitalmars-d-learn

On 7/26/16 4:58 PM, ParticlePeter wrote:

On Tuesday, 26 July 2016 at 20:18:48 UTC, Steven Schveighoffer wrote:


void processMember( T, ignore... )() {
  foreach( member; __traits( allMembers, T )) { // this is a
compile-time list, so it's a static foreach.
foreach(i, arg; ignore ){ // i is the index into the ignore tuple
  static if( arg == member ) break; // break out of the foreach
loop, need to ignore it.
  else static if(i + 1 == arg.length) // this is the last element!
  {
  // process member here, generate e.g. setter function as string
mixin
  }
}
  }
}


There is one problem with this approach, ignore might be empty (I should
have mentioned it). Would you know a workaround for that case as well?


Hm... good point :)

Here is a workaround:

foreach(i, arg; AliasSeq!(ignore, "SENTINEL"))
   static if(i == ignore.length)
   {
  // process, it's good
   }
   else static if(arg == member) break;

-Steve


Re: Search elemnt in Compile-time Argument List of strings

2016-07-26 Thread ParticlePeter via Digitalmars-d-learn

On Tuesday, 26 July 2016 at 21:20:18 UTC, ParticlePeter wrote:
...

First of all there seems to be a typo, it should not be:
  else static if(i + 1 == arg.length)

ignore must be used instead of arg, as arg.length is the length 
of a string:

  else static if(i + 1 == ignore.length)

if ignore is empty, its length is 0, so that the statement 
would always evaluate to false.


Btw, if ignore is not empty, only the last element (arg) is 
skipped.



Test:
void processMember( T, ignore... )() {
  foreach( member; __traits( allMembers, T )) {
foreach( i, arg; ignore ) { // i is the index into the ignore 
tuple
  static if( arg == member ) break; // break out of the 
foreach loop, ...
  else static if( i + 1 == ignore.length ) { // this is the 
last element!

pragma( msg, "processing ", member );
  }
}
  }
}

struct Foo { float a, b, c, d; }

int main() {
  processMember!( Foo );// nada
  processMember!( Foo, "c" );   // works
  processMember!( Foo, "c", "b" );  // skips only b
}





Re: Search elemnt in Compile-time Argument List of strings

2016-07-26 Thread ParticlePeter via Digitalmars-d-learn

On Tuesday, 26 July 2016 at 21:01:19 UTC, Ali Çehreli wrote:

On 07/26/2016 01:58 PM, ParticlePeter wrote:
On Tuesday, 26 July 2016 at 20:18:48 UTC, Steven Schveighoffer 
wrote:

...

void processMember( T, ignore... )() {
  foreach( member; __traits( allMembers, T )) { // this is a
compile-time list, so it's a static foreach.
foreach(i, arg; ignore ){ // i is the index into the 
ignore tuple
  static if( arg == member ) break; // break out of the 
foreach

loop, need to ignore it.
  else static if(i + 1 == arg.length) // this is the last 
element!

  {
  // process member here, generate e.g. setter function 
as string

mixin
  }
}
  }
}


There is one problem with this approach, ignore might be empty 
(I should
have mentioned it). Would you know a workaround for that case 
as well?


It should work for empty ignore. Can you show with a short 
example please.


Ali


First of all there seems to be a typo, it should not be:
  else static if(i + 1 == arg.length)

ignore must be used instead of arg, as arg.length is the length 
of a string:

  else static if(i + 1 == ignore.length)

if ignore is empty, its length is 0, so that the statement would 
always evaluate to false.


Btw, if ignore is not empty, only the last element (arg) is 
skipped.




Re: Why D isn't the next "big thing" already

2016-07-26 Thread phant0m via Digitalmars-d-learn

On Tuesday, 26 July 2016 at 15:11:00 UTC, llaine wrote:

Hi guys,

I'm using D since a few month now and I was wondering why 
people don't jump onto it that much and why it isn't the "big 
thing" already.


Everybody is into javascript nowadays, but IMO even for doing 
web I found Vibe.d more interesting and efficient than node.js 
for example.


I agree that you have to be pragmatic and choose the right 
tools for the right jobs but I would be interested to have 
other opinion on thoses questions.


As far as I know, most of the people wait when D will be used by 
big companies for big projects. It's the chicken-egg problem. 
Personally, I found that D improves my productivity a lot 
(comparing to C++). I gave up on opinions of other people and use 
what is convenient for me in my own projects. But not everybody 
such "brave".


Re: Search elemnt in Compile-time Argument List of strings

2016-07-26 Thread Ali Çehreli via Digitalmars-d-learn

On 07/26/2016 01:58 PM, ParticlePeter wrote:

On Tuesday, 26 July 2016 at 20:18:48 UTC, Steven Schveighoffer wrote:
...

void processMember( T, ignore... )() {
  foreach( member; __traits( allMembers, T )) { // this is a
compile-time list, so it's a static foreach.
foreach(i, arg; ignore ){ // i is the index into the ignore tuple
  static if( arg == member ) break; // break out of the foreach
loop, need to ignore it.
  else static if(i + 1 == arg.length) // this is the last element!
  {
  // process member here, generate e.g. setter function as string
mixin
  }
}
  }
}


There is one problem with this approach, ignore might be empty (I should
have mentioned it). Would you know a workaround for that case as well?


It should work for empty ignore. Can you show with a short example please.

Ali



Re: Search elemnt in Compile-time Argument List of strings

2016-07-26 Thread ParticlePeter via Digitalmars-d-learn
On Tuesday, 26 July 2016 at 20:18:48 UTC, Steven Schveighoffer 
wrote:

...

void processMember( T, ignore... )() {
  foreach( member; __traits( allMembers, T )) { // this is a 
compile-time list, so it's a static foreach.
foreach(i, arg; ignore ){ // i is the index into the ignore 
tuple
  static if( arg == member ) break; // break out of the 
foreach loop, need to ignore it.
  else static if(i + 1 == arg.length) // this is the last 
element!

  {
  // process member here, generate e.g. setter function as 
string mixin

  }
}
  }
}


There is one problem with this approach, ignore might be empty (I 
should have mentioned it). Would you know a workaround for that 
case as well?


Re: Search elemnt in Compile-time Argument List of strings

2016-07-26 Thread ParticlePeter via Digitalmars-d-learn
On Tuesday, 26 July 2016 at 20:18:48 UTC, Steven Schveighoffer 
wrote:

...
Thanks a lot for this really cool and detailed explanation 
(upvoting!).


It's a bit weird to work on these compile-time things, but they 
are so cool when you look at what is available in std.meta and 
std.traits :)


Agreed with each aspect. When I (just) read Philippe Sigaud's D 
Templates Tutorial I didn't get a thing. Important thing is 
getting your hands dirty, then it comes slowly.


















Re: Check of point inside/outside polygon

2016-07-26 Thread Gorge Jingale via Digitalmars-d-learn

On Tuesday, 26 July 2016 at 19:08:09 UTC, H. S. Teoh wrote:
On Tue, Jul 26, 2016 at 06:39:58PM +, Gorge Jingale via 
Digitalmars-d-learn wrote:

On Tuesday, 26 July 2016 at 17:38:43 UTC, Suliman wrote:
> I have arbitrary polygon. I need any solution. Performance 
> is does not matter at current moment.


A polygon is made up of lines. For a point to be inside a 
convex polygon, it must be to the "right" of all the lines 
with clockwise orientation.

[...]

Unfortunately he wants to handle arbitrary polygons that are 
not necessarily convex.



T


The example was for convex, the method using intersections was 
for general polygons that do not have self-intersections. Convex 
polygons have 0 intersection numbers.






Re: Search elemnt in Compile-time Argument List of strings

2016-07-26 Thread Steven Schveighoffer via Digitalmars-d-learn

On 7/26/16 3:30 PM, ParticlePeter wrote:

I want to generate one function for any struct data member, but also
want to be able to skip few of the members. The first part works, but I
have some trouble with the skipping.

I pass the struct type and a Compile-time Argument List of strings as
template arguments to a template function, list all members of the
struct and compare each member to each element of the List. If the
member is in the List skip processing of that member. Pretty straight
forward ... should be.

// First approach doesn't work:
// Error: variable skip cannot be read at compile time
void processMember( T, ignore... )() {
  foreach( member; __traits( allMembers, T )) {
bool skip = false;
foreach( arg; ignore )
  skip = skip || ( arg == member );

static if( !skip ) {
  // process member here, generate e.g. setter function as string mixin
}
  }
}

// Second approach, get warnings for every skipped member
// and every line after the return statement:
// Warning: statement is not reachable
void processMember( T, ignore... )() {
  foreach( member; __traits( allMembers, T )) {
foreach( arg; ignore )
  static if( arg == member )
return;
// process member here, generate e.g. setter function as string mixin
  }
}

So how can I achieve my goal the right way?


You are doing it *almost* right.

What you need to remember is what is compile time, and what is runtime. 
In order to declare something is readable at compile-time, you need to 
have an expression that only involves compile-time constants. This means 
you need to process *all* the ignore's at once, or process the "end of 
the loop" after you haven't found it. Here is one way to do it:



void processMember( T, ignore... )() {
  foreach( member; __traits( allMembers, T )) { // this is a 
compile-time list, so it's a static foreach.

foreach(i, arg; ignore ){ // i is the index into the ignore tuple
  static if( arg == member ) break; // break out of the foreach 
loop, need to ignore it.

  else static if(i + 1 == arg.length) // this is the last element!
  {
  // process member here, generate e.g. setter function as string mixin
  }
}
  }
}

Another way is to use std.meta.anySatisfy 
(http://dlang.org/phobos/std_meta.html#.anySatisfy), which can apply a 
template to each element in a compile-time list to see if any match:


template skipper(string target)
{
   enum shouldSkip(string s) = (s == target);
}

// replace your bool skip = ... with this:
enum skip = anySatisfy!(skipper!(member).shouldSkip, ignore);

It's a bit weird to work on these compile-time things, but they are so 
cool when you look at what is available in std.meta and std.traits :)


-Steve


Re: randomIO, std.file, core.stdc.stdio

2016-07-26 Thread Steven Schveighoffer via Digitalmars-d-learn

On 7/26/16 3:30 PM, Charles Hixson via Digitalmars-d-learn wrote:

On 07/26/2016 11:31 AM, Steven Schveighoffer via Digitalmars-d-learn wrote:



Now, C i/o's buffering may not suit your exact needs. So I don't know
how it will perform. You may want to consider mmap which tells the
kernel to link pages of memory directly to disk access. Then the
kernel is doing all the buffering for you. Phobos has support for it,
but it's pretty minimal from what I can see:
http://dlang.org/phobos/std_mmfile.html


I've considered mmapfile often, but when I read the documentation I end
up realizing that I don't understand it.  So I look up memory mapped
files in other places, and I still don't understand it.  It looks as if
the entire file is stored in memory, which is not at all what I want,
but I also can't really believe that's what's going on.


Of course that isn't what is happening :)

What happens is that the kernel says memory page 0x12345 (or whatever) 
is mapped to the file. Then when you access a mapped page, the system 
memory management unit gets a page fault (because that memory isn't 
loaded), which triggers the kernel to load that page of memory. Kernel 
sees that the memory is really mapped to that file, and loads the page 
from the file instead. As you write to the memory location, the page is 
marked dirty, and at some point, the kernel flushes that page back to disk.


Everything is done behind the scenes and is in tune with the filesystem 
itself, so you get a little extra benefit from that.



I know that
there was an early form of this in a version of BASIC (the version that
RISS was written in, but I don't remember which version that was) and in
*that* version array elements were read in as needed.  (It wasn't
spectacularly efficient.)  But memory mapped files don't seem to work
that way, because people keep talking about how efficient they are.  Do
you know a good introductory tutorial?  I'm guessing that "window size"
might refer to the number of bytes available, but what if you need to
append to the file?  Etc.


To be honest, I'm not super familiar with actually using them, I just 
have a rough idea of how they work. The actual usage you will have to 
look up.



A part of the problem is that I don't want this to be a process with an
arbitrarily high memory use.


You should know that you can allocate as much memory as you want, as 
long as you have address space for it, and you won't actually map that 
to physical memory until you use it. So the management of the memory is 
done lazily, all supported by the MMU hardware. This is true for actual 
memory too!


Note that the only "memory" you are using for the mmaped file are page 
buffers in the kernel which are likely already being used to buffer the 
disk reads. It's not like it's loading the entire file into memory, and 
probably doesn't even load all sequential pages into memory. It only 
loads the ones you use.


I'm pretty much at my limit for knowledge of this subject (and maybe I 
have a few things incorrect), I'm sure others here know much more. I 
suggest you play a bit with it to see what the performance is like. I 
have also heard that it's very fast.


-Steve


Re: randomIO, std.file, core.stdc.stdio

2016-07-26 Thread Adam D. Ruppe via Digitalmars-d-learn

On Tuesday, 26 July 2016 at 19:30:35 UTC, Charles Hixson wrote:
It looks as if the entire file is stored in memory, which is 
not at all what I want, but I also can't really believe that's 
what's going on.



It is just mapped to virtual memory without actually being loaded 
into physical memory, so when you access the array it returns, 
the kernel loads a page of the file into memory, but it doesn't 
do that until it actually has to.


Think of it as being like this:

struct MagicFile {
ubyte[] opIndex(size_t idx) {
  auto buffer = new ubyte[](some_block_length);
  fseek(fp, idx, SEEK_SET);
  fread(buffer.ptr, buffer.length, 1);
  return buffer;
}
}


And something analogous for writing, but instead of being done 
with overloaded operators in D, it is done with the MMU hardware 
by the kernel (and the kernel also does smarter buffering than 
this little example).



A part of the problem is that I don't want this to be a process 
with an arbitrarily high memory use.


The kernel will automatically handle physical memory usage too, 
similarly to a page file. If you haven't read a portion of the 
file recently, it will discard that page, since it can always 
read it again off disk if needed, but if you do have memory to 
spare, it will keep the data in memory for faster access later.



So basically the operating system handles a lot of the details 
which makes it efficient.



Growing a memory mapped file is a bit tricky though, you need to 
unmap and remap. Since it is an OS concept, you can always look 
for C or C++ examples too, like herE: 
http://stackoverflow.com/questions/4460507/appending-to-a-memory-mapped-file/4461462#4461462


Re: Search elemnt in Compile-time Argument List of strings

2016-07-26 Thread ParticlePeter via Digitalmars-d-learn

On Tuesday, 26 July 2016 at 19:30:18 UTC, ParticlePeter wrote:

// Second approach, get warnings for every skipped member
// and every line after the return statement:
// Warning: statement is not reachable
void processMember( T, ignore... )() {
  foreach( member; __traits( allMembers, T )) {
foreach( arg; ignore )
  static if( arg == member )
return;
// process member here, generate e.g. setter function as 
string mixin

  }
}

So how can I achieve my goal the right way?


I just realized that the second approach, despite the warnings, 
does not achieve its goal. The members are still forwarded. So I 
should rather ask how I could filter the members at all.


Search elemnt in Compile-time Argument List of strings

2016-07-26 Thread ParticlePeter via Digitalmars-d-learn
I want to generate one function for any struct data member, but 
also want to be able to skip few of the members. The first part 
works, but I have some trouble with the skipping.


I pass the struct type and a Compile-time Argument List of 
strings as template arguments to a template function, list all 
members of the struct and compare each member to each element of 
the List. If the member is in the List skip processing of that 
member. Pretty straight forward ... should be.


// First approach doesn't work:
// Error: variable skip cannot be read at compile time
void processMember( T, ignore... )() {
  foreach( member; __traits( allMembers, T )) {
bool skip = false;
foreach( arg; ignore )
  skip = skip || ( arg == member );

static if( !skip ) {
  // process member here, generate e.g. setter function as 
string mixin

}
  }
}

// Second approach, get warnings for every skipped member
// and every line after the return statement:
// Warning: statement is not reachable
void processMember( T, ignore... )() {
  foreach( member; __traits( allMembers, T )) {
foreach( arg; ignore )
  static if( arg == member )
return;
// process member here, generate e.g. setter function as 
string mixin

  }
}

So how can I achieve my goal the right way?


Re: randomIO, std.file, core.stdc.stdio

2016-07-26 Thread Charles Hixson via Digitalmars-d-learn

On 07/26/2016 11:31 AM, Steven Schveighoffer via Digitalmars-d-learn wrote:

On 7/26/16 1:57 PM, Charles Hixson via Digitalmars-d-learn wrote:


Thanks.  Since there isn't any excess overhead I guess I'll use stdio.
Buffering, however, isn't going to help at all since I'm doing
randomIO.  I know that most of the data the system reads from disk is
going to end up getting thrown away, since my records will generally be
smaller than 8K, but there's no help for that.



Even for doing random I/O buffering is helpful. It depends on the size 
of your items.


Essentially, to read 10 bytes from a file probably costs the same as 
reading 100,000 bytes from a file. So may as well buffer that in case 
you need it.


Now, C i/o's buffering may not suit your exact needs. So I don't know 
how it will perform. You may want to consider mmap which tells the 
kernel to link pages of memory directly to disk access. Then the 
kernel is doing all the buffering for you. Phobos has support for it, 
but it's pretty minimal from what I can see: 
http://dlang.org/phobos/std_mmfile.html


-Steve
I've considered mmapfile often, but when I read the documentation I end 
up realizing that I don't understand it.  So I look up memory mapped 
files in other places, and I still don't understand it.  It looks as if 
the entire file is stored in memory, which is not at all what I want, 
but I also can't really believe that's what's going on.  I know that 
there was an early form of this in a version of BASIC (the version that 
RISS was written in, but I don't remember which version that was) and in 
*that* version array elements were read in as needed.  (It wasn't 
spectacularly efficient.)  But memory mapped files don't seem to work 
that way, because people keep talking about how efficient they are.  Do 
you know a good introductory tutorial?  I'm guessing that "window size" 
might refer to the number of bytes available, but what if you need to 
append to the file?  Etc.


A part of the problem is that I don't want this to be a process with an 
arbitrarily high memory use.  Buffering would be fine, if I could use 
it, but for my purposes sequential access is likely to be rare, and the 
working layout of the data in RAM doesn't (can't reasonably) match the 
layout on disk.  IIUC (this is a few decades old) the system buffer size 
is about 8K.  I expect to never need to read that large a chunk, but I'm 
going to try to keep the chunks in multiples of 1024 bytes, and if it's 
reasonable to exactly 1024 bytes.  So I should never need two reads or 
writes for a chunk.  I guess to be sure of this I'd better make sure the 
file header is also 1024 bytes.  (I'm guessing that the seek to position 
results in the appropriate buffer being read into the system buffer, so 
if my header were 512 bytes I might occasionally need to do double reads 
or writes.)


I'm guessing that memory mapped files trade off memory use against speed 
of access, and for my purposes that's probably a bad trade, even though 
databases are doing that more and more.  I'm likely to need all the 
memory I can lay my hands on, and even then thrashing wouldn't surprise 
me.  So a fixed buffer size seems a huge advantage.


Re: Check of point inside/outside polygon

2016-07-26 Thread H. S. Teoh via Digitalmars-d-learn
On Tue, Jul 26, 2016 at 06:39:58PM +, Gorge Jingale via Digitalmars-d-learn 
wrote:
> On Tuesday, 26 July 2016 at 17:38:43 UTC, Suliman wrote:
> > I have arbitrary polygon. I need any solution. Performance is does not
> > matter at current moment.
> 
> A polygon is made up of lines. For a point to be inside a convex polygon, it
> must be to the "right" of all the lines with clockwise orientation.
[...]

Unfortunately he wants to handle arbitrary polygons that are not
necessarily convex.


T

-- 
Be in denial for long enough, and one day you'll deny yourself of things you 
wish you hadn't.


Re: Remove stuff from a template mixin

2016-07-26 Thread Gorge Jingale via Digitalmars-d-learn
I might want to actually use Add internally in B so I can add 
some elements behind the scenes, I do not want to expose it to 
the outside world though.





Remove stuff from a template mixin

2016-07-26 Thread Gorge Jingale via Digitalmars-d-learn
Is there a way to remove functions and fields that a mixin 
template adds?


I use mixin templates to create other types contents, like

struct A { mixin Stuff(); }

But Sometimes I only want some of the stuff.

struct B { mixin Stuff(); @disable Add(); }

B is like an A but doesn't have the ability to add.

While I could do something like move the Add function to another 
template, it gets messy quickly because all I want to do is 
remove a feature, not create a hierarchical system like oop.


I tried making add private, but b.Add() still calls Stuff.Add.



Re: Check of point inside/outside polygon

2016-07-26 Thread Gorge Jingale via Digitalmars-d-learn

On Tuesday, 26 July 2016 at 17:38:43 UTC, Suliman wrote:
I have arbitrary polygon. I need any solution. Performance is 
does not matter at current moment.


A polygon is made up of lines. For a point to be inside a convex 
polygon, it must be to the "right" of all the lines with 
clockwise orientation.


One way for this to work is simply draw a line segment from each 
vertex to the point and compare it to the number of intersections 
with other lines. The number of intersections must be odd for it 
to be inside the polygon. Think of a regular polygon, any point 
inside will have no other line segments between it and the point. 
All intersection values will be 0.


So, for each n vertices we have n line segments, we must the find 
the number of intersection points for the other n-1 line 
segments. This reduces the problem to line segment intersection 
but is of the order O(n^2), but works in general.






Re: randomIO, std.file, core.stdc.stdio

2016-07-26 Thread Steven Schveighoffer via Digitalmars-d-learn

On 7/26/16 1:57 PM, Charles Hixson via Digitalmars-d-learn wrote:


Thanks.  Since there isn't any excess overhead I guess I'll use stdio.
Buffering, however, isn't going to help at all since I'm doing
randomIO.  I know that most of the data the system reads from disk is
going to end up getting thrown away, since my records will generally be
smaller than 8K, but there's no help for that.



Even for doing random I/O buffering is helpful. It depends on the size 
of your items.


Essentially, to read 10 bytes from a file probably costs the same as 
reading 100,000 bytes from a file. So may as well buffer that in case 
you need it.


Now, C i/o's buffering may not suit your exact needs. So I don't know 
how it will perform. You may want to consider mmap which tells the 
kernel to link pages of memory directly to disk access. Then the kernel 
is doing all the buffering for you. Phobos has support for it, but it's 
pretty minimal from what I can see: http://dlang.org/phobos/std_mmfile.html


-Steve


Re: Check of point inside/outside polygon

2016-07-26 Thread H. S. Teoh via Digitalmars-d-learn
On Tue, Jul 26, 2016 at 05:38:43PM +, Suliman via Digitalmars-d-learn wrote:
> I have arbitrary polygon. I need any solution. Performance is does not
> matter at current moment.

In that case, maybe you'd want to look at:

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

Note, however, that this only works in 2D, and doesn't generalize to
higher dimensional shapes.


T

-- 
Let X be the set not defined by this sentence...


Re: randomIO, std.file, core.stdc.stdio

2016-07-26 Thread Charles Hixson via Digitalmars-d-learn



On 07/26/2016 10:18 AM, Steven Schveighoffer via Digitalmars-d-learn wrote:

On 7/26/16 12:58 PM, Charles Hixson via Digitalmars-d-learn wrote:


Ranges aren't free, are they? If so then I should probably use stdfile,
because that is probably less likely to change than core.stdc.stdio.


Do you mean slices?


When I see "f.rawRead([0 .. 1])" it looks to me as if unneeded code
is being generated explictly to be thrown away.  (I don't like using
pointer/length either, but it's actually easier to understand than this
kind of thing, and this LOOKS like it's generating extra code.)


This is probably a misunderstanding on your part.

 is accessing the item as a pointer. Since the compiler already 
has it as a reference, this is a noop -- just an expression to change 
the type.


[0 .. 1] is constructing a slice out of a pointer. It's done all 
inline by the compiler (there is no special _d_constructSlice 
function), so that is very very quick. There is no bounds checking, 
because pointers do not have bounds checks.


So there is pretty much zero overhead for this. Just push the pointer 
and length onto the stack (or registers, not sure of ABI), and call 
rawRead.



That said, perhaps I should use stdio anyway.  When doing I/O it's the
disk speed that's the really slow part, and that so dominates things
that worrying about trivialities is foolish.  And since it's going to be
wrapped anyway, the ugly will be confined to a very small routine.


Having written a very templated io library 
(https://github.com/schveiguy/iopipe), I can tell you that in my 
experience, the slowdown comes from 2 things: 1) spending time calling 
the kernel, and 2) not being able to inline.


This of course assumes that proper buffering is done. Buffering should 
mitigate most of the slowdown from the disk. It is expensive, but you 
amortize the expense by buffering.


C's i/o is pretty much as good as it gets for an opaque non-inlinable 
system, as long as your requirements are simple enough. The std.stdio 
code should basically inline into the calls you should be making, and 
it handles a bunch of stuff that optimizes the calls (such as locking 
the file handle for one complex operation).


-Steve
Thanks.  Since there isn't any excess overhead I guess I'll use stdio.  
Buffering, however, isn't going to help at all since I'm doing 
randomIO.  I know that most of the data the system reads from disk is 
going to end up getting thrown away, since my records will generally be 
smaller than 8K, but there's no help for that.




Re: Check of point inside/outside polygon

2016-07-26 Thread Suliman via Digitalmars-d-learn
I have arbitrary polygon. I need any solution. Performance is 
does not matter at current moment.


Re: randomIO, std.file, core.stdc.stdio

2016-07-26 Thread Steven Schveighoffer via Digitalmars-d-learn

On 7/26/16 12:58 PM, Charles Hixson via Digitalmars-d-learn wrote:


Ranges aren't free, are they? If so then I should probably use stdfile,
because that is probably less likely to change than core.stdc.stdio.


Do you mean slices?


When I see "f.rawRead([0 .. 1])" it looks to me as if unneeded code
is being generated explictly to be thrown away.  (I don't like using
pointer/length either, but it's actually easier to understand than this
kind of thing, and this LOOKS like it's generating extra code.)


This is probably a misunderstanding on your part.

 is accessing the item as a pointer. Since the compiler already has 
it as a reference, this is a noop -- just an expression to change the type.


[0 .. 1] is constructing a slice out of a pointer. It's done all inline 
by the compiler (there is no special _d_constructSlice function), so 
that is very very quick. There is no bounds checking, because pointers 
do not have bounds checks.


So there is pretty much zero overhead for this. Just push the pointer 
and length onto the stack (or registers, not sure of ABI), and call rawRead.



That said, perhaps I should use stdio anyway.  When doing I/O it's the
disk speed that's the really slow part, and that so dominates things
that worrying about trivialities is foolish.  And since it's going to be
wrapped anyway, the ugly will be confined to a very small routine.


Having written a very templated io library 
(https://github.com/schveiguy/iopipe), I can tell you that in my 
experience, the slowdown comes from 2 things: 1) spending time calling 
the kernel, and 2) not being able to inline.


This of course assumes that proper buffering is done. Buffering should 
mitigate most of the slowdown from the disk. It is expensive, but you 
amortize the expense by buffering.


C's i/o is pretty much as good as it gets for an opaque non-inlinable 
system, as long as your requirements are simple enough. The std.stdio 
code should basically inline into the calls you should be making, and it 
handles a bunch of stuff that optimizes the calls (such as locking the 
file handle for one complex operation).


-Steve


Re: question about conditional operator (?:)

2016-07-26 Thread Ali Çehreli via Digitalmars-d-learn

On 07/26/2016 06:41 AM, Richard wrote:


From http://wiki.dlang.org/Operator_precedence


In case it's useful to others, I explain that table a little bit here 
(associativity, unordered operators, and the precedence of =>):


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

Ali



Re: randomIO, std.file, core.stdc.stdio

2016-07-26 Thread Charles Hixson via Digitalmars-d-learn

On 07/26/2016 05:31 AM, Steven Schveighoffer via Digitalmars-d-learn wrote:

On 7/25/16 9:19 PM, Charles Hixson via Digitalmars-d-learn wrote:

On 07/25/2016 05:18 PM, ketmar via Digitalmars-d-learn wrote:

On Monday, 25 July 2016 at 18:54:27 UTC, Charles Hixson wrote:

Are there reasons why one would use rawRead and rawWrite rather than
fread and fwrite when doiing binary random io?  What are the 
advantages?


In particular, if one is reading and writing structs rather than
arrays or ranges, are there any advantages?


yes: keeping API consistent. ;-)

for example, my stream i/o modules works with anything that has
`rawRead`/`rawWrite` methods, but don't bother to check for any other.

besides, `rawRead` is just looks cleaner, even with all `()[0..1])`
noise.

so, a question of style.


OK.  If it's just a question of "looking cleaner" and "style", then I
will prefer the core.stdc.stdio approach.  I find it's appearance
extremely much cleaner...except that that's understating things. I'll
probably wrap those routines in a struct to ensure things like files
being properly closed, and not have explicit pointers persisting over
large areas of code.


It's more than just that. Having a bounded array is safer than a 
pointer/length separated parameters. Literally, rawRead and rawWrite 
are inferred @safe, whereas fread and fwrite are not.


But D is so nice with UFCS, you don't have to live with APIs you don't 
like. Allow me to suggest adding a helper function to your code:


rawReadItem(T)(File f, ref T item) @trusted
{
   f.rawRead([0 .. 1]);
}

-Steve

That *does* make the syntax a lot nicer, and I understand the safety 
advantage of not using pointer/length separated parameters.  But I'm 
going to be wrapping the I/O anyway, and the external interface is going 
to be more like:

struct RF (T, long magic)
{

void read (size_t recNo, ref T val){...}
size_t read (ref T val){...}
...
}
where a sequential read returns the record number, or you specify the 
record number and get an indexedIO read.  So the length with be 
T.sizeof, and will be specified at the time the file is opened.  To me 
this seems to eliminate the advantage of stdfile, and stdfile seems to 
add a level of indirection.


Ranges aren't free, are they? If so then I should probably use stdfile, 
because that is probably less likely to change than core.stdc.stdio.  
When I see "f.rawRead([0 .. 1])" it looks to me as if unneeded code 
is being generated explictly to be thrown away.  (I don't like using 
pointer/length either, but it's actually easier to understand than this 
kind of thing, and this LOOKS like it's generating extra code.)


That said, perhaps I should use stdio anyway.  When doing I/O it's the 
disk speed that's the really slow part, and that so dominates things 
that worrying about trivialities is foolish.  And since it's going to be 
wrapped anyway, the ugly will be confined to a very small routine.


Re: Check of point inside/outside polygon

2016-07-26 Thread H. S. Teoh via Digitalmars-d-learn
On Tue, Jul 26, 2016 at 01:32:00PM +, Suliman via Digitalmars-d-learn wrote:
> Ideally I need algorithm that can return bool if one polygon
> overlapped/intersected by another. But I do not know math.

Are you talking about triangles, or general polygons?  Are the polygons
convex or arbitrary?  Depending on what kind of polygon it is, the
solution may be more or less complex.  If you're dealing with convex
polygons (including triangles -- though you can probably simplify things
a bit more for triangles), take a look at this:

http://www.iro.umontreal.ca/~plante/compGeom/algorithm.html

If your polygons are non-convex, the solution will be quite complicated
and may not have good performance. You might want to consider various
algorithms for decomposing such polygons into convex pieces for easier
handling.


> After some googling I found topic on SO[1] about point inside/outside
> polygon. It's not directly what I need, but as temporal solution would
> be enough.
[...]

This approach may not be as straightforward as you think.  Consider two
equilateral triangles inscribed inside a regular hexagon (i.e., "David's
Star", or the 6/3 star polygon).  Neither of the triangles's vertices
lie inside the other triangle, yet the two triangles do intersect each
other. You may say, test the centers of the polygons too, however, it's
easy to come up with other pairs of polygons where the respective
centers don't lie in the other polygon but the two polygons nevertheless
still intersect.  You need a general algorithm for finding the
intersection; point-sampling generally is not good enough.


T

-- 
Gone Chopin. Bach in a minuet.


Re: randomIO, std.file, core.stdc.stdio

2016-07-26 Thread Charles Hixson via Digitalmars-d-learn

On 07/25/2016 09:22 PM, ketmar via Digitalmars-d-learn wrote:

On Tuesday, 26 July 2016 at 04:05:22 UTC, Charles Hixson wrote:
Yes, but I really despise the syntax they came up with.  It's 
probably good if most of your I/O is ranges, but mine hasn't yet ever 
been.  (Combining ranges with random I/O?)


that's why i wrote iv.stream, and then iv.vfs, with convenient things 
like `readNum!T`, for example. you absolutely don't need to 
reimplement the whole std.stdio.File if all you need it better API. 
thanks to UFCS, you can write your new API as free functions accepting 
std.stdio.File as first arg. or even generic stream, like i did in 
iv.stream:



enum isReadableStream(T) = is(typeof((inout int=0) {
  auto t = T.init;
  ubyte[1] b;
  auto v = cast(void[])b;
  t.rawRead(v);
}));

enum isWriteableStream(T) = is(typeof((inout int=0) {
  auto t = T.init;
  ubyte[1] b;
  t.rawWrite(cast(void[])b);
}));

T readInt(T : ulong, ST) (auto ref ST st) if (isReadableStream!ST) {
  T res;
  ubyte* b = cast(ubyte*)
  foreach (immutable idx; 0..T.sizeof) {
if (st.rawRead(b[idx..idx+1]).length != 1) throw new 
Exception("read error");

  }
  return res;
}


and then:
  auto fl = File("myfile");
  auto i = fl.readInt!uint;

something like that.

That's sort of what I have in mind, but I want to do what in Fortran 
would be (would have been?) called record I/O, except that I want a file 
header that specifies a few things like magic number, records allocated, 
head of free list, etc.  In practice I don't see any need for record 
size not known at compile time...except that if there are different
versions of the program, they might include different things, so, e.g., 
the size of the file header might need to be variable.


This is a design problem I'm still trying to wrap my head around. 
Efficiency seems to say "you need to know the size at compile time", but 
flexibility says "you can't depend on the size at compile time".  The 
only compromise position seems to compromise safety (by depending on 
void * and record size parameters that aren't guaranteed safe).  I'll 
probably eventually decide in favor of "size fixed at compile time", but 
I'm still dithering.  But clearly efficiency dictates that the read size 
not be a basic type.  I'm currently thinking of a struct that's about 1 
KB in size.  As far as the I/O routines are concerned this will probably 
all be uninterpreted bytes, unless I throw in some sequencing for error 
recovery...but that's probably making things too complex, and should be 
left for a higher level.


Clearly this is a bit of a specialized case, so I wouldn't be 
considering implementing all of stdio, only the relevant bits, and those 
wrapped with an interpretation based around record number.


The thing is, I'd probably be writing this wrapper anyway, what I was 
wondering originally is whether there was any reason to use std.file as 
the underlying library rather than going directly to core.stdc.stdio.


Why D isn't the next "big thing" already

2016-07-26 Thread llaine via Digitalmars-d-learn

Hi guys,

I'm using D since a few month now and I was wondering why people 
don't jump onto it that much and why it isn't the "big thing" 
already.


Everybody is into javascript nowadays, but IMO even for doing web 
I found Vibe.d more interesting and efficient than node.js for 
example.


I agree that you have to be pragmatic and choose the right tools 
for the right jobs but I would be interested to have other 
opinion on thoses questions.








Re: question about conditional operator (?:)

2016-07-26 Thread Jonathan M Davis via Digitalmars-d-learn
On Tuesday, July 26, 2016 13:41:39 Richard via Digitalmars-d-learn wrote:
> On Tuesday, 26 July 2016 at 13:19:54 UTC, ag0aep6g wrote:
> > Operator precedence is different from what you think. `a ? b :
> > c = d` means `(a ? b : c) = d`. But you want `a ? b : (c = d)`.
> > So you need parentheses around `p+=1`.
> >
> > Or just go with `if` and `else`. It's clearer anyway.
>
>  From http://wiki.dlang.org/Operator_precedence
>
> Priority(15 is highest)
> 3  Conditional operator  ?:
> 2  Assignment operators= -= += <<= >>=
>
>  >>>= = *= %= ^= ^^= ~=
>
> I was actually close to not needing parentheses :). But I see
> that your suggestion to stick with if else in this case is the
> sensible thing to do, especially since ?: seems to lead to more
> errors. Thanks for the answers.

The ternary operator is invaluable for stuff like initializing a constant
based on boolean condition, and it can be useful in code in general, but I
think that most everyone would agree that you don't want to be doing
mutating operations inside of a ternary operator and that if/else statements
are far better suited to that - particularly since the ternary operator
results in a value, which is not at all what you're looking to do here.

That being said, it surprises me how often folks get confused by the
precedence of the ternary operator and start throwing parens around it. The
only reason that you'd need to here is becasue of the assignment operations,
which really shouldn't be used in a ternary expression anyway (except when
using the result of the whole expression as the value to assign).

- Jonathan M Davis



Re: question about conditional operator (?:)

2016-07-26 Thread Richard via Digitalmars-d-learn

On Tuesday, 26 July 2016 at 13:19:54 UTC, ag0aep6g wrote:
Operator precedence is different from what you think. `a ? b : 
c = d` means `(a ? b : c) = d`. But you want `a ? b : (c = d)`. 
So you need parentheses around `p+=1`.


Or just go with `if` and `else`. It's clearer anyway.


From http://wiki.dlang.org/Operator_precedence

Priority(15 is highest)
3  Conditional operator  ?: 
2  Assignment operators= -= += <<= >>= 
>>>= = *= %= ^= ^^= ~=


I was actually close to not needing parentheses :). But I see 
that your suggestion to stick with if else in this case is the 
sensible thing to do, especially since ?: seems to lead to more 
errors. Thanks for the answers.


Check of point inside/outside polygon

2016-07-26 Thread Suliman via Digitalmars-d-learn
Ideally I need algorithm that can return bool if one polygon 
overlapped/intersected by another. But I do not know math.


After some googling I found topic on SO[1] about point 
inside/outside polygon. It's not directly what I need, but as 
temporal solution would be enough.


Maybe somebody already wrote this algorithm in D. Could you share 
it plz.


I tried to translate algorithm in D, but I do not understand some 
things. For example:


public static bool PointInPolygon(LatLong p, List poly) 
// Ok we are getting `p` - looking point, and `poly` -- our 
polygon. But what format it should have? WKT? Something else?


poly.Add(new LatLong { Lat = poly[0].Lat, Lon = poly[0].Lon }); 
// Why we add Lat and Long to poly? And again what it's format?


All other code look work in D to.


[1] 
http://stackoverflow.com/questions/924171/geo-fencing-point-inside-outside-polygon/6786279#6786279





Re: question about conditional operator (?:)

2016-07-26 Thread ag0aep6g via Digitalmars-d-learn

On 07/26/2016 03:09 PM, Richard wrote:

if(n%p==0)
n/=p;
else
p+=1;

[...]

However, if I replace the content of the for loop with the ?: operator,
the program is not
correct anymore (largestPrimeFactor(4) now returns 3):

[...]

n%p==0 ? n/=p : p+=1 ;

[...]

What am I doing wrong here?


Operator precedence is different from what you think. `a ? b : c = d` 
means `(a ? b : c) = d`. But you want `a ? b : (c = d)`. So you need 
parentheses around `p+=1`.


Or just go with `if` and `else`. It's clearer anyway.


Re: question about conditional operator (?:)

2016-07-26 Thread Adam D. Ruppe via Digitalmars-d-learn

On Tuesday, 26 July 2016 at 13:17:27 UTC, Adam D. Ruppe wrote:

(n%p==0) ? n/=p : p+=1 ;



And actually, using ?: with /= and += is kinda bizarre.

I think you are better off leaving this as if/else since the 
point of this is the assignment rather than the return value.


Re: question about conditional operator (?:)

2016-07-26 Thread Adam D. Ruppe via Digitalmars-d-learn

On Tuesday, 26 July 2016 at 13:09:28 UTC, Richard wrote:

n%p==0 ? n/=p : p+=1 ;



Try

(n%p==0) ? n/=p : p+=1 ;


I'm pretty sure the order of operations (precedence rules) puts 
?: above ==.


Re: question about conditional operator (?:)

2016-07-26 Thread Cauterite via Digitalmars-d-learn

On Tuesday, 26 July 2016 at 13:09:28 UTC, Richard wrote:

Hello all,


try using some parentheses:
(n%p==0) ? (n/=p) : (p+=1) ;


question about conditional operator (?:)

2016-07-26 Thread Richard via Digitalmars-d-learn

Hello all,

I've got a program that correctly computes the largest factor in 
the prime decomposition of a positive number:


*
import std.math std.stdio;

ulong largestPrimeFactor(ulong n) {
for(ulong p=2; p<=sqrt(cast(real)n); ) {
if(n%p==0)
n/=p;
else
p+=1;
}
return n;
}

void main() {
writeln(largestPrimeFactor(4));
}
*

However, if I replace the content of the for loop with the ?: 
operator, the program is not

correct anymore (largestPrimeFactor(4) now returns 3):

*
import std.math std.stdio;

ulong largestPrimeFactor(ulong n) {
for(ulong p=2; p<=sqrt(cast(real)n); ) {
n%p==0 ? n/=p : p+=1 ;
}
return n;
}

void main() {
writeln(largestPrimeFactor(4));
}
*

What am I doing wrong here?
I'm using dmd version 2.071.1-0 on ubuntu.


Re: Expression template

2016-07-26 Thread Ilya Yaroshenko via Digitalmars-d-learn

On Tuesday, 26 July 2016 at 10:35:12 UTC, Etranger wrote:


I'll have time 2 months from now as I'm getting married in 2 
weeks :)


Congratulations!




Re: randomIO, std.file, core.stdc.stdio

2016-07-26 Thread Steven Schveighoffer via Digitalmars-d-learn

On 7/25/16 9:19 PM, Charles Hixson via Digitalmars-d-learn wrote:

On 07/25/2016 05:18 PM, ketmar via Digitalmars-d-learn wrote:

On Monday, 25 July 2016 at 18:54:27 UTC, Charles Hixson wrote:

Are there reasons why one would use rawRead and rawWrite rather than
fread and fwrite when doiing binary random io?  What are the advantages?

In particular, if one is reading and writing structs rather than
arrays or ranges, are there any advantages?


yes: keeping API consistent. ;-)

for example, my stream i/o modules works with anything that has
`rawRead`/`rawWrite` methods, but don't bother to check for any other.

besides, `rawRead` is just looks cleaner, even with all `()[0..1])`
noise.

so, a question of style.


OK.  If it's just a question of "looking cleaner" and "style", then I
will prefer the core.stdc.stdio approach.  I find it's appearance
extremely much cleaner...except that that's understating things. I'll
probably wrap those routines in a struct to ensure things like files
being properly closed, and not have explicit pointers persisting over
large areas of code.


It's more than just that. Having a bounded array is safer than a 
pointer/length separated parameters. Literally, rawRead and rawWrite are 
inferred @safe, whereas fread and fwrite are not.


But D is so nice with UFCS, you don't have to live with APIs you don't 
like. Allow me to suggest adding a helper function to your code:


rawReadItem(T)(File f, ref T item) @trusted
{
   f.rawRead([0 .. 1]);
}

-Steve


Re: Assert question

2016-07-26 Thread Adam D. Ruppe via Digitalmars-d-learn

On Tuesday, 26 July 2016 at 12:13:02 UTC, DLearner wrote:
What is the recommended way of identifying which assert has 
been triggered?


If you compile with -g, run the program in a debugger. It will 
tell you.


If you compile and do NOT use -release, the error message 
automatically printed by the assert will tell you the line number 
on the first line of output.


Re: Assert question

2016-07-26 Thread Steven Schveighoffer via Digitalmars-d-learn

On 7/26/16 8:13 AM, DLearner wrote:

Suppose a program contains several points that control should not get to.
So each such point is blocked by assert(0).
What is the recommended way of identifying which assert has been triggered?

Is one allowed anything like 'assert(0,"Crashed at point A");', where
the message goes to stderr?


In non-release mode, assert(0, msg) prints the message (an error is 
thrown). In release mode, the assert(0) halts the program immediately 
and does not print any message.


So yes and no :)

-Steve


Assert question

2016-07-26 Thread DLearner via Digitalmars-d-learn
Suppose a program contains several points that control should not 
get to.

So each such point is blocked by assert(0).
What is the recommended way of identifying which assert has been 
triggered?


Is one allowed anything like 'assert(0,"Crashed at point A");', 
where the message goes to stderr?


Re: Expression template

2016-07-26 Thread Etranger via Digitalmars-d-learn

On Saturday, 23 July 2016 at 23:55:44 UTC, ag0aep6g wrote:

On 07/23/2016 01:05 PM, Etranger wrote:

[...]


To avoid the string mixin, you can let VecExpression take an 
alias of the mixin template (Vec_impl/VecSum_impl) and the list 
of arguments:


[...]


Thanks ! that's way much cleaner and the type strictness loss is 
not a problem since it is what I want.


Re: Expression template

2016-07-26 Thread Etranger via Digitalmars-d-learn

On Sunday, 24 July 2016 at 10:53:41 UTC, Ilya Yaroshenko wrote:

On Saturday, 23 July 2016 at 11:05:57 UTC, Etranger wrote:


[...]


Yes, but it is more complicated in terms of multidimensional 
and generic abstraction.
First we need to finish and test general matrix multiplication 
[2].


[...]


Thanks allot for your suggestions. I started looking into the 
ndslice and mir code. For me it seems that there is an urgent 
need to have a better benchmarking (like rust bench or google 
benchmark framework for cpp) framework than what is available. I 
can may be look into it.


I'll have time 2 months from now as I'm getting married in 2 
weeks :)


Re: Static ternary if

2016-07-26 Thread Cauterite via Digitalmars-d-learn

On Tuesday, 26 July 2016 at 00:54:59 UTC, Michael Coulombe wrote:
If that's ok, then try out std.traits.Select or 
std.traits.select:

https://dlang.org/phobos/std_traits.html#Select


Damn, I looked real hard for that template, I knew it existed. I 
expected it to be in std.meta though.




Re: Trouble using 'sort'

2016-07-26 Thread Bahman Movaqar via Digitalmars-d-learn
On 07/26/2016 11:42 AM, drug wrote:
> Another option is `makeIndex` (std.algorithm.sorting) and then sorting
> of that index.

That's an interesting option; at least I don't have to touch the range.
Thanks.

-- 
Bahman


Re: Trouble using 'sort'

2016-07-26 Thread Bahman Movaqar via Digitalmars-d-learn
On 07/26/2016 10:41 AM, Jonathan M Davis via Digitalmars-d-learn wrote:
>> So it may be something about what kind of range I'm passing to `sort`.
>> Am I right?
> 
> sort requires a random access range. Without knowing exactly which
> algorithms your using, I can't say for sure that that's the problem, but
> usually it is. Most of the time, you don't end up with a random access range
> after chaining several range-based functions. You _can_, but it depends
> entirely on which functions they are and the type of your original range.
> 
> It's frequently the case that if you want to sort a range, you have to call
> array() on it to convert it to an array, and then you can sort the array.

Thanks...that explains it.

-- 
Bahman


Re: Trouble using 'sort'

2016-07-26 Thread drug via Digitalmars-d-learn

26.07.2016 09:11, Jonathan M Davis via Digitalmars-d-learn пишет:


It's frequently the case that if you want to sort a range, you have to call
array() on it to convert it to an array, and then you can sort the array.

- Jonathan M Davis

Another option is `makeIndex` (std.algorithm.sorting) and then sorting 
of that index.


Re: Trouble using 'sort'

2016-07-26 Thread Jonathan M Davis via Digitalmars-d-learn
On Tuesday, July 26, 2016 10:11:43 Bahman Movaqar via Digitalmars-d-learn 
wrote:
> On 07/26/2016 09:35 AM, Bahman Movaqar wrote:
> > I have a range which is the result of a couple of chained range
> >
> > operations, and each element is:
> > Tuple!(string, "product", double, "price")
> >
> > Now I'd like to sort the range by "price" using:
> > sort!((pp1, pp2) => cmp(pp1.price,  pp2.price) > 0)(theRange)
> >
> > But I get a compile time error:
> >
> > source/services.d(166,63): Error: template std.algorithm.sorting.sort
> > cannot deduce function from argument types !((pp1, pp2) =>
> > cmp(pp1.price, pp2.price) > 0)(MapResult!(__lambda5, Result)),
> > candidates are:
> >
> > 
/home/bahman/Programs/D/dmd-2.071.0/linux/bin64/../../src/phobos/std/algorithm/sorting.d(1027,1):
> >std.algorithm.sorting.sort(alias less = "a < b", SwapStrategy ss
> >
> > = SwapStrategy.unstable, Range)(Range r) if ((ss ==
> > SwapStrategy.unstable && (hasSwappableElements!Range ||
> > hasAssignableElements!Range) || ss != SwapStrategy.unstable &&
> > hasAssignableElements!Range) && isRandomAccessRange!Range &&
> > hasSlicing!Range && hasLength!Range)
> > source/services.d(168,5): Error: var has no effect in expression
> > (theRange)
> > dmd failed with exit code 1.
>
> Alright...further experiments.  The following works:
>
> sort!((pp1, pp2) => cmp(pp1.price,  pp2.price) > 0)(theRange)
>
> So it may be something about what kind of range I'm passing to `sort`.
> Am I right?

sort requires a random access range. Without knowing exactly which
algorithms your using, I can't say for sure that that's the problem, but
usually it is. Most of the time, you don't end up with a random access range
after chaining several range-based functions. You _can_, but it depends
entirely on which functions they are and the type of your original range.

It's frequently the case that if you want to sort a range, you have to call
array() on it to convert it to an array, and then you can sort the array.

- Jonathan M Davis