Subject: Try this if your dog is misbehaving

From: Dog-Training <[email-masked]>
Date: Fri, 22 Aug 2014 10:24:37 -0700

Chances are you're training your dog wrong.

Every dog needs to be trained properly:
- 

If your getting nervous that one day they could attack someone then you need to do something about it. Don't live in denial or hide your dog from social activities. That could make the situation worse.

A new statistic show 85% of people are afraid their dog could harm somebody one day.

You don't want to end up having to get rid of your dog: http://www.bosdietpower.com/dog/train/behavior-3457345.html

-

-

-

-
From: DOG-Source US ~ 11561-Faye Road ~ Garden Grove CA ~ 
Re-move-Prefshttp://www.bosdietpower.com/d.htm or_write
---  ---  ---  ---  ---  ---  ---  ---  ---  ---  ---  ---  ---  ---  ---  ---  ---  ---  

A long time ago, a little Dalmatian puppy sat outside the fence at the school. The puppy loved watching the children play. He wanted to play with the children, but he was very shy. 
 
One day, the puppy followed two children home from school. He curled up under a tree in the front yard to take a nap. Sparky wakes up from his napSuddenly, he woke up. When he looked up, he saw that the children's house was on fire. The puppy knew he needed to get help. He ran down the street to the fire station, barking all the way.
 
Sparky barking at the fire stationThe puppy saw the firefighters jump on their trucks and leave. He tried to run behind them, but his little legs could not keep up. When he got back to the house, he looked all around for the children but could not see them. He was very worried.
 
After the fire was out, the firefighters noticed the sad-looking puppy shivering under a tree.
 
Sparky is held by Firefighter Janet"Look, it's the little puppy we saw at the station." Firefighter Janet scooped up the puppy in her arms "Hey, little guy, where do you live?" 
 
"I know," said Firefighter Janet, "let's take him to see the family. I'll bet he could cheer up the kids," said the firefighter. She knocked on the door. The puppy could barely believe his eyes
 
Sparky greets the childrenThe children were safe They hugged the puppy and he wagged his tail.
 
"Do you know who this puppy belongs to?" asked the firefigher. "He's a real hero, he ran all the way to the fire station to let us know there was a fire at your house."
 
Sparky with Firefighter Janet and the children"I guess that makes him a fire dog. Maybe we should call him Sparky. Sparky the Fire Dog, said the firefighter." Sparky found a new home at the fire station.
 
Sparky was very proud of his new name and loved his new home at the fire station. He worked hard to teach children and their families everywhere how to stop fires from happening.
 
The End

I'm running the following code on a JDK Version 1.7.0_60:

System.out.println(Math.pow(1.5476348320352065, (0.3333333333333333)));
The result is: 1.1567055833133086

I'm running exactly the same code on a JDK Version 1.7.0.

The result is: 1.1567055833133089

I understand that double is not infinitely precise, but was there a change in the java spec that causes the difference?

PS: Because we use a legacy system, Big Decimal is not an option.

Edit: I was able to track down the time of the change: It was introduced in the JDK Version 1.7.0_40 (as compared to Version 1.7.0_25).

java math floating-point pow
share|improve this question
edited 21 hours ago

Jeremie Miserez
1,473715	
asked yesterday

Damnum
17017
5	 	
It may well be a difference in which hardware instructions the JIT uses.   Jon Skeet yesterday
3	 	
What affect does this have on your program's output (other than the difference shown above)? How does this affect the functionality of your program? Is your code written in a way to allow for tolerance of double's limitations.   Hovercraft Full Of Eels yesterday 
1	 	
Out of curiosity, in what field is you application? I have hard time imagining a situation where a difference of 3E-16 would make a significant difference.   dasblinkenlight yesterday
1	 	
Were the two calculations on the same machine? as according to the std, a faithful rounding, i.e. correct within 1 ulp, is required as the power function is very expensive to be correctly rounded. Therefore pow function is not portable.   Garp 18 hours ago 
1	 	
If these small relative errors in the elementary computations sum up to something that big in the result, then there are other problems in the code. The implied condition number is outside the solar system. Does the problem actually have a well-defined result? What is the margin of the relative error expected from the choice of numerical algorithm? Check that the algorithms used matches the implementation, try to transform formulas to avoid cancellations, use the relatively  error compensated summation methods found in Knuth, Higham, Rhump.   LutzL 4 hours ago
show 4 more comments
3 Answers
activeoldestvotes
up vote
25
down vote
but was there a change in the java spec that causes the difference?

