SyntaxFix.com - Programming Questions & Answers Hub For Beginners

Some Of The Best Answers From Latest Asked Questions

How can I send emails through SSL SMTP with the .NET Framework?

Is there a way with the .NET Framework to send emails through an SSL SMTP server on port 465? The usual way: System.Net.Mail.SmtpClient _SmtpServer = new System.Net.Mail.SmtpClient("tempurl.org"); _SmtpServer.Port = 465; _SmtpServer.EnableSsl = tru...

HTML input arrays

<input name="foo[]" ... > I've used these before, but I'm wondering what it is called and if there is a specification for it? I couldn't find it in the HTML 4.01 Spec and results in various Google results only call it an "array" along with m...

Adding files to java classpath at runtime

Is it possible to add a file (not necessarily a jar file) to java classpath at runtime. Specifically, the file already is present in the classpath, what I want is whether I can add a modified copy of this file to the classpath. Thanks,...

How to find Current open Cursors in Oracle

What is the query to find the no. of current open cursors in an Oracle Instance? Also, what is the accuracy/update frequency of this data? I am using Oracle 10gR2...

How do I record audio on iPhone with AVAudioRecorder?

Now that iPhone 3.0 SDK is public, I think I can ask this question for those of you that have already been playing with the 3.0 SDK. I want to record audio in my application, but I want to use AVAudioRecorder and not the older way of recording like t...

Edit and Continue: "Changes are not allowed when..."

Even if I create a clean WinForms project, Edit and Continue doesn't work and gives me the error: Changes are not allowed when the debugger has been attached to an already running process or the code being debugged was optimized at build or run time...

How to debug heap corruption errors?

I am debugging a (native) multi-threaded C++ application under Visual Studio 2008. On seemingly random occasions, I get a "Windows has triggered a break point..." error with a note that this might be due to a corruption in the heap. These e...

MySQL: @variable vs. variable. What's the difference?

In another question I posted someone told me that there is a difference between: @variable and: variable in MySQL. He also mentioned how MSSQL has batch scope and MySQL has session scope. Can someone elaborate on this for me?...

How to read/process command line arguments?

I am originally a C programmer. I have seen numerous tricks and "hacks" to read many different arguments. What are some of the ways Python programmers can do this? Related What’s the best way to grab/parse command line arguments passed to a Py...

Enter key press behaves like a Tab in Javascript

I'm looking to create a form where pressing the enter key causes focus to go to the "next" form element on the page. The solution I keep finding on the web is... <body onkeydown="if(event.keyCode==13){event.keyCode=9; return event.keyCode}"> ...

Pass mouse events through absolutely-positioned element

I'm attempting to capture mouse events on an element with another absolutely-positioned element on top of it. Right now, events on the absolutely-positioned element hit it and bubble up to its parent, but I want it to be "transparent" to these mouse...

Selecting option by text content with jQuery

