SyntaxFix.com - Programming Questions & Answers Hub For Beginners


Some Of The Best Answers From Latest Asked Questions

Datatable vs Dataset

One feature of the DataSet is that if you can call multiple select statements in your stored procedures, the DataSet will have one DataTable for each.

How to call shell commands from Ruby

If you really need Bash, per the note in the "best" answer.

First, note that when Ruby calls out to a shell, it typically calls /bin/sh, not Bash. Some Bash syntax is not supported by /bin/sh on all systems.

If you need to use Bash, insert bash -c "your Bash-only command" inside of your desired calling method:

quick_output = system("ls -la")
quick_bash = system("bash -c 'ls -la'")

To test:

system("echo $SHELL")
system('bash -c "echo $SHELL"')

Or if you are running an existing script file like

script_output = system("./my_script.sh")

Ruby should honor the shebang, but you could always use

system("bash ./my_script.sh")

to make sure, though there may be a slight overhead from /bin/sh running /bin/bash, you probably won't notice.

Creating a custom JButton in Java

I'm probably going a million miles in the wrong direct (but i'm only young :P ). but couldn't you add the graphic to a panel and then a mouselistener to the graphic object so that when the user on the graphic your action is preformed.

Convert HashBytes to VarChar

Changing the datatype to varbinary seems to work the best for me.

What are MVP and MVC and what is the difference?

Model-View-Controller

MVC is a pattern for the architecture of a software application. It separate the application logic into three separate parts, promoting modularity and ease of collaboration and reuse. It also makes applications more flexible and welcoming to iterations.It separates an application into the following components:

  • Models for handling data and business logic
  • Controllers for handling the user interface and application
  • Views for handling graphical user interface objects and presentation

To make this a little more clear, let's imagine a simple shopping list app. All we want is a list of the name, quantity and price of each item we need to buy this week. Below we'll describe how we could implement some of this functionality using MVC.

enter image description here

Model-View-Presenter

  • The model is the data that will be displayed in the view (user interface).
  • The view is an interface that displays data (the model) and routes user commands (events) to the Presenter to act upon that data. The view usually has a reference to its Presenter.
  • The Presenter is the “middle-man” (played by the controller in MVC) and has references to both, view and model. Please note that the word “Model” is misleading. It should rather be business logic that retrieves or manipulates a Model. For instance: If you have a database storing User in a database table and your View wants to display a list of users, then the Presenter would have a reference to your database business logic (like a DAO) from where the Presenter will query a list of Users.

If you want to see a sample with simple implementation please check this GitHub post

A concrete workflow of querying and displaying a list of users from a database could work like this: enter image description here

What is the difference between MVC and MVP patterns?

MVC Pattern

  • Controller are based on behaviors and can be shared across views

  • Can be responsible for determining which view to display (Front Controller Pattern)

MVP Pattern

  • View is more loosely coupled to the model. The presenter is responsible for binding the model to the view.

  • Easier to unit test because interaction with the view is through an interface

  • Usually view to presenter map one to one. Complex views may have multi presenters.

How do I create a branch?

Branching in Subversion is facilitated by a very very light and efficient copying facility.

Branching and tagging are effectively the same. Just copy a whole folder in the repository to somewhere else in the repository using the svn copy command.

Basically this means that it is by convention what copying a folder means - whether it be a backup, tag, branch or whatever. Depending upon how you want to think about things (normally depending upon which SCM tool you have used in the past) you need to set up a folder structure within your repository to support your style.

Common styles are to have a bunch of folders at the top of your repository called tags, branches, trunk, etc. - that allows you to copy your whole trunk (or sub-sets) into the tags and/or branches folders. If you have more than one project you might want to replicate this kind of structure under each project:

It can take a while to get used to the concept - but it works - just make sure you (and your team) are clear on the conventions that you are going to use. It is also a good idea to have a good naming convention - something that tells you why the branch/tag was made and whether it is still appropriate - consider ways of archiving branches that are obsolete.

What do the result codes in SVN mean?

Take a look in the Subversion Book reference: "Status of working copy files and directories"

Highly recommended for anyone doing pretty much anything with SVN.

Python: What OS am I running on?

Check the available tests with module platform and print the answer out for your system:

import platform

print dir(platform)

for x in dir(platform):
    if x[0].isalnum():
        try:
            result = getattr(platform, x)()
            print "platform."+x+": "+result
        except TypeError:
            continue

What is the single most influential book every programmer should read?

Object-Oriented Software Construction by Bertrand Meyer

Learning to write a compiler

"... Let's Build a Compiler ..."

I'd second http://compilers.iecc.com/crenshaw/ by @sasb. Forget buying more books for the moment.

Why? Tools & language.

The language required is Pascal and if I remember correctly is based on Turbo-Pascal. It just so happens if you go to http://www.freepascal.org/ and download the Pascal compiler all the examples work straight from the page ~ http://www.freepascal.org/download.var The beaut thing about Free Pascal is you can use it almost whatever processor or OS you can care for.

Once you have mastered the lessons then try the more advanced "Dragon Book" ~ http://en.wikipedia.org/wiki/Dragon_book

What good technology podcasts are out there?

This one's not specifically about development, but Security Now from Steve Gibson and Leo Laporte is an excellent discussion of security issues. I think it's a must-listen for just about any computer user who's concerned about security, and especially for web developers who are responsible both for the security of their site and at least partially responsible for their users' security.

How do you express binary literals in Python?

0 in the start here specifies that the base is 8 (not 10), which is pretty easy to see:

>>> int('010101', 0)
4161

If you don't start with a 0, then python assumes the number is base 10.

>>> int('10101', 0)
10101

Make XAMPP / Apache serve file outside of htdocs folder

Ok, per pix0r's, Sparks' and Dave's answers it looks like there are three ways to do this:


Virtual Hosts

  1. Open C:\xampp\apache\conf\extra\httpd-vhosts.conf.
  2. Un-comment ~line 19 (NameVirtualHost *:80).
  3. Add your virtual host (~line 36):

    <VirtualHost *:80>
        DocumentRoot C:\Projects\transitCalculator\trunk
        ServerName transitcalculator.localhost
        <Directory C:\Projects\transitCalculator\trunk>
            Order allow,deny
            Allow from all
        </Directory>
    </VirtualHost>
    
  4. Open your hosts file (C:\Windows\System32\drivers\etc\hosts).

  5. Add

    127.0.0.1 transitcalculator.localhost #transitCalculator
    

    to the end of the file (before the Spybot - Search & Destroy stuff if you have that installed).

  6. Save (You might have to save it to the desktop, change the permissions on the old hosts file (right click > properties), and copy the new one into the directory over the old one (or rename the old one) if you are using Vista and have trouble).
  7. Restart Apache.

Now you can access that directory by browsing to http://transitcalculator.localhost/.


Make an Alias

  1. Starting ~line 200 of your http.conf file, copy everything between <Directory "C:/xampp/htdocs"> and </Directory> (~line 232) and paste it immediately below with C:/xampp/htdocs replaced with your desired directory (in this case C:/Projects) to give your server the correct permissions for the new directory.

  2. Find the <IfModule alias_module></IfModule> section (~line 300) and add

    Alias /transitCalculator "C:/Projects/transitCalculator/trunk"
    

    (or whatever is relevant to your desires) below the Alias comment block, inside the module tags.


Change your document root

  1. Edit ~line 176 in C:\xampp\apache\conf\httpd.conf; change DocumentRoot "C:/xampp/htdocs" to #DocumentRoot "C:/Projects" (or whatever you want).

  2. Edit ~line 203 to match your new location (in this case C:/Projects).


Notes:

  • You have to use forward slashes "/" instead of back slashes "\".
  • Don't include the trailing "/" at the end.
  • restart your server.

How to check for file lock?

The other answers rely on old information. This one provides a better solution.

Long ago it was impossible to reliably get the list of processes locking a file because Windows simply did not track that information. To support the Restart Manager API, that information is now tracked. The Restart Manager API is available beginning with Windows Vista and Windows Server 2008 (Restart Manager: Run-time Requirements).

I put together code that takes the path of a file and returns a List<Process> of all processes that are locking that file.

static public class FileUtil
{
    [StructLayout(LayoutKind.Sequential)]
    struct RM_UNIQUE_PROCESS
    {
        public int dwProcessId;
        public System.Runtime.InteropServices.ComTypes.FILETIME ProcessStartTime;
    }

    const int RmRebootReasonNone = 0;
    const int CCH_RM_MAX_APP_NAME = 255;
    const int CCH_RM_MAX_SVC_NAME = 63;

