SyntaxFix.com - Programming Questions & Answers Hub For Beginners


Some Of The Best Answers From Latest Asked Questions

Operation must use an updatable query. (Error 3073) Microsoft Access

Since Jet 4, all queries that have a join to a SQL statement that summarizes data will be non-updatable. You aren't using a JOIN, but the WHERE clause is exactly equivalent to a join, and thus, the Jet query optimizer treats it the same way it treats a join.

I'm afraid you're out of luck without a temp table, though maybe somebody with greater Jet SQL knowledge than I can come up with a workaround.

BTW, it might have been updatable in Jet 3.5 (Access 97), as a whole lot of queries were updatable then that became non-updatable when upgraded to Jet 4.

--

Is there a simple JavaScript slider?

Here is another light JavaScript Slider that seems to fit your needs.

NOT IN vs NOT EXISTS

Actually, I believe this would be the fastest:

SELECT ProductID, ProductName 
    FROM Northwind..Products p  
          outer join Northwind..[Order Details] od on p.ProductId = od.ProductId)
WHERE od.ProductId is null

Detecting Back Button/Hash Change in URL

HTML5 has included a much better solution than using hashchange which is the HTML5 State Management APIs - https://developer.mozilla.org/en/DOM/Manipulating_the_browser_history - they allow you to change the url of the page, without needing to use hashes!

Though the HTML5 State Functionality is only available to HTML5 Browsers. So you probably want to use something like History.js which provides a backwards compatible experience to HTML4 Browsers (via hashes, but still supports data and titles as well as the replaceState functionality).

You can read more about it here: https://github.com/browserstate/History.js

Div 100% height works on Firefox but not in IE

I don't think IE supports the use of auto for setting height / width, so you could try giving this a numeric value (like Jarett suggests).

Also, it doesn't look like you are clearing your floats properly. Try adding this to your CSS for #container:

#container {
    height:100%;
    width:100%;
    overflow:hidden;
    /* for IE */
    zoom:1;
}

Detecting when a div's height changes using jQuery

This is how I recently handled this problem:

$('#your-resizing-div').bind('getheight', function() {
    $('#your-resizing-div').height();
});

function your_function_to_load_content() {
    /*whatever your thing does*/
    $('#your-resizing-div').trigger('getheight');
}

I know I'm a few years late to the party, just think my answer may help some people in the future, without having to download any plugins.

Embedding JavaScript engine into .NET

i believe all the major opensource JS engines (JavaScriptCore, SpiderMonkey, V8, and KJS) provide embedding APIs. The only one I am actually directly familiar with is JavaScriptCore (which is name of the JS engine the SquirrelFish lives in) which provides a pure C API. If memory serves (it's been a while since i used .NET) .NET has fairly good support for linking in C API's.

I'm honestly not sure what the API's for the other engines are like, but I do know that they all provide them.

That said, depending on your purposes JScript.NET may be best, as all of these other engines will require you to include them with your app, as JSC is the only one that actually ships with an OS, but that OS is MacOS :D

Best way to define private methods for a class in Objective-C

There isn't really a "private method" in Objective-C, if the runtime can work out which implementation to use it will do it. But that's not to say that there aren't methods which aren't part of the documented interface. For those methods I think that a category is fine. Rather than putting the @interface at the top of the .m file like your point 2, I'd put it into its own .h file. A convention I follow (and have seen elsewhere, I think it's an Apple convention as Xcode now gives automatic support for it) is to name such a file after its class and category with a + separating them, so @interface GLObject (PrivateMethods) can be found in GLObject+PrivateMethods.h. The reason for providing the header file is so that you can import it in your unit test classes :-).

By the way, as far as implementing/defining methods near the end of the .m file is concerned, you can do that with a category by implementing the category at the bottom of the .m file:

@implementation GLObject(PrivateMethods)
- (void)secretFeature;
@end

or with a class extension (the thing you call an "empty category"), just define those methods last. Objective-C methods can be defined and used in any order in the implementation, so there's nothing to stop you putting the "private" methods at the end of the file.

Even with class extensions I will often create a separate header (GLObject+Extension.h) so that I can use those methods if required, mimicking "friend" or "protected" visibility.

Since this answer was originally written, the clang compiler has started doing two passes for Objective-C methods. This means you can avoid declaring your "private" methods completely, and whether they're above or below the calling site they'll be found by the compiler.

What is the difference between g++ and gcc?

What is the difference between g++ and gcc?

gcc has evolved from a single language "GNU C Compiler" to be a multi-language "GNU Compiler Collection". The term "GNU C Compiler" is still used sometimes in the context of C programming.

The g++ is the C++ compiler for the GNU Compiler Collection. Like gnat is the Ada compiler for gcc. see Using the GNU Compiler Collection (GCC)

For example, the Ubuntu 16.04 and 18.04 man g++ command returns the GCC(1) manual page.

The Ubuntu 16.04 and 18.04 man gcc states that ...

g++ accepts mostly the same options as gcc

and that the default ...

... use of gcc does not add the C++ library. g++ is a program that calls GCC and automatically specifies linking against the C++ library. It treats .c, .h and .i files as C++ source files instead of C source files unless -x is used. This program is also useful when precompiling a C header file with a .h extension for use in C++ compilations.

Search the gcc man pages for more details on the option variances between gcc and g++.

Which one should be used for general c++ development?

Technically, either gcc or g++ can be used for general C++ development with applicable option settings. However, the g++ default behavior is naturally aligned to a C++ development.

The Ubuntu 18.04 'gcc' man page added, and Ubuntu 20.04 continues to have, the following paragraph:

The usual way to run GCC is to run the executable called gcc, or machine-gcc when cross-compiling, or machine-gcc-version to run a specific version of GCC. When you compile C++ programs, you should invoke GCC as g++ instead.

How do I split a multi-line string into multiple lines?

inputString.splitlines()

Will give you a list with each item, the splitlines() method is designed to split each line into a list element.

Is there a regular expression to detect a valid regular expression?

No, if you are strictly speaking about regular expressions and not including some regular expression implementations that are actually context free grammars.

There is one limitation of regular expressions which makes it impossible to write a regex that matches all and only regexes. You cannot match implementations such as braces which are paired. Regexes use many such constructs, let's take [] as an example. Whenever there is an [ there must be a matching ], which is simple enough for a regex "\[.*\]".

What makes it impossible for regexes is that they can be nested. How can you write a regex that matches nested brackets? The answer is you can't without an infinitely long regex. You can match any number of nested parenthesis through brute force but you can't ever match an arbitrarily long set of nested brackets.

This capability is often referred to as counting, because you're counting the depth of the nesting. A regex by definition does not have the capability to count.


I ended up writing "Regular Expression Limitations" about this.

How can I find the method that called the current method?

In general, you can use the System.Diagnostics.StackTrace class to get a System.Diagnostics.StackFrame, and then use the GetMethod() method to get a System.Reflection.MethodBase object. However, there are some caveats to this approach:

  1. It represents the runtime stack -- optimizations could inline a method, and you will not see that method in the stack trace.
  2. It will not show any native frames, so if there's even a chance your method is being called by a native method, this will not work, and there is in-fact no currently available way to do it.

(NOTE: I am just expanding on the answer provided by Firas Assad.)

