It seems that you're using an outdated browser. Some things may not work as they should (or don't work at all).
We suggest you upgrade newer and better browser like: Chrome, Firefox, Internet Explorer or Opera

×
avatar
dtgreene: Actually, just tested in both Firefox and Chromium; NaN === NaN is false, no exception thrown.
You're right, maybe I had a typo when trying it on the Chrome console. I was at my wife's laptop and the keyboard is rather fiddly.

And the display is tiny, text is very small.
Post edited November 26, 2015 by toxicTom
avatar
JDelekto: Excellent! ---> That was directed at you ToxicTom.

BTW, the passing of 'undefined' was to protect "undefined" and you could compare anything to the 'undefined' variable and be sure it was true if truly undefined (including variables set to null).

One of the really cool tricks I've learned in JavaScript is the use of the || operator on assignment. Even empty strings can be replaced with others.

For example:

var template = "";

template = template || "<div></div>";

even if template were null, or an empty string, it would be populated.
I always use strict mode, so protecting undefined should not be necessary.

Concerning the ||, I use it all the time:

window.modelFactory = window.modelFactory || {};
window.modelFactory.createProductModel = function (data, options) {
...
};

or:

var doSomethingAndCheck = function () {
...
return model.isValid();
};

var displayErrors = function () {
...
};

doSomethingAndCheck() || displayErrors();
low rated
Here's another interesting Python example (carrots indicate indentation):

for x in range(300):
^a = eval(str(x))
^b = eval(str(x))
^assert a is b, x

Can you predict what the code does without running it?

Of note, this example behaves differently in pypy (at least in pypy 3).
avatar
toxicTom: ...
doSomethingAndCheck() || displayErrors();
Have you seen the "namespace" pattern at all? I try to use it when I can to organize code into conceptual groupings, so I can do something like:

Root.namespace("UI", {
customCombo: function() {}
});

Then in other code, you could alias it as:

var rui = Root.UI;

rui.customCombo();

It's a contrived example, but hopefully enough to get the idea across.

BTW, to use strict mode, you do something like this at the top of your code right?

"use strict";

I suppose I got so caught up in the pattern of protecting 'undefined', it's like second nature to using strict. does it harm anything using it in that way?
Post edited November 26, 2015 by JDelekto
avatar
dtgreene: Here's another interesting Python example (carrots indicate indentation):

for x in range(300):
^a = eval(str(x))
^b = eval(str(x))
^assert a is b, x

Can you predict what the code does without running it?

Of note, this example behaves differently in pypy (at least in pypy 3).
I would assume that the code iterates through a range of numbers, converts number to a string twice, assigning it to variables a and b in succession, then asserts the value of a is the same as b, failing with displaying the value of x. I would really expect is something bad to happen in a case where multiple threads or processors are use iterating the code in the 'for' loop.

However, it seems tricky, a and b could be considered declared, not defined an attempt to be evaluated before the 'for' takes places. You've piqued my curiosity, do tell.
Post edited November 26, 2015 by JDelekto
avatar
JDelekto: Have you seen the "namespace" pattern at all? I try to use it when I can to organize code into conceptual groupings, so I can do something like:

Root.namespace("UI", {
customCombo: function() {}
});

Then in other code, you could alias it as:

var rui = Root.UI;

rui.customCombo();

It's a contrived example, but hopefully enough to get the idea across.

BTW, to use strict mode, you do something like this at the top of your code right?

"use strict";

I suppose I got so caught up in the pattern of protecting 'undefined', it's like second nature to using strict. does it harm anything using it in that way?
In larger applications I use namespacing with extend like described here: http://addyosmani.com/blog/essential-js-namespacing/

Your way of protecting undefined does no harm. And yes "use strict"; as the first line in any js-file enforces strict mode.

Note that most browsers silently protect keywords like undefined anyway (and silently). Just try on the console:

undefined = 1;
console.log(undefined); // undefined
low rated
avatar
dtgreene: Here's another interesting Python example (carrots indicate indentation):

for x in range(300):
^a = eval(str(x))
^b = eval(str(x))
^assert a is b, x

Can you predict what the code does without running it?

Of note, this example behaves differently in pypy (at least in pypy 3).
avatar
JDelekto: I would assume that the code iterates through a range of numbers, converts number to a string twice, assigning it to variables a and b in succession, then asserts the value of a is the same as b, failing with displaying the value of x. I would really expect is something bad to happen in a case where multiple threads or processors are use iterating the code in the 'for' loop.

However, it seems tricky, a and b could be considered declared, not defined an attempt to be evaluated before the 'for' takes places. You've piqued my curiosity, do tell.
Actual output (python 3.4.3):
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
AssertionError: 257

First, the GIL (Global Interpreter Lock) prevents multiple threads from executing the same Python code; hence, the multi-thread issue you mentioned can't happen in pure Python (at least with the CPython interpreter).

What's going on here is that CPython actually treats integer variables as pointers to integer objects. Because they are so commonly used, CPython pre-allocates integers from -5 to 256. As a result, when x is in that range, a and b are allocated the same integer object and therefore point to the same one, and the "is" comparison returns true.

When x is 257, however, things change. Since there is no pre-allocated 257, the program allocates a new object for a and a *different* new object for b. As a result, the "is" comparison (which is a pointer comparison, not a value comparison, by the way) returns false and the assert statement yields an AssertionError.

It is worth noting that the eval and str stuff was done solely to force the interpreter to create new objects instead of just re-using the object that x points to.

Of note, with some hackery (via ctypes or C extensions), it is possible to change the value of integer constants. For instance, you could set the value of 13 to be 42. Note that this can produce strange results, and I believe setting the value of 0 to something else will cause simple operations to segfault the interpreter. Setting something else to 0 will allow you to divide by zero, bypassing the interpreter's check that would normally disallow that.

Here is a link to a description of how CPython implements integers:
http://www.laurentluce.com/posts/python-integer-objects-implementation/
avatar
dtgreene: Actual output (python 3.4.3):
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
AssertionError: 257

First, the GIL (Global Interpreter Lock) prevents multiple threads from executing the same Python code; hence, the multi-thread issue you mentioned can't happen in pure Python (at least with the CPython interpreter).

What's going on here is that CPython actually treats integer variables as pointers to integer objects. Because they are so commonly used, CPython pre-allocates integers from -5 to 256. As a result, when x is in that range, a and b are allocated the same integer object and therefore point to the same one, and the "is" comparison returns true.

When x is 257, however, things change. Since there is no pre-allocated 257, the program allocates a new object for a and a *different* new object for b. As a result, the "is" comparison (which is a pointer comparison, not a value comparison, by the way) returns false and the assert statement yields an AssertionError.

It is worth noting that the eval and str stuff was done solely to force the interpreter to create new objects instead of just re-using the object that x points to.

Of note, with some hackery (via ctypes or C extensions), it is possible to change the value of integer constants. For instance, you could set the value of 13 to be 42. Note that this can produce strange results, and I believe setting the value of 0 to something else will cause simple operations to segfault the interpreter. Setting something else to 0 will allow you to divide by zero, bypassing the interpreter's check that would normally disallow that.

Here is a link to a description of how CPython implements integers:
http://www.laurentluce.com/posts/python-integer-objects-implementation/
Pretty crazy...
This was not a good day. I feel like a complete noob. I fear I may need to hand in my geek cred...anyone know where I can get a geek cred card so I can hand it in?

First I rewrote most of a class I wrote last week. Basically a hackish helper library to translate a tagged SQL statement accepted through a jQuery XmlHttpRequest, validating it and helping translate the tags to the actual table data fields, validating the input. It feels like an ugly hack, but short of having to rewrite my data-access layer or switching to an ORM for accepting complex seardh queries, I don't know how. Any good advice here?