    enum RM_APP_TYPE
    {
        RmUnknownApp = 0,
        RmMainWindow = 1,
        RmOtherWindow = 2,
        RmService = 3,
        RmExplorer = 4,
        RmConsole = 5,
        RmCritical = 1000
    }

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    struct RM_PROCESS_INFO
    {
        public RM_UNIQUE_PROCESS Process;

        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCH_RM_MAX_APP_NAME + 1)]
        public string strAppName;

        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCH_RM_MAX_SVC_NAME + 1)]
        public string strServiceShortName;

        public RM_APP_TYPE ApplicationType;
        public uint AppStatus;
        public uint TSSessionId;
        [MarshalAs(UnmanagedType.Bool)]
        public bool bRestartable;
    }

    [DllImport("rstrtmgr.dll", CharSet = CharSet.Unicode)]
    static extern int RmRegisterResources(uint pSessionHandle,
                                          UInt32 nFiles,
                                          string[] rgsFilenames,
                                          UInt32 nApplications,
                                          [In] RM_UNIQUE_PROCESS[] rgApplications,
                                          UInt32 nServices,
                                          string[] rgsServiceNames);

    [DllImport("rstrtmgr.dll", CharSet = CharSet.Auto)]
    static extern int RmStartSession(out uint pSessionHandle, int dwSessionFlags, string strSessionKey);

    [DllImport("rstrtmgr.dll")]
    static extern int RmEndSession(uint pSessionHandle);

    [DllImport("rstrtmgr.dll")]
    static extern int RmGetList(uint dwSessionHandle,
                                out uint pnProcInfoNeeded,
                                ref uint pnProcInfo,
                                [In, Out] RM_PROCESS_INFO[] rgAffectedApps,
                                ref uint lpdwRebootReasons);

    /// <summary>
    /// Find out what process(es) have a lock on the specified file.
    /// </summary>
    /// <param name="path">Path of the file.</param>
    /// <returns>Processes locking the file</returns>
    /// <remarks>See also:
    /// http://msdn.microsoft.com/en-us/library/windows/desktop/aa373661(v=vs.85).aspx
    /// http://wyupdate.googlecode.com/svn-history/r401/trunk/frmFilesInUse.cs (no copyright in code at time of viewing)
    /// 
    /// </remarks>
    static public List<Process> WhoIsLocking(string path)
    {
        uint handle;
        string key = Guid.NewGuid().ToString();
        List<Process> processes = new List<Process>();

        int res = RmStartSession(out handle, 0, key);

        if (res != 0)
            throw new Exception("Could not begin restart session.  Unable to determine file locker.");

        try
        {
            const int ERROR_MORE_DATA = 234;
            uint pnProcInfoNeeded = 0,
                 pnProcInfo = 0,
                 lpdwRebootReasons = RmRebootReasonNone;

            string[] resources = new string[] { path }; // Just checking on one resource.

            res = RmRegisterResources(handle, (uint)resources.Length, resources, 0, null, 0, null);

            if (res != 0) 
                throw new Exception("Could not register resource.");                                    

            //Note: there's a race condition here -- the first call to RmGetList() returns
            //      the total number of process. However, when we call RmGetList() again to get
            //      the actual processes this number may have increased.
            res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, null, ref lpdwRebootReasons);

            if (res == ERROR_MORE_DATA)
            {
                // Create an array to store the process results
                RM_PROCESS_INFO[] processInfo = new RM_PROCESS_INFO[pnProcInfoNeeded];
                pnProcInfo = pnProcInfoNeeded;

                // Get the list
                res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, processInfo, ref lpdwRebootReasons);

                if (res == 0)
                {
                    processes = new List<Process>((int)pnProcInfo);

                    // Enumerate all of the results and add them to the 
                    // list to be returned
                    for (int i = 0; i < pnProcInfo; i++)
                    {
                        try
                        {
                            processes.Add(Process.GetProcessById(processInfo[i].Process.dwProcessId));
                        }
                        // catch the error -- in case the process is no longer running
                        catch (ArgumentException) { }
                    }
                }
                else
                    throw new Exception("Could not list processes locking resource.");                    
            }
            else if (res != 0)
                throw new Exception("Could not list processes locking resource. Failed to get size of result.");                    
        }
        finally
        {
            RmEndSession(handle);
        }

        return processes;
    }
}

UPDATE

Here is another discussion with sample code on how to use the Restart Manager API.

How big can a MySQL database get before performance starts to degrade

I would focus first on your indexes, than have a server admin look at your OS, and if all that doesn't help it might be time for a master/slave configuration.

That's true. Another thing that usually works is to just reduce the quantity of data that's repeatedly worked with. If you have "old data" and "new data" and 99% of your queries work with new data, just move all the old data to another table - and don't look at it ;)

-> Have a look at partitioning.

How does database indexing work?

An index is just a data structure that makes the searching faster for a specific column in a database. This structure is usually a b-tree or a hash table but it can be any other logic structure.

Adding a Method to an Existing Object Instance

In Python monkeypatching generally works by overwriting a class or function's signature with your own. Below is an example from the Zope Wiki:

from SomeOtherProduct.SomeModule import SomeClass
def speak(self):
   return "ook ook eee eee eee!"
SomeClass.speak = speak

This code will overwrite/create a method called peak in the class. In Jeff Atwood's recent post on monkey patching, he showed an example in C# 3.0 which is the current language I use for work.

String literals and escape characters in postgresql

I find it highly unlikely for Postgres to truncate your data on input - it either rejects it or stores it as is.

milen@dev:~$ psql
Welcome to psql 8.2.7, the PostgreSQL interactive terminal.

Type:  \copyright for distribution terms
       \h for help with SQL commands
       \? for help with psql commands
       \g or terminate with semicolon to execute query
       \q to quit