No.* According to the Javadocs for Math.pow, a difference of up to one ULP (Unit in the Last Place) is permitted. If we take a look at your two values:

System.out.printf("%016x\n", Double.doubleToLongBits(1.1567055833133086));
System.out.printf("%016x\n", Double.doubleToLongBits(1.1567055833133089));
we get:

3ff281ddb6b6e675
3ff281ddb6b6e676
which indeed differ by one ULP.

What you're seeing is probably due to slight differences in the sequence of floating-point instructions used by the JDK/JVM to implement these operations.

* At least, not so far as I know
share|improve this answer
edited 21 hours ago

Lambart
4391514	
answered yesterday

Oli Charlesworth
150k11255421
  	 	
I still wonder where could that difference come from.   biziclop yesterday
4	 	
@biziclop: For that, we'd need to trawl through the source code for the platform-specific native methods, which I don't fancy doing right now ;)   Oli Charlesworth yesterday
  	 	
Me neither, that's why I just wonder :)   biziclop yesterday
  	 	
IEEE floating point implementation is the source.   duffymo yesterday
7	 	
For the record, the exact result is 1.156705583313308737..., and the answer given by Java 1.7.0_60 is more accurate.   Tavian Barnes yesterday
add a comment

up vote
5
down vote
If you want repeatable floating point values between JVMs you can use the strictfp keyword, see following question When should I use the "strictfp" keyword in java?

share|improve this answer
answered yesterday

user3679868
48716
  	 	
If I annotate the calling method/class with strictfp, the difference between version 1.7.0_25 and 1.7.0_40 remains the same.   Damnum 23 hours ago
6	 	
@Damnum strictfp doesn't do anything with respect to the methods in Math. Try StrictMath.pow() and see if it produces consistent results.   ntoskrnl 21 hours ago
  	 	
StrictMath.pow() appears to specify the use of fdlibm. You should get consistent results, but they aren't especially high-quality.   tmyklebu 17 hours ago
1	 	
@tmyklebu That bring us to the almost-philosophical question of why IEEE 754 did not, for those functions that couldn't be computed to 0.5ULP ly enough to mandate it, standardize some specific algorithms with the accuracy/code size/speed trade-offs that were the state of the art at the time of standardizing. And the answer to that appears to be that they did not want to make life harder than necessary for newer, more accurate algorithms, which would have had to fight against the standard. In retrospect, well done IEEE 754 (and Sun for relegating fdlibm to StrictMath).   Pascal Cuoq 6 hours ago
  	 	
@PascalCuoq: I believe (from my dim memories of someone's (Kahan's) history of the IEEE 754 standard) they thought about this and rejected the idea so they wouldn't crimp the style of future implementations that could possibly be faster or more accurate. "Faster" also being an acceptable goal.   tmyklebu 5 hours ago
show 1 more comment
up vote
2
down vote
There was no change in the spec, but there have been some changes in the hotspot optimizer that might () be related to this.

I dug up these code parts:

>From update 25: vm/opto/library_call.cpp : inline_pow
>From update 40: vm/opto/library_call.cpp : inline_pow
(these are not exactly the versions where these changes have been introduced, I just picked them because of the version information that you provided).

The changes (and what the code is doing at all) are far beyond what I can analyze in reasonable time, but maybe someone finds this reference interesting or useful.

