Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I'd like to read whole content of a text file to a `std::string` object with c++.
With Python, I can write:
```
text = open("text.txt", "rt").read()
```
It is very simple and elegant. I hate ugly stuff, so I'd like to know - what is the most elegant way to read a text file with C++?
Thanks. | There are many ways, you pick which is the most elegant for you.
Reading into char\*:
```
ifstream file ("file.txt", ios::in|ios::binary|ios::ate);
if (file.is_open())
{
file.seekg(0, ios::end);
size = file.tellg();
char *contents = new char [size];
file.seekg (0, ios::beg);
file.read (contents, s... | There's [another thread](https://stackoverflow.com/questions/116038/what-is-the-best-way-to-slurp-a-file-into-a-stdstring-in-c) on this subject.
My solutions from this thread (both one-liners):
The nice (see Milan's second solution):
```
string str((istreambuf_iterator<char>(ifs)), istreambuf_iterator<char>());
```
... | What is the most elegant way to read a text file with c++? | [
"",
"c++",
"text",
"file-io",
""
] |
When you run something similar to:
```
UPDATE table SET datetime = NOW();
```
on a table with 1 000 000 000 records and the query takes 10 seconds to run, will all the rows have the exact same time (minutes and seconds) or will they have different times? In other words, will the time be when the query started or when... | <http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_now>
> "NOW() returns a constant time that indicates the time at which the statement began to execute. (Within a stored routine or trigger, NOW() returns the time at which the routine or triggering statement began to execute.) This differs f... | Assign `NOW()` to a variable then update the datetime with variable:
```
update_date_time=now()
```
now update like this
```
UPDATE table SET datetime =update_date_time;
```
correct the syntax, as per your requirement | When running UPDATE ... datetime = NOW(); will all rows updated have the same date/time? | [
"",
"mysql",
"sql",
"datetime",
"sql-update",
""
] |
I'm having performance oddities with Java2D. I know of the sun.java2d.opengl VM parameter to enable 3D acceleration for 2D, but even using that has some weird issues.
Here are results of tests I ran:
Drawing a 25x18 map with 32x32 pixel tiles on a JComponent
Image 1 = .bmp format, Image 2 = A .png format
## Withou... | I think I found a solution by researching and putting bits and pieces together from too many Google searches.
Here it is, comments and all:
```
private BufferedImage toCompatibleImage(BufferedImage image)
{
// obtain the current system graphical settings
GraphicsConfiguration gfxConfig = GraphicsEnvironment.
... | Well, this is old post but I'd like to share my findings about direct drawing with Swing/AWT, without BufferedImage.
Some kind of drawing, as 3D, are better done when painting directly to a **int[]** buffer. Once done the images, you can use an **ImageProducer** instance, like **MemoryImageSource**, to produce images.... | Java2D Performance Issues | [
"",
"java",
"java-2d",
""
] |
Very simply put:
I have a class that consists mostly of static public members, so I can group similar functions together that still have to be called from other classes/functions.
Anyway, I have defined two static unsigned char variables in my class public scope, when I try to modify these values in the same class' c... | If you are using **C++ 17** you can just use the `inline` specifier (see <https://stackoverflow.com/a/11711082/55721>)
---
If using older versions of the C++ standard, you must add the definitions to match your declarations of X and Y
```
unsigned char test::X;
unsigned char test::Y;
```
somewhere. You might want t... | Static data members declarations in the class declaration are not definition of them.
To define them you should do this in the `.CPP` file to avoid duplicated symbols.
The only data you can declare and define is integral static constants.
(Values of `enums` can be used as constant values as well)
You might want to re... | Unresolved external symbol on static class members | [
"",
"c++",
"class",
"static",
"members",
""
] |
I have a production server running with the following flag: -**XX:+HeapDumpOnOutOfMemoryError**
Last night it generated a java-38942.hprof file when our server encountered a heap error. It turns out that the developers of the system knew of the flag but no way to get any useful information from it.
Any ideas? | If you want a fairly advanced tool to do some serious poking around, look at [the Memory Analyzer project](http://www.eclipse.org/mat/) at Eclipse, contributed to them by SAP.
Some of what you can do is mind-blowingly good for finding memory leaks etc -- including running a form of limited SQL (OQL) against the in-mem... | You can use [JHAT](https://docs.oracle.com/javase/8/docs/technotes/tools/unix/jhat.html), The Java Heap Analysis Tool provided by default with the JDK. It's command line but starts a web server/browser you use to examine the memory. Not the most user friendly, but at least it's already installed most places you'll go. ... | How do I analyze a .hprof file? | [
"",
"java",
"profiling",
"heap-memory",
""
] |
I'm looking to add localization to a web site (asp.net /c# if that makes a difference) with a minimum of effort. I've looked at tools like [wiztom](http://www.wizart.com/en/index.shtml) [multilizer](http://www.multilizer.com/) and I am curious as to others experience with them.
Have you used tools like these successfu... | From my experience with making localized applications I can say that there really isn't an easy, shrink-wrapped solution to this problem. Your best bet is to do a lot of reading on the topic (Google is your friend) and figure out a solution that works best in your specific instance. I think you'll have an issue with th... | I've used the following:
1. Alchemy Catalyst
2. Trados
3. Globalyzer
4. Lingobit
Which you use depends on what you're looking to do:
Are you looking for a tool to help you with string externalization alone (internationalization), or to help you manage the translation/localization workflow?
How big is the applicatio... | Localization / internationalization tool | [
"",
"c#",
"asp.net",
"localization",
""
] |
I have a source base that, depending on defined flags at build time, creates two different apps. I can build both of these apps using a Makefile by specifying two different targets, one that compiles with a flag and one that compiles without, and having an aggregate target that builds both.
How do I do the equivalent ... | Create one solution with two project files in the same folder. Set two different configurations in your solution, one of them building one of the projects, the other one building the other project.
Alternatively, you can have one project which always builds to intermediate binary and then have a postbuild step that co... | Release vs Debug? You can create your own custom configurations as well. But building a completely different app based on the configuration seems like a bad idea.
Normal visual studio can have multiple projects in one solution, and I think there's a way to shoe-horn this into Express edition (perhaps by opening a solu... | How do I build two different apps from one Visual C# project? | [
"",
"c#",
"windows",
"visual-studio",
"build-process",
"build-automation",
""
] |
Would you recommend me the best approach to edit SQL query with Visual Studio 2008 Professional, please?
I know I can open Query window from context menu in Server Explorer and edit text in SQL Pane. But unfortunately I am not allowed to save query to a file and Find and Replace commands are not working there.
Altern... | If you create a Database project within your solution in Visual Studio, then you can set up a default database connection for that project. Then any \*.sql files that are included in the database project can be executed against that connection. What I usually do is select the text to be exectued and right-click it, the... | When I have to connect to Sql Server, I use NetBeans, as it has a number of features that make it much easier to use than Visual Studio. One of these is intellisense, which is very useful when you have an alias for a table name and lots of long field names. The general handling of connections and connection pools is al... | Editing SQL query with Visual Studio 2008 | [
"",
"sql",
"visual-studio",
"editor",
""
] |
If I have a style defined
```
.style1
{
width: 140px;
}
```
can I reference it from a second style?
```
.style2
{
ref: .style1;
}
```
Or is there a way via javascript/jQuery?
--- Edit
To clarify the problem, I am trying to apply whatever style is defined for a #x and #c to .x and .c without altering the CSS... | There's no way to do it with CSS -- it's an oft-requested feature, but not included in the spec yet. You also can't do it directly with JS, but there's sort of a hacky workaround:
```
$('.style2').addClass ('style1');
``` | you can achieve the same functionality by allowing elements to inherit multiple styles. ex.
```
<p class="style1 style2">stuff</p>
```
and then your css would include, for example:
```
.style1 {width:140px;}
.style2 {height:140px;}
```
edit: actually robert's answer might better approximate the method you are tryin... | Is there a way to reference an existing CSS style from another CSS style using CSS or javascript? | [
"",
"javascript",
"jquery",
"dynamic-css",
""
] |
Do any apps/packages exist that will support writing to OS X's log database from external sources. I'm not too familiar with the specifics of the database, beyond the fact that you can view its contents from the Console app. I'm not even sure if it's just a version of some simple DB like SQLite or if it is some sort of... | I've never used OS X but you might want to look into the [syslog](http://www.php.net/syslog) function. | In your PHP do a **syslog(LOG\_WARNING, "whatever");**
In terminal type **syslog -w**
It will output **Warning: whatever**
It will then print out the syslogs. You will get system message as well in the syslog. The -w help only list recent stuff. | Using PHP to write to OS X's log database? | [
"",
"php",
"macos",
"logging",
""
] |
Is is possible to create COM component and ActiveX controls in .Net (using c# language). I searched internet but i could`t get anything.
Thanks,
santhosh | Declare an interface and implement it with class.
If you have parameters/return values that are not OLE Automation compatible (custom structs, enums and so on), you might need to decorate them with the [MarshalAs attribute](http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshalasattribute.aspx... | Yes, it is possible, there is this article in [CodeProject](http://www.codeproject.com/KB/COM/com_object_in_c_.aspx). A friend of mine tried it and had some trouble accessing the COM-object from his unmanaged app, though, so there are some pitfalls. | Create COM component and ActiveX controls | [
"",
"c#",
".net",
".net-3.5",
""
] |
What do the brackets do in a sql statement?
For example, in the statement:
```
insert into table1 ([columnname1], columnname2) values (val1, val2)
```
Also, what does it do if the table name is in brackets? | The [] marks the delimitation of a identifier, so if you have a column whose name contains spaces like Order Qty you need to enclose it with [] like:
```
select [Order qty] from [Client sales]
```
They are also to escape reserved keywords used as identifiers | This is Microsoft SQL Server nonstandard syntax for "delimited identifiers." SQL supports delimiters for identifiers to allow table names, column names, or other metadata objects to contain the following:
* SQL reserved words: "Order"
* Words containing spaces: "Order qty"
* Words containing punctuation:
"Order-qty"... | [] brackets in sql statements | [
"",
"sql",
"ms-access",
""
] |
When we execute `select count(*) from table_name` it returns the number of rows.
What does `count(1)` do? What does `1` signify here? Is this the same as `count(*)` (as it gives the same result on execution)? | The parameter to the COUNT function is an expression that is to be evaluated for each row. The COUNT function returns the number of rows for which the expression evaluates to a non-null value. ( \* is a special expression that is not evaluated, it simply returns the number of rows.)
There are two additional modifiers ... | Here is [a link](http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:40208915257337) that will help answer your questions. In short:
> count(\*) is the correct way to write
> it and count(1) is OPTIMIZED TO BE
> count(\*) internally -- since
>
> a) count the rows where 1 is not null
> is less efficient... | What does "select count(1) from table_name" on any database tables mean? | [
"",
"sql",
"database",
"oracle",
""
] |
I've been trying to get up to speed on some of the newer features in C# and one of them that I haven't had occasion to use is anonymous types.
I understand the usage as it pertains to LINQ queries and I looked at [this SO post](https://stackoverflow.com/questions/48668/how-should-anonymous-types-be-used-in-c) which as... | With a bit of reflection, you can turn an anonymous type into a Dictionary<string, object>; Roy Osherove blogs his technique for this here: <http://weblogs.asp.net/rosherove/archive/2008/03/11/turn-anonymous-types-into-idictionary-of-values.aspx>
Jacob Carpenter uses anonymous types as a way to initialize immutable ob... | ASP.NET MVC routing uses these objects all over the place. | Other than for LINQ queries, how do you use anonymous types in C#? | [
"",
"c#",
"anonymous-types",
""
] |
I always felt that expecting exceptions to be thrown on a regular basis and using them as flow logic was a bad thing. Exceptions feel like they should be, well, the "*exception*". If you're expecting and planning for an exception, that would seem to indicate that your code should be refactored, at least in .NET...
Ho... | Wow,
First off, can you please distill the question down a bit, while it was nice to read a well thought out and explained question, that was quite a lot to digest.
The short answer is "yes", but it can depend.
* We have some applications where we have lots of business logic tied up in the SQL queries (not my design... | Your lead is absolutely right. Exceptions are not just for once in a blue moon situations, but specifically for reporting other than expected outcomes.
In this case the foreign key check would still take place, and exceptions are the mechanism by which you can be notified.
What you should NOT do is catch and suppress... | Catching exceptions as expected program execution flow control? | [
"",
".net",
"sql",
"sql-server",
"exception",
""
] |
I have a method lets say:
```
private static String drawCellValue(
int maxCellLength, String cellValue, String align) { }
```
and as you can notice, I have a parameter called align. Inside this method I'm going to have some if condition on whether the value is a 'left' or 'right'.. setting the parameter as String... | This should do it:
```
private enum Alignment { LEFT, RIGHT };
String drawCellValue (int maxCellLength, String cellValue, Alignment align){
if (align == Alignment.LEFT)
{
//Process it...
}
}
``` | Even cooler with enums you can use switch:
```
switch (align) {
case LEFT: {
// do stuff
break;
}
case RIGHT: {
// do stuff
break;
}
default: { //added TOP_RIGHT but forgot about it?
throw new IllegalArgumentException("Can't yet handle " + align);
}
}
```
Enums are co... | Java: Enum parameter in method | [
"",
"java",
"parameters",
"methods",
"enums",
""
] |
I have a class hierarchy as such:
```
+-- VirtualNode
|
INode --+ +-- SiteNode
| |
+-- AbstractNode --+
|
+-- SiteSubNode
```
And a corresponding `NodeCollection` class that is build on `INode`. In ... | What you're after is the [visitor pattern](http://en.wikipedia.org/wiki/Visitor_pattern), I think. | [Polymorphism:](http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming)
When ever you have a select statement using the type of an object, it is a prime candidate for refactoring to polymorphism.
Check out the book [Refactoring](https://rads.stackoverflow.com/amzn/click/com/0201485672) by Martin Fow... | Aren't there any better ways of displaying an object other than using hierarchy? | [
"",
"c#",
"design-patterns",
""
] |
What does the following code do in C/C++?
```
if (blah(), 5) {
//do something
}
``` | Comma operator is applied and the value 5 is used to determine the conditional's true/false.
It will execute blah() and get something back (presumably), then the comma operator is employed and 5 will be the only thing that is used to determine the true/false value for the expression.
---
Note that the , operator cou... | If the comma operator is not overloaded, the code is similar to this:
```
blah();
if (5) {
// do something
}
```
If the comma operator is overloaded, the result will be based on that function.
```
#include <iostream>
#include <string>
using namespace std;
string blah()
{
return "blah";
}
bool operator,(cons... | What does the comma operator do? | [
"",
"c++",
"c",
"operators",
"comma-operator",
""
] |
Is it a problem if you use the global keyword on variables you don't end up using? Compare:
```
function foo() {
global $fu;
global $bah;
if (something()) {
$fu->doSomething();
} else {
$bah->doSomething();
}
}
function bar() {
if (something()) {
global $fu;
$fu... | If there is, it won't be (humanly) measurable, unless you are literally calling this function millions of times. And even if it was a recursive function with that property, I still wouldn't use your second method for the maintainability aspects you already brought up.
**Edit:** For arguments sake, I actually went and ... | As monoxide said, there's no significant performance difference.
However, I'd avoid using global if at all possible; it's a bad road to go down and you'll end up with spaghetti. Use a static class; it'll keep things much better organized. | Does using global create any overhead? | [
"",
"php",
"optimization",
""
] |
Unless I am missing an obvious built-in method, what is the quickest way to get the *n*th occurrence of a string within a string?
I realize that I could loop the [IndexOf](https://msdn.microsoft.com/en-us/library/k8b1470s(v=vs.110).aspx) method by updating its start index on each iteration of the loop. But doing it th... | That's basically what you need to do - or at least, it's the easiest solution. All you'd be "wasting" is the cost of n method invocations - you won't actually be checking any case twice, if you think about it. (IndexOf will return as soon as it finds the match, and you'll keep going from where it left off.) | You really could use the regular expression `/((s).*?){n}/` to search for n-th occurrence of substring `s`.
In C# it might look like this:
```
public static class StringExtender
{
public static int NthIndexOf(this string target, string value, int n)
{
Match m = Regex.Match(target, "((" + Regex.Escape(... | Get the index of the nth occurrence of a string? | [
"",
"c#",
".net",
"string",
"indexing",
"indexof",
""
] |
JavaScript doesn't seem to have a native `trim()` method. How can I trim white spaces at the start and end of a string with JavaScript? | I know this question is ancient but now, Javascript actually does have a native .trim()
<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim> | The shortest form for jQuery:
```
string = $.trim(string);
```
[Link](http://docs.jquery.com/Utilities/jQuery.trim#str) | How to trim() white spaces from a string? | [
"",
"javascript",
"jquery",
"string",
"trim",
""
] |
How, in the simplest possible way, distinguish between Windows XP and Windows Vista, using Python and [pywin32](http://python.net/crew/mhammond/win32/Downloads.html) or [wxPython](http://www.wxpython.org/)?
Essentially, I need a function that called will return True iff current OS is Vista:
```
>>> isWindowsVista()
T... | Python has the lovely 'platform' module to help you out.
```
>>> import platform
>>> platform.win32_ver()
('XP', '5.1.2600', 'SP2', 'Multiprocessor Free')
>>> platform.system()
'Windows'
>>> platform.version()
'5.1.2600'
>>> platform.release()
'XP'
```
NOTE: As mentioned in the comments proper values may not be retur... | The simplest solution I found is this one:
```
import sys
def isWindowsVista():
'''Return True iff current OS is Windows Vista.'''
if sys.platform != "win32":
return False
import win32api
VER_NT_WORKSTATION = 1
version = win32api.GetVersionEx(1)
if not version or len(version) < 9:
... | How to check if OS is Vista in Python? | [
"",
"python",
"windows",
"windows-vista",
"wxpython",
"pywin32",
""
] |
This seems very noisy to me. Five lines of overhead is just too much.
```
m_Lock.EnterReadLock()
Try
Return m_List.Count
Finally
m_Lock.ExitReadLock()
End Try
```
So how would you simply this? | I was thinking the same, but in C# ;-p
```
using System;
using System.Threading;
class Program
{
static void Main()
{
ReaderWriterLockSlim sync = new ReaderWriterLockSlim();
using (sync.Read())
{
// etc
}
}
}
public static class ReaderWriterExt
{
seale... | All the solutions posted so far are at risk of deadlock.
A using block like this:
```
ReaderWriterLockSlim sync = new ReaderWriterLockSlim();
using (sync.Read())
{
// Do stuff
}
```
gets converted into something like this:
```
ReaderWriterLockSlim sync = new ReaderWriterLockSlim();
IDisposable d = sync.Read();
try... | How would you simplify Entering and Exiting a ReaderWriterLock? | [
"",
"c#",
".net",
"vb.net",
"parallel-processing",
"readerwriterlock",
""
] |
A question about different methods of outputting html from PHP; what are the performance differences between these:
Method 1 - variable concatenation
```
$html = '';
$html .= '<ul>';
for ($k = 1; $k < = 1000; $k++){
$html .= '<li> This is list item #'.$k.'</li>';
}
$html .= '</ul>';
echo $html;
```
Method 2 - ou... | It's a bit old, but [this post](http://blog.libssh2.org/index.php?/archives/28-How-long-is-a-piece-of-string.html) by Sara Golemon will probably help. AFAIK the output buffering functions are quite fast and efficient and so is `echo`, so that's what I would use. | The idea of string concatenation itself aside, you're really asking (I think) how you should be building up web pages, and it strikes me that any form of explicit concatentation is probably the wrong thing to do.
Try using the [Model-View-Control pattern](http://en.wikipedia.org/wiki/Model-view-controller) to build up... | PHP HTML generation - using string concatention | [
"",
"php",
"performance",
"string-concatenation",
""
] |
Pretty simple scenario. I have a web service that receives a byte array that is to be saved as a particular file type on disk. What is the most efficient way to do this in C#? | That would be [`File.WriteAllBytes()`](http://msdn.microsoft.com/en-us/library/system.io.file.writeallbytes.aspx). | `System.IO.File.WriteAllBytes(path, data)` should do fine. | What is the most efficient way to save a byte array as a file on disk in C#? | [
"",
"c#",
".net",
""
] |
I'm writing some code for a class constructor which loops through all the properties of the class and calls a generic static method which populates my class with data from an external API. So I've got this as an example class:
```
public class MyClass{
public string Property1 { get; set; }
public int Property2 { g... | Do you want to call DoStuff<T> with T = the type of each property? In which case, "as is" you would need to use reflection and MakeGenericMethod - i.e.
```
var properties = this.GetType().GetProperties();
foreach (PropertyInfo p in properties)
{
object value = typeof(MyClass)
.GetMethod("DoStuff")
.MakeGen... | Was your constructor code meant to read like this:
```
public MyClass(){
var properties = this.GetType().GetProperties();
foreach(PropertyInfo p in properties){
p.SetValue(this, DoStuff(p.Name), new object[0]);
}
}
```
? Note the `DoStuff` instead of `MyClass`.
If so, the problem is that you're trying to u... | Reflection and generic types | [
"",
"c#",
".net",
"generics",
"reflection",
""
] |
What is a C#'s analog of `std::pair` in C++? I found `System.Web.UI.Pair` class, but I'd prefer something template-based. | Tuples [are available since .NET4.0](http://msdn.microsoft.com/en-us/library/system.tuple(v=vs.110).aspx) and support generics:
```
Tuple<string, int> t = new Tuple<string, int>("Hello", 4);
```
---
In previous versions you can use `System.Collections.Generic.KeyValuePair<K, V>` or a solution like the following:
``... | `System.Web.UI` contained the `Pair` class because it was used heavily in ASP.NET 1.1 as an internal ViewState structure.
**Update Aug 2017:** C# 7.0 / .NET Framework 4.7 provides a syntax to declare a Tuple with named items using the [`System.ValueTuple`](https://msdn.microsoft.com/en-us/library/system.valuetuple.asp... | What is a C# analog of C++ std::pair? | [
"",
"c#",
".net",
"data-structures",
"std-pair",
"base-class-library",
""
] |
I've got a nice little class built that acts as a cache. Each item has an expiration TimeSpan or DateTime. Each time an attempt to access an item in the cache is made, the item's expiration is checked, and if it's expired, the item is removed from the cache and nothing is returned.
That's great for objects that are ac... | In my experience, maintaining a custom caching mechanism became more trouble than it was worth. There are several libraries out there that have already solved these problems. I would suggest using one of them. A popular one in .Net is the Enterprise Library, although I have limited experience with its caching abilities... | The best code is no code. Use the ASP.NET cache instead. You can reference it as System.Web.HttpRuntime.Cache in any application, not just web applications. | How to purge expired items from cache? | [
"",
"c#",
".net",
"caching",
""
] |
I want to be able to explore the contents of a DB for this version of the DB. I was thinking of using the Squirrel DB client (which needs a JDBC driver).
Therefore, I'm looking for a JDBC type 4 driver for SQL SERVER 3.5. Can somone point me to a FREE OR open source or trial ware ?
If no JDBC driver, how do MS develo... | There is a free program called SQLCeEditor that does it.
I'd still like a JDBC driver though since that would make it easy to use with Eclipse and Java. | Have you tried [SQL Server Management Studio Express](http://www.microsoft.com/downloads/details.aspx?FamilyId=C243A5AE-4BD1-4E3D-94B8-5A0F62BF7796&DisplayLang=en)?
> You can access SQL Server Compact 3.5
> databases stored on a smart device or
> on the desktop computer by using SQL
> Server Management Studio in SQL S... | jdbc driver for Microsoft SQL Server CE(Compact Edition) 3.5 | [
"",
"java",
"sql-server",
"database",
"jdbc",
"sql-server-ce",
""
] |
A while a go I had to developed a music site that allowed audio files to be uploaded to a site and then converted in to various formats using ffmpeg, people would then download the uploaded audio files after purchasing them and a tmp file would be created and placed at the download location and was only valid for each ... | See this earlier StackOverflow question [Storing images in a database, Yea or nay?](https://stackoverflow.com/questions/3748/storing-images-in-db-yea-or-nay).
I know you mentioned images and video, however this question has relevance to all large binary content media files.
The consensus seems to be that storing file... | I would recommend storing as files and storing their locations in the database.
Storage the files in a database requires more resources and makes backing up/restoring databases slower.
Do you really want to have to transfer lots of videos every time you do a database dump?
File systems work very well for dishing out f... | Where to store uploaded files (sound, pictures and video) | [
"",
"php",
"mysql",
"storage",
"blob",
""
] |
When I disable ViewState for the page. It does not allow any other control to use ViewState .. even if I set EnableViewState="true" for that particular control ..
is it possible to enable ViewState for a control when ViewState is disabled for the page itself?
if not how can disable viewstate for controls on page exce... | If you set turn page's ViewState off, then there is no way for you to enable ViewState for specific components. This is because ViewState is serialzed recursively, so when if the Page is not allowing ViewState, it will not serialize the ViewState for any of it's child controls.
In answer to your question, if you don't... | > If you set turn page's ViewState off,
> then there is no way for you to enable
> ViewState for specific components.
> This is because ViewState is serialzed
> recursively, so when if the Page is
> not allowing ViewState, it will not
> serialize the ViewState for any of
> it's child controls.it's child controls.
With... | Enable ViewState for few controls and disable for others/page | [
"",
"c#",
"asp.net",
"viewstate",
""
] |
I have a dict, which I need to pass key/values as keyword arguments.. For example..
```
d_args = {'kw1': 'value1', 'kw2': 'value2'}
example(**d_args)
```
This works fine, *but* if there are values in the d\_args dict that are not accepted by the `example` function, it obviously dies.. Say, if the example function is ... | A little nicer than inspecting the code object directly and working out the variables is to use the inspect module.
```
>>> import inspect
>>> def func(a,b,c=42, *args, **kwargs): pass
>>> inspect.getargspec(func)
(['a', 'b', 'c'], 'args', 'kwargs', (42,))
```
If you want to know if its callable with a particular set... | This will print names of all passable arguments, keyword and non-keyword ones:
```
def func(one, two="value"):
y = one, two
return y
print func.func_code.co_varnames[:func.func_code.co_argcount]
```
This is because first `co_varnames` are always parameters (next are local variables, like `y` in the example ab... | Can you list the keyword arguments a function receives? | [
"",
"python",
"arguments",
"introspection",
""
] |
I'm investigating an annotation-based approach to validating Spring beans using [spring modules](https://springmodules.dev.java.net/). In [this tutorial](http://wheelersoftware.com/articles/spring-bean-validation-framework.html), the following bean (getters and setters omitted) is used as an example:
```
public final ... | I took a quick look at the [BeanValidator API](https://springmodules.dev.java.net/source/browse/%2Acheckout%2A/springmodules/www/docs/javadocs/0.8/org/springmodules/validation/bean/BeanValidator.html), and it looks like you might want to try the *errorCodeConverter* property.
You would need to implement your own [Erro... | Spring validation does have an ErrorCodeConverter that does this:
org.springmodules.validation.bean.converter.KeepAsIsErrorCodeConverter
When this is used, the resource bundle will be checked for the following codes:
[errorCode.commandBeanName.fieldName, errorCode.fieldName, errorCode.fieldClassName, errorCode]
* e... | annotation based Spring bean validation | [
"",
"java",
"validation",
"spring-modules",
""
] |
I have read the documentation on this and I think I understand. An [`AutoResetEvent`](http://msdn.microsoft.com/en-us/library/system.threading.autoresetevent.aspx) resets when the code passes through `event.WaitOne()`, but a [`ManualResetEvent`](http://msdn.microsoft.com/en-us/library/system.threading.manualresetevent.... | Yes. It's like the difference between a tollbooth and a door. The `ManualResetEvent` is the door, which needs to be closed (reset) manually. The `AutoResetEvent` is a tollbooth, allowing one car to go by and automatically closing before the next one can get through. | Just imagine that the `AutoResetEvent` executes `WaitOne()` and `Reset()` as a single atomic operation.
The `AutoResetEvent` also guarantees to only release **one** waiting thread. | What is the difference between ManualResetEvent and AutoResetEvent in .NET? | [
"",
"c#",
".net",
"multithreading",
"autoresetevent",
"manualresetevent",
""
] |
The in-house application framework we use at my company makes it necessary to put every SQL query into transactions, even though if I know that none of the commands will make changes in the database. At the end of the session, before closing the connection, I commit the transaction to close it properly. I wonder if the... | Databases often preserve either a before-image journal (what it was before the transaction) or an after-image journal (what it will be when the transaction completes.) If it keeps a before-image, that has to be restored on a rollback. If it keeps an after-image, that has to replace data in the event of a commit.
Oracl... | I agree with the previous answers that there's no difference between COMMIT and ROLLBACK in this case. There might be a negligible difference in the CPU time needed to determine that there's nothing to COMMIT versus the CPU time needed to determine that there's nothing to ROLLBACK. But, if it's a negligible difference,... | Is there a difference between commit and rollback in a transaction only having selects? | [
"",
"sql",
"oracle",
"transactions",
"commit",
"rollback",
""
] |
Does windows have any decent sampling (eg. non-instrumenting) profilers available? Preferably something akin to Shark on MacOS, although i am willing to accept that i am going to have to pay for such a profiler on windows.
I've tried the profiler in VS Team Suite and was not overly impressed, and was wondering if ther... | [Intel VTune](http://www.intel.com/cd/software/products/asmo-na/eng/239144.htm) is good and is non-instrumenting. We evaluated a whole bunch of profilers for Windows, and this was the best for working with driver code (though it does unmanaged user level code as well). A particular strength is that it reads all the Int... | For Windows, check out the free [Xperf](http://blogs.msdn.com/pigscanfly/archive/2008/02/09/xperf-a-new-tool-in-the-windows-sdk.aspx) that ships with the Windows SDK. It uses sampled profile, has some useful UI, & does not require instrumentation. Quite useful for tracking down performance problems. You can answer ques... | Decent profiler for Windows? | [
"",
"c++",
"windows",
"performance",
"profiling",
""
] |
It appears that in PHP objects are passed by reference. Even assignment operators do not appear to be creating a copy of the Object.
Here's a simple, contrived proof:
```
<?php
class A {
public $b;
}
function set_b($obj) { $obj->b = "after"; }
$a = new A();
$a->b = "before";
$c = $a; //i would especially expe... | In PHP 5+ objects are passed by reference. In PHP 4 they are passed by value (that's why it had runtime pass by reference, which became deprecated).
You can use the 'clone' operator in PHP5 to copy objects:
```
$objectB = clone $objectA;
```
Also, it's just objects that are passed by reference, not everything as you... | The answers are commonly found in Java books.
1. cloning:
If you don't override clone method, the default behavior is shallow copy. If your objects have only primitive member variables, it's totally ok. But in a typeless language with another object as member variables, it's a headache.
2. serialization/deserializa... | How do I create a copy of an object in PHP? | [
"",
"php",
"copy",
"clone",
"shallow-copy",
""
] |
How can I delete the contents of a local folder in Python?
The current project is for Windows, but I would like to see \*nix also. | ```
import os, shutil
folder = '/path/to/folder'
for filename in os.listdir(folder):
file_path = os.path.join(folder, filename)
try:
if os.path.isfile(file_path) or os.path.islink(file_path):
os.unlink(file_path)
elif os.path.isdir(file_path):
shutil.rmtree(file_path)
... | You can simply do this:
```
import os
import glob
files = glob.glob('/YOUR/PATH/*')
for f in files:
os.remove(f)
```
You can of course use an other filter in you path, for example : /YOU/PATH/\*.txt for removing all text files in a directory. | How to delete the contents of a folder? | [
"",
"python",
"file",
""
] |
I ran into an interesting (and very frustrating) issue with the `equals()` method today which caused what I thought to be a well tested class to crash and cause a bug that took me a very long time to track down.
Just for completeness, I wasn't using an IDE or debugger - just good old fashioned text editor and System.o... | In Java, the `equals()` method that is inherited from `Object` is:
```
public boolean equals(Object other);
```
In other words, the parameter must be of type `Object`. This is called *overriding*; your method `public boolean equals(Book other)` does what is called *overloading* to the `equals()` method.
The `ArrayLi... | If you use eclipse just go to the top menu
> Source --> Generate equals() and
> hashCode() | Overriding the java equals() method - not working? | [
"",
"java",
"equals",
"overriding",
""
] |
Given a credit card number and no additional information, what is the best way in PHP to determine whether or not it is a valid number?
Right now I need something that will work with American Express, Discover, MasterCard, and Visa, but it might be helpful if it will also work with other types. | There are three parts to the validation of the card number:
1. **PATTERN** - does it match an issuers pattern (e.g. VISA/Mastercard/etc.)
2. **CHECKSUM** - does it actually check-sum (e.g. not just 13 random numbers after "34" to make it an AMEX card number)
3. **REALLY EXISTS** - does it actually have an associated a... | From [10 regular expressions you can't live without in PHP](http://web.archive.org/web/20080918014358/http://www.roughguidetophp.com/10-regular-expressions-you-just-cant-live-without-in-php/):
```
function check_cc($cc, $extra_check = false){
$cards = array(
"visa" => "(4\d{12}(?:\d{3})?)",
"amex" ... | What is the best way to validate a credit card in PHP? | [
"",
"php",
"validation",
"e-commerce",
"numbers",
"credit-card",
""
] |
When I parse my xml file (variable f) in this method, I get an error
> C:\Documents and Settings\joe\Desktop\aicpcudev\OnlineModule\map.dtd (The system cannot find the path specified)
I know I do not have the dtd, nor do I need it. How can I parse this File object into a Document object while ignoring DTD reference e... | A similar approach to the one suggested by [@anjanb](https://stackoverflow.com/questions/155101/make-documentbuilderparse-ignore-dtd-references#155330)
```
builder.setEntityResolver(new EntityResolver() {
@Override
public InputSource resolveEntity(String publicId, String systemId)
t... | Try setting features on the DocumentBuilderFactory:
```
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setValidating(false);
dbf.setNamespaceAware(true);
dbf.setFeature("http://xml.org/sax/features/namespaces", false);
dbf.setFeature("http://xml.org/sax/features/validation", false);
dbf.setFea... | Make DocumentBuilder.parse ignore DTD references | [
"",
"java",
"document",
"dtd",
""
] |
I need to develop a generic jQuery-based search plugin for the ASP.NET MVC application I'm building, but I can't figure out how it's supposed to fit, or what the best practice is. I want to do the following:
```
$().ready(function() {
$('#searchHolder').customSearch('MyApp.Models.User');
});
```
As long as I have... | Just to follow up (I'm very surprised nobody else has had any opinions on this), in an effort to keep best practice I've opted to adopt [jTemplates](http://jtemplates.tpython.com/).
It enables me to request some Model-style JSON from my server-side Controller and process it using syntax similar to that I would already... | It sounds to me like what you want are `partials`, a RoR term so not sure that they exist in the same format in ASP.NET MVC. Basically a partial is a part of a View thats defined in its own file and can be called from anywhere. So in your search controller, you would pull out the Model asked for, do some reflection to ... | Where does jQuery UI fit in MVC? | [
"",
"javascript",
"model-view-controller",
"jquery-plugins",
""
] |
I could probably write this myself, but the specific way I'm trying to accomplish it is throwing me off. I'm trying to write a generic extension method similar to the others introduced in .NET 3.5 that will take a nested IEnumerable of IEnumerables (and so on) and flatten it into one IEnumerable. Anyone have any ideas?... | Hmm... I'm not sure *exactly* what you want here, but here's a "one level" option:
```
public static IEnumerable<TElement> Flatten<TElement,TSequence> (this IEnumerable<TSequence> sequences)
where TSequence : IEnumerable<TElement>
{
foreach (TSequence sequence in sequences)
{
foreach(TElement elem... | Here's an extension that might help. It will traverse all nodes in your hierarchy of objects and pick out the ones that match a criteria. It assumes that each object in your hierarchy **has a collection property** that holds its child objects.
## Here's the extension:
```
/// Traverses an object hierarchy and return ... | Recursive List Flattening | [
"",
"c#",
".net",
"recursion",
""
] |
I have some code that creates a fairly large xml DOM and writes it off to a file (up to 50-100MB) . It basically creates the DOM and then calls a toString on it and writes it out with ofstream. Is there a way to get streaming output of the generated dom so that it doesn't create the whole structure in memory all at onc... | Ok, turns out libxml2 has a streaming API:
<http://xmlsoft.org/examples/testWriter.c>
It's a little old style (very C-ish) but you can write your wrapper around it. | I would recommend [GenX](http://www.tbray.org/ongoing/When/200x/2004/02/20/GenxStatus) as a streaming XML writer, I use this in [Programmer's Notepad](http://pnotepad.org/) and it works a treat, you can see examples of use in the source code. Extremely fast, and it produces good UTF-8 XML. Memory usage while you use it... | create and stream large XML document in C++ | [
"",
"c++",
"xml",
""
] |
I am getting the following error when I put class files in subfolders of my App\_Code folder:
errorCS0246: The type or namespace name 'MyClassName' could not be found (are you missing a using directive or an assembly reference?)
This class is not in a namespace at all. Any ideas? | You need to add codeSubDirectories to your compilation element in web.config
```
<configuration>
<system.web>
<compilation>
<codeSubDirectories>
<add directoryName="View"/>
</codeSubDirectories>
</compilation>
</system.web>
</configuration>
``` | Check for BuildAction property of file. This should be set to "Compile" | How come classes in subfolders in my App_Code folder are not being found correctly? | [
"",
"c#",
"asp.net",
"namespaces",
"app-code",
""
] |
Has anyone else seen people do this:
```
private string _name;
public string Name{ get{ return _name; } set{ _name = value;}}
```
I understand using accessors if you are going to exercise some sort of control over how it gets set or perform some sort of function on it when there is a get. But if you are just going to... | If you make the member a public field, then you can't later refactor it into a property without changing the interface to your class. If you expose it as a property from the very beginning, you can make whatever changes to the property accessor functions that you need and the class's interface remains unchanged.
Note ... | If you define a public interface with a property in assembly A, you could then use this interface in assembly B.
Now, you can change the property's implementation (maybe fetching the value from a database instead of storing it in a field). Then you can recompile assembly A, and replace an older one. Assembly B would c... | public variables vs private variables with accessors | [
"",
"c#",
"oop",
"accessor",
""
] |
```
<div id="myDiv">
<a>...</a>
<a>...</a>
<a>...</a>
<a>...</a>
<a>...</a>
<a>...</a>
</div>
```
If you wanted to select the 2nd, 3rd and 4th `a` tags in the above example, how would you do that? The only thing I can think of is:
```
$("#myDiv a:eq(1), #myDiv a:eq(2), #myDiv a:eq(3)")
`... | jQuery [slice()](http://docs.jquery.com/Traversing/slice) function taking indexes of the first and the last needed elements selects a subset of the matched elements. Note what it doesn't include last element itself.
In your particular case you should use
```
$("#myDiv a").slice(1, 4)
``` | Using the [.slice()](http://docs.jquery.com/Traversing/slice) function does exactly what I need. | How to select a range of elements in jQuery | [
"",
"javascript",
"jquery",
""
] |
Let me start with a specific example of what I'm trying to do.
I have an array of year, month, day, hour, minute, second and millisecond components in the form `[ 2008, 10, 8, 00, 16, 34, 254 ]`. I'd like to instantiate a Date object using the following standard constructor:
```
new Date(year, month, date [, hour, mi... | I've done more investigation of my own and came up with the conclusion that **this is an impossible feat**, due to how the Date class is implemented.
I've inspected the [SpiderMonkey](http://www.mozilla.org/js/spidermonkey/) source code to see how Date was implemented. I think it all boils down to the following few li... | I'd hardly call this elegant, but in my testing (FF3, Saf4, IE8) it works:
`var arr = [ 2009, 6, 22, 10, 30, 9 ];`
Instead of this:
`var d = new Date( arr[0], arr[1], arr[2], arr[3], arr[4], arr[5] );`
Try this:
`var d = new Date( Date.UTC.apply( window, arr ) + ( (new Date()).getTimezoneOffset() * 60000 ) );` | Instantiating a JavaScript object by calling prototype.constructor.apply | [
"",
"javascript",
"reflection",
""
] |
What am I doing wrong here?
```
string q = "john s!";
string clean = Regex.Replace(q, @"([^a-zA-Z0-9]|^\s)", string.Empty);
// clean == "johns". I want "john s";
``` | just a FYI
```
string clean = Regex.Replace(q, @"[^a-zA-Z0-9\s]", string.Empty);
```
would actually be better like
```
string clean = Regex.Replace(q, @"[^\w\s]", string.Empty);
``` | This:
```
string clean = Regex.Replace(dirty, "[^a-zA-Z0-9\x20]", String.Empty);
```
> > **\x20** is ascii hex for 'space' character
you can add more individual characters that you want to be allowed.
If you want for example **"?"** to be ok in the return string add **\x3f**. | Regex to match alphanumeric and spaces | [
"",
"c#",
"regex",
""
] |
How can I use HttpWebRequest (.NET, C#) asynchronously? | Use [`HttpWebRequest.BeginGetResponse()`](http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.begingetresponse.aspx)
```
HttpWebRequest webRequest;
void StartWebRequest()
{
webRequest.BeginGetResponse(new AsyncCallback(FinishWebRequest), null);
}
void FinishWebRequest(IAsyncResult result)
{
web... | By far the easiest way is by using [TaskFactory.FromAsync](http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskfactory.fromasync.aspx) from the [TPL](http://msdn.microsoft.com/en-us/library/dd460717.aspx). It's literally a couple of lines of code when used in conjunction with the new [async/await](http:/... | How to use HttpWebRequest (.NET) asynchronously? | [
"",
"c#",
".net",
"asynchronous",
"httprequest",
""
] |
I have a couple of solutions, but none of them work perfectly.
**Platform**
1. ASP.NET / VB.NET / .NET 2.0
2. IIS 6
3. IE6 (primarily), with some IE7; Firefox not necessary, but useful
*Allowed 3rd Party Options*
1. Flash
2. ActiveX (would like to avoid)
3. Java (would like to avoid)
**Current Attempts**
*Gmail S... | [@davidinbcn.myopenid.co](https://stackoverflow.com/questions/50315/how-do-you-allow-multiple-file-uploads-on-an-internal-windows-authentication-in#70521): That's basically how I solved this issue. But, in an effort to provide a more detailed answer, I'm posting my solution here.
**The Solution!**
Create two web appl... | I don't think there is any work around for the integrated windows authentication. What you could possibly do is save the files to a generic unprotected folder and, in the case of swfupload, use a handler to move the file when its fully uploaded | How do you allow multiple file uploads on an internal windows-authentication intranet? | [
"",
"javascript",
"flash",
"authentication",
"activex",
"file-upload",
""
] |
i have a wordpress blog and want to give people the same user experience for adding comments that is in stackoverflow. There are a number of comments ajax plugins out there but i can't find a working one that allows you to inline on the main page, go in and add comments without first drilling down into a seperate singl... | I was never able to get AJAXed Wordpress to do what me (and apparently the questioner) want to do.
I use a custom solution that makes use of a plug-in called [Inline Ajax Comments](http://kashou.net/blog/inline-ajax-comments). I had a heck of a time finding a download link, but here's one that still works: <http://kas... | I think [AJAXed Wordpress](http://wordpress.org/extend/plugins/ajaxd-wordpress/) does what you're looking for, among other things:
### [AJAXed Wordpress](http://anthologyoi.com/awp)
> AJAXed Wordpress (AWP) harnesses the power of both AJAX and Wordpress to improve
> the user experience, the administration capabilitie... | wordpress - having comments inline ajax like in stackoverflow | [
"",
"php",
"ajax",
"wordpress",
"comments",
""
] |
How do you detect if `Socket#close()` has been called on a socket on the remote side? | The `isConnected` method won't help, it will return `true` even if the remote side has closed the socket. Try this:
```
public class MyServer {
public static final int PORT = 12345;
public static void main(String[] args) throws IOException, InterruptedException {
ServerSocket ss = ServerSocketFactory.g... | Since the answers deviate I decided to test this and post the result - including the test example.
The server here just writes data to a client and does not expect any input.
The server:
```
ServerSocket serverSocket = new ServerSocket(4444);
Socket clientSocket = serverSocket.accept();
PrintWriter out = new PrintWr... | How to detect a remote side socket close? | [
"",
"java",
"networking",
"sockets",
"tcp",
""
] |
I call my JavaScript function. Why do I *sometimes* get the error 'myFunction is not defined' when it *is* defined?
For example. I'll occasionally get 'copyArray is not defined' even in this example:
```
function copyArray( pa ) {
var la = [];
for (var i=0; i < pa.length; i++)
la.push( pa[i] );
re... | It shouldn't be possible for this to happen if you're just including the scripts on the page.
The "copyArray" function should always be available when the JavaScript code starts executing no matter if it is declared before or after it -- unless you're loading the JavaScript files in dynamically with a dependency libra... | I had this function not being recognized as defined in latest Firefox for Linux, though Chromium was dealing fine with it.
What happened in my case was that I had a former `SCRIPT` block, before the block that defined the function with problem, stated in the following way:
```
<SCRIPT src="mycode.js"/>
```
(That is,... | Why is my JavaScript function sometimes "not defined"? | [
"",
"javascript",
""
] |
Is there a way in PHP to make HTTP calls and not wait for a response? I don't care about the response, I just want to do something like `file_get_contents()`, but not wait for the request to finish before executing the rest of my code. This would be super useful for setting off "events" of a sort in my application, or ... | You can do trickery by using exec() to invoke something that can do HTTP requests, like `wget`, but you must direct all output from the program to somewhere, like a file or /dev/null, otherwise the PHP process will wait for that output.
If you want to separate the process from the apache thread entirely, try something... | The answer I'd previously accepted didn't work. It still waited for responses. This does work though, taken from [How do I make an asynchronous GET request in PHP?](https://stackoverflow.com/questions/962915/how-do-i-make-an-asynchronous-get-request-in-php)
```
function post_without_wait($url, $params)
{
foreach (... | How to make HTTP requests in PHP and not wait on the response | [
"",
"php",
"http",
"asynchronous",
""
] |
We use an IBM database known as Universe that holds all of our user id's, passwords, and profile information in a table called USERINFO.
Can I use the Membership Provider to connect to this database and authenticate the user?
The database access is actually through a web service since we don't have a direct connect t... | As mentioned above, you'll need to create a custom membership provider which a fairly straightforward. You'll create a .NET class that inherits from System.Web.Security.MembershipProvider. There are several methods that need to be overriden in your class, but most are not even used by the MVC account controller. The ma... | You'll have to create a custom provider for that. It isn't very hard, as long as you can access the web service without an issue. | What is the best way to handle authentication in ASP.NET MVC with a Universe database? | [
"",
"c#",
"asp.net-mvc",
"u2",
"universe",
""
] |
In IE when I insert text into a `<pre>` tag the newlines are ignored:
```
<pre id="putItHere"></pre>
<script>
function putText() {
document.getElementById("putItHere").innerHTML = "first line\nsecond line";
}
</script>
```
Using `\r\n` instead of a plain `\n` does not work.
`<br/>` does work but inserts an extra... | These [quirksmode.org bug report and comments](http://www.quirksmode.org/bugreports/archives/2004/11/innerhtml_and_t.html) about innerHTML behaviour of Internet Explorer could help:
"*IE applies **HTML normalization** to the data that is assigned to the innerHTML property. This causes incorrect display of whitespace i... | Does this work in IE?
```
document.getElementById("putItHere")
.appendChild(document.createTextNode("first line\nsecond line"));
```
I tested it with Firefox and it works. :-) | Inserting a newline into a pre tag (IE, Javascript) | [
"",
"javascript",
"html",
"internet-explorer",
"pre",
""
] |
I have a webpage that pulls information from a database, converts it to .csv format, and writes the file to the HTTPResponse.
```
string csv = GetCSV();
Response.Clear();
Response.ContentType = "text/csv";
Response.Write(csv);
```
This works fine, and the file is sent to the client with no problems. However, when the... | I believe this will work for you.
```
Response.AddHeader("content-disposition", "attachment; filename=NewFileName.csv");
``` | You just need to set the **Content-Disposition** header
```
Content-Disposition: attachment; filename=data.csv
```
---
This Microsoft Support article has some good information
[How To Raise a "File Download" Dialog Box for a Known MIME Type](http://support.microsoft.com/kb/260519) | Change name of file sent to client? | [
"",
"c#",
"asp.net",
"http",
""
] |
If I load the nextimg URL manually in the browser, it gives a new picture every time I reload. But this bit of code shows the same image every iteration of `draw()`.
How can I force myimg not to be cached?
```
<html>
<head>
<script type="text/javascript">
function draw(){
var canvas = document.get... | That actually sounds like a bug in the browser -- you could file at <http://bugs.webkit.org> if it's in Safari or <https://bugzilla.mozilla.org/> for Firefox. Why do i say potential browser bug? Because the browser realises it should not be caching on reload, yet it does give you a cached copy of the image when you req... | The easiest way is to sling an ever-changing querystring onto the end:
```
var url = 'http://.../?' + escape(new Date())
```
Some people prefer using `Math.random()` for that instead of `escape(new Date())`. But the correct way is probably to alter the headers the web server sends to disallow caching. | JavaScript: how to force Image() not to use the browser cache? | [
"",
"javascript",
"image",
"caching",
""
] |
Mobile Safari is a very capable browser, and it can handle my website as it is perfectly. However, there are a few elements on my page that could be optimized for browsing using this device; such as serving specific thumbnails that are smaller than the desktop counterparts to help fit more content into the screen.
I w... | Compare the user agent string with the one of a Safari Mobile uses:
[Safari Mobile User Agent String](http://developer.apple.com/library/safari/#documentation/AppleApplications/Reference/SafariWebContent/OptimizingforSafarioniPhone/OptimizingforSafarioniPhone.html#//apple_ref/doc/uid/TP40006517-SW3) | Thanks Joe, I read that page and found the [WebKit detection library](http://trac.webkit.org/wiki/DetectingWebKit) (in JavaScript). I changed the code to suit my needs.
For anyone that's interested, here's my solution.
```
<?php
/* detect Mobile Safari */
$browserAsString = $_SERVER['HTTP_USER_AGENT'];
if (strstr(... | How do I detect Mobile Safari server side using PHP? | [
"",
"php",
"iphone",
"optimization",
"mobile-safari",
""
] |
We have recently migrated a large, high demand web application to Tomcat 5.5 from Tomcat 4 and have noticed some peculiar slowdown behavior that appears to be related to JVM pauses. In order to run our application and support increased load over time on Tomcat 4, many not so standard JVM parameters were set and tuned a... | One of the Java Champions, Kirk Pepperdine's blog : <http://kirk.blog-city.com/how_to_cripple_gc_ergonomics.htm>.
Quote 1
"GC documentation will tell you what the setting affects but often without telling what the effect will be. The biggest clue that you've taken the wrong fork in the road is when you explicitly se... | As someone who's in the midst of messing with this as well, I certainly don't have any definitive answers, especially given how application-specific this sort of thing is. A good reference, which you've likely seen, is here:
<http://java.sun.com/javase/technologies/hotspot/gc/gc_tuning_6.html>
However,it's a pretty l... | Appropriate Tomcat 5.5 start-up parameters to tune JVM for extremely high demand, large heap web application? | [
"",
"java",
"tomcat",
"jvm",
"performance",
""
] |
If I want to call `Bar()` instead of `Foo()`, does `Bar()` return me a copy (additional overhead) of what Foo() returns, or it returns the same object which `Foo()` places on the temporary stack?
```
vector<int> Foo(){
vector<int> result;
result.push_back(1);
return result;
}
vector<int> Bar(){ ... | Both may happen. However, most compiler will not do copy as soon as you optimize.
Your code indicate there should be a copy. However, the compiler is allowed to remove any copy that do not change the semantic and the program.
Note: This is why you should NEVER have a copy constructor that does anything but copying co... | Normally it returns a copy of the returned `vector<int>`. However this highly depends on the optimization done by the compiler. See the following discussion.
**Debug Build**
```
vector<int> Foo(){
004118D0 push ebp
004118D1 mov ebp,esp
004118D3 push 0FFFFFFFFh
004118D5 push offs... | Function returning the return of another function | [
"",
"c++",
"function",
"vector",
"return-value",
""
] |
I'm currently trying to pass a mono threaded program to multithread. This software do heavy usage of "refCounted" objects, which lead to some issues in multithread. I'm looking for some design pattern or something that might solve my problem.
The main problem is object deletion between thread, normally deletion only d... | If the count is part of the object then you have an inherent problem if one thread can be trying to *increase* the reference count whilst another is trying to remove the *last* reference. There needs to be an extra value on the ref count for each globally accessible pointer to the object, so you can always safely incre... | Surely each thread simply needs to manage the reference counts correctly... That is, if ThreadA and ThreadB are both working with Obj1 then BOTH ThreadA and ThreadB should own a reference to the object and BOTH should call release when they're done with the object.
In a single threaded application it's likely that you... | C++: Multithreading and refcounted object | [
"",
"c++",
"multithreading",
"refcounting",
""
] |
I have a web page where I'd like to remap Ctrl+N to a different behavior. I followed YUI's example of register Key Listeners and my function is called but Firefox still creates a new browser window. Things seem to work fine on IE7. How do I stop the new window from showing up?
Example:
```
var kl2 = new YAHOO.util.Ke... | The trick is the 'fn' function is whack.
Experimentally, you can see that the function type for fn takes two parameters. The first param actually contains the TYPE of event. The second one contains... and this is screwy: an array containing the codepoint at index 0 and the actual event object at index 1.
So changing ... | I'm just guessing here but I don't think it can be done.
If it's possible it definitely shouldn't be. Generic keyboard shortcuts are something you should not mess with. What's next? Hook the window close button to open a new window... | Prevent Default Behavior in Key Listeners in YUI | [
"",
"javascript",
"firefox",
"yui",
""
] |
In PHP, which is quicker; using `include('somefile.php')` or querying a MySQL database with a simple `SELECT` query to get the same information?
For example, say you had a JavaScript autocomplete search field which needed 3,000 terms to match against. Is it quicker to read those terms in from another file using `inclu... | It depends. If your file is stored locally in your server and the database is installed in another machine, then the faster is to include the file.
Buuuuut, because it depends on your system it could be not true. I suggest to you to make a PHP test script and run it 100 times from the command line, and repeat the test... | Including a file should almost always be quicker. If your database is on another machine (e.g. in shared hosting) or in a multi-server setup the lookup will have to make an extra hop.
However, in practice the difference is probably not going to matter. If the list is dynamic then storing it in MySQL will make your lif... | What's quicker; including another file or querying a MySQL database in PHP? | [
"",
"php",
"mysql",
"performance",
"include",
""
] |
Can anyone recommend a ready-to-use class/library compatible with C/C++/MFC/ATL that would parse iCal/vCal/Google calendar files (with recurrences)? It can be free or commercial. | there is a [parser in PHP for iCal](http://www.phpclasses.org/browse/package/3278.html), you can downloaded and check the code to suit your language.
for vCal/vCard parsing [there's a C Library](http://sourceforge.net/projects/ccard).
for Google Calendar I couldn't find any exact answer, so, try to Google it. | For vCal you can try the [CCard](http://ccard.sourceforge.net/) project on SourceForge:
<http://sourceforge.net/projects/ccard>
It's a C library but it states Windows as a supported platform.
\*Edit: balexandre already linked to it :) | Parsing iCal/vCal/Google calendar files in C++ | [
"",
"c++",
"mfc",
"icalendar",
"google-calendar-api",
"vcalendar",
""
] |
So I understand what a static method or field is, I am just wondering when to use them. That is, when writing code what design lends itself to using static methods and fields.
One common pattern is to use static methods as a static factory, but this could just as easily be done by overloading a constructor. Correct? F... | It gives a better idea of the intent when you use a static factory -- it also lets you have different factories that take the same argument types but have a different meaning. For example, imagine if Bitmap had LoadFromResource(string) -- it would not be possible to have two constructors that both took string.
**EDIT*... | Static methods are usually useful for operations that don't require any data from an instance of the class (from `this`) and can perform their intended purpose solely using their arguments.
A simple example of this would be a method `Point::distance(Point a, Point b);` that calculates the distance between two points ... | When should I write Static Methods? | [
"",
"c#",
"oop",
""
] |
I thought people would be working on little code projects together, but I don't see them, so here's an easy one:
Code that validates a valid US Zip Code. I know there are ZIP code databases out there, but there are still uses, like web pages, quick validation, and also the fact that zip codes keep getting issued, so y... | **Javascript Regex Literal**:
US Zip Codes: `/(^\d{5}$)|(^\d{5}-\d{4}$)/`
```
var isValidZip = /(^\d{5}$)|(^\d{5}-\d{4}$)/.test("90210");
```
Some countries use [Postal Codes](http://en.wikipedia.org/wiki/Postal_code), which would fail this pattern. | ```
function isValidUSZip(sZip) {
return /^\d{5}(-\d{4})?$/.test(sZip);
}
``` | ZIP Code (US Postal Code) validation | [
"",
"javascript",
"validation",
""
] |
Here's the situation:
I'm developing a simple application with the following structure:
* FormMain (startup point)
* FormNotification
* CompleFunctions
Right?
Well, in **FormMain** I have the following function:
```
private void DoItInNewThread(ParameterizedThreadStart pParameterizedThreadStart, object pParameters,... | Almost every GUI library is designed to only allow calls that change the GUI to be made in a single thread designated for that purpose (called the UI thread). If you are in another thread, you are required to arrange for the call to change the GUI to be made in the UI thread. In .NET, the way to do that is to call Invo... | You aren't allowed to make WinForms calls from other threads. Look at BeginInvoke in the form -- you can call a delegate to show the form from the UI thread.
Edit: From the comments (do not set CheckForIllegalCrossThreadCalls to false).
**More Info**
Almost every GUI library is designed to only allow calls that chang... | My form doesn't properly display when it is launched from another thread | [
"",
"c#",
"winforms",
"multithreading",
""
] |
I have a list of objects, each containing an Id, Code and Description.
I need to convert this list into a Hashtable, using **Description** as the key and **Id** as the value.
This is so the Hashtable can then be serialised to JSON.
Is there a way to convert from List<Object> to Hashtable without writing a loop to go... | Let's assume that your List contains objects of type Foo (with an int Id and a string Description).
You can use Linq to turn that list into a Dictionary like this:
```
var dict = myList.Cast<Foo>().ToDictionary(o => o.Description, o => o.Id);
``` | If you have access to Linq, you can use the [ToDictionary](http://msdn.microsoft.com/en-us/library/bb549277.aspx) function. | How can I convert List<object> to Hashtable in C#? | [
"",
"c#",
"list",
"hashtable",
""
] |
I'm writing a little debug app for a bit of kit we're developing and I'd like to roll it out to a few users to see if they can provoke any crashes. Does anyone know a way of effectively wrapping a wxPython app to catch any and all unhandled exceptions that would cause the app to crash?
Ideally I'd want to capture all ... | For logging standard output, you can use a stdout wrapper, such as this one:
```
from __future__ import with_statement
class OutWrapper(object):
def __init__(self, realOutput, logFileName):
self._realOutput = realOutput
self._logFileName = logFileName
def _log(self, text):
with open(s... | For the exception handling, assuming your log file is opened as log:
```
import sys
import traceback
def excepthook(type, value, tb):
message = 'Uncaught exception:\n'
message += ''.join(traceback.format_exception(type, value, tb))
log.write(message)
sys.excepthook = excepthook
``` | How can I capture all exceptions from a wxPython application? | [
"",
"python",
"exception",
"error-handling",
"wxwidgets",
"error-reporting",
""
] |
I've used [DJ Java Decompiler](http://members.fortunecity.com/neshkov/dj.html), which has a handy GUI, but it seems as if the latest version is only a trial and forces you to purchase the software after some period of days (I recall using an earlier free version about a year ago at a previous job).
I'm aware of Jad an... | Eclipse will allow you to [view the bytecode for classes](http://archive.eclipse.org/eclipse/downloads/drops/R-3.3-200706251500/whatsnew/eclipse-news-part2.html), if the source is unavailable (search for 'disassembled bytecodes').
It seems there is also a third-party plugin that uses asm [here](http://asm.objectweb.or... | JAD is one of the best Java Decompiler today. This is one brilliant piece of software. Nevertheless, the last JDK supported by JAD 1.5.8 (Apr 14, 2001) is JDK 1.3.
DJ Java Decompiler, JadClipse, Cavaj and JarInspector are powered by Jad.
The last version of Decafe Pro has been released on 2002-01-03.
These viewers ca... | Best free Java .class viewer? | [
"",
"java",
"decompiling",
""
] |
```
class Foo(models.Model):
title = models.CharField(max_length=20)
slug = models.SlugField()
```
Is there a built-in way to get the slug field to autopopulate based on the title? Perhaps in the Admin and outside of the Admin. | for Admin in Django 1.0 and up, you'd need to use
```
prepopulated_fields = {'slug': ('title',), }
```
in your admin.py
Your key in the prepopulated\_fields dictionary is the field you want filled, and the value is a tuple of fields you want concatenated.
Outside of admin, you can use the `slugify` function in your... | Thought I would add a complete and up-to-date answer with gotchas mentioned:
## 1. Auto-populate forms in Django Admin
If you are only concerned about adding and updating data in the admin, you could simply use the [prepopulated\_fields](https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.Mo... | Is there an easy way to populate SlugField from CharField? | [
"",
"python",
"django",
"slug",
""
] |
What is the best way to write bytes in the middle of a file using Java? | Reading and Writing in the middle of a file is as simple as using a [`RandomAccessFile`](http://java.sun.com/javase/6/docs/api/java/io/RandomAccessFile.html) in Java.
[`RandomAccessFile`](http://java.sun.com/javase/6/docs/api/java/io/RandomAccessFile.html), despite its name, is more like an `InputStream` and `OutputSt... | Use `RandomAccessFile`
* [Tutorial](http://java.sun.com/docs/books/tutorial/essential/io/rafs.html)
* [Javadocs](http://java.sun.com/javase/6/docs/api/java/io/RandomAccessFile.html) | Best Way to Write Bytes in the Middle of a File in Java | [
"",
"java",
"file",
"java-io",
""
] |
What is the best or most concise method for returning a string repeated an arbitrary amount of times?
The following is my best shot so far:
```
function repeat(s, n){
var a = [];
while(a.length < n){
a.push(s);
}
return a.join('');
}
``` | Good news! [`String.prototype.repeat`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat) is [now a part of JavaScript](http://www.ecma-international.org/ecma-262/6.0/index.html#sec-string.prototype.repeat).
```
"yo".repeat(2);
// returns: "yoyo"
```
The method is supporte... | > **Note to new readers:** This answer is old and and not terribly practical - it's just "clever" because it uses Array stuff to get
> String things done. When I wrote "less process" I definitely meant
> "less code" because, as others have noted in subsequent answers, it
> performs like a pig. So don't use it if speed ... | Repeat String - Javascript | [
"",
"javascript",
"string",
""
] |
This is what I currently have:
```
CREATE OR REPLACE TRIGGER MYTRIGGER
AFTER INSERT ON SOMETABLE
FOR EACH ROW
DECLARE
v_emplid varchar2(10);
BEGIN
SELECT
personnum into v_emplid
FROM PERSON
WHERE PERSONID = :new.EMPLOYEEID;
dbms_output.put(v_emplid);
/* INSERT INTO SOMEOTHERTABLE USING v_emplid and s... | 1) There must be something else to your example because that sure seems to work for me
```
SQL> create table someTable( employeeid number );
Table created.
SQL> create table person( personid number, personnum varchar2(10) );
Table created.
SQL> ed
Wrote file afiedt.buf
1 CREATE OR REPLACE TRIGGER MYTRIGGER
2... | You are playing with Lava (not just fire) in your trigger. DBMS\_OUTPUT in a trigger is really, really bad. You can blow-out on a buffer overflow in your trigger and the whole transaction is shot. Good luck tracking that down. If you must do output-to-console like behavior, invoke an AUTONOMOUS TRANSACTION procedure th... | What is the syntax to use a Select statement inside a PL/SQL Trigger? | [
"",
"sql",
"oracle",
"plsql",
"ora-00923",
""
] |
Is it possible to set a default value for columns in JPA, and if, how is it done using annotations? | Actually it is possible in JPA, although a little bit of a hack using the `columnDefinition` property of the `@Column` annotation, for example:
```
@Column(name="Price", columnDefinition="Decimal(10,2) default '100.00'")
``` | You can do the following:
```
@Column(name="price")
private double price = 0.0;
```
There! You've just used zero as the default value.
Note this will serve you if you're only accessing the database from this application. If other applications also use the database, then you should make this check from the database u... | Setting default values for columns in JPA | [
"",
"java",
"jpa",
"annotations",
""
] |
Now that `shared_ptr` is in tr1, what do you think should happen to the use of `std::auto_ptr`? They both have different use cases, but all use cases of `auto_ptr` can be solved with `shared_ptr`, too. Will you abandon `auto_ptr` or continue to use it in cases where you want to express explicitly that only one class ha... | To provide a little more ammunition to the 'avoid `std::auto_ptr`' camp: `auto_ptr` is being deprecated in the next standard (C++0x). I think this alone is good enough ammunition for any argument to use something else.
However, as [Konrad Rudolph](https://stackoverflow.com/questions/197048/idiomatic-use-of-stdautoptr-... | auto\_ptr is nice in signatures, too. When a function takes an `auto_ptr<T>` by value, it means it will consume the `T`. If a function returns an `auto_ptr<T>`, it's clear that it relinquishes ownership. This can communicate your intents about the lifetime.
On the other hand, using `scoped_ptr<T>` implies that you don... | Idiomatic use of std::auto_ptr or only use shared_ptr? | [
"",
"c++",
"coding-style",
"smart-pointers",
"tr1",
""
] |
I have 150+ SQL queries in separate text files that I need to analyze (just the actual SQL code, not the data results) in order to identify all column names and table names used. Preferably with the number of times each column and table makes an appearance. Writing a brand new SQL parsing program is trickier than is se... | I actually ended up using a tool called
[SQL Pretty Printer](http://www.dpriver.com/pp/sqlformat.htm). You can purchase a desktop version, but I just used the free online application. Just copy the query into the text box, set the Output to "List DB Object" and click the Format SQL button.
It work great using around 1... | How about using the Execution Plan report in MS SQLServer? You can save this to an xml file which can then be parsed. | Is there a way to parser a SQL query to pull out the column names and table names? | [
"",
"sql",
"parsing",
""
] |
How do I determine if an object reference is null in C# w/o throwing an exception if it is null?
i.e. If I have a class reference being passed in and I don't know if it is null or not. | What Robert said, but for that particular case I like to express it with a guard clause like this, rather than nest the whole method body in an if block:
```
void DoSomething( MyClass value )
{
if ( value == null ) return;
// I might throw an ArgumentNullException here, instead
value.Method();
}
``` | testing against null will never\* throw an exception
```
void DoSomething( MyClass value )
{
if( value != null )
{
value.Method();
}
}
```
---
\* never as in *should never*. As @Ilya Ryzhenkov points out, an *incorrect* implementation of the != operator for MyClass could throw an exception. Fortu... | How do I detect a null reference in C#? | [
"",
"c#",
""
] |
Is there any substantial difference between those two terms?. I understand that JDK stands for Java Development Kit that is a subset of SDK (Software Development Kit). But specifying Java SDK, it should mean the same as JDK. | From this [wikipedia entry](http://en.wikipedia.org/wiki/Java_Development_Kit#Ambiguity_between_a_JDK_and_an_SDK):
> The JDK is a subset of what is loosely defined as a software development kit (SDK) in the general sense. In the descriptions which accompany their recent releases for Java SE, EE, and ME, Sun acknowledg... | JDK is the SDK for Java.
SDK stands for 'Software Development Kit', a developers tools that enables one to write the code with more more ease, effectiveness and efficiency.
SDKs come for various languages. They provide a lot of APIs (Application Programming Interfaces) that makes the programmer's work easy.
[![enter ... | Differences between JDK and Java SDK | [
"",
"sdk",
"java",
""
] |
What is the most efficient way of turning the list of values of a dictionary into an array?
For example, if I have a `Dictionary` where `Key` is `String` and `Value` is `Foo`, I want to get `Foo[]`
I am using VS 2005, C# 2.0 | ```
// dict is Dictionary<string, Foo>
Foo[] foos = new Foo[dict.Count];
dict.Values.CopyTo(foos, 0);
// or in C# 3.0:
var foos = dict.Values.ToArray();
``` | Store it in a list. It is easier;
```
List<Foo> arr = new List<Foo>(dict.Values);
```
Of course if you specifically want it in an array;
```
Foo[] arr = (new List<Foo>(dict.Values)).ToArray();
``` | Convert dictionary values into array | [
"",
"c#",
".net",
"arrays",
"generics",
"dictionary",
""
] |
I'm looking for a technique (javascript, CSS, whatever ???) that will let me control the amount of a string that is displayed. The string is the result of a search (and therefore not initially known). A simple Character count approach is trivial, but not acceptable, as it needs to handle proportional fonts. In otherwor... | Perhaps the CSS property `overflow: hidden;` can help you, in conjuntion with `width`. | Using a span with fixed width, overflow-x:hidden and white-space:nowrap would be a start.
To get the elipsis in a cross browser scenario will be difficult. IE has text-overflow:elipsis but that is non-standard. This is emulated with -o-text-overflow in Opera. However mozilla doesn't have this. The yahoo Javascript API... | Limit displayed length of string on web page | [
"",
"javascript",
"css",
"string",
"dhtml",
""
] |
what is the best way of displaying/using the revision number in a java webapp?
we just use ant to build our .war archive, no buildserver or such. i'd hope there was some kind if $ref that i could write in a resource file, but this is only updated when the file in question is committed. i need it globally.
what would ... | **There are a couple of Ant tasks that can do this for you.**
[SvnAnt task](http://subclipse.tigris.org/svnant.html) from tigris is the oldest.
Documentation is [here](http://subclipse.tigris.org/svnant/svn.html#info) - in particular take a look at the `info` element which exposes the Subversion repository's revision... | We use the following ant task to include the svn version in a attribute in the jar, along with the version of other packages that are being used
```
<target name="package" depends="compile" description="Package up the project as a jar">
<!-- Create the subversion version string -->
<exec executable="svnversion" failif... | obtain current svn revision in webapp | [
"",
"java",
"svn",
"web-applications",
"revision",
""
] |
This is a nut I'm cracking these days
Application I'm working on has some advanced processing towards SQL. One of the operations selects various metadata on the objects in the current context from different tables, based on the item names in the collection. For this, a range of "select...from...where...in()" is execut... | Hrm, without knowing context and more about the data and how you are using the results and performance issues, i will try to suggest an alternative. Could you possibly split into multiple queries? Do the same as you do now, but instead of building a query with 2100+ in items, build two with 1050 in each, and then merge... | One potential workaround is to use the ability to query XML and simply send all the data for your 'in' as an xml column and then join on that.
The same approach could be used to populate your temp table, but then again, why not just use it directly.
Here's a short sample that should illustrate:
```
declare @wanted x... | Parameterized Sql queries | [
"",
"c#",
".net",
"sql-server-2005",
"ado.net",
""
] |
I need to zip and password-protect a file. Is there a good (free) library for this?
This needs to be opened by a third party, so the password protection needs to work with standard tools. | UPDATE 2020: There are other choices now, notably [Zip4J](http://www.lingala.net/zip4j/).
---
After much searching, I've found three approaches:
A freely available set of source code, suitable for a single file zip. However, there is no license. Usage is AesZipOutputStream.zipAndEcrypt(...).
<http://merkert.de/de/in... | You can try [Zip4j](http://www.lingala.net/zip4j/), a pure java library to handle zip file. It supports encryption/ decryption of PKWare and AES encryption methods.
Key features:
* Create, Add, Extract, Update, Remove files from a Zip file
* Read/Write password protected Zip files
* Supports AES 128/256 Encryption
* ... | Recommendations on a free library to be used for zipping files | [
"",
"java",
"encryption",
"zip",
""
] |
How can I do the Ruby method ["Flatten" Ruby Method](http://www.ruby-doc.org/core/classes/Array.html#M002241) in C#. This method flattens a jagged array into a single-dimensional array.
For example:
```
s = [ 1, 2, 3 ] #=> [1, 2, 3]
t = [ 4, 5, 6, [7, 8] ] #=> [4, 5, 6, [7, 8]]
a = [ s, t, 9, 10 ] #... | Recursive solution:
```
IEnumerable Flatten(IEnumerable array)
{
foreach(var item in array)
{
if(item is IEnumerable)
{
foreach(var subitem in Flatten((IEnumerable)item))
{
yield return subitem;
}
}
else
{
y... | I would have responded in a comment, but I need more than 300 characters.
@Alexander's solution is awesome, but it runs into a problem with arrays of strings. Since string implements IEnumerable, I think it will end up returning each character in every string. You can use a generic parameter to tell it what kind of th... | Flatten Ruby method in C# | [
"",
"c#",
"ruby",
"arrays",
""
] |
I have a collection of ClickOnce packages in a publish folder on a network drive and need to move them all to another server (our DR machine).
After copy/pasting the whole directory and running the setups on the new machine I get an error message stating that it cannot find the old path:
> Activation of
> ...MyClickO... | I found a solution:
Firstly, using MageUI, I changed the "Start Location" under "Deployment Options". On saving, it prompted me to sign with a key, which I created there and then. I then ran the `setup.exe` file, and it worked without fail.
After checking which files had changed, I realised it was only the one file: ... | Without getting into too much detail, this should get you going.
ClickOnce manifests must be signed with a certificate for security reasons. You can purchase a code signing certificate or generate a test one. The main drawback of a test certificate is that your application publisher will appear as "Unknown" rather tha... | How to move a ClickOnce deployment package | [
"",
"c#",
"clickonce",
"manifest",
""
] |
I'm trying to modify the class of an element if an ajax call based on that element is successful
```
<script type='text/javascript'>
$("#a.toggle").click(function(e){
$.ajax({
url: '/changeItem.php',
dataType: 'json',
type: 'POST',
success: function(data,text){
if(data.e... | You can just store it in a variable. Example:
```
$("#a.toggle").click(function(e)
{
var target = $(this);
$.ajax({
url: '/changeItem.php',
dataType: 'json',
type: 'POST',
success: function(data,text)
{
if(data.error=='')
{
if(target.hasClass('class1'))... | jQuery passes the target of the event, along with some other information about it, to your handler function. See <http://docs.jquery.com/Events_%28Guide%29> for more info about this.
In your code, it'd be referenced like $(e.target). | How do I reference the calling dom element in a jquery ajax success function? | [
"",
"javascript",
"jquery",
""
] |
Is there such a thing as unit test generation? If so...
...does it work well?
...What are the auto generation solutions that are available for .NET?
...are there examples of using a technology like this?
...is this only good for certain types of applications, or could it be used to replace all manually written unit... | Take a look at [Pex](http://research.microsoft.com/Pex/). Its a Microsoft Research project. From the website:
*Pex generates Unit Tests from hand-written Parameterized Unit Tests through Automated Exploratory Testing based on Dynamic Symbolic Execution.*
## UPDATE for 2019:
As mentioned in the comments, Pex is now c... | I believe there's no point in Unit test generation, as far as TDD goes.
You only make unit tests so that you're sure that you (as a developer) are on track w/ regards to design and specs. Once you start generating tests automatically, it loses that purpose. Sure it would probably mean 100% code coverage, but that cove... | Auto-generation of .NET unit tests | [
"",
"c#",
".net",
"unit-testing",
"automation",
"automated-tests",
""
] |
This semester, I took a course in computer graphics at my University. At the moment, we're starting to get into some of the more advanced stuff like heightmaps, averaging normals, tesselation etc.
I come from an object-oriented background, so I'm trying to put everything we do into reusable classes. I've had good succ... | The most practical approach seems to be to ignore most of OpenGL functionality that is not directly applicable (or is slow, or not hardware accelerated, or is a no longer a good match for the hardware).
OOP or not, to render some scene those are various types and entities that you usually have:
**Geometry** (meshes).... | **Object transformations**
Avoid depending on OpenGL to do your transformations. Often, tutorials teach you how to play with the transformation matrix stack. I would not recommend using this approach since you may need some matrix later that will only be accessible through this stack, and using it is very long since t... | What are some best practices for OpenGL coding (esp. w.r.t. object orientation)? | [
"",
"c++",
"opengl",
"oop",
""
] |
Whilst refactoring some code I came across some getter methods that returns a std::string. Something like this for example:
```
class foo
{
private:
std::string name_;
public:
std::string name()
{
return name_;
}
};
```
Surely the getter would be better returning a `const std::string&`? The cu... | The only way this can cause a problem is if the caller stores the reference, rather than copy the string, and tries to use it after the object is destroyed. Like this:
```
foo *pFoo = new foo;
const std::string &myName = pFoo->getName();
delete pFoo;
cout << myName; // error! dangling reference
```
However, since yo... | Actually, another issue **specifically** with returning a string *not* by reference, is the fact that `std::string` provides access via pointer to an internal `const char*` via the [c\_str()](http://www.cplusplus.com/reference/string/string/c_str/) method. This has caused me many hours of debugging headache. For instan... | Returning a const reference to an object instead of a copy | [
"",
"c++",
"constants",
""
] |
I truly love VIM - it's one of only a handful of applications I've every come across that make you feel warm and fuzzy inside. However, for PHP development, I still use PDT Eclipse although I would love to switch.
The reason I can't quite at the moment is the CTRL+SPACE code-assist functionality that I rely on so much... | Vim has [OmniCompletion](http://vimdoc.sourceforge.net/htmldoc/version7.html#new-omni-completion) built in, you should add this to your .vimrc:
```
filetype plugin on
au FileType php set omnifunc=phpcomplete#CompletePHP
```
In addition I recommend you this plugins:
* [VTreeExplorer](http://www.vim.org/scripts/script... | Code assist it's a new feature of VIM 7
[Ctrl+x] [Ctrl+o] will auto complete your code or open a popup of options
More features of VIM 7 can be found in this [blogpost](http://linuxhelp.blogspot.com/2006/09/visual-walk-through-of-couple-of-new.html)
Btw, I too like vim, but the PDT (and other IDEs) has much more feat... | Converting from Eclipse PDT to Vim | [
"",
"php",
"eclipse",
"vim",
"eclipse-pdt",
""
] |
I am currently having a hardtime understanding and implementing events in C# using delagates. I am used to the Java way of doing things:
1. Define an interface for a listener type which would contain a number of method definitions
2. Define adapter class for that interface to make things easier if I'm not interested i... | You'd create four events, and methods to raise them, along with a new EventArgs-based class to indicate the error:
```
public class ExceptionEventArgs : EventArgs
{
private readonly Exception error;
public ExceptionEventArgs(Exception error)
{
this.error = error;
}
public Error
{
... | You'll have to define a single delegate for that
```
public delegate void ComputerEvent(object sender, ComputerEventArgs e);
```
ComputerEventArgs would be defined like this:
```
public class ComputerEventArgs : EventArgs
{
// TODO wrap in properties
public Computer computer;
public Exception error;
... | C# event handling (compared to Java) | [
"",
"c#",
"event-handling",
"delegates",
""
] |
when i have a many-to.many relation with nhibernate and let nhibernate generate my db schema, it adds an aditional table that contains the primary keys of the related entities.
is it possible to add additional fields to this and access them without having to hassle around with sql manually? | I don't think thats possible. If you are saying that the relation has some state than in essence it is an object in it's own right and should be treated (mapped) as such. | Agree with Jasper. What you are modeling in that case is not a relation but an entity itself, with 1-N and N-1 relations to the other two entities.
It is not that NHibernate cannot handle it, it is that you simply cannot model it. | additional fields in NHibernate many-to-many relation tables | [
"",
"c#",
".net",
"nhibernate",
""
] |
I've used ZenTest and autotest to work on Ruby projects before, and I used to using them for test-driven development a la [this configuration](http://blog.internautdesign.com/2006/11/12/autotest-growl-goodness). I have a project that I'm currently working on in Java, and I was wondering if there is something similar in... | Might I also suggest Infinitest, it is under active development and works with other languages besides Java. I believe it works fine with Scala, but I haven't had much luck using it with Groovy.
It is free for personal use and is being developed by Improving. | I use junit max which is a eclipse plugin written by kent beck | Is there something like ZenTest/Autotest for Java and JUnit | [
"",
"java",
"ruby",
"unit-testing",
"tdd",
"autotest",
""
] |
I find it annoying that I can't clear a list. In this example:
```
a = []
a.append(1)
a.append(2)
a = []
```
The second time I initialize a to a blank list, it creates a new instance of a list, which is in a different place in memory, so I can't use it to reference the first, not to mention it's inefficient.
The on... | You are looking for:
```
del L[:]
``` | I'm not sure why you're worried about the fact that you're referencing a new, empty list in memory instead of the same "pointer".
Your other list is going to be collected sooner or later and one of the big perks about working in a high level, garbage-collected language is that you don't normally need to worry about st... | Clearing a list | [
"",
"python",
"memory-management",
"refactoring",
"list",
""
] |
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 my head around those :) | While I'm not sure about exactly what you want to accomplish, this bit of code worked for me.
```
<select id="mySelect" multiple="multiple">
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
<option value="4">Fourth</option>
</select>
<script type="text/javasc... | No need to use jQuery for this:
```
var foo = document.getElementById('yourSelect');
if (foo)
{
if (foo.selectedIndex != null)
{
foo.selectedIndex = 0;
}
}
``` | Check if option is selected with jQuery, if not select a default | [
"",
"javascript",
"jquery",
"forms",
"dom",
"html-select",
""
] |
I have a server written in Java that runs as a Windows service (thanks to Install4J). I want this service to be able to download the latest version of the JAR file it runs from, and start running the new code. The stitch is that I don't want the Windows service to fully exit.
Ideally, I would accomplish this by a unix... | Here is a complicated, but portable, way.
Split your code into two jars. One very small jar is there just to manage process startup. It creates a ClassLoader that holds the other jar on its classpath.
When you want to load a new version, you terminate all threads running code from the old jar. Null out all references... | As far as I know, there is no way to do this in Java.
I suppose you could work around it by using the Java [`Runtime.exec`](http://java.sun.com/javase/6/docs/api/java/lang/Runtime.html#exec(java.lang.String)) or [`ProcessBuilder`](http://java.sun.com/javase/6/docs/api/java/lang/ProcessBuilder.html)'s start() command (... | How can I replace the current Java process, like a unix-style exec? | [
"",
"java",
"windows-services",
""
] |
Inside a service, what is the best way to determine a special folder path (e.g., "My Documents") for a specific user? `SHGetFolderPath` allows you to pass in a token, so I am assuming there is some way to impersonate the user whose folder you are interested in.
Is there a way to do this based just on a username? If no... | I would mount the user's registry hive and look for the path value. Yes, it's a sub-optimal solution, for all the reasons mentioned (poor forwards compatibility, etc.). However, like many other things in Windows, MS didn't provide an API way to do what you want to do, so it's the best option available.
You can get the... | Please, do not go into the registry to find this information. That location might change in future versions of Windows. Use SHGetFolderPath instead.
<http://msdn.microsoft.com/en-us/library/bb762181(VS.85).aspx>
Edit: It looks like [LogonUser](http://msdn.microsoft.com/en-us/library/aa378184(VS.85).aspx) will provide... | How can I get the path of a Windows "special folder" for a specific user? | [
"",
"c++",
"windows",
"winapi",
"special-folders",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.