Top Questions on Stack Overflow

List of Tags
655
Matt Sheppard

What's the best way of checking if an object property in JavaScript is undefined?

Sorry, I initially said variable rather than object property. I believe the same == undefined approach doesn't work there.

Answered By: Erwin ( 721)

Use:

if (typeof something === "undefined") 
   alert("something is undefined");
654
Allain Lalonde

Should be trivial, and it might even be in the help, but I can't figure out how to navigate it.

Answered By: Greg Hewgill ( 755)

Use the > command. To indent 5 lines, 5>>. To mark a block of lines and indent it, Vjj> to indent 3 lines (vim only). To indent a curly-braces block, put your cursor on one of the curly braces and use >%.

If you’re copying blocks of text around and need to align the indent of a block in its new location, use ]p instead of just p. This aligns the pasted block with the surrounding text.

Also, the shiftwidth setting allows you to control how many spaces to indent.

653
knaser

I know it is possible to match for the word and using tools options reverse the match. (eg. by grep -v) However I want to know if it is possible using regular expressions to match lines which does not contain a specific word, say hede?

Input:

Hoho
Hihi
Haha
hede

# grep "Regex for do not contain hede" Input

Output:

Hoho
Hihi
Haha
Answered By: Bart Kiers ( 1105)

The fact that regex doesn't support inverse matching is not entirely true. You can mimic this behavior by using negative look-arounds:

^((?!hede).)*$

The regex above will match any string, or line without a line break, not containing the (sub) string 'hede'. As mentioned, this is not something regex is "good" at (or should do), but still, it is possible.

And if you need to match line break chars as well, use the DOT-ALL modifier (the trialing s in the following pattern):

/^((?!hede).)*$/s

or use it inline:

/(?s)^((?!hede).)*$/

(where the /.../ are the regex delimiters, ie, not part of the pattern)

If the DOT-ALL modifier is not available, you can mimic the same behavior with the character class [\s\S]:

/^((?!hede)[\s\S])*$/

Explanation

A string is just a list of n characters. Before, and after each character, there's an empty string. So a list of n characters will have n+1 empty strings. Consider the string "ABhedeCD":

    +--+---+--+---+--+---+--+---+--+---+--+---+--+---+--+---+--+
S = |e1| A |e2| B |e3| h |e4| e |e5| d |e6| e |e7| C |e8| D |e9|
    +--+---+--+---+--+---+--+---+--+---+--+---+--+---+--+---+--+

index    0      1      2      3      4      5      6      7

where the e's are the empty strings. The regex (?!hede). looks ahead to see if there's no substring "hede" to be seen, and if that is the case (so something else is seen), then the . (dot) will match any character except a line break. Look-arounds are also called zero-width-assertions because they don't consume any characters. They only assert/validate something.

So, in my example, every empty string is first validated to see if there's no "hede" up ahead, before a character is consumed by the . (dot). The regex (?!hede). will do that only once, so it is wrapped in a group, and repeated zero or more times: ((?!hede).)*. Finally, the start- and end-of-input are anchored to make sure the entire input is consumed: ^((?!hede).)*$

As you can see, the input "ABhedeCD" will fail because on e3, the regex (?!hede) fails (there is "hede" up ahead!).

644
David Murdoch

Chrome supports the placeholder attribute on input[type=text] elements (others probably do too).

But the following CSS doesn't do diddly squat to the placeholder's value:

CSS:

input[placeholder], [placeholder], *[placeholder] {
   color:red !important;
}

HTML:

<input type="text" placeholder="Value" />

Value will still remain grey instead of red.

Is there a way to change the color of the placeholder text?

p.s. I'm already using the jQuery placeholder plugin for the browsers that don't support the placeholder attribute natively.

Answered By: toscho ( 1114)

Implementation

There are three different implementations: pseudo-elements, pseudo-classes, and nothing.

IE up to version 9 and Opera up to version 12 do not support any CSS selector for placeholders.

The discussion about the best implementation is still going on. Note the pseudo-elements act like real elements in the Shadow DOM. A padding on an input will not get the same background color as the pseudo-element.

CSS selectors

User agents are required to ignore a rule with an unknown selector. See Selectors Level 3:

a group of selectors containing an invalid selector is invalid.