Is there a destructor for Java?

If it's just memory you are worried about, don't. Just trust the GC it does a decent job. I actually saw something about it being so efficient that it could be better for performance to create heaps of tiny objects than to utilize large arrays in some instances.

jquery-ui-dialog - How to hook into dialog close event

$("#dialog").dialog({
    autoOpen: false,
    resizable: false,
    width: 400,
    height: 140,
    modal: true, 
    buttons: {
        "SUBMIT": function() { 
        $("form").submit();
    }, 
        "CANCEL": function() { 
        $(this).dialog("close");
    } 
    },
    close: function() {
      alert('close');
    }
});

What is the best way to get all the divisors of a number?

To expand on what Shimi has said, you should only be running your loop from 1 to the square root of n. Then to find the pair, do n / i, and this will cover the whole problem space.

As was also noted, this is a NP, or 'difficult' problem. Exhaustive search, the way you are doing it, is about as good as it gets for guaranteed answers. This fact is used by encryption algorithms and the like to help secure them. If someone were to solve this problem, most if not all of our current 'secure' communication would be rendered insecure.

Python code:

import math

def divisorGenerator(n):
    large_divisors = []
    for i in xrange(1, int(math.sqrt(n) + 1)):
        if n % i == 0:
            yield i
            if i*i != n:
                large_divisors.append(n / i)
    for divisor in reversed(large_divisors):
        yield divisor

print list(divisorGenerator(100))

Which should output a list like:

[1, 2, 4, 5, 10, 20, 25, 50, 100]

Is there a command to refresh environment variables from the command prompt in Windows?

Edit: this only works if the environment changes you're doing are as a result of running a batch file.

If a batch file begins with SETLOCAL then it will always unravel back to your original environment on exit even if you forget to call ENDLOCAL before the batch exits, or if it aborts unexpectedly.

Almost every batch file I write begins with SETLOCAL since in most cases I don't want the side-effects of environment changes to remain. In cases where I do want certain environment variable changes to propagate outside the batch file then my last ENDLOCAL looks like this:

ENDLOCAL & (
  SET RESULT1=%RESULT1%
  SET RESULT2=%RESULT2%
)

Find out which remote branch a local branch is tracking

I use EasyGit (a.k.a. "eg") as a super lightweight wrapper on top of (or along side of) Git. EasyGit has an "info" subcommand that gives you all kinds of super useful information, including the current branches remote tracking branch. Here's an example (where the current branch name is "foo"):

pknotz@s883422: (foo) ~/workspace/bd
$ eg info
Total commits:      175
Local repository: .git
Named remote repositories: (name -> location)
  origin -> git://sahp7577/home/pknotz/bd.git
Current branch: foo
  Cryptographic checksum (sha1sum): bd248d1de7d759eb48e8b5ff3bfb3bb0eca4c5bf
  Default pull/push repository: origin
  Default pull/push options:
    branch.foo.remote = origin
    branch.foo.merge = refs/heads/aal_devel_1
  Number of contributors:        3
  Number of files:       28
  Number of directories:       20
  Biggest file size, in bytes: 32473 (pygooglechart-0.2.0/COPYING)
  Commits:       62

Authenticating in PHP using LDAP through Active Directory

I like the Zend_Ldap Class, you can use only this class in your project, without the Zend Framework.

RegEx: Grabbing values between quotation marks