milen=> create table EscapeTest (text varchar(50));
CREATE TABLE
milen=> insert into EscapeTest (text) values ('This will be inserted \n This will not be');
WARNING:  nonstandard use of escape in a string literal
LINE 1: insert into EscapeTest (text) values ('This will be inserted...
                                              ^
HINT:  Use the escape string syntax for escapes, e.g., E'\r\n'.
INSERT 0 1
milen=> select * from EscapeTest;
          text
------------------------
 This will be inserted
  This will not be
(1 row)

milen=>

How do you debug PHP scripts?

Nusphere is also a good debugger for php nusphere

Are PHP Variables passed by value or by reference?

Actually both methods are valid but it depends upon your requirement. Passing values by reference often makes your script slow. So it's better to pass variables by value considering time of execution. Also the code flow is more consistent when you pass variables by value.

Why is Git better than Subversion?

This is the wrong question to be asking. It's all too easy to focus on git's warts and formulate an argument about why subversion is ostensibly better, at least for some use cases. The fact that git was originally designed as a low-level version control construction set and has a baroque linux-developer-oriented interface makes it easier for the holy wars to gain traction and perceived legitimacy. Git proponents bang the drum with millions of workflow advantages, which svn guys proclaim unnecessary. Pretty soon the whole debate is framed as centralized vs distributed, which serves the interests of the enterprise svn tool community. These companies, which typically put out the most convincing articles about subversion's superiority in the enterprise, are dependent on the perceived insecurity of git and the enterprise-readiness of svn for the long-term success of their products.

But here's the problem: Subversion is an architectural dead-end.

Whereas you can take git and build a centralized subversion replacement quite easily, despite being around for more than twice as long svn has never been able to get even basic merge-tracking working anywhere near as well as it does in git. One basic reason for this is the design decision to make branches the same as directories. I don't know why they went this way originally, it certainly makes partial checkouts very simple. Unfortunately it also makes it impossible to track history properly. Now obviously you are supposed to use subversion repository layout conventions to separate branches from regular directories, and svn uses some heuristics to make things work for the daily use cases. But all this is just papering over a very poor and limiting low-level design decision. Being able to a do a repository-wise diff (rather than directory-wise diff) is basic and critical functionality for a version control system, and greatly simplifies the internals, making it possible to build smarter and useful features on top of it. You can see in the amount of effort that has been put into extending subversion, and yet how far behind it is from the current crop of modern VCSes in terms of fundamental operations like merge resolution.

Now here's my heart-felt and agnostic advice for anyone who still believes Subversion is good enough for the foreseeable future:

Subversion will never catch up to the newer breeds of VCSes that have learned from the mistakes of RCS and CVS; it is a technical impossibility unless they retool the repository model from the ground up, but then it wouldn't really be svn would it? Regardless of how much you think you don't the capabilities of a modern VCS, your ignorance will not protect you from the Subversion's pitfalls, many of which are situations that are impossible or easily resolved in other systems.

It is extremely rare that the technical inferiority of a solution is so clear-cut as it is with svn, certainly I would never state such an opinion about win-vs-linux or emacs-vs-vi, but in this case it is so clearcut, and source control is such a fundamental tool in the developer's arsenal, that I feel it must be stated unequivocally. Regardless of the requirement to use svn for organizational reasons, I implore all svn users not to let their logical mind construct a false belief that more modern VCSes are only useful for large open-source projects. Regardless of the nature of your development work, if you are a programmer, you will be a more effective programmer if you learn how to use better-designed VCSes, whether it be Git, Mercurial, Darcs, or many others.

How do I use itertools.groupby()?

The example on the Python docs is quite straightforward:

groups = []
uniquekeys = []
for k, g in groupby(data, keyfunc):
    groups.append(list(g))      # Store group iterator as a list
    uniquekeys.append(k)

So in your case, data is a list of nodes, keyfunc is where the logic of your criteria function goes and then groupby() groups the data.

You must be careful to sort the data by the criteria before you call groupby or it won't work. groupby method actually just iterates through a list and whenever the key changes it creates a new group.

How to create a new object instance from a Type

Without use of Reflection:

private T Create<T>() where T : class, new()
{
    return new T();
}

What is the difference between an int and an Integer in Java and C#?

int is used to declare primitive variable

e.g. int i=10;

Integer is used to create reference variable of class Integer

Integer a = new Integer();

The definitive guide to form-based website authentication

I do not think the above answer is "wrong" but there are large areas of authentication that are not touched upon (or rather the emphasis is on "how to implement cookie sessions", not on "what options are available and what are the trade-offs".

My suggested edits/answers are

  • The problem lies more in account setup than in password checking.
  • The use of two-factor authentication is much more secure than more clever means of password encryption
  • Do NOT try to implement your own login form or database storage of passwords, unless the data being stored is valueless at account creation and self-generated (that is, web 2.0 style like Facebook, Flickr, etc.)

    1. Digest Authentication is a standards-based approach supported in all major browsers and servers, that will not send a password even over a secure channel.

This avoids any need to have "sessions" or cookies as the browser itself will re-encrypt the communication each time. It is the most "lightweight" development approach.

However, I do not recommend this, except for public, low-value services. This is an issue with some of the other answers above - do not try an re-implement server-side authentication mechanisms - this problem has been solved and is supported by most major browsers. Do not use cookies. Do not store anything in your own hand-rolled database. Just ask, per request, if the request is authenticated. Everything else should be supported by configuration and third-party trusted software.

So ...

First, we are confusing the initial creation of an account (with a password) with the re-checking of the password subsequently. If I am Flickr and creating your site for the first time, the new user has access to zero value (blank web space). I truly do not care if the person creating the account is lying about their name. If I am creating an account of the hospital intranet/extranet, the value lies in all the medical records, and so I do care about the identity (*) of the account creator.

This is the very very hard part. The only decent solution is a web of trust. For example, you join the hospital as a doctor. You create a web page hosted somewhere with your photo, your passport number, and a public key, and hash them all with the private key. You then visit the hospital and the system administrator looks at your passport, sees if the photo matches you, and then hashes the web page/photo hash with the hospital private key. From now on we can securely exchange keys and tokens. As can anyone who trusts the hospital (there is the secret sauce BTW). The system administrator can also give you an RSA dongle or other two-factor authentication.

But this is a lot of a hassle, and not very web 2.0. However, it is the only secure way to create new accounts that have access to valuable information that is not self-created.

  1. Kerberos and SPNEGO - single sign-on mechanisms with a trusted third party - basically the user verifies against a trusted third party. (NB this is not in any way the not to be trusted OAuth)

  2. SRP - sort of clever password authentication without a trusted third party. But here we are getting into the realms of "it's safer to use two-factor authentication, even if that's costlier"

  3. SSL client side - give the clients a public key certificate (support in all major browsers - but raises questions over client machine security).

In the end, it's a tradeoff - what is the cost of a security breach vs the cost of implementing more secure approaches. One day, we may see a proper PKI widely accepted and so no more own rolled authentication forms and databases. One day...

How do you make sure email you send programmatically is not automatically marked as spam?

It sounds like you are depending on some feedback to determine what is getting stuck on the receiving end. You should be checking the outbound mail yourself for obvious "spaminess".

Buy any decent spam control system, and send your outbound mail through it. If you send any decent volume of mail, you should be doing this anyhow, because of the risk of sending outbound viruses, especially if you have desktop windows users.

Proofpoint had spam + anti-virus + some reputation services in a single deployment, for example. (I used to work there, so I happen to know this off the top of my head. I'm sure other vendors in this space have similar features.) But you get the idea. If you send your mail through a basic commerical spam control setup, and it doesn't pass, it shouldn't be going out of your network.

Also, there are some companies that can assist you with increasing delivery rates of non-spam, outbound email, like Habeas.

Generate list of all possible permutations of a string

There are several ways to do this. Common methods use recursion, memoization, or dynamic programming. The basic idea is that you produce a list of all strings of length 1, then in each iteration, for all strings produced in the last iteration, add that string concatenated with each character in the string individually. (the variable index in the code below keeps track of the start of the last and the next iteration)

Some pseudocode:

list = originalString.split('')
index = (0,0)
list = [""]
for iteration n in 1 to y:
  index = (index[1], len(list))
  for string s in list.subset(index[0] to end):
    for character c in originalString:
      list.add(s + c)

you'd then need to remove all strings less than x in length, they'll be the first (x-1) * len(originalString) entries in the list.

How do you sort a dictionary by value?

You do not sort entries in the Dictionary. Dictionary class in .NET is implemented as a hashtable - this data structure is not sortable by definition.

If you need to be able to iterate over your collection (by key) - you need to use SortedDictionary, which is implemented as a Binary Search Tree.

In your case, however the source structure is irrelevant, because it is sorted by a different field. You would still need to sort it by frequency and put it in a new collection sorted by the relevant field (frequency). So in this collection the frequencies are keys and words are values. Since many words can have the same frequency (and you are going to use it as a key) you cannot use neither Dictionary nor SortedDictionary (they require unique keys). This leaves you with a SortedList.

I don't understand why you insist on maintaining a link to the original item in your main/first dictionary.

If the objects in your collection had a more complex structure (more fields) and you needed to be able to efficiently access/sort them using several different fields as keys - You would probably need a custom data structure that would consist of the main storage that supports O(1) insertion and removal (LinkedList) and several indexing structures - Dictionaries/SortedDictionaries/SortedLists. These indexes would use one of the fields from your complex class as a key and a pointer/reference to the LinkedListNode in the LinkedList as a value.

You would need to coordinate insertions and removals to keep your indexes in sync with the main collection (LinkedList) and removals would be pretty expensive I'd think. This is similar to how database indexes work - they are fantastic for lookups but they become a burden when you need to perform many insetions and deletions.

All of the above is only justified if you are going to do some look-up heavy processing. If you only need to output them once sorted by frequency then you could just produce a list of (anonymous) tuples:

var dict = new SortedDictionary<string, int>();
// ToDo: populate dict

var output = dict.OrderBy(e => e.Value).Select(e => new {frequency = e.Value, word = e.Key}).ToList();

foreach (var entry in output)
{
    Console.WriteLine("frequency:{0}, word: {1}",entry.frequency,entry.word);
}

error_log per Virtual Host?

Don't set error_log to where your syslog stuff goes, eg /var/log/apache2, because they errors will get intercepted by ErrorLog. Instead, create a subdir in your project folder for logs and do php_value error_log "/path/to/project/logs". This goes for both .htaccess files and vhosts. Also make sure you put php_flag log_errors on

Versioning SQL Server database

A while ago I found a VB bas module that used DMO and VSS objects to get an entire db scripted off and into VSS. I turned it into a VB Script and posted it here. You can easily take out the VSS calls and use the DMO stuff to generate all the scripts, and then call SVN from the same batch file that calls the VBScript to check them in.

Embedding Windows Media Player for all browsers

The best way to deploy video on the web is using Flash - it's much easier to embed cleanly into a web page and will play on more or less any browser and platform combination. The only reason to use Windows Media Player is if you're streaming content and you need extraordinarily strong digital rights management, and even then providers are now starting to use Flash even for these. See BBC's iPlayer for a superb example.

I would suggest that you switch to Flash even for internal use. You never know who is going to need to access it in the future, and this will give you the best possible future compatibility.

EDIT - March 20 2013. Interesting how these old questions resurface from time to time! How different the world is today and how dated this all seems. I would not recommend a Flash only route today by any means - best practice these days would probably be to use HTML 5 to embed H264 encoded video, with a Flash fallback as described here: http://diveintohtml5.info/video.html

Multiple submit buttons in an HTML form

Change the previous button type into a button like this:

<input type="button" name="prev" value="Previous Page" />

Now the Next button would be the default, plus you could also add the default attribute to it so that your browser will highlight it like so:

<input type="submit" name="next" value="Next Page" default />

Difference between Math.Floor() and Math.Truncate()

Math.Floor(): Returns the largest integer less than or equal to the specified double-precision floating-point number.

Math.Round(): Rounds a value to the nearest integer or to the specified number of fractional digits.

Determine a user's timezone

Getting a valid TZ Database timezone name in PHP is a two-step process:

  1. With JavaScript, get timezone offset in minutes through getTimezoneOffset. This offset will be positive if the local timezone is behind UTC and negative if it is ahead. So you must add an opposite sign to the offset.

    var timezone_offset_minutes = new Date().getTimezoneOffset();
    timezone_offset_minutes = timezone_offset_minutes == 0 ? 0 : -timezone_offset_minutes;
    

    Pass this offset to PHP.

  2. In PHP convert this offset into a valid timezone name with timezone_name_from_abbr function.

    // Just an example.
    $timezone_offset_minutes = -360;  // $_GET['timezone_offset_minutes']
    
    // Convert minutes to seconds
    $timezone_name = timezone_name_from_abbr("", $timezone_offset_minutes*60, false);
    
    // America/Chicago
    echo $timezone_name;</code></pre>
    

I've written a blog post on it: How to Detect User Timezone in PHP. It also contains a demo.

Calculate relative time in C#

I would recommend computing this on the client side too. Less work for the server.

The following is the version that I use (from Zach Leatherman)

/*
 * Javascript Humane Dates
 * Copyright (c) 2008 Dean Landolt (deanlandolt.com)
 * Re-write by Zach Leatherman (zachleat.com)
 * 
 * Adopted from the John Resig's pretty.js
 * at http://ejohn.org/blog/javascript-pretty-date
 * and henrah's proposed modification 
 * at http://ejohn.org/blog/javascript-pretty-date/#comment-297458
 * 
 * Licensed under the MIT license.
 */

function humane_date(date_str){
        var time_formats = [
                [60, 'just now'],
                [90, '1 minute'], // 60*1.5
                [3600, 'minutes', 60], // 60*60, 60
                [5400, '1 hour'], // 60*60*1.5
                [86400, 'hours', 3600], // 60*60*24, 60*60
                [129600, '1 day'], // 60*60*24*1.5
                [604800, 'days', 86400], // 60*60*24*7, 60*60*24
                [907200, '1 week'], // 60*60*24*7*1.5
                [2628000, 'weeks', 604800], // 60*60*24*(365/12), 60*60*24*7
                [3942000, '1 month'], // 60*60*24*(365/12)*1.5
                [31536000, 'months', 2628000], // 60*60*24*365, 60*60*24*(365/12)
                [47304000, '1 year'], // 60*60*24*365*1.5
                [3153600000, 'years', 31536000], // 60*60*24*365*100, 60*60*24*365
                [4730400000, '1 century'] // 60*60*24*365*100*1.5
        ];

        var time = ('' + date_str).replace(/-/g,"/").replace(/[TZ]/g," "),
                dt = new Date,
                seconds = ((dt - new Date(time) + (dt.getTimezoneOffset() * 60000)) / 1000),
                token = ' ago',
                i = 0,
                format;

        if (seconds < 0) {
                seconds = Math.abs(seconds);
                token = '';
        }

        while (format = time_formats[i++]) {
                if (seconds < format[0]) {
                        if (format.length == 2) {
                                return format[1] + (i > 1 ? token : ''); // Conditional so we don't return Just Now Ago
                        } else {
                                return Math.round(seconds / format[2]) + ' ' + format[1] + (i > 1 ? token : '');
                        }
                }
        }

        // overflow for centuries
        if(seconds > 4730400000)
                return Math.round(seconds / 4730400000) + ' centuries' + token;

        return date_str;
};

if(typeof jQuery != 'undefined') {
        jQuery.fn.humane_dates = function(){
                return this.each(function(){
                        var date = humane_date(this.title);
                        if(date && jQuery(this).text() != date) // don't modify the dom if we don't have to
                                jQuery(this).text(date);
                });
        };
}

How do I calculate someone's age based on a DateTime type birthday?

Here's a one-liner:

int age = new DateTime(DateTime.Now.Subtract(birthday).Ticks).Year-1;

How do you redirect HTTPS to HTTP?

all the above did not work when i used cloudflare, this one worked for me:

RewriteCond %{HTTP:X-Forwarded-Proto} =https
RewriteRule ^(.*)$ http://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

and this one definitely works without proxies in the way:

RewriteCond %{HTTPS} on
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

How do you determine the size of a file in C?

Based on NilObject's code:

#include <sys/stat.h>
#include <sys/types.h>

off_t fsize(const char *filename) {
    struct stat st; 

    if (stat(filename, &st) == 0)
        return st.st_size;

    return -1; 
}

Changes:

  • Made the filename argument a const char.
  • Corrected the struct stat definition, which was missing the variable name.
  • Returns -1 on error instead of 0, which would be ambiguous for an empty file. off_t is a signed type so this is possible.

If you want fsize() to print a message on error, you can use this:

#include <sys/stat.h>
#include <sys/types.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>

off_t fsize(const char *filename) {
    struct stat st;

    if (stat(filename, &st) == 0)
        return st.st_size;

    fprintf(stderr, "Cannot determine size of %s: %s\n",
            filename, strerror(errno));

    return -1;
}

On 32-bit systems you should compile this with the option -D_FILE_OFFSET_BITS=64, otherwise off_t will only hold values up to 2 GB. See the "Using LFS" section of Large File Support in Linux for details.

Center text output from Graphics.DrawString()

To draw a centered text:

TextRenderer.DrawText(g, "my text", Font, Bounds, ForeColor, BackColor, 
  TextFormatFlags.HorizontalCenter | 
  TextFormatFlags.VerticalCenter |
  TextFormatFlags.GlyphOverhangPadding);

Determining optimal font size to fill an area is a bit more difficult. One working soultion I found is trial-and-error: start with a big font, then repeatedly measure the string and shrink the font until it fits.

Font FindBestFitFont(Graphics g, String text, Font font, 
  Size proposedSize, TextFormatFlags flags)
{ 
  // Compute actual size, shrink if needed
  while (true)
  {
    Size size = TextRenderer.MeasureText(g, text, font, proposedSize, flags);

    // It fits, back out
    if ( size.Height <= proposedSize.Height && 
         size.Width <= proposedSize.Width) { return font; }

    // Try a smaller font (90% of old size)
    Font oldFont = font;
    font = new Font(font.FontFamily, (float)(font.Size * .9)); 
    oldFont.Dispose();
  }
}

You'd use this as:

Font bestFitFont = FindBestFitFont(g, text, someBigFont, sizeToFitIn, flags);
// Then do your drawing using the bestFitFont
// Don't forget to dispose the font (if/when needed)

How do you open a file in C++?

**#include<fstream> //to use file
#include<string>  //to use getline
using namespace std;
int main(){
ifstream file;
string str;
file.open("path the file" , ios::binary | ios::in);
while(true){
   getline(file , str);
   if(file.fail())
       break;
   cout<<str;
}
}**

Change visibility of ASP.NET label with JavaScript

If you wait until the page is loaded, and then set the button's display to none, that should work. Then you can make it visible at a later point.

How do I enable MSDTC on SQL Server?

MSDTC must be enabled on both systems, both server and client.
Also, make sure that there isn't a firewall between the systems that blocks RPC.
DTCTest is a nice litt app that helps you to troubleshoot any other problems.

How to resolve symbolic links in a shell script

My answer here Bash: how to get real path of a symlink?

but in short very handy in scripts:

script_home=$( dirname $(realpath "$0") )
echo Original script home: $script_home

These are part of GNU coreutils, suitable for use in Linux systems.

To test everything, we put symlink into /home/test2/, amend some additional things and run/call it from root directory:

/$ /home/test2/symlink
/home/test
Original script home: /home/test

Where

Original script is: /home/test/realscript.sh
Called script is: /home/test2/symlink

Database, Table and Column Naming Conventions?

Here's a link that offers a few choices. I was searching for a simple spec I could follow rather than having to rely on a partially defined one.

http://justinsomnia.org/writings/naming_conventions.html

How do I remove duplicate items from an array in Perl?

That last one was pretty good. I'd just tweak it a bit:

my @arr;
my @uniqarr;

foreach my $var ( @arr ){
  if ( ! grep( /$var/, @uniqarr ) ){
     push( @uniqarr, $var );
  }
}

I think this is probably the most readable way to do it.

Are the shift operators (<<, >>) arithmetic or logical in C?

GCC does

  1. for -ve - > Arithmetic Shift

  2. For +ve -> Logical Shift

Best Practices for securing a REST API / web service

One of the best posts I've ever come across regarding Security as it relates to REST is over at 1 RainDrop. The MySpace API's use OAuth also for security and you have full access to their custom channels in the RestChess code, which I did a lot of exploration with. This was demo'd at Mix and you can find the posting here.

Performing a Stress Test on Web Application?

A little late to this party. I agree that Pylot is the best up-and-coming open source tool out there. It's simple to use and is actively worked on by a great guy (Corey Goldberg). As the founder of OpenQA, I'm also happy that Pylot now is listed on our home page and uses some of our infrastructure (namely the forums).

However, I also recently decided that the entire concept of load testing was flawed: emulating HTTP traffic, with applications as complex as they have become, is a pain in the butt. That's why I created the commercial tool BrowserMob. It's an external load testing service that uses Selenium to control real web browsers when playing back load.

The approach obviously requires a ton more hardware than normal load testing techniques, but hardware is actually pretty cheap when you are using cloud computing. And a nice side effect of this is that the scripting is much easier than normal load testing. You don't have to do any advanced regex matching (like JMeter requires) to extract out cookies, .NET session state, Ajax request parameters, etc. Since you're using real browsers, they just do what they are supposed to do.

Sorry to blatantly pitch a commercial product, but hopefully the concept is interesting to some folks and at least gets them thinking about some new ways to deal with load testing when you have access to a bunch of extra hardware!

How to autosize a textarea using Prototype?

Using ASP.NET, just simply do this:

<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Automatic Resize TextBox</title>
        <script type="text/javascript">
            function setHeight(txtarea) {
                txtarea.style.height = txtdesc.scrollHeight + "px";
            }
        </script>
    </head>

    <body>
        <form id="form1" runat="server">
            <asp:TextBox ID="txtarea" runat= "server" TextMode="MultiLine"  onkeyup="setHeight(this);" onkeydown="setHeight(this);" />
        </form>
    </body>
</html>

PDF Editing in PHP?

I really had high hopes for dompdf (it is a cool idea) but the positioning issue are a major factor in my using fpdf. Though it is tedious as every element has to be set; it is powerful as all get out.

I lay an image underneath my workspace in the document to put my layout on top of to fit. Its always been sufficient even for columns (requires a tiny bit of php string calculation, but nothing too terribly heady).

Good luck.

What is Turing Complete?

I think the importance of the concept "Turing Complete" is in the the ability to identify a computing machine (not necessarily a mechanical/electrical "computer") that can have its processes be deconstructed into "simple" instructions, composed of simpler and simpler instructions, that a Universal machine could interpret and then execute.

I highly recommend The Annotated Turing

@Mark i think what you are explaining is a mix between the description of the Universal Turing Machine and Turing Complete.

Something that is Turing Complete, in a practical sense, would be a machine/process/computation able to be written and represented as a program, to be executed by a Universal Machine (a desktop computer). Though it doesn't take consideration for time or storage, as mentioned by others.

What is the difference between String and string in C#?

There is no difference.

The C# keyword string maps to the .NET type System.String - it is an alias that keeps to the naming conventions of the language.

Similarly, int maps to System.Int32.

How to show a GUI message box from a bash script in linux?

Kdialog and dialog are both good, but I'd recommend Zenity. Quick, easy, and much better looking the xmessage or dialog.

Graph visualization library in JavaScript

In a commercial scenario, a serious contestant for sure is yFiles for HTML:

It offers:

  • Easy import of custom data (this interactive online demo seems to pretty much do exactly what the OP was looking for)
  • Interactive editing for creating and manipulating the diagrams through user gestures (see the complete editor)
  • A huge programming API for customizing each and every aspect of the library
  • Support for grouping and nesting (both interactive, as well as through the layout algorithms)
  • Does not depend on a specfic UI toolkit but supports integration into almost any existing Javascript toolkit (see the "integration" demos)
  • Automatic layout (various styles, like "hierarchic", "organic", "orthogonal", "tree", "circular", "radial", and more)
  • Automatic sophisticated edge routing (orthogonal and organic edge routing with obstacle avoidance)
  • Incremental and partial layout (adding and removing elements and only slightly or not at all changing the rest of the diagram)
  • Support for grouping and nesting (both interactive, as well as through the layout algorithms)
  • Implementations of graph analysis algorithms (paths, centralities, network flows, etc.)
  • Uses HTML 5 technologies like SVG+CSS and Canvas and modern Javascript leveraging properties and other more ES5 and ES6 features (but for the same reason will not run in IE versions 8 and lower).
  • Uses a modular API that can be loaded on-demand using UMD loaders

Here is a sample rendering that shows most of the requested features:

Screenshot of a sample rendering created by the BPMN demo.

Full disclosure: I work for yWorks, but on Stackoverflow I do not represent my employer.

How to create a SQL Server function to "join" multiple rows from a subquery into a single delimited field?

With the other answers, the person reading the answer must be aware of the vehicle table and create the vehicle table and data to test a solution.

Below is an example that uses SQL Server "Information_Schema.Columns" table. By using this solution, no tables need to be created or data added. This example creates a comma separated list of column names for all tables in the database.

SELECT
    Table_Name
    ,STUFF((
        SELECT ',' + Column_Name
        FROM INFORMATION_SCHEMA.Columns Columns
        WHERE Tables.Table_Name = Columns.Table_Name
        ORDER BY Column_Name
        FOR XML PATH ('')), 1, 1, ''
    )Columns
FROM INFORMATION_SCHEMA.Columns Tables
GROUP BY TABLE_NAME 

How should I load files into my Java application?

getResource is fine, but using relative paths will work just as well too, as long as you can control where your working directory is (which you usually can).

Furthermore the platform dependence regarding the separator character can be gotten around using File.separator, File.separatorChar, or System.getProperty("file.separator").

C# loop - break vs. continue

By example

foreach(var i in Enumerable.Range(1,3))
{
    Console.WriteLine(i);
}

Prints 1, 2, 3 (on separate lines).

Add a break condition at i = 2

foreach(var i in Enumerable.Range(1,3))
{
    if (i == 2)
        break;

    Console.WriteLine(i);
}

Now the loop prints 1 and stops.

Replace the break with a continue.

foreach(var i in Enumerable.Range(1,3))
{
    if (i == 2)
        continue;

    Console.WriteLine(i);
}

Now to loop prints 1 and 3 (skipping 2).

Thus, break stops the loop, whereas continue skips to the next iteration.

Log4Net configuring log level

Use threshold.

For example:

   <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
        <threshold value="WARN"/>
        <param name="File" value="File.log" />
        <param name="AppendToFile" value="true" />
        <param name="RollingStyle" value="Size" />
        <param name="MaxSizeRollBackups" value="10" />
        <param name="MaximumFileSize" value="1024KB" />
        <param name="StaticLogFileName" value="true" />
        <layout type="log4net.Layout.PatternLayout">
            <param name="Header" value="[Server startup]&#13;&#10;" />
            <param name="Footer" value="[Server shutdown]&#13;&#10;" />
            <param name="ConversionPattern" value="%d %m%n" />
        </layout>
    </appender>
    <appender name="EventLogAppender" type="log4net.Appender.EventLogAppender" >
        <threshold value="ERROR"/>
        <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%date [%thread]- %message%newline" />
        </layout>
    </appender>
    <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
        <threshold value="INFO"/>
        <layout type="log4net.Layout.PatternLayout">
            <param name="ConversionPattern" value="%d [%thread] %m%n" />
        </layout>
    </appender>

In this example all INFO and above are sent to Console, all WARN are sent to file and ERRORs are sent to the Event-Log.

Getting the text from a drop-down box

This should return the text value of the selected value

var vSkill = document.getElementById('newSkill');

var vSkillText = vSkill.options[vSkill.selectedIndex].innerHTML;

alert(vSkillText);

Props: @Tanerax for reading the question, knowing what was asked and answering it before others figured it out.

Edit: DownModed, cause I actually read a question fully, and answered it, sad world it is.

SQL Server Escape an Underscore

Obviously @Lasse solution is right, but there's another way to solve your problem: T-SQL operator LIKE defines the optional ESCAPE clause, that lets you declare a character which will escape the next character into the pattern.

For your case, the following WHERE clauses are equivalent:

WHERE username LIKE '%[_]d';            -- @Lasse solution
WHERE username LIKE '%$_d' ESCAPE '$';
WHERE username LIKE '%^_d' ESCAPE '^';

IsNothing versus Is Nothing

If you take a look at the MSIL as it's being executed you'll see that it doesn't compile down to the exact same code. When you use IsNothing() it actually makes a call to that method as opposed to just evaluating the expression.

The reason I would tend to lean towards using "Is Nothing" is when I'm negating it becomes "IsNot Nothing' rather than "Not IsNothing(object)" which I personally feel looks more readable.

Tab Escape Character?

For someone who needs quick reference of C# Escape Sequences that can be used in string literals:

\t     Horizontal tab (ASCII code value: 9)

\n     Line feed (ASCII code value: 10)

\r     Carriage return (ASCII code value: 13)

\'     Single quotation mark

\"     Double quotation mark

\\     Backslash

\?     Literal question mark

\x12     ASCII character in hexadecimal notation (e.g. for 0x12)

\x1234     Unicode character in hexadecimal notation (e.g. for 0x1234)

It's worth mentioning that these (in most cases) are universal codes. So \t is 9 and \n is 10 char value on Windows and Linux. But newline sequence is not universal. On Windows it's \n\r and on Linux it's just \n. That's why it's best to use Environment.Newline which gets adjusted to current OS settings. With .Net Core it gets really important.

Equivalent VB keyword for 'break'

In both Visual Basic 6.0 and VB.NET you would use:

  • Exit For to break from For loop
  • Wend to break from While loop
  • Exit Do to break from Do loop

depending on the loop type. See Exit Statements for more details.

The imported project "C:\Microsoft.CSharp.targets" was not found

This error can also occur when opening a Silverlight project that was built in SL 4, while you have SL 5 installed.

Here is an example error message: The imported project "C:\Program Files (x86)\MSBuild\Microsoft\Silverlight\v4.0\Microsoft.Silverlight.CSharp.targets" was not found.

Note the v4.0.

To resolve, edit the project and find:

<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>

And change it to v5.0.

Then reload project and it will open (unless you do not have SL 5 installed).

x86 Assembly on a Mac

As stated before, don't use syscall. You can use standard C library calls though, but be aware that the stack MUST be 16 byte aligned per Apple's IA32 function call ABI.

If you don't align the stack, your program will crash in __dyld_misaligned_stack_error when you make a call into any of the libraries or frameworks.

The following snippet assembles and runs on my system:

; File: hello.asm
; Build: nasm -f macho hello.asm && gcc -o hello hello.o

SECTION .rodata
hello.msg db 'Hello, World!',0x0a,0x00

SECTION .text

extern _printf ; could also use _puts...
GLOBAL _main

; aligns esp to 16 bytes in preparation for calling a C library function
; arg is number of bytes to pad for function arguments, this should be a multiple of 16
; unless you are using push/pop to load args
%macro clib_prolog 1
    mov ebx, esp        ; remember current esp
    and esp, 0xFFFFFFF0 ; align to next 16 byte boundary (could be zero offset!)
    sub esp, 12         ; skip ahead 12 so we can store original esp
    push ebx            ; store esp (16 bytes aligned again)
    sub esp, %1         ; pad for arguments (make conditional?)
%endmacro

; arg must match most recent call to clib_prolog
%macro clib_epilog 1
    add esp, %1         ; remove arg padding
    pop ebx             ; get original esp
    mov esp, ebx        ; restore
%endmacro

_main:
    ; set up stack frame
    push ebp
    mov ebp, esp
    push ebx

    clib_prolog 16
    mov dword [esp], hello.msg
    call _printf
    ; can make more clib calls here...
    clib_epilog 16

    ; tear down stack frame
    pop ebx
    mov esp, ebp
    pop ebp
    mov eax, 0          ; set return code
    ret

How can I undo git reset --hard HEAD~1?

This has saved my life: https://medium.com/@CarrieGuss/how-to-recover-from-a-git-hard-reset-b830b5e3f60c

Basically you need to run:

for blob in $(git fsck --lost-found | awk ‘$2 == “blob” { print $3 }’); do git cat-file -p $blob > $blob.txt; done

Then manually going through the pain to re-organise your files to the correct structure.

Takeaway: Never use git reset --hard if you dont completely 100% understand how it works, best not to use it.

Python, Unicode, and the Windows console

Like Giampaolo Rodolà's answer, but even more dirty: I really, really intend to spend a long time (soon) understanding the whole subject of encodings and how they apply to Windoze consoles,

For the moment I just wanted sthg which would mean my program would NOT CRASH, and which I understood ... and also which didn't involve importing too many exotic modules (in particular I'm using Jython, so half the time a Python module turns out not in fact to be available).

def pr(s):
    try:
        print(s)
    except UnicodeEncodeError:
        for c in s:
            try:
                print( c, end='')
            except UnicodeEncodeError:
                print( '?', end='')

NB "pr" is shorter to type than "print" (and quite a bit shorter to type than "safeprint")...!

Length of a JavaScript object

This method gets all your object's property names in an array, so you can get the length of that array which is equal to your object's keys' length.

Object.getOwnPropertyNames({"hi":"Hi","msg":"Message"}).length; // => 2

Accessing post variables using Java Servlets

POST variables should be accessible via the request object: HttpRequest.getParameterMap(). The exception is if the form is sending multipart MIME data (the FORM has enctype="multipart/form-data"). In that case, you need to parse the byte stream with a MIME parser. You can write your own or use an existing one like the Apache Commons File Upload API.

SQL Server Management Studio alternatives to browse/edit tables and run queries

There is an express version on SSMS that has considerably fewer features but still has the basics.

Setting a div's height in HTML with CSS

No need to write own css, there is an library called "Bootstrap css" by calling that in your HTML head section, we can achieve many stylings,Here is an example: If you want to provide two column in a row, you can simply do the following:

_x000D_
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
_x000D_
<div class="row">_x000D_
  <div class="col-md-6">Content</div>_x000D_
  <div class="col-md-6">Content</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Here md stands for medium device,,you can use col-sm-6 for smaller devices and col-xs-6 for extra small devices

Using ConfigurationManager to load config from an arbitrary location

This should do the trick :

AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", "newAppConfig.config);

Source : https://www.codeproject.com/Articles/616065/Why-Where-and-How-of-NET-Configuration-Files

Learning Regular Expressions

The most important part is the concepts. Once you understand how the building blocks work, differences in syntax amount to little more than mild dialects. A layer on top of your regular expression engine's syntax is the syntax of the programming language you're using. Languages such as Perl remove most of this complication, but you'll have to keep in mind other considerations if you're using regular expressions in a C program.

If you think of regular expressions as building blocks that you can mix and match as you please, it helps you learn how to write and debug your own patterns but also how to understand patterns written by others.

Start simple

Conceptually, the simplest regular expressions are literal characters. The pattern N matches the character 'N'.

Regular expressions next to each other match sequences. For example, the pattern Nick matches the sequence 'N' followed by 'i' followed by 'c' followed by 'k'.

If you've ever used grep on Unix—even if only to search for ordinary looking strings—you've already been using regular expressions! (The re in grep refers to regular expressions.)

Order from the menu

Adding just a little complexity, you can match either 'Nick' or 'nick' with the pattern [Nn]ick. The part in square brackets is a character class, which means it matches exactly one of the enclosed characters. You can also use ranges in character classes, so [a-c] matches either 'a' or 'b' or 'c'.

The pattern . is special: rather than matching a literal dot only, it matches any character. It's the same conceptually as the really big character class [-.?+%$A-Za-z0-9...].

Think of character classes as menus: pick just one.

Helpful shortcuts

Using . can save you lots of typing, and there are other shortcuts for common patterns. Say you want to match a digit: one way to write that is [0-9]. Digits are a frequent match target, so you could instead use the shortcut \d. Others are \s (whitespace) and \w (word characters: alphanumerics or underscore).

The uppercased variants are their complements, so \S matches any non-whitespace character, for example.

Once is not enough

From there, you can repeat parts of your pattern with quantifiers. For example, the pattern ab?c matches 'abc' or 'ac' because the ? quantifier makes the subpattern it modifies optional. Other quantifiers are

  • * (zero or more times)
  • + (one or more times)
  • {n} (exactly n times)
  • {n,} (at least n times)
  • {n,m} (at least n times but no more than m times)

Putting some of these blocks together, the pattern [Nn]*ick matches all of

  • ick
  • Nick
  • nick
  • Nnick
  • nNick
  • nnick
  • (and so on)

The first match demonstrates an important lesson: * always succeeds! Any pattern can match zero times.

A few other useful examples:

  • [0-9]+ (and its equivalent \d+) matches any non-negative integer
  • \d{4}-\d{2}-\d{2} matches dates formatted like 2019-01-01

Grouping

A quantifier modifies the pattern to its immediate left. You might expect 0abc+0 to match '0abc0', '0abcabc0', and so forth, but the pattern immediately to the left of the plus quantifier is c. This means 0abc+0 matches '0abc0', '0abcc0', '0abccc0', and so on.

To match one or more sequences of 'abc' with zeros on the ends, use 0(abc)+0. The parentheses denote a subpattern that can be quantified as a unit. It's also common for regular expression engines to save or "capture" the portion of the input text that matches a parenthesized group. Extracting bits this way is much more flexible and less error-prone than counting indices and substr.

Alternation

Earlier, we saw one way to match either 'Nick' or 'nick'. Another is with alternation as in Nick|nick. Remember that alternation includes everything to its left and everything to its right. Use grouping parentheses to limit the scope of |, e.g., (Nick|nick).

For another example, you could equivalently write [a-c] as a|b|c, but this is likely to be suboptimal because many implementations assume alternatives will have lengths greater than 1.

Escaping

Although some characters match themselves, others have special meanings. The pattern \d+ doesn't match backslash followed by lowercase D followed by a plus sign: to get that, we'd use \\d\+. A backslash removes the special meaning from the following character.

Greediness

Regular expression quantifiers are greedy. This means they match as much text as they possibly can while allowing the entire pattern to match successfully.

For example, say the input is

"Hello," she said, "How are you?"

You might expect ".+" to match only 'Hello,' and will then be surprised when you see that it matched from 'Hello' all the way through 'you?'.

To switch from greedy to what you might think of as cautious, add an extra ? to the quantifier. Now you understand how \((.+?)\), the example from your question works. It matches the sequence of a literal left-parenthesis, followed by one or more characters, and terminated by a right-parenthesis.

If your input is '(123) (456)', then the first capture will be '123'. Non-greedy quantifiers want to allow the rest of the pattern to start matching as soon as possible.

(As to your confusion, I don't know of any regular-expression dialect where ((.+?)) would do the same thing. I suspect something got lost in transmission somewhere along the way.)

Anchors

Use the special pattern ^ to match only at the beginning of your input and $ to match only at the end. Making "bookends" with your patterns where you say, "I know what's at the front and back, but give me everything between" is a useful technique.

Say you want to match comments of the form

-- This is a comment --

you'd write ^--\s+(.+)\s+--$.

Build your own

Regular expressions are recursive, so now that you understand these basic rules, you can combine them however you like.

Tools for writing and debugging regexes:

Books

Free resources

Footnote

†: The statement above that . matches any character is a simplification for pedagogical purposes that is not strictly true. Dot matches any character except newline, "\n", but in practice you rarely expect a pattern such as .+ to cross a newline boundary. Perl regexes have a /s switch and Java Pattern.DOTALL, for example, to make . match any character at all. For languages that don't have such a feature, you can use something like [\s\S] to match "any whitespace or any non-whitespace", in other words anything.

Recommended Fonts for Programming?

I experimented with Myriad until I realised using a variable-width font was a fools game.

Courier New here, although I am going to try out Envy after seeing it here.

SQL Case Expression Syntax?

The complete syntax depends on the database engine you're working with:

For SQL Server:

CASE case-expression
    WHEN when-expression-1 THEN value-1
  [ WHEN when-expression-n THEN value-n ... ]
  [ ELSE else-value ]
END

or:

CASE
    WHEN boolean-when-expression-1 THEN value-1
  [ WHEN boolean-when-expression-n THEN value-n ... ]
  [ ELSE else-value ]
END

expressions, etc:

case-expression    - something that produces a value
when-expression-x  - something that is compared against the case-expression
value-1            - the result of the CASE statement if:
                         the when-expression == case-expression
                      OR the boolean-when-expression == TRUE
boolean-when-exp.. - something that produces a TRUE/FALSE answer

Link: CASE (Transact-SQL)

Also note that the ordering of the WHEN statements is important. You can easily write multiple WHEN clauses that overlap, and the first one that matches is used.

Note: If no ELSE clause is specified, and no matching WHEN-condition is found, the value of the CASE expression will be NULL.

How to easily consume a web service from PHP

HI I got this from this site : http://forums.asp.net/t/887892.aspx?Consume+an+ASP+NET+Web+Service+with+PHP

The web service has method Add which takes two params:

<?php
    $client = new SoapClient("http://localhost/csharp/web_service.asmx?wsdl");

     print_r( $client->Add(array("a" => "5", "b" =>"2")));
?>

How do I update Ruby Gems from behind a Proxy (ISA-NTLM)

If you are having problems getting authenticated through your proxy, be sure to set the environment variables in exactly the format below:

set HTTP_PROXY=some.proxy.com
set HTTP_PROXY_USER=user
set HTTP_PROXY_PASS=password

The user:password@ syntax doesn't seem to work and there are also some badly named environment variables floating around on Stack Overflow and various forum posts.

Also be aware that it can take a while for your gems to start downloading. At first I thought it wasn't working but with a bit of patience they started downloading as expected.

Drop all tables whose names begin with a certain string

I saw this post when I was looking for mysql statement to drop all WordPress tables based on @Xenph Yan here is what I did eventually:

SELECT CONCAT(  'DROP TABLE `', TABLE_NAME,  '`;' ) AS query
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME LIKE  'wp_%'

this will give you the set of drop queries for all tables begins with wp_

How do I retrieve my MySQL username and password?

If you have root access to the server where mysql is running you should stop the mysql server using this command

sudo service mysql stop

Now start mysql using this command

sudo /usr/sbin/mysqld --skip-grant-tables  --skip-networking &

Now you can login to mysql using

sudo mysql
FLUSH PRIVILEGES;
SET PASSWORD FOR 'root'@'localhost' = PASSWORD('MyNewPass');

Full instructions can be found here http://www.techmatterz.com/recover-mysql-root-password/

How to include PHP files that require an absolute path?

have a look at http://au.php.net/reserved.variables

I think the variable you are looking for is: $_SERVER["DOCUMENT_ROOT"]

Accessing a Dictionary.Keys Key through a numeric index

In case you decide to use dangerous code that is subject to breakage, this extension function will fetch a key from a Dictionary<K,V> according to its internal indexing (which for Mono and .NET currently appears to be in the same order as you get by enumerating the Keys property).

It is much preferable to use Linq: dict.Keys.ElementAt(i), but that function will iterate O(N); the following is O(1) but with a reflection performance penalty.

using System;
using System.Collections.Generic;
using System.Reflection;

public static class Extensions
{
    public static TKey KeyByIndex<TKey,TValue>(this Dictionary<TKey, TValue> dict, int idx)
    {
        Type type = typeof(Dictionary<TKey, TValue>);
        FieldInfo info = type.GetField("entries", BindingFlags.NonPublic | BindingFlags.Instance);
        if (info != null)
        {
            // .NET
            Object element = ((Array)info.GetValue(dict)).GetValue(idx);
            return (TKey)element.GetType().GetField("key", BindingFlags.Public | BindingFlags.Instance).GetValue(element);
        }
        // Mono:
        info = type.GetField("keySlots", BindingFlags.NonPublic | BindingFlags.Instance);
        return (TKey)((Array)info.GetValue(dict)).GetValue(idx);
    }
};

What Are Some Good .NET Profilers?

ANTS Profiler. I haven't used many, but I don't really have any complaints about ANTS. The visualization is really helpful.

IllegalArgumentException or NullPointerException for a null parameter?

NullPointerException thrown when attempting to access an object with a reference variable whose current value is null.

IllegalArgumentException thrown when a method receives an argument formatted differently than the method expects.

Storing Images in DB - Yea or Nay?

If you are on Teradata, then Teradata Developer Exchange has a detailed article on loading and retrieving lobs and blobs..

http://developer.teradata.com/applications/articles/large-objects-part-1-loading

Call ASP.NET function from JavaScript?

The Microsoft AJAX library will accomplish this. You could also create your own solution that involves using AJAX to call your own aspx (as basically) script files to run .NET functions.

This is the library called AjaxPro which was written an MVP named Michael Schwarz. This was library was not written by Microsoft.

I have used AjaxPro extensively, and it is a very nice library, that I would recommend for simple callbacks to the server. It does function well with the Microsoft version of Ajax with no issues. However, I would note, with how easy Microsoft has made Ajax, I would only use it if really necessary. It takes a lot of JavaScript to do some really complicated functionality that you get from Microsoft by just dropping it into an update panel.

Create a new Ruby on Rails application using MySQL instead of SQLite

you first should make sure that MySQL driver is on your system if not run this on your terminal if you are using Ubuntu or any Debian distro

sudo apt-get install mysql-client libmysqlclient-dev

and add this to your Gemfile

gem 'mysql2', '~> 0.3.16'

then run in your root directory of the project

bundle install

after that you can add the mysql config to config/database.yml as the previous answers

SQL Client for Mac OS X that works with MS SQL Server

When this question was asked there were very few tools out there were worth much. I also ended up using Fusion and a Windows client. I have tried just about everything for MAC and Linux and never found anything worthwhile. That included dbvisualizer, squirrel (particularly bad, even though the windows haters in my office swear by it), the oracle SQL developer and a bunch of others. Nothing compared to DBArtizan on Windows as far as I was concerned and I was prepared to use it with Fusion or VirtualBox. I don't use the MS product because it is only limited to MS SQL.

Bottom line is nothing free is worthwhile, nor were most commercial non windows products

However, now (March 2010) I believe there are two serious contenders and worthwhile versions for the MAC and Linux which have a low cost associated with them. The first one is Aqua Data Studio which costs about $450 per user, which is a barely acceptable, but cheap compared to DBArtizan and others with similar functionality (but MS only). The other is RazorSQL which only costs $69 per user. Aqua data studio is good, but a resource hog and basically pretty sluggish and has non essential features such as the ER diagram tool, which is pretty bad at that. The Razor is lightning fast and is only a 16meg download and has everything an SQL developer needs including a TSQL editor.

So the big winner is RazorSQL and for $69, well worth it and feature ridden. Believe me, after several years of waiting to find a cheap non windows substitute for DBartizan, I have finally found one and I have been very picky.

Multiple Updates in MySQL

Why does no one mention multiple statements in one query?

In php, you use multi_query method of mysqli instance.

From the php manual

MySQL optionally allows having multiple statements in one statement string. Sending multiple statements at once reduces client-server round trips but requires special handling.

Here is the result comparing to other 3 methods in update 30,000 raw. Code can be found here which is based on answer from @Dakusan

Transaction: 5.5194580554962
Insert: 0.20669293403625
Case: 16.474853992462
Multi: 0.0412278175354

As you can see, multiple statements query is more efficient than the highest answer.

If you get error message like this:

PHP Warning:  Error while sending SET_OPTION packet

You may need to increase the max_allowed_packet in mysql config file which in my machine is /etc/mysql/my.cnf and then restart mysqld.

MAC addresses in JavaScript

The quick and simple answer is No.

Javascript is quite a high level language and does not have access to this sort of information.

Capturing TAB key in text box

there is a problem in best answer given by ScottKoon

here is it

} else if(el.attachEvent ) {
    myInput.attachEvent('onkeydown',this.keyHandler); /* damn IE hack */
}

Should be

} else if(myInput.attachEvent ) {
    myInput.attachEvent('onkeydown',this.keyHandler); /* damn IE hack */
}

