Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I'll phrase this in the form of an example to make it more clear.
Say I have a vector of animals and I want to go through the array and see if the elements are either dogs or cats?
```
class Dog: public Animal{/*...*/};
class Cat: public Animal{/*...*/};
int main()
{
vector<Animal*> stuff;
//cramming the dogs and ca... | As others has noted, you should neither use the `typeid`, nor the `dynamic_cast` operator to get the dynamic type of what your pointer points to. virtual functions were created to avoid this kind of nastiness.
Anyway here is what you do if you **really** want to do it (note that dereferencing an iterator will give you... | You can use `dynamic_cast`, as long as the vector contains Animal pointers.
```
vector <Animal *> stuff;
for(int i=0;i<stuff.size();i++) {
Dog *pDog = dynamic_cast <Dog *> (stuff[i]);
if(pDog) {
// do whatever with the dog
}
Cat *pCat = dynamic_cast <Cat *> (stuff[i]);
if(pCat) {
... | C++ class identification question | [
"",
"c++",
"class",
"identification",
""
] |
In Python, the where and when of using string concatenation versus string substitution eludes me. As the string concatenation has seen large boosts in performance, is this (becoming more) a stylistic decision rather than a practical one?
For a concrete example, how should one handle construction of flexible URIs:
```... | Concatenation is (significantly) faster according to my machine. But stylistically, I'm willing to pay the price of substitution if performance is not critical. Well, and if I need formatting, there's no need to even ask the question... there's no option but to use interpolation/templating.
```
>>> import timeit
>>> d... | Don't forget about named substitution:
```
def so_question_uri_namedsub(q_num):
return "%(domain)s%(questions)s/%(q_num)d" % locals()
``` | String concatenation vs. string substitution in Python | [
"",
"python",
"string",
"string-concatenation",
""
] |
I can split editor panes horizontally or vertically, but it does not seem possible to view code in two separate physical windows. I am aware that Idea can open multiple **projects** in separate windows, but I'd like to be able to do this for two files in a **single** project.
One answer suggested unpinning the tab, bu... | Unfortunately there is no way (as of IDEA 8.0.1) to do what you're asking for. As you pointed out, you can split the editor pane but there is always exactly one editor per IDEA project.
UPDATE: As of IDEA 10 (currently the latest is 10.5), the answer is yes, you can :-) | This is now possible in IDEA X. Hopefully you're still an IDEA user and can take advantage of this :) | Can IntelliJ IDEA open more than one editor window for files from the same project? | [
"",
"java",
"ide",
"intellij-idea",
""
] |
In C# if I want to convert a double (1.71472) to an int then I get the answer 2. If I do this in Java using intValue() method, I get 1 as the answer.
Does Java round down on conversions?
Why do the Java API docs have such scant information about their classes i.e.
> Returns the value of the specified
> number as an ... | Java rounds toward zero when narrowing from a floating point to an integer type—and so does C#, when you use the casting conversion. It's `Convert.ToInt32` that rounds:
```
double d = 1.71472;
int x = (int) d; // x = 1
int y = Convert.ToInt32(d); // y = 2
```
Details can be found in the [Java Language Specification](... | Java rounds toward zero when narrowing from a floating point to an integer type.
There's more documentation about the general rules in the [Java Language Specification](http://java.sun.com/docs/books/jls/third_edition/html/conversions.html). Note that while the documentation in `Number` leaves options open for subclas... | Different answer when converting a Double to an Int - Java vs .Net | [
"",
"java",
".net",
"rounding",
""
] |
I was reading the Math.random() javadoc and saw that random is only psuedorandom.
Is there a library (specifically java) that generates random numbers according to random variables like environmental temperature, CPU temperature/voltage, or anything like that? | Check out <http://random.org/>
RANDOM.ORG is a true random number service that generates randomness via atmospheric noise.
The Java library for interfacing with it can be found here:
<http://sourceforge.net/projects/trng-random-org/> | Your question is ambiguous, which is causing the answers to be all over the place.
If you are looking for a Random implementation which relies on the system's source of randomness (as I'm guessing you are), then java.security.SecureRandom does that. The default configuration for the Sun security provider in your java.... | True random generation in Java | [
"",
"java",
"random",
""
] |
I am trying to respond back to a client with a PDF stored in a MSSQL varbinary(MAX) field. The response works on my localhost and a test server over http connection, but does not work on the production server over https connection. I am using just a simple BinaryWrite (code below).
```
byte[] displayFile = Databas... | I just managed to get around this by replacing
```
Response.Clear();
```
with
```
Response.ClearContent();
Response.ClearHeaders();
```
so the whole thing looks like:
```
byte[] downloadBytes = doc.GetData();
Response.ClearContent();
Response.ClearHeaders();
Response.Buffer = true;
Response.ContentType = "applica... | IE 7 has/had a [mime type "issue"](http://support.microsoft.com/kb/945686) with PDF, related to the [convoluted mime type rules](http://msdn.microsoft.com/en-us/library/ms775147.aspx). You may want to verify if the client has that patch.
There's also been sporadic complaints of IE 7 blank pages due to other reasons (s... | C# BinaryWrite over SSL | [
"",
"c#",
".net",
"file",
"binary",
""
] |
I know this specific question has been [asked before](https://stackoverflow.com/questions/185235/jquery-tabs-getting-newly-selected-index), but I am not getting any results using the `bind()` event on the `jQuery UI Tabs` plugin.
I just need the `index` of the newly selected tab to perform an action when the tab is cl... | **For JQuery UI versions before 1.9**: `ui.index` from the `event` is what you want.
**For JQuery UI 1.9 or later**: see the [answer](https://stackoverflow.com/a/12973370/2333214) by Giorgio Luparia, below. | If you need to get the tab index from outside the context of a tabs event, use this:
```
function getSelectedTabIndex() {
return $("#TabList").tabs('option', 'selected');
}
```
Update:
From version 1.9 'selected' is changed to 'active'
```
$("#TabList").tabs('option', 'active')
``` | jQuery UI Tabs - How to Get Currently Selected Tab Index | [
"",
"javascript",
"jquery",
"jquery-ui",
"tabs",
"jquery-ui-tabs",
""
] |
In a project we have text files looking like this:
```
mv A, R3
mv R2, B
mv R1, R3
mv B, R4
add A, R1
add B, R1
add R1, R2
add R3, R3
add R21, X
add R12, Y
mv X, R2
```
I need to replace the strings according to the following, but I am looking
for a more general solution.
```
R1 => R2
R2 => R3
R3 => R1
R12 => R21... | I've actually had to use this sort of algorithm several times in the past two weeks. So here it is the world's second-most verbose language...
```
import java.util.HashMap;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
/*
R1 => R2
R2 => R3
R3 => R1
R12 => R21
R21 => R12
*/
String inputString
... | The perl solution has an advantage of replacing all strings in one shot, sort of "transactionally". If you don't have the same option in Java (and I can't think of a way make it happen), you need to be careful of replacing R1=>R2, then R2=>R3. In that case, both R1 and R2 end up being replaced with R3. | How can I replace strings in a text in Java? | [
"",
"java",
"regex",
"perl",
""
] |
I need a Java library to convert PDFs to TIFF images. The PDFs are faxes, and I will be converting to TIFF so that I can then do barcode recognition on the image. Can anyone recommend a good free open source library for conversion from PDF to TIFF? | Disclaimer: I work for Atalasoft
[We have an SDK that can convert PDF to TIFF](http://www.atalasoft.com/products/dotimage/). The rendering is powered by Foxit software which makes a very powerful and efficient PDF renderer. | I can't recommend any code library, but it's easy to use GhostScript to convert PDF into bitmap formats. I've personally used the script below (which also uses the netpbm utilties) to convert the *first* page of a PDF into a JPEG thumbnail:
```
#!/bin/sh
/opt/local/bin/gs -q -dLastPage=1 -dNOPAUSE -dBATCH -dSAFER -r3... | A good library for converting PDF to TIFF? | [
"",
"java",
"pdf",
"tiff",
""
] |
I'm researching this for a project and I'm wondering what other people are doing to prevent stale CSS and JavaScript files from being served with each new release. I don't want to append a timestamp or something similar which may prevent caching on every request.
I'm working with the Spring 2.5 MVC framework and I'm a... | I add a parameter to the request with the revision number, something like:
```
<script type="text/javascript" src="/path/to/script.js?ver=456"></script>
```
The 'ver' parameter is updated automatically with each build (read from file, which the build updates). This makes sure the scripts are cached only for the curre... | Like @eran-galperin, I use a parameter in the reference to the JS file, but I include a server-generated reference to the file's "last modified" date. @stein-g-strindhaug suggests this approach. It would look something like this:
```
<script type="text/javascript" src="/path/to/script.js?1347486578"></script>
```
The... | What are best practices for preventing stale CSS and JavaScript | [
"",
"javascript",
"css",
"spring-mvc",
"amazon-s3",
""
] |
Both of these appservers are at least in part OSGI based. One (Glassfish) is obviously Java EE while the other isn't. Now I'm at the stage of choosing a platform for a new project and the natural choice is Glassfish v3 Prelude. This does raise the issue of perhaps we should be using S2AP instead.
The question then is ... | Java EE app servers have distributed transaction managers. If that is at all important, then may want to see if SpringSource dm includes such.
It is possible to do XA TX with Spring-Framework, is just that you're left on your own to locate a suitable XA manager and integrate it.
Course XA TX have very much fallen int... | This is an old thread but I thought it would be useful for people coming across this (as I did) to share the recent GlassFish OSGi enhancements, mainly in the area of OSGi Enterprise RFC's : <http://wiki.glassfish.java.net/Wiki.jsp?page=OsgiDashboard>
Of course there's also the @Resource-based injection of OSGi Declar... | Advantages/disadvantages of Glassfish v3 Prelude vs Springsource dm server for Web applications? | [
"",
"java",
"spring",
"jakarta-ee",
"glassfish",
""
] |
DataGridView.CellContentClick is not firing if I mouse click a DataGridViewCheckBoxCell very fast. How can I solve this? I need to know when CheckBox's check state changes | Try handling the `CellMouseUp` event.
You can check which colum the `MouseUp` event occurred in to see if it is your checkbox column.
You can also find out if it is in edit mode and end the edit mode programmatically, which in turn will fire the `CellValueChanged` event.
In the example below, I have a DataGridView... | Regardless of how fast the user clicks in the checkbox cell, the value won't change from true to false or vise versa until they click out of that row, and the DataGridView goes out of edit mode.
What I've done in the past, is set that column to ReadOnly = true. Then, in the CellContentClick event handler, if that colu... | DataGridView.CellContentClick | [
"",
"c#",
"winforms",
""
] |
I am using VMware Workstation 6.5 on Windows Vista x64. I would like to automate some of the VM management tasks. I know that there is a COM API (<http://www.vmware.com/support/developer/vix-api/>) available which I could use directly.
Is there a C# wrapper for this COM API?
Thanks,
Arnie | ArnieZ.
Any COM DLL can be used from .NET. Adding it as reference in visual studio will generate a DLL called
"YourDll.Interop.dll"
This is a .NET -> COM marshaling library, and will do what you need.
You can also generate this from the command line using tlbimp.exe
Of course, you'll have to keep in mind that you ... | There's now a nice library that wraps this up:
<http://www.codeproject.com/KB/library/VMWareTasks.aspx> | Is there a C# wrapper for the VMware VIX API? | [
"",
"c#",
"api",
"vmware",
"wrapper",
"vix",
""
] |
I have a table that represents a series of matches between ids from another table as follows:
```
CREATE TABLE #matches (
asid1 int,
asid2 int
)
insert into #matches values (1,2)
insert into #matches values (1,3)
insert into #matches values (3,1)
insert into #matches values (3,4)
insert into #matches values (7,6)... | It appears that a [Disjoint-set](http://en.wikipedia.org/wiki/Disjoint-set_data_structure) is what you need to solve this. Here is a [listing](http://www.emilstefanov.net/Programming/DisjointSets.aspx) of a C# and C++ implementation. | If this can be done at all within SQL, it's going to be insanely difficult. You should analyze that table in whatever programming language you're using. | linking groups of matches | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I see in a header that I didn't write myself the following:
```
class MonitorObjectString: public MonitorObject {
// some other declarations
friend inline bool operator==(MonitorObjectString& lhs, MonitorObjectString& rhs) { return(lhs.fVal==rhs.fVal); }
```
I can't understand why this method is declared as fri... | ```
friend inline bool operator==(MonitorObjectString& lhs, MonitorObjectString& rhs) {
return(lhs.fVal==rhs.fVal);
}
```
is sometimes called `friend definition`, because it is a friend declaration that also defines the function. It will define the function as a non-member function of the namespace surrounding t... | Grammatically speaking...
The `friend` keyword is still needed to tell the compiler that this function is not a member of a class, **EDIT:** but instead a non-member function that can see the private members of the class.
---
However, this could have been implemented more cleanly like this:
```
/* friend */ inline ... | friend AND inline method, what's the point ? | [
"",
"c++",
"methods",
"inline",
"friend",
""
] |
I am trying to send some data from a LINQ query in C# to an Excel speed sheet using OLE
I have a query like this:
```
Var data = from d in db.{MyTable}
where d.Name = "Test"
select d;
```
I have the Excel OLE object working fine, I just can't figure out how to populate the cells in Excel with t... | Sending individual OLE commands for each Excel cell is very slow so the key is to create an object array like this:
```
int noOfRows = data.Count - 1;
int noOfColumns = mydataclass.GetType().GetProperties().Count() - 1;
Object[noOfRows, noOfColumns] myArray;
```
Sending an object array allows you to send a mixture of... | I assume you are not using OLE in a web scenario, because it will eventually fail.
If you just need raw data, you can dump to a tab-delimited textfile:
var lines = data.Select(d => d.Name + '\t' + d.AnotherProperty + ...); | Populate Excel with data from LINQ to SQL query | [
"",
"c#",
"winforms",
"linq",
"excel",
"ole",
""
] |
I usually do not have difficulty to read JavaScript code but for this one I can’t figure out the logic. The code is from an exploit that has been published 4 days ago. You can find it at [milw0rm](https://web.archive.org/web/20100412164007/http://www.milw0rm.com/exploits/7477).
Here is the code:
```
<html>
<div i... | The shellcode contains some x86 assembly instructions that will do the actual exploit. `spray` creates a long sequence of instructions that will be put in `memory`. Since we can't usually find out the exact location of our shellcode in memory, we put a lot of `nop` instructions before it and jump to somewhere there. Th... | This looks like an exploit of the [recent Internet Explorer bug](http://www.microsoft.com/technet/security/Bulletin/MS08-078.mspx) that Microsoft released the emergency patch for. It uses a flaw in the databinding feature of Microsoft's XML handler, that causes heap memory to be deallocated incorrectly.
Shellcode is m... | How does this milw0rm heap spraying exploit work? | [
"",
"javascript",
"x86",
"exploit",
"assembly",
""
] |
This is also a question that I asked in a comment in one of Miško Hevery's [google talks](http://misko.hevery.com/2008/11/11/clean-code-talks-dependency-injection/) that was dealing with dependency injection but it got buried in the comments.
I wonder how can the factory / builder step of wiring the dependencies toget... | This talk is about Java and dependency injection.
In C++ we try **NOT** to pass RAW pointers around. This is because a RAW pointer have no ownership semantics associated with it. If you have no ownership then we don't know who is responsible for cleaning up the object.
I find that most of the time dependency injectio... | This is interesting, DI in C++ using templates:
<http://adam.younglogic.com/?p=146>
I think the author is making the right moves as to not translate Java DI into C++ too literally. Worth the read. | Dependency injection in C++ | [
"",
"c++",
"unit-testing",
"dependency-injection",
""
] |
Does anyone know a way to find out programatically which physical disk holds a given partition?
Manually, I can find this info using Start->Run->diskmgmt.msc , where I can see that (on my computer) that partitions C: and D: are on disk 1, E: & F: on disk 0.
This is for optimizing some file crunching operations by doin... | You can obtain this information using WMI from System.Management namespace by quering [Win32\_DiskDrive](http://msdn.microsoft.com/en-us/library/aa394132(VS.85).aspx) class.
[Here's](http://msdn.microsoft.com/en-us/library/ms257340(VS.80).aspx) basic info about WMI in .NET. | In addition to Arul's answer, here's a link that shows how to geth the disk<->partition association using WMI from a VBS script: [WMI Tasks: Disks and File Systems](http://msdn.microsoft.com/en-us/library/aa394592.aspx)
-> see the last example on the page.
Edit: Even better, [here's a good article](http://www.c-sharpc... | How to find the disk that holds a given partition in C#? | [
"",
"c#",
"filesystems",
"disk",
""
] |
Assuming a class called `Bar` in a namespace called `foo`, which syntax do you prefer for your source (.cpp/.cc) file?
```
namespace foo {
...
void Bar::SomeMethod()
{
...
}
} // foo
```
or
```
void foo::Bar::SomeMethod()
{
...
}
```
I use namespaces heavily and prefer the first syntax, but when adding cod... | I would decline the first (*edit* : question changed, the first is what i prefer too now). Since it is not clear where Bar refers to from only looking at the function definition. Also, with your first method, slippy errors could show up:
```
namespace bar {
struct foo { void f(); };
}
namespace baz {
struc... | I prefer an option not listed:
```
namespace foo {
void Bar::SomeMethod()
{
...
}
} // foo namespace
```
Unlike option one, this makes it obvious your code belongs in the foo namespace, not merely uses it. Unlike option two, it saves lots of typing. Win-win. | Preferred namespace syntax for source files | [
"",
"c++",
"namespaces",
""
] |
Is there a problem with using `IEnumerable<T>` as a return type?
FxCop complains about returning `List<T>` (it advises returning `Collection<T>` instead).
Well, I've always been guided by a rule "accept the least you can, but return the maximum."
From this point of view, returning `IEnumerable<T>` is a bad thing, but... | This is really a two part question.
1) Is there inherently anything wrong with returning an IEnumerable<T>
No nothing at all. In fact if you are using C# iterators this is the expected behavior. Converting it to a List<T> or another collection class pre-emptively is not a good idea. Doing so is making an assumption o... | No, `IEnumerable<T>` is a *good* thing to return here, since all you are promising is "a sequence of (typed) values". Ideal for LINQ etc, and perfectly usable.
The caller can easily put this data into a list (or whatever) - especially with LINQ (`ToList`, `ToArray`, etc).
This approach allows you to lazily spool back... | IEnumerable<T> as return type | [
"",
"c#",
"collections",
"ienumerable",
"enumeration",
""
] |
Do T-SQL queries in SQL Server support short-circuiting?
For instance, I have a situation where I have two database and I'm comparing data between the two tables to match and copy some info across. In one table, the "ID" field will always have leading zeros (such as "000000001234"), and in the other table, the ID fiel... | SQL Server does **NOT** short circuit where conditions.
it can't since it's a cost based system: [How SQL Server short-circuits WHERE condition evaluation](http://weblogs.sqlteam.com/mladenp/archive/2008/02/25/How-SQL-Server-short-circuits-WHERE-condition-evaluation.aspx) . | You could add a computed column to the table. Then, index the computed column and use that column in the join.
Ex:
```
Alter Table Table1 Add PaddedId As Right('000000000000' + Id, 12)
Create Index idx_WhateverIndexNameYouWant On Table1(PaddedId)
```
Then your query would be...
```
select * from table1 where table1... | SQL Server - Query Short-Circuiting? | [
"",
"sql",
"sql-server",
""
] |
I have been up and down this site and found a lot of info on the Screen class and how to count the number of monitors and such but how do I determine which montitor a form is currently in? | A simpler method than using the bounds is to use the Screen.FromControl() method. This is the same functionality that Windows uses.
```
Screen.FromControl(this)
```
will return the screen object for the screen that contains most of the form that you call it from. | This should do the trick for you:
```
private Screen FindCurrentMonitor(Form form)
{
return Windows.Forms.Screen.FromRectangle(new Rectangle( _
form.Location, form.Size));
}
```
It will return the screen that has the majority of the form in it. Alternativley, you can use
```
return Windows.Forms.Scree... | How do I determine which monitor my winform is in? | [
"",
"c#",
".net",
"winforms",
".net-3.5",
".net-2.0",
""
] |
Is there a reasonable way to access FoxPro databases using LINQ? | One the blessing/curses of .NET is that the answer is rarely "no" to any .NET programming question.
For example, this guy (thanks Sergey and Larry) shows a way to access FoxPro-type DBs with LINQ: <http://blogs.msdn.com/calvin_hsia/archive/2007/11/30/6620133.aspx>
A better question is probably, not can you, but shoul... | I just finished working on implementation.
<http://linqtovfp.codeplex.com/> | LINQ with FoxPro? | [
"",
"c#",
".net",
"linq",
"foxpro",
""
] |
I am inside the IDE and I can run all the unit tests in a file but is there any way to run all test in a project or solution at once? | Right click on the project or solution in the VS solution-explorer and choose 'Run Unit Tests' Or go to the Resharper menu, choose Unit-Testing and choose one of the options from there. | If you learn executing menu commands with Alt-Letters, you can execute many commands fast even if they don't have direct shortcuts. Especially, if shortcuts are two-key combos.
As for **run**ning all tests in solution the command is Alt-**RUN**, i.e. Alt-R for ReSharper menu, U for Unit Testing, and N for all tests in... | ReSharper run all unit tests in a project or solution at once | [
"",
"c#",
"resharper",
""
] |
Is the following possible in SQL Server 2000?
```
CREATE FUNCTION getItemType (@code varchar(18))
RETURNS int
AS
BEGIN
Declare @Type tinyint
Select @Type = case len(@code)
WHEN 12,14,17 THEN 1
WHEN 13,15,18 THEN 2
WHEN 8,10 THEN 3
ELSE 0
END
RETURN (@Type)
END
```
Thanks. | try this:
```
Select @Type =
(select case
WHEN len(@code) IN (12,14,17) THEN 1
WHEN len(@code) IN (13,15,18) THEN 2
WHEN len(@code) IN (8,10) THEN 3
ELSE 0
END)
``` | This should do it:
```
CREATE FUNCTION getItemType(@code VARCHAR(18))
RETURNS INT
AS
BEGIN
RETURN CASE
WHEN LEN(@code) IN (12,14,17) THEN 1
WHEN LEN(@code) IN (13,15,18) THEN 2
WHEN LEN(@code) IN (8,100) THEN 3
ELSE 0
END
END
``` | SQL CASE Statement | [
"",
"sql",
"sql-server",
"sql-server-2000",
"case-statement",
""
] |
I have around 8-9 parameters to pass in a function which returns an array. I would like to know that its better to pass those parameters directly in the function or pass an array instead? Which will be a better way and why? | If I would do anything, then it would be to create an structure that holds all parameters to get nice intellisence and strong names.
```
public struct user
{
public string FirstName;
public string LastName;
public string zilionotherproperties;
public bool SearchByLastNameOnly;
}
public user[] Ge... | Pass them individually, because:
* that is the type-safe way.
* IntelliSense will pick it up in Visual Studio and when you write your calling functions, you will know what's what.
* It is faster to execute that way.
If the parameter really IS the array, though, then pass the array. Example:
For functions which look ... | Regarding Passing Many Parameters | [
"",
"c#",
".net",
"asp.net",
".net-2.0",
""
] |
I was thinking about how to create a program that would only be valid for X period of time, (within a C# app).
What I was thinking was that you would have the current date as a constant inside the program and it would check to see if it is X days older than that. Naturally I do not want to store the date, or the X out... | Precompilation directives are your key here. You could create a constant in your application and have it set when you compile.
Make sure you obfuscate your code, however. Someone could disassemble it easily and tamper with the constant. Another solution is to have your software "phone home" to register itself. That wa... | Check out AssemblyInfo.cs file in the Properties folder in your project:
```
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]... | C# put date into program when compiled | [
"",
"c#",
""
] |
I don't want to discuss the merits of this approach, just if it is possible. I believe the answer to be "no". But maybe someone will surprise me!
Imagine you have a core widget class. It has a method `calculateHeight()`, that returns a height. The height is too big - this result in buttons (say) that are too big. You ... | Perhaps you could use Aspect Oriented Programming to trap calls to that function and return your own version instead?
Spring offers some AOP functionality but there are other libraries that do it as well. | One ugly solution would be to put your own implementation of DefaultWidget (with same FQCN) earlier on the Classpath than the normal implementation. It's a terrible hack, but every other approach that I can think of is even worse. | Is it possible to monkey patch in Java? | [
"",
"java",
"reflection",
"monkeypatching",
""
] |
I have been working on this for the greater part of the day and I cant seem to make this part of my code work. The intent of the code is to allow the user to input a set of values in order to calculate the missing value. As an additional feature I placed a CheckBox on the form to allow the user to do further calculatio... | Without really knowing what the problem is, a few things look a bit odd:
* Also, mixing decimal and int in a calculation can lead to unexpected results unless you really know what you are doing. I suggest using only decimals (or doubles, which are way faster and usually have enough precision for engineering computatio... | Change this:
```
int y, b;
```
To this:
```
int y;
decimal b;
```
and it works, according to this test:
```
public void Test2()
{
int y;
decimal b;
decimal x, z, a;
decimal z1, z2;
x = 480m;
y = 2500;
a = 5.75m;
b = 10;
z1 = ((y * 1000... | C# Math Problem | [
"",
"c#",
"math",
""
] |
Ok here's what I'm trying to do I want to write a class that inherits everything from the class ListItem
```
class RealListItem : ListItem
{
public string anExtraStringINeed;
}
```
For some reason or another .net is treating all the members like they are private when I try to do this so my class is worthless.
I ... | The System.Web.UI.Controls.ListItem class is "sealed"... That means you cannot inherit from it... | As Charles states, ListItem is sealed which means you can't inherit from it. In the framework, some classes are marked as sealed and others are not. (The ones that aren't sealed you can inherit.)
You could create your own ListItem that contains a System.Web.UI.WebControls.ListItem, but I don't think this will actually... | Inheriting a .net class | [
"",
"c#",
".net",
"asp.net",
""
] |
I was just browsing a forum and someone asked about a PHP file they had found on the web. It has several spots like this in the code:
`if ($REMOTE_ADDR == "") $ip = "no ip";
else $ip = getHostByAddr($REMOTE_ADDR);`
I have always thought brackets are needed to enclose what you want to do if the condition is true. Is t... | you can do if else statements like this:
```
<?php
if ($something) {
echo 'one conditional line of code';
echo 'another conditional line of code';
}
if ($something) echo 'one conditional line of code';
if ($something)
echo 'one conditional line of code';
echo 'a NON-conditional line of code'; // this line get... | To go into a little more detail, the reason that the braces are optional is that the syntax looks like:
```
if(CONDITION) BLOCK
[elseif(CONDITION) BLOCK]
[else BLOCK]
```
BLOCK can be a single statement:
```
foo();
```
or it can be a brace-enclosed group of statements:
```
{
foo();
bar();
}
``` | PHP conditionals, brackets needed? | [
"",
"php",
"brackets",
"conditional-statements",
""
] |
Since PHP is a dynamic language what's the best way of checking to see if a provided field is empty?
I want to ensure that:
1. null is considered an empty string
2. a white space only string is considered empty
3. that "0" is not considered empty
This is what I've got so far:
```
$question = trim($_POST['question']... | A literal answer to the question from the post title is quite obvious and straightforward:
```
function IsNullOrEmptyString($str){
return ($str === null || trim($str) === '');
}
```
But for *input variables,* which you're actually asking about, it would be both superfluous and insufficient.
A `$_POST` array elem... | Old post but someone might need it as I did ;)
```
if (strlen($str) == 0){
do what ever
}
```
replace `$str` with your variable.
`NULL` and `""` both return 0 when using `strlen`. | Better way to check variable for null or empty string? | [
"",
"php",
"validation",
""
] |
Simple question; what's better and why?
```
out.resize( in.size() );
T1::iterator outit = out.begin();
for( inIt = in.begin() to end, ++inIt, ++outIt )
*outit = *inIt
OR
out.erase();
for( inIt = in.begin() to end, ++inIt )
out.push_back( inIt );
```
I'm assuming the memory assignme... | The second, and if you're concerned about multiple extensions use out.reserve(). The right answer to adding to a vector is almost always push\_back or back\_inserter, which avoid some possible problems (exception guarantees, constructors, writing past the end, for example) that you'd have to pay attention to with other... | The second one, as long as you reserve the right capacity first.
One problem I see (apart from style) is that in the first one, if your copy assignment throws, you have taken an operation that should give you the strong guarantee, and used it to give no guarantee. | Looped push_back against resize() + iterator | [
"",
"c++",
"stl",
""
] |
If you started a new Java EE project today which is to be finished in about a year, which application server would you choose and why?
Part of your answer should include your arguments for your decision. And also how much experience you have with the Java EE server you choose and with the other available servers on th... | I have used WebLogic, WebSphere, JBoss, GlassFish, Resin, Jetty, Tomcat, and a few others over the last 10+ years. So, if I were considering a new project, I would ask myself a few questions first. One thing that I would not question anymore is that I would flat refuse to use JSPs unless I was tortured until I cried fo... | The term "application server" is ambiguous. With GlassFish v3, you can start small with, say, a traditional web container and evolve (using OSGi and simple "add container" functionality) to add anything you'd like : JPA, JAX-RS, EJB's, JTA, JMS, ESB, etc... Yet it's the same product, same admin interface, etc. Does thi... | Would you, at present date, use JBoss or Glassfish (or another) as Java EE server for a new project? | [
"",
"java",
"jboss",
"jakarta-ee",
"glassfish",
""
] |
Is there a simple way to **set the focus** (input cursor) of a web page **on the first input element** (textbox, dropdownlist, ...) on loading the page without having to know the id of the element?
I would like to implement it as a common script for all my pages/forms of my web application. | You can also try jQuery based method:
```
$(document).ready(function() {
$('form:first *:input[type!=hidden]:first').focus();
});
``` | Although this doesn't answer the question (requiring a common script), I though it might be useful for others to know that HTML5 introduces the 'autofocus' attribute:
```
<form>
<input type="text" name="username" autofocus>
<input type="password" name="password">
<input type="submit" value="Login">
</form>
```
... | How do I set the focus to the first input element in an HTML form independent from the id? | [
"",
"javascript",
"html",
"forms",
"focus",
""
] |
I have at my SQL Server 2000 Database a column with type **Image**. How can I map it into NHibernate? | We used BinaryBlob on the mapping config file, and byte[] on the property. | Below is the sample code that i have used to map an image field. Where BlogImage was a column of Image Datatype mapped to byte type property BlogImage. length="2147483647" was used to ensure copy of full image in to database as nhibernate some times limit the max size of data that is going to be inserted.
```
<?xml ve... | How to map Image type in NHibernate? | [
"",
"c#",
"sql-server",
"nhibernate",
""
] |
I'm looking for a good plugin for doing web front end work in Eclipse. I don't want something that completely takes over eclipse, or something that has masses of dependencies that need to be updated all the time, or something that is geared towards a particular server-side platform, or something that costs a heap.
Is ... | Personally, I use the standalone community version of Aptana for that sort of thing, as I don't really use Eclipse for anything much else these days.
There is an Eclipse plugin version of Aptana, info available here: <http://www.aptana.com/docs/index.php/Plugging_Aptana_into_an_existing_Eclipse_configuration>
Update:... | This is a very old initial question but since it's still very visible in Google I thought I'd update the answer for 2018 for anyone who happens to be wondering the same. Right now, the best editor for all the web languages is [CodeMix](https://www.genuitec.com/products/codemix/codemix-journey/). You can read about it a... | What CSS/JS/HTML/XML plugin(s) do you use in Eclipse? | [
"",
"javascript",
"html",
"css",
"eclipse",
""
] |
**Is there a tool that will take you java beans (pojos) and automatically make them a form for a webpage?**
To be more clear I have a bunch of Jaxb objects that I want to be able to display in a form without having to code a bunch of html. Is there a tool that will read the jaxb objects and generate the editable form ... | Have a look at [Grails](http://grails.org), in particular [Scaffolding](http://grails.org/Scaffolding). It's a Groovy framework, but your POJOs will plug straight in. | If I interpret your question quite literally, then you should take a look at the ROMA framework: <http://www.romaframework.org/>. It tries to take POJOs (beans) which are annotated and automatically generate user interfaces. | Is there a tool to generate web pages based on Java beans? | [
"",
"java",
"web-applications",
"javabeans",
"pojo",
""
] |
The log file from a JVM crash contains all sorts of useful information for debugging, such as shared libraries loaded and the complete environment. Can I force the JVM to generate one of these programmatically; either by executing code that crashes it or some other way? Or alternatively access the same information anot... | You can try throwing an OutOfMemoryError and adding the -XX:+HeapDumpOnOutOfMemoryError jvm argument. This is new as of 1.6 as are the other tools suggested by McDowell.
<http://blogs.oracle.com/watt/resource/jvm-options-list.html> | Have a look at the [JDK Development Tools](http://java.sun.com/javase/6/docs/technotes/tools/), in particular the [Troubleshooting Tools](http://java.sun.com/javase/6/docs/technotes/tools/#troubleshoot) for dumping the heap, printing config info, etcetera. | Can I force generation of a JVM crash log file? | [
"",
"java",
"jvm",
"crash",
""
] |
When I try to create a Excel or Word workbook project in VS, I get the message:
> A compatible version of Microsoft
> Office is not installed on this
> computer. You must install the
> version of Office that is compatible
> with your project. In addition,
> repair the version of the Visual
> Studio Tools for Office ru... | The following steps worked:
1) Unistall Office Pro, reboot and reinstall.
2) Repair VS 2008 from disk. | Office 2k3 Standard is not compatible with VSTO; upgrading from 2k3 standard has likely left something in your registry.
[This thread](http://social.msdn.microsoft.com/Forums/en-US/vsto/thread/3f12200d-f685-4bc9-bff0-d380067f515a) suggests that even moving to 2k7 doesn't give compatibility in this case! How about crea... | VSTO: Can't create workbooks | [
"",
"c#",
".net",
"visual-studio",
"vsto",
""
] |
I [this post](https://stackoverflow.com/questions/381164), I've seen this:
```
class MonitorObjectString: public MonitorObject {
// some other declarations
friend inline bool operator==(/*const*/ MonitorObjectString& lhs,
/*const*/ MonitorObjectString& rhs)
{ return lhs.fV... | Perhaps the classes use a form of lazy initialization. When the data is accessed, proper initialization must occur, and the data must be fetched. This may change class members.
However, lazy initialization can be formed so that modification to the class isn't necessary. This can be accomplished by using the [Pimpl idi... | Most likely they forgot the `const`.
Operator overloads *should* behave consistently and not perform 'out of character' actions.
As a general rule, an equality operator should never modify any of the objects it is comparing. Declaring `const` enforces this at the compiler level. However, it is often left out. "Const c... | An operator == whose parameters are non-const references | [
"",
"c++",
"operators",
"constants",
"equals-operator",
""
] |
Is there an openID implementation in Java? I would like to use this in a tomcat application. | The [openid4java](https://github.com/jbufu/openid4java) library seems to be the most popular. | The only one I have looked into is [OpenID4Java](http://code.sxip.com/openid4java/) by there is are more options listed on at <http://wiki.openid.net/Libraries>.
I recommend looking at [Using OpenID](http://www.theserverside.com/tt/articles/article.tss?l=OpenID) on [TheServerSide.COM](http://www.theserverside.com) for... | Is there an openID implementation in Java? | [
"",
"java",
"jsp",
"tomcat",
"openid",
""
] |
I'm so sick of the pass-callback-data-as-void\*-struct anti-pattern. Boost bind solves it nicely, but is an unacceptable dependency. What's a lightweight alternative? How would I write it myself as simply as possible? | I'm not familiar with boost:bind, but is it something like this?
```
#include <iostream>
void foo (int const& x) {
std::cout << "x = " << x << std::endl;
}
void bar (std::string const& s) {
std::cout << "s = " << s << std::endl;
}
template<class T>
void relay (void (*f)(T const&), T const& a) {
f(a);
}
... | First, I question your assertion that it's far too heavy for you to use.
Second, roll your own template, if you need to control the behavior.
Third, if you're afraid of rolling your own template, I question your ability to judge that `boost::bind` is too heavy for you to use. | lightweight boost::bind | [
"",
"c++",
"function",
"boost",
"binders",
""
] |
I've used the [`setargv.obj` linking for expanding wildcard arguments](http://msdn.microsoft.com/en-us/library/8bch7bkk.aspx) in the past for a number of C and C++ applications, but I can't find any similar mention for .NET applications.
Is there a standard way to have your application's command line parameters automa... | Your code looks like exactly how you're supposed to do it. | Here is my rough hack. I'd love for it to be recursive. And having experienced the shortcoming of Windows wildcards, I might decide to use regular expressions rather than letting GetFiles() do it for me.
```
using System.IO;
public static string[] ExpandFilePaths(string[] args)
{
var fileList = new List<string>()... | Is there a wildcard expansion option for .NET applications? | [
"",
"c#",
".net",
"vb.net",
"wildcard",
""
] |
I have a sqlite (v3) table with this column definition:
```
"timestamp" DATETIME DEFAULT CURRENT_TIMESTAMP
```
The server that this database lives on is in the CST time zone. When I insert into my table without including the timestamp column, sqlite automatically populates that field with the current timestamp in GMT... | I found on the sqlite documentation (<https://www.sqlite.org/lang_datefunc.html>) this text:
> Compute the date and time given a unix
> timestamp 1092941466, and compensate
> for your local timezone.
```
SELECT datetime(1092941466, 'unixepoch', 'localtime');
```
That didn't look like it fit my needs, so I tried chan... | simply use local time as the default:
```
CREATE TABLE whatever(
....
timestamp DATE DEFAULT (datetime('now','localtime')),
...
);
``` | Sqlite: CURRENT_TIMESTAMP is in GMT, not the timezone of the machine | [
"",
"sql",
"sqlite",
"timezone",
"timestamp",
""
] |
I have a webservice in java that receives a list of information to be inserted or updated in a database. I don't know which one is to insert or update.
Which one is the best approach to abtain better performance results:
1. Iterate over the list(a object list, with the table pk on it), try to insert the entry on Data... | If your database supports MERGE, I would have thought that was most efficient (and treats all the data as a single set).
See:
<http://www.oracle.com/technology/products/oracle9i/daily/Aug24.html>
<https://web.archive.org/web/1/http://blogs.techrepublic%2ecom%2ecom/datacenter/?p=194> | If performance is your goal then first get rid of the word iterate from your vocabulary! learn to do things in sets.
If you need to update or insert, always do the update first. Otherwise it is easy to find yourself updating the record you just inserted by accident. If you are doing this it helps to have an identifier... | Insert fail then update OR Load and then decide if insert or update | [
"",
"java",
"database",
"performance",
""
] |
I'm currently building a Spring MVC application. I was looking to use JSP pages with tag libraries for handling the view layer and formatting of the HTML, but I've come across another group in my company that uses Velocity templates for the same purpose.
From what I can see, it seems to me as if there are a lot of sim... | I would prefer to use Velocity just because using JSP+JSTL can allow lazy/sloppy developers to get into trouble by adding scriptlets. There should be no reason to have java code in your view tier. It doesn't take much to understand Velocity and as a matter of fact I just picked it up in about two weeks. While I don't l... | I actually slightly prefer Freemarker to Velocity, just in case you're open to exploring other options. Comparison here:
<http://freemarker.org/fmVsVel.html>
I agree with Ben's statements about enforcing a simple view by avoiding JSP and the possibility of scriptlets. I also like the ability to render a Freemarker or... | Benefits of using JSTL vs Velocity for view layer in MVC app? | [
"",
"java",
"spring",
"jsp",
"spring-mvc",
"velocity",
""
] |
**UPDATE**
I have combined various answers from here into a 'definitive' answer on a [new question](https://stackoverflow.com/questions/1747235/weak-event-handler-model-for-use-with-lambdas/1747236#1747236).
**Original question**
In my code I have an event publisher, which exists for the whole lifetime of the applic... | I know that this question is ancient, but hell - I found it, and I figure that others might as well. I'm trying to resolve a related issue, and might have some insight.
You mentioned Dustin Campbell's WeakEventHandler - it indeed cannot work with anonymous methods by design. I was trying to fiddle something together t... | If you retain a reference to the anonymous delegate and then remove it when the controls are removed from the form that should allow both the controls and the anonymous delegates to be garbage collected.
So something like this:
```
public static class Linker
{
//(Non-lambda version, I'm not comfortable with lamb... | Garbage collection when using anonymous delegates for event handling | [
"",
"c#",
"event-handling",
"garbage-collection",
""
] |
C#: How do you tell which item index is selected in ListView? | ```
ListView mylistv = new ListView();
var index = mylistv.SelectedIndices();
```
That should do it. | Have you tried SelectedIndices?
```
myListView.SelectedIndices
``` | C#: How do you tell which item index is selected in ListView? | [
"",
"c#",
""
] |
I'm looking for something like `alert()`, but that doesn't "pause" the script.
I want to display an alert and allow the next command, a form `submit()`, to continue. So the page will be changing after the alert is displayed, but it won't wait till the user has clicked OK.
Is there something like this or is it just on... | You could do the alert in a setTimeout (which a very short timeout) as setTimeout is asynchronous:
```
setTimeout("alert('hello world');", 1);
```
Or to do it properly you really show use a method rather than a string into your setTimeout:
```
setTimeout(function() { alert('hello world'); }, 1);
```
Otherwise you o... | If already using JQuery <http://docs.jquery.com/UI/Dialog> is simple to use and styles nicely. | Is there a JavaScript alert that doesn't pause the script? | [
"",
"javascript",
""
] |
I'm working on a legacy application that has a C++ extended stored procedure. This xsproc uses ODBC to connect to the database, which means it requires a DSN to be configured.
I'm updating the installer (created using Visual Studio 2008 setup project), and want to have a custom action that can create the ODBC DSN entr... | I actually solved this myself in the end by manipulating the registry. I've created a class to contain the functionality, the contents of which I've included here:
```
///<summary>
/// Class to assist with creation and removal of ODBC DSN entries
///</summary>
public static class ODBCManager
{
private const string... | Further to [chrfalch's post](https://stackoverflow.com/questions/334939/how-do-i-create-an-odbc-dsn-entry-using-c/2336287#2336287), here is some sample code for updating a DSN (I know the OP is asking for creation, however this code is easily translatable to whatever you need to do) using the API call rather than via t... | How do I create an ODBC DSN entry using C#? | [
"",
"c#",
"odbc",
""
] |
By default C# compares DateTime objects to the 100ns tick. However, my database returns DateTime values to the nearest millisecond. What's the best way to compare two DateTime objects in C# using a specified tolerance?
Edit: I'm dealing with a truncation issue, not a rounding issue. As Joe points out below, a rounding... | I usally use the TimeSpan.FromXXX methods to do something like this:
```
if((myDate - myOtherDate) > TimeSpan.FromSeconds(10))
{
//Do something here
}
``` | How about an extension method for DateTime to make a bit of a fluent interface (those are all the rage right?)
```
public static class DateTimeTolerance
{
private static TimeSpan _defaultTolerance = TimeSpan.FromSeconds(10);
public static void SetDefault(TimeSpan tolerance)
{
_defaultTolerance = to... | How do you compare DateTime objects using a specified tolerance in C#? | [
"",
"c#",
"datetime",
"comparison",
"resolution",
""
] |
I am using C# .Net 2.0 to write a webservices client. The server's soap implementation is tested and is pretty solid. gSoap/C++ applications had no problem reading the responses. However the .Net implementation complains "There is an error in XML document" while calling one of the methods. Similar responses recieved fr... | First of all I'd grab a snapshot of the failing XML in the Deserialise stage to try and diagnose the problem.
You can hook your soap extension into your client app without recompiling. Just add:
```
<webServices>
<soapExtensionTypes>
<add type="DebugTools.SOAP.SOAPTrace.SoapTraceExtension, DebugTools.SOAP... | If you would like to step through the serialise/deserialise code, you can use a tool called SGen. This comes with VS in the SDK, and is used as follows:
1. Compile the app using the normal VS-generated (or wsdl.exe generated) proxy classes (These are usually hidden and are in a file called Reference.cs
2. Drop to the ... | XML Parse error while processing the SOAP response | [
"",
"c#",
"vb.net",
"web-services",
""
] |
We have a lot of unit tests but they aren't run every night. I have setup some batch files that compile all the code from the SVN repository and I would like to run NUnit. This is not a big problem because I can call it from the batch file after the compilation BUT the output is stored in the network drive and I need t... | We have recently started using TeamCity with our projects, and so far it seems great. We are using it with Subversion and NUnit, aswell as running an external program which makes the final install file of the application. The projects and build configurations are really easy to set up. | Sounds like you need a build server. See [Cruise Control .Net](http://sourceforge.net/projects/ccnet/) | NUnit with night build, how to get errors easily? | [
"",
"c#",
".net",
"unit-testing",
"automation",
""
] |
I have some Python code that works correctly when I use python.exe to run it, but fails if I use pythonw.exe.
```
def runStuff(commandLine):
outputFileName = 'somefile.txt'
outputFile = open(outputFileName, "w")
try:
result = subprocess.call(commandLine, shell=True, stdout=outp... | `sys.stdin` and `sys.stdout` handles are invalid because pythonw does not provide console support as it runs as a deamon, so default arguments of `subprocess.call()` are failing.
Deamon programs close stdin/stdout/stderr purposedly and use logging instead, so that you have to manage this yourself: I would suggest to u... | For the record, my code now looks like this:
```
def runStuff(commandLine):
outputFileName = 'somefile.txt'
outputFile = open(outputFileName, "w")
if guiMode:
result = subprocess.call(commandLine, shell=True, stdout=outputFile, stderr=subprocess.STDOUT)
else:
proc = subprocess.Popen(co... | Python subprocess.call() fails when using pythonw.exe | [
"",
"python",
"multithreading",
"subprocess",
""
] |
Using instance methods as callbacks for event handlers changes the scope of `this` from *"My instance"* to *"Whatever just called the callback"*. So my code looks like this
```
function MyObject() {
this.doSomething = function() {
...
}
var self = this
$('#foobar').bind('click', function(){
self.doSom... | This question is not specific to jQuery, but specific to JavaScript in general. The core problem is how to "channel" a variable in embedded functions. This is the example:
```
var abc = 1; // we want to use this variable in embedded functions
function xyz(){
console.log(abc); // it is available here!
function qwe... | Yeah, this appears to be a common standard. Some coders use self, others use me. It's used as a reference back to the "real" object as opposed to the event.
It's something that took me a little while to really get, it does look odd at first.
I usually do this right at the top of my object (excuse my demo code - it's ... | var self = this? | [
"",
"javascript",
"jquery",
"scope",
"closures",
""
] |
I'm just wondering if there is a quick way to echo undefined variables without getting a warning? (I can change error reporting level but I don't want to.) The smallest I have so far is:
`isset($variable)?$variable:''`
I dislike this for a few reasons:
* It's a bit "wordy" and complex
* `$variable` is repeated
* The... | you could use the ifsetor() example taken from [here](http://wiki.php.net/rfc/ifsetor):
```
function ifsetor(&$variable, $default = null) {
if (isset($variable)) {
$tmp = $variable;
} else {
$tmp = $default;
}
return $tmp;
}
```
for example:
```
echo ifsetor($variable);
echo ifsetor($... | You can run it with the [error suppression operator](http://www.php.net/operators.errorcontrol) @.
```
echo @$variable;
```
However, it's best not to ignore unset variables. Unset variables could indicate a logical error on the script, and it's best to ensure all variables are set before use. | PHP: printing undefined variables without warning | [
"",
"php",
"variables",
"warnings",
"undefined",
""
] |
I`m developing an application using Spring WebFlow 2, Facelets and JSF. One of my flows does have a page that must trigger a form submit at certain events. For each different action, a different view must be presented. So, I'm trying to activate the following javascript code to perform the submission:
```
function myF... | I've got the solution in the Spring WebFlow forum. According to Jeremy Grelle, the submission of "\_eventId" parameter does not trigger transitions when integrating Spring WebFlow to JSF. The solution he gave was to create a JSF PhaseListener that creates a JSF action when an "\_eventId" parameter is sent.
The phaseLi... | Don't know anything about SringFaceletsSF, but I think that event handler should probably return `true`. Otherwise your browser will not submit the form.
so:
```
function myFormSubmit( eventId ) {
var formAction = document.myForm.action;
document.myForm.action = formAction + '&_eventId=' + eventId;
document.... | Javascript form submission to activate Spring Web Flow transitions with JSF integration | [
"",
"javascript",
"jsf",
"facelets",
"spring-webflow",
""
] |
I'm just playing around and I'm trying to grab information from websites. Unfortunately, with the following code:
```
import sys
import socket
import re
from urlparse import urlsplit
url = urlsplit(sys.argv[1])
sock = socket.socket()
sock.connect((url[0] + '://' + url[1],80))
path = url[2]
if not path:
path = '... | Please please please please please please please don't do this.
urllib and urllib2 are your friends.
Read [the "missing" urllib2 manual](http://www.voidspace.org.uk/python/articles/urllib2.shtml) if you are having trouble with it. | > ```
> sock.connect((url[0] + '://' + url[1],80))
> ```
Do not do that, instead do this:
```
sock.connect((url[1], 80))
```
`connect` expects a hostname, not a URL.
Actually, you should probably use something higher-level than sockets to do HTTP. Maybe [httplib](http://docs.python.org/library/httplib.html). | (Python) socket.gaierror on every addres...except http://www.reddit.com? | [
"",
"python",
"http",
"sockets",
""
] |
I love to Extend my Assert.AreEqual to many different classes, the known one is the CollectionAssert of course, but I can think of some more such as: [ImageAssert](http://www.human-debugger.net/blog/2008/12/21/TddExtendingAssertToSupportImages.aspx), XmlAssert etc..
Did you Create your own Assert classes? and what kin... | I've just added an implementation to [ImageAssert](https://web.archive.org/web/20131031051646/http://human-debugger.net/wp-blog/2008/12/21/tdd-extending-assert-to-support-images/) as I wrote above (in my question)
I would be glad to hear more of that kind of samples
```
[TestMethod]
public void CompareImagesSize()
{
... | That's my solution:
```
using MyStuff;
using A = Microsoft.VisualStudio.TestTools.UnitTesting.Assert;
namespace Mytestproj.Tests
{
public static class Assert
{
public static void AreEqual(object expected, object actual)
{
A.AreEqual(expected, actual);
}
// my exte... | How did you extend your Assert class | [
"",
"c#",
"unit-testing",
"tdd",
"assertions",
""
] |
I'm just wondering how other developers tackle this issue of getting 2 or 3 answers from a method.
1) return a object[]
2) return a custom class
3) use an out or ref keyword on multiple variables
4) write or borrow (F#) a simple Tuple<> generic class
<http://slideguitarist.blogspot.com/2008/02/whats-f-tuple.ht... | Your question points to the possibility that you'll be returning more data in the future, so I would recommend implementing your own class to contain the data.
What this means is that your method signature will remain the same even if the inner representation of the object you're passing around changes to accommodate ... | It entirely depends on what the results are. If they are related to one another, I'd usually create a custom class.
If they're not really related, I'd either use an out parameter or split the method up. If a method wants to return three unrelated items, it's probably doing too much. The exception to this is when you'r... | C# Syntax - Your preferred practice for getting 2 or 3 answers from a method | [
"",
"c#",
".net",
"syntax",
"parameters",
"tuples",
""
] |
I'm not really sure how to title this question but basically I have an interface like this:
```
public interface IFoo
{
string ToCMD();
}
```
a couple of absract classes which implement IFoo like:
```
public abstract class Foo : IFoo
{
public abstract string ToCMD();
}
public abstract class Bar : IFoo
{
... | The need for an inheritance chain is questionable, in general.
However the specific scenario of combining an abstract base class with an interface.. I see it this way:
If you have an abstract base class like this, you should also have a corresponding interface. If you have an interface, then use the abstract base cla... | you need the interface; you may or may not need the abstract class.
in general, if you can provide some useful behavior in a base class, then provide a base class; if the base class is not complete by itself then make it abstract (MustInherit in VB parlance)
otherwise, the interface is sufficient | Inheritance design using Interface + abstract class. Good practice? | [
"",
"c#",
"oop",
"inheritance",
""
] |
Working to get DateTimes for any time zone.
I'm using DateTimeOffset, and a string, and an XmlElement attribute. When I do, I get the following error:
> [InvalidOperationException: 'dateTime'
> is an invalid value for the
> XmlElementAttribute.DataType property.
> dateTime cannot be converted to
> System.String.]
> ... | Take a look at this StackOverflow question about serializing dates and UTC:
[Best practices for DateTime serialization in .Net framework 3.5/SQL Server 2008](https://stackoverflow.com/questions/65164/best-practices-for-datetime-serialization-in-net-framework-35sql-server-2008)
No need to create a special property jus... | This is what worked for me
```
private const string DateTimeOffsetFormatString = "yyyy-MM-ddTHH:mm:sszzz";
private DateTimeOffset eventTimeField;
[System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified, Order = 0)]
public string eventTime
{
get { return eventTimeField.ToSt... | How to serialize to dateTime | [
"",
"c#",
"datetime",
".net-2.0",
"xml-serialization",
""
] |
In PHP, is there an easy way to convert a number to a word? For instance, *27* to *twenty-seven*. | I [found](http://bloople.net/num2text/cnumlib.txt) some (2007/2008) source-code online and as it is copyright but I can use it freely and modify it however I want, so I place it here and re-license under CC-Wiki:
```
<?php
/**
* English Number Converter - Collection of PHP functions to convert a number
* ... | Alternatively, you can use the NumberFormatter class from [`intl`](http://www.php.net/manual/en/intl.setup.php) package in PHP . Here's a sample code to get you started (for commandline):
```
<?php
if ($argc < 3)
{
echo "usage: php {$argv[0]} lang-tag number ...\n";
exit;
}
array_shift($argv);
$lang_... | Is there an easy way to convert a number to a word in PHP? | [
"",
"php",
"numbers",
""
] |
I'm writing a unit test for a method that packs boolean values into a byte. The various bit locations are determined by the value of an enum, which only has 5 values right now, but it's conceivable (though extremely unlikely) that this number could go to 9.
I'd like a simple test along the lines of:
private byte m\_m... | I think this test does what you want. It is probably a waste of your time to get more generic than this.
```
public void testEnumSizeLessThanOneByte() throws Exception
{
assertTrue("MyEnum must have 8 or less values.",
MyEnum.values().length <= 8);
}
``` | if this is a real concern and performance isn't that important you could always use a [bitset](http://java.sun.com/j2se/1.4.2/docs/api/java/util/BitSet.html) | Programatically calculate the size of a value type | [
"",
"java",
"unit-testing",
"sizeof",
"bitmask",
"memory-size",
""
] |
I have a class that inherits QTreeWidget. How can I find the currently selected row?
Usually I connect signals to slots this way:
```
connect(myButton, SIGNAL(triggered(bool)), this, SLOT(myClick()));
```
However, I can't find anything similar for `QTreeWidget->QTreeWidgetItem`.
The only way I found is to redefine th... | Using the itemClicked() signal will miss any selection changes made using the keyboard. I'm assuming that's a bad thing in your case. | Dusty is almost correct. But the itemSelectionChanged signal will not tell you which item is selected.
```
QList<QTreeWidgetItem *> QTreeWidget::selectedItems() const
```
will give you the selected item(s).
So, connect a slot to the itemSelectionChanged signal, then call selectedItems() on the tree widget to get the... | How can I find the selected item in a QTreeWidget? | [
"",
"c++",
"qt",
"events",
"kde-plasma",
"treewidget",
""
] |
Having fallen behind in the world of ORM and modern data access, I'm looking to move away from DataSets (*shudder*) and into a proper mapping framework.
I've just about got my head around Linq to SQL, an I'm now looking into NHibernate with the view to using it in our next project.
With old school sql and data sets, ... | A quick answer is that the ORM will check the property name and will transform it to a SQL query that will do you name = .... So it won't load all the customers into the memory to search for the name. | Nhibernate comes with a couple of different ways to query the database.
Hibernate uses a Sql like syntax called HQL, which is SQL on objects. Also it can do a search by example, where you create an object and fill in the critea you want, then hibernate will pull the object out of the DB which have the same property val... | NHibernate efficiency | [
"",
"c#",
"performance",
"nhibernate",
""
] |
Hello all you helpful folks @ stackoverflow!
Best resources for Java GUI's?
Looking at the Java Documentation, it is pretty easy to figure out the basics of JButtons, JFrames, etc but grasping the concepts of accessing JComponents from a frame, what creating a different panel does, etc is not very easy to understand.... | Hmm... Have you seen the [The Swing tutorial](http://java.sun.com/docs/books/tutorial/uiswing/index.html)? | Once you've finished the [Swing Tutorial](http://java.sun.com/docs/books/tutorial/uiswing/index.html), you should have a look at [Java Swing](http://books.google.com/books?id=cPxGfk-FZNUC&dq=java+swing&pg=PP1&ots=gFtz5Zntal&source=bn&sig=hKGpY7QtUTZrNjav41bPRuN4VcI&hl=en&sa=X&oi=book_result&resnum=4&ct=result). It's a ... | Java GUI - General | [
"",
"java",
"user-interface",
"jbutton",
""
] |
I am having a problem setting the Authorize attribute Role value from a variable. The error message says it requires a const variable. When I create a const type variable it works fine but I am trying to load the value from the Web.Config file or anything else that will allow the end user to set this. I'm using integra... | You can use `User.InRole( "RoleName" )` within a controller.
**EDIT: The code below will not work since GetCustomAttributes() apparently returns a copy of each attribute instead of a reference to the actual attribute. Left as answer to provide context for other answers.**
As far as setting it in the authorize attribu... | I have a class called StringResources that provides access to static string values. I ran into the same snag and solved the problem in the following manner. I inherited from the AuthorizeAttribute class and added a method override for the AuthorizeCore method. The functionality of the method had a call to IsInRole() an... | ASP.NET MVC: Problem setting the Authorize attribute Role from a variable, requires const | [
"",
"c#",
"asp.net-mvc",
"authorization",
""
] |
I discovered to have some problem to fully understand callbacks scoping when trying to learn Jquery. I would add that i have little experience with the Javascript language The code:
```
var globDom; // placeholder for DOM fragment
// Getting xml file; jquery parses the file and give me back a DOM fragment
// saveX... | What Herms said. your (simplified) timeline looks like
```
0.001 globdom = undefined;
0.002 $.get(somerequest, callback)
0.003 alert(globdom)
.. 50 milliseconds later ..
0.053 saveXml(xmlDom)
``` | I haven't used jquery myself, but my understanding is that a lot of the stuff it does is asynchronous. That get method probably doesn't call your callback immediately. You'll need to wait until after the callback has been run before you try accessing globDom.
Try putting an alert within your callback method. Does that... | Callback and scope | [
"",
"javascript",
"jquery",
""
] |
I need to sanitize HTML submitted by the user by closing any open tags with correct nesting order. I have been looking for an algorithm or Python code to do this but haven't found anything except some half-baked implementations in PHP, etc.
For example, something like
```
<p>
<ul>
<li>Foo
```
becomes
```
<p>
... | using BeautifulSoup:
```
from BeautifulSoup import BeautifulSoup
html = "<p><ul><li>Foo"
soup = BeautifulSoup(html)
print soup.prettify()
```
gets you
```
<p>
<ul>
<li>
Foo
</li>
</ul>
</p>
```
As far as I know, you can't control putting the <li></li> tags on separate lines from Foo.
using Tidy:
```
impo... | Run it through [Tidy](http://tidy.sourceforge.net/) or one of its ported [libraries](http://utidylib.berlios.de/).
Try to code it by hand and you *will* want to gouge your eyes out. | How do I fix wrongly nested / unclosed HTML tags? | [
"",
"python",
"html",
"algorithm",
"xhtml",
""
] |
I'm writing small and very [DRY](http://en.wikipedia.org/wiki/DRY) framework, which heavily relies on metadata. I'd like to know if there is a way to obtain method parameter names, i.e. given some method
```
public void a(int myIntParam, String theString) { ... }
```
get the strings `"myIntParam"` and `"theString"`.
... | We created a custom annotation for the method that holds a String[] of parameter names. This approach felt a little easier to manage than having to annotate each individual parameter. We plan to add build-time checking that the number of annotated parameter names matches the number of arguments, since that it what we r... | Here is a dirty solution that needs some tweaking. Maybe someone can make it better.
### Cons:
* Requires that you know the location of compiled class file.
* It has to be compiled with the -g flag.
### Code:
```
import com.sun.org.apache.bcel.internal.classfile.ClassParser;
import com.sun.org.apache.bcel.internal.... | Is there a way to obtain names of method parameters in Java? | [
"",
"java",
"reflection",
""
] |
I'm trying to write out a `Byte[]` array representing a complete file to a file.
The original file from the client is sent via TCP and then received by a server. The received stream is read to a byte array and then sent to be processed by this class.
This is mainly to ensure that the receiving `TCPClient` is ready fo... | Based on the first sentence of the question: *"I'm trying to write out a Byte[] array **representing a complete file** to a file."*
The path of least resistance would be:
```
File.WriteAllBytes(string path, byte[] bytes)
```
Documented here:
> [`System.IO.File.WriteAllBytes` - MSDN](http://msdn.microsoft.com/en-us/... | You can use a `BinaryWriter` object.
```
protected bool SaveData(string FileName, byte[] Data)
{
BinaryWriter Writer = null;
string Name = @"C:\temp\yourfile.name";
try
{
// Create a new stream to write to the file
Writer = new BinaryWriter(File.OpenWrite(Name));
// Writer raw... | Can a Byte[] Array be written to a file in C#? | [
"",
"c#",
".net",
""
] |
In the footer of my page, I would like to add something like "last updated the xx/xx/200x" with this date being the last time a certain mySQL table has been updated.
What is the best way to do that? Is there a function to retrieve the last updated date? Should I access to the database every time I need this value? | In later versions of MySQL you can use the `information_schema` database to tell you when another table was updated:
```
SELECT UPDATE_TIME
FROM information_schema.tables
WHERE TABLE_SCHEMA = 'dbname'
AND TABLE_NAME = 'tabname'
```
This does of course mean opening a connection to the database.
---
An alternat... | I don't have information\_schema database, using mysql version 4.1.16, so in this case you can query this:
```
SHOW TABLE STATUS FROM your_database LIKE 'your_table';
```
It will return these columns:
```
| Name | Engine | Version | Row_format | Rows | Avg_row_length
| Data_length | Max_data_length | Index_l... | How can I tell when a MySQL table was last updated? | [
"",
"mysql",
"sql",
""
] |
I have a .NET webform that has a file upload control that is tied to a regular expression validator. This validator needs to validate that only certain filetypes should be allowed for upload (jpg,gif,doc,pdf)
The current regular expression that does this is:
```
^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))(.jpg|.JPG|.g... | Your regex seems a bit too complex in my opinion. Also, remember that the dot is a special character meaning "any character". The following regex should work (note the escaped dots):
```
^.*\.(jpg|JPG|gif|GIF|doc|DOC|pdf|PDF)$
```
You can use a tool like [Expresso](http://www.ultrapico.com/Expresso.htm) to test your ... | ```
^.+\.(?:(?:[dD][oO][cC][xX]?)|(?:[pP][dD][fF]))$
```
Will accept .doc, .docx, .pdf files having a filename of at least one character:
```
^ = beginning of string
.+ = at least one character (any character)
\. = dot ('.')
(?:pattern) = match the pattern without storing the match)
[dD] ... | Validating file types by regular expression | [
"",
"c#",
"asp.net",
".net",
"regex",
""
] |
I was writing some code, and I notice a pattern in the exception handling that got me thinking:
```
try{
// do stuff... throws JMS, Create and NamingException
} catch (NamingException e) {
log1(e);
rollback();
doSomething(e)
} catch (CreateException e) {
log1(e);
rollback();... | They are considering an extension of this type for Java 7.
See: <http://tech.puredanger.com/java7#catch> | As long as we're making up syntaxes, here's how I'd like to see it:
```
try
{
// do stuff ...
}
catch (NamingException e)
catch (CreateException e)
{
log1(e);
rollback();
doSoemthing(e);
}
```
Similar to the the fallthrough of a switch statement or C# `using` block. Of course, there's a problem here with ... | Cool or Stupid? Catch(Exception[NamingException, CreateException] e) | [
"",
"java",
"programming-languages",
"exception",
""
] |
As input I get an int (well, actually a string I should convert to an int).
This int should be converted to bits.
For each bit position that has a 1, I should get the position.
In my database, I want all records that have an int value field that has this position as value.
I currently have the following naive c... | Your feeling is correct. This should be solved with bitmasks. BitConverter does not return bits (and how could it? "bits" isn't an actual data type), it converts raw bytes to CLR data types. Whenever you want to extract the bits out of something, you should think bitmasks.
If you want to check if a bit at a certain po... | I suspect [BitArray](http://msdn.microsoft.com/en-us/library/system.collections.bitarray.aspx) is what you're after. Alternatively, using bitmasks yourself isn't hard:
```
for (int i=0; i < 32; i++)
{
if ((value & (1 << i)) != 0)
{
Console.WriteLine("Bit {0} was set!", i);
}
}
``` | Why does the BitConverter return Bytes and how can I get the bits then? | [
"",
"c#",
"bit-manipulation",
"bit-masks",
""
] |
I can remember *Convert* class in .net which is named not in accordance with the guide lines. Any more examples? | In Java, `java.lang.System.arraycopy` - note the lowercase second c.
Also `NullPointerException` in Java is better as `NullReferenceException` in .NET.
`AppDomain` violates the convention of *normally* not using abbreviations.
`Control.ID` violates the explicit convention of Pascal-casing ID to "Id" and Camel-casing... | * [IPEndPoint](http://msdn.microsoft.com/en-us/library/system.net.ipendpoint.aspx) breaks the [compound word capitalization](http://msdn.microsoft.com/en-us/library/ms229043.aspx) guideline (which, oddly enough, specifically calls out endpoint as an example).
* All the Interop references are verboten, because they are ... | Which are the examples for contra guideline implementations/misnomers in .net/java framework? | [
"",
"java",
".net",
""
] |
I'd like to write a simple detail formatter that displays `byte[]` data in the form of a `String` (using `String.<init>([B)` to do the dirty work).
However, I'm not sure how to find the class name for `[B` to use when creating the formatter. Is this even possible? Or, alternatively, is there another way to view byte a... | I don't know how to get eclipse's detail formatter to automagically display byte arrays as Strings, but you can display a particular byte array by adding `new String(byteArray)` as a watch expression. | If your question is how would I get a string representation of a byte array of [0,1,2] to be "[0,1,2]", I would suggest you take a look at Arrays.toString(byte[])
<http://java.sun.com/javase/6/docs/api/java/util/Arrays.html#toString(byte[])> | How can I display a byte array as a String in java's debug detail formatter? | [
"",
"java",
"eclipse",
"debugging",
""
] |
Is it possible to reflectively instantiate a generic type in Java? Using the technique described [here](http://www.velocityreviews.com/forums/t149816-generics-and-forname.html) I get an error because class tokens cannot be generic. Take the example below. I want to instantiate some subclass of Creator that implements C... | The generic information is lost in runtime. There is no runtime equivalent of a Creator<String>.class. You could create a type between Creator and StringCreator which fixes the generic type:
```
public interface Creator<T> {
T create();
}
public interface StringCreator extends Creator<String> { }
public class ... | This will do what you are trying to do while providing type safety. There's no way to avoid an unchecked warning, but the type checking done here justifies its suppression.
```
public static void main(String[] args)
throws Exception
{
Class<? extends Creator<String>> clz = load(argv[0], String.class);
... | can I reflectively instantiate a generic type in java? | [
"",
"java",
"generics",
"reflection",
""
] |
From time to time my applications GUI stops redrawing.
There a lot of threads that are firing all kinds of events (like timers or network data ready etc.). Also there are a lot of controls that are subscribing these events. Because of that, all the event handlers play the InvokeRequired/Invoke game.
Now I figured out t... | Invoke waits until the event is handled in the GUI thread. If you want it to be asynchronous use BeginInvoke() | Deadlock perhaps? Do you make sure that the events are never fired while holding a lock?
Are you able to see this with a debugger attached? If so, make it freeze and then hit the "pause" button - and see what the UI thread is doing.
Note that if you are able to get away with BeginInvoke instead of Invoke, life is a b... | Invoke() is blocking | [
"",
"c#",
".net",
"winforms",
".net-2.0",
""
] |
I need to connect to an Exchange mailbox in a Python script, without using any profile setup on the local machine (including using Outlook). If I use win32com to create a MAPI.Session I could logon (with the Logon() method) with an existing profile, but I want to just provide a username & password.
Is this possible? I... | I'm pretty sure this is going to be impossible without using Outlook and a MAPI profile. If you can sweet talk your mail admin into enabling IMAP on the Exchange server it would make your life a lot easier. | I know this is an old thread, but...
If you're using Exchange 2007 or newer, or Office365, take a look at Exchange Web Services. It's a pretty comprehensive SOAP-based interface for Exchange, and you can do pretty much anything Outlook is able to do, including delegate or impersonation access to other user accounts.
... | Connect to Exchange mailbox with Python | [
"",
"python",
"email",
"connection",
"exchange-server",
"pywin32",
""
] |
Yesterday, I found myself writing code like this:
```
SomeStruct getSomeStruct()
{
SomeStruct input;
cin >> input.x;
cin >> input.y;
}
```
Of course forgetting to actually return the struct I just created. Oddly enough, the values in the struct that *was* returned by this function got initialized to zero... | > Did another SomeStruct get created and initialized somewhere implicitly?
Think about how the struct is returned. If both `x` and `y` are 32 bits, it is too big to fit in a register on a 32-bit architecture, and the same applies to 64-bit values on a 64-bit architecture (@Denton Gentry's answer mentions how simpler v... | Falling off the end of a function that is declared to return a value (without explicitly returning a value) leads to undefined consequences. For gcc, you should start with the `-Wall` command line switch that turns on most useful warnings. The specific gcc warning that controls the warning you want is `-Wreturn-type` (... | What happens if you don't return a value in C++? | [
"",
"c++",
"g++",
"return-value",
""
] |
In my javascript I have this
```
loopDeLoop:
while (foo !== bar) {
switch (fubar) {
case reallyFubar:
if (anotherFoo == anotherBar) {
break loopDeLoop;
}
break;
default:
... | You are using the label correctly.
JSLint is throwing a warning because labels in Javascript are horribly bad style, and JSLint wants you to know that.
To reiterate, if you use labels at all, even correctly, JSLint will give that warning.
Edit:
Looks like you might be able to disable the label warning with a `-use_o... | You could set a flag that determines whether or not you are done working in the loop.
```
var done = false;
while (foo !== bar && !done) {
switch (fubar) {
case reallyFubar:
if (anotherFoo == anotherBar) {
done = true;
}
break;
default:
... | Getting a JSLint warning concerning labels in Javascript | [
"",
"javascript",
"jslint",
""
] |
I have a generic method with this (dummy) code (yes I'm aware IList has predicates, but my code is not using IList but some other collection, anyway this is irrelevant for the question...)
```
static T FindThing<T>(IList collection, int id) where T : IThing, new()
{
foreach (T thing in collection)
... | Three options:
* Return `default` (or `default(T)` for older versions of C#) which means you'll return `null` if `T` is a reference type (or a nullable value type), `0` for `int`, `'\0'` for `char`, etc. ([Default values table (C# Reference)](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/... | ```
return default(T);
``` | How can I return NULL from a generic method in C#? | [
"",
"c#",
"generics",
""
] |
In our C++ course they suggest not to use C++ arrays on new projects anymore. As far as I know [Stroustrup](https://en.wikipedia.org/wiki/Bjarne_Stroustrup) himself suggests not to use arrays. But are there significant performance differences? | Using C++ arrays with `new` (that is, using dynamic arrays) should be avoided. There is the problem that you have to keep track of the size, and you need to delete them manually and do all sorts of housekeeping.
Using arrays on the stack is also discouraged because you don't have range checking, and passing the array ... | ## Preamble for micro-optimizer people
Remember:
> "Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget ab... | Using arrays or std::vectors in C++, what's the performance gap? | [
"",
"c++",
"arrays",
"vector",
""
] |
I have a result from an SQL query that I would like to sort alphabetical, but there are a couple of commonly used results that I would like to float to the top.
Is there a simple way I can achieve this either by doing clever SQL or by sorting the (asp.net) datatable once I have it filled?
I know the database ID of the... | The easiest way to do this is to sort by something that sets those fields aside from the others...
Under the assumption you have access to modify the structure of the table (which you may not), then add a "sticky" field which allows you to mark items as sticky and attach an order to the sticky items if you like. Sort ... | You could define a custom column that sets a "special flag" that you can sort by. Then, sort by the alphabetical column.
```
SELECT ...
IsSpecial = CASE WHEN RowID IN (100,534,203) THEN 1 ELSE 0 END
FROM ...
ORDER BY IsSpecial DESC, RowID ASC, Name ASC
``` | How can I sort an SQL result but keep some results as special? | [
"",
".net",
"sql",
"sorting",
""
] |
We want to build a library of c# *snips* for .NET. We are looking around to see if there is something similar out there. The library will be open source and free to use and distribute.
I see there is a similar question here, but is more theoretical than practical, I want to have [Good Source of .NET Dsg Patterns](http... | Doodads has a lot of C# examples in their website
[Here is a list of GOF Pattern implementation in C#](http://dofactory.com/Patterns/Patterns.aspx)
They also have a 'Design Pattern Framework' for GOF patterns, it is commercial. I purchased it long time back, was good for reference.
<http://dofactory.com/Framework/Fr... | If there would be a library, why would we even bother with the pattern? We'd just use the lib and fall into the pit of success.
The idea of the pattern is to not make the same mistake as the other thousand developers. The pattern is something of "if you need to architect something that way, this way works best" .. And... | Is there any good framework or library for c# snips of design-patterns? | [
"",
"c#",
"design-patterns",
""
] |
A common argument against using .NET for high volume, transactional enterprise systems is that IIS does not compare to the likes of Weblogic and websphere for java. Is this true? Unfortunately for .NET web apps IIS is the only option as an application server. Does anyone have any arguments against this? I would like to... | I've been coding ASP.NET for 6 years now and prior to getting into the field I was a network engineer. IMO, ASP.NET on IIS is faster out of the box than most of those other platforms. However, it's easy to screw up performance with mediocre programming skills, and it is possible that a highly tuned platform could beat ... | If you are asking if IIS & .Net can do high performance web sites, the answer is yes. You are unlikely to get to the kind of scale where either of the web servers you have mentioned starts being the problem. You are more likely to have issues with back end databases first.
If you are asking how to convince management ... | How does IIS compare in terms of performance and scalability to weblogic and websphere for enterprise web applications? | [
"",
"java",
".net",
"iis",
"websphere",
"weblogic",
""
] |
The Zend Framework based site I have been working on is now being migrated to its production server. This server turns out to be nginx (surprise!). Naturally the site does not work correctly as it was developed on Apache and relies on an htaccess file.
My question is... anyone have any experience with this? Any ideas ... | I know it's a pretty old thread but it might help some people anyway.
Basically it redirects any 404 error to index.php, but if the file exists (type file) it will set the right root.
I did it from the top of my head. It might not be working right away, and you have to put the right path and fastcgi config. I also pu... | ```
server {
listen 80; ## listen for ipv4
listen [::]:80 default ipv6only=on; ## listen for ipv6
server_name localhost;
access_log /var/log/nginx/localhost.access.log;
error_log /var/log/nginx/localhost.error.log;
root /var/www/localhost/public;
try_files $uri @php_index;
# pass the PHP scripts ... | Zend Framework on nginx | [
"",
"php",
"zend-framework",
"mod-rewrite",
"nginx",
""
] |
I've got a table, called faq\_questions with the following structure:
```
id int not_null auto_increment,
question varchar(255),
sort_order int
```
I'm attempting to build a query that given a sort order, selects the row with the next highest sort order.
Example:
```
id question sort_order
1 'This... | It seems too simple, but it looks like what you need:
```
SELECT id,question FROM `questions`
WHERE `sort_order` > sort_order_variable
ORDER BY sort_order ASC
LIMIT 1
``` | ```
SELECT * FROM table_name WHERE sort_order > 5 ORDER BY sort_order ASC LIMIT 1
``` | MySql Query, Select greater than | [
"",
"sql",
"mysql",
""
] |
I'm using VS 2008 to create a C++ DLL (not managed) project and I need convert a char\* to a long long type. Is there an easy way to do it?
Thanks in advance :) | Try `_atoi64.` This takes `char*` and returns `__int64`. | The easiest way is to use the std::stringstream (it's also the most typesafe...)
```
std::stringstream sstr(mystr);
__int64 val;
sstr >> val;
```
You may need to target a 64-bit application for this to work.
[C++ FAQ](http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.2) | convert string to long long | [
"",
"c++",
"string",
"visual-studio-2008",
""
] |
I'm writing a small and inadequate linear algebra library in C++ for a project (I'm sorry). I'm implementing matrices and operations using double precision numbers. I'm doing right? Should I implement a template class instead? Is there a more precise type around? | I've written a C++ linear algebra library using templates. My thought was that we might want to use complex numbers or extended precision numbers some day. That was maybe seven years ago, and we haven't done it yet. We almost always use doubles as the template type, and we have typedefs to make that easy.
A few times ... | I would implement the class/struct using a template. In the beginning, you will most likely be satisfied with just `double`, but I have found that in every project where I **didn't** implement matrices as templates, I later regretted it.
Also, it gives you an opportunity to use more interesting element-algebras - inte... | Best base type to deal with linear algebra | [
"",
"c++",
"linear-algebra",
"double-precision",
""
] |
I have a little project with some jsp deployed on an Tomcat 5.5. Recently the Servlets which are also deployed with the jsp files (one war archive) stopped working. I also checked out a previous version from my svn which should work. What I noticed that the `displayname` (I use a german version of Tomcat , so I guess t... | Is the `<display-name>` element in the web.xml file? Is the `web.xml` file in the WAR and at `/WEB-INF/web.xml`? Does it validate (eclipse can do that, or try [w3c.org's validation service](http://validator.w3.org/))? | You are looking for
```
<web-app blahblah>
<display-name>**This**</display-name>
<servlet>
<servlet-name>Not this</servlet-name>
</servlet>
</web-app>
``` | tomcat application missing displayname | [
"",
"java",
"eclipse",
"tomcat",
"servlets",
""
] |
I have 2 tables, an active table and an inactive table. I want to *move* rows from the active to the inactive table. My first thought was
```
insert into inactive select * from active where ...
delete from active active where ...
```
However about .42 seconds later I noticed this will drop/duplicate rows if updates a... | Status flags are your friend.
```
UPDATE old_data SET move="MARKED";
INSERT INTO somewhere... SELECT where move="MARKED";
DELETE FROM old_data WHERE move="MARKED";
```
If you do this with Autocommit off, it will seize locks all over the place.
You can COMMIT after each step, if you want to do a little less locking. | Does your database support the OUTPUT Clause? Then this could be a perfect and easy to follow solution for you, couldn't it?
<http://msdn.microsoft.com/en-us/library/ms177564.aspx>
```
delete active with (readpast)
output DELETED.*
into inactive
where ...
``` | Move rows between tables in SQL | [
"",
"sql",
"partitioning",
""
] |
I need to grab the height of the window and the scrolling offset in jQuery, but I haven't had any luck finding this in the jQuery docs or Google.
I'm 90% certain there's a way to access height and scrollTop for an element (presumably including the window), but I just can't find the specific reference. | From jQuery Docs:
```
const height = $(window).height();
const scrollTop = $(window).scrollTop();
```
<http://api.jquery.com/scrollTop/>
<http://api.jquery.com/height/> | from <http://api.jquery.com/height/> (Note: The difference between the use for the window and the document object)
```
$(window).height(); // returns height of browser viewport
$(document).height(); // returns height of HTML document
```
from <http://api.jquery.com/scrollTop/>
```
$(window).scrollTop() // return t... | How do I determine height and scrolling position of window in jQuery? | [
"",
"javascript",
"jquery",
""
] |
Which is more efficient?
```
SELECT theField
FROM theTable
GROUP BY theField
```
or
```
SELECT DISTINCT theField
FROM theTable
``` | In your example, both queries will generate the same execution plan so their performance will be the same.
However, they both have their own purpose. To make your code easier to understand, you should use distinct to **eliminate duplicate rows** and group by to **apply aggregate operators** (sum, count, max, ...). | Doesn't matter, it results in the same execution plan. (at least for these queries). These kind of questions are easy to solve, by enabling query analyzer or SSMS to show the execution plan and perhaps the server trace statistics after running the query. | Which is better: Distinct or Group By | [
"",
"sql",
"sql-server",
""
] |
Goal: Create [Photomosaics](http://en.wikipedia.org/wiki/Photographic_mosaic) programmatically using .NET and C#.
Main reason I'd like to do this programatically is to be able to record which image and where it goes myself, so I can create an animated effect of the images coming together to create the photomosaic. It ... | [Photomosaic-generator](http://www.atalasoft.com/cs/blogs/31appsin31days/archive/2008/05/18/photomosaic-generator.aspx)
There's source code available | I think you can borrow ideas from color quantization. For each photograph, calculate it's average color. Since it's small, that's how it will look when viewed from a distance. Then split your target image in photograph-sized rectangles and calculate their average colors. Or, for better results, properly downsize it so,... | Programmatically create Photomosaic | [
"",
"c#",
".net",
"graphics",
""
] |
How do I check if a variable, specifically a pointer, is defined in C++? Suppose I have a class:
```
class MyClass {
public:
MyClass();
~MyClass() {
delete pointer; // if defined!
}
initializePointer() {
pointer = new OtherClass();
}
private:
OtherClass* pointer;
};
``` | Why worry about checking for the pointers value? Just initialize it to a null pointer value and then just call delete on it. delete on a null pointer does nothing (the standard guarantees it).
```
class MyClass {
public:
MyClass():pointer(0) { }
~MyClass() {
delete pointer;
pointer = 0;
... | I tend to initialize my pointer values to NULL on object construction. This allows a check against NULL to see if the pointer variable is defined. | Check for pointer definedness in C++ | [
"",
"c++",
"pointers",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.