This version

  • accounts for escaped quotes
  • controls backtracking

    /(["'])((?:(?!\1)[^\\]|(?:\\\\)*\\[^\\])*)\1/
    

How can I merge properties of two JavaScript objects dynamically?

I extended David Coallier's method:

  • Added the possibility to merge multiple objects
  • Supports deep objects
  • override parameter (that's detected if the last parameter is a boolean)

If override is false, no property gets overridden but new properties will be added.

Usage: obj.merge(merges... [, override]);

Here is my code:

Object.defineProperty(Object.prototype, "merge", {
    enumerable: false,
    value: function () {
        var override = true,
            dest = this,
            len = arguments.length,
            props, merge, i, from;

        if (typeof(arguments[arguments.length - 1]) === "boolean") {
            override = arguments[arguments.length - 1];
            len = arguments.length - 1;
        }

        for (i = 0; i < len; i++) {
            from = arguments[i];
            if (from != null) {
                Object.getOwnPropertyNames(from).forEach(function (name) {
                    var descriptor;

                    // nesting
                    if ((typeof(dest[name]) === "object" || typeof(dest[name]) === "undefined")
                            && typeof(from[name]) === "object") {

                        // ensure proper types (Array rsp Object)
                        if (typeof(dest[name]) === "undefined") {
                            dest[name] = Array.isArray(from[name]) ? [] : {};
                        }
                        if (override) {
                            if (!Array.isArray(dest[name]) && Array.isArray(from[name])) {
                                dest[name] = [];
                            }
                            else if (Array.isArray(dest[name]) && !Array.isArray(from[name])) {
                                dest[name] = {};
                            }
                        }
                        dest[name].merge(from[name], override);
                    } 

                    // flat properties
                    else if ((name in dest && override) || !(name in dest)) {
                        descriptor = Object.getOwnPropertyDescriptor(from, name);
                        if (descriptor.configurable) {
                            Object.defineProperty(dest, name, descriptor);
                        }
                    }
                });
            }
        }
        return this;
    }
});

Examples and TestCases:

function clone (obj) {
    return JSON.parse(JSON.stringify(obj));
}
var obj = {
    name : "trick",
    value : "value"
};

var mergeObj = {
    name : "truck",
    value2 : "value2"
};

var mergeObj2 = {
    name : "track",
    value : "mergeObj2",
    value2 : "value2-mergeObj2",
    value3 : "value3"
};

assertTrue("Standard", clone(obj).merge(mergeObj).equals({
    name : "truck",
    value : "value",
    value2 : "value2"
}));

assertTrue("Standard no Override", clone(obj).merge(mergeObj, false).equals({
    name : "trick",
    value : "value",
    value2 : "value2"
}));

assertTrue("Multiple", clone(obj).merge(mergeObj, mergeObj2).equals({
    name : "track",
    value : "mergeObj2",
    value2 : "value2-mergeObj2",
    value3 : "value3"
}));

assertTrue("Multiple no Override", clone(obj).merge(mergeObj, mergeObj2, false).equals({
    name : "trick",
    value : "value",
    value2 : "value2",
    value3 : "value3"
}));

var deep = {
    first : {
        name : "trick",
        val : "value"
    },
    second : {
        foo : "bar"
    }
};

var deepMerge = {
    first : {
        name : "track",
        anotherVal : "wohoo"
    },
    second : {
        foo : "baz",
        bar : "bam"
    },
    v : "on first layer"
};

assertTrue("Deep merges", clone(deep).merge(deepMerge).equals({
    first : {
        name : "track",
        val : "value",
        anotherVal : "wohoo"
    },
    second : {
        foo : "baz",
        bar : "bam"
    },
    v : "on first layer"
}));

assertTrue("Deep merges no override", clone(deep).merge(deepMerge, false).equals({
    first : {
        name : "trick",
        val : "value",
        anotherVal : "wohoo"
    },
    second : {
        foo : "bar",
        bar : "bam"
    },
    v : "on first layer"
}));

var obj1 = {a: 1, b: "hello"};
obj1.merge({c: 3});
assertTrue(obj1.equals({a: 1, b: "hello", c: 3}));

obj1.merge({a: 2, b: "mom", d: "new property"}, false);
assertTrue(obj1.equals({a: 1, b: "hello", c: 3, d: "new property"}));

var obj2 = {};
obj2.merge({a: 1}, {b: 2}, {a: 3});
assertTrue(obj2.equals({a: 3, b: 2}));

var a = [];
var b = [1, [2, 3], 4];
a.merge(b);
assertEquals(1, a[0]);
assertEquals([2, 3], a[1]);
assertEquals(4, a[2]);


var o1 = {};
var o2 = {a: 1, b: {c: 2}};
var o3 = {d: 3};
o1.merge(o2, o3);
assertTrue(o1.equals({a: 1, b: {c: 2}, d: 3}));
o1.b.c = 99;
assertTrue(o2.equals({a: 1, b: {c: 2}}));

// checking types with arrays and objects
var bo;
a = [];
bo = [1, {0:2, 1:3}, 4];
b = [1, [2, 3], 4];

a.merge(b);
assertTrue("Array stays Array?", Array.isArray(a[1]));

a = [];
a.merge(bo);
assertTrue("Object stays Object?", !Array.isArray(a[1]));

a = [];
a.merge(b);
a.merge(bo);
assertTrue("Object overrides Array", !Array.isArray(a[1]));

a = [];
a.merge(b);
a.merge(bo, false);
assertTrue("Object does not override Array", Array.isArray(a[1]));

a = [];
a.merge(bo);
a.merge(b);
assertTrue("Array overrides Object", Array.isArray(a[1]));

a = [];
a.merge(bo);
a.merge(b, false);
assertTrue("Array does not override Object", !Array.isArray(a[1]));

My equals method can be found here: Object comparison in JavaScript

Java maximum memory on Windows XP

Oracle JRockit, which can handle a non-contiguous heap, can have a Java heap size of 2.85 GB on Windows 2003/XP with the /3GB switch. It seems that fragmentation can have quite an impact on how large a Java heap can be.

Add table row in jQuery

My solution:

//Adds a new table row
$.fn.addNewRow = function (rowId) {
    $(this).find('tbody').append('<tr id="' + rowId + '"> </tr>');
};

usage:

$('#Table').addNewRow(id1);

Dynamic SELECT TOP @var In SQL Server

In x0n's example, it should be:

SET ROWCOUNT @top

SELECT * from sometable

SET ROWCOUNT 0

http://msdn.microsoft.com/en-us/library/ms188774.aspx

SQL Server Express 2008 Install Side-by-side w/ SQL 2005 Express Fails

N.B. These notes are for SQL Server Express 2008 R2 (so Microsoft still haven't made this any easier). I also realise that I complicated things by installing 32-bit SQL Server Express 2005 and 64-bit SQL Server Express 2008.

I followed the steps by Josh Hinman above. Uninstalling the SQL Server Express 2005 "Workstation Components" was not enough. I required an uninstall of the 2005 Management Studio as well.

I also tried the Upgrade route that Josh Hinman suggested by clicking on the 'Upgrade from SQL Server 2000, SQL Server 2005 or SQL Server 2008'. This route never gave me the option of installing the components side-by-side it just went straight through the process of upgrading from 2005 to 2008. It completed successfully - but hadn't actually done anything. Thankfully though it hadn't harmed any existing database instances. So be warned trying that route.

(Built-in) way in JavaScript to check if a string is a valid number

I like the simplicity of this.

Number.isNaN(Number(value))

The above is regular Javascript, but I'm using this in conjunction with a typescript typeguard for smart type checking. This is very useful for the typescript compiler to give you correct intellisense, and no type errors.

Typescript typeguards

isNotNumber(value: string | number): value is string {
    return Number.isNaN(Number(this.smartImageWidth));
}
isNumber(value: string | number): value is number {
    return Number.isNaN(Number(this.smartImageWidth)) === false;
}

Let's say you have a property width which is number | string. You may want to do logic based on whether or not it's a string.

var width: number|string;
width = "100vw";

if (isNotNumber(width)) 
{
    // the compiler knows that width here must be a string
    if (width.endsWith('vw')) 
    {
        // we have a 'width' such as 100vw
    } 
}
else 
{
    // the compiler is smart and knows width here must be number
    var doubleWidth = width * 2;    
}

The typeguard is smart enough to constrain the type of width within the if statement to be ONLY string. This permits the compiler to allow width.endsWith(...) which it wouldn't allow if the type was string | number.

You can call the typeguard whatever you want isNotNumber, isNumber, isString, isNotString but I think isString is kind of ambiguous and harder to read.

What are named pipes?

Inter-process communication (mostly) for Windows Applications. Similar to using sockets to communicate between applications in Unix.

MSDN

How to convert milliseconds into human readable form?

This is a method I wrote. It takes an integer milliseconds value and returns a human-readable String:

public String convertMS(int ms) {
    int seconds = (int) ((ms / 1000) % 60);
    int minutes = (int) (((ms / 1000) / 60) % 60);
    int hours = (int) ((((ms / 1000) / 60) / 60) % 24);

    String sec, min, hrs;
    if(seconds<10)  sec="0"+seconds;
    else            sec= ""+seconds;
    if(minutes<10)  min="0"+minutes;
    else            min= ""+minutes;
    if(hours<10)    hrs="0"+hours;
    else            hrs= ""+hours;

    if(hours == 0)  return min+":"+sec;
    else    return hrs+":"+min+":"+sec;

}

Should a retrieval method return 'null' or throw an exception when it can't produce the return value?

Exceptions should be exceptional. Return null if it is valid to return a null.

How do I get list of all tables in a database using TSQL?

select * from sysobjects where xtype='U'

How to edit CSS style of a div using C# in .NET

Add the runat="server" attribute to it so you have:

<div id="formSpinner" runat="server">
    <img src="images/spinner.gif">
    <p>Saving...</p>
</div>

That way you can access the class attribute by using:

formSpinner.Attributes["class"] = "classOfYourChoice";

It's also worth mentioning that the asp:Panel control is virtually synonymous (at least as far as rendered markup is concerned) with div, so you could also do:

<asp:Panel id="formSpinner" runat="server">
    <img src="images/spinner.gif">
    <p>Saving...</p>
</asp:Panel>

Which then enables you to write:

formSpinner.CssClass = "classOfYourChoice";

This gives you more defined access to the property and there are others that may, or may not, be of use to you.

Regex to match URL end-of-line or "/" character

/(.+)/(\d{4}-\d{2}-\d{2})-(\d+)(/.*)?$

1st Capturing Group (.+)

.+ matches any character (except for line terminators)

  • + Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)

2nd Capturing Group (\d{4}-\d{2}-\d{2})

\d{4} matches a digit (equal to [0-9])

  • {4} Quantifier — Matches exactly 4 times

- matches the character - literally (case sensitive)

\d{2} matches a digit (equal to [0-9])

  • {2} Quantifier — Matches exactly 2 times

- matches the character - literally (case sensitive)

\d{2} matches a digit (equal to [0-9])

  • {2} Quantifier — Matches exactly 2 times

- matches the character - literally (case sensitive)

3rd Capturing Group (\d+)

\d+ matches a digit (equal to [0-9])

  • + Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)

4th Capturing Group (.*)?

? Quantifier — Matches between zero and one times, as many times as possible, giving back as needed (greedy)

.* matches any character (except for line terminators)

  • * Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)

$ asserts position at the end of the string

SQL Server: Is it possible to insert into two tables at the same time?

If you want the actions to be more or less atomic, I would make sure to wrap them in a transaction. That way you can be sure both happened or both didn't happen as needed.

Django development IDE

Well, I've been using my own one. Recently they released an alpha version. Here it is at pfaide.com/.

How many parameters are too many?

One of Alan Perlis's well-known programming epigrams (recounted in ACM SIGPLAN Notices 17(9), September, 1982) states that "If you have a procedure with 10 parameters, you probably missed some."

How should strace be used?

Minimal runnable example

If a concept is not clear, there is a simpler example that you haven't seen that explains it.

In this case, that example is the Linux x86_64 assembly freestanding (no libc) hello world:

hello.S

.text
.global _start
_start:
    /* write */
    mov $1, %rax    /* syscall number */
    mov $1, %rdi    /* stdout */
    mov $msg, %rsi  /* buffer */
    mov $len, %rdx  /* buffer len */
    syscall

    /* exit */
    mov $60, %rax   /* exit status */
    mov $0, %rdi    /* syscall number */
    syscall
msg:
    .ascii "hello\n"
len = . - msg

GitHub upstream.

Assemble and run:

as -o hello.o hello.S
ld -o hello.out hello.o
./hello.out

Outputs the expected:

hello

Now let's use strace on that example:

env -i ASDF=qwer strace -o strace.log -s999 -v ./hello.out arg0 arg1
cat strace.log

We use:

strace.log now contains:

execve("./hello.out", ["./hello.out", "arg0", "arg1"], ["ASDF=qwer"]) = 0
write(1, "hello\n", 6)                  = 6
exit(0)                                 = ?
+++ exited with 0 +++

With such a minimal example, every single character of the output is self evident:

  • execve line: shows how strace executed hello.out, including CLI arguments and environment as documented at man execve

  • write line: shows the write system call that we made. 6 is the length of the string "hello\n".

    = 6 is the return value of the system call, which as documented in man 2 write is the number of bytes written.

  • exit line: shows the exit system call that we've made. There is no return value, since the program quit!

More complex examples

The application of strace is of course to see which system calls complex programs are actually doing to help debug / optimize your program.

Notably, most system calls that you are likely to encounter in Linux have glibc wrappers, many of them from POSIX.

Internally, the glibc wrappers use inline assembly more or less like this: How to invoke a system call via sysenter in inline assembly?

The next example you should study is a POSIX write hello world:

main.c

#define _XOPEN_SOURCE 700
#include <unistd.h>

int main(void) {
    char *msg = "hello\n";
    write(1, msg, 6);
    return 0;
}

Compile and run:

gcc -std=c99 -Wall -Wextra -pedantic -o main.out main.c
./main.out

This time, you will see that a bunch of system calls are being made by glibc before main to setup a nice environment for main.

This is because we are now not using a freestanding program, but rather a more common glibc program, which allows for libc functionality.

Then, at the every end, strace.log contains:

write(1, "hello\n", 6)                  = 6
exit_group(0)                           = ?
+++ exited with 0 +++

So we conclude that the write POSIX function uses, surprise!, the Linux write system call.

We also observe that return 0 leads to an exit_group call instead of exit. Ha, I didn't know about this one! This is why strace is so cool. man exit_group then explains:

This system call is equivalent to exit(2) except that it terminates not only the calling thread, but all threads in the calling process's thread group.

And here is another example where I studied which system call dlopen uses: https://unix.stackexchange.com/questions/226524/what-system-call-is-used-to-load-libraries-in-linux/462710#462710

Tested in Ubuntu 16.04, GCC 6.4.0, Linux kernel 4.4.0.

How do I rename a column in a database table using SQL?

You can use the following command to rename the column of any table in SQL Server:

exec sp_rename 'TableName.OldColumnName', 'New colunmName'

How to read the content of a file to a string in C?

If the file is text, and you want to get the text line by line, the easiest way is to use fgets().

char buffer[100];
FILE *fp = fopen("filename", "r");                 // do not use "rb"
while (fgets(buffer, sizeof(buffer), fp)) {
... do something
}
fclose(fp);

asp:TextBox ReadOnly=true or Enabled=false?

If a control is disabled it cannot be edited and its content is excluded when the form is submitted.

If a control is readonly it cannot be edited, but its content (if any) is still included with the submission.

What is the best way to delete a value from an array in Perl?

I think your solution is the simplest and most maintainable.

The rest of the post documents the difficulty of turning tests on elements into splice offsets. Thus, making it a more complete answer.

Look at the gyrations you have to go through to have an efficient (i.e. one-pass) algorithm to turn tests on list items into indexes. And it's not that intuitive at all.

sub array_remove ( \@& ) { 
    my ( $arr_ref, $test_block ) = @_;
    my $sp_start  = 0;
    my $sp_len    = 0;
    for ( my $inx = 0; $inx <= $#$arr_ref; $inx++ ) {
        local $_ = $arr_ref->[$inx];
        next unless $test_block->( $_ );
        if ( $sp_len > 0 && $inx > $sp_start + $sp_len ) {
            splice( @$arr_ref, $sp_start, $sp_len );
            $inx    = $inx - $sp_len;
            $sp_len = 0;
        }
        $sp_start = $inx if ++$sp_len == 1;
    }
    splice( @$arr_ref, $sp_start, $sp_len ) if $sp_len > 0;
    return;
}

Switch statement fallthrough in C#?

Just a quick note to add that the compiler for Xamarin actually got this wrong and it allows fallthrough. It has supposedly been fixed, but has not been released. Discovered this in some code that actually was falling through and the compiler did not complain.

Is there a "theirs" version of "git merge -s ours"?

I think what you actually want is:

git checkout -B mergeBranch branchB
git merge -s ours branchA
git checkout branchA
git merge mergeBranch
git branch -D mergeBranch

This seems clumsy, but it should work. The only think I really dislike about this solution is the git history will be confusing... But at least the history will be completely preserved and you won't need to do something special for deleted files.

How do I get a file extension in PHP?

The simplest way to get file extension in PHP is to use PHP's built-in function pathinfo.

$file_ext = pathinfo('your_file_name_here', PATHINFO_EXTENSION);
echo ($file_ext); // The output should be the extension of the file e.g., png, gif, or html

Using ALTER to drop a column if it exists in MySQL

Chase Seibert's answer works, but I'd add that if you have several schemata you want to alter the SELECT thus:

select * from information_schema.columns where table_schema in (select schema()) and table_name=...

How to check if PHP array is associative or sequential?

Could this be the solution?

  public static function isArrayAssociative(array $array) {
      reset($array);
      return !is_int(key($array));
  }

The caveat is obviously that the array cursor is reset but I'd say probably the function is used before the array is even traversed or used.

How to decrypt a password from SQL server?

You realise that you may be making a rod for your own back for the future. The pwdencrypt() and pwdcompare() are undocumented functions and may not behave the same in future versions of SQL Server.

Why not hash the password using a predictable algorithm such as SHA-2 or better before hitting the DB?

How to resolve a Java Rounding Double issue

To control the precision of floating point arithmetic, you should use java.math.BigDecimal. Read The need for BigDecimal by John Zukowski for more information.

Given your example, the last line would be as following using BigDecimal.

import java.math.BigDecimal;

BigDecimal premium = BigDecimal.valueOf("1586.6");
BigDecimal netToCompany = BigDecimal.valueOf("708.75");
BigDecimal commission = premium.subtract(netToCompany);
System.out.println(commission + " = " + premium + " - " + netToCompany);

This results in the following output.

877.85 = 1586.6 - 708.75

How do I abort the execution of a Python script?

You could put the body of your script into a function and then you could return from that function.

def main():
  done = True
  if done:
    return
    # quit/stop/exit
  else:
    # do other stuff

if __name__ == "__main__":
  #Run as main program
  main()

Clearing all cookies with JavaScript

I have some more sophisticated and OOP-oriented cookie control module. It also contains deleteAll method to clear all existing cookie. Make notice that this version of deleteAll method has setting path=/ that causes deleting of all cookies within current domain. If you need to delete cookies only from some scope you will have to upgrade this method my adding dynamic path parameter to this method.

There is main Cookie class:

import {Setter} from './Setter';

export class Cookie {
    /**
     * @param {string} key
     * @return {string|undefined}
     */
    static get(key) {
        key = key.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1');

        const regExp = new RegExp('(?:^|; )' + key + '=([^;]*)');
        const matches = document.cookie.match(regExp);

        return matches
            ? decodeURIComponent(matches[1])
            : undefined;
    }

    /**
     * @param {string} name
     */
    static delete(name) {
        this.set(name, '', { expires: -1 });
    }

    static deleteAll() {
        const cookies = document.cookie.split('; ');

        for (let cookie of cookies) {
            const index = cookie.indexOf('=');

            const name = ~index
                ? cookie.substr(0, index)
                : cookie;

            document.cookie = name + '=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/';
        }
    }

    /**
     * @param {string} name
     * @param {string|boolean} value
     * @param {{expires?:Date|string|number,path?:string,domain?:string,secure?:boolean}} opts
     */
    static set(name, value, opts = {}) {
        Setter.set(name, value, opts);
    }
}

Cookie setter method (Cookie.set) is rather complex so I decomposed it into other class. There is code of this one:

export class Setter {
    /**
     * @param {string} name
     * @param {string|boolean} value
     * @param {{expires?:Date|string|number,path?:string,domain?:string,secure?:boolean}} opts
     */
    static set(name, value, opts = {}) {
        value = Setter.prepareValue(value);
        opts = Setter.prepareOpts(opts);

        let updatedCookie = name + '=' + value;

        for (let i in opts) {
            if (!opts.hasOwnProperty(i)) continue;

            updatedCookie += '; ' + i;

            const value = opts[i];

            if (value !== true)
                updatedCookie += '=' + value;
        }

        document.cookie = updatedCookie;
    }

    /**
     * @param {string} value
     * @return {string}
     * @private
     */
    static prepareValue(value) {
        return encodeURIComponent(value);
    }

    /**
     * @param {{expires?:Date|string|number,path?:string,domain?:string,secure?:boolean}} opts
     * @private
     */
    static prepareOpts(opts = {}) {
        opts = Object.assign({}, opts);

        let {expires} = opts;

        if (typeof expires == 'number' && expires) {
            const date = new Date();

            date.setTime(date.getTime() + expires * 1000);

            expires = opts.expires = date;
        }

        if (expires && expires.toUTCString)
            opts.expires = expires.toUTCString();

        return opts;
    }
}

How to modify existing, unpushed commit messages?

On this question there are a lot of answers, but none of them explains in super detail how to change older commit messages using Vim. I was stuck trying to do this myself, so here I'll write down in detail how I did this especially for people who have no experience in Vim!

I wanted to change my five latest commits that I already pushed to the server. This is quite 'dangerous' because if someone else already pulled from this, you can mess things up by changing the commit messages. However, when you’re working on your own little branch and are sure no one pulled it you can change it like this:

Let's say you want to change your five latest commits, and then you type this in the terminal:

git rebase -i HEAD~5

*Where 5 is the number of commit messages you want to change (so if you want to change the 10th to last commit, you type in 10).

This command will get you into Vim there you can ‘edit’ your commit history. You’ll see your last five commits at the top like this:

pick <commit hash> commit message

Instead of pick you need to write reword. You can do this in Vim by typing in i. That makes you go in to insert mode. (You see that you’re in insert mode by the word INSERT at the bottom.) For the commits you want to change, type in reword instead of pick.

Then you need to save and quit this screen. You do that by first going in to ‘command-mode’ by pressing the Escbutton (you can check that you’re in command-mode if the word INSERT at the bottom has disappeared). Then you can type in a command by typing :. The command to save and quit is wq. So if you type in :wq you’re on the right track.

Then Vim will go over every commit message you want to reword, and here you can actually change the commit messages. You’ll do this by going into insert mode, changing the commit message, going into the command-mode, and save and quit. Do this five times and you’re out of Vim!

Then, if you already pushed your wrong commits, you need to git push --force to overwrite them. Remember that git push --force is quite a dangerous thing to do, so make sure that no one pulled from the server since you pushed your wrong commits!

Now you have changed your commit messages!

(As you see, I'm not that experienced in Vim, so if I used the wrong 'lingo' to explain what's happening, feel free to correct me!)

Multiple Indexes vs Multi-Column Indexes

The multi-column index can be used for queries referencing all the columns:

SELECT *
FROM TableName
WHERE Column1=1 AND Column2=2 AND Column3=3

This can be looked up directly using the multi-column index. On the other hand, at most one of the single-column index can be used (it would have to look up all records having Column1=1, and then check Column2 and Column3 in each of those).

Adding a JAR to an Eclipse Java library

You might also consider using a build tool like Maven to manage your dependencies. It is very easy to setup and helps manage those dependencies automatically in eclipse. Definitely worth the effort if you have a large project with a lot of external dependencies.

After submitting a POST form open a new window showing the result

Add

<form target="_blank" ...></form>

or

form.setAttribute("target", "_blank");

to your form's definition.

How to save picture to iPhone photo library?

The simplest way is:

UIImageWriteToSavedPhotosAlbum(myUIImage, nil, nil, nil);

For Swift, you can refer to Saving to the iOS photo library using swift

OnClick in Excel VBA

Clearly, there is no perfect answer. However, if you want to allow the user to

  1. select certain cells
  2. allow them to change those cells, and
  3. trap each click,even repeated clicks on the same cell,

then the easiest way seems to be to move the focus off the selected cell, so that clicking it will trigger a Select event.

One option is to move the focus as I suggested above, but this prevents cell editing. Another option is to extend the selection by one cell (left/right/up/down),because this permits editing of the original cell, but will trigger a Select event if that cell is clicked again on its own.

If you only wanted to trap selection of a single column of cells, you could insert a hidden column to the right, extend the selection to include the hidden cell to the right when the user clicked,and this gives you an editable cell which can be trapped every time it is clicked. The code is as follows

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
  'prevent Select event triggering again when we extend the selection below
  Application.EnableEvents = False
  Target.Resize(1, 2).Select
  Application.EnableEvents = True
End Sub

How do I find out if a column exists in a VB.Net DataRow

You can encapsulate your block of code with a try ... catch statement, and when you run your code, if the column doesn't exist it will throw an exception. You can then figure out what specific exception it throws and have it handle that specific exception in a different way if you so desire, such as returning "Column Not Found".

Minimum rights required to run a windows service as a domain account

Two ways:

  1. Edit the properties of the service and set the Log On user. The appropriate right will be automatically assigned.

  2. Set it manually: Go to Administrative Tools -> Local Security Policy -> Local Policies -> User Rights Assignment. Edit the item "Log on as a service" and add your domain user there.

How do you round a floating point number in Perl?

Negative numbers can add some quirks that people need to be aware of.

printf-style approaches give us correct numbers, but they can result in some odd displays. We have discovered that this method (in my opinion, stupidly) puts in a - sign whether or not it should or shouldn't. For example, -0.01 rounded to one decimal place returns a -0.0, rather than just 0. If you are going to do the printf style approach, and you know you want no decimal, use %d and not %f (when you need decimals, it's when the display gets wonky).

