SyntaxFix.com - Programming Questions & Answers Hub For Beginners

Some Of The Best Answers From Latest Asked Questions

What is the difference between varchar and nvarchar?

Is it just that nvarchar supports multibyte characters? If that is the case, is there really any point, other than storage concerns, to using varchars?...

How do you run a single test/spec file in RSpec?

I want to be able to run a single spec file's tests — for the one file I'm editing, for example. rake spec executes all the specs. My project is not a Rails project, so rake spec:doc doesn't work. Don't know if this matters, but here is my d...

Best way to find if an item is in a JavaScript array?

What is the best way to find if an object is in an array? This is the best way I know: _x000D_ _x000D_ function include(arr, obj) {_x000D_ for (var i = 0; i < arr.length; i++) {_x000D_ if (arr[i] == obj) return true;_x000D_ }_x000D_ }_x0...

Ruby: character to ascii from a string

this wiki page gave a general idea of how to convert a single char to ascii http://en.wikibooks.org/wiki/Ruby_Programming/ASCII But say if I have a string and I wanted to get each character's ascii from it, what do i need to do? "string".each_byte ...

How do I find which process is leaking memory?

I have a system (Ubuntu) with many processes and one (or more) have a memory leak. Is there a good way to find the process that has the leak? Some of the process are JVMs, some are not. Some are home grown some are open source....

Exception thrown inside catch block - will it be caught again?

This may seem like a programming 101 question and I had thought I knew the answer but now find myself needing to double check. In this piece of code below, will the exception thrown in the first catch block then be caught by the general Exception cat...

How can I modify a saved Microsoft Access 2007 or 2010 Import Specification?

Does anyone know how to modify an existing import specification in Microsoft Access 2007 or 2010? In older versions there used to be an Advanced button presented during the import wizard that allowed you to select and edit an existing specification....

C# Interfaces. Implicit implementation versus Explicit implementation

What are the differences in implementing interfaces implicitly and explicitly in C#? When should you use implicit and when should you use explicit? Are there any pros and/or cons to one or the other? Microsoft's official guidelines (from first e...

How do I get the directory that a program is running from?