So we need separate rules for each browser. Otherwise the whole group would be ignored by all browsers.

::-webkit-input-placeholder { /* WebKit browsers */
    color:    #999;
}
:-moz-placeholder { /* Mozilla Firefox 4 to 18 */
    color:    #999;
}
::-moz-placeholder { /* Mozilla Firefox 19+ */
    color:    #999;
}
:-ms-input-placeholder { /* Internet Explorer 10+ */
    color:    #999;
}

Usage notes

  • Be careful to avoid bad contrasts.
  • Note that placeholder text is just cut off if it doesn’t fit – size your input elements in em and test them with big minimum font size settings. Don’t forget translations: some languages need more room for the same word.
  • Browsers with HTML support for placeholder but without CSS support for that (like Opera) should be tested too.
  • Some browsers use additional default CSS for some input types (email, search). These might affect the rendering in unexpected ways. Use the properties -webkit-appearance and -moz-appearance to change that. Example:

    [type="search"] {
        -moz-appearance:    textfield;
        -webkit-appearance: textfield;
        appearance: textfield;
    }
    
643
git
Readonly

How do you delete untracked files from your git working copy?

Answered By: Andreas Ericsson ( 903)
git clean -f

If you want to also remove directories, run git clean -f -d.

If you just want to remove ignored files, run git clean -f -X.

If you want to remove ignored as well as non-ignored files, run git clean -f -x.

Note the case difference on the X for the two latter commands.

Unless you specify -f and clean.requireForce is set to "true" (the default) in your configuration, nothing will actually happen, with a recent enough version of git.

Note that as of git-1.6.0, the dashed style of writing git commands (ie, git-clean instead of git clean) is obsoleted.

See the git-clean docs for more information.

I am doing some numerical optimization on a scientific application. One thing I noticed is that GCC will optimize the call pow(a,2) by compiling it into a*a, but the call pow(a,6) is not optimized and will actually call the library function pow, which greatly slows down the performance. (In contrast, Intel C++ Compiler, executable icc, will eliminate the library call for pow(a,6).)

What I am curious about is that when I replaced pow(a,6) with a*a*a*a*a*a using GCC 4.5.1 and options "-O3 -lm -funroll-loops -msse4", it uses 5 mulsd instructions:

movapd  %xmm14, %xmm13
mulsd   %xmm14, %xmm13
mulsd   %xmm14, %xmm13
mulsd   %xmm14, %xmm13
mulsd   %xmm14, %xmm13
mulsd   %xmm14, %xmm13

while if I write (a*a*a)*(a*a*a), it will produce

movapd  %xmm14, %xmm13
mulsd   %xmm14, %xmm13
mulsd   %xmm14, %xmm13
mulsd   %xmm13, %xmm13

which reduces the number of multiply instructions to 3. icc has similar behavior.

Why do compilers not recognize this optimization trick?

Answered By: Lambdageek ( 1069)

Because Floating Point Math is not Associative. The way you group the operands in floating point multiplication has an effect on the numerical accuracy of the answer.

As a result, most compilers are very conservative about reordering floating point calculations unless they can be sure that the answer will stay the same, or unless you tell them you don't care about numerical accuracy. For example: the -ffast-math option of gcc.

What is the difference between INNER JOIN and OUTER JOIN?

Answered By: Mark Harrison ( 1084)

Assuming you're joining on columns with no duplicates, which is by far the most common case:

  • An inner join of A and B gives the result of A intersect B, i.e. the inner part of a venn diagram intersection.

  • An outer join of A and B gives the results of A union B, i.e. the outer parts of a venn diagram union.

Examples

Suppose you have two Tables, with a single column each, and data as follows:

A    B
-    -
1    3
2    4
3    5
4    6

Note that (1,2) are unique to A, (3,4) are common, and (5,6) are unique to B.

Inner join

An inner join using either of the equivalent queries gives the intersection of the two tables, i.e. the two rows they have in common.

select * from a INNER JOIN b on a.a = b.b;
select a.*,b.*  from a,b where a.a = b.b;

a | b
--+--
3 | 3
4 | 4

Left outer join

A left outer join will give all rows in A, plus any common rows in B.