While it's correct and for math no big deal, for display it just looks weird showing something like "-0.0".

For the int method, negative numbers can change what you want as a result (though there are some arguments that can be made they are correct).

The int + 0.5 causes real issues with -negative numbers, unless you want it to work that way, but I imagine most people don't. -0.9 should probably round to -1, not 0. If you know that you want negative to be a ceiling rather than a floor then you can do it in one-liner, otherwise, you might want to use the int method with a minor modification (this obviously only works to get back whole numbers:

my $var = -9.1;
my $tmpRounded = int( abs($var) + 0.5));
my $finalRounded = $var >= 0 ? 0 + $tmpRounded : 0 - $tmpRounded;

PreparedStatement IN clause alternatives?

You can use Collections.nCopies to generate a collection of placeholders and join them using String.join:

List<String> params = getParams();
String placeHolders = String.join(",", Collections.nCopies(params.size(), "?"));
String sql = "select * from your_table where some_column in (" + placeHolders + ")";
try (   Connection connection = getConnection();
        PreparedStatement ps = connection.prepareStatement(sql)) {
    int i = 1;
    for (String param : params) {
        ps.setString(i++, param);
    }
    /*
     * Execute query/do stuff
     */
}

What is the proper way to re-throw an exception in C#?

The first preserves the original stack trace of the exception, the second one replaces it with the current location.