Due to this it didn't work in IE. Hoping that ScottKoon will update code

How to set background color of HTML element using css properties in JavaScript

$("body").css("background","green"); //jQuery

document.body.style.backgroundColor = "green"; //javascript

so many ways are there I think it is very easy and simple

Demo On Plunker

Why can't I have abstract static methods in C#?

Here is a situation where there is definitely a need for inheritance for static fields and methods:

abstract class Animal
{
  protected static string[] legs;

  static Animal() {
    legs=new string[0];
  }

  public static void printLegs()
  {
    foreach (string leg in legs) {
      print(leg);
    }
  }
}


class Human: Animal
{
  static Human() {
    legs=new string[] {"left leg", "right leg"};
  }
}


class Dog: Animal
{
  static Dog() {
    legs=new string[] {"left foreleg", "right foreleg", "left hindleg", "right hindleg"};
  }
}


public static void main() {
  Dog.printLegs();
  Human.printLegs();
}


//what is the output?
//does each subclass get its own copy of the array "legs"?

Big O, how do you calculate/approximate it?

I don't know how to programmatically solve this, but the first thing people do is that we sample the algorithm for certain patterns in the number of operations done, say 4n^2 + 2n + 1 we have 2 rules:

  1. If we have a sum of terms, the term with the largest growth rate is kept, with other terms omitted.
  2. If we have a product of several factors constant factors are omitted.