I have a class depending on an integer template parameter. At one point in my program I want to use one instantiation of this template, depending on a value of this parameter determined at runtime. Here is a simple example demonst how I would go about this currently, using a big switch statement:

#include <string>
#include <iostream>
#include <type_traits>

template<unsigned A>
struct Wrapper {
    typedef typename std::conditional<A==1, int, float>::type DataType;
    DataType content[A];
    void foo() {
        std::cout << A << std::endl;
    };
};    

int main(int argc, char *argv[])
{
    std::string arg = argv[1];
    int arg_int = std::stoi(arg);

    switch (arg_int) {
    case 1: {
        Wrapper<1> w;
        w.foo();
        break;
    }
    case 2: {
        Wrapper<2> w;
        w.foo();
        break;
    }
    case 3: {
        Wrapper<3> w;
        w.foo();
        break;
    }
    default:
        return 1;
    };

    return 0;
}
This will quickly get unwieldy once I have not only one parameter A, but multiple template arguments in various combinations. Let's also assume that in reality there is a really good reason to implement A as a template parameter.

Is there a way to replace the huge switch statement with almost identical case statements, e.g. using some metaprogramming magic from Boost or a preprocessor hack?

Ideally I would like to be able write something like the following:

INSTANTIATE_DEPENDING(i, {1, 2, 3},
            {
                Wrapper<i> w;
                w.foo();
            }
    );
c++ templates boost c-preprocessor
share|improve this question
edited Aug 8 at 12:26

asked Aug 8 at 11:16

rerx
457211
  	 	
Seems like either a task to solve using virtual inheritance, or, if the integer really just represents the size of an array, then with std::vector.   The Paramagnetic Croissant Aug 8 at 11:22
  	 	
I would create a separate structure for such params to group them and use it as template parameter   user1534985 Aug 8 at 11:26
  	 	
The template class is really more complicated than in the simple example. There is no way to avoid having different template instantiations, I have added some extra complexity to the example.   rerx Aug 8 at 11:35
  	 	
What constraints are there on the valid numbers used in the switch?   Niall Aug 8 at 11:41 
  	 	
In this case the valid numbers are {1, 2, 3}. It might be different set. I may be able to arrange that they are always ascending natural numbers, though.   rerx Aug 8 at 11:48
add a comment
7 Answers
activeoldestvotes
up vote
15
down vote
accepted
You could use a variadic template, maybe like this:

#include <cstdlib>
#include <string>

int main(int argc, char * argv[])
{
    if (argc = 2) { return EXIT_FAILURE; }

    handle_cases<1, 3, 4, 9, 11>(std::stoi(argv[1]));
}
Implementation:

template <int ...> struct IntList {};

void handle_cases(int, IntList<>) { /* "default case" */ }

template <int I, int ...N> void handle_cases(int i, IntList<I, N...>)
{
    if (I = i) { return handle_cases(i, IntList<N...>()); }

    Wrapper<I> w;
    w.foo();
}

template <int ...N> void handle_cases(int i)
{
    handle_cases(i, IntList<N...>());
}
share|improve this answer
edited Aug 8 at 12:11

answered Aug 8 at 11:46

Kerrek SB
194k22304521
  	 	
This is rather beautiful (for C++ standards) and taught me about variadic templates. I can also see how to extend this to multiple parameters by using tuples as template parameters.   rerx Aug 8 at 12:31
  	 	
Ah, unfortunately extending this is not as straight forward as I thought. typedef std::tuple<int, char> ParamTuple; template <ParamTuple ...> struct ParamTupleList {}; does not compile: class std::tuple<int, char> is not a valid type for a template constant parameter   rerx Aug 8 at 12:50
  	 	
@rerx: The final function template is just for convenience. You could also say handle_cases(std::stoi(argv[1]), IntList<1, 2, 3>()) directly. That syntax is straight-forward to extend to multiple parameters: f(x, y, z, IntList<1,2,3>(), IntList<3,4>(), IntList<>())   Kerrek SB Aug 8 at 13:40
  	 	