After that I spent an hour trying to get my data-access library to compile with it. Intellisense knew about it. All seemed good.
Yet whenever I compiled I got an error that the namespace was not found, even though the .dll was referenced and contained the namespace.

In the end it turned out the library was compiled .NET 4.5, executable was compiled .NET 4.0 -_-

And just to round off the day, VIsual Studio refused to merge the branch back into the master branch after I'd tested the new "feature" implementation...in the end I just shut down VS and used git bash.

Sorry for the gripe.
avatar
DrakeFox: First I rewrote most of a class I wrote last week. Basically a hackish helper library to translate a tagged SQL statement accepted through a jQuery XmlHttpRequest, validating it and helping translate the tags to the actual table data fields, validating the input. It feels like an ugly hack, but short of having to rewrite my data-access layer or switching to an ORM for accepting complex seardh queries, I don't know how. Any good advice here?
Depends. What exactly is it you're trying to do? It sounds like you want to use an XML based syntax to make queries against a database by translating the XML into SQL, is that more or less correct?
avatar
DrakeFox: After that I spent an hour trying to get my data-access library to compile with it. Intellisense knew about it. All seemed good.
Yet whenever I compiled I got an error that the namespace was not found, even though the .dll was referenced and contained the namespace.

In the end it turned out the library was compiled .NET 4.5, executable was compiled .NET 4.0 -_-
I did something similar today. I spent a good two hours chasing a non-existant DB access problem. It turned out that the mapping assembly I'd deployed was an older version from before I even added the DB calls to the code. All of my projects have a post-build event which copies the compiled assembly to a specific folder, and every time you test a map in Visual Studio, it compiles the assembly first. As it turns out however, the configured build events are only executed when you manually build a project, not when it is being built automatically as part of a test. I was not aware of this, so I neglected to check the timestamp on the assembly, since I assumed it must be the same assembly as last time I tested it. I was wrong :-(
avatar
DrakeFox: First I rewrote most of a class I wrote last week. Basically a hackish helper library to translate a tagged SQL statement accepted through a jQuery XmlHttpRequest, validating it and helping translate the tags to the actual table data fields, validating the input. It feels like an ugly hack, but short of having to rewrite my data-access layer or switching to an ORM for accepting complex seardh queries, I don't know how. Any good advice here?
avatar
Wishbone: Depends. What exactly is it you're trying to do? It sounds like you want to use an XML based syntax to make queries against a database by translating the XML into SQL, is that more or less correct?
Not quite. More I've got one .dll project for data access (Data classes and classes for fetching/saving) another project for a service doing monitoring of external data and updating the database as needed (through the .dll) and a third project using the same .dll to make a HTML/javascript user interface.

Should've likely gone with an ORM for it, though I still have distrust that an ORM is going to be optimal for some of the discovery code I'm doing. So instead I've written my own data layer.

Specific example was a quick-fetch option on the user interface. Enter a value hit submit. Server code will check if it's a pure int value, and if so treat it like a reference to a specific item returning that item. Otherwise it'll try to fetch a piece of equipment from the database where name = @input or serial = @input

So my options for that latter bit was to either update the data access .dll with a method for this specific use case, or to first make one query for name, then one separate query for serial, join the two results, removing any objects which might otherwise show up twice.
Also foresaw this might be an issue if I want to make more complex queries later. So my stupid idea was to allow the javascript or server handler to send a string array. First string being semi-SQL, the rest being the string values of the parameters. So in this case [ "[NAME=1] or [SERIAL=1]", inputField.value ], basically a tag being alias for the field you want, what kind of condition (= > < or so on) and the index of the array which contains the referenced value.
The helper would pick out the tags, parse the condition and check the value is actually present, then defer to a Data layer implemented interface to have it translate what the field means in context to that class' sql queries, and handle parsing and conversion of the string data to check it's valid for the given field.