Therefore the first is BY FAR the better.

Multiple Inheritance in C#

In my own implementation I found that using classes/interfaces for MI, although "good form", tended to be a massive over complication since you need to set up all that multiple inheritance for only a few necessary function calls, and in my case, needed to be done literally dozens of times redundantly.

Instead it was easier to simply make static "functions that call functions that call functions" in different modular varieties as a sort of OOP replacement. The solution I was working on was the "spell system" for a RPG where effects need to heavily mix-and-match function calling to give an extreme variety of spells without re-writing code, much like the example seems to indicate.

Most of the functions can now be static because I don't necessarily need an instance for spell logic, whereas class inheritance can't even use virtual or abstract keywords while static. Interfaces can't use them at all.

Coding seems way faster and cleaner this way IMO. If you're just doing functions, and don't need inherited properties, use functions.

How do I check if an element is hidden in jQuery?

You can do this:

isHidden = function(element){
    return (element.style.display === "none");
};

if(isHidden($("element")) == true){
    // Something
}

log4j vs logback

Not exactly answering your question, but if you could move away from your self-made wrapper then there is Simple Logging Facade for Java (SLF4J) which Hibernate has now switched to (instead of commons logging).

SLF4J suffers from none of the class loader problems or memory leaks observed with Jakarta Commons Logging (JCL).