I see. But all parameter values would need to be of the same (integer) type?   rerx Aug 8 at 13:51 
  	 	
It looks cute but if you have a long list, is handle_cases() going to be O(N) on the length of the list as it recurses through it all? In your case if i == 11   Cow Aug 8 at 15:50 
show 3 more comments

up vote
5
down vote
arg_int is a runtime parameter so there is no way to attach it directly to a template parameter. You could use some kind of handler table which would remove the switch statement here.

You'd use something like lookup_handler( int N ) returning a type handler which might be a lambda invoking one of those template functions.

Registering all your lambdas on the table could be done recursively starting with the highest numbered one you allow.

template< unsigned N > register_lambda()
{
     table.add( Wrapper<N>() );
     register_lambda< N-1 >;
}
and specialise for register_lambda<0>

Then somewhere you call register_lambda<32> say and you have registered all the numbers from 0 to 32.

One way to implement such a table is:

class lambda_table
{
 typedef std::function<void()> lambda_type; 
    public:
        void add( lambda_type );
        bool lookup( size_t key, lambda_type & lambda ) const;
};
>From main() or wherever you want to invoke it you have a reference to this table (call it table) then call

lambda_type lambda;
if( table.find( arg_int, lambda ) )
        lanbda();
else
      default_handler();
You might change this to give the table itself a default handler where none has been supplied for this number.

Although lambdas can wrap all kinds of data members you might actually want your templates to be classes in a hierarchy rather than lambdas given the data storage within them.

share|improve this answer
edited Aug 8 at 12:06

answered Aug 8 at 11:30

Cow
18.9k22045
  	 	
hey, register is keyword >o<   ikh Aug 8 at 11:33
  	 	
yeah I replaced it although it's intended as an illustration, to show how it might be done.   Cow Aug 8 at 11:37
  	 	
Could you write a more complete answer, explicitly showing how to replace the switch?   rerx Aug 8 at 11:38
  	 	
All of that examples are replacing your switch directly. The key is to put it all into a data structure, where your arg_int is the key and retrieves a pointer to a function, that handles your wrapper-foo-thing.   Stefan Weiser Aug 8 at 11:42
add a comment
up vote
3
down vote
just use macros

template<unsigned A>
struct Wrapper {
    int content[A];
    void foo() { };
};

#define WRAPPER_SWITCH_CASE(i) case i: Wrapper<i>().foo(); break;

int main(int argc, char *argv[])
{
    std::string arg = argv[1];
    int arg_int = std::stoi(arg);

    switch (arg_int) {
        WRAPPER_SWITCH_CASE(1)
        WRAPPER_SWITCH_CASE(2)
        WRAPPER_SWITCH_CASE(3)
        default: return 1;
    };

    return 0;
}
(live example)

But as you know, macros are harmful; I think Wrapper should be allocate content at runtime, not template.

share|improve this answer
edited Aug 8 at 23:14

answered Aug 8 at 11:33

ikh
2,561119
  	 	
I'm definitely in favor of using macros (locally, i.e., with an '#undef' afterwards, which should not be too harmful). Now can we extend this solution by some recursive template trick or something else, so that we get rid of the explicit switch? I would like to have something similar to INSTANTIATE_DEPENDING(i, {1, 2, 3}, ... in the question.   rerx Aug 8 at 11:43
  	 	
Macros are not "harmful" but make the code hard to follow and maintain and can in many cases cause subtle errors.   Cow Aug 8 at 15:51
  	 	
@Cow Including your points, it's harmful >o<   ikh Aug 8 at 16:12
  	 	
@rerx Yes, in C++11, there's varidic macro, which is derived fron C99's.   ikh Aug 8 at 16:14
1	 	
@ikh Replace the "1"s with "i"s in the macro definition   Lan Pac Aug 8 at 20:41 
show 1 more comment
up vote
2
down vote
a short prof of concept application using a recursive generator for the Wrappers:

#include <iostream>
#include <vector>

struct FooProvider
{
    virtual void foo() = 0;
};

template<unsigned A>
struct Wrapper : public FooProvider {
    Wrapper() {std::cout << A << std::endl;}
    int content[A];
    virtual void foo() { std::cout << "call:" << A << std::endl;};
};

static std::vector<FooProvider*> providers;

template <unsigned CTR>
struct Instantiator
{
    Instantiator()
    {
        providers.insert(providers.begin(), new Wrapper<CTR>);
        Instantiator<CTR - 1>();
    }
};

template <>
struct Instantiator<0>
{
    Instantiator() {}
};

int main()
{
    Instantiator<100>();
    providers[4]->foo();

    // do not forget to delete the providers
}
share|improve this answer
answered Aug 8 at 11:37

fritzone
9,37421852
  	 	
You all suggest, that all numbers from 0..N are registered? The core of the question is, how to replace a switch.   Stefan Weiser Aug 8 at 11:39
  	 	
I would prefer a solution without any virtual functions.   rerx Aug 8 at 11:45
  	 	
This is just a more elaborate expansion of what I suggested in recursive registration to a table. You could use a lambda instead of polymorphism through virtual.   Cow Aug 8 at 11:50
  	 	
How exactly does Wrapper<T> use its array data though? If you want these instances to be generated every time you invoke the class it's fine as it is. If you want exactly one of each of these to exist it's a different issue. If you want this data to persist, the approach of having a class from which they all derive may work better   Cow Aug 8 at 12:09
add a comment
up vote
2
down vote
You could just use a higher-order looping macro that passes the block implementation to a generic loop expander:

#define M_NARGS(...) M_NARGS_(__VA_ARGS__, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
#define M_NARGS_(_10, _9, _8, _7, _6, _5, _4, _3, _2, _1, N, ...) N

#define M_CONC(A, B) M_CONC_(A, B)
#define M_CONC_(A, B) A##B
#define M_ID(...) __VA_ARGS__

#define M_FOR_EACH(ACTN, ...) M_CONC(M_FOR_EACH_, M_NARGS(__VA_ARGS__)) (ACTN, __VA_ARGS__)

#define M_FOR_EACH_0(ACTN, E) E
#define M_FOR_EACH_1(ACTN, E) ACTN(E)
#define M_FOR_EACH_2(ACTN, E, ...) ACTN(E) M_FOR_EACH_1(ACTN, __VA_ARGS__)
#define M_FOR_EACH_3(ACTN, E, ...) ACTN(E) M_FOR_EACH_2(ACTN, __VA_ARGS__)
#define M_FOR_EACH_4(ACTN, E, ...) ACTN(E) M_FOR_EACH_3(ACTN, __VA_ARGS__)
#define M_FOR_EACH_5(ACTN, E, ...) ACTN(E) M_FOR_EACH_4(ACTN, __VA_ARGS__)
//...etc

#define INSTANTIATE_DEPENDING(L, C) M_FOR_EACH(C, M_ID L)

//...
#define CASE_BLOCK(n) case n: { Wrapper<n> w; w.foo(); break; }

INSTANTIATE_DEPENDING((1, 2, 3), CASE_BLOCK)