I want to set a dropdown box to whatever has been passed through a querystring using jquery. How do I add the selected attribute to an option such that the "TEXT" value is equal to a certain param from the query string? $(document).ready(function...

PostgreSQL - max number of parameters in "IN" clause?

In Postgres, you can specify an IN clause, like this: SELECT * FROM user WHERE id IN (1000, 1001, 1002) Does anyone know what's the maximum number of parameters you can pass into IN?...

how to emulate "insert ignore" and "on duplicate key update" (sql merge) with postgresql?

Some SQL servers have a feature where INSERT is skipped if it would violate a primary/unique key constraint. For instance, MySQL has INSERT IGNORE. What's the best way to emulate INSERT IGNORE and ON DUPLICATE KEY UPDATE with PostgreSQL?...

Selecting a Linux I/O Scheduler

I read that it's supposedly possible to change the I/O scheduler for a particular device on a running kernel by writing to /sys/block/[disk]/queue/scheduler. For example I can see on my system: [email protected]:~$ cat /sys/block/sda/queue/scheduler noop ...

Filter element based on .data() key/value

Say I have 4 div elements with class .navlink, which, when clicked, use .data() to set a key called 'selected', to a value of true: $('.navlink')click(function() { $(this).data('selected', true); }) Every time a new .navlink is clicked, I would li...

Reverse the ordering of words in a string

I have this string s1 = "My name is X Y Z" and I want to reverse the order of the words so that s1 = "Z Y X is name My". I can do it using an additional array. I thought hard but is it possible to do it inplace (without using additional data struct...

What .NET collection provides the fastest search

I have 60k items that need to be checked against a 20k lookup list. Is there a collection object (like List, HashTable) that provides an exceptionly fast Contains() method? Or will I have to write my own? In otherwords, is the default Contains() meth...

Facebook database design?

I have always wondered how Facebook designed the friend <-> user relation. I figure the user table is something like this: user_email PK user_id PK password I figure the table with user's data (sex, age etc connected via user email I would as...

Converting Symbols, Accent Letters to English Alphabet

The problem is that, as you know, there are thousands of characters in the Unicode chart and I want to convert all the similar characters to the letters which are in English alphabet. For instance here are a few conversions: ?->H ?->V ?->Y...

Illegal mix of collations MySQL Error

I'm getting this strange error while processing a large number of data... Error Number: 1267 Illegal mix of collations (latin1_swedish_ci,IMPLICIT) and (utf8_general_ci,COERCIBLE) for operation '=' SELECT COUNT(*) as num from keywords WHERE campai...

How do I use CREATE OR REPLACE?

Am I correct in understanding that CREATE OR REPLACE basically means "if the object exists, drop it, then create it either way?" If so, what am I doing wrong? This works: CREATE TABLE foo (id NUMBER, title VARCHAR2(4000) DEFAULT 'Default Title')...

C++ Singleton design pattern

Recently I've bumped into a realization/implementation of the Singleton design pattern for C++. It has looked like this (I have adopted it from the real-life example): // a lot of methods are omitted here class Singleton { public: static Si...

How to get function parameter names/values dynamically?

Is there a way to get the function parameter names of a function dynamically? Let’s say my function looks like this: function doSomething(param1, param2, .... paramN){ // fill an array with the parameter name and value // some other code }...

How to fix "The ConnectionString property has not been initialized"

When I start my application I get: The ConnectionString property has not been initialized. Web.config: <connectionStrings> <add name="MyDB" connectionString="Data Source=localhost\sqlexpress;Initial Catalog=mydatabase;User I...

How to strip all non-alphabetic characters from string in SQL Server?

How could you remove all characters that are not alphabetic from a string? What about non-alphanumeric? Does this have to be a custom function or are there also more generalizable solutions?...

How do I replace whitespaces with underscore?

I want to replace whitespace with underscore in a string to create nice URLs. So that for example: "This should be connected" becomes "This_should_be_connected" I am using Python with Django. Can this be solved using regular expressions? ...

How can I create a war file of my project in NetBeans?

How can I create a war file of my project in NetBeans?...

How can I set a UITableView to grouped style

I have a UITableViewController subclass with sections. The sections are showing with the default style (no rounded corners). How can I set the TableView style to grouped in the code? I'm not using Interface Builder for this, so I need something like ...

Fastest Way to Find Distance Between Two Lat/Long Points

I currently have just under a million locations in a mysql database all with longitude and latitude information. I am trying to find the distance between one point and many other points via a query. It's not as fast as I want it to be especially wit...

How to find out the number of CPUs using python

I want to know the number of CPUs on the local machine using Python. The result should be user/real as output by time(1) when called with an optimally scaling userspace-only program....

How to select the first element with a specific attribute using XPath

The XPath bookstore/book[1] selects the first book node under bookstore. How can I select the first node that matches a more complicated condition, e.g. the first node that matches /bookstore/book[@location='US']...

What is the default encoding of the JVM?

Is UTF-8 the default encoding in Java? If not, how can I know which encoding is used by default?...

How do I get the function name inside a function in PHP?

Is it possible? function test() { echo "function name is test"; } ...

How do I look inside a Python object?

I'm starting to code in various projects using Python (including Django web development and Panda3D game development). To help me understand what's going on, I would like to basically 'look' inside the Python objects to see how they tick - like the...

How to call a function from a string stored in a variable?

I need to be able to call a function, but the function name is stored in a variable, is this possible? e.g: function foo () { //code here } function bar () { //code here } $functionName = "foo"; // I need to call the function base...

Does a `+` in a URL scheme/host/path represent a space?

I am aware that a + in the query string of a URL represents a space. Is this also the case outside of the query string region? That is to say, does the following URL: http://a.com/a+b/c actually represent: http://a.com/a b/c (and thus need to b...

How to add one day to a date?

I want to add one day to a particular date. How can I do that? Date dt = new Date(); Now I want to add one day to this date....

Escape text for HTML

How do i escape text for html use in C#? I want to do sample="<span>blah<span>" and have <span>blah<span> show up as plain text instead of blah only with the tags part of the html :(. Using C# not ASP...

Auto detect mobile browser (via user-agent?)

How can I detect if a user is viewing my web site from a mobile web browser so that I can then auto detect and display the appropriate version of my web site?...

Initialization of an ArrayList in one line

I wanted to create a list of options for testing purposes. At first, I did this: ArrayList<String> places = new ArrayList<String>(); places.add("Buenos Aires"); places.add("Córdoba"); places.add("La Plata"); Then, I refactored the cod...

How can I change NULL to 0 when getting a single value from a SQL function?

I have a query that counts the price of all items between two dates. Here is the select statement: SELECT SUM(Price) AS TotalPrice FROM Inventory WHERE (DateAdded BETWEEN @StartDate AND @EndDate) You can assume all of the tables have been set up ...

How to use Git?

I am an engineering student who spends most of his spare time watching TV rather than coding. So basically I have zero experience with any kind of version control system. My understanding is somehow they make distribution of projects easier. I was l...

Write HTML to string

I have code like this. Is there a way to make it easier to write and maintain? Using C# .NET 3.5. string header(string title) { StringWriter s = new StringWriter(); s.WriteLine("{0}","<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"...

How to truncate milliseconds off of a .NET DateTime

I'm trying to compare a time stamp from an incoming request to a database stored value. SQL Server of course keeps some precision of milliseconds on the time, and when read into a .NET DateTime, it includes those milliseconds. The incoming request to...

Read pdf files with php

I have a large PDF file that is a floor map for a building. It has layers for all the office furniture including text boxes of seat location. My goal is to read this file with PHP, search the document for text layers, get their contents and coordina...

Setting Margin Properties in code

MyControl.Margin.Left = 10; Error: Cannot modify the return value of 'System.Windows.FrameworkElement.Margin' because it is not a variable ...

How can I see if a Perl hash already has a certain key?

I have a Perl script that is counting the number of occurrences of various strings in a text file. I want to be able to check if a certain string is not yet a key in the hash. Is there a better way of doing this altogether? Here is what I am doing: ...

How to convert UTF-8 byte[] to string?

I have a byte[] array that is loaded from a file that I happen to known contains UTF-8. In some debugging code, I need to convert it to a string. Is there a one liner that will do this? Under the covers it should be just an allocation and a mem...

Cast to generic type in C#

I have a Dictionary to map a certain type to a certain generic object for that type. For example: typeof(LoginMessage) maps to MessageProcessor<LoginMessage> Now the problem is to retrieve this generic object at runtime from the Dictionary. ...

Using DISTINCT and COUNT together in a MySQL Query

Is something like this possible: SELECT DISTINCT COUNT(productId) WHERE keyword='$keyword' What I want is to get the number of unique product Ids which are associated with a keyword. The same product may be associated twice with a keyword, or more...

Write applications in C or C++ for Android?

I'm trying to develop/port a game to Android, but it's in C, and Android supports Java, but I'm sure there must be a way to get a C app on there, anyone knows of a way to accomplish this?...

Auto insert date and time in form input field?

Using javascript, how can we auto insert the current DATE and TIME into a form input field. I'm building a "Problems" form to keep track of user submitted complaints about a certain service. I'm collecting as much info as possible. I want to save th...

How can I split a text file using PowerShell?

I need to split a large (500 MB) text file (a log4net exception file) into manageable chunks like 100 5 MB files would be fine. I would think this should be a walk in the park for PowerShell. How can I do it?...

What is the basic difference between the Factory and Abstract Factory Design Patterns?

What is the basic difference between the Factory and Abstract Factory Patterns?...

How to create war files

What are the best practices of creating war files (using eclipse) to run on tomcat? tutorials, links, examples are highly appreciated. ...

What is the best free SQL GUI for Linux for various DBMS systems

As I make the full switch from Windows to Linux (CentOS 5) I'm in search of the best free GUI SQL Client tool for MSSQL, MySQL, Oracle, etc... any suggestions? I've tried DBVisualizer (The best bet so far but still limited by the free version, not a...

How to write a UTF-8 file with Java?

I have some current code and the problem is its creating a 1252 codepage file, i want to force it to create a UTF-8 file Can anyone help me with this code, as i say it currently works... but i need to force the save on utf.. can i pass a parameter o...

Detecting endianness programmatically in a C++ program

Is there a programmatic way to detect whether or not you are on a big-endian or little-endian architecture? I need to be able to write code that will execute on an Intel or PPC system and use exactly the same code (i.e. no conditional compilation)....

MySQL SELECT x FROM a WHERE NOT IN ( SELECT x FROM b ) - Unexpected result

I expect the result of the third query below to contain id=732. It doesn't. Why is that? mysql> SELECT id FROM match ORDER BY id DESC LIMIT 5 ; +------------+ | id | +------------+ | 732 | | 730 | | 655 | | 45...

How to keep a Python script output window open?

I have just started with Python. When I execute a python script file on Windows, the output window appears but instantaneously goes away. I need it to stay there so I can analyze my output. How can I keep it open?...

Find index of last occurrence of a sub-string using T-SQL

Is there a straightforward way of finding the index of the last occurrence of a string using SQL? I am using SQL Server 2000 right now. I basically need the functionality that the .NET System.String.LastIndexOf method provides. A little googling r...

How can I add new keys to a dictionary?

Is it possible to add a key to a Python dictionary after it has been created? It doesn't seem to have an .add() method....

When to use .First and when to use .FirstOrDefault with LINQ?

I've searched around and haven't really found a clear answer as to when you'd want to use .First and when you'd want to use .FirstOrDefault with LINQ. When would you want to use .First? Only when you'd want to catch the exception if no results wher...

How to add link to flash banner

I am primarily a developer and dont know to use Adobe Flash CS4. Is there a simple way to add link to flash banner. I have .flv file with some items in Library and two layers. Please, give me step by step instructions. Edit: I find simple solution, ...

How to fix Python indentation

I have some Python code that have inconsistent indentation. There is a lot of mixture of tabs and spaces to make the matter even worse, and even space indentation is not preserved. The code works as expected, but it's difficult to maintain. How can...

Get Value of Row in Datatable c#

i have a problem with my code. foreach (DataRow dr in dt_pattern.Rows) { part = dr["patternString"].ToString(); if (part != vpart) { System.Console.WriteLine(part); System.Console.WriteLine("Geben Sie bitte für...

Nginx - Customizing 404 page

Nginx+PHP (on fastCGI) works great for me. When I enter a path to a PHP file which doesn't exist, instead of getting the default 404 error page (which comes for any invalid .html file), I simply get a "No input file specified.". How can I customize ...

Location of ini/config files in linux/unix?

Two questions, really: Is there a standard/convention regarding the placement on configuration files? For system or quasi-system programs they seem to usually be somewhere in /etc. It seems less clear for plain application programs or programs ...

How to write hello world in assembler under Windows?

I wanted to write something basic in assembly under Windows, I'm using NASM, but I can't get anything working. How to write and compile hello world without the help of C functions on Windows?...

Finding current executable's path without /proc/self/exe

It seems to me that Linux has it easy with /proc/self/exe. But I'd like to know if there is a convenient way to find the current application's directory in C/C++ with cross-platform interfaces. I've seen some projects mucking around with argv[0], but...

jquery UI dialog: how to initialize without a title bar?

Is it possible to open a jQuery UI Dialog without a title bar?...

accessing a variable from another class

Very simple question but I can't do it. I have 3 classes: DrawCircle class import java.awt.*; import java.awt.event.*; import javax.swing.*; class DrawCircle extends JPanel { private int w, h, di, diBig, diSmall, maxRad, xSq, ySq, xPoint, yPoi...

Good font for code presentations?

There's a couple of good questions regarding screen fonts for coding. I'm putting together some Keynote presentations that will contain code fragments screen dumps of terminal windows And the usual Courier display is looking a bit tired. What a...

Commenting code in Notepad++

I'm using Notepad++ as an editor to write programs in Python. It might sound daft but I looked around in the editor and could not find any means (not the manual way but something like in Emacs) to do a block comment in my code. Since so many languag...

How to unzip a file using the command line?

Which commands can be used via the command line to unzip a file? Preferably something built into Windows or open source/free tools....

Java Code for calculating Leap Year

I am following "The Art and Science of Java" book and it shows how to calculate a leap year. The book uses ACM Java Task Force's library. Here is the code the books uses: import acm.program.*; public class LeapYear extends ConsoleProgram { pub...

Use success() or complete() in AJAX call

I want to understand the AJAX call below, in terms of the complete() method; When I replace complete() with success(), I get an empty responseText just as with the AJAX error() method. On the other hand, when I leave the complete() method there as...

What are public, private and protected in object oriented programming?

What are public, private and protected in object oriented programming?...

How to convert a string to lower or upper case in Ruby

How do I take a string and convert it to lower or upper case in Ruby?...

How to view the assembly behind the code using Visual C++?

I was reading another question pertaining the efficiency of two lines of code, and the OP said that he looked at the assembly behind the code and both lines were identical in assembly. Digression aside, how could I view the assembly code created whe...

How can I hide or encrypt JavaScript code?

Is there any way to hide or encrypt JavaScript code to prevent people from viewing, copying, and/or modifying proprietary programs?...

How to reverse apply a stash?

I have a small patch saved away in my git stash. I've applied it to my working copy using git stash apply. Now, I'd like to back out those changes by reverse applying the patch (kind of like what git revert would do but against the stash). Does an...

What is the best method of handling currency/money?

I'm working on a very basic shopping cart system. I have a table items that has a column price of type integer. I'm having trouble displaying the price value in my views for prices that include both Euros and cents. Am I missing something obvious...

Is there a way to use shell_exec without waiting for the command to complete?

I have a process intensive task that I would like to run in the background. The user clicks on a page, the PHP script runs, and finally, based on some conditions, if required, then it has to run a shell script, E.G.: shell_exec('php measurePerforma...

How can I convert String to Int?

I have a TextBoxD1.Text and I want to convert it to an int to store it in a database. How can I do this?...

Using ls to list directories and their total sizes

Is it possible to use ls in Unix to list the total size of a sub-directory and all its contents as opposed to the usual 4K that (I assume) is just the directory file itself? total 12K drwxrwxr-x 6 *** *** 4.0K 2009-06-19 10:10 branches drwxrwxr-x 1...

How to Set OnClick attribute with value containing function in ie8?

My goal is to change the onclick attribute of a link. I can do it successfully, but the resulting link doesn't work in ie8. It does work in ff3. For example, this works in Firefox 3, but not IE8. Why? <p><a id="bar" href="#" onclick="temp(...

How to search by key=>value in a multidimensional array in PHP

Is there any fast way to get all subarrays where a key value pair was found in a multidimensional array? I can't say how deep the array will be. Simple example array: $arr = array(0 => array(id=>1,name=>"cat 1"), 1 => array...

Condition within JOIN or WHERE

Is there any difference (performance, best-practice, etc...) between putting a condition in the JOIN clause vs. the WHERE clause? For example... -- Condition in JOIN SELECT * FROM dbo.Customers AS CUS INNER JOIN dbo.Orders AS ORD ON CUS.CustomerID...

Simple PowerShell LastWriteTime compare

I need a PowerShell script that can access a file's properties and discover the LastWriteTime property and compare it with the current date and return the date difference. I have something like this... $writedate = Get-ItemProperty -Path $source -N...

Why is the use of alloca() not considered good practice?

alloca() allocates memory on the stack rather than on the heap, as in the case of malloc(). So, when I return from the routine the memory is freed. So, actually this solves my problem of freeing up dynamically allocated memory. Freeing of memory allo...

INNER JOIN ON vs WHERE clause

For simplicity, assume all relevant fields are NOT NULL. You can do: SELECT table1.this, table2.that, table2.somethingelse FROM table1, table2 WHERE table1.foreignkey = table2.primarykey AND (some other conditions) Or else: SELEC...

Can you use @Autowired with static fields?

Is there some way to use @Autowired with static fields. If not, are there some other ways to do this?...

How to convert object array to string array in Java

I use the following code to convert an Object array to a String array : Object Object_Array[]=new Object[100]; // ... get values in the Object_Array String String_Array[]=new String[Object_Array.length]; for (int i=0;i<String_Array.length;i++) ...

Excel - extracting data based on another list

I have an Excel worksheet with two columns (name/ID) and then another list that is a subset of the names only from the larger aforementioned list. I want to go through the subset list and then pull the data from the larger list (name/ID) and put it s...

Objective-C: Calling selectors with multiple arguments

In MyClass.m, I've defined - (void) myTest: (NSString *) withAString{ NSLog(@"hi, %@", withAString); } and the appropriate declaration in MyClass.h . Later I want to call [self performSelector:@selector(mytest:withAString:) withObject: mystri...

Testing HTML email rendering

Are there any good tools to easily test how HTML email will look across different email clients? I prefer something with instant feed back rather than a submit and wait service like http://litmusapp.com Or at the very least a way to test the Outlook ...

Expand div to max width when float:left is set

I have something like that: <div style="width:100px;float:left">menu</div> <div style="float:left">content</div> both floats are neccesary. I want the content div to fill the whole screen minus those 100px for the menu. If ...

Why isn't Python very good for functional programming?

I have always thought that functional programming can be done in Python. Thus, I was surprised that Python didn't get much of a mention in this question, and when it was mentioned, it normally wasn't very positive. However, not many reasons were give...