SLF4J supports JDK logging, log4j and logback. So then it should be fairly easy to switch from log4j to logback when the time is right.

Edit: Aplogies that I hadn't made myself clear. I was suggesting using SLF4J to isolate yourself from having to make a hard choice between log4j or logback.

How can I verify if a Windows Service is running

I guess something like this would work:

Add System.ServiceProcess to your project references (It's on the .NET tab).

using System.ServiceProcess;

ServiceController sc = new ServiceController(SERVICENAME);

switch (sc.Status)
{
    case ServiceControllerStatus.Running:
        return "Running";
    case ServiceControllerStatus.Stopped:
        return "Stopped";
    case ServiceControllerStatus.Paused:
        return "Paused";
    case ServiceControllerStatus.StopPending:
        return "Stopping";
    case ServiceControllerStatus.StartPending:
        return "Starting";
    default:
        return "Status Changing";
}

Edit: There is also a method sc.WaitforStatus() that takes a desired status and a timeout, never used it but it may suit your needs.

Edit: Once you get the status, to get the status again you will need to call sc.Refresh() first.

Reference: ServiceController object in .NET.

How do I trap ctrl-c (SIGINT) in a C# console app

The Console.CancelKeyPress event is used for this. This is how it's used:

public static void Main(string[] args)
{
    Console.CancelKeyPress += delegate {
        // call methods to clean up
    };

    while (true) {}
}

When the user presses Ctrl + C the code in the delegate is run and the program exits. This allows you to perform cleanup by calling necessairy methods. Note that no code after the delegate is executed.

There are other situations where this won't cut it. For example, if the program is currently performing important calculations that can't be immediately stopped. In that case, the correct strategy might be to tell the program to exit after the calculation is complete. The following code gives an example of how this can be implemented:

class MainClass
{
    private static bool keepRunning = true;

    public static void Main(string[] args)
    {
        Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs e) {
            e.Cancel = true;
            MainClass.keepRunning = false;
        };

        while (MainClass.keepRunning) {
            // Do your work in here, in small chunks.
            // If you literally just want to wait until ctrl-c,
            // not doing anything, see the answer using set-reset events.
        }
        Console.WriteLine("exited gracefully");
    }
}

The difference between this code and the first example is that e.Cancel is set to true, which means the execution continues after the delegate. If run, the program waits for the user to press Ctrl + C. When that happens the keepRunning variable changes value which causes the while loop to exit. This is a way to make the program exit gracefully.

Case-insensitive search

If you're just searching for a string rather than a more complicated regular expression, you can use indexOf() - but remember to lowercase both strings first because indexOf() is case sensitive:

var string="Stackoverflow is the BEST"; 
var searchstring="best";

// lowercase both strings
var lcString=string.toLowerCase();
var lcSearchString=searchstring.toLowerCase();

var result = lcString.indexOf(lcSearchString)>=0;
alert(result);

Or in a single line:

var result = string.toLowerCase().indexOf(searchstring.toLowerCase())>=0;

What does 'const static' mean in C and C++?

It has uses in both C and C++.

As you guessed, the static part limits its scope to that compilation unit. It also provides for static initialization. const just tells the compiler to not let anybody modify it. This variable is either put in the data or bss segment depending on the architecture, and might be in memory marked read-only.