#undef CASE_BLOCK  //if you like, not essential to the concept
Not a lot to say about that: the loop repeats the block for the length of the passed list, passing the items in the list to the macro it is to expand. So you put your implementation in that macro (and #undef it if you want it to be local).

More elegantly (letting you nest the parameterized code to expand inside the expression where it belongs, instead of a second definition), you could use the rather high-end Order metaprogramming library:

#include <order/interpreter.h>

ORDER_PP(    // runs Order code
  8for_each_in_range(8fn(8I,
                         8print( (case) 8I (: { )
                                    (Wrapper<) 8I (> w; w.foo(); break; }) )),
                     1, 4)
)
(Use 8for-each instead of 8for_each_in_range for non-contiguous lists. Order's got full functional programming semantics so such things are minor issues.)

I am trying to detect if a folder or a file is dragged in events dragover or dragenter.

For example:

In the ondrop event, there is an argument, MouseEvent, with a field named dataTransfer, where are listed files or items (depends on browser), and I can define what it is for Chrome or Firefox.

But for the dragover and dragenter events those fields are empty.

Note:

For both, files and folders, dataTransfer.types is equal to "Files". That is, event.dataTransfer.types[i] == "Files" is true for both folders and files.

I need that information while dragging (dragover and dragenter events), not drop.

Background Research

I found the following Stack Overflow answer fit for my question:

WebKit, and hence Chrome, is quite restrictive on when you can call getData. You're not allowed to do it inside dragstart or dragover. I think this is the canonical bug.

But that answer is from 2012, and I can't find actual updated information.

I am looking for updated information on this.

javascript html5 drag-and-drop folder
share|improve this question
edited Aug 8 at 15:37

Tanner
6,47711839	
asked Jul 29 at 13:24

kris
413315
1	 	
I found the fit answer for my question here (stackoverflow.com/questions/9534677/) but it's 2012 year, and I can't find an actual info(   kris Jul 29 at 19:17
1	 	
A minimal working example that clarifies or demonstrates the problem might help people provide quality answers.   Marcin Aug 7 at 18:36
7	 	
The meta question   Peter Mortensen Aug 7 at 18:54
1	 	
My guess is you simply can't do this: what if I am dragging a file or folder over my browser window to something unrelated: I wouldn't want a random website to glean any information about the content of what I am dragging if it isn't the final target.   Mark Rotteveel Aug 8 at 7:13
  	 	
Yes Info about content file should not be available while dragging due to security. But we know the type of dragging element (file or dom element). So, if many browsers does not support folder dnd, so we have right to know file or folder is it.   kris Aug 8 at 8:55
add a comment
2 Answers
activeoldestvotes
up vote
30
down vote
+25
Clarifications on the file drag/drop in HTML5
I made some researches in many documentations for this topic and tested it by myself on various browsers, so I decided to summarize all I know about drag and drop of files here.

Dragging:

When you drag a file you can use some listeners, such as:

dragenter
dragover
dragend
dragleave
Given that these are drag events, the files property of event.dataTransfer will either have length == 0 or be empty (null). So you can't read files details in a drag event and you can't check if they are folders. This is not a bug, it's a security measure. Imagine you can read files on a drag event: you would be able to read everything even if the user doesn't want to upload files to your site. It would make no sense, seriously. Imagine you are dragging a file from your desktop to another folder and you accidentally drag it through a web page: now the web page reads your file and stores your personal informations on its server... that would be a great privacy and security fault.

However, you will still be able to detect if you are dropping files by ite over the array event.dataTransfer.types. You can create a function that checks if the drag event contains files, and then call it in the event handler.

Example:

function containsFiles(event) {
    if (event.dataTransfer.types) {
        for (var i=0; i<event.dataTransfer.types.length; i++) {
            if (event.dataTransfer.types[i] == "Files") {
                return true;
            }
        }
    }

    return false;
}

function handleDragEnter(e) {
    e.preventDefault();
    if containsFiles(e) {
        // The drag event contains files
        // Do something
    } else {
        // The drag event doesn't contain files
        // Do something else
    }
}
Dropping:

When you drop a file into the drop div, you will use a listener for the event drop to read some file properties such as name, size, type and last modification date.

To detect if a file is a folder, you are going to:

Check if the file has type == "", because folders have no type.
Check if the file size is a multiple of 4096: size%4096 == 0, because folders always have a size multiple of 4096 bytes (which is 4KiB).