Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
A long time ago when I was a young lat I used to do a lot of assembler and optimization programming. Today I mainly find myself building web apps (it's alright too...). However, whenever I create fields for database tables I find myself using values like 16, 32 & 128 for text fields and I try to combine boolean values ... | Database optimization is quite unlike machine code optimization. With databases, most of the time you want to reduce disk I/O, and wastefully trying to align fields will only make less records fit in a disk block/page. Also, if any alignment is beneficial, the database engine will do it for you automatically.
What wil... | The size of the field itself may be important, but usually for text if you use nvarchar or varchar it is not a big deal. Since the DB will take what you use. the follwoing will have a greater impact on your SQL speed:
don't have more columns then you need. bigger table in terms of columns means the database will be le... | Is there any performance reason to use powers of two for field sizes in my database? | [
"",
"sql",
"database",
"optimization",
""
] |
The IT department of a subsidiary of ours had a consulting company write them an ASP.NET application. Now it's having intermittent problems with mixing up who the current user is and has been known to show Joe some of Bob's data by mistake.
The consultants were brought back to troubleshoot and we were invited to liste... | I would agree. These guys seem quite incompetent.
(BTW, I'd check to see if in "SomeProprietarySessionManagementLookup," they're using static data. Saw this -- with behavior *exactly as you describe* on a project I inherited several months ago. It was a total head-slap moment when we finally saw it ... And wished we c... | Rule of thumb: If you need to ask if a consultant knows what he's doing, he probably doesn't ;)
And I tend to agree here. Obviously you haven't provided much, but they don't seem terribly competent. | Does This ASP.NET Consultant Know What He's Doing? | [
"",
"c#",
"asp.net",
"exception",
"session-variables",
""
] |
I'm pretty sure there should be a more Pythonic way of doing this - but I can't think of one: How can I merge a two-dimensional list into a one-dimensional list? Sort of like zip/map but with more than two iterators.
Example - I have the following list:
```
array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
```
I want to hav... | ```
[sum(a) for a in zip(*array)]
``` | [sum(value) for value in zip(\*array)] is pretty standard.
This might help you understand it:
```
In [1]: array=[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
In [2]: array
Out[2]: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
In [3]: *array
------------------------------------------------------------
File "<ipython console>", line 1
... | Merging/adding lists in Python | [
"",
"python",
"list",
""
] |
I want to find out if length property for Java arrays is an int/long or something else. | It is an int. See the [Java Language Specification](http://java.sun.com/docs/books/jls/third_edition/html/arrays.html#10.7), section 10.7. | In [Java Language spec, Arrays](http://java.sun.com/docs/books/jls/third_edition/html/arrays.html) you can see in 10.4:
> Arrays must be indexed by int values;
> short, byte, or char values may also
> be used as index values because they
> are subjected to unary numeric
> promotion and become int values.
> An attempt ... | What is the data type for length property for Java arrays? | [
"",
"java",
"types",
"limits",
""
] |
I have a large collection of static 'Utility' classes that contain very generic static methods. For example, I have a CollectionUtility class that has useful methods like:
public static void RemoveDuplicates(ICollection collection)... etc
With C# 3.0 I've been converting these to extension methods.
Now, I've heard s... | You're talking about code that would be shared library stuff. Static methods do have a place in shared libs. Check out System.Linq.Enumerable
I'd follow these guidelines:
* These aren't static methods by default. They should only be static methods because they are naturally stateless (behavior only depend on paramete... | > I've heard some talk that in an 'enterprise level' application it is often considered best practice to avoid large libraries of these static classes and methods. I imagine that it could get quite hard to maintain.
IMHO you should apply things like generics to cut down on the size of your utility methods/libraries, a... | Alternative to libraries of static classes | [
"",
"c#",
"class",
"static",
""
] |
What are some good templating engines for web designers? I definitely have my preferences as to what I'd prefer to work with as a programmer. But web designers seem to have a different way of thinking about things and thus may prefer a different system.
So:
* Web designers: what templating engine do you prefer to wor... | Look at [Mako](http://www.makotemplates.org/).
Here's how I cope with web designers.
1. Ask them to mock up the page. In HTML.
2. Use the HTML as the basis for the template, replacing the mocked-up content with `${...}` replacements.
3. Fold in loops to handle repeats.
The use of if-statements requires negotiation, ... | I had good votes when [answering this same question's duplicate](https://stackoverflow.com/questions/98245/what-is-your-single-favorite-python-templating-engine#98285).
My answer was:
[Jinja2](http://jinja.pocoo.org/2 "Jinja2 homepage").
Nice [syntax](http://jinja.pocoo.org/2/documentation/templates "template syntax... | Python templates for web designers | [
"",
"python",
"templating",
""
] |
What is the prefered method for creating a byte array from an input stream?
Here is my current solution with .NET 3.5.
```
Stream s;
byte[] b;
using (BinaryReader br = new BinaryReader(s))
{
b = br.ReadBytes((int)s.Length);
}
```
Is it still a better idea to read and write chunks of the stream? | It really depends on whether or not you can trust `s.Length`. For many streams, you just don't know how much data there will be. In such cases - and before .NET 4 - I'd use code like this:
```
public static byte[] ReadFully(Stream input)
{
byte[] buffer = new byte[16*1024];
using (MemoryStream ms = new MemoryS... | While Jon's answer is correct, he is rewriting code that already exists in `CopyTo`. So for .Net 4 use Sandip's solution, but for previous version of .Net use Jon's answer. Sandip's code would be improved by use of "using" as exceptions in `CopyTo` are, in many situations, quite likely and would leave the `MemoryStream... | Creating a byte array from a stream | [
"",
"c#",
".net-3.5",
"inputstream",
""
] |
I am wondering how I can break up my index.php homepage to multiple php pages (i.e. header.php, footer.php) and build a working index.php page using those separate php pages. I know WordPress uses this with different functions like:
```
GetHeader();
GetFoodter();
```
But when I tried to use those functions, it errors... | ```
include 'header.php';
include 'footer.php';
``` | Go with an MVC framework like Zend's. That way you'll keep more maintainable code. | Breaking up PHP Websites | [
"",
"php",
""
] |
When you lock an object is that object locked throughout the whole application?
For Example, this snippet from C# 3.0 in a Nutshell Section 19.6.1 "Thread Safety and .NET Framework Types":
```
static void AddItems( )
{
for (int i = 0; i < 100; i++)
lock (list)
list.Add ("Item " + list.Count);
... | ```
class UsefulStuff {
object _TheLock = new object { };
public void UsefulThingNumberOne() {
lock(_TheLock) {
//CodeBlockA
}
}
public void UsefulThingNumberTwo() {
lock(_TheLock) {
//CodeBlockB
}
}
}
```
`CodeBlockA` and `CodeBlockB` are pre... | One other thing to note is that static constructors ARE executed in a threadsafe way by the runtime. If you are creating a singleton and declare it as:
```
public class Foo
{
private static Foo instance = new Foo();
public static Foo Instance
{
get { return instance; }
}
}
```
Then it will be... | Does the lock(objlocker) make that object thread safe app wide? And are static members automatically thread safe? | [
"",
"c#",
"multithreading",
"thread-safety",
"static-members",
""
] |
I have a PHP script that sends critical e-mails. I know how to check whether the e-mail was sent successfully. However, is there a way to verify whether the e-mail reached its destination? | If you make the email HTML based, you can include images in it which contain URLs with information unique to the recipient. You could structure your application so that these URLs trigger some code to mark that particular email as read before returning the required image data.
To be totally effective, the images would... | Delivery Status Notification is the usual way: [http://www.sendmail.org/~ca/email/dsn.html](http://www.sendmail.org/%7Eca/email/dsn.html)
You can't tell if an email is read unless you use that microsoft email thing and the reader has not disabled read receipts.
Edit: I haven't progressed to HTML email yet so I never ... | Is there a way to determine whether an e-mail reaches its destination? | [
"",
"php",
"error-handling",
"email",
"error-detection",
""
] |
How can I get Environnment variables and if something is missing, set the value? | Use the [System.Environment](https://learn.microsoft.com/en-us/dotnet/api/system.environment) class.
The methods
```
var value = System.Environment.GetEnvironmentVariable(variable [, Target])
```
and
```
System.Environment.SetEnvironmentVariable(variable, value [, Target])
```
will do the job for you.
The optiona... | ***Get and Set***
**Get**
```
string getEnv = Environment.GetEnvironmentVariable("envVar");
```
**Set**
```
string setEnv = Environment.SetEnvironmentVariable("envvar", varEnv);
``` | How do I get and set Environment variables in C#? | [
"",
"c#",
".net",
".net-2.0",
"environment-variables",
""
] |
I have a gridview like below:
```
<asp:GridView DataKeyNames="TransactionID"
AllowSorting="True" AllowPaging="True"ID="grvBrokerage"
runat="server" AutoGenerateColumns="False"
CssClass="datatable" Width="100%"
<Columns>
<asp:BoundField Da... | When you are using an ObjectDataSource (or any other \*DataSource), you set the DataSourceID for your GridView, not the DataSource. The DataSourceID should be whatever the ID of your ObjectDataSource is. If you provide the declaration of your ObjectDataSource, I might be able to help more.
As to why your DataSource is... | Your datasource no longer exists when you're posting back.
Try creating your datasources in your Page\_Init function, then hooking your gridview up to it. Has always worked for me (Using SQLDataSources).
EDIT: Alternatively, you could re-create your datasource for the grid on each postback. That might work.
EDIT2: O... | Sorting a GridView with an ObjectDataSource is not Sorting | [
"",
"c#",
"asp.net",
""
] |
Given a class instance, is it possible to determine if it implements a particular interface? As far as I know, there isn't a built-in function to do this directly. What options do I have (if any)? | ```
interface IInterface
{
}
class TheClass implements IInterface
{
}
$cls = new TheClass();
if ($cls instanceof IInterface) {
echo "yes";
}
```
You can use the "instanceof" operator. To use it, the left operand is a class instance and the right operand is an interface. It returns true if the object implements a... | As [therefromhere](https://stackoverflow.com/users/8331/therefromhere) points out, you can use `class_implements()`. Just as with Reflection, this allows you to specify the class name as a string and doesn't require an instance of the class:
```
interface IInterface
{
}
class TheClass implements IInterface
{
}
$inte... | Checking if an instance's class implements an interface? | [
"",
"php",
"interface",
"oop",
""
] |
ok so my issue is i have the string '\222\222\223\225' which is stored as latin-1 in the db. What I get from django (by printing it) is the following string, 'ââââ¢' which I assume is the UTF conversion of it. Now I need to pass the string into a function that
does this operation:
```
strdecryptedPassword + chr(ord(c)... | Your first error 'chr() arg not in range(256)' probably means you have underflowed the value, because chr cannot take negative numbers. I don't know what the encryption algorithm is supposed to do when the inputcounter + 33 is more than the actual character representation, you'll have to check what to do in that case.
... | As Vinko notes, Latin-1 or ISO 8859-1 doesn't have printable characters for the octal string you quote. According to my notes for 8859-1, "C1 Controls (0x80 - 0x9F) are from ISO/IEC 6429:1992. It does not define names for 80, 81, or 99". The code point names are as Vinko lists them:
```
\222 = 0x92 => PRIVATE USE TWO
... | UTF-8 latin-1 conversion issues, python django | [
"",
"python",
"django",
"utf-8",
"character-encoding",
""
] |
I plan to use PyInstaller to create a stand-alone python executable. PythonInstaller comes with built-in support for UPX and uses it to compress the executable but they are still really huge (about 2,7 mb).
Is there any way to create even smaller Python executables? For example using a shrinked python.dll or something... | If you recompile pythonxy.dll, you can omit modules that you don't need. Going by size, stripping off the unicode database and the CJK codes creates the largest code reduction. This, of course, assumes that you don't need these. Remove the modules from the pythoncore project, and also remove them from PC/config.c | Using a earlier Python version will also decrease the size considerably if your really needing a small file size. I don't recommend using a very old version, Python2.3 would be the best option. I got my Python executable size to 700KB's! Also I prefer Py2Exe over Pyinstaller. | Tiny python executable? | [
"",
"python",
"executable",
"pyinstaller",
""
] |
currently i have jdbc code with the following basic stucture:
get Connection
(do the next 4 lines several times, never closing statement)
get statement
get result set
process result set
close result set
close connection
It occurred to me after writing this code that i need to close the statement.
1 what a... | The answer depends on your JDBC driver unfortunately. What you wrote there might work.
However, the general rule is that you close your statement only when you are done with the corresponding resultset.
EDIT: I realize that you had a second question where you asked about the effects of not closing the statements/Resu... | The close behavior is specified in the [JDBC Specification](http://jcp.org/aboutJava/communityprocess/final/jsr221/index.html). Closing the Connection releases all JDBC resources associated with the connection and will implicitly close all Statements, ResultSets, etc. Closing the statement will close the ResultSets.
E... | jdbc: when can i close what | [
"",
"java",
"database",
"jdbc",
""
] |
I have heard that closures could be introduced in the next Java standard that is scheduled to be released somewhere around next summer.
What would this syntax look like?
I read somewhere that introducing closures in java is a bigger change than generic was in java 5. Is this true? pros and cons?
(By now we definitel... | Have a look at <http://www.javac.info/> .
It seems like this is how it would look:
```
boolean even = { int x => x % 2 == 0 }.invoke(15);
```
where the `{ int x => x % 2 == 0 }` bit is the closure. | It really depends on what gets introduced, and indeed *whether* it will be introduced at all. There are a number of closure proposals of varying sizes.
See [Alex Miller's Java 7 page](http://tech.puredanger.com/java7#closures) for the proposals and various blog posts.
Personally I'd love to see closures - they're [be... | Closures in Java 7 | [
"",
"java",
"syntax",
"closures",
"java-7",
""
] |
I have a page where search resuts are shown both in a grid and on a map (using KML generated on the fly, overlaid on an embedded Google map). I've wired this up to work as the user types; here's the skeleton of my code, which works:
```
$(function() {
// Wire up search textbox
$('input.Search').bind("keyup", u... | Instead of calling `update()` directly, call a wrapper that checks to see if there are any pending delayed updates:
```
$('input.Search').bind("keyup", delayedUpdate);
function delayedUpdate() {
if (updatePending) {
clearTimeout(updatePending);
}
updatePending = setTimeout(update, 250);
}
functi... | As a first approach, what about something like :
```
$('input.Search').bind("keyup", function() { setTimeout(update, 5) } );
```
(not sure about the exact setTimeout syntax).
You can also keep a variable to track whether the timeout has already been scheduled or not. | How do I set up a timer to prevent overlapping ajax calls? | [
"",
"javascript",
"jquery",
""
] |
I want to get a type of a "BasePage" object that I am creating. Every Page object is based off BasePage. For instance, I have a Login.aspx and in my code-behind and a class that has a method Display:
```
Display(BasePage page) {
ResourceManager manager = new ResourceManager(page.GetType());
}
```
In my project st... | If your code-beside looks like this:
```
public partial class _Login : BasePage
{ /* ... */
}
```
Then you would get the `Type` object for it with *`typeof(_Login)`*. To get the type dynamically, you can find it recursively:
```
Type GetCodeBehindType()
{ return getCodeBehindTypeRecursive(this.GetType());
}
T... | After some additional research I found that if I call Page.GetType().BaseType it returns the code-behind type of the Aspx page. | ASP.Net and GetType() | [
"",
"c#",
"asp.net",
"reflection",
"resourcemanager",
""
] |
For instance in the snippet below - how do I access the h1 element knowing the ID of parent element (header-inner div)?
```
<div id='header-inner'>
<div class='titlewrapper'>
<h1 class='title'>
Some text I want to change
</h1>
</div>
</div>
```
Thanks! | ```
function findFirstDescendant(parent, tagname)
{
parent = document.getElementById(parent);
var descendants = parent.getElementsByTagName(tagname);
if ( descendants.length )
return descendants[0];
return null;
}
var header = findFirstDescendant("header-inner", "h1");
```
Finds the element with the... | If you were to use [jQuery](http://jquery.com/) as mentioned by some posters, you can get access to the element very easily like so (though technically this would return a collection of matching elements if there were more than one H1 descendant):
```
var element = $('#header-inner h1');
```
Using a library like JQue... | How to access HTML element without ID? | [
"",
"javascript",
"dom",
"xhtml",
""
] |
I'm working through some homework and a question on a previous exam paper asks to name all of the abstract classes in a given UML diagram. Fairly straightforward, I suppose. There are one abstract class and three interfaces. Do these interfaces qualify as abstract classes, in general? | Thing is, while technically interfaces may be represented as classes in languages like Java, I wouldn't consider them classes.
Abstract? Hell yes. Class? No.
Interfaces cannot have constructors, neither properties, fields, function bodies, etc. Interfaces cannot be inherited, they are implemented (again, technically ... | All interface are [indeed abstract](http://en.wikipedia.org/wiki/Interface_(Java))
Actually, you can declare an method as abstract within an interface... except any 'checkstyle' tool will tell you the abstract keyword is redundant. And all methods are public.
If a class implements an interface and does not implement ... | Is a Java interface an abstract class? | [
"",
"java",
"oop",
"interface",
"abstract-class",
""
] |
I've previously used [`jquery-ui tabs`](https://jqueryui.com/tabs/) extension to load page fragments via `ajax`, and to conceal or reveal hidden `div`s within a page. Both of these methods are well documented, and I've had no problems there.
Now, however, I want to do something different with tabs. When the user selec... | I would take a look at the [events](http://docs.jquery.com/UI/Tabs#Events) for Tabs. The following is taken from the jQuery docs:
```
$('.ui-tabs-nav').bind('tabsselect', function(event, ui) {
ui.options // options used to intialize this widget
ui.tab // anchor element of the selected (clicked) tab
ui.... | in jQuery UI - v1.9.2
```
ui.newTab.index()
```
to get a base 0 index of active tab | jQuery tabs - getting newly selected index | [
"",
"javascript",
"jquery",
"jquery-ui",
"jquery-plugins",
"jquery-ui-tabs",
""
] |
I regularly want to check if an object has a member or not. An example is the creation of a singleton in a function. For that purpose, you can use `hasattr` like this:
```
class Foo(object):
@classmethod
def singleton(self):
if not hasattr(self, 'instance'):
self.instance = Foo()
re... | These are two different methodologies: №1 is LBYL (look before you leap) and №2 is EAFP (easier to ask forgiveness than permission).
Pythonistas typically suggest that EAFP is better, with arguments in style of "what if a process creates the file between the time you test for it and the time you try to create it yours... | I just tried to measure times:
```
class Foo(object):
@classmethod
def singleton(self):
if not hasattr(self, 'instance'):
self.instance = Foo()
return self.instance
class Bar(object):
@classmethod
def singleton(self):
try:
return self.instance
... | Checking for member existence in Python | [
"",
"python",
"exception",
"introspection",
"hasattr",
""
] |
I'm writing a construct in PHP where a parser determins which function to call dynamically, kind of like this:
```
// The definition of what to call
$function_call_spec = array( "prototype" => "myFunction",
"parameters" => array( "first_par" => "Hello",
... | You should use [`call_user_func_array`](http://php.net/call_user_func_array) which can call any function or method and takes parameteres from an array.
Alternatively you can use [`ReflectionFunction::invokeArgs`](http://php.net/manual/en/language.oop5.reflection.php#language.oop5.reflection.reflectionfunction), but th... | ```
call_user_func_array($funcPrototype, $function_call_spec["parameters"]);
```
You might want to create a wrapper that names the function to your preference, such as:
```
function InvokeFunction($function, $args = array()) {
return call_user_func_array($function, (array)$args);
}
```
With this function you can... | Using function prototypes dynamically in PHP | [
"",
"php",
"function-calls",
""
] |
I created the setup project for the application and I can see that the later modifications of the configuration file (Application.exe.config) don't affect the application execution.
I am developing an application with the database file included and I want to enable users to move the database file and modify connection... | It should work, provided that you use the exact same connection string setting in your DB access DLL's Settings.settings file and in your application's config file.
An example that works well for me:
```
<connectionStrings>
<add name="YourApp.Properties.Settings.DatabaseConnectionString"
connectionString="Data S... | Have you checked out using a [UDL file](http://support.microsoft.com/kb/308426)?
If you save your connection string in the udl file, the user can change the connection via an interface by simply double clicking that file.
You can set your connection string in the app to point to the udl file.
You can also launch the ud... | Connection Strings modification after the deployment | [
"",
"c#",
".net",
"database",
"deployment",
"sql-server-express",
""
] |
I need a tool that handle both on-screen and printed reports, via my C# application.
I'm looking for simple, standard and powerful.
I need to be able to give the user the ability to select which columns to display, formatting, etc... with my own GUI and dynamically build the report based upon their choices. Crystal d... | We use SQL reporting services. HTML reports have their place but you dont get very much controlling over formatting.
SQL reporting services summary:
Advantages:
Basic version is free
Included with SQL express
Many exporting options pdf, html, csv etc
Can use many different datasources
Webservice which expos... | Check out the Report Viewer stuff in studio 2008 / .NET 3.5
This amazing site has the full scoop:
[GotReportViewer](http://www.gotreportviewer.com/)
It's a nice build in reporting system that will show a report and print. It's not full blown like Crystal or SQL Reporting Services. If all you need is some lightweight ... | What is the reporting tool that you would use? | [
"",
"c#",
"printing",
"report",
""
] |
I've been reading about thread-safe singleton patterns here:
<http://en.wikipedia.org/wiki/Singleton_pattern#C.2B.2B_.28using_pthreads.29>
And it says at the bottom that the only safe way is to use pthread\_once - which isn't available on Windows.
Is that the **only** way of guaranteeing thread safe initialisation?
... | If you are are using Visual C++ 2005/2008 you can use the double checked locking pattern, since "[volatile variables behave as fences](http://en.wikipedia.org/wiki/Double-checked_locking#Usage_in_Microsoft_Visual_C.2B.2B)". This is the most efficient way to implement a lazy-initialized singleton.
From [MSDN Magazine:]... | A simple way to guarantee **cross-platform thread safe initialization of a singleton** is to perform it explicitly (via a call to a static member function on the singleton) in the main thread of your application **before** your application starts any other threads (or at least any other threads that will access the sin... | How can I create a thread-safe singleton pattern in Windows? | [
"",
"c++",
"windows",
"singleton",
""
] |
I have a models `A` and `B`, that are like this:
```
class A(models.Model):
title = models.CharField(max_length=20)
(...)
class B(models.Model):
date = models.DateTimeField(auto_now_add=True)
(...)
a = models.ForeignKey(A)
```
Now I have some `A` and `B` objects, and I'd like to get a query that selects al... | Sounds like a job for [`extra`](http://docs.djangoproject.com/en/dev/ref/models/querysets/#extra-select-none-where-none-params-none-tables-none-order-by-none-select-params-none).
```
A.objects.extra(
select={
'b_count': 'SELECT COUNT(*) FROM yourapp_b WHERE yourapp_b.a_id = yourapp_a.id',
},
where=... | The question and selected answer are from 2008 and since then this functionality has been integrated into the django framework. Since this is a top google hit for "django filter foreign key count" I'd like to add an easier solution with a recent django version using [Aggregation](https://docs.djangoproject.com/en/dev/t... | Django models - how to filter number of ForeignKey objects | [
"",
"python",
"django",
"database-design",
""
] |
What are the correct version numbers for C#? What came out when? Why can't I find any answers about ***C# 3.5***?
This question is primarily to aid those who are searching for an answer using an incorrect version number, e.g. ***C# 3.5***. The hope is that anyone failing to find an answer with the wrong version number... | # C# language version history:
These are the [versions of C#](https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-version-history) known about at the time of this writing:
* **C# 1.0** released with .NET 1.0 and VS2002 (January 2002)
* **C# 1.2** (bizarrely enough); released with .NET 1.1 and VS2003 (Apr... | This is the same as most answers here, but tabularized for ease, and it has **Visual Studio** and **.NET** versions for completeness.
| C# version | VS version | .NET version | CLR version | Release date |
| --- | --- | --- | --- | --- |
| 1.0 | 2002 | 1.0 | 1.0 | Feb 2002 |
| 1.2 | 2003 | 1.1 | 1.1 | Apr 2003 |
| 2.0... | What are the correct version numbers for C#? | [
"",
"c#",
".net",
"visual-studio",
".net-core",
".net-framework-version",
""
] |
Given the string "ThisStringHasNoSpacesButItDoesHaveCapitals" what is the best way to add spaces before the capital letters. So the end string would be "This String Has No Spaces But It Does Have Capitals"
Here is my attempt with a RegEx
```
System.Text.RegularExpressions.Regex.Replace(value, "[A-Z]", " $0")
``` | The regexes will work fine (I even voted up Martin Browns answer), but they are expensive (and personally I find any pattern longer than a couple of characters prohibitively obtuse)
This function
```
string AddSpacesToSentence(string text, bool preserveAcronyms)
{
if (string.IsNullOrWhiteSpace(text))
... | Your solution has an issue in that it puts a space before the first letter T so you get
```
" This String..." instead of "This String..."
```
To get around this look for the lower case letter preceding it as well and then insert the space in the middle:
```
newValue = Regex.Replace(value, "([a-z])([A-Z])", "$1 $2");... | Add spaces before Capital Letters | [
"",
"c#",
"regex",
"string",
""
] |
I'm doing some shennanigans with jQuery to put little plus/minus icons next to my expanders. Its similar to the windows file trees, or firebugs code expanders.
It works, but its not specific enough.
Hopefully this makes sense...
```
$('div.toggle').hide();//hide all divs that are part of the expand/collapse
$('ul.pr... | ```
$(this).contents('img.expander')
```
This is what you want. It will select all of the nodes that are children of your list. In your case, all of your images are nested inside of the list element, so this will filter out only what you want. | How about making your click event toggle a CSS class on a parent item (in your case, perhaps the ul.product-info). Then you can use CSS background properties to change the background image for a <span> instead of using a literal <img> and trying to fiddle with the src. You would also be able to accomplish a showing and... | Open/Close Icons | [
"",
"javascript",
"jquery",
"html",
"dom",
""
] |
I'm programming something that allows users to store documents and pictures on a webserver, to be stored and retrieved later. When users upload files to my server, PHP tells me what filetype it is based on the extension. However, I'm afraid that users could rename a zip file as somezipfile.png and store it, thus keepin... | [Magic number](http://en.wikipedia.org/wiki/Magic_number_(programming)#Magic_numbers_in_files). If you can read first few bytes of a binary file you can know what kind of file it is. | Check out the [FileInfo](http://php.net/manual/en/book.fileinfo.php) PECL extension for PHP, which can do the MIME magic lookups for you. | How do I tell if someone's faking a filetype? (PHP) | [
"",
"php",
"upload",
"mime-types",
"file-type",
""
] |
I have an import-from-excel script as part of a CMS that previously ran without issue.
My shared-hosting provider has recently upgraded their infrastructure, including PHP from 5.1 to 5.2.6, and the script now returns "Uninitialized string offset: -XXX in /path/scriptname.php on line 27" (XXX being a decreasing number... | > Uninitialized string offset:
... means that `$data` is not an array. | Solved here:
<http://www.phpbuilder.com/board/archive/index.php/t-10328608.html> | Uninitialized string offset error from PHP import script | [
"",
"php",
"apache",
"web-hosting",
""
] |
What is a fast way to select a random row from a large mysql table?
I'm working in php, but I'm interested in any solution even if it's in another language. | Grab all the id's, pick a random one from it, and retrieve the full row.
If you know the id's are sequential without holes, you can just grab the max and calculate a random id.
If there are holes here and there but mostly sequential values, and you don't care about a slightly skewed randomness, grab the max value, ca... | I knew there had to be a way to do it in a single query in a fast way. And here it is:
A fast way without involvement of external code, kudos to
<http://jan.kneschke.de/projects/mysql/order-by-rand/>
```
SELECT name
FROM random AS r1 JOIN
(SELECT (RAND() *
(SELECT MAX(id)
... | quick selection of a random row from a large table in mysql | [
"",
"mysql",
"sql",
"select",
"random",
""
] |
Am I safe in casting a C++ bool to a Windows API BOOL via this construct
```
bool mybool = true;
BOOL apiboolean = mybool ? TRUE : FALSE;
```
I'd assume this is a yes because I don't see any obvious problems but I wanted to take a moment to ask only because this may be more subtle than it appears.
*Thanks to Dima fo... | Do you mean
```
bool b;
...
BOOL apiboolean = b ? TRUE : FALSE;
```
If so, then yes, this will work. | Yes, that will work, but
```
bool b;
...
BOOL apiboolean = (BOOL) b;
```
should work just as well, as does the reverse:
```
bool bb = (bool) apiboolean;
``` | How do I cast a bool to a BOOL? | [
"",
"c++",
"winapi",
"casting",
"boolean",
""
] |
A pattern that's started to show up a lot in one of the web apps I'm working are links that used to just be a regular a-tag link now need a popup box asking "are you sure?" before the link will go. (If the user hits cancel, nothing happens.)
We've got a solution that works, but somehow we're a web app shop without a J... | **Unobtrusive Javascript**
The best practice is to add event handler methods to the links.
The *confirm()* function produces the dialog box you described, and returns true or false depending on the user's choice.
Event handler methods on links have a special behavior, which is that they kill the link action if they ... | Here's how we've been doing it:
```
<a href="#" onClick="goThere(); return false;">Go to new page</a>`
function goThere()
{
if( confirm("Are you sure?") )
{
window.location.href="newPage.aspx";
}
}
```
(EDIT: Code reformatted to avoid horizontal scroll) | What's the best way to replace links with JS functions? | [
"",
"javascript",
""
] |
I've got a Repeater and its SqlDatasource nested inside a Gridview TemplatedField.
The Repeater's datasource SelectCommand is set using the FormatString of an Eval from the Gridview.
The SelectCommand has a WHERE clause which is to compare a string.
Because I have already used the single and double quotes, I am h... | Don't forget that a .aspx page is simply XML. You just escape the quotes as you normally would.
For example:
```
<asp:Repeater ID="repeatTheLabel" runat="server">
<ItemTemplate>
<asp:Label ID="Label1" Text="<%# Eval("Id", "This is item '{0}'.") %>" runat="server" />
</ItemTemplate>... | Why don't you define this WHERE clause as a const in your codebehind. Define:
```
protected const string SELECTCLAUSE =
"SELECT Blah FROM TableName WHERE (StringField = '{0}')";
```
Then your SelectCommand property would be:
```
SelectCommand='<%# Eval("Bar", SELECTCLAUSE ) %>'
``` | How to use Single Quotes in Eval Format String | [
"",
"asp.net",
"sql",
"eval",
"string-formatting",
""
] |
In oracle, I want to create a delete sproc that returns an integer based on the outcome of the deletion.
this is what i have so far.
```
create or replace
PROCEDURE Testing
(
iKey IN VARCHAR2
)
AS
BEGIN
delete from MyTable WHERE
TheKey = iKey;
END Testing;
```
i've tried putting a RETURNS INTEGER in but th... | Use a function and the implicit SQL cursor to determine the number of rows deleted
```
create or replace
FUNCTION Testing
(
iKey IN VARCHAR2
) RETURN INTEGER
AS
BEGIN
delete from MyTable WHERE
TheKey = iKey;
RETURN SQL%ROWCOUNT;
END Testing;
```
That should work | A procedure does not return a value. A function returns a value, but you shouldn't be doing DML in a function (otherwise you cannot do things like reference the function in a SQL statement, you confuse permission grants since normally DBAs want to be able to grant read-only users access to all the functions so that use... | oracle procedure returns integer | [
"",
"sql",
"oracle",
""
] |
Does Eclipse have a feature that lets you search a project to find all calls to deprecated methods? | You can set the compiler to generate errors or warnings (your choice) for any usage of deprecated API.
> Preferences -> Java -> Compiler -> Errors/Warnings -> *Deprecated and restricted API* section.
Then, each use of a deprecated method or API will show up as an error/warning in the Problems view. | *[Updating eight years later, for current versions of Eclipse, with screenshots.]*
**First, build your projects.** Once you've built your projects, the Problems view includes deprecations by default. You can group all the deprecations together.
**To show the Problems view,** use *Window>Show View>Problems*.
**If dep... | Can Eclipse Be Used To Find All Deprecated Method Calls? | [
"",
"java",
"eclipse",
"ide",
""
] |
Is there a way to declare a variable as Nullable in c#?
```
struct MyStruct {
int _yer, _ner;
public MyStruct() {
_yer = Nullable<int>; //This does not work.
_ner = 0;
}
}
``` | \_yer must be declare as int? or Nullable<int>.
```
int? _yer;
int _ner;
public MyStruct(int? ver, int ner) {
_yer = ver;
_ner = ner;
}
}
```
Or like this:
```
Nullable<int> _yer;
int _ner;
public MyStruct(Nullable<int> ver, int ner) {
_yer = ver;
_ner ... | Try declaring your variable like this:
```
int? yer;
``` | Initialising a struct variable to Nullable<int> | [
"",
"c#",
".net",
"nullable",
""
] |
What is the purpose of the colon before a block in Python?
Example:
```
if n == 0:
print "The end"
``` | The colon is there to declare the start of an indented block.
Technically, it's not necessary; you could just indent and de-indent when the block is done. However, based on the [Python koan](http://www.python.org/dev/peps/pep-0020/) “explicit is better than implicit” (EIBTI), I believe that Guido deliberately made the... | Consider the following list of things to buy from the grocery store, written in Pewprikanese.
```
pewkah
lalala
chunkykachoo
pewpewpew
skunkybacon
```
When I read that, I'm confused, Are chunkykachoo and pewpewpew a kind of lalala? Or what if chunkykachoo and pewpewpew are indented just because they are speci... | What is the purpose of the colon before a block in Python? | [
"",
"python",
"syntax",
""
] |
Is it better to learn how to code AJAX without the use of an AJAX library? What are the advantages of coding from scratch over using a library such as jQuery?
### See also:
[What are some of the pros and cons of using jQuery?](https://stackoverflow.com/questions/122902/what-are-some-of-the-pros-and-cons-of-using-jque... | For learning, yes, avoid libraries. Especially for something as conceptually simple as AJAX, forcing yourself to learn how the browser can be used "raw" will benefit you immensely later on, even if you are using a library to take care of the drudgery and abstract away browser differences.
Once you have a solid underst... | While I think it is really important to understand conceptually what is going on and be able to correctly implement calls using an AJAX library, I disagree with @Shog9 that you need to write the actual code to perform an XmlHttpRequest in order to start using AJAX. I'd say do some background reading to understand the c... | Should I avoid using a JavaScript library while learning how to write AJAX client code? | [
"",
"javascript",
"ajax",
""
] |
I have a class called `Ship` and a class called `Lifeboat`
Lifeboat inherits from Ship.
Ship contains a method called `Validate()` which is called before save and it has an abstract method called `FurtherValidate()` which it calls from Validate. The reason this is in place is so when you call validate on the base it ... | The exact scenario you describe isn't possible. You can restrict access to the `FurtherValidate` method to only derived classes by using the `protected` access modifier. You could also restrict it to only classes in the same assembly by using the `internal` modifier, but this would still allow the programmer writing th... | ```
protected abstract bool FurtherValidate();
```
only Ship and Lifeboat can see it now.
EDIT:
Lifeboat must be able to see it. How should it be able to override `FurtherValidate` when it can't even see it. I would rename it to `ValidateCore`, the 'Core' part (to me) implies that it should not be called without a ve... | How do I hide a method so it's not called by programmers but still usable in code? | [
"",
"c#",
"inheritance",
""
] |
I'm serializing an object in a C# VS2003 / .Net 1.1 application. I need it serialized without the processing instruction, however. The XmlSerializer class puts out something like this:
```
<?xml version="1.0" encoding="utf-16" ?>
<MyObject>
<Property1>Data</Property1>
<Property2>More Data</Property2>
</MyObje... | The following link will take you to a post where someone has a method of supressing the processing instruction by using an XmlWriter and getting into an 'Element' state rather than a 'Start' state. This causes the processing instruction to not be written.
[Suppress Processing Instruction](http://www.tech-archive.net/A... | I made a small correction
```
XmlSerializer serializer = new XmlSerializer(typeof(MyObject));
StringBuilder builder = new StringBuilder();
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
using ( XmlWriter stringWriter = XmlWriter.Create(builder, settings) )
{
serializer.... | Omitting XML processing instruction when serializing an object | [
"",
"c#",
".net",
"xml-serialization",
"visual-studio-2003",
""
] |
To use [modular exponentiation](http://en.wikipedia.org/wiki/Modular_exponentiation) as you would require when using the [Fermat Primality Test](http://en.wikipedia.org/wiki/Fermat_primality_test) with large numbers (100,000+), it calls for some very large calculations.
When I multiply two large numbers (eg: 62574 and... | For some reason, there are two standard libraries in PHP handling the arbitrary length/precision numbers: [BC Math](http://www.php.net/manual/en/book.bc.php) and [GMP](http://www.php.net/manual/en/book.gmp.php). I personally prefer GMP, as it's fresher and has richer API.
Based on GMP I've implemented [Decimal2 class]... | use this
```
$num1 = "123456789012345678901234567890";
$num2 = "9876543210";
$r = mysql_query("Select @sum:=$num1 + $num2");
$sumR = mysql_fetch_row($r);
$sum = $sumR[0];
``` | Working with large numbers in PHP | [
"",
"php",
"bignum",
""
] |
I'd like to write some unit tests for some code that connects to a database, runs one or more queries, and then processes the results.
(Without actually using a database)
Another developer here wrote our own DataSource, Connection, Statement, PreparedStatement, and ResultSet implementation that will return the corresp... | You could use [DBUnit](http://dbunit.sourceforge.net/) together with a [HSQLDB](http://hsqldb.org/) which can read its initial data from CSV files for example. | You have several options:
* Mock the database with a Mock library, e.g. [JMock](http://www.jmock.org/). The huge drawback of this that your queries and the data will most likely be not tested at all.
* Use a light weight database for the tests, such as [HSQLDB](http://hsqldb.org/). If your queries are simple, this is ... | How do I unit test jdbc code in java? | [
"",
"java",
"database",
"unit-testing",
"jdbc",
"junit",
""
] |
I have seen a codebase recently that I fear is violating alignment constraints. I've scrubbed it to produce a minimal example, given below. Briefly, the players are:
* *Pool*. This is a class which allocates memory efficiently, for some definition of 'efficient'. *Pool* is guaranteed to return a chunk of memory that i... | Ok - had a chance to read it properly. You have an alignment problem, and invoke undefined behaviour when you access the char array as an Obj\_list. Most likely your platform will do one of three things: let you get away with it, let you get away with it at a runtime penalty or occasionally crash with a bus error.
You... | If you want to ensure alignment of your structures, just do a
```
// MSVC
#pragma pack(push,1)
// structure definitions
#pragma pack(pop)
// *nix
struct YourStruct
{
....
} __attribute__((packed));
```
To ensure 1 byte alignment of your char array in Aggregate | What is the Performance, Safety, and Alignment of a Data member hidden in an embedded char array in a C++ Class? | [
"",
"c++",
"alignment",
""
] |
I have several identical elements with different attributes that I'm accessing with SimpleXML:
```
<data>
<seg id="A1"/>
<seg id="A5"/>
<seg id="A12"/>
<seg id="A29"/>
<seg id="A30"/>
</data>
```
I need to remove a specific **seg** element, with an id of "A12", how can I do this? I've tried loopin... | While [SimpleXML](http://de.php.net/manual/en/book.simplexml.php) provides [a way to remove](https://stackoverflow.com/a/16062633/367456) XML nodes, its modification capabilities are somewhat limited. One other solution is to resort to using the [DOM](http://de.php.net/manual/en/book.dom.php) extension. [dom\_import\_s... | Contrary to popular belief in the existing answers, each Simplexml element node can be removed from the document just by itself and `unset()`. The point in case is just that you need to understand how SimpleXML actually works.
First locate the element you want to remove:
```
list($element) = $doc->xpath('/*/seg[@id="... | Remove a child with a specific attribute, in SimpleXML for PHP | [
"",
"php",
"xml",
"dom",
"simplexml",
""
] |
I have been slowly learning SQL the last few weeks. I've picked up all of the relational algebra and the basics of how relational databases work. What I'm trying to do now is learn how it's implemented.
A stumbling block I've come across in this, is foreign keys in MySQL. I can't seem to find much about the other than... | Assuming your categories and users table already exist and contain cID and uID respectively as primary keys, this should work:
```
CREATE TABLE `posts` (
`pID` bigint(20) NOT NULL auto_increment,
`content` text NOT NULL,
`time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`uID` bigint(20) NOT NULL,
`wikiptr` bigint(2... | **Edited:** Robert and Vinko state that you need to declare the name of the referenced column in the foreign key constraint. This is necessary in InnoDB, although in standard SQL you're permitted to omit the referenced column name if it's the same name in the parent table.
One idiosyncrasy I've encountered in MySQL is... | Foreign keys in MySQL? | [
"",
"sql",
"mysql",
"foreign-keys",
""
] |
I created an ASMX file with a code behind file. It's working fine, but it is outputting XML.
However, I need it to output JSON. The ResponseFormat configuration doesn't seem to work. My code-behind is:
```
[System.Web.Script.Services.ScriptService]
public class _default : System.Web.Services.WebService {
[WebMeth... | From [WebService returns XML even when ResponseFormat set to JSON](http://forums.asp.net/p/1327142/2652827.aspx):
> Make sure that the request is a POST request, not a GET. Scott Guthrie has a [post explaining why](http://weblogs.asp.net/scottgu/archive/2007/04/04/json-hijacking-and-how-asp-net-ajax-1-0-mitigates-thes... | To receive a pure JSON string, without it being wrapped into an XML, you have to write the JSON string directly to the `HttpResponse` and change the `WebMethod` return type to `void`.
```
[System.Web.Script.Services.ScriptService]
public class WebServiceClass : System.Web.Services.WebService {
[WebMeth... | How to let an ASMX file output JSON | [
"",
"c#",
"json",
"asmx",
""
] |
If I want to have a case-insensitive string-keyed dictionary, which version of StringComparer should I use given these constraints:
* The keys in the dictionary come from either C# code or config files written in english locale only (either US, or UK)
* The software is internationalized and will run in different local... | [This MSDN article](http://msdn.microsoft.com/en-us/library/ms973919.aspx#stringsinnet20_topic4) covers everything you could possibly want to know in great depth, including the Turkish-I problem.
It's been a while since I read it, so I'm off to do so again. See you in an hour! | There are three kinds of comparers:
* Culture-aware
* Culture invariant
* Ordinal
Each comparer has a **case-sensitive** as well as a **case-insensitive** version.
An **ordinal** comparer uses ordinal values of characters. This is the fastest comparer, it should be used for internal purposes.
A **culture-aware** co... | Which Version of StringComparer to use | [
"",
"c#",
".net",
"string",
"internationalization",
""
] |
In a forms model, I used to get the current logged-in user by:
```
Page.CurrentUser
```
How do I get the current user inside a controller class in ASP.NET MVC? | If you need to get the user from within the controller, use the `User` property of Controller. If you need it from the view, I would populate what you specifically need in the `ViewData`, or you could just call User as I think it's a property of `ViewPage`. | I found that `User` works, that is, `User.Identity.Name` or `User.IsInRole("Administrator")`. | How to get the current user in ASP.NET MVC | [
"",
"c#",
".net",
"asp.net-mvc",
"iis",
"forms-authentication",
""
] |
I tried this:
```
ALTER TABLE My.Table DROP MyField
```
and got this error:
-MyField is not a constraint.
-Could not drop constraint. See previous errors.
There is just one row of data in the table and the field was just added.
**EDIT:**
Just to follow up, the sql was missing COLUMN indeed.
Now I get even more se... | Brian solved your original problem - for your new problem (The object 'some\_object\_\_somenumbers' is dependent on column 'MyField') it means you have a dependancy issue. Something like an index, foreign key reference, default value, etc. To drop the constraint use:
```
ALTER TABLE TableName DROP ConstraintName
```
... | I think you are just missing the COLUMN keyword:
```
ALTER TABLE TableName DROP COLUMN ColumnName
```
You will also need to make sure that any constraint that is depending on ColumnName is dropped first.
You can do this by:
```
ALTER TABLE TableName DROP ConstraintName
```
For each constraint that you have.
If yo... | How to remove a field from SQLServer2005 table | [
"",
"sql",
"sql-server-2005",
""
] |
I've got a java server (not web based, more like a big, many-threaded standalone application) that needs to talk to a MS SQL Server database.
I just worked on a different project that ported a home-grown O/R layer from oracle to SQL Server, and it ran into significant problems because of too many oracle assumptions (l... | I've used Hibernate and iBATIS. Choosing one over the other depends upon the situation.
Hibernate:
* is much pickier about database schema
* generates most of the sql for you
* more features
* more complex
iBATIS:
* works better when you want to work with existing schema
* requires you to write your own sql
* easie... | **Hibernate** is the usual choice. Besides that you can take a look at Oracle TopLink, iBatis, whatever suites you best. | Java O/R layer for SQL server? | [
"",
"java",
"sql-server",
"database",
"orm",
""
] |
I have mapped several java classes like Customer, Assessment, Rating, ... to a database with Hibernate.
Now i am thinking about a history-mode for all changes to the persistent data. The application is a web application. In case of deleting (or editing) data another user should have the possibility to see the changes a... | One way to do it would be to have a "change history" entity with properties for entity id of the entity changed, action (edit/delete), property name, orginal value, new value. Maybe also reference to the user performing the edit. A deletion would create entities for all properties of the deleted entity with action "del... | One approach to maintaining audit/undo trails is to mark each version of an object's record with a version number. Finding the current version would be a painful effort if the this were a simple version number, so a reverse version numbering works best. "version' 0 is always the current and if you do an update the vers... | Best practice to realize a long-term history-mode for a O/RM system(Hibernate)? | [
"",
"java",
"database",
"hibernate",
"orm",
""
] |
I've been working with some C# legacy code and I've been seeing a lot of @ symbols in front of variable names. What does this signify or do?
Currently I'm seeing it a lot in front of variables with common names that aren't reserved. E.g.:
```
MyProcedure(@step.LoadInstanceId, @step.ResultCode, @step.StatusCode);
```
... | It's just a way to allow declaring reserved keywords as vars.
```
void Foo(int @string)
``` | It allows you to use a reserved word, like 'public' for example, as a variable name.
```
string @public = "foo";
```
I would not recommend this, as it can lead to unecessary confusion. | What does placing a @ in front of a C# variable name do? | [
"",
"c#",
""
] |
I have an abstract base class which acts as an interface.
I have two "sets" of derived classes, which implement half of the abstract class. ( one "set" defines the abstract virtual methods related to initialization, the other "set" defines those related to the actual "work". )
I then have derived classes which use mu... | It looks like you want to do virtual inheritance. Whether that turns out to actually be a good idea is another question, but here's how you do it:
```
class AbsBase {...};
class AbsInit: public virtual AbsBase {...};
class AbsWork: public virtual AbsBase {...};
class NotAbsTotal: public AbsInit, public AbsWork {...};
... | It can be done, although it gives most the shivers.
You need to use "virtual inheritance", the syntax for which is something like
```
class AbsInit: public virtual AbsBase {...};
class AbsWork: public virtual AbsBase {...};
class NotAbsTotal: public AbsInit, public AbsWork {...};
```
Then you have to specify which f... | Multiple Inheritance from two derived classes | [
"",
"c++",
"inheritance",
"multiple-inheritance",
""
] |
In my spring application context file, I have something like:
```
<util:map id="someMap" map-class="java.util.HashMap" key-type="java.lang.String" value-type="java.lang.String">
<entry key="some_key" value="some value" />
<entry key="some_key_2" value="some value" />
</util:map>
```
In java class, the impl... | The problem is that a cast is a runtime check - but due to type erasure, at runtime there's actually no difference between a `HashMap<String,String>` and `HashMap<Foo,Bar>` for any other `Foo` and `Bar`.
Use `@SuppressWarnings("unchecked")` and hold your nose. Oh, and campaign for reified generics in Java :) | Well, first of all, you're wasting memory with the new `HashMap` creation call. Your second line completely disregards the reference to this created hashmap, making it then available to the garbage collector. So, don't do that, use:
```
private Map<String, String> someMap = (HashMap<String, String>)getApplicationConte... | Type safety: Unchecked cast | [
"",
"java",
"spring",
"type-safety",
"unchecked",
""
] |
I need to create reports in a C# .NET Windows app. I've got an SQL Server 2005 database, Visual Studio 2005 and am quite OK with creating stored procedures and datasets.
Can someone please point me in the right direction for creating reports? I just can't seem work it out. Some examples would be a good start, or a sim... | I have managed to make this work now.
**Brief Overview**
It works by having a 'data class' which is just a regular C# class containing variables and no code. This is then instantiated and filled with data and then placed inside an ArrayList. The ArrayList is bound to the report viewer, along with the name of the repo... | Crystal is one possible option for creating reports. It has been around a long time and a lot of people seem to like it.
You might want to take a look at SQL reporting services. I have used both but my preferance is SQL reporting services. Its pretty well integrated into studio and works similar to the other microsoft... | Using Crystal Reports in Visual Studio 2005 (C# .NET Windows App) | [
"",
"c#",
".net",
"database",
"visual-studio",
"crystal-reports",
""
] |
This [article](http://themechanicalbride.blogspot.com/2008/04/using-operators-with-generics.html) describes a way, in C#, to allow the addition of arbitrary value types which have a + operator defined for them. In essence it allows the following code:
```
public T Add(T val1, T val2)
{
return val1 + val2;
}
```
Th... | Due to the way templates are compiled in C++, simply doing:
```
template < class T >
T add(T const & val1, T const & val2)
{
return val1 + val2;
}
```
will work, you'll get a compile error for every type where an operator+ is not defined.
C++ templates generate code for every type instantiation, so for every typ... | **In C++ this is simply not an issue.** The code as in your first sample works if literally translated into C++ (ETA: as Pieter did), but I can't think of any situation where directly using + wouldn't work. You're looking for a solution to a problem that doesn't exist. | Operations on arbitrary value types | [
"",
"c++",
"c",
"cuda",
"gpgpu",
"value-type",
""
] |
In an application I work on, any business logic error causes an exception to be thrown, and the calling code handles the exception. This pattern is used throughout the application and works well.
I have a situation where I will be attempting to execute a number of business tasks from inside the business layer. The req... | The [Task Parallel Library extensions](http://msdn.microsoft.com/magazine/cc163340.aspx) for .NET (which [will become part of .NET 4.0](http://blogs.msdn.com/pfxteam/archive/2008/10/10/8994927.aspx)) follow the pattern suggested in other answers: collecting all exceptions that have been thrown into an AggregateExceptio... | Two ways of the top of my head would be either make a custom exception and add the exceptions to this class and throw that the end :
```
public class TaskExceptionList : Exception
{
public List<Exception> TaskExceptions { get; set; }
public TaskExceptionList()
{
TaskExceptions = new List<Exception>... | Throwing multiple exceptions in .Net/C# | [
"",
"c#",
".net",
"exception",
""
] |
I want to setup a statistics monitoring platform to watch a specific service, but I'm not quiet sure how to go about it. Processing the intercepted data isn't my concern, just how to go about it. One idea was to setup a proxy between the client application and the service so that all TCP traffic went first to my proxy,... | You didn't mention one approach: you could modify memcached or your client to record the statistics you need. This is probably the easiest and cleanest approach.
Between the proxy and the libpcap approach, there are a couple of tradeoffs:
```
- If you do the packet capture approach, you have to reassemble the TCP
s... | Exactly what are you trying to track? If you want a simple count of packets or bytes, or basic header information, then `iptables` will record that for you:
```
iptables -I INPUT -p tcp -d $HOST_IP --dport $HOST_PORT -j LOG $LOG_OPTIONS
```
If you need more detailed information, look into the `iptables ULOG` target, ... | Intercepting traffic to memcached for statistics/analysis | [
"",
"c++",
"c",
"linux",
"networking",
"memcached",
""
] |
In my C# source code I may have declared integers as:
```
int i = 5;
```
or
```
Int32 i = 5;
```
In the currently prevalent 32-bit world they are equivalent. However, as we move into a 64-bit world, am I correct in saying that the following will become the same?
```
int i = 5;
Int64 i = 5;
``` | No. The C# specification rigidly defines that `int` is an alias for `System.Int32` with exactly 32 bits. Changing this would be a *major* breaking change. | The `int` keyword in C# is defined as an alias for the `System.Int32` type and this is (judging by the name) meant to be a 32-bit integer. To the specification:
> [CLI specification](http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-335.pdf) section 8.2.2 (Built-in value and reference types) has a tabl... | Is an int a 64-bit integer in 64-bit C#? | [
"",
"c#",
"64-bit",
"32-bit",
"primitive",
""
] |
Is there any way that I can change how a Literal of a code snippet renders when it is used in the code that the snippet generates?
Specifically I'd like to know if I can have a literal called say, $PropertyName$ and then get the snippet engine to render "\_$PropertyName$ where the first character is made lowercase.
I... | Unfortunately there seems to be no way. Snippets offer amazingly limited support for [transformation functions](http://msdn.microsoft.com/en-us/library/ms242312(VS.80).aspx) as you can see.
You have to stick with the VS standard solution, which is to write two literals: one for the property name, and the other for the... | You can enter a upper first letter, then a property name, then a lower first letter. Try this snippet:
```
<?xml version="1.0" encoding="utf-8"?>
<CodeSnippet Format="1.0.0" xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<Header>
<Title>Notifiable Property</Title>
<Author>Nikolay Makhoni... | Formatting Literal parameters of a C# code snippet | [
"",
"c#",
"code-generation",
"code-snippets",
""
] |
I'm trying to access the command line and execute a command, and then return the output to my aspx page. A good example would be running dir on page load of an aspx page and returning the output via Response.Write(). I have tried using the code below. When I try debugging this it runs but never finishes loading and no ... | You have a problem with the syntax of commandline arguments to cmd.exe. This is why cmd never exits.
In order to have cmd.exe run a program and then quit, you need to send it the syntax "/c [command]". Try running the same code with the line
```
si.StartInfo.Arguments = "dir";
```
replaced with
```
... | Most likely your problem is with the permissions. The user under which ASP.NET process runs is with very limited rights.
So, either you have to set the proper permissions for that user, or run ASP.NET under some other user.
This hides a security risks though, so you have to be very careful. | Running Command line from an ASPX page, and returning output to page | [
"",
"c#",
"asp.net",
""
] |
Im trying to get into some basic JavaFX game development and I'm getting confused with some circle maths.
I have a circle at (x:250, y:250) with a radius of 50.
My objective is to make a smaller circle to be placed on the circumference of the above circle based on the position of the mouse.
Where Im getting confused... | `atan(height/length)` is not enough to get the angle. You need to compensate for each quadrant, as well as the possibility of "division-by-zero". Most programming language libraries supply a method called `atan2` which take two arguments; `y` and `x`. This method does this calculation for you.
More information on [Wik... | You can get away without calculating the angle. Instead, use the center of your circle (250,250) and the position of the mouse (xpos,ypos) to define a line. The line intersects your circle when its length is equal to the radius of your circle:
```
// Calculate distance from center to mouse.
xlen = xpos - x_center_pos;... | How to position a Node along a circular orbit around a fixed center based on mouse coordinates (JavaFX)? | [
"",
"java",
"geometry",
"javafx",
"trigonometry",
"javafx-1",
""
] |
I've been trying to use Firebug's profiler to better understand the source of some JavaScript performance issues we are seeing, but I'm a little confused by the output.
When I profile some code the profiler reports **Profile (464.323 ms, 26,412 calls)**. I suspect that the 464.323 ms is the sum of the execution time f... | Each column has a description of what it means if you set your mouse to hover over it in Firebug. I'll assume you can read up on how each column works on your own then. However, you have definitely come across some odd behavior which needs to be explained.
The *own time* is the amount of time the function spent execut... | If I understand things correctly it goes something like this:
On the first line you'll see that the Own time is "only 0.006ms". That means that even though time spent in that function was 783.506ms most of it was spent inside functions called from that function.
When I use Firebug to optimize code I try to reduce the... | Understanding Firebug profiler output | [
"",
"javascript",
"profiling",
"firebug",
"profiler",
""
] |
Already implemented performance boosters :
- Get compatible image of GraphicsConfiguration to draw on
- Enable OpenGL pipeline in 1.5: Not possible due to severe artifacts
So far I am fine, the main profiled bottleneck of the program is drawing an image with several thousand tiles. Unfortunately it is not regular, els... | You could try to set the popups to non-leightweight. I am not quite sure if it works but it could, because the popup is a native component then and will not be overdrawn.
Setting Popups to heavyweight: JPopupMenu.setDefaultLightWeightPopupEnabled(false)
More Information: [Mixing heavy and light components](http://www.... | Here is some example code:
```
import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.awt.image.VolatileImage;
import java.io.File;
import java.io.IOException;
import java.ut... | Accelerate 2D images in Java *without* disturbing JMenus | [
"",
"java",
"performance",
"swing",
"2d",
""
] |
Here's the deal. I have an XML document with a lot of records. Something like this:
```
print("<?xml version="1.0" encoding="utf-8" ?>
<Orders>
<Order>
<Phone>1254</Phone>
<City>City1</City>
<State>State</State>
</Order>
<Order>
<Phone>98764321</Phone>
... | You have a couple of options:
1. [XmlDataDocument](http://msdn.microsoft.com/en-us/library/system.xml.xmldatadocument(VS.80).aspx) or [XmlDocument](http://msdn.microsoft.com/en-us/library/system.xml.xmldocument(VS.80).aspx). The downside to this approach is that the data will be cached in memory, which is bad if you h... | If the data maps fairly cleanly to an object model, you could try using xsd.exe to generate some classes from the .xsd, and process the classes into your DAL of choice. The problem is that if the volume is high (you mention thousands of records), you will most likely have a *lot* of round-trips.
Another option might b... | Validating and Extracting XML record by record into Database | [
"",
"c#",
".net",
"xml",
"linq",
"linq-to-xml",
""
] |
**Problem solved:** Thanks guys, see my answer below.
I have a website running in Tomcat 5.5 hooked up to a MySQL5 database using Hibernate3.
One record simply refuses to keep any changes performed on it. If I change the record programmatically, the values revert back to what they were previously.
If I manually modi... | You could temporarily enable the mysql query logging and see exactly what sql statement altered the value. Since you say it changes immediately after the server starts you should be able to figure out the statement pretty quickly.
<http://dev.mysql.com/doc/refman/5.0/en/query-log.html> | To answer your question:
> Does anyone know how to resolve the ?
> for the columns to actual values?
You can do this with [p6spy](http://www.p6spy.com/). Instructions for how to set this up in a Spring app are available [here](http://swik.net/Spring/Spring%27s+corner/Integrate+P6Spy+with+Spring/vq6).
However, I thin... | Database record reverting after manual change | [
"",
"java",
"mysql",
"tomcat5.5",
"hibernate3",
""
] |
I have a device that supports 4-color graphics (much like CGA in the old days).
I wanted to use [PIL](http://www.pythonware.com/products/pil/) to read the image and convert it using my 4-color palette (of red, green, yellow, black), but I can't figure out if it's even possible at all. I found some mailing list archive... | First: your four colour palette (black, green, red, yellow) has *no* blue component. So, you have to accept that your output image will hardly approximate the input image, unless there is no blue component to start with.
Try this code:
```
import Image
def estimate_color(c, bit, c_error):
c_new= c - c_error
... | John, I found that first link as well, but it didn't directly help me with the problem. It did make me look deeper into quantize though.
I came up with this yesterday before going to bed:
```
import sys
import PIL
import Image
PALETTE = [
0, 0, 0, # black, 00
0, 255, 0, # green, 01
255, 0, 0... | How do I convert any image to a 4-color paletted image using the Python Imaging Library? | [
"",
"python",
"image-processing",
"python-imaging-library",
""
] |
I want to be able to get a list of all differences between two JavaScript object graphs, with the property names and values where the deltas occur.
For what it is worth, these objects are usually retrieved from the server as JSON and typically are no more than a handful of layers deep (i.e. it may be an array of objec... | After reviewing the existing answers, I noticed that the <https://github.com/flitbit/diff> library was not yet listed as a solution.
From my research, this library seems to be the best in terms of active development, contributions and forks for solving the challenge of diffing objects. This is very handy for creating ... | Here is a partial, naïve solution to my problem - I will update this as I further develop it.
```
function findDifferences(objectA, objectB) {
var propertyChanges = [];
var objectGraphPath = ["this"];
(function(a, b) {
if(a.constructor == Array) {
// BIG assumptions here: That both arrays are s... | How can I get a list of the differences between two JavaScript object graphs? | [
"",
"javascript",
"json",
"data-structures",
"diff",
""
] |
In C#, how do I set the Identity of a Thread?
For example, if I have Thread MyThread, which is already started, can I change MyThread's Identity?
Or is this not possible? | You can set the Identity of a thread by creating a new Principal. You can use any Identity that inherits from [System.Security.Principal.IIdentity](https://msdn.microsoft.com/en-us/library/system.security.principal.iidentity(v=vs.110).aspx), but you need a class that inherits from [System.Security.Principal.IPrincipal]... | **Update for the accepted answer [apply ONLY on .NET framework 4.5 and above]**
In `.NET 4.5` the property `IsAuthenticated` has no set accessor, so you can not set it directly as the accepted answer doing.
You can use the following code for setting that property.
```
GenericIdentity identity = new GenericIdentit... | Set Identity of Thread | [
"",
"c#",
".net",
"multithreading",
"iidentity",
""
] |
In my experience it seems that most people will tell you that it is unwise to force a garbage collection but in some cases where you are working with large objects that don't always get collected in the 0 generation but where memory is an issue, is it ok to force the collect? Is there a best practice out there for doin... | The best practise is to not force a garbage collection.
According to MSDN:
> "It is possible to force garbage
> collection by calling Collect, but
> most of the time, this should be
> avoided because it may create
> performance issues. "
However, if you can reliably test your code to confirm that calling Collect() w... | Look at it this way - is it more efficient to throw out the kitchen garbage when the garbage can is at 10% or let it fill up before taking it out?
By not letting it fill up, you are wasting your time walking to and from the garbage bin outside. This analogous to what happens when the GC thread runs - all the managed t... | Best Practice for Forcing Garbage Collection in C# | [
"",
"c#",
".net",
"garbage-collection",
""
] |
Given an object:
```
let myObject = {
"ircEvent": "PRIVMSG",
"method": "newURI",
"regex": "^http://.*"
};
```
How do I remove the property `regex` to end up with the following `myObject`?
```
let myObject = {
"ircEvent": "PRIVMSG",
"method": "newURI"
};
``` | To remove a property from an object (mutating the object), you can do it by using the `delete` keyword, like this:
```
delete myObject.regex;
// or,
delete myObject['regex'];
// or,
var prop = "regex";
delete myObject[prop];
```
Demo
```
var myObject = {
"ircEvent": "PRIVMSG",
"method": "newURI",
"regex": "^ht... | Objects in JavaScript can be thought of as maps between keys and values. The `delete` operator is used to remove these keys, more commonly known as object properties, one at a time.
```
var obj = {
myProperty: 1
}
console.log(obj.hasOwnProperty('myProperty')) // true
delete obj.myProperty
console.log(obj.ha... | How do I remove a property from a JavaScript object? | [
"",
"javascript",
"object",
"properties",
""
] |
I have a view using a master page that contains some javascript that needs to be executed using the OnLoad of the Body. What is the best way to set the OnLoad on my MasterPage only for certain views?
On idea I tried was to pass the name of the javascript function as ViewData. But I dont really want my Controllers to h... | I have been using the following pattern with my current MVC project and it seems to be working pretty good for my .js work thus far...
Within my Master Page I load up my standard script files that I want to be used in all of my content pages (things like jquery.js, global.js, jquery-plugins, .css files, etc.). I then ... | Solution from Blog: [Using body onload with ASP.net 2.0 MasterPages](http://blog.thewightstuff.net/blog/2007/03/using-body-onload-with-aspnet-20.html)
```
MasterPage.master
<head>
<asp:ContentPlaceHolder runat="server" id="Headers">
</asp:ContentPlaceHolder>
<script language=javascript>
function mp_onload() {
... | Setting the Body's OnLoad attribute in an Asp.net MVC Master Page | [
"",
"javascript",
"asp.net-mvc",
"master-pages",
""
] |
I have this XML in a column in my table:
```
<keywords>
<keyword name="First Name" value="|FIRSTNAME|" display="Jack" />
<keyword name="Last Name" value="|LASTNAME|" display="Jones" />
<keyword name="City" value="|CITY|" display="Anytown" />
<keyword name="State" value="|STATE|" display="MD" />
</keywords>
```... | Here is a sample code:
To read keywords we need to call *Elements("**keyword**")* not *Elements("**keywords**")* since *keywords* is a root node.
```
// IEnumerable sequence with keywords data
var keywords = from kw in ga.ArticleKeywords.Elements("keyword")
select new {
Name = (strin... | Once again I am amazed that people don't even try their answers and people still up vote when they don't work.
The .Elements will get the list of elements at the current root, which is not a keyword.
Also the one using .Attributes["X"] does not even compile you need to use () of course again it would be operating on e... | How do I access the XML data in my column using LINQ to XML? | [
"",
"c#",
"xml",
"linq-to-sql",
"linq-to-xml",
""
] |
I have a Perl application that parses MediaWiki SQL tables and displays data from multiple wiki pages. I need to be able to re-create the absolute image path to display the images, eg: `.../f/fc/Herbs.jpg/300px-Herbs.jpg`
From MediaWiki Manual:
> Image\_Authorisation: "the [image] path can be calculated easily from t... | One possible way would be to calculate the MD5 signature of the file (or the file ID in a database), and then build/find the path based on that.
For example, say we get an MD5 signature like "1ff8a7b5dc7a7d1f0ed65aaa29c04b1e"
The path might look like "/1f/f" or "/1f/ff/8a"
The reason is that you don't want to have a... | The accepted answer is incorrect:
* The MD5 sum of a string is 32 hex characters (128 bits), not 16
* The file path is calculated from the MD5 sum of the filename, not the contents of the file itself
* The first directory in the path is the first character, and the second directory is the first and second characters. ... | How does MediaWiki compose the image paths? | [
"",
"php",
"perl",
"mediawiki",
""
] |
How can I know in a C#-Application, in which direction the screen of the mobile device is orientated? (i.e. horizontal or vertical). | In Microsoft.WindowsMobile.Status there is a class which keeps track of all kinds of properties of your device.
Besides the one you need, DisplayRotation, it also contains properties about phone coverage, Nr of missed calls, next appointment and many more. See [msdn](http://msdn.microsoft.com/en-us/library/microsoft.wi... | Add a reference to Microsoft.WindowsCE.Forms to your project. Then you can reference the
Microsoft.WindowsCE.Forms.**SystemSettings.ScreenOrientation** property, which will give you what you need.
Incidentally, you can set this property, so it can be used to set your screen orientation also. | How to determine the orientation of the screen in C# for mobile devices? | [
"",
"c#",
"user-interface",
"windows-mobile",
""
] |
I've got a big big code base that includes two main namespaces: the engine and the application.
The engine defines a vector3 class as a typedef of another vector3 class, with equality operators that sit in the engine namespace, not in the vector3 class. I added a class to the application that also had equality operato... | C++ Standard, 3.4.4.2 declares:
> For each argument type T in the function call, there is a set of zero or more associated namespaces and a set of zero
> or more associated classes to be considered. The sets of namespaces and classes is determined entirely by the types of
> the function arguments (and the namespace of... | I once ran into the same problem with a compiler that didn't have Argument Dependent Lookup (Koenig Lookup - thanks @igor) (VC6 I think). This means that when it sees an operator, it just looks in the enclosing namespaces.
So can you tell us what compiler you use?
Moving to another compiler solved it.
Very inconveni... | function overloading fail: why did these operators clash? | [
"",
"c++",
"operator-overloading",
"overloading",
""
] |
My php is weak and I'm trying to change this string:
```
http://www.example.com/backend.php?/c=crud&m=index&t=care
^
```
to be:
```
http://www.example.com/backend.php?c=crud&m=index&t=care
^
```
removing the `/` after the `backend.php?`. Any ideas... | I think that it's better to use simply [str\_replace](http://www.php.net/str_replace), like the manual says:
> If you don't need fancy replacing
> rules (like regular expressions), you
> should always use this function
> instead of ereg\_replace() or
> preg\_replace().
```
<?
$badUrl = "http://www.site.com/backend.ph... | ```
$str = preg_replace('/\?\//', '?', $str);
```
Edit: See CMS' answer. It's late, I should know better. | PHP removing a character in a string | [
"",
"php",
"string",
""
] |
I'm trying to do an image capture on a high end Nokia phone (N95). The phone's internal camera is very good (4 megapixels) but in j2me I only seem to be able to get a maximum of 1360x1020 image out. I drew largely from this example <http://developers.sun.com/mobility/midp/articles/picture/>
What I did was start with 6... | This [explanation](http://www.forum.nokia.com/document/Java_ME_Developers_Library/?content=GUID-00C29EFF-1A32-49D6-9AF4-0E5D8F1EE772.html) on Nokia forum may help you.
It says that "The maximum image size that can be captured depends on selected image format, encoding options and free heap memory available."
and
"It... | Your cameras resolution is natively:
2582 x 1944 . Try capturing there to see how that goes.
This place:
<http://developers.sun.com/mobility/midp/articles/picture/index.html>
Mentions the use of:
```
byte[] raw = mVideoControl.getSnapshot(null);
Image image = Image.createImage(raw, 0, raw.length);
```
The use of ra... | Full Resolution Camera Access in j2me | [
"",
"java",
"java-me",
"mobile",
"camera",
"mmapi",
""
] |
I am performing a lot of JavaScript work in the browser and would like to have some of that backend functionality in the front-end. Specifically, it would be nice to have the functions `get()`, `save()`, `all()` and `count()` available to the client. Additionally, it would be great to have the field list of the model a... | It sounds like you're looking for a complete JavaScript interface to the model and queryset APIs. I can't imagine that this would have ever been done or even be a simple task. Not only would you need to somehow generate JavaScript instances of models (much more than JSON serialisation provides, since you also want the ... | You need a data serializer. You can do it with django built in serializers. It is documented on official django site. [djangoproject\_topics-serialization](http://docs.djangoproject.com/en/dev/topics/serialization/#topics-serialization) | Generate JavaScript objects out of Django Models | [
"",
"javascript",
"django",
"django-models",
"code-generation",
""
] |
I am looking for a data structure that operates similar to a hash table, but where the table has a size limit. When the number of items in the hash reaches the size limit, a culling function should be called to get rid of the least-retrieved key/value pairs in the table.
Here's some pseudocode of what I'm working on:
... | You are looking for an `LRUList`/`Map`. Check out `LinkedHashMap`:
The `removeEldestEntry(Map.Entry)` method may be overridden to impose a policy for removing stale mappings automatically when new mappings are added to the map. | Googling "LRU map" and "I'm feeling lucky" gives you this:
<http://commons.apache.org/proper/commons-collections//javadocs/api-release/org/apache/commons/collections4/map/LRUMap.html>
> A Map implementation with a fixed
> maximum size which removes the least
> recently used entry if an entry is
> added when full.
So... | What is a data structure kind of like a hash table, but infrequently-used keys are deleted? | [
"",
"java",
"algorithm",
"data-structures",
"caching",
""
] |
I would like to print *only* the contents of a textarea element from a website page. In particular, I would like to ensure that nothing gets clipped by the boundary of the textarea as the contents will be quite large.
What is the best strategy for tackling this? | Make a print stylesheet where all of the elements *except* the textarea are set in CSS to display: none;, and for the textarea, overflow: visible.
Link it to the page with the link tag in the header set to media="print".
You're done. | Make a different CSS with media set to print
```
<link rel="stylesheet" type="text/css" href="print.css" media="print" />
```
<http://webdesign.about.com/cs/css/a/aa042103a.htm> | Printing only a textarea | [
"",
"javascript",
"printing",
"textarea",
"printing-web-page",
""
] |
Background
I have been asked by a client to create a picture of the world which has animated arrows/rays that come from one part of the world to another.
The rays will be randomized, will represent a transaction, will fade out after they happen and will increase in frequency as time goes on. The rays will start in on... | If you are adventurous use OpenGL :)
You can draw bezier curves in 3d space on top of a textured plane (earth map), you can specify a thickness for them and you can draw a point (small cone) at the end. It's easy and it looks nice, problem is learning the basics of OpenGL if you haven't used it before but that would b... | > The client will present this as a slide in a presentation in a windows machine
I think this is the key to your answer. Before going to a 3d implementation and writing all the code in the world to create this feature, you need to look at the presentation software. Chances are, your options will boil down to two thing... | How to create a picture with animated aspects programmatically | [
"",
"python",
"image",
"graphics",
"animation",
"drawing",
""
] |
I've got a WAR file that I need to add two files to. Currently, I'm doing this:
```
File war = new File(DIRECTORY, "server.war");
JarOutputStream zos = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(war)));
//Add file 1
File file = new File(DIRECTORY, "file1.jar");
InputStream is = new BufferedInpu... | It seems this can't be done. I thought it was for a while, but it seems that it wasn't quite having the effect I wanted. Doing it this way resulted in the equivalent of two separate jar files concatinated together. The weird part was that the tools were making some sense of it. JAR found the first, original jar file an... | Yeah, there's an extra boolean argument to the [FileOutputStream constructor](http://java.sun.com/j2se/1.4.2/docs/api/java/io/FileOutputStream.html#FileOutputStream(java.io.File,%20boolean)) which lets you force it to append to the file rather than overwrite it. Change your code to
```
JarOutputStream zos = new JarOut... | How do I update a pre-existing Jar file | [
"",
"java",
"jar",
""
] |
How do I load MS Word document (.doc and .docx) to memory (variable) without doing this?:
*wordApp.Documents.Open*
I don't want to open MS Word, I just want that text inside.
You gave me answer for DOCX, but what about DOC? I want free and high performance solution - not to open 12.000 instances of Word to process a... | You can use wordconv.exe which is part of the Office Compatibility Pack to convert from doc to docx.
<http://www.microsoft.com/downloads/details.aspx?familyid=941b3470-3ae9-4aee-8f43-c6bb74cd1466&displaylang=en>
Just call the command like so:
"C:\Program Files\Microsoft Office\Office12\wordconv.exe" -oice -nme InputF... | If you are dealing with docx you can do this with out doing any interop with Word
.docx file actually a ZIP contains an XML file , you can read the XML
Please refer the below links
<http://conceptdev.blogspot.com/2007/03/open-docx-using-c-to-extract-text-for.html>
[Office (2007) Open XML File Formats](http://msdn.mic... | How to load text of MS Word document in C# (.NET)? | [
"",
"c#",
".net",
"ms-word",
"docx",
"doc",
""
] |
I am trying to use some pinvoke code to call a C function. The function fills a buffer with data.
The structure is set up as a DWORD for the length, followed by a string. How do I extract the string from the IntPtr?
```
IntPtr buffer = Marshal.AllocHGlobal(nRequiredSize);
PInvokedFunction(buffer, nRequiredSize);
s... | You should do this:
```
IntPtr sBuffer = new IntPtr( buffer.ToInt64() + 4 );
string s = Marshal.PtrToStringAuto( sBuffer );
```
So your code is 64bit safe. | The best I could come up with was the following, though the use of the UnmanagedMemoryStream seems a bit of a hack.
```
IntPtr buffer = Marshal.AllocHGlobal((int)nRequiredSize);
PInvokedFunction(buffer, nRequiredSize);
UnmanagedMemoryStream memStream = new UnmanagedMemoryStream(buffer.ToPointer(), nRequiredSize);
... | Pointer math in C# | [
"",
"c#",
"pinvoke",
"pointer-arithmetic",
""
] |
I'm starting a new application and looking at using an ORM -- in particular, SQLAlchemy.
Say I've got a column 'foo' in my database and I want to increment it. In straight sqlite, this is easy:
```
db = sqlite3.connect('mydata.sqlitedb')
cur = db.cursor()
cur.execute('update table stuff set foo = foo + 1')
```
I fig... | SQLAlchemy's ORM is meant to be used together with the SQL layer, not hide it. But you do have to keep one or two things in mind when using the ORM and plain SQL in the same transaction. Basically, from one side, ORM data modifications will only hit the database when you flush the changes from your session. From the ot... | ```
session.query(Clients).filter(Clients.id == client_id_list).update({'status': status})
session.commit()
```
Try this =) | Efficiently updating database using SQLAlchemy ORM | [
"",
"python",
"orm",
"sqlalchemy",
""
] |
I've been doing some socket programming to transmit information across the wire. I've run into a problem with DataOutputStream.writeUTF(). It seems to allow strings of up to 64k but I have a few situations where I can run over this. Are there any good alternatives that support larger strings or do I need to roll my own... | It actually uses a two bytes to write the length of the string before using an algorithm that compacts it into one, two or three bytes per character. (See the documentation on java.io.DataOutput) It is close to UTF-8, but even though documented as being so, there are compatibility problems. If you are not terribly worr... | `ObjectOutputStream.writeObject()` properly handles long strings (verified by looking at the source code). Write the string out this way:
```
ObjectOutputStream oos = new ObjectOutputStream(out);
... other write operations ...
oos.writeObject(myString);
... other write operations ...
```
Read it this way:
```
Object... | Writing large strings with DataOutputStream | [
"",
"java",
"dataoutputstream",
""
] |
I need to execute a select and then update some of the rows in the `ResultSet` in an atomic way.
The code I am using looks like (simplified):
```
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
rs = stmt.executeQuery("SELECT ...");
while (rs.next()) {
if (conditions_to_up... | There's probably a whole heap of technologies and concepts that come into play here, and things start to get fairly sticky when you start considering multi-threaded / multi request applications.
As Iassevk stated, you should look into using [Transactions](http://java.sun.com/docs/books/tutorial/jdbc/basics/transaction... | > What happens if any other process has changed the database row that you are updating via updateRow() ? Is there any way to lock the rows in the ResultSet ?
In Oracle, you can kinda mark certain rows for update by issuing the following SQL.
```
select cola, colB from tabA for update;
```
The next transaction/thread... | Update more than one row atomically | [
"",
"java",
"database",
"jdbc",
"atomic",
""
] |
I know it is a good practice to declare virtual destructors for base classes in C++, but is it always important to declare `virtual` destructors even for abstract classes that function as interfaces? Please provide some reasons and examples why. | It's even more important for an interface. Any user of your class will probably hold a pointer to the interface, not a pointer to the concrete implementation. When they come to delete it, if the destructor is non-virtual, they will call the interface's destructor (or the compiler-provided default, if you didn't specify... | The answer to your question is often, but not always. If your abstract class forbids clients to call delete on a pointer to it (or if it says so in its documentation), you are free to not declare a virtual destructor.
You can forbid clients to call delete on a pointer to it by making its destructor protected. Working ... | Why should I declare a virtual destructor for an abstract class in C++? | [
"",
"c++",
"inheritance",
"virtual-destructor",
""
] |
I would like to create a batch script, to go through 20,000 links in a DB, and weed out all the 404s and such. How would I get the HTTP status code for a remote url?
Preferably not using curl, since I dont have it installed. | CURL would be perfect but since you don't have it, you'll have to get down and dirty with sockets. The technique is:
1. Open a socket to the server.
2. Send an HTTP HEAD request.
3. Parse the response.
Here is a quick example:
```
<?php
$url = parse_url('http://www.example.com/index.html');
$host = $url['host'];
$... | If im not mistaken none of the php built-in functions return the http status of a remote url, so the best option would be to use sockets to open a connection to the server, send a request and parse the response status:
pseudo code:
```
parse url => $host, $port, $path
$http_request = "GET $path HTTP/1.0\nHhost: $host... | How do you get the HTTP status code for a remote domain in php? | [
"",
"php",
""
] |
Is there a (standardized) way to get the name of the current method using c++?
Using GNU GCC you can do this by using the macro `__FUNCTION__` and `__PRETTY_FUNCTION__` (surrounded by 2 underscores), however, this is of course non portable. Is there a way to do this in standard c++ or a way to make it portable? | The `__func__` identifier is part of the C99 standard and is in the C++0x draft.
The identifier `__func__` is implicitly declared by the compiler as if the following were at the very start of each function body:
```
static const char __func__[] = "function-name";
```
where `function-name` is an implementation-define... | No...... but some things end up being non standard standards!
see <http://msdn.microsoft.com/en-us/library/b0084kay(VS.80).aspx> which outlines the ANSI standard stuff, and then microsofs which includes *FUNCTION* | Getting the name of the current method in c++ | [
"",
"c++",
"introspection",
""
] |
It sounds a lot more complicated than it really is.
So in Perl, you can do something like this:
```
foreach my $var (@vars) {
$hash_table{$var->{'id'}} = $var->{'data'};
}
```
I have a JSON object and I want to do the same thing, but with a javascript associative array in jQuery.
I've tried the following:
```
ha... | I think you can use the JSON response as an associative array. So you should be able to go directly in and use the JSON.
Assuming you received the above example:
```
$('result').innerHTML = data['results']['dataset_a']['dataset_two']['data'];
// Or the shorter form:
$('result').innerHTML = data.results.dataset_a.data... | Why would you want to change an array into another array ?-)
-- why not simply access the data, if you want to simplify or filter, you can traverse the arrays of the object directly !-) | Dynamic Associative Array Creation in Javascript from JSON | [
"",
"javascript",
"jquery",
"json",
""
] |
What's the term for this design?
```
object.method1().method2().method3()
```
..when all methods return \*this?
I found the term for this a while ago, but lost it meanwhile.
I have no clue how to search for this on google :)
Also if anyone can think of a better title for the question, feel free to change it.
Thanks... | Looks to me like you are describing a fluent interface. Ive also heard it referred to as pipelineing or chaining.
Update-Gishu: <http://martinfowler.com/bliki/FluentInterface.html> | > It chains these method calls, which is why this is called [method chaining](https://isocpp.org/wiki/faq/references#method-chaining) | What's the term for design ala "object.method1().method2().method3()"? | [
"",
"c++",
""
] |
I have a text file where I want to change only the first line of the file. The file could be millions of rows long, so I'd rather not have to loop over everything, so I'm wondering if there is another way to do this.
I'd also like to apply some rules to the first line so that I replace instances of certain words with ... | A `RandomAccessFile` will do the trick, unless the length of the resulting line is different from the length of the original line.
If it turns out you are forced to perform a copy (where the first line is replaced and the rest of the data shall be copied as-is), I suggest using a `BufferedReader` and `BufferedWriter`.... | If the new line has a different amount of characters (bytes) than the original first line, you will have to re-write the whole file to get rid of the gap or avoid overwriting part of the second line.
Of course, various tools like `String.replaceFirst(String regex, String replacement)` ([javadoc](http://java.sun.com/j2... | Replace first line of a text file in Java | [
"",
"java",
""
] |
Hi Guys could you please help me refactor this so that it is sensibly pythonic.
```
import sys
import poplib
import string
import StringIO, rfc822
import datetime
import logging
def _dump_pop_emails(self):
self.logger.info("open pop account %s with username: %s" % (self.account[0], self.account[1]))
self.popi... | This isn't refactoring (it doesn't need refactoring as far as I can see), but some suggestions:
You should use the email package rather than rfc822. Replace rfc822.Message with email.Message, and use email.Utils.parseaddr(msg["From"]) to get the name and email address, and msg["Subject"] to get the subject.
Use os.pa... | I don't see anything significant wrong with that code -- is it behaving incorrectly, or are you just looking for general style guidelines?
A few notes:
1. Instead of `logger.info ("foo %s %s" % (bar, baz))`, use `"foo %s %s", bar, baz`. This avoids the overhead of string formatting if the message won't be printed.
2.... | Incoming poplib refactoring using windows python 2.3 | [
"",
"python",
"email",
"refactoring",
"poplib",
""
] |
I am attempting to load an activex object on the same page where my flex application resides. Is this possible? Can I have 2 object tags on one page?
As of right now the flex application loads fine but when I attempt to access the activeX control it says its null. But if I have the same activex control on its own webp... | One of the issues was that my browser was caching the page, I realized that once I made a change to the name of the ActiveX object and the error thrown was still referencing the old name of the ActiveX object. The other error was I had a Var with the same name of the ActiveX object inside the javascript code, that seem... | Whoops, I found the error. It was a simple error in my javascript code. Turns out it works fine adding another Object tag and loading another activex control. Chalk this up as a learning experience. | Loading ActiveX object on Flex application html page | [
"",
"javascript",
"html",
"apache-flex",
"activex",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.