When all tags are parsed the output is something to plop into a where clause with the proper table names, comparison and parameters in place so the data layer class can use that to build it's query.

The thought being sanitation of input happens in the class which knows the data storage and a class specifically built for sanitizing and generating SQL conditions, and it'd allow the user interface to create rather complex queries without me having to update the data layer every time I hit an edge case.

And I realise this is a completely horrible waste of time and breach of good coding practices. But short of going with an ORM tossing all the work on the synchronization service and pretty much letting the UI layer make the data queries (through the ORM) I know no other good pattern to solve an issue like this.
avatar
DrakeFox: Specific example was a quick-fetch option on the user interface. Enter a value hit submit. Server code will check if it's a pure int value, and if so treat it like a reference to a specific item returning that item. Otherwise it'll try to fetch a piece of equipment from the database where name = @input or serial = @input
It sounds like what you're actually trying to do is making a search engine, trying to guess what the user is looking for.

This database you're working with, do you have control of it or can you not make changes to it? Because if I were to do something like that, I would probably use a stored procedure (or a whole series of them) tailored for the purpose rather than trying to generate a single all-purpose query in an assembly.
avatar
DrakeFox: Specific example was a quick-fetch option on the user interface. Enter a value hit submit. Server code will check if it's a pure int value, and if so treat it like a reference to a specific item returning that item. Otherwise it'll try to fetch a piece of equipment from the database where name = @input or serial = @input
avatar
Wishbone: It sounds like what you're actually trying to do is making a search engine, trying to guess what the user is looking for.

This database you're working with, do you have control of it or can you not make changes to it? Because if I were to do something like that, I would probably use a stored procedure (or a whole series of them) tailored for the purpose rather than trying to generate a single all-purpose query in an assembly.
Yeah I've got control of the database. And you're right, I should've probably leaned on stored procedures.
low rated
I just thought of a problem that isn't as simple as it looks; shuffling a deck of cards. It sounds easy; just randomly pick cards until you have a suitable deck?

However, there are some constraints I will impose:

1. Every possible deck must be generatable. A typical PRNG does not have a long enough period to allow this. (For the solution to count, it must be possible to prove this mathematically.)

2. The shuffling must be reasonably fast. Using /dev/random on a Linux system is not suitable because entropy will run out before the deck is shuffled. /dev/urandom isn't exactly suitable as some deck shuffles would require a lot of time to generate, as the PRNG would not have enough randomness.

Under these constraints, is there a good solution?

Edit: I could add a third constraint: The solution must not depend on an external source of entropy.
Post edited December 01, 2015 by dtgreene
avatar
dtgreene: I just thought of a problem that isn't as simple as it looks; shuffling a deck of cards. It sounds easy; just randomly pick cards until you have a suitable deck?

However, there are some constraints I will impose:

1. Every possible deck must be generatable. A typical PRNG does not have a long enough period to allow this. (For the solution to count, it must be possible to prove this mathematically.)

2. The shuffling must be reasonably fast. Using /dev/random on a Linux system is not suitable because entropy will run out before the deck is shuffled. /dev/urandom isn't exactly suitable as some deck shuffles would require a lot of time to generate, as the PRNG would not have enough randomness.

Under these constraints, is there a good solution?

Edit: I could add a third constraint: The solution must not depend on an external source of entropy.
If you take the Factorial of 52, you'll get the Max number of combinations an actual deck can be generated with. Using this knowledge, all you have to do is randomly generate a number at that point from 1 to the Max number and you'll quickly and easily decode every single card pulled form that particular combination. (about 74-76 bits).

Now as for if any particular PRNG can get every combination possible is a bit of a question. Supposedly there's one called the twister which will work (could generate a google of random numbers before repeating). I created a PRNG a while back based on using encryption to create randomness (although unlikely you'd use that).