select * from a LEFT OUTER JOIN b on a.a = b.b;
select a.*,b.*  from a,b where a.a = b.b(+);

a |  b  
--+-----
1 | null
2 | null
3 |    3
4 |    4

Full outer join

A full outer join will give you the union of A and B, i.e. All the rows in A and all the rows in B. If something in A doesn't have a corresponding datum in B, then the B portion is null, and vice versa.

select * from a FULL OUTER JOIN b on a.a = b.b;

 a   |  b  
-----+-----
   1 | null
   2 | null
   3 |    3
   4 |    4
null |    6
null |    5
635
johnstok

Say I create an object thus:

var myJSONObject =
        {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"};

What is the best way to remove the property 'regex'? i.e. I would like to end up with myJSONObject such that:

myJSONObject ==
        {"ircEvent": "PRIVMSG", "method": "newURI"};

Thanks.

Answered By: nickf ( 935)

like this:

delete myJSONObject.regex;
// or,
delete myJSONObject['regex'];
// or,
var prop = "regex";
delete myJSONObject[prop];

Update: For anyone interested in reading more about it, kangax has written an incredibly in-depth blog post about the delete statement on his blog. Understanding delete. Highly recommended.

635
Darryl Hein

What is the best method in jQuery to add an additional row to a table as the last row?

Update

Is this acceptable:

$('#myTable').append('<tr><td>my data</td><td>more data</td></tr>');

Are there limitations to what you can add to a table like this (such as inputs, selects, number of rows)?

Answered By: Luke Bennett ( 611)

The approach you suggest is not guaranteed to give you the result you're looking for - what if you had a tbody for example:

<table id="myTable">
  <tbody>
    <tr>...</tr>
    <tr>...</tr>
  </tbody>
</table>

You would end up with the following:

<table id="myTable">
  <tbody>
    <tr>...</tr>
    <tr>...</tr>
  </tbody>
  <tr>...</tr>
</table>

I would therefore recommend this approach instead:

$('#myTable tr:last').after('<tr>...</tr><tr>...</tr>');

You can include anything within the after() method as long as it's valid HTML, including multiple rows as per the example above.

Update: Revisiting this answer following recent activity with this question. eyelidlessness makes a good comment that there will always be a tbody in the DOM; this is true, but only if there is at least one row. If you have no rows, there will be no tbody unless you have specified one yourself.

DaRKoN_ suggests appending to the tbody rather than adding content after the last tr. This gets around the issue of having no rows, but still isn't bulletproof as you could theoretically have multiple tbody elements and the row would get added to each of them.

Weighing everything up, I'm not sure there is a single one-line solution that accounts for every single possible scenario. You will need to make sure the jQuery code tallies with your markup.

I think the safest solution is probably to ensure your table always includes at least one tbody in your markup, even if it has no rows. On this basis, you can use the following which will work however many rows you have (and also account for multiple tbody elements):

$('#myTable > tbody:last').append('<tr>...</tr><tr>...</tr>');
620
brad

What is the most concise and efficient way to find out if a JavaScript array contains an obj?

This is the only way I know to do it:

contains(a, obj) {
    for (var i = 0; i < a.length; i++) {
        if (a[i] === obj) {
            return true;
        }
    }
    return false;
}

Is there a better and more concise way to accomplish this?

This is very closely related to Stack Overflow question Best way to find an item in a JavaScript Array? which addresses finding objects in an array using indexOf.

Answered By: codeape ( 1021)

Modern browsers have Array#indexOf, which does exactly that; this is in the new(ish) ECMAScript 5th edition specification, but it has been in several browsers for years. Older browsers can be supported using the code listed in the "compatibility" section at the bottom of that page.

jQuery has a utility function for this:

$.inArray(value, array)

It returns the index of a value in an array. It returns -1 if the array does not contain the value.

jQuery has several useful utility functions.

An excellent JavaScript utility library is underscore.js:

Some other frameworks:

Notice how some frameworks implement this as a function. While other frameworks add the function to the array prototype.

Languages that compile to javascript

In coffeescript, the in operator is the equivalent of contains:

a = [1, 2, 3, 4]
alert(2 in a)

Dart:

var mylist = [1, 2, 3];
assert(mylist.contains(1));
assert(mylist.indexOf(1) == 0);