Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
In a C# console application, is there a smart way to have console output mirrored to a text file?
Currently I am just passing the same string to both `Console.WriteLine` and `InstanceOfStreamWriter.WriteLine` in a log method. | This may be some kind of more work, but I would go the other way round.
Instantiate a `TraceListener` for the console and one for the log file; thereafter use `Trace.Write` statements in your code instead of `Console.Write`. It becomes easier afterwards to remove the log, or the console output, or to attach another lo... | This is a simple class which subclasses TextWriter to allow redirection of the input to both a file and the console.
Use it like this
```
using (var cc = new ConsoleCopy("mylogfile.txt"))
{
Console.WriteLine("testing 1-2-3");
Console.WriteLine("testing 4-5-6");
Console.ReadKey();
}
```
Here is the ... | Mirroring console output to a file | [
"",
"c#",
".net",
"file",
"text",
"console",
""
] |
Kicking around some small structures while answering [this post](https://stackoverflow.com/questions/414981/directly-modifying-listt-elements), I came across the following unexpectedly:
The following structure, using an int field is perfectly legal:
```
struct MyStruct
{
public MyStruct ( int size )
{
... | From C# 6 onward: this is no longer a problem
---
Becore C# 6, you need to call the default constructor for this to work:
```
public MyStruct(int size) : this()
{
Size = size;
}
```
A bigger problem here is that you have a mutable struct. This is **never** a good idea. I would make it:
```
public int Size { ge... | You can fix this by first calling the default constructor:
```
struct MyStruct
{
public MyStruct(int size) : this()
{
this.Size = size; // <-- now works
}
public int Size { get; set; }
}
``` | Automatic Properties and Structures Don't Mix? | [
"",
"c#",
"c#-3.0",
"struct",
"automatic-properties",
""
] |
Is there a VB.NET equivalent to the C#:
```
public string FirstName { get; set; }
```
I know you can do
```
Public Property name() As String
Get
Return _name.ToString
End Get
Set(ByVal value As String)
_name = value
End Set
End Property
```
But I can't seem to google up an answer on a Visua... | There is no shorthand for Visual Studio 2008 or prior for VB.NET.
In Visual Studio 2010 and beyond, you can use the following shorthand:
```
Public Property FirstName as String
```
This will be handled as your short version in C# is - I think they call it "Auto Property"
See also: [Auto-Implemented Properties (Visu... | In Visual Studio 2008, after typing just the keyword `Property`, press the `Tab` key. It'll paste a template snippet for you which you can fill very quickly.
But yeah, there is not a replacement of a Visual Basic 10-type shortcut in Visual Basic 9. | VB.NET equivalent of C# property shorthand? | [
"",
"c#",
"vb.net",
"language-features",
""
] |
I've created an web authentication app using c# & asp.net and want to bounce off how secure you think it is. All navigation is done by https.
**User Registration**
1. User enters 3 datapoints (SSN,Lname and DOB). If that combination is found in our system, a session variable is set and navigates to next page.
2. If s... | What aspect of either ASP.NET Forms Authentication or using the Membership Provider bits didn't fit with your needs? I've found both to be very flexible in many different scenarios?
Rolling your own is usually going to make life hard in the future, especially when you need to start making changes. Also your use of a m... | The thing about "rolling your own" is that it's very easy to get it wrong in subtle ways such that it *appears* to work. You then, of course, deploy this code and move on to other things with no clue that anything is wrong. After all, it passed all your tests.
A year later it turns out your site was hacked six months ... | How secure is this ASP.Net authentication model? | [
"",
"c#",
"asp.net",
"security",
""
] |
**Why the following example prints "0" and what must change for it to print "1" as I expected ?**
```
#include <iostream>
struct base {
virtual const int value() const {
return 0;
}
base() {
std::cout << value() << std::endl;
}
virtual ~base() {}
};
struct derived : public base {
virtual... | Because `base` is constructed first and hasn't "matured" into a `derived` yet. It can't call methods on an object when it can't guarantee that the object is already properly initialized. | When a derived object is being constructed, before the body of the derived class constructor is called the base class constructor must complete. Before the derived class constructor is called the dynamic type of the object under construction is a base class instance and not a derived class instance. For this reason, wh... | C++ virtual function from constructor | [
"",
"c++",
"oop",
"class",
"constructor",
"virtual",
""
] |
I have been using python with RDBMS' (MySQL and PostgreSQL), and I have noticed that I really do not understand how to use a cursor.
Usually, one have his script connect to the DB via a client DB-API (like psycopg2 or MySQLdb):
```
connection = psycopg2.connect(host='otherhost', etc)
```
And then one creates a curso... | ya, i know it's months old :P
DB-API's cursor appears to be closely modeled after SQL cursors. AFA resource(rows) management is concerned, *DB-API does not specify whether the client must retrieve all the rows or DECLARE an actual SQL cursor*. As long as the fetchXXX interfaces do what they're supposed to, DB-API is h... | Assuming you're using PostgreSQL, the cursors probably are just implemented using the database's native cursor API. You may want to look at the source code for [pg8000](http://pybrary.net/pg8000/), a pure Python PostgreSQL DB-API module, to see how it handles cursors. You might also like to look at [the PostgreSQL docu... | How do cursors work in Python's DB-API? | [
"",
"python",
"performance",
"rdbms",
"cursors",
"psycopg2",
""
] |
I notice sometimes users mistype their email address (in a contact-us form), for example, typing @yahho.com, @yhoo.com, or @yahoo.co instead of @yahoo.com
I feel that this can be corrected on-the-spot with some javascript. Simply check the email address for possible mistakes, such as the ones listed above, so that if ... | Here's a dirty implementation that could kind of get you some simple checks using the [`Levenshtein distance`](http://en.wikipedia.org/wiki/Levenshtein_distance). Credit for the "levenshteinenator" goes to [`this link`](http://andrew.hedges.name/experiments/levenshtein/). You would add whatever popular domains you want... | In addition to soundex, you may also want to have a look at algorithms for determining [Levenshtein](http://en.wikipedia.org/wiki/Levenshtein_distance) distance. | detecting mistyped email addresses in javascript | [
"",
"javascript",
"email-validation",
""
] |
I want to be able to read line by line from a pdf, compare it to a string( a filename), and if the string appears in that line, write that line to a list.
So far I had a quick look at ITextSharp and at PDFSharp, but it doesn't seem like these are the right tools for the job as they focus most on altering and printing ... | I use [PDFBox](http://www.pdfbox.org/userguide/dot_net.html) with Lucene. It was easy to find out how it works and it does the job.
It's opensource and free. | You may want to try [Docotic.Pdf library](https://bitmiracle.com/pdf-library/).
The library can be used to extract multi-line plain text from all pages of a PDF and then you can search for a filename or anything else in that text.
Please take a look at the sample in [my answer](https://stackoverflow.com/questions/489... | c# Read line from PDF | [
"",
"c#",
"pdf",
".net-2.0",
""
] |
```
void foo(void **Pointer);
int main ()
{
int *IntPtr;
foo(&((void*)IntPtr));
}
```
Why do I get an error?
```
error: lvalue required as unary ‘&’ operand
```
Thanks | (void\*) is not an lvalue, it is kind of a casting operator, you need to have the ampersand to the immediate left of the variable (lvalue).
This should be right:
```
foo(((void**)&IntPtr));
``` | ```
void foo(void **Pointer);
int main ()
{
int *IntPtr;
foo((void**)&IntPtr);
}
``` | How to cast a pointer in C++ | [
"",
"c++",
"casting",
"pointers",
"types",
""
] |
Is there an attribute I can use on a method so that when stepping through some code in Debug mode the Debugger stays on the outside of the method? | ```
[DebuggerStepThrough]
```
([docs](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.debuggerstepthroughattribute?view=netframework-4.7)) | Not forgetting to add:
```
using System.Diagnostics;
``` | Attribute to Skip over a Method while Stepping in Debug Mode | [
"",
"c#",
".net",
"debugging",
"attributes",
""
] |
```
#include "cv.h"
#include "highgui.h"
#include <stdio.h>
int main(int argc, char* argv[]){
cvNamedWindow("Window1", CV_WINDOW_AUTOSIZE);
IplImage* image = 0;
->->image = cvLoadImage(argv[1]);<-<-
if(!image) printf("Unable to load image!");
cvShowImage("Window1", image);
char c = cvWaitKey(0... | Under Project->Properties->Configuration Properties->Debugging there is a field "Working Directory". Set that to the directory you want to execute in and that should fix the problem. | Are you certain "247.png" is in the current working directory when you have the name hardcoded?
Run the program under something like [Process Monitor](http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx) to see what file is really being opened (or what file I/O errors there might be).
After your edit to add... | Why does OpenCV reject cvLoadImage("string.ext"), but accept cvLoadImage(argv[1])? | [
"",
"c++",
"c",
"visual-studio",
"opencv",
""
] |
I've got a problem on a *WebForms* application where a user selects some criteria from drop downs on the page and hits a button on the page which calls this method:
```
protected void btnSearch_Click(object sender, EventArgs e)
```
They then click on button to download a zip file based on the criteria which calls thi... | When they click the download button, do a Redirect to the ZIP file handler (page?) to download the file. i.e. use the Post-Redirect-Get pattern: <http://en.wikipedia.org/wiki/Post/Redirect/Get> | Are you using the Content-Disposition header?
```
Response.AddHeader("Content-Disposition", "attachment; filename=fileName.zip");
```
Try changing the content type to match the file type? | Why do my Button send two postbacks when downloading zip file? | [
"",
"c#",
"webforms",
"postback",
""
] |
im writing an application that downloads and installs addons for programs which needs to save the data to program files (for the programs in question). Now this works fine on xp and vista with uac disabled however it is failing on normal vista due to the virtual folders.
How would one get around this with out needing ... | I got around uac by making a windows service that does the work i need and only runs while the app is running. | Only write to Program Files during installation. After that, write to the user folders.
You can elevate the apps privileges later, but you'll just be delaying the prompt. The whole point of UAC is to prevent random apps from writing to folders that require admin privileges. (ok, not the whole point, but a large portio... | Avoiding UAC in vista | [
"",
"c++",
"windows-vista",
"uac",
""
] |
I read somewhere that snprintf is faster than ostringstream. Has anyone has any experiences with it? If yes why is it faster. | `std::ostringstream` is not **required** to be slower, but it is generally slower when implemented. [FastFormat's website has some benchmarks](http://www.fastformat.org/performance.html).
The Standard library design for streams supports much more than `snprintf` does. The design is meant to be extensible, and includes... | We replaced some stringstreams in inner loops with sprintf (using statically allocated buffers), and this made a big difference, both in msvc and gcc. I imagine that the dynamic memory management of this code:
```
{
char buf[100];
int i = 100;
sprintf(buf, "%d", i);
// do something with buf
}
```
is much simp... | Why is snprintf faster than ostringstream or is it? | [
"",
"c++",
"c",
"performance",
""
] |
I'm just curious about this. It strikes me that the behavior of a StringBuilder is functionally (if not technically) the same as a Stream -- it's a bin of data to which other data can be added.
Again, just curious. | Stream is an input and output of *binary* data.
StringBuilder is means of building up *text* data.
Beyond that, there's the issue of state - a StringBuilder just has the current value, with no idea of "position". It allows you to access and mutate data anywhere within it. A stream, on the other hand, is logically a p... | `StringBuilder` has more than just Append functions. It also has insert functions which is unnatural for a stream. Use the `StringWriter` class if you want a stream that wraps a `StringBuilder`. | Why isn't the StringBuilder class inherited from Stream? | [
"",
"c#",
"stream",
"stringbuilder",
""
] |
I'm porting a medium-sized C++ project from Visual Studio 2005 to MacOS, XCode / GCC 4.0.
One of the differences I have just stumbled across has to do with erasing an element from a map. In Visual Studio I could erase an element specified by an iterator and assign the return value to the iterator to get the position o... | No. You have to increment the iterator before erasing. Like this
```
m_ResourceMap.erase(itor++);
```
The iterator is invalidated by the erase, so you can't increment it afterwards. | By the look of things gcc is following the STL standard so I guess you'll have to change your code.
```
void erase(iterator pos) Associative Container Erases the element pointed to by pos.
``` | Why does the g++ 4.0 version of map<T>::erase(map::<T> iterator) not return a iterator? | [
"",
"c++",
"gcc",
"stl",
""
] |
Can someone suggest a way to compare the values of **two dates** greater than, less than, and not in the past using JavaScript? The values will be coming from text boxes. | The [Date object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) will do what you want - construct one for each date, then compare them using the `>`, `<`, `<=` or `>=`.
The `==`, `!=`, `===`, and `!==` operators require you to use `date.getTime()` as in
```
var d1 = new Date()... | Compare `<` and `>` just as usual, but anything involving `==` or `===` should use a `+` prefix. Like so:
```
const x = new Date('2013-05-23');
const y = new Date('2013-05-23');
// less than, greater than is fine:
console.log('x < y', x < y); // false
console.log('x > y', x > y); // false
console.log('x <= y', x <= y... | Compare two dates with JavaScript | [
"",
"javascript",
"date",
"datetime",
"compare",
""
] |
Regardless of what the user's local time zone is set to, using C# (.NET 2.0) I need to determine the time (DateTime object) in the Eastern time zone.
I know about these methods but there doesn't seem to be an obvious way to get a DateTime object for a different time zone than what the user is in.
```
DateTime.Now
D... | As everyone else mentioned, .NET 2 doesn't contain any time zone information.
The information is stored in the registry, though, and its fairly trivial to write a wrapper class around it:
```
SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones
```
contains sub-keys for all time zones. The TZI field value cont... | In .NET 3.5, there is [`TimeZoneInfo`](http://msdn.microsoft.com/en-us/library/system.timezoneinfo.aspx), which provides a lot of functionality in this area; 2.0SP1 has [`DateTimeOffset`](http://msdn.microsoft.com/en-us/library/system.datetimeoffset.aspx), but this is much more limited.
Getting `UtcNow` and adding a f... | Get DateTime For Another Time Zone Regardless of Local Time Zone | [
"",
"c#",
"datetime",
".net-2.0",
""
] |
I want to use the Split function on a string but keep the delimiting sequence as the first characters in each element of the string array. I am using this function to split HTML on every instance of a URL so I can run regex patterns on the URLs on a website. Is there any overloads of the split function to do this? or d... | There is no built-in method for doing that. If you are splitting on a single pattern though, this can be coded out with the following
```
public IEnumerable<string> SplitAndKeepPrefix(this string source, string delimeter) {
return SplitAndKeepPrefix(source, delimeter, StringSplitOptions.None);
}
public IEnumerable<... | ```
public static string[] SplitAndKeepDelimiters(this string Original, string[] Delimeters, StringSplitOptions Options)
{
var strings = EnumSplitAndKeepDelimiters(Original, Delimeters);
if (Options == StringSplitOptions.RemoveEmptyEntries)
{
return strings.Where((s) => s.Le... | String.Split variation in C# | [
"",
"c#",
"string",
""
] |
I have these tables:
```
Projects(projectID, CreatedByID)
Employees(empID,depID)
Departments(depID,OfficeID)
Offices(officeID)
```
`CreatedByID` is a [foreign key](http://en.wikipedia.org/wiki/Foreign_key) for `Employees`. I have a query that runs for almost every page load.
Is it bad practice to just add a redundan... | Denormalization has the advantage of fast `SELECT`s on large queries.
Disadvantages are:
* It takes more coding and time to ensure integrity (which is most important in your case)
* It's slower on DML (INSERT/UPDATE/DELETE)
* It takes more space
As for optimization, you may optimize either for faster querying or for... | Normalize till it hurts, then denormalize till it works | How far to take normalization? | [
"",
"sql",
"database-design",
"database-normalization",
""
] |
**DUPE: [Should 'using' statements be inside or outside the namespace?](https://stackoverflow.com/questions/125319/should-usings-be-inside-or-outside-the-namespace)**
If I add a new class using Visual Studio to the project, It adds all the using statements before namespace but for the same project, FxCop says that put... | See [Should 'using' statements be inside or outside the namespace?](https://stackoverflow.com/questions/125319/should-usings-be-inside-or-outside-the-namespace) | I prefer the default which is at the top of the file. This is completely up to you but I guess with the majority of people using the default template of Visual Studio and having them at the top, it'll be expected there.
With the namespaces outside of your namespace, it does become more readable as, to me, the namespac... | Where to put using statements in a C# .cs file | [
"",
"c#",
""
] |
Now I appreciate the moral of the story is "don't hog the UI thread" but we tried to KISS by keeping things on the UI thread for as long as possible but I think we've just hit the tipping point and we're going to have to change our design.
But anyway..... something I noticed on our device that doesn't happen on deskto... | The issue was to do with a bug in the BSP (apparently from some Freescale code) that meant that the keyboard driver was functioning at a much lower priority interrupt than was intended.
This is now fixed and everything works awesome fine. :) | ```
for (int i = 0; i < 1000000; i++)
{
}
```
Empty loops to provide time delays are indicative of poor understanding of the EVENT driven model.
Windows CE has a different enough event handler from the desktop version of windows that, while windows tolerates this type of abuse, windows CE wil... | Why does Windows CE drop key events if you hog the UI thread | [
"",
"c#",
"winforms",
"compact-framework",
"windows-ce",
""
] |
I am trying to use Qt for a project in school but am running into problems. I started following the tutorials and I am running into Makefile problems. Most of the tutorials say to run `qmake -project`, then `qmake` and finally `make`. But when I try this I run into the error `make: *** No targets specified and no makef... | qmake on OS X creates Xcode project files. You can create a Makefile with:
```
qmake -spec macx-g++
```
If you don't want the Makefile to create an app bundle, you could also remove 'app\_bundle' your configuration, for example by adding the following lines to your project file.
```
mac {
CONFIG -= app_bundle
}
``... | As other posters have pointed out, the default behavior of qmake on the Mac is to create xCode project files. You can type in something special every time you run qmake or add a few lines to each project file. There is a more permanent solution. I run into this every time I install Qt on my Mac. From a command line typ... | How to compile a simple Qt and c++ application using g++ on mac os x? | [
"",
"c++",
"macos",
"qt",
"makefile",
"qmake",
""
] |
Is it possible to use the `with` statement directly with CSV files? It seems natural to be able to do something like this:
```
import csv
with csv.reader(open("myfile.csv")) as reader:
# do things with reader
```
But csv.reader doesn't provide the `__enter__` and `__exit__` methods, so this doesn't work. I can ho... | The primary use of `with` statement is an exception-safe cleanup of an object used in the statement. `with` makes sure that files are closed, locks are released, contexts are restored, etc.
Does [csv.reader](http://docs.python.org/library/csv.html#csv.reader) have things to cleanup in case of exception?
I'd go with:
... | Yes. The second way is correct.
As to why? Who ever knows. You're right, it's probably an easy change. It's not as high priority as other things.
You can easily make your own patch kit and submit it. | Using "with" statement for CSV files in Python | [
"",
"python",
"csv",
"with-statement",
""
] |
I want to define a JavaScript class, Foo.
```
Foo = function(value){
this.value = value;
};
```
I will create "instances" of my Foo:
```
foo1 = new Foo(1);
foo2 = new Foo(1);
```
and I want my instances of Foo to be comparable with each other using the standard == equality operator:
```
foo1 == foo2; // t... | JavaScript does not have operator overloading. See [this discussion](https://stackoverflow.com/questions/27030/comparing-arrays-of-objects-in-javascript) covering your question. | Not in a clean way...
```
Foo = function (value){
this.value = value;
};
```
Override the toString function of your own object:
```
Foo.prototype.toString = function( ){ return this.value.toString(); }
```
Creating two test objects:
```
foo1 = new Foo(1);
foo2 = new Foo(1);
```
If the values of your objects i... | How can you define how objects are compared in JavaScript | [
"",
"javascript",
"comparison",
"equals",
""
] |
I have heard that using exception trapping is not a recommended practice for number testing.
For example:
```
bool isnumeric
try
{
int i = int.parse(textbox1.text);
isnumeric = true;
}
catch {isnumenric=false}
```
Is there some other way that I could test for numbers in C#? | Yes try using
```
int i;
bool success = Int32.TryParse(textBox1.text, out i);
```
The **TryParse** method basically does what you are doing above. | Use the built-in [TryParse](http://msdn.microsoft.com/en-us/library/f02979c7.aspx)
E.g.
```
int number;
bool result = Int32.TryParse(value, out number);
``` | In C# should try-catch be used for is-numeric testing? | [
"",
"c#",
""
] |
I have a Python [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime-objects) object. What is the best way to subtract one day? | You can use a [`timedelta`](http://docs.python.org/library/datetime.html#timedelta-objects) object:
```
from datetime import datetime, timedelta
d = datetime.today() - timedelta(days=days_to_subtract)
``` | Subtract `datetime.timedelta(days=1)` | How to subtract a day from a date? | [
"",
"python",
"date",
"datetime",
"timedelta",
""
] |
I am trying to write a Java class to extract a large zip file containing ~74000 XML files. I get the following exception when attempting to unzip it utilizing the java zip library:
**java.util.zip.ZipException**: too many entries in ZIP file
Unfortunately due to requirements of the project I can not get the zip broke... | Using `ZipInputStream` instead of `ZipFile` should probably do it. | Using apache IOUtils:
```
FileInputStream fin = new FileInputStream(zip);
ZipInputStream zin = new ZipInputStream(fin);
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
FileOutputStream fout = new FileOutputStream(new File(
outputDirectory, ze.getName()));
IOUtils.copy(zin,... | java.util.zip.ZipException: too many entries in ZIP file | [
"",
"java",
"zip",
"large-files",
"unzip",
""
] |
Is there any algorithm in c# to singularize - pluralize a word (in english) or does exist a .net library to do this (may be also in different languages)? | You also have the [System.Data.Entity.Design.PluralizationServices.PluralizationService](http://msdn.microsoft.com/en-us/library/system.data.entity.design.pluralizationservices.pluralizationservice.aspx).
**UPDATE**: Old answer deserves update. There's now also Humanizer: <https://github.com/MehdiK/Humanizer> | I can do it for Esperanto, with no special cases!
```
string plural(string noun) { return noun + "j"; }
```
For English, it would be useful to become familiar with the rules for [Regular Plurals of Nouns](http://web2.uvcs.uvic.ca/elc/studyzone/330/grammar/plural.htm), as well as [Irregular Plurals of Nouns](http://we... | Is there any algorithm in c# to singularize - pluralize a word? | [
"",
"c#",
"algorithm",
""
] |
From an [SO answer](https://stackoverflow.com/questions/423823/whats-your-favorite-programmer-ignorance-pet-peeve#answer-424035)1 about Heap and Stack, it raised me a question: Why it is important to know where the variables are allocated?
At [another answer](https://stackoverflow.com/questions/79923/what-and-where-ar... | So long as you know what the semantics are, the only consequences of stack vs heap are in terms of making sure you don't overflow the stack, and being aware that there's a cost associated with garbage collecting the heap.
For instance, the JIT *could* notice that a newly created object was never used outside the curre... | (**edit:** *My original answer contained the oversimplification "structs are allocated on the stack" and confused stack-vs-heap and value-vs-reference concerns a bit, because they are coupled in C#.*)
Whether objects live on the stack or not is an implementation detail which is not very important. Jon has already expl... | Heap versus Stack allocation implications (.NET) | [
"",
"c#",
".net",
"performance",
"stack",
"heap-memory",
""
] |
I'm trying to access an OleVariant in a callback that is coming from an ActiveX library.
Here's what the event handler is defined as in the TLB:
```
procedure(ASender: TObject; var structQSnap: {??structVTIQSnap}OleVariant) of object;
```
Here's the definition of structVTIQSnap in the TLB:
```
structVTIQSnap = pack... | I think that Delphi's ActiveX import wizard doesn't know how to handle the structVTIQSnap type (which seems to be a record) properly and just uses the default OleVariant.
Is there a type declaration named structVTIQSnap or similar in the generated ...\_TLB.pas file? Try using that instead of OleVariant, e.g.
```
proce... | You could try to typecast the *structQSnap* to a pointer to this struct. Something like
```
PstructVTIQSnap = ^structVTIQSnap;
structVTIQSnap = packed record
bstrSymbol: WideString;
// other stuff...
end;
```
and
```
procedure TForm1.HandleVTIQuoteSnap(ASender: TObject;
var structQSnap: OleVariant);
var
ps... | Invalid Variant Operation Exception Trying to Access OleVariant in Delphi - Works in C# | [
"",
"c#",
"delphi",
"com",
"ole",
""
] |
When you create an aspx page as this one:
```
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head ru... | If it's related to the browser that your audience is using, then they're used to it happening, because it happens on every other site besides yours. I'd say it's not worth worrying about - kind of like people with JavaScript turned off. They know they've got it turned off, and they're accustomed to sites lacking certai... | First of all, it is NOT standard behavior to get a beep when pressing enter in a textbox on a webpage. Try Google's search page, or for that matter try the Name, Email, and Home Page fields at the bottom of this page. None of them beep when pressing enter - in any browser.
To prevent the beep, handle the onKeyDown eve... | Avoid Beep sound when enter keypress in a textbox | [
"",
"asp.net",
"javascript",
"onkeypress",
""
] |
I have a program that captures live data from a piece of hardware on a set interval. The data is returned as XML. There are several things I would like to do with this data (in order):
-display it to user
-save it to disk
-eventually, upload it to database
My current approach is to take the XML, parse it into a hashta... | When you receive a new XML document from the source, directly save to disk and parse it to display to the user.
With a background process, or user initiated, read the xml files from disk and send them to the server based on created date (so you can retrieve only the latest ones) for insert into MySql. | That mostly depends on the amount and rate of data you're moving. If you have to upload to the database seldom and it only takes a few seconds, the flexibility of XML is surely good to have. If you're never using the locally stored data except to upload it to the database and parsing takes a few minutes you might want ... | C#: capture data, display to user, save to disk, upload to database: BEST approach | [
"",
"c#",
"xml",
"file-io",
""
] |
Is there a tool to count the number of methods defined in a header? This seems like something that people would want to do from time to time, but I've never heard of such a utility. I could roll my own (and it'd be quite easy to come up with something that works for me in *this* particular case), but I thought I'd try ... | Try this:
```
ctags --c++-kinds=f -x myfile.h
```
To list all functions in the file myfile.h . To count the number of functions in `deque.tcc`:
```
$ ctags --c++-kinds=f --language-force=c++ -x deque.tcc | wc -l
24
``` | I dunno if doxygen --> <http://www.doxygen.nl/> does it, but I wouldn't be surprised if it also does that.
It generates documentation from the header files + javadoc like comments.
It will find the functions also so that kinda is counting. | Counting the number of methods defined in a C++ header | [
"",
"c++",
""
] |
We work heavily with serialization and having to specify Serializable tag on every object we use is kind of a burden. Especially when it's a 3rd-party class that we can't really change.
The question is: since Serializable is an empty interface and Java provides robust serialization once you add `implements Serializabl... | Serialization is fraught with pitfalls. Automatic serialization support of this form makes the class internals part of the public API (which is why javadoc gives you the [persisted forms of classes](http://java.sun.com/javase/6/docs/api/serialized-form.html#java.net.URL)).
For long-term persistence, the class must be ... | I think both Java and .Net people got it wrong this time around, would have been better to make everything serializable by default and only need to mark those classes that can't be safely serialized instead.
For example in Smalltalk (a language created in 70s) every object is serializable by default. I have no idea wh... | Why Java needs Serializable interface? | [
"",
"java",
"serialization",
""
] |
Is there any way to access all WiFi access points and their respective RSSI values using .NET? It would be really nice if I could do it without using unmanaged code or even better if it worked in mono as well as .NET.
If it is possible i would appriciate a code sample.
Thanks
---
Here are a few similiar stackoverflo... | It is a wrapper project with managed code in c# at <http://www.codeplex.com/managedwifi>
It supports Windows Vista and XP SP2 (or later version).
sample code:
```
using NativeWifi;
using System;
using System.Text;
namespace WifiExample
{
class Program
{
/// <summary>
/// Converts a 802.11 SS... | If the platform is Windows10, you can use `Microsoft.Windows.SDK.Contracts` package to access all available wifis.
First, install `Microsoft.Windows.SDK.Contracts` package from nuget.
Then, you can use next code to get ssid and signal strength.
```
var adapters = await WiFiAdapter.FindAllAdaptersAsync();
foreach (va... | How do I get the available wifi APs and their signal strength in .net? | [
"",
"c#",
".net",
"networking",
"mono",
"wifi",
""
] |
In general, what is the best way of storing binary data in C++? The options, as far as I can tell, pretty much boil down to using strings or vector<char>s. (I'll omit the possibility of char\*s and malloc()s since I'm referring specifically to C++).
Usually I just use a string, however I'm not sure if there are overhe... | vector of char is nice because the memory is contiguious. Therefore you can use it with a lot of C API's such as berkley sockets or file APIs. You can do the following, for example:
```
std::vector<char> vect;
...
send(sock, &vect[0], vect.size());
```
and it will work fine.
You can essentially treat it just l... | The biggest problem with std::string is that the current standard doesn't guarantee that its underlying storage is contiguous. However, there are no known STL implementations where string is not contiguous, so in practice it probably won't fail. In fact, the new C++0x standard is going to fix this problem, by mandating... | "Proper" way to store binary data with C++/STL | [
"",
"c++",
"stl",
"binary-data",
""
] |
What query do I need to run in PHP to get the structure of a given table in the database? And what query do I need to run to get a list of all the tables? | To get a list of columns for a table, use the DESCRIBE SQL statement. The syntax is as follows:
```
DESCRIBE TableName
```
To get a list of tables on the database, use this SQL statement:
```
SHOW TABLES
``` | ```
$q = mysql_query('DESCRIBE tablename');
while($row = mysql_fetch_array($q)) {
echo "{$row['Field']} - {$row['Type']}\n";
}
```
found it at <http://www.electrictoolbox.com/mysql-table-structure-describe/> | How do I get the MySQL table structure in PHP? Plus a list of all tables? | [
"",
"php",
"mysql",
""
] |
I'm a C++ programmer just starting to learn Python. I'd like to know how you keep track of instance variables in large Python classes. I'm used to having a `.h` file that gives me a neat list (complete with comments) of all the class' members. But since Python allows you to add new instance variables on the fly, how do... | First of all: class attributes, or instance attributes? Or both? =)
*Usually* you just add instance attributes in `__init__`, and class attributes in the class definition, often before method definitions... which should probably cover 90% of use cases.
If code adds attributes on the fly, it probably (hopefully :-) ha... | I would say, the standard practice to avoid this is to *not write classes where you can be 1000 lines away from anything!*
Seriously, that's way too much for just about any useful class, especially in a language that is as expressive as Python. Using more of what the Standard Library offers and abstracting away code i... | What's a good way to keep track of class instance variables in Python? | [
"",
"python",
"variables",
""
] |
Am trying to implement a **generic way for reading sections** from a config file. The config file may contain 'standard' sections or 'custom' sections as below.
```
<configuration>
<configSections>
<section name="NoteSettings" type="System.Configuration.NameValueSectionHandler"/>
</configSections>
<appSettings... | Since configuration file is XML file, you can use XPath queries for this task:
```
Configuration configFile = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);
XmlDocument document = new XmlDocument();
document.Load(configFile.FilePath);
foreach (XmlNode node in docum... | Read your config into a XmlDocument then use XPath to find the elements your looking for?
Something like;
```
XmlDocument doc = new XmlDocument();
doc.Load(HttpContext.Current.Server.MapPath("~/web.config"));
XmlNodeList list = doc.SelectNodes("//configuration/appSettings");
foreach (XmlNode node in list[0].ChildNo... | Generic method for reading config sections | [
"",
"c#",
".net",
"version-control",
""
] |
I have a simple table with 6 columns. Most of the time any insert statements to it works just fine, but once in a while I'm getting a DB Timeout exception:
Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. The statement has been terminated.
Timeout is set... | Our QA had some Excel connections that returned big result sets, those queries got suspended with WaitType of ASYNC\_NETWORK\_IO for some time. During this time all other queries timed out, so that specific insert had nothing to do with it. | I think your most likely culprit is a blocking lock from another transaction (or maybe from a trigger or something else behind the scenes).
The easiest way to tell is to kick off the `INSERT`, and while it's hung, run `EXEC SP_WHO2` in another window on the same server. This will list all of the current database activ... | SQL Server simple Insert statement times out | [
"",
"sql",
"sql-server",
"database",
"nhibernate",
"timeout",
""
] |
I hate the JavaBeans pattern with a passion that burns like the fire of a thousand suns. Why?
* **Verbose**. It's 2009. I shouldn't have to write 7 LOC for a property. If they have event listeners then hold on to your hat.
* **No type-safe references**. There is no type-safe way to reference a property. The whole poin... | I think you're pretty close with the declaration you have there (see below for a sketch). However, by using a non-beans approach, you'll probably lose support provided by most tools that assume the JavaBeans protocol is in effect. Please be kind. The code below is off the top of my head...
```
public class Property<T>... | Check out my Bean annotations at
<http://code.google.com/p/javadude/wiki/Annotations>
Basically you do things like:
```
@Bean(
properties={
@Property(name="name"),
@Property(name="phone", bound=true),
@Property(name="friend", type=Person.class, kind=PropertyKind.LIST)
}
)
public class Person extends ... | JavaBeans alternatives? | [
"",
"java",
"properties",
"javabeans",
""
] |
I need an advice for a c# asp.net project.
My client wants to see some reports via the gridview object with master/detail structure.
The main gridview will be full by all master data and each row will have a **+** icon (or button) on the first cells.
When user clicks this icon, the all details data of that master row ... | Thanks but its for updating or inserting.
Instead , i have found that page, it seems more effective.
[GridView control to show master-child or master-slave data, written in c#, asp.net, and javascript.](http://www.progtalk.com/ViewArticle.aspx?ArticleID=54) | [Matt Berseth](http://mattberseth.com/) has one of the most impresive tutorials on this kind'a stuff
it contains til now [28 tutorials](http://mattberseth.com/blog/gridview/) only on the GridView plus a lot from other asp.net controls as well using jQuery with them. I do learn plenty with him. I really love his work a... | collapsable master detail gridview structure | [
"",
"c#",
"asp.net",
"ajax",
"asp.net-ajax",
""
] |
I've compiled my Python program using Py2Exe, and on the client's computer we've satisfied all the dependencies using dependency walker, but we still get "The application configuration is incorrect. Reinstalling the application may correct the problem." I'm also using wxPython.
The client does not have administrator a... | I've ran into this myself and my random Googling has pointed me to several people saying to downgrade python 2.6 to 2.5, which worked for me. | Give [GUI2exe](http://code.google.com/p/gui2exe/) a shot; it's developed by Andrea Gavana who's big in the wxpython community and wraps a bunch of the freezers, including py2exe. It's likely a dll issue, try [searching the wxpython list archive](http://www.google.com/search?hl=en&client=firefox-a&rls=org.mozilla%3Aen-U... | Py2Exe - "The application configuration is incorrect." | [
"",
"python",
"wxpython",
"compilation",
"py2exe",
""
] |
```
Patient
-------
PatientID
Visit
-----
VisitID
PatientID
HeartRate
VisitDate
```
How do I select all of the patients who have a visit, the date of their **first** visit, and their heart rate at that **first** visit? | ```
SELECT
p.PatientID,
v.VisitID,
v.HeartRate,
v.VisitDate
FROM
Patient p
INNER JOIN Visit v ON p.PatientID = v.PatientID
WHERE
v.VisitDate = (
SELECT MIN(VisitDate)
FROM Visit
WHERE PatientId = p.PatientId
)
```
---
EDIT: Alternative version. Same thing. (less obvious, therefore less d... | Is this what you want?
Of course the join isn't really necessary here since there are no extra fields in Patient. But I guess IRL there are.
```
select PatientId, HeartRate, VisitDate from Patient p
left join Visit v on p.PatientID = v.PatientId
``` | Query help for someone who has been using Linq-to-Sql too much lately | [
"",
"sql",
""
] |
I am playing with Google App Engine and Python and I cannot list the files of a static directory. Below is the code I currently use.
**app.yaml**
```
- url: /data
static_dir: data
```
**Python code to list the files**
```
myFiles = []
for root, dirs, files in os.walk(os.path.join(os.path.dirname(__file__), 'data/... | <https://developers.google.com/appengine/docs/python/config/appconfig#Python_app_yaml_Static_file_handlers>
They're not where you think they are, GAE puts static content into GoogleFS which is equivalent of a CDN. The idea is that static content is meant to be served directly to your users and not act as a file store ... | Here´s a project that let you browse your static files:
<http://code.google.com/p/appfilesbrowser/>
And here is must see list of recipes for appengine:
<http://appengine-cookbook.appspot.com/>
(I found about that project here sometime ago) | How to list the files in a static directory? | [
"",
"python",
"google-app-engine",
""
] |
I have a list of non-overlaping ranges (ranges of numbers, e.g. 500-1000, 1001-1200 .. etc), is there an elegant and fast way to do lookup by only passing a number? I could use List.BinarySearch() or Array.BinarySearch() but I have to pass the type of the range object (Array.BinarySearch(T[], T)), I can pass a dummy ra... | Three options:
* Create a dummy Range and suck it up. Urgh.
* Hand-craft a binary search just for this case. Not too bad.
* Generalise the binary search for any IList and a TValue, given an IRangeComparer. I'm not wild on the name "TRange" here - we're not necessarily talking about ranges, but just finding the right p... | If you have .Net 3.5 or above, try
```
foundRange = yourList.Where(range =› range.BottomNumber ‹= searchInt && range.TopNumber ›= searchInt).FirstOrDefault();
``` | Doing a range lookup in C#? | [
"",
"c#",
""
] |
I want customers to use their openId on my site. I googled for this but didn't find any good tutorial. I use PHP and MySQL.
There is one at Plaxo. But it says we should download something from JanRain.com.
I saw the openId module of Drupal. It doesn't want anything to be downloaded.
Can anyone tell me what to do exa... | Many decent libraries are listed here:
<http://wiki.openid.net/Libraries> | Stack Overflow uses this library for the smoking hot javascript interface: <http://code.google.com/p/openid-selector/> | How do you enable customers use their openid on your website, just like stackoverflow? | [
"",
"php",
"mysql",
"openid",
""
] |
I'm writing a little utility that starts with selecting a file, and then I need to select a folder. I'd like to default the folder to where the selected file was.
`OpenFileDialog.FileName` returns the **full path & filename** - what I want is to obtain just the **path portion (sans filename)**, so I can use that as th... | Use the [`Path`](http://msdn.microsoft.com/en-us/library/system.io.path.aspx) class from [`System.IO`](http://msdn.microsoft.com/en-us/library/system.io.aspx). It contains useful calls for manipulating file paths, including [`GetDirectoryName`](http://msdn.microsoft.com/en-us/library/system.io.path.getdirectoryname.asp... | how about this:
```
string fullPath = ofd.FileName;
string fileName = ofd.SafeFileName;
string path = fullPath.Replace(fileName, "");
``` | Extracting Path from OpenFileDialog path/filename | [
"",
"c#",
".net",
"parsing",
"path",
""
] |
Which class hierarchy is most necessary in order to get an excellent grasp of C#, for the aspiring C# desktop applications programmer? Not just the totally obvious stuff.
**EDIT:** To clarify, I mean, that as I am learning C#, I would like to know what are the classes I should be acquainted with, which aren't necessar... | Just found this link in another thread: [map](http://www.geekpedia.com/gallery/fullsize/net-framework-3.5-types-and-namespaces-poster.jpg)
Also, download [Reflector](http://www.red-gate.com/products/reflector/) and browse through the .NET Framework classes, starting with mscorlib.dll and System.dll. | System.Collections
System.Data (many apps have a database backend)
System.Windows (as it's a desktop app)
System.Graphics (as above)
System.Diagnostics (provides various objects and methods useful for logging and when debugging, always important in commercial code).
These namespaces contain important classes to do... | What are the core classes In C#? | [
"",
"c#",
".net",
""
] |
The general rule is that I want to say, "T has a method with a String parameter which will return List." Put verbosely, we might call the interface ICanCreateListOfObjectsFromString. A possible application might be search.
It feels like it'd be nice to have a static method in my interface, but I know that's not allowe... | Sounds like you're trying to implement a Mixin... Something of that sort exists in C# 3.0, and they are named "Extension Methods".
What do allow you to do? Well, they allow you to create functions that work in types that you specify, and "add" methods to them. Since that type can be an interface, this lets you define ... | Maybe the [factory pattern](http://en.wikipedia.org/wiki/Factory_method_pattern) is what you’re looking for. | How to setup an Object Creation Interface "rule" in C#? | [
"",
"c#",
"class",
"oop",
"interface",
"static-methods",
""
] |
How do you programmatically upload a file to a document library in sharepoint?
I am currently making a Windows application using C# that will add documents to a document library list. | You can upload documents to SharePoint libraries using the Object Model or [SharePoint Webservices](http://msdn.microsoft.com/en-us/library/lists.lists.aspx).
Upload using Object Model:
```
String fileToUpload = @"C:\YourFile.txt";
String sharePointSite = "http://yoursite.com/sites/Research/";
String documentLibraryN... | if you get this error "**Value does not fall within the expected range**" in this line:
```
SPFolder myLibrary = oWeb.Folders[documentLibraryName];
```
use instead this to fix the error:
```
SPFolder myLibrary = oWeb.GetList(URL OR NAME).RootFolder;
```
Use always URl to get Lists or others because they are unique,... | How do you upload a file to a document library in sharepoint? | [
"",
"c#",
"sharepoint",
"upload",
""
] |
I have some windows services written in C#. When somebody stops or starts the service, I would like to be able to determine who it was and log that information.
I tried logging `Environment.UserName` but that evaluates to SYSTEM even on my local machine.
Also, for the time being these services are running on Windows ... | Within the Event Viewer (Control Panel | Administrative Tools | Event Viewer) on the System tab the Service Control Manager logs who started and stop each event. I've just tested this myself and viewed the results. This leads me to two things:
1. You may be able to query or hook those events from the Service Control M... | * You can filter the System EventLog by Service Control Manager
[](https://i.stack.imgur.com/xpcxp.png)
Event ID 7040 - covers Service start type change (eg disabled, manual, automatic)
Event ID 7036 - covers Service start/stop
[![enter image desc... | Is it possible to log who started or stopped a windows service? | [
"",
"c#",
"windows-services",
""
] |
I have the following text:
```
<i><b>It is noticeably faster.</b></i> <i><b>They take less disk space.</i>
```
And the following regex:
```
(</[b|i|u]>)+(\s*)(<[b|i|u]>)+
```
The matching creates the following groups:
```
0: </b></i> <b><i>
1: </i>
2: spaces
3: <b>
```
How can I change my regex so it creates gr... | I suspect you've already got what you need - you just need to enumerate the captures for each group. Here's a sample program showing that in action:
```
using System;
using System.Text.RegularExpressions;
class Test
{
static void Main()
{
string text =
"<i><b>It is noticeably faster.</b></i> <i><b>Th... | You can't. A group can only hold one thing, even if it hits more than one thing in the same match because of a +, \*, or similar. You could, of course, use a regex or similar on that group to get the individual items.
Thus, every match will have exactly one thing per group. | Regex: Why no group for every found item? | [
"",
"c#",
"regex",
""
] |
I read that you should define your JavaScript functions in the `<head>` tag, but how does the location of the `<script>` (whether in the `<head>`, `<body>`, or any other tag) affect a JavaScript function.
Specifically, how does it affect the scope of the function and where you can call it from? | Telling people to add `<SCRIPT>` only in the head **sounds** like a reasonable thing to do, but as others have said there are many reasons why this isn't recommended or even practical - mainly speed and the way that HTML pages are generated dynamically.
This is what the [HTML 4 spec says](http://www.w3.org/TR/REC-html... | The normal rules of play still stand; don't use stuff before it's defined. :)
Also, take note that the 'put everything at the bottom' advice isn't *the* only rule in the book - in some cases it may not be feasible and in other cases it may make more sense to put the script elsewhere.
The main reason for putting a scr... | How does the location of a script tag in a page affect a JavaScript function that is defined in it? | [
"",
"javascript",
"html",
"function",
"tags",
""
] |
How do I connect to a remote URL in Java which requires authentication. I'm trying to find a way to modify the following code to be able to programatically provide a username/password so it doesn't throw a 401.
```
URL url = new URL(String.format("http://%s/manager/list", _host + ":8080"));
HttpURLConnection connectio... | You can set the default authenticator for http requests like this:
```
Authenticator.setDefault (new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication ("username", "password".toCharArray());
}
});
```
Also, if you require more flexibilit... | There's a native and less intrusive alternative, which works only for your call.
```
URL url = new URL(“location address”);
URLConnection uc = url.openConnection();
String userpass = username + ":" + password;
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes()));
uc.setRequestPrope... | Connecting to remote URL which requires authentication using Java | [
"",
"java",
"httpurlconnection",
""
] |
I am a newbie to Python and have come across the following example in my book that is not explained very well. Here is my print out from the interpreter:
```
>>> s = 'spam'
>>> s[:-1]
'spa'
```
Why does slicing with no beginning bound and a `'-1'` return every element except the last one? Is calling `s[0:-1]` logical... | Yes, calling `s[0:-1]` is exactly the same as calling `s[:-1]`.
Using a negative number as an index in python returns the nth element from the right-hand side of the list (as opposed to the usual left-hand side).
so if you have a list as so:
```
myList = ['a', 'b', 'c', 'd', 'e']
print myList[-1] # prints 'e'
```
t... | ```
>>> l = ['abc', 'def', 'ghi', 'jkl', 'mno', 'pqr', 'stu', 'vwx', 'yz&']
# I want a string up to 'def' from 'vwx', all in between
# from 'vwx' so -2;to 'def' just before 'abc' so -9; backwards all so -1.
>>> l[-2:-9:-1]
['vwx', 'stu', 'pqr', 'mno', 'jkl', 'ghi', 'def']
# For the same 'vwx' 7 to 'def' just before '... | I don't understand slicing with negative bounds in Python. How is this supposed to work? | [
"",
"python",
"slice",
""
] |
any problems with doing this?
```
int i = new StreamReader("file.txt").ReadToEnd().Split(new char[] {'\n'}).Length
``` | The method you posted isn't particularly good. Lets break this apart:
```
// new StreamReader("file.txt").ReadToEnd().Split(new char[] {'\n'}).Length
// becomes this:
var file = new StreamReader("file.txt").ReadToEnd(); // big string
var lines = file.Split(new char[] {'\n'}); // big array
var count = lin... | Well, the problem with doing this is that you allocate a *lot* of memory when doing this on large files.
I would rather read the file line by line and manually increment a counter. This may not be a one-liner but it's much more memory-efficient.
Alternatively, you may load the data in even-sized chunks and count the ... | c# how do I count lines in a textfile | [
"",
"c#",
""
] |
This is a follow-up to [Dynamic Shared Library compilation with g++](https://stackoverflow.com/q/483797/1288).
I'm trying to create a shared class library in C++ on Linux. I'm able to get the library to compile, and I can call some of the (non-class) functions using the tutorials that I found [here](https://stackoverf... | **myclass.h**
```
#ifndef __MYCLASS_H__
#define __MYCLASS_H__
class MyClass
{
public:
MyClass();
/* use virtual otherwise linker will try to perform static linkage */
virtual void DoSomething();
private:
int x;
};
#endif
```
**myclass.cc**
```
#include "myclass.h"
#include <iostream>
using namespace std... | The following shows an example of a shared class library shared.[h,cpp] and a main.cpp module using the library. It's a very simple example and the makefile could be made much better. But it works and may help you:
shared.h defines the class:
```
class myclass {
int myx;
public:
myclass() { myx=0; }
vo... | C++ Dynamic Shared Library on Linux | [
"",
"c++",
"linux",
"shared-libraries",
""
] |
I'm attempting to do something which should be relatively simple. I'm using a ListView to show a number of items, using the ItemTemplate. Inside the ItemTemplate I have a div surrounding the full item, so that I can highlight on a hover event, (being handled already by jQuery).
What I would like to do is have the clic... | Wire up a method to the [ItemDataBound](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listview.itemdatabound.aspx) event of your ListView. In there, you can use [FindControl](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listviewitem.findcontrol.aspx) method on the [Item](http://... | Why don't you just give those linkbuttons a specific css class?
```
<asp:linkbutton id="Button1" runat="server" text="View Details" CssClass="detailsButtons" />
```
Then in jquery just select the class to assign them all in one call.
```
$(".detailsButtons").click( function() { .... } );
```
If that doesn't work be... | How do I pull the clientID of an asp:button inside an asp:listview for use with jQuery? | [
"",
"c#",
"asp.net",
"jquery",
""
] |
Or: Should I optimize my string-operations in PHP? I tried to ask PHP's manual about it, but I didn't get any hints to anything. | PHP already optimises it - variables are assigned [using copy-on-write](http://php.net/debug_zval_dump), and objects are passed by reference. In PHP **4** it doesn't, but nobody should be using PHP 4 for new code anyway. | One of the most essential speed optimization techniques in many languages is instance reuse. In that case the speed increase comes from at least 2 factors:
**1. Less instantiations means less time spent on construction.**
**2. The less the amount of memory that the application uses, the less [CPU cache misses](http:/... | Are php strings immutable? | [
"",
"php",
"string",
""
] |
I am currently saving a .net ( c# ) usercontrol to the disk as a XML file by saving each property as an element in the xml document. The file is used for later recreation of the controls at runtime. I am wondering if it is possible or better to save the control as a binary file. There would be many controls so I guess ... | We had to do this for a data-driven application where a user could create persistable views. We did an XML version to start but moved to using BinaryFormatter and the ISerializable interface as this allows us to control exactly what gets persisted and which constructors to use. For the controls we actually persisted th... | Winforms controls don't serialize especially well, and you might have a lot of difficulty getting the base-classes (i.e. not your code) to play ball. Things like `Color`, for example, regularly provide surprisingly troublesome to serialize.
Xml would be an obvious (if somewhat predictable) choice, but you generally ne... | C# whats best method of saving dynamically created controls | [
"",
"c#",
".net",
""
] |
Why can't you assign a number with a decimal point to the decimal type directly without using type suffix? isn't this kind of number considered a number of type decimal?
```
decimal bankBalance = 3433.20; // ERROR!
``` | **Edit**: I may have missed the last part of the question, so the overview below is hardly useful.
Anyway, the reason you can't do what you're trying to do is because there is no implicit conversion between floating point types and `decimal`. You can however assign it from an integer, as there is an implicit conversio... | Actually, hidden spec feature: you can ;-p
```
decimal bankBalance = (decimal)3433.20;
```
This is genuinely parsed by the compiler as a decimal (not a float and a cast). See the IL to prove it. Note that the precision gets truncated, though (this has 1 decimal digit, not the 2 you get from the `M` version).
IL gene... | why can't you assign a number with a decimal point to decimal type directly without using type suffix? | [
"",
"c#",
""
] |
We have a web application that periodically sends out e-mails to users. At the moment we generate the html version and the text version in the code. However, this is cumbersome to maintain.
Is there a good e-mail template system out there that can generate both the html and text versions of an e-mail from the same tem... | You could use a utility which transforms HTML to Text in Java (Google for it, for example [this one](http://www.clapper.org/software/java/util/javadocs/util/api/org/clapper/util/html/HTMLUtil.html#makeCharacterEntities(java.lang.String))) by stripping tags and converting the special HTML chars. However, this will not g... | I would also recommend the use of a template engine. Create two templates, one for the text part and one for the HTML part. Use the include functionality of the template engine so you can re-use literal texts in both templates. | What's a good html e-mail template system that also, correctly, renders a text/plain alternative? | [
"",
"java",
"html",
"text",
"templates",
"email",
""
] |
We are looking at implementing a caching framework for our application to help improve the overall performance of our site.
We are running on Websphere 6.1, Spring, Hibernate and Oracle. The focus currently is on the static data or data that changes very little through out the day but is used a lot.
So any info would... | Well the hibernate cache system does just that, I used [ehCache](http://ehcache.sourceforge.net/) effectively and easily with [Hibernate (and the second level cache system)](http://www.hibernate.org/hib_docs/reference/en/html/performance-cache.html).
[Lucene](http://lucene.apache.org/) could be an option too depending... | Hibernate has first and second level caching built in. You can configure it to use EhCache, OSCache, SwarmCache, or C3P0 - your choice. | What caching model/framework with Websphere Spring Hibernate Oracle? | [
"",
"java",
"hibernate",
"spring",
"caching",
"websphere",
""
] |
This seems like such a trivial problem, but I can't seem to pin how I want to do it. Basically, I want to be able to produce a figure from a socket server that at any time can give the number of packets received in the last minute. How would I do that?
I was thinking of maybe summing a dictionary that uses the current... | When you say the last minute, do you mean the exact last seconds or the last full minute from x:00 to x:59? The latter will be easier to implement and would probably give accurate results. You have one prev variable holding the value of the hits for the previous minute. Then you have a current value that increments eve... | A common pattern for solving this in other languages is to let the thing being measured simply increment an integer. Then you leave it to the listening client to determine intervals and frequencies.
So you basically do *not* let the socket server know about stuff like "minutes", because that's a feature the observer c... | Python - Hits per minute implementation? | [
"",
"python",
""
] |
Is this warning anything to worry about? I've read that it can cause erratic behaviour?
It's an example I'm trying to compile, could someone explain to me why the author declares the object as a class but then typedef's it to a structure? Is it perfectly normal to do so if the class is [POD](http://en.wikipedia.org/w/... | This warning appears when you have a one type declaration that contradicts another (one says "class", the other says "struct"). Given the one definition rule, all declarations except for at most one must be forward declarations. The warning will generally indicate that a forward declaration of a type is wrong and is us... | Just to bring the comment by MSalters against [this](https://stackoverflow.com/questions/468486/warning-c4099-type-name-first-seen-using-class-now-seen-using-struct-ms-vs#468545) post above to the top level. I have had several hard to find linker errors as a result of VC using the 'class' or 'struct' keyword in its man... | Warning C4099: type name first seen using 'class' now seen using 'struct' (MS VS 2k8) | [
"",
"c++",
"compiler-warnings",
""
] |
I've just recently upgraded to using Visual Studio express editions with service pack 1. Previously I was using the express editions minus the service pack. The IDE for C++ and C# run fine for me but when running the Visual Web Developer IDE I get a crash when trying to switch to design mode on any page I attempt it on... | Well the computer has lost in the end as it always does! I found this thread to be a big help as there were a bunch of people posting with very similar issues to mine...
<http://forums.asp.net/t/1186584.aspx?PageIndex=1>
On the first page there is the following suggestion...
> Make sure Microsoft Web Authoring
> Com... | Is your installation customised in anyway? Do you have VS add-ins, etc. installed? If so, try removing them one by one and/or restore all app settings back to their defaults. I'm not so familiar with the express editions so I'm not sure what kind of customisations they support.
If all else fails, I hate to say it but.... | Visual Web Developer Express with SP1 crashing when switching to design mode | [
"",
"c#",
"asp.net",
""
] |
Im trying do this basically:
```
var tr = document.createElement("tr");
var td = document.createElement("td");
td.appendChild(document.createTextNode('<input class="param" type="text" name="dummy" value="fred"/>'));
tr.appendChild(td);
```
but it just displays the input... as normal text, how do I ins... | You could either
```
td.innerHTML = '<input class="param" type="text" name="dummy" value="fred"/>';
```
or
```
var ip = document.createElement( 'input' );
ip.className = 'param';
ip.type = 'text';
ip.name = 'dummy';
ip.value = 'fred';
td.appendChild( ip );
```
EDIT
ie won't allow the type of a form element to be ... | Try using innerHtml property of element.
That is try using `td.innerHtml = "<input ...../>"` | Add a row to a table in Javascript that contains input classes | [
"",
"javascript",
""
] |
So i am working with some email header data, and for the to:, from:, cc:, and bcc: fields the email address(es) can be expressed in a number of different ways:
```
First Last <name@domain.com>
Last, First <name@domain.com>
name@domain.com
```
And these variations can appear in the same message, in any order, all in o... | Here is the solution i came up with to accomplish this:
```
String str = "Last, First <name@domain.com>, name@domain.com, First Last <name@domain.com>, \"First Last\" <name@domain.com>";
List<string> addresses = new List<string>();
int atIdx = 0;
int commaIdx = 0;
int lastComma = 0;
for (int c = 0; c < str.Length; c+... | There is internal `System.Net.Mail.MailAddressParser` class which has method `ParseMultipleAddresses` which does exactly what you want. You can access it directly through reflection or by calling `MailMessage.To.Add` method, which accepts email list string.
```
private static IEnumerable<MailAddress> ParseAddress(stri... | Best way to parse string of email addresses | [
"",
"c#",
".net",
"parsing",
""
] |
Is there a way of getting the position (index) of an item in a CTreeCtrl?
I am interested in the index of a node at its particular level.
I was thinking to maintain the item positions within the item "data" field, but the problem is that my tree is sorted and I cannot predict the position an item will receive (well,... | I don't think you can. I assumed that maybe the control could be treated as an array (maybe it still can but I can't find a reference).
Anyways, there are no member functions (according to the [MFC API](http://msdn.microsoft.com/en-us/library/7w95665f(VS.80).aspx)) that give you access to that information | ```
/// there is another way if you "Use Unicode Character Set" (visual studio)
/// Properties->General->Character Set
CPoint point;
GetCursorPos(&point);
m_Tree.ScreenToClient(&point);
UINT nHitFlags;
HTREEITEM hItem = m_Tree.HitTest(point, &nHitFlags);
int idx = m_Tree.MapItemToAccId(hItem... | CTreeCtrl - getting an item position | [
"",
"c++",
"mfc",
""
] |
Does anybody know of a convenient means of determining if a string value "qualifies" as a floating-point number?
```
bool IsFloat( string MyString )
{
... etc ...
return ... // true if float; false otherwise
}
``` | If you can't use a Boost library function, you can write your own isFloat function like this.
```
#include <string>
#include <sstream>
bool isFloat( string myString ) {
std::istringstream iss(myString);
float f;
iss >> noskipws >> f; // noskipws considers leading whitespace invalid
// Check the entire... | You may like Boost's lexical\_cast (see <http://www.boost.org/doc/libs/1_37_0/libs/conversion/lexical_cast.htm>).
```
bool isFloat(const std::string &someString)
{
using boost::lexical_cast;
using boost::bad_lexical_cast;
try
{
boost::lexical_cast<float>(someString);
}
catch (bad_lexical_cast &)
{
... | C++ IsFloat function | [
"",
"c++",
"string",
"floating-point",
""
] |
In Twisted when implementing the dataReceived method, there doesn't seem to be any examples which refer to packets being fragmented. In every other language this is something you manually implement, so I was just wondering if this is done for you in twisted already or what? If so, do I need to prefix my packets with a ... | In the dataReceived method you get back the data as a string of indeterminate length meaning that it may be a whole message in your protocol or it may only be part of the message that some 'client' sent to you. You will have to inspect the data to see if it comprises a whole message in your protocol.
I'm currently usi... | When dealing with TCP, you should really forget all notion of 'packets'. TCP is a stream protocol - you stream data in and data streams out the other side. Once the data is sent, it is allowed to arrive in as many or as few blocks as it wants, as long as the data all arrives in the right order. You'll have to manually ... | Python/Twisted - TCP packet fragmentation? | [
"",
"python",
"tcp",
"twisted",
"packet",
""
] |
I used multiple threads in a few programs, but still don't feel very comfortable about it.
What multi-threading libraries for C#/.NET are out there and which advantages does one have over the other?
By multi-threading libraries I mean everything which helps make programming with multiple threads easier.
What .NET in... | There are various reasons for using multiple threads in an application:
* UI responsiveness
* Concurrent operations
* Parallel speedup
The approach one should choose depends on what you're trying to do. For UI responsiveness, consider using `BackgroundWorker`, for example.
For concurrent operations (e.g. a server: s... | I like this one
<http://www.codeplex.com/smartthreadpool> | Multi-threading libraries for .NET | [
"",
"c#",
".net",
"multithreading",
""
] |
I am working on an SWT project as part of a team. We are constantly breaking each others build environment because Eclipses .classpath file is checked into version control and we include different SWT libraries for our machines.
Depending on who committed last, the .classpath entry can be:
```
<classpathentry kind="l... | Eclipse will let you define classpath variables so you can keep the .classpath the same, but each developer would configure her Eclipse according to platform. You could at least then version the .classpath file. You will have to alter the directory structure of where you store your SWT jars to something where the jar n... | You should have these libraries in a separate, easily identifiable project instead of placed in each and every project.
E.g. create a project named "00-swt-provider" (so it goes on top) and let it reference one of "00-swt-provider-carbon", "00-swt-provider-win32" or "00-swt-provider-gtk".
Either of these export the a... | How can I specify an Eclipse .classpath entry for specific O/S platform? | [
"",
"java",
"eclipse",
"swt",
"classpath",
""
] |
At present I am using eclipse for JAVA project. I always wanted to use VIM for my project. Is there any good resource or tutorial that can help me? | I was a vim diehard for years (and still am). However I finally succumbed to the lure of Eclipse, and I wouldn't look back (I've had to make a sideways move to Intellij, but that's another story).
Having said that, I run Eclipse with this [Vim plugin](http://www.satokar.com/viplugin/) (note: others available), and tha... | IMHO, the built-in tutorial of vim is a very good start. I started from there and got used to the basic key bindings within a few hours. After that, it's a matter of experience and constant learning from online articles, blogs, watching-over-the-shoulder, etc., and ultimately the built-in :help command. | Any good tutorial for moving from eclipse to vim? | [
"",
"java",
"eclipse",
"vim",
"editor",
""
] |
The following query will display all Dewey Decimal numbers that have been duplicated in the "book" table:
```
SELECT dewey_number,
COUNT(dewey_number) AS NumOccurrences
FROM book
GROUP BY dewey_number
HAVING ( COUNT(dewey_number) > 1 )
```
However, what I'd like to do is have my query display the name of the author... | A nested query can do the job.
```
SELECT author_last_name, dewey_number, NumOccurrences
FROM author INNER JOIN
( SELECT author_id, dewey_number, COUNT(dewey_number) AS NumOccurrences
FROM book
GROUP BY author_id, dewey_number
HAVING ( COUNT(dewey_number) > 1 ) ) AS duplicates
ON author.i... | You probably want this
```
SELECT dewey_number, author_last_name,
COUNT(dewey_number) AS NumOccurrences
FROM book
GROUP BY dewey_number,author_last_name
HAVING ( COUNT(dewey_number) > 1 )
``` | How do I find duplicate entries in a database table? | [
"",
"sql",
"postgresql",
""
] |
I have two lists of objects. Each list is already sorted by a property of the object that is of the datetime type. I would like to combine the two lists into one sorted list. Is the best way just to do a sort or is there a smarter way to do this in Python? | People seem to be over complicating this.. Just combine the two lists, then sort them:
```
>>> l1 = [1, 3, 4, 7]
>>> l2 = [0, 2, 5, 6, 8, 9]
>>> l1.extend(l2)
>>> sorted(l1)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
```
..or shorter (and without modifying `l1`):
```
>>> sorted(l1 + l2)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
```
..eas... | > is there a smarter way to do this in Python
This hasn't been mentioned, so I'll go ahead - there is a [merge stdlib function](https://github.com/python/cpython/blob/3.7/Lib/heapq.py#L314) in the heapq module of python 2.6+. If all you're looking to do is getting things done, this might be a better idea. Of course, i... | Combining two sorted lists in Python | [
"",
"python",
"list",
"sorting",
""
] |
I have two arrays built while parsing a text file. The first contains the column names, the second contains the values from the current row. I need to iterate over both lists at once to build a map. Right now I have the following:
```
var currentValues = currentRow.Split(separatorChar);
var valueEnumerator = currentVa... | if there are the same number of column names as there are elements in each row, could you not use a for loop?
```
var currentValues = currentRow.Split(separatorChar);
for(var i=0;i<columnList.Length;i++){
// use i to index both (or all) arrays and build your map
}
``` | You've got a non-obvious pseudo-bug in your initial code - `IEnumerator<T>` extends `IDisposable` so you should dispose it. This can be very important with iterator blocks! Not a problem for arrays, but would be with other `IEnumerable<T>` implementations.
I'd do it like this:
```
public static IEnumerable<TResult> P... | How to iterate over two arrays at once? | [
"",
"c#",
"iterator",
"enumerator",
""
] |
I am writing a class that implements the following method:
```
public void run(javax.sql.DataSource dataSource);
```
Within this method, I wish to construct a Spring application context using a configuration file similar to the following:
```
<bean id="dataSource" abstract="true" />
<bean id="dao" class="my.Dao">
... | I discovered two Spring interfaces can be used to implement what I need. The [BeanNameAware](http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/beans/factory/BeanNameAware.html) interface allows Spring to tell an object its name within an application context by calling the [setBeanName(String)]... | I have been in the exact same situation. As nobody proposed my solution (and I think my solution is more elegant), I will add it here for future generations :-)
The solution consists of two steps:
1. create parent ApplicationContext and register your existing bean in it.
2. create child ApplicationContext (pass in pa... | Adding a Pre-constructed Bean to a Spring Application Context | [
"",
"java",
"spring",
""
] |
For example:
```
Queue<System.Drawing.SolidBrush> brushQ = new Queue<System.Drawing.SolidBrush>();
...
brushQ.Clear();
```
If I don't explicitly dequeue each item and dispose of them individually, do the remaining items get disposed when calling Clear()? How about when the queue is garbage collected?
Assuming the an... | When do you expect them to be disposed? How will the collection know if there are other references to the objects in it? | The generic collections don't actually know anything about the type of object they contain, so calling Clear will not cause them to call Dispose() on the items. The GC will eventually dispose of them once the collection itself gets disposed of, provided nothing else has an active reference to one of those items.
If yo... | If a generic collection is instantiated to contain iDisposable items, do the items get disposed? | [
"",
"c#",
".net",
"idisposable",
""
] |
```
class test {
public:
test &operator=(const test & other){} // 1
const test & operator+(const test& other) const {} // 2
const test & operator+(int m) {} //3
private:
int n;
};
int main()
{
test t1 , t2, t3;
// this works fine t1 = t2.operator+(t3) , calls 2 and 1
t1 = t2 + t3;
// this works fi... | Because object returned by t2+t3 is const, and you cannot call its non-const function (3).
It works fine in case of "t1 = t2 + 100 +t3;", because object returned by t2+100 is const too, but you are calling its const function (2), which is ok. | 1. Change X to test.
2. Add a semicolon to the end of the penultimate statement.
3. Remove the const from the addition operator return values as you're modifying them.
The following compiles:
```
class test {
public:
test& operator=(const test & other){} // 1
test& operator+(const X& other) const {} // 2
test&... | Operator overload | [
"",
"c++",
""
] |
I am writing a small app to teach myself ASP.NET MVC, and one of its features is the ability to search for books at Amazon (or other sites) and add them to a "bookshelf".
So I created an interface called IBookSearch (with a method DoSearch), and an implementation AmazonSearch that looks like this
```
public class Ama... | It seems that your main issue here is knowing when to write mock code. I see your point: if you haven't written the code yet, how can you mock it?
I think the answer is that you want to start your TDD with very, very simple tests, as Kent Beck does in [*Test Driven Development*](https://rads.stackoverflow.com/amzn/cli... | You'll want to write a mock when you're testing code that uses the search, not for testing the search itself.
For the class above, I might test by:
* searching for a common book and checking that is was found and is valid.
* searching for a random fixed string "kjfdskajfkldsajklfjafa" and making sure no books were fo... | TDD: How would you work on this class, test-first style? | [
"",
"c#",
"tdd",
"mocking",
"test-first",
""
] |
I have a very simple class with only one field member (e.g. String). Is it OK to implement `hashCode()` to simply return `fieldMember.hashCode()`? Or should I manipulate the field's hash code somehow? Also, if I should manipulate it, why is that? | If fieldMember is a pretty good way to uniquely identify the object, I would say yes. | Joshua Bloch lays out how to properly override equals and hashCode in "Effective Java" [Chapter 3](http://java.sun.com/developer/Books/effectivejava/Chapter3.pdf). | Implementing `hashCode()` for very simple classes | [
"",
"java",
"hashcode",
""
] |
I need to convert some files to PDF and then attach them to an email. I'm using Pear Mail for the email side of it and that's fine (mostly--still working out some issues) but as part of this I need to create temporary files. Now I could use the [tempnam()](http://au.php.net/manual/en/function.tempnam.php) function but ... | I've used uniqid() in the past to generate a unique filename, but not actually create the file.
```
$filename = uniqid(rand(), true) . '.pdf';
```
The first parameter can be anything you want, but I used rand() here to make it even a bit more random. Using a set prefix, you could further avoid collisions with other t... | Seriously, use [tempnam()](https://www.php.net/manual/en/function.tempnam.php). Yes, this creates the file, but this is a very intentional security measure designed to prevent another process on your system from "stealing" your filename and causing your process to overwrite files you don't want.
I.e., consider this se... | Unique and temporary file names in PHP? | [
"",
"php",
""
] |
in my python program to upload a file to the internet, im using a GTK progress bar to show the upload progress. But the problems that im facing is that the progress bar does not show any activity until the upload is complete, and then it abruptly indicates upload complete. im using pycurl to make the http requests...my... | I'm going to quote the [PyGTK FAQ](http://faq.pygtk.org/index.py?req=show&file=faq23.020.htp):
> You have created a progress bar inside a window, then you start running a loop that does some work:
```
while work_left:
...do something...
progressbar.set_fraction(...)
```
> You will notice that the window does... | More than likely the issue is that in your progress callback, which is where I presume you're updating the progress bar, you're not making a call to manually update the display i.e. run through the GUI's event loop. This is just speculation though, if you can provide more code, it might be easier to narrow it down furt... | Progress bar not updating during operation | [
"",
"python",
"user-interface",
"gtk",
"progress-bar",
"pygtk",
""
] |
Anyone have a regex to strip lat/long from a string? such as:
ID: 39.825 -86.88333 | ```
var latlong = 'ID: 39.825 -86.88333';
var point = latlong.match( /-?\d+\.\d+/g );
//result: point = ['39.825', '-86.88333'];
``` | To match one value
```
-?\d+\.\d+
```
For both values:
```
(-?\d+\.\d+)\ (-?\d+\.\d+)
```
And if the string always has this form:
```
"ID: 39.825 -86.88333".match(/^ID:\ (-?\d+\.\d+)\ (-?\d+\.\d+)$/)
``` | Regex to strip lat/long from a string | [
"",
"javascript",
"regex",
"geospatial",
""
] |
I am currently writing a small framework that will be used internally by other developers within the company.
I want to provide good Intellisense information, but I am not sure *how* to document thrown exceptions.
In the following example:
```
public void MyMethod1()
{
MyMethod2();
// also may throw Invalid... | You should document every exception that might be thrown by your code, including those in any methods that you might call.
If the list gets a bit big, you might want to create your own exception type. Catch all the ones you might encounter within your method, wrap them in your exception, and throw that.
Another place... | You should use the [standard xml documentation](http://msdn.microsoft.com/en-us/library/5ast78ax(VS.80).aspx).
```
/// <exception cref="InvalidOperationException">Why it's thrown.</exception>
/// <exception cref="FileNotFoundException">Why it's thrown.</exception>
/// <exception cref="DivideByZeroException">Why it's t... | How to document thrown exceptions in c#/.net | [
"",
"c#",
".net",
"documentation",
"intellisense",
""
] |
I am using System.Timers.Timer class in one of the classes in my application.
I know that Timer class has Dispose method inherited from the parent Component class that implements IDisposable interface.
Instances of the class below are created many times during my application lifecycle; each of them has an instance of T... | Generally speaking you should always dispose of disposable resources. I certainly would be looking to in the case you outline above. If you implement IDisposable on the class that implements the timer you can then use the class in a using statement, meaning resources will be explicitly released when your class is dispo... | I see that you asked this question a year ago but let me throw in my 2 cents worth. Slightly less because of inflation :). Recently I discovered in our application that we weren't disposing of timers. We had a collection of objects and each object had a timer. When we removed the item from the collection we thought it ... | Is it necessary to dispose System.Timers.Timer if you use one in your application? | [
"",
"c#",
".net",
"timer",
"dispose",
""
] |
I have a Java string of XML content. I use Velocity to generate some HTML reports, and this XML needs to be included into one of those HTML files. It would be nice if this XML is syntax colored and formatted. Does anyone know of a Java library to do this? | <https://jhighlight.dev.java.net/> | Using [XSLT and CSS by Oliver Becker](http://www2.informatik.hu-berlin.de/~obecker/XSLT/):
```
import javax.xml.transform.*;
TransformerFactory tf = TransformerFactory.newInstance();
InputStream xslt = getClass().getResourceAsStream("xmlverbatim.xsl"); // or FileInputStream
Transformer t = tf.newTransformer(new Strea... | Java library for converting XML to syntax colored HTML | [
"",
"java",
"xml",
"syntax-highlighting",
""
] |
Hi im trying to write a lockless list i got the adding part working it think but the code that extracts objects from the list does not work to good :(
Well the list is not a normal list.. i have the Interface IWorkItem
```
interface IWorkItem
{
DateTime ExecuteTime { get; }
bool Cancelled { get; }
void Ex... | The problem is your algorithm: Consider this sequence of events:
Thread 1 calls `list.Add(workItem1)`, which completes fully.
Status is:
```
first=workItem1, workItem1.next = null
```
Then thread 1 calls `list.Add(workItem2)` and reaches the spot right before the second `Replace` (where you have the comment "//lets... | So are you sure that it needs to be lockless? Depending on your work load the non-blocking solution can sometimes be slower. Check out this [MSDN article](http://msdn.microsoft.com/en-us/library/bb310595(VS.85).aspx) for a little more. Also proving that a lockless data structure is correct can be very difficult. | Lockless list help! | [
"",
"c#",
"multithreading",
"lock-free",
""
] |
I am looking to take a PDF and extract any text from it. I then want to make it available using ColdFusion's available Verity search to search the contents.
Are there any libraries out there that do this quite well already? I am including Java or .NET (Java prefered) libraries in the scope since they can be called fro... | If you have the ability to run your own software (i.e. Dedicated/VPS) then you could investigate using [Tesseract OCR](http://code.google.com/p/tesseract-ocr/) with `cfexecute` to convert the PDFs to text? | Verity should be able to index PDF files by default:
<http://livedocs.adobe.com/coldfusion/6/Developing_ColdFusion_MX_Applications_with_CFML/indexSearch2.htm#1142322> | Performing Optical Character Recognition on PDF's from ColdFusion using a Java or .NET Library? | [
"",
"java",
"pdf",
"coldfusion",
"ocr",
""
] |
Lets say I have this array,
```
int[] numbers = {1, 3, 4, 9, 2};
```
How can I delete an element by "name"? , lets say number 4?
Even `ArrayList` didn't help to delete?
```
string strNumbers = " 1, 3, 4, 9, 2";
ArrayList numbers = new ArrayList(strNumbers.Split(new char[] { ',' }));
numbers.RemoveAt(numbers.IndexOf... | ***If you want to remove all instances of 4 without needing to know the index:***
***LINQ:*** (.NET Framework 3.5)
```
int[] numbers = { 1, 3, 4, 9, 2 };
int numToRemove = 4;
numbers = numbers.Where(val => val != numToRemove).ToArray();
```
***Non-LINQ:*** (.NET Framework 2.0)
```
static bool isNotFour(int n)
{
... | ```
int[] numbers = { 1, 3, 4, 9, 2 };
numbers = numbers.Except(new int[]{4}).ToArray();
``` | How to delete an element from an array in C# | [
"",
"c#",
".net",
"arrays",
""
] |
I have an application where I need to populate a textbox with a company name and I have filled a custom AutoCompleteStringColection with all the available company names from the database. When a user enters changes the company name by typing and selecting from the list a new company name I need to have the id (Guid), o... | No, you cannot extend classes with properties. Additionally, `String` is `sealed` so you can't extend it by inheriting. The only recourse is to composition: encapsulate `string` in your own class. | It sounds like you should create your own class:
```
class Company {
public string Name {get;set;}
public override string ToString() {return Name;}
// etc
}
```
Now bind to a set of `Company` objects; the `ToString` override will ensure that the `Name` is displayed by default, and you can add whatever els... | Extending the String Class With Properties? | [
"",
"c#",
"string",
"extension-methods",
""
] |
What's the best way to pass an optional argument that is nearly always the same? Case in point is Javascript's parseInt function; the second argument for radix is optional, but to avoid a string beginning with a zero being treated as octal, it is generally recognized good practice to always specify 10 as the second arg... | I'd go with your solution - wrap it in a suitably-named function, keep it's behaviour/calling convention consistent with the library function, and use the wrapper function. | We use a lot a functions that apply a default if the passed value is null.
```
// base defaults to 10
function ParseInteger(str,base)
{
if(base==null)
base=10;
return parseInt(str,base);
}
``` | How to best pass optional function arguments that are nearly always the same | [
"",
"javascript",
"function",
""
] |
Which of the following is better?
```
a instanceof B
```
or
```
B.class.isAssignableFrom(a.getClass())
```
The only difference that I know of is, when 'a' is null, the first returns false, while the second throws an exception. Other than that, do they always give the same result? | When using `instanceof`, you need to know the class of `B` at compile time. When using `isAssignableFrom()` it can be dynamic and change during runtime. | `instanceof` can only be used with reference types, not primitive types. `isAssignableFrom()` can be used with any class objects:
```
a instanceof int // syntax error
3 instanceof Foo // syntax error
int.class.isAssignableFrom(int.class) // true
```
See [<http://java.sun.com/javase/6/docs/api/java/lang/Class.html#... | What is the difference between instanceof and Class.isAssignableFrom(...)? | [
"",
"java",
"instanceof",
"reflection",
""
] |
For C# in a winForms environment, I've licensed my classes by writing specifics to the regestry, encrypted.
Under Mono there are some facilities that are not available to you. The Registry is one of those. What method would you use to license your code under Mono?
I don't want a malicious user to be able to delete th... | The registry is available to you using the standard .Net Registry classes. You can write your encrypted values there, and retrieve them later.
However, the registry on Linux is just a file in the user's home directory, so what you can't really do is modify it from outside Mono, like from a .msi (as an example, .msi's ... | Any kind of encrypted certificate license ought to be at least as secure on Mono as it is on Windows. Deploy the app without the certificate. If it doesn't detect the certificate, its in 'reduced functionality' mode. If it does, then its in 'full mode'. Only issue certificate on purchase. For full-functionality-time-li... | How would you license your Mono code? | [
"",
"c#",
"licensing",
"mono",
""
] |
I am trying to set every row's CheckColor to *Blue* in the table tblCheckbook (why the hell do people add tbl to the start of every table, I think I know it's a table).
I'm using this query
```
UPDATE tblCheckbook
SET CheckColor = Blue
```
However, Microsoft SQL Server Management Studio Express complains In... | Try this:
```
UPDATE tblCheckbook
SET CheckColor = 'Blue'
``` | use 'Blue' not Blue | MS SQL update Query, gotta be something simple | [
"",
"sql",
"sql-server",
"t-sql",
"syntax",
""
] |
For some reason Eclipse doesn't remember source lookup path for some java projects, and every time during debugging (after redeploying) I need to press "Edit source lookup path" button and add current project to the list.
Does anyone know how to make it remember selected source location?
**EDIT:**
It is a tomcat proj... | Try looking at the Run/Debug configuration for what you are executing, and check the source tab. You can add elements manually, but that is really not recommended.
The elements in the source tab are based on the classpath of the project containing the element that you run. In the case of running tomcat, the source pat... | Solution is:
Window / Preferences
Tomcat / Source Path
Click your project name. Don't forget to change it if you cahnge to another project! | Eclipse doesn't remember source lookup path | [
"",
"java",
"eclipse",
""
] |
I'm examining the feasibility of porting an existing Windows MFC control to OS X/Carbon.
My test bed is a C++ Carbon application generated using the XCode 3 Wizard.
I'm looking for a quick way to dump some trace info to the debugger or the OS X equivalent of DbgView. On Win32 I'd use OutputDebugString() - what's the d... | There is no real equivalent. Xcode uses GDB under the hood, so you're basically dealing with that. You could, however, implement it yourself. The code sample below will produce output to standard out only when the debugger is present. You could further protect this by wrapping it in preprocessor directives as a macro a... | First off, Carbon isn't and won't be available in 64-bit. If Apple ever drops 32-bit Mac OS X (which it's safe to assume will happen sooner or later), your app will not run. Use Cocoa.
That said, there are several ways to do logging:
1. NSLog
This is a Cocoa function, but you can use it in Carbon apps, too. Link ... | OS X equivalent to OutputDebugString()? | [
"",
"c++",
"macos",
"cross-platform",
"macos-carbon",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.