If we simplify f(x), where f(x) is the formula for number of operations done, (4n^2 + 2n + 1 explained above), we obtain the big-O value [O(n^2) in this case]. But this would have to account for Lagrange interpolation in the program, which may be hard to implement. And what if the real big-O value was O(2^n), and we might have something like O(x^n), so this algorithm probably wouldn't be programmable. But if someone proves me wrong, give me the code . . . .

Best ways to teach a beginner to program?

Project Euler has a number of interesting mathematics problems that could provide great material for a beginning programmer to cut her teeth on. The problems begin easy and increase in difficulty and the web is full of sample solutions in various programming languages.

Calling a function of a module by using its name (a string)

Patrick's solution is probably the cleanest. If you need to dynamically pick up the module as well, you can import it like:

module = __import__('foo')
func = getattr(module, 'bar')
func()

What is Inversion of Control?

A very simple written explanation can be found here

http://binstock.blogspot.in/2008/01/excellent-explanation-of-dependency.html

It says -

"Any nontrivial application is made up of two or more classes that collaborate with each other to perform some business logic. Traditionally, each object is responsible for obtaining its own references to the objects it collaborates with (its dependencies). When applying DI, the objects are given their dependencies at creation time by some external entity that coordinates each object in the system. In other words, dependencies are injected into objects."