All that is how C treats these variables (or how C++ treats namespace variables). In C++, a member marked static is shared by all instances of a given class. Whether it's private or not doesn't affect the fact that one variable is shared by multiple instances. Having const on there will warn you if any code would try to modify that.

If it was strictly private, then each instance of the class would get its own version (optimizer notwithstanding).

Testing socket connection in Python

It seems that you catch not the exception you wanna catch out there :)

if the s is a socket.socket() object, then the right way to call .connect would be:

import socket
s = socket.socket()
address = '127.0.0.1'
port = 80  # port number is a number, not string
try:
    s.connect((address, port)) 
    # originally, it was 
    # except Exception, e: 
    # but this syntax is not supported anymore. 
except Exception as e: 
    print("something's wrong with %s:%d. Exception is %s" % (address, port, e))
finally:
    s.close()

Always try to see what kind of exception is what you're catching in a try-except loop.

You can check what types of exceptions in a socket module represent what kind of errors (timeout, unable to resolve address, etc) and make separate except statement for each one of them - this way you'll be able to react differently for different kind of problems.

How to read the last row with SQL Server

Well I'm not getting the "last value" in a table, I'm getting the Last value per financial instrument. It's not the same but I guess it is relevant for some that are looking to look up on "how it is done now". I also used RowNumber() and CTE's and before that to simply take 1 and order by [column] desc. however we nolonger need to...

I am using SQL server 2017, we are recording all ticks on all exchanges globally, we have ~12 billion ticks a day, we store each Bid, ask, and trade including the volumes and the attributes of a tick (bid, ask, trade) of any of the given exchanges.

We have 253 types of ticks data for any given contract (mostly statistics) in that table, the last traded price is tick type=4 so, when we need to get the "last" of Price we use :

select distinct T.contractId,
LAST_VALUE(t.Price)over(partition by t.ContractId order by created ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)
from [dbo].[Tick] as T
where T.TickType=4

You can see the execution plan on my dev system it executes quite efficient, executes in 4 sec while the exchange import ETL is pumping data into the table, there will be some locking slowing me down... that's just how live systems work. execution plan against 85,697,659 rows

grid controls for ASP.NET MVC?

We have just rolled our own due to limited functionality requirements on our grids. We use some JQuery here and there for some niceties like pagination and that is all we really need.

If you need something a little more fully featured you could check out ExtJs grids here.

Also MvcContrib has a grid implementation that you could check out - try here. Or more specifically here.

Do you use NULL or 0 (zero) for pointers in C++?

I prefer to use NULL as it makes clear that your intent is the value represents a pointer not an arithmetic value. The fact that it's a macro is unfortunate, but since it's so widely ingrained there's little danger (unless someone does something really boneheaded). I do wish it were a keyword from the beginning, but what can you do?

That said, I have no problem with using pointers as truth values in themselves. Just as with NULL, it's an ingrained idiom.

C++09 will add the the nullptr construct which I think is long overdue.

Select top 10 records for each category

This works on SQL Server 2005 (edited to reflect your clarification):

select *
from Things t
where t.ThingID in (
    select top 10 ThingID
    from Things tt
    where tt.Section = t.Section and tt.ThingDate = @Date
    order by tt.DateEntered desc
    )
    and t.ThingDate = @Date
order by Section, DateEntered desc

Finding the index of an item in a list

You have to set a condition to check if the element you're searching is in the list

if 'your_element' in mylist:
    print mylist.index('your_element')
else:
    print None

Disable the postback on an <ASP:LinkButton>

To avoid refresh of page, if the return false is not working with asp:LinkButton use

href="javascript: void;"

or

href="#"

along with OnClientClick="return false;"

<asp:LinkButton ID="linkPrint" runat="server" CausesValidation="False" href="javascript: void;"
        OnClientClick="javascript:self.print();return false;">Print</asp:LinkButton>

Above is code will call the browser print without refresh the page.

What is the difference between char, nchar, varchar, and nvarchar in SQL Server?

Just to clear up... or sum up...

  • nchar and nvarchar can store Unicode characters.
  • char and varchar cannot store Unicode characters.
  • char and nchar are fixed-length which will reserve storage space for number of characters you specify even if you don't use up all that space.
  • varchar and nvarchar are variable-length which will only use up spaces for the characters you store. It will not reserve storage like char or nchar.

nchar and nvarchar will take up twice as much storage space, so it may be wise to use them only if you need Unicode support.

Build a simple HTTP server in C

I suggest you take a look at tiny httpd. If you want to write it from scratch, then you'll want to thoroughly read RFC 2616. Use BSD sockets to access the network at a really low level.

Determine SQL Server Database Size

sp_helpdb

no looping needed, unlike sp_spaceused.

What is the difference between a URI, a URL and a URN?

This is one of the most confusing and possibly irrelevant topics I've encountered as a web professional.

As I understand it, a URI is a description of something, following an accepted format, that can define both or either the unique name (identification) of something or its location.

There are two basic subsets:

  • URLs, which define location (especially to a browser trying to look up a webpage) and
  • URNs, which define the unique name of something.

I tend to think of URNs as being similar to GUIDs. They are simply a standardized methodology for providing unique names for things. As in the namespace declarative that uses a company's name—it's not like there is a resource sitting on a server somewhere to correspond to that line of text—it simply uniquely identifies something.

I also tend to completely avoid the term URI and discuss things only in terms of URL or URN as appropriate, because it causes so much confusion. The question we should really try answering for people isn't so much the semantics, but how to identify when encountering the terms whether or not there is any practical difference in them that will change the approach to a programming situation. For example, if someone corrects me in conversation and says, "oh, that's not a URL it's a URI" I know they're full of it. If someone says, "we're using a URN to define the resource," I'm more likely to understand we are only naming it uniquely, not locating it on a server.

If I'm way off base, please let me know!

Python List vs. Array - when to use?

The array module is kind of one of those things that you probably don't have a need for if you don't know why you would use it (and take note that I'm not trying to say that in a condescending manner!). Most of the time, the array module is used to interface with C code. To give you a more direct answer to your question about performance:

Arrays are more efficient than lists for some uses. If you need to allocate an array that you KNOW will not change, then arrays can be faster and use less memory. GvR has an optimization anecdote in which the array module comes out to be the winner (long read, but worth it).

On the other hand, part of the reason why lists eat up more memory than arrays is because python will allocate a few extra elements when all allocated elements get used. This means that appending items to lists is faster. So if you plan on adding items, a list is the way to go.

TL;DR I'd only use an array if you had an exceptional optimization need or you need to interface with C code (and can't use pyrex).

MySQL - force not to use cache for testing speed of query

Try using the SQL_NO_CACHE (MySQL 5.7) option in your query. (MySQL 5.6 users click HERE )

eg.

SELECT SQL_NO_CACHE * FROM TABLE

This will stop MySQL caching the results, however be aware that other OS and disk caches may also impact performance. These are harder to get around.

How do I start a process from C#?

Declare this

[DllImport("user32")]
private static extern bool SetForegroundWindow(IntPtr hwnd);
[DllImport("user32")]
private static extern bool ShowWindowAsync(IntPtr hwnd, int a);