Is there a platform-agnostic and filesystem-agnostic method to obtain the full path of the directory from where a program is running using C/C++? Not to be confused with the current working directory. (Please don't suggest libraries unless they're st...

How can I use xargs to copy files that have spaces and quotes in their names?

I'm trying to copy a bunch of files below a directory and a number of the files have spaces and single-quotes in their names. When I try to string together find and grep with xargs, I get the following error: find .|grep "FooBar"|xargs -I{} cp "{}"...

Automated Python to Java translation

Is there a tool out there that can automatically convert Python to Java? Can Jython do this?...

Resizing an iframe based on content

I am working on an iGoogle-like application. Content from other applications (on other domains) is shown using iframes. How do I resize the iframes to fit the height of the iframes' content? I've tried to decipher the javascript Google uses but it...

Converting a pointer into an integer

I am trying to adapt an existing code to a 64 bit machine. The main problem is that in one function, the previous coder uses a void* argument that is converted into suitable type in the function itself. A short example: void function(MESSAGE_ID id, ...

How do I detect a click outside an element?

I have some HTML menus, which I show completely when a user clicks on the head of these menus. I would like to hide these elements when the user clicks outside the menus' area. Is something like this possible with jQuery? $("#menuscontainer").click...

How to insert a string which contains an "&"

How can I write an insert statement which includes the & character? For example, if I wanted to insert "J&J Construction" into a column in the database. I'm not sure if it makes a difference, but I'm using Oracle 9i....

Default port for SQL Server

I need to know the default port settings for the following services SQL Server SQL Browser SQL Reporting services SQL Analysis services I neeed to know the port settings for these services for different versions of SQL Server (2000,2005,2008) A...

How can I search for a multiline pattern in a file?

I needed to find all the files that contained a specific string pattern. The first solution that comes to mind is using find piped with xargs grep: find . -iname '*.py' | xargs grep -e 'YOUR_PATTERN' But if I need to find patterns that spans on mo...

Is Eclipse the best IDE for Java?

Is Eclipse the best IDE for Java? If not, is there something better? I want to know and possibly try it out. Thanks....

What's the canonical way to check for type in Python?

What is the best way to check whether a given object is of a given type? How about checking whether the object inherits from a given type? Let's say I have an object o. How do I check whether it's a str?...

*.h or *.hpp for your class definitions

I've always used a *.h file for my class definitions, but after reading some boost library code, I realised they all use *.hpp. I've always had an aversion to that file extension, I think mainly because I'm not used to it. What are the advantages an...

How do I rename all folders and files to lowercase on Linux?

I have to rename a complete folder tree recursively so that no uppercase letter appears anywhere (it's C++ source code, but that shouldn't matter). Bonus points for ignoring CVS and Subversion version control files/folders. The preferred way would b...

What is the difference between a port and a socket?

This was a question raised by one of the software engineers in my organisation. I'm interested in the broadest definition....

SQL-Server: Is there a SQL script that I can use to determine the progress of a SQL Server backup or restore process?

When I backup or restore a database using MS SQL Server Management Studio, I get a visual indication of how far the process has progressed, and thus how much longer I still need to wait for it to finish. If I kick off the backup or restore with a scr...

VBA array sort function?

I'm looking for a decent sort implementation for arrays in VBA. A Quicksort would be preferred. Or any other sort algorithm other than bubble or merge would suffice. Please note that this is to work with MS Project 2003, so should avoid any of the E...

WSDL validator?

Is there any online service available to validate Web Service WSDL file?...

When to use self over $this?

In PHP 5, what is the difference between using self and $this? When is each appropriate?...

How do I control how Emacs makes backup files?

Emacs puts backup files named foo~ everywhere and I don't like having to remember to delete them. Also, if I edit a file that has a hard link somewhere else in the file system, the hard link points to the backup when I'm done editing, and that's con...

How to save an activity state using save instance state?

I've been working on the Android SDK platform, and it is a little unclear how to save an application's state. So given this minor re-tooling of the 'Hello, Android' example: package com.android.hello; import android.app.Activity; import android.os....

How to detect a remote side socket close?

How do you detect if Socket#close() has been called on a socket on the remote side?...

Difference between a class and a module

I came from Java, and now I am working more with Ruby. One language feature I am not familiar with is the module. I am wondering what exactly is a module and when do you use one, and why use a module over a class?...

Has anyone ever got a remote JMX JConsole to work?

It seems that I've never got this to work in the past. Currently, I KNOW it doesn't work. But we start up our Java process: -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=6002 -Dcom.sun.management.jmxremote.authenticate=false -D...

How to calculate number of days between two given dates?

If I have two dates (ex. '8/18/2008' and '9/26/2008'), what is the best way to get the number of days between these two dates?...

When should I use GC.SuppressFinalize()?

In .NET, under which circumstances should I use GC.SuppressFinalize()? What advantage(s) does using this method give me?...

How can I call controller/view helper methods from the console in Ruby on Rails?

When I load script/console, sometimes I want to play with the output of a controller or a view helper method. Are there ways to: simulate a request? call methods from a controller instance on said request? test helper methods, either via said cont...

How do I unlock a SQLite database?

sqlite> DELETE FROM mails WHERE (`id` = 71); SQL error: database is locked How do I unlock the database so this will work?...

How do I create an Excel (.XLS and .XLSX) file in C# without installing Microsoft Office?

How can I create an Excel spreadsheet with C# without requiring Excel to be installed on the machine that's running the code?...

HashSet vs. List performance

It's clear that a search performance of the generic HashSet<T> class is higher than of the generic List<T> class. Just compare the hash-based key with the linear approach in the List<T> class. However calculating a hash key may its...

Which browser has the best support for HTML 5 currently?

Where can I test HTML 5 functionality today - is there any test build of any rendering engines which would allow testing, or is it to early? I'm aware that much of the spec hasn't been finalised, but some has, and it would be good to try it out!...

Capturing URL parameters in request.GET

I am currently defining regular expressions in order to capture parameters in a URL, as described in the tutorial. How do I access parameters from the URL as part the HttpRequest object? My HttpRequest.GET currently returns an empty QueryDict object....

Order of items in classes: Fields, Properties, Constructors, Methods

Is there an official C# guideline for the order of items in terms of class structure? Does it go: Public Fields Private Fields Properties Constructors Methods ? I'm curious if there is a hard and fast rule about the order of items? I'm kind of a...

How do I detect when someone shakes an iPhone?

I want to react when somebody shakes the iPhone. I don't particularly care how they shake it, just that it was waved vigorously about for a split second. Does anyone know how to detect this?...

Programmatically find the number of cores on a machine

Is there a way to determine how many cores a machine has from C/C++ in a platform-independent way? If no such thing exists, what about determining it per-platform (Windows/*nix/Mac)?...

Using underscores in Java variables and method names

Even nowadays I often see underscores in Java variables and methods, an example are member variables (like "m_count" or "_count"). As far as I remember, to use underscores in these cases is called bad style by Sun. The only place they should be used...

How do I list / export private keys from a keystore?

How do I list and export a private key from a keystore?...

How to run Visual Studio post-build events for debug build only

How can I limit my post-build events to running only for one type of build? I'm using the events to copy DLL files to a local IIS virtual directory, but I don't want this happening on the build server in release mode....

Regular expression to match non-ASCII characters?

What is the easiest way to match non-ASCII characters in a regex? I would like to match all words individually in an input string, but the language may not be English, so I will need to match things like ü, ö, ß, and ñ. Also, this is in Javascrip...

How do you copy a record in a SQL table but swap out the unique id of the new row?

This question comes close to what I need, but my scenario is slightly different. The source table and destination table are the same and the primary key is a uniqueidentifier (guid). When I try this: insert into MyTable select * from MyTable whe...

How to use GROUP BY to concatenate strings in MySQL?

Basically the question is how to get from this: foo_id foo_name 1 A 1 B 2 C to this: foo_id foo_name 1 A B 2 C ...

Check if option is selected with jQuery, if not select a default

Using jQuery, how do you check if there is an option selected in a select menu, and if not, assign one of the options as selected. (The select is generated with a maze of PHP functions in an app I just inherited, so this is a quick fix while I get m...

Adding a caption to an equation in LaTeX

Well, it seems simple enough, but I can't find a way to add a caption to an equation. The caption is needed to explain the variables used in the equation, so some kind of table-like structure to keep it all aligned and pretty would be great....

What are some ways of accessing Microsoft SQL Server from Linux?

We have a Windows machine running SQL Server 2005, and we need to be able to run some database queries on it from a Linux box. What are some of the recommended ways of doing this? Ideally, we would want a command-line utility similar to sqlcmd on W...

HTTP vs HTTPS performance

Are there any major differences in performance between http and https? I seem to recall reading that HTTPS can be a fifth as fast as HTTP. Is this valid with the current generation webservers/browsers? If so, are there any whitepapers to support i...

How to format numbers as currency string?

I would like to format a price in JavaScript. I'd like a function which takes a float as an argument and returns a string formatted like this: "$ 2,500.00" What's the best way to do this?...

Visual Studio keyboard shortcut to automatically add the needed 'using' statement

What is the keyboard shortcut to expand the little red line that gives you the menu where you can choose to have the necessary using statement added to the top of the file?...

Windows batch files: .bat vs .cmd?

As I understand it, .bat is the old 16-bit naming convention, and .cmd is for 32-bit Windows, i.e., starting with NT. But I continue to see .bat files everywhere, and they seem to work exactly the same using either suffix. Assuming that my code will ...

Is there a better way to do optional function parameters in JavaScript?

I've always handled optional parameters in JavaScript like this: function myFunc(requiredArg, optionalArg){ optionalArg = optionalArg || 'defaultValue'; // Do stuff } Is there a better way to do it? Are there any cases where using || like th...

What is the difference between a framework and a library?

What is the difference between a framework and a library? I always thought of a library as a set of objects and functions that focuses on solving a particular problem or a specific area of application development (i.e. database access); and a frame...

Unloading classes in java?

I have a custom class loader so that a desktop application can dynamically start loading classes from an AppServer I need to talk to. We did this since the amount of jars that are required to do this are ridiculous (if we wanted to ship them). We als...

Oracle: is there a tool to trace queries, like Profiler for sql server?

i work with sql server, but i must migrate to an application with Oracle DB. for trace my application queries, in Sql Server i use wonderful Profiler tool. is there something of equivalent for Oracle?...

How to use sed to replace only the first occurrence in a file?

I would like to update a large number of C++ source files with an extra include directive before any existing #includes. For this sort of task, I normally use a small bash script with sed to re-write the file. How do I get sed to replace just the f...

Are there any disadvantages to always using nvarchar(MAX)?

In SQL Server 2005, are there any disadvantages to making all character fields nvarchar(MAX) rather than specifying a length explicitly, e.g. nvarchar(255)? (Apart from the obvious one that you aren't able to limit the field length at the database le...

Loading .sql files from within PHP

I'm creating an installation script for an application that I'm developing and need to create databases dynamically from within PHP. I've got it to create the database but now I need to load in several .sql files. I had planned to open the file and m...

Character reading from file in Python

In a text file, there is a string "I don't like this". However, when I read it into a string, it becomes "I don\xe2\x80\x98t like this". I understand that \u2018 is the unicode representation of "'". I use f1 = open (file1, "r") text = f1.read() ...

Get list of databases from SQL Server

How can I get the list of available databases on a SQL Server instance? I'm planning to make a list of them in a combo box in VB.NET....

Best way to detect when a user leaves a web page?

What is the best way to detect if a user leaves a web page? The onunload JavaScript event doesn't work every time (the HTTP request takes longer than the time required to terminate the browser). Creating one will probably be blocked by current brow...

Is there a cross-browser onload event when clicking the back button?

For all major browsers (except IE), the JavaScript onload event doesn’t fire when the page loads as a result of a back button operation — it only fires when the page is first loaded. Can someone point me at some sample cross-browser code (Firefo...

How can I save a screenshot directly to a file in Windows?

Is there a one button way to save a screenshot directly to a file in Windows? TheSoftwareJedi accurately answered above question for Windows 8 and 10. Below original extra material remains for posterity. This is a very important question as the 31...

How to position one element relative to another with jQuery?

I have a hidden DIV which contains a toolbar-like menu. I have a number of DIVs which are enabled to show the menu DIV when the mouse hovers over them. Is there a built-in function which will move the menu DIV to the top right of the active (mouse ...

How to use 'find' to search for files created on a specific date?

How do I use the UNIX command find to search for files created on a specific date?...

Create ArrayList from array

I have an array that is initialized like: Element[] array = {new Element(1), new Element(2), new Element(3)}; I would like to convert this array into an object of the ArrayList class. ArrayList<Element> arraylist = ???; ...

Hiding a password in a python script (insecure obfuscation only)

I have got a python script which is creating an ODBC connection. The ODBC connection is generated with a connection string. In this connection string I have to include the username and password for this connection. Is there an easy way to obscure ...

How do I get the MAX row with a GROUP BY in LINQ query?

I am looking for a way in LINQ to match the follow SQL Query. Select max(uid) as uid, Serial_Number from Table Group BY Serial_Number Really looking for some help on this one. The above query gets the max uid of each Serial Number because of the ...

VBScript -- Using error handling

I want to use VBScript to catch errors and log them (ie on error "log something") then resume the next line of the script. For example, On Error Resume Next 'Do Step 1 'Do Step 2 'Do Step 3 When an error occurs on step 1, I want it to log that e...

Best way to encode text data for XML

I was looking for a generic method in .Net to encode a string for use in an Xml element or attribute, and was surprised when I didn't immediately find one. So, before I go too much further, could I just be missing the built-in function? Assuming ...

Is mathematics necessary for programming?

I happened to debate with a friend during college days whether advanced mathematics is necessary for any veteran programmer. He used to argue fiercely against that. He said that programmers need only basic mathematical knowledge from high school or f...

What's the best way to loop through a set of elements in JavaScript?

In the past and with most my current projects I tend to use a for loop like this: var elements = document.getElementsByTagName('div'); for (var i=0; i<elements.length; i++) { doSomething(elements[i]); } I've heard that using a "reverse whil...

What's the difference between an argument and a parameter?

When verbally talking about methods, I'm never sure whether to use the word argument or parameter or something else. Either way the other people know what I mean, but what's correct, and what's the history of the terms? I'm a C# programmer, but I al...

What is the default lifetime of a session?

If I hit a page which calls session_start(), how long would I have to wait before I get a new session ID when I refresh the page?...

How to start automatic download of a file in Internet Explorer?

How do I initialize an automatic download of a file in Internet Explorer? For example, in the download page, I want the download link to appear and a message: "If you download doesn't start automatically .... etc". The download should begin shortly ...

How do you assert that a certain exception is thrown in JUnit 4 tests?

How can I use JUnit4 idiomatically to test that some code throws an exception? While I can certainly do something like this: @Test public void testFooThrowsIndexOutOfBoundsException() { boolean thrown = false; try { foo.doStuff(); } catc...

How to import a SQL Server .bak file into MySQL?

The title is self explanatory. Is there a way of directly doing such kind of importing?...

What is the equivalent of the C++ Pair<L,R> in Java?

Is there a good reason why there is no Pair<L,R> in Java? What would be the equivalent of this C++ construct? I would rather avoid reimplementing my own. It seems that 1.6 is providing something similar (AbstractMap.SimpleEntry<K,V>), bu...

What are best practices that you use when writing Objective-C and Cocoa?

I know about the HIG (which is quite handy!), but what programming practices do you use when writing Objective-C, and more specifically when using Cocoa (or CocoaTouch)....

How do you loop through each line in a text file using a windows batch file?

I would like to know how to loop through each line in a text file using a Windows batch file and process each line of text in succession....

PHP Session data not being saved

I have one of those "I swear I didn't touch the server" situations. I honestly didn't touch any of the php scripts. The problem I am having is that php data is not being saved across different pages or page refreshes. I know a new session is being cr...

ASP.NET MVC - passing parameters to the controller

I have a controller with an action method as follows: public class InventoryController : Controller { public ActionResult ViewStockNext(int firstItem) { // Do some stuff } } And when I run it I get an error stating: The par...

How do I specify the exit code of a console application in .NET?

I have a trivial console application in .NET. It's just a test part of a larger application. I'd like to specify the "exit code" of my console application. How do I do this?...

What's the difference between a method and a function?

Can someone provide a simple explanation of methods vs. functions in OOP context?...

Unit test naming best practices

What are the best practices for naming unit test classes and test methods? This was discussed on SO before, at What are some popular naming conventions for Unit Tests? I don't know if this is a very good approach, but currently in my testing projec...

Can HTML checkboxes be set to readonly?

I thought they could be, but as I'm not putting my money where my mouth was (so to speak) setting the readonly attribute doesn't actually seem to do anything. I'd rather not use Disabled, since I want the checked check boxes to be submitted with the...

How do you truncate all tables in a database using TSQL?

I have a test environment for a database that I want to reload with new data at the start of a testing cycle. I am not interested in rebuilding the entire database- just simply "re-setting" the data. What is the best way to remove all the data from...

Trigger a button click with JavaScript on the Enter key in a text box

I have one text input and one button (see below). How can I use JavaScript to trigger the button's click event when the Enter key is pressed inside the text box? There is already a different submit button on my current page, so I can't simply make t...

Microsoft Excel mangles Diacritics in .csv files?

I am programmatically exporting data (using PHP 5.2) into a .csv test file. Example data: Numéro 1 (note the accented e). The data is utf-8 (no prepended BOM). When I open this file in MS Excel is displays as Numéro 1. I am able to open this ...

How does one get started with procedural generation?

Procedural generation has been brought into the spotlight recently (by Spore, MMOs, etc), and it seems like an interesting/powerful programming technique. My questions are these: Do you know of any mid-sized projects that utilize procedural generat...

Convert JavaScript String to be all lower case?

How can I convert a JavaScript string value to be in all lower case letters? Example: "Your Name" to "your name"...

How do you remove Subversion control for a folder?

I have a folder, c:\websites\test, and it contains folders and files that were checked out from a repository that no longer exists. How do I get Subversion to stop tracking that folder and any of the subfolders and files? I know I could simply dele...

Polymorphism vs Overriding vs Overloading

In terms of Java, when someone asks: what is polymorphism? Would overloading or overriding be an acceptable answer? I think there is a bit more to it than that. IF you had a abstract base class that defined a method with no implementation, ...

Volatile vs. Interlocked vs. lock

Let's say that a class has a public int counter field that is accessed by multiple threads. This int is only incremented or decremented. To increment this field, which approach should be used, and why? lock(this.locker) this.counter++;, Interlocke...

Encode/Decode URLs in C++

Does anyone know of any good C++ code that does this?...

Unnamed/anonymous namespaces vs. static functions

A feature of C++ is the ability to create unnamed (anonymous) namespaces, like so: namespace { int cannotAccessOutsideThisFile() { ... } } // namespace You would think that such a feature would be useless -- since you can't specify the name of...