What's the safest way to iterate through the keys of a Perl hash?

The place where each can cause you problems is that it's a true, non-scoped iterator. By way of example:

while ( my ($key,$val) = each %a_hash ) {
    print "$key => $val\n";
    last if $val; #exits loop when $val is true
}

# but "each" hasn't reset!!
while ( my ($key,$val) = each %a_hash ) {
    # continues where the last loop left off
    print "$key => $val\n";
}

If you need to be sure that each gets all the keys and values, you need to make sure you use keys or values first (as that resets the iterator). See the documentation for each.

What is recursion and when should I use it?

"If I have a hammer, make everything look like a nail."

Recursion is a problem-solving strategy for huge problems, where at every step just, "turn 2 small things into one bigger thing," each time with the same hammer.

Example

Suppose your desk is covered with a disorganized mess of 1024 papers. How do you make one neat, clean stack of papers from the mess, using recursion?

  1. Divide: Spread all the sheets out, so you have just one sheet in each "stack".
  2. Conquer:
    1. Go around, putting each sheet on top of one other sheet. You now have stacks of 2.
    2. Go around, putting each 2-stack on top of another 2-stack. You now have stacks of 4.
    3. Go around, putting each 4-stack on top of another 4-stack. You now have stacks of 8.
    4. ... on and on ...
    5. You now have one huge stack of 1024 sheets!

Notice that this is pretty intuitive, aside from counting everything (which isn't strictly necessary). You might not go all the way down to 1-sheet stacks, in reality, but you could and it would still work. The important part is the hammer: With your arms, you can always put one stack on top of the other to make a bigger stack, and it doesn't matter (within reason) how big either stack is.

How can we generate getters and setters in Visual Studio?

First get Extension just press (Ctrl + Shift + X) and install getter setter ....

After this, just select your variable and right click. Go to Command palette...

And type getter ... It will suggest generate get and set methods. Click on this...