And put this inside your function (note that "checkInstalled" is optional, but if you'll use it, you have to implement it)

if (ckeckInstalled("example"))
{
    int count = Process.GetProcessesByName("example").Count();
    if (count < 1)
        Process.Start("example.exe");
    else
    {
        var proc = Process.GetProcessesByName("example").FirstOrDefault();
        if (proc != null && proc.MainWindowHandle != IntPtr.Zero)
        {
            SetForegroundWindow(proc.MainWindowHandle);
            ShowWindowAsync(proc.MainWindowHandle, 3);
        }
    }
}

NOTE: I'm not sure if this works when more than one instance of the .exe is running.

What are the complexity guarantees of the standard containers?

I'm not aware of anything like a single table that lets you compare all of them in at one glance (I'm not sure such a table would even be feasible).

Of course the ISO standard document enumerates the complexity requirements in detail, sometimes in various rather readable tables, other times in less readable bullet points for each specific method.

Also the STL library reference at http://www.cplusplus.com/reference/stl/ provides the complexity requirements where appropriate.

C++: what regex library should I use?

In C++ projects past, I have used PCRE with good success. It's very complete and well-tested since it's used in many high profile projects. And I see that Google has contributed a set of C++ wrappers for PCRE recently, too.

How to convert a column number (e.g. 127) into an Excel column (e.g. AA)

A little late to the game, but here's the code I use (in C#):

private static readonly string _Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static int ColumnNameParse(string value)
{
    // assumes value.Length is [1,3]
    // assumes value is uppercase
    var digits = value.PadLeft(3).Select(x => _Alphabet.IndexOf(x));
    return digits.Aggregate(0, (current, index) => (current * 26) + (index + 1));
}

Styling multi-line conditions in 'if' statements?

All respondents that also provide multi-conditionals for the if statement is just as ugly as the problem presented. You don't solve this problem by doing the same thing..

Even the PEP 0008 answer is repulsive.

Here is a far more readable approach

condition = random.randint(0, 100) # to demonstrate
anti_conditions = [42, 67, 12]
if condition not in anti_conditions:
    pass

Want me to eat my words? Convince me you need multi-conditionals and I'll literally print this and eat it for your amusement.

Regex to match alphanumeric and spaces

This:

string clean = Regex.Replace(dirty, "[^a-zA-Z0-9\x20]", String.Empty);

\x20 is ascii hex for 'space' character

you can add more individual characters that you want to be allowed. If you want for example "?" to be ok in the return string add \x3f.

ORA-01438: value larger than specified precision allows for this column

One issue I've had, and it was horribly tricky, was that the OCI call to describe a column attributes behaves diffrently depending on Oracle versions. Describing a simple NUMBER column created without any prec or scale returns differenlty on 9i, 1Og and 11g

What does "select count(1) from table_name" on any database tables mean?

Depending on who you ask, some people report that executing select count(1) from random_table; runs faster than select count(*) from random_table. Others claim they are exactly the same.

This link claims that the speed difference between the 2 is due to a FULL TABLE SCAN vs FAST FULL SCAN.

File input 'accept' attribute - is it useful?

Back in 2008 this wasn't important because of the lack of mobile OS'es but now quite important thing.

When you set accepted mime types, then in for example Android user is given system dialog with apps which can provide him the content of mime which file input accepts, what is great because navigating through files in file explorer on mobile devices is slow and often stressful.

One important thing is that some mobile browsers (based on Android version of Chrome 36 and Chrome Beta 37) does not support app filtering over extension(s) and multiple mime types.

How do I install cURL on Windows?

You're probably mistaking what PHP.ini you need to edit. first, add a PHPinfo(); to a info.php, and run it from your browser.

Write down the PHP ini directory path you see in the variables list now! You will probably notice that it's different from your PHP-CLI ini file.

Enable the extension

You're done :-)

What is the difference between re.search and re.match?

re.search searches for the pattern throughout the string, whereas re.match does not search the pattern; if it does not, it has no other choice than to match it at start of the string.

What is tempuri.org?

http://en.wikipedia.org/wiki/Tempuri

tempuri.org is the default namespace URI used by Microsoft development products, like Visual Studio.

Base64 decode snippet in C++

I use this:

class BinaryVector {
public:
    std::vector<char> bytes;

    uint64_t bit_count = 0;

public:
    /* Add a bit to the end */
    void push_back(bool bit);

    /* Return false if character is unrecognized */
    bool pushBase64Char(char b64_c);
};

void BinaryVector::push_back(bool bit)
{
    if (!bit_count || bit_count % 8 == 0) {
        bytes.push_back(bit << 7);
    }
    else {
        uint8_t next_bit = 8 - (bit_count % 8) - 1;
        bytes[bit_count / 8] |= bit << next_bit;
    }
    bit_count++;
}

/* Converts one Base64 character to 6 bits */
bool BinaryVector::pushBase64Char(char c)
{
    uint8_t d;

    // A to Z
    if (c > 0x40 && c < 0x5b) {
        d = c - 65;  // Base64 A is 0
    }
    // a to z
    else if (c > 0x60 && c < 0x7b) {
        d = c - 97 + 26;  // Base64 a is 26
    }
    // 0 to 9
    else if (c > 0x2F && c < 0x3a) {
        d = c - 48 + 52;  // Base64 0 is 52
    }
    else if (c == '+') {
        d = 0b111110;
    }
    else if (c == '/') {
        d = 0b111111;
    }
    else if (c == '=') {
        d = 0;
    }
    else {
        return false;
    }

    push_back(d & 0b100000);
    push_back(d & 0b010000);
    push_back(d & 0b001000);
    push_back(d & 0b000100);
    push_back(d & 0b000010);
    push_back(d & 0b000001);

    return true;
}

bool loadBase64(std::vector<char>& b64_bin, BinaryVector& vec)
{
    for (char& c : b64_bin) {
        if (!vec.pushBase64Char(c)) {
            return false;
        }
    }
    return true;
}

Use vec.bytes to access converted data.

Makefile If-Then Else and Loops

Have you tried the GNU make documentation? It has a whole section about conditionals with examples.

How to do something to each file in a directory with a batch script

Another way:

for %f in (*.mp4) do call ffmpeg -i "%~f" -vcodec copy -acodec copy "%~nf.avi"

How can I delete (not disable) ActiveX add-ons in Internet Explorer (7 and 8 Beta 2)?

You can go to IE Tools -> Internet options -> Advanced Tab. Under Advanced, check for security and put a check on the 1st 2 options which says,"Allow active content from CDs to run on My Computer* and Allow active content to run in files on My Computer*"

Restart your browser and the ActiveX scripts will not be shown.

How do I convert a list of ascii values to a string in python?

Same basic solution as others, but I personally prefer to use map instead of the list comprehension:


>>> L = [104, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100]
>>> ''.join(map(chr,L))
'hello, world'

Using "super" in C++

I don't know whether it's rare or not, but I've certainly done the same thing.

As has been pointed out, the difficulty with making this part of the language itself is when a class makes use of multiple inheritance.

How to preview git-pull without doing fetch?

What about cloning the repo elsewhere, and doing git log on both the real checkout and the fresh clone to see if you got the same thing.

jQuery DIV click, with anchors

$("div.clickable").click( function(event) { window.location = $(this).attr("url"); event.preventDefault(); });