Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I have an instance of a `System.Drawing.Bitmap` and would like to make it available to my WPF app in the form of a `System.Windows.Media.Imaging.BitmapImage`.
What would be the best approach for this? | Thanks to Hallgrim, here is the code I ended up with:
```
ScreenCapture = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
bmp.GetHbitmap(),
IntPtr.Zero,
System.Windows.Int32Rect.Empty,
BitmapSizeOptions.FromWidthAndHeight(width, height));
```
I also ended up binding to a BitmapSource inst... | How about loading it from MemoryStream?
```
using(MemoryStream memory = new MemoryStream())
{
bitmap.Save(memory, ImageFormat.Png);
memory.Position = 0;
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.StreamSource = memory;
bitmapImage.CacheOption = BitmapCache... | Load a WPF BitmapImage from a System.Drawing.Bitmap | [
"",
"c#",
"wpf",
"bitmap",
""
] |
Are there any dictionary classes in the .NET base class library which allow duplicate keys to be used? The only solution I've found is to create, for example, a class like:
```
Dictionary<string, List<object>>
```
But this is quite irritating to actually use. In Java, I believe a MultiMap accomplishes this, but canno... | If you're using .NET 3.5, use the [`Lookup`](http://msdn.microsoft.com/en-us/library/bb460184.aspx) class.
EDIT: You generally create a `Lookup` using [`Enumerable.ToLookup`](http://msdn.microsoft.com/en-us/library/system.linq.enumerable.tolookup.aspx). This does assume that you don't need to change it afterwards - bu... | The List class actually works quite well for key/value collections containing duplicates where you would like to iterate over the collection. Example:
```
List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>();
// add some values to the collection here
for (int i = 0; i < list.Count; i+... | Duplicate keys in .NET dictionaries? | [
"",
"c#",
".net",
"dictionary",
"multimap",
""
] |
This may seem like a programming 101 question and I had thought I knew the answer but now find myself needing to double check. In this piece of code below, will the exception thrown in the first catch block then be caught by the general Exception catch block below?
```
try {
// Do something
} catch(IOException e) {
... | No, since the new `throw` is not in the `try` block directly. | No. It's very easy to check.
```
public class Catch {
public static void main(String[] args) {
try {
throw new java.io.IOException();
} catch (java.io.IOException exc) {
System.err.println("In catch IOException: "+exc.getClass());
throw new RuntimeException();
... | Exception thrown inside catch block - will it be caught again? | [
"",
"java",
"exception",
""
] |
I'm building an installer for an application. The user gets to select a datasource they have configured and nominate what type of database it is. I want to confirm that the database type is indeed Postgres, and if possible, what version of Postgres they are running by sending a SQL statement to the datasource. | Try this:
```
mk=# SELECT version();
version
-----------------------------------------------------------------------------------------------
PostgreSQL 8.3.3 on i486-pc-linux-gnu, compiled by GCC cc (GCC) 4.2.3 (Ubuntu 4.2.3-2ubun... | `SHOW server_version;`
(for completeness) | How can I confirm a database is Postgres & what version it is using SQL? | [
"",
"sql",
"postgresql",
""
] |
Any recommended crypto libraries for Python. I know I've asked something similar in [x509 certificate parsing libraries for Java](https://stackoverflow.com/questions/143523/), but I should've split the question in two.
What I need is the ability to parse X.509 Certificates to extract the information contained in them.... | You might want to try [keyczar](http://www.keyczar.org/) as mentioned by me in your other post, since that library actually has implementations for both python and java. That would make it easier to use it in both contexts.
A word of warning: I have not actually used this library 8(, so please take this with a grain o... | Use M2Crypto, it is the most complete tool IMHO | Crypto/X509 certificate parsing libraries for Python | [
"",
"python",
"cryptography",
"openssl",
"x509",
""
] |
I am building a menu in HTML/CSS/JS and I need a way to prevent the text in the menu from being highlighted when double-clicked on. I need a way to pass the id's of several divs into a function and have highlighting turned off within them.
So when the user accidentally (or on purpose) double clicks on the menu, the me... | In (Mozilla, Firefox, Camino, Safari, Google Chrome) you can use this:
```
div.noSelect {
-moz-user-select: none; /* mozilla browsers */
-khtml-user-select: none; /* webkit browsers */
}
```
For IE there is no CSS option, but you can capture the ondragstart event, and return false;
**Update**
Browser support fo... | You could use this CSS to simply hide the selection color (not supported by IE):
```
#id::-moz-selection {
background: transparent;
}
#id::selection {
background: transparent;
}
``` | What is the best way to prevent highlighting of text when clicking on its containing div in javascript? | [
"",
"javascript",
"html",
"css",
""
] |
I have made a SVG image, or more like mini application, for viewing graphs of data. I want to include this in a HTML page, and call methods on the SVG image.
Example:
```
<object id="img" data="image.svg" width="500" height="300"/>
<script>document.getElementById("img").addData([1,23,4]);</script>
```
Is it at all p... | Solution:
in svg:
```
<script>document.method = function() {}</script>
```
in html (using prototype to add event listeners):
```
<script>$("img").observe("load", function() {$("img").contentDocument.method()});
```
You need to listen to the load event on the image. Once the image is loaded, you can use the `elemen... | Things are actually simpler than you expect. You do not really need to read convoluted tutorial to understand the concept, neither do you have to use JQuery. Here is the basic layout:
* A JavaScript function in your html document.
```
<script type="text/javascript">
function change(){
var s=document.getEl... | Is it possible to manipulate an SVG document embedded in an HTML doc with JavaScript? | [
"",
"javascript",
"html",
"svg",
""
] |
I would like to create a page where all images which reside on my website are listed with title and alternative representation.
I already wrote me a little program to find and load all HTML files, but now I am stuck at how to extract `src`, `title` and `alt` from this HTML:
```
<img src="/image/fluffybunny.jpg" title... | ## EDIT : now that I know better
Using regexp to solve this kind of problem is [a bad idea](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454) and will likely lead in unmaintainable and unreliable code. Better use an [HTML parser](http://simplehtmldom.so... | ```
$url="http://example.com";
$html = file_get_contents($url);
$doc = new DOMDocument();
@$doc->loadHTML($html);
$tags = $doc->getElementsByTagName('img');
foreach ($tags as $tag) {
echo $tag->getAttribute('src');
}
``` | How to extract img src, title and alt from html using php? | [
"",
"php",
"html",
"regex",
"html-parsing",
"html-content-extraction",
""
] |
We have got loads of options for `php + MySQL + Apache` combo... Which is the best pack among these ?
Lets confine our ideas to `WAMP vs XAMPP`, is there a better option to go for?
I created an online programming contest web app called `CodeFire` on `XAMPP`, later I had to switch to `WAMP`, where none of the `php` sc... | I like XAMPP, personally. I have an install running on a thumbdrive that I carry around that's pretty much my development environment for LAMP web dev on any machine I happen to be at (I'm mostly on Windows client machines).
Small, fully-functional, and stable - works really well for my needs. | I like [WAMP](http://www.wampserver.com/en/) the best, real simple interface and I can easily switch between different versions of PHP 5.26/4.44/4.3.9, MySQL 5/4, and Apache 2/1.3 | XAMPP and WAMP in the LAMP, what's the best? | [
"",
"php",
"mysql",
"apache",
""
] |
I have a temp table with the exact structure of a concrete table `T`. It was created like this:
```
select top 0 * into #tmp from T
```
After processing and filling in content into `#tmp`, I want to copy the content back to `T` like this:
```
insert into T select * from #tmp
```
This is okay as long as `T` doesn't ... | As identity will be generated during insert anyway, could you simply remove this column from #tmp before inserting the data back to T?
```
alter table #tmp drop column id
```
**UPD:** Here's an example I've tested in SQL Server 2008:
```
create table T(ID int identity(1,1) not null, Value nvarchar(50))
insert into T... | SET IDENTITY\_INSERT ON
INSERT command
SET IDENTITY\_INSERT OFF | Insert into ... Select *, how to ignore identity? | [
"",
"sql",
"sql-server",
""
] |
**EDIT: This question is more about language engineering than C++ itself. I used C++ as an example to show what I wanted, mostly because I use it daily. I didn't want to know how it works on C++ but open a discussion on how it *could* be done.**
That's not the way it works right now, that's the way I *wish* it could b... | I guess you're missing the point of C++, and C++ semantics. You missed the fact **C++ is correct in passing (almost) everything by value, because it's the way it's done in C. Always**. But not only in C, as I'll show you below...
## Parameters Semantics on C
In C, everything is passed by value. "primitives" and "PODs... | A compiler option that totally changes the meaning of a section of code sounds like a really bad idea to me. Either get use to the C++ syntax or find a different language. | Default pass-by-reference semantics in C++ | [
"",
"c++",
"programming-languages",
"syntax",
"semantics",
""
] |
I am currently working on an web application that uses ASP.NET 2.0 framework. I need to redirect to a certain page, say SessionExpired.aspx, when the user session expires. There are lot of pages in the project, so adding code to every page of the site is not really a good solution. I have MasterPages though, which I th... | You can handle this in global.asax in the Session\_Start event. You can check for a session cookie in the request there. If the session cookie exists, the session has expired:
```
public void Session_OnStart()
{
if (HttpContext.Current.Request.Cookies.Contains("ASP.NET_SessionId") != null)
{
... | I usually add an HtmlMeta control to the Page.Header.Controls collection on the master page when the user has "logged in". Set it to Refresh to your SessionExpired.aspx page with an appropriate timeout length, and you're good to go. | How can I redirect to a page when the user session expires? | [
"",
"c#",
"asp.net",
""
] |
Is there a way of comparing two bitmasks in Transact-SQL to see if any of the bits match? I've got a User table with a bitmask for all the roles the user belongs to, and I'd like to select all the users that have *any* of the roles in the supplied bitmask. So using the data below, a roles bitmask of 6 (designer+program... | The answer to your question is to use the Bitwise `&` like this:
```
SELECT * FROM UserTable WHERE Roles & 6 != 0
```
The `6` can be exchanged for any combination of your bitfield where you want to check that any user has one or more of those bits. When trying to validate this I usually find it helpful to write this ... | Use the Transact-SQL [bitwise AND operator](http://msdn.microsoft.com/en-us/library/ms174965.aspx) "&" and compare the result to zero. Even better, instead of coding the roles as bits of an integer column, use boolean columns, one for each role. Then your query would simply be designer AND programmer friendly. If you e... | Comparing two bitmasks in SQL to see if any of the bits match | [
"",
"sql",
"sql-server",
"t-sql",
"bitmask",
""
] |
In PHP, a string enclosed in "double quotes" will be parsed for variables to replace whereas a string enclosed in 'single quotes' will not. In Python, does this also apply? | [No](http://docs.python.org/reference/lexical_analysis.html#strings):
> ### 2.4.1. String and Bytes literals
>
> ...In plain English: Both types of literals can be enclosed in matching single quotes (`'`) or double quotes (`"`). They can also be enclosed in matching groups of three single or double quotes (these are g... | Python is one of the few (?) languages where ' and " have identical functionality. The choice for me usually depends on what is inside. If I'm going to quote a string that has single quotes within it I'll use double quotes and visa versa, to cut down on having to escape characters in the string.
Examples:
```
"this d... | Is there any difference between "string" and 'string' in Python? | [
"",
"python",
"string",
"quotes",
"double-quotes",
""
] |
Is it possible to have a `MySQLi prepared statement` within the `fetch()` call of a previous statement? If not, what's the best way around it?
Example code:
```
if($stmt = $link->prepare("SELECT item FROM data WHERE id = ?")) {
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->bind_result($item);
... | You should be able to do that, although you make have to start a second connection. | This is the single connection way:
```
if($stmt = $link->prepare("SELECT item FROM data WHERE id = ?")) {
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->store_result(); // <-- this
$stmt->bind_result($item);
while( $stmt->fetch() ) {
/* Other code here */
$itemSummary = $item... | Possible to use multiple/nested MySQLi statements? | [
"",
"php",
"mysql",
"mysqli",
""
] |
In wxPython, if I create a list of radio buttons and place the list initially, is it possible to change the contents in that list later?
For example, I have a panel that uses a boxSizer to place the widgets initially. One of those widgets is a list of radio buttons (I have also tried a normal radiobox). I would like t... | To make new list elements appear in correct places, you have to re-layout the grid after adding new elements to it. For example, to add a few new items, you could call:
```
def addNewSkills(self, newSkillList):
'''newSkillList is a list of skill names you want to add'''
for skillName in newSkillList:
n... | Two possible solutions
1. Rebuild the sizer with the radio widgets each time you have to make a change
2. Hold the radio button widgets in a list, and call SetLabel each time you have to change their labels. | Dynamic radio button creation | [
"",
"python",
"user-interface",
"layout",
"wxpython",
""
] |
> **Possible Duplicate:**
> [Pre & post increment operator behavior in C, C++, Java, & C#](https://stackoverflow.com/questions/6457130/pre-post-increment-operator-behavior-in-c-c-java-c-sharp)
Here is a test case:
```
void foo(int i, int j)
{
printf("%d %d", i, j);
}
...
test = 0;
foo(test++, test);
```
I would... | This is an example of unspecified behavior. The standard does **not** say what order arguments should be evaluated in. This is a compiler implementation decision. The compiler is free to evaluate the arguments to the function in any order.
In this case, it looks like actually processes the arguments right to left inst... | This is not just *unspecified* behaviour, it is actually **undefined behaviour** .
Yes, the order of argument evaluation is *unspecified*, but it is *undefined* to both read and modify a single variable without an intervening sequence point unless the read is solely for the purpose of computing the new value. There is... | Post increment operator behavior | [
"",
"c++",
"c",
"post-increment",
""
] |
I have email addresses encoded with HTML character entities. Is there anything in .NET that can convert them to plain strings? | You can use [`HttpUtility.HtmlDecode`](https://learn.microsoft.com/en-us/dotnet/api/system.web.httputility.htmldecode).
If you are using .NET 4.0+ you can also use [`WebUtility.HtmlDecode`](https://learn.microsoft.com/en-us/dotnet/api/system.net.webutility.htmldecode) which does not require an extra assembly reference... | On .Net 4.0:
```
System.Net.WebUtility.HtmlDecode()
```
No need to include assembly for a C# project | How can I decode HTML characters in C#? | [
"",
"c#",
""
] |
What number of classes do you think is ideal per one namespace "branch"? At which point would one decide to break one namespace into multiple ones? Let's not discuss the logical grouping of classes (assume they are logically grouped properly), I am, at this point, focused on the maintainable vs. not maintainable number... | "42? No, it doesn't work..."
Ok, let's put our programming prowess to work and see what is Microsoft's opinion:
```
# IronPython
import System
exported_types = [
(t.Namespace, t.Name)
for t in System.Int32().GetType().Assembly.GetExportedTypes()]
import itertools
get_ns = lambda (ns, typename): ns
sorted_exporte... | With modern IDEs and other dev tools, I would say that if all the classes belong in a namespace, then there is no arbitrary number at which you should break up a namespace just for maintainability. | Ideal number of classes per namespace branch | [
"",
"c#",
"namespaces",
"grouping",
""
] |
That's the question: Which library can help me to access data available via WebDAV in my Java-programs? OpenSource is preferred. | The now deprecated [Apache Jakarta Slide](http://jakarta.apache.org/slide/) project includes a Java [WebDAV client library](http://jakarta.apache.org/slide/clientjavadoc/index.html) - but this project is retired due to the lack of a developer community.
[Apache Jackrabbit](http://jackrabbit.apache.org/) is mentioned a... | I created a very easy to use java webdav client: <http://sardine.googlecode.com/>
This now moved to github : <https://github.com/lookfirst/sardine> | Which Java-library can be used to access data via WebDAV? | [
"",
"java",
"webdav",
""
] |
For example, I have an ASP.NET form that is called by another aspx:
```
string url = "http://somewhere.com?P1=" + Request["param"];
Response.Write(url);
```
I want to do something like this:
```
string url = "http://somewhere.com?P1=" + Request["param"];
string str = GetResponse(url);
if (str...) {}
```
I need to g... | Webclient.DownloadString() is probably want you want. | ```
WebClient client = new WebClient();
string response = client.DownloadString(url);
``` | How do I read an HttpResponse in ASP.NET 2.0? | [
"",
"c#",
"asp.net",
"httpresponse",
""
] |
When I try the following lookup in my code:
```
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
return (DataSource) envCtx.lookup("jdbc/mydb");
```
I get the following exception:
```
java.sql.SQLException: QueryResults: Unable to initialize naming context:
Nam... | Thanks for the response toolkit.... yes, I can access my datasource by going directly to java:jdbc/mydb, but I'm using an existing code base that connects via the ENC. Here's some interesting info that I've found out ....
1. The above code works with **JBoss 4.2.2.GA** and here's the JNDI ctx parameters being used:
... | java:comp/env is known as the Enterprise Naming Context (ENC) and is not globally visible. See [here](http://www.informit.com/articles/article.aspx?p=384904) for more information. You will need to locate the global JNDI name which your datasource is regsitered at.
The easiest way to do this is to navigate to JBoss' we... | Help configuring JNDI with embedded JBoss in Tomcat 5.5.x | [
"",
"java",
"jboss",
"seam",
"jndi",
"embedded-jboss",
""
] |
Is there a Java package providing funcionality like the .Net System.Data namespace ?
Specificaly the DataSet and Adaptor classes ? | Use [java.util](http://java.sun.com/javase/6/docs/api/java/util/package-summary.html) for the collections.
[java.sql](http://java.sun.com/javase/6/docs/api/java/sql/package-summary.html) for databases. | The equivalent to ADO.NET is JDBC. You can get the flavor of it here:
<http://www.heimetli.ch/jdbc/JDBCQuery.html> | Is there a Java equivalent for .Net System.Data? | [
"",
"java",
".net",
"database",
""
] |
I have developed some custom DAO-like classes to meet some very specialized requirements for my project that is a server-side process that does not run inside any kind of framework.
The solution works great except that every time a new request is made, I open a new connection via MySQLdb.connect.
What is the best "dr... | IMO, the "more obvious/more idiomatic/better solution" is to use an existing ORM rather than invent DAO-like classes.
It appears to me that ORM's are more popular than "raw" SQL connections. Why? Because Python *is* OO, and the mapping from a SQL row to an object *is* absolutely essential. There aren't many use cases ... | In MySQL?
I'd say don't bother with the connection pooling. They're often a source of trouble and with MySQL they're not going to bring you the performance advantage you're hoping for. This road may be a lot of effort to follow--politically--because there's so much best practices hand waving and textbook verbiage in t... | What is the best solution for database connection pooling in python? | [
"",
"python",
"mysql",
"connection-pooling",
""
] |
I have a Python module installed on my system and I'd like to be able to see what functions/classes/methods are available in it.
I want to call the `help` function on each one. In Ruby I can do something like `ClassName.methods` to get a list of all the methods available on that class. Is there something similar in Py... | Use the [`inspect`](https://docs.python.org/3/library/inspect.html) module:
```
from inspect import getmembers, isfunction
from somemodule import foo
print(getmembers(foo, isfunction))
```
Also see the [`pydoc`](https://docs.python.org/3/library/pydoc.html) module, the `help()` function in the interactive interprete... | You can use `dir(module)` to see all available methods/attributes. Also check out PyDocs. | How to list all functions in a module? | [
"",
"python",
"reflection",
"module",
"inspect",
""
] |
I'm attempting to do an AJAX call (via JQuery) that will initiate a fairly long process. I'd like the script to simply send a response indicating that the process has started, but JQuery won't return the response until the PHP script is done running.
I've tried this with a "close" header (below), and also with output ... | The following PHP manual page (incl. user-notes) suggests multiple instructions on how to close the TCP connection to the browser without ending the PHP script:
* [Connection handling *Docs*](http://php.net/features.connection-handling)
Supposedly it requires a bit more than sending a close header.
---
OP then conf... | It's necessary to send these 2 headers:
```
Connection: close
Content-Length: n (n = size of output in bytes )
```
Since you need know the size of your output, you'll need to buffer your output, then flush it to the browser:
```
// buffer all upcoming output
ob_start();
echo 'We\'ll email you as soon as this is done... | How do I close a connection early? | [
"",
"php",
"jquery",
"ajax",
""
] |
First of all, I'm fairly sure snapping to grid is fairly easy, however I've run into some odd trouble in this situation and my maths are too weak to work out specifically what is wrong.
Here's the situation
I have an abstract concept of a grid, with Y steps exactly Y\_STEP apart (the x steps are working fine so ignor... | Ok, I'm answering my own question here, as alexk mentioned, using int to truncate was my mistake.
The behaviour I'm after is best modeled by math.floor().
Apologies, the original question does not contain enough information to really work out what the problem is. I didn't have the extra bit of information at that poi... | Do you have a typo in positionChanged() ?
```
def positionChanged(self, newPos):
self.snappedPos = snapToGrid(newPos, Y_OFFSET, Y_STEP)
```
I guess you are off by one pixel because of the accuracy problems during float division. Try changing your snapToGrid() to this:
```
def snapToGrid(originalPos, offset, step... | What is wrong with my snap to grid code? | [
"",
"python",
"graphics",
"grid",
""
] |
I'd like to automatically change my database connection settings on a per-vhost basis, so that I don't have to edit any PHP code as it moves from staging to live and yet access different databases. This is on a single dedicated server.
So I was wondering, can I set a PHP variable or constant in httpd.conf as part of t... | Did you tried to use the .htaccess file? You could override the php.ini values using it.
Just put the .htaccess file into your htdocs directory:
```
php_value name value
```
Futher information:
* <https://php.net/manual/en/configuration.changes.php>
* <https://php.net/manual/en/ini.php> | Yep...you can do this:
```
SetEnv DATABASE_NAME testing
```
and then in PHP:
```
$database = $_SERVER["DATABASE_NAME"];
```
or
```
$database = getenv("DATABASE_NAME");
``` | Setting PHP variables in httpd.conf? | [
"",
"php",
"apache",
""
] |
I'm using .NET 3.5. I have two string arrays, which may share one or more values:
```
string[] list1 = new string[] { "apple", "orange", "banana" };
string[] list2 = new string[] { "banana", "pear", "grape" };
```
I'd like a way to merge them into one array with no duplicate values:
```
{ "apple", "orange", "banana"... | ```
string[] result = list1.Union(list2).ToArray();
```
from [msdn](http://msdn.microsoft.com/en-us/library/bb341731.aspx): "This method excludes duplicates from the return set. This is different behavior to the Concat(TSource) method, which returns all the elements in the input sequences including duplicates." | Why do you imagine that it would be inefficient? As far as I'm aware, both Concat and Distinct are evaluated lazily, using a HashSet behind the scenes for Distinct to keep track of the elements which have already been returned.
I'm not sure how you'd manage to make it more efficient than that in a general way :)
EDIT... | Efficiently merge string arrays in .NET, keeping distinct values | [
"",
"c#",
"linq",
"arrays",
"merge",
"distinct",
""
] |
I am trying to figure out this:
```
c = 1
def f(n):
print c + n
def g(n):
c = c + n
f(1) # => 2
g(1) # => UnboundLocalError: local variable 'c' referenced before assignment
```
Thanks! | Within a function, variables that are assigned to are treated as local variables by default. To assign to global variables, use the [`global`](https://docs.python.org/3/reference/simple_stmts.html#the-global-statement) statement:
```
def g(n):
global c
c = c + n
```
This is one of the quirky areas of Python t... | Global state is something to avoid, especially needing to mutate it. Consider if `g()` should simply take two parameters or if `f()` and `g()` need to be methods of a common class with `c` an instance attribute
```
class A:
c = 1
def f(self, n):
print self.c + n
def g(self, n):
self.c += n
... | Python scope: "UnboundLocalError: local variable 'c' referenced before assignment" | [
"",
"python",
"scope",
""
] |
Could anyone explain with some examples when it is better to call functions by reference and when it is better to call by address? | Pass your arguments to function using reference whenever possible.
Passing arguments by reference eliminate the chance of them being NULL.
If you want it to be possible to pass NULL value to a function then use pointer. | This has already been discussed. See [Pointer vs. Reference](https://stackoverflow.com/questions/114180/pointer-vs-reference). | when to pass function arguments by reference and when by address? | [
"",
"c++",
"pointers",
"function",
"reference",
""
] |
As a way to find inspiration and improve my PHP skills, I am looking for some beautiful PHP source code to read, preferably an open source "standard" web site rather than a more tool-like project such as phpMyAdmin.
So, where can I find some beautiful PHP code? | CodeIgniter code is beautiful. There are many projects written in CodeIgniter which are publically available and you can check out the source code.
Have a look at the [Getting started](http://codeigniter.com/user_guide/overview/getting_started.html) page of CodeIgniter's tutorial and read through. I can gaurantee you'... | Not all opensource projects are great examples as of how things are done.
Take a look at [PEAR](http://pear.php.net), [ezComponents](http://ezcomponents.org/) and the [Zend Framework](http://framework.zend.com). All three are pretty popular in the PHP world, they solve a ton of different problems [each sometimes with ... | Where to find beautiful PHP code to read? | [
"",
"php",
""
] |
According to this article [Silverlight 2 Beta 2](http://msdn.microsoft.com/en-us/library/cc197951(VS.95).aspx) supports the `DataContractJsonSerializer` object. But, when I try to use it VS says
> "Type 'DataContractJsonSerializer' is not defined".
I have a method marked as ScriptableMember that gets called from Java... | Actually the answer is, the DataContractJsonSerializer is part of Silverlight 2 Beta 2, but you need to add a reference to System.ServiceModel.Web to your Silverlight project to use it.
I didn't realize that you still needed to add dll references in Silverlight. I thought it automatically included everything in a simi... | There is a Silverlight version of Json.NET that will serialize your objects to JSON. It doesn't require [DataContract] and [DataMember] attributes all over your objects.
[Json.NET](http://james.newtonking.com/projects/json-net.aspx) | How do you Serialize ScriptObjects to JSON to save in Silverlight Isolated Storage? | [
"",
"javascript",
"silverlight",
"json",
"isolatedstorage",
""
] |
I am looking for a way to create a ZIP file from a folder in Windows C/C++ APIs. I can find the way to do this in VBScript using the Shell32.Application CopyHere method, and I found a tutorial explaining how to do it in C# also, but nothing for the C API (C++ is fine too, project already uses MFC).
I'd be really grate... | EDIT: This answer is old, but I cannot delete it because it was accepted. See the next one
<https://stackoverflow.com/a/121720/3937>
----- ORIGINAL ANSWER -----
There is sample code to do that here
[EDIT: Link is now broken]
<http://www.eggheadcafe.com/software/aspnet/31056644/using-shfileoperation-to.aspx>
Make ... | As noted elsewhere in the comments, this will only work on a already-created Zip file. The content must also not already exist in the zip file, or an error will be displayed. Here is the working sample code I was able to create based on the accepted answer. You need to link to shell32.lib and also kernel32.lib (for Cre... | Creating a ZIP file on Windows (XP/2003) in C/C++ | [
"",
"c++",
"winapi",
"zip",
""
] |
I keep reading about C99 and C++11 and all these totally sweet things that are getting added to the language standard that might be nice to use someday. However, we currently languish in the land of writing C++ in Visual Studio.
Will any of the new stuff in the standard ever get added to visual studio, or is Microsoft... | MS has a series of public replies to this, most of them blaming their users. Like this one:
<https://devblogs.microsoft.com/cppblog/iso-c-standard-update/>
> Now, the Visual C++ compiler team receives the occasionally question as to why we haven’t implemented C99. It’s really based on interest from our users. Where w... | Herb Sutter is both the chair and a very active member of C++ standardisation comitee, as well as software architect on Visual Studio for Microsoft.
He is among the author of the new C++ memory model standardised for C++0x. For example, the following papers:
<http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2... | Visual Studio support for new C / C++ standards? | [
"",
"c++",
"visual-studio",
"visual-c++",
"c++11",
"c99",
""
] |
Recently I noticed my application appears to be eating memory that never gets released. After profiling with CLRProfiler I've found that the Castle Windsor container I'm using is holding onto objects. These objects are declared with the lifestyle="transient" attribute in the config xml.
I've found if I put an explicit... | I think the answers here are missing a vital point - that this behavior is configurable out of the box via release policies - check out the documentation on the castle project site [here](http://www.castleproject.org/container/documentation/trunk/advanced/releasepolicy.html).
In many scenarios especially where your co... | One thing to note is that this seems to have been fixed in the Castle Trunk. In r5475, Hammett changed the default release policy in MicroKernel to `LifecycledComponentsReleasePolicy`. | Why does Castle Windsor hold onto transient objects? | [
"",
"c#",
"castle-windsor",
""
] |
I'm building a `PHP` site, but for now the only `PHP` I'm using is a half-dozen or so includes on certain pages. (I will probably use some database queries eventually.)
Are simple `include()` statements a concern for speed or scaling, as opposed to static `HTML`? What kinds of things tend to cause a site to bog down? | Strictly speaking, straight HTML will always serve faster than a server-side approach since the server doesn't have to do any interpretation of the code.
To answer the bigger question, there **are** a number of things that will cause your site to bog down; there's just no specific threshold for when your code is causi... | Certainly include() is slower than static pages. However, with modern systems you're not likely to see this as a bottleneck for a long time - if ever. The benefits of using includes to keep common parts of your site up to date outweigh the tiny performance hit, in my opinion (having different navigation on one page bec... | PHP performance considerations? | [
"",
"php",
"performance",
"scalability",
""
] |
I have been told that there is a performance difference between the following code blocks.
```
foreach (Entity e in entityList)
{
....
}
```
and
```
for (int i=0; i<entityList.Count; i++)
{
Entity e = (Entity)entityList[i];
...
}
```
where
```
List<Entity> entityList;
```
I am no CLR expect but from what I... | foreach creates an instance of an enumerator (returned from GetEnumerator) and that enumerator also keeps state throughout the course of the foreach loop. It then repeatedly calls for the Next() object on the enumerator and runs your code for each object it returns.
They don't boil down to the same code in any way, re... | [Here](http://www.codeproject.com/KB/cs/foreach.aspx) is a good article that shows the IL differences between the two loops.
Foreach is technically slower however much easier to use and easier to read. Unless performance is critical I prefer the foreach loop over the for loop. | Difference between foreach and for loops over an IEnumerable class in C# | [
"",
"c#",
"performance",
"loops",
""
] |
I am looking for some advice on what should I concentrate my efforts to get the needed skills to become a Java developer for Oracle applications. I'm bit confused as there are lot of technologies in the Java world. Where should I start? What to avoid? Is JDeveloper a good IDE for a beginner? | To become an Oracle Developer there is a bit more to learn than jdbc. You should take a look at the Oracle web site. It is kind of slow and not very intuitive but has a lot of good information. There are OUGs that have good info as well.
If you just want to access Oracle via JAVA then you should use a framework such a... | You're question is a little bit too vague in order to give a proper answer...
If you plan to query the Oracle Database from an External Java Program (Either within a Swing Application or an Application Server) then you need to learn 2 core APIs:
* JDBC (Java Database Connectivity)
* JPA (Java Persistence API)
JDBC i... | How to start learning JAVA for use with Oracle RDBMS? | [
"",
"java",
"oracle",
""
] |
I realize that parameterized SQL queries is the optimal way to sanitize user input when building queries that contain user input, but I'm wondering what is wrong with taking user input and escaping any single quotes and surrounding the whole string with single quotes. Here's the code:
```
sSanitizedInput = "'" & Repla... | First of all, it's just bad practice. Input validation is always necessary, but it's also always iffy.
Worse yet, blacklist validation is always problematic, it's much better to explicitly and strictly define what values/formats you accept. Admittedly, this is not always possible - but to some extent it must always b... | Okay, this response will relate to the update of the question:
> "If anyone knows of any specific way to mount a SQL injection attack against this sanitization method I would love to see it."
Now, besides the MySQL backslash escaping - and taking into account that we're actually talking about MSSQL, there are actuall... | Can I protect against SQL injection by escaping single-quote and surrounding user input with single-quotes? | [
"",
"sql",
"security",
"sql-server-2000",
"sql-injection",
"sanitization",
""
] |
I can't get my GridView to enable a user to sort a column of data when I'm using a custom SqlDataSource.
I have a GridView in which the code in the ASP reference to it in the HTML is minimal:
```
<asp:GridView id="grid" runat="server" AutoGenerateColumns="False" AllowSorting="True">
</asp:GridView>
```
In the code-b... | First you need to add an event:
```
<asp:GridView AllowSorting="True" OnSorting="gvName_Sorting" ...
```
Then that event looks like:
```
protected void gvName_Sorting( object sender, GridViewSortEventArgs e )
{
...
//rebind gridview
}
```
You basically have to get your data again.
You're right that it look... | You could also just reassign the datasource.SelectCommand before the DataBind() call in the Sorting handler. Something like this:
```
protected void gvItems_Sorting(object sender, GridViewSortEventArgs e)
{
GridView gv = (GridView)sender;
SqlDataSource ds = (SqlDataSource)gv.DataSource;
ds.SelectCommand = ... | How to sort columns in an ASP.NET GridView if using a custom DataSource? | [
"",
"c#",
"asp.net",
"gridview",
"sqldatasource",
""
] |
Suppose I have a simple XHTML document that uses a custom namespace for attributes:
```
<html xmlns="..." xmlns:custom="http://www.example.com/ns">
...
<div class="foo" custom:attr="bla"/>
...
</html>
```
How do I match each element that has a certain custom attribute using jQuery? Using
```
$("div[custo... | [jQuery](https://jquery.com/) does not support custom namespaces directly, but you can find the divs you are looking for by using filter function.
```
// find all divs that have custom:attr
$('div').filter(function() { return $(this).attr('custom:attr'); }).each(function() {
// matched a div with custom::attr
$(th... | This works in some conditions:
`$("div[custom\\:attr]")`
However, for a more advanced method, see [this XML Namespace jQuery plug-in](http://www.rfk.id.au/blog/entry/xmlns-selectors-jquery) | jQuery attribute selectors: How to query for an attribute with a custom namespace | [
"",
"javascript",
"jquery",
""
] |
I am using c# 2005 i want to write string diagonally on image. But by default c# provides the option to write horizontally or vertically.
how we write diagonally?
Thanks | Do a [Graphics.rotateTransform](http://msdn.microsoft.com/en-us/library/system.drawing.graphics.rotatetransform.aspx) before the drawString call. Don't forget to reverse the change afterwards, as Phil Wright points out. | You can use the RotateTransform and TranslateTransform that are available on the Graphics class. Because using DrawString is GDI+ the transforms affects the drawing. So use something like this...
```
g.RotateTransform(45f);
g.DrawString("My String"...);
g.RotateTransform(-45f);
```
Don't forget to reverse the change ... | How can drawString method be used for writing diagonal way | [
"",
"c#",
"image",
"visual-studio-2005",
"gdi",
"drawstring",
""
] |
I'd like to get **uniform distribution** in range [0.0, 1.0)
If possible, please let the implementation make use of random bytes from **/dev/urandom.**
It would also be nice if your solution was **thread-safe**. If you're not sure, please indicate that.
See [some solution](https://stackoverflow.com/questions/146387#... | This seems to be pretty good way:
```` ```
unsigned short int r1, r2, r3;
// let r1, r2 and r3 hold random values
double result = ldexp(r1, -48) + ldexp(r2, -32) + ldexp(r3, -16);
``` ````
This is based on NetBSD's drand48 implementation. | **Simple**: A double has 52 bits of precision assuming IEEE. So generate a 52 bit (or larger) unsigned random integer (for example by reading bytes from dev/urandom), convert it into a double and divide it by 2^(number of bits it was).
This gives a numerically uniform distribution (in that the probability of a value b... | What is the best way to produce random double on POSIX? | [
"",
"c++",
"multithreading",
"random",
"posix",
""
] |
I can't figure out a use case for being able to annotate interfaces in Java.
Maybe someone could give me an example? | I've used it in Spring to annotate interfaces where the annotation should apply to all subclasses. For example, say you have a Service interface and you might have multiple implementations of the interface but you want a security annotation to apply regardless of the annotation. In that case, it makes the most sense to... | A use case that I am working with is javax/hibernate bean validation, we are using interfaces to help us on avoiding to define validations on every specific class.
```
public interface IUser {
@NotNull Long getUserId();
...
}
public class WebUser implements IUser {
private Long userId;
@Override
... | Annotations on Interfaces? | [
"",
"java",
"annotations",
""
] |
I am having some 10 lac records in my single SQL Table. I need to load this much record in my record. I need to know whether this will load. when i tried loading to report its showing out of memory exception. | This is impossible to answer unless you expand your question. What language are you using? Which report generating framwork? How does the SQL query look like?
**Edit:** Ah, ok, Microsoft SQL Reporting Services. Well, it should easily handle queries on tables with millions of tuples, I'm sure. It all depends on how you... | Reporting Services (and Cognos, Business Objects, and other BI reporting suites) generally have problems rendering reports that have hundreds of thousands of records or millions of records in the OUTPUT. Most of these systems don't have much of a problem aggregating the data into tens of thousands of records, but once ... | SQL Reporting services - Out of Memory Exception | [
"",
"asp.net",
"sql",
"reporting-services",
""
] |
Here's the problem:
In C# I'm getting information from a legacy ACCESS database. .NET converts the content of the database (in the case of this problem a string) to Unicode before handing the content to me.
How do I convert this Unicode string back to it's ASCII equivalent?
---
**Edit**
Unicode char 710 is indeed... | Okay, let's elaborate. Both [csgero](https://stackoverflow.com/questions/138449/how-to-convert-a-unicode-character-to-its-extended-ascii-equivalent#138579) and [bzlm](https://stackoverflow.com/questions/138449/how-to-convert-a-unicode-character-to-its-extended-ascii-equivalent#138583) pointed in the right direction.
B... | You cannot use the default ASCII encoding (Encoding.ASCII) here, but must create the encoding with the appropriate code page using Encoding.GetEncoding(...). You might try to use code page 1252, which is a superset of ISO 8859-1. | How to convert a Unicode character to its ASCII equivalent | [
"",
"c#",
".net",
"unicode",
"ascii",
""
] |
I've been creating snapins with the new MMC 3.0 classes and C#. I can't seem to find any examples of how to get rid of the "Console Root" node when creating the \*.msc files. I looked through the examples in the SDK, but I can't seem to find anything for this.
I have seen other snapins that do what I want, but I can't... | If I've understood you correctly, this isn't specific to MMC3, but it did take me a while to realise. Right-click on the node, and click `New Window from Here`. Then switch back to the Console Root window, and close it (Ctrl+F4).
Inside the .msc, it's //View/BookMark/@NodeID, which needs to be "2" (etc.), instead of "... | I know this is an older post, so maybe a response is not necessary but what you're trying to do requires saving a customized MSC file. As one reply states, add your SnapIn, select Open new window from here, then save the MSC file. This is your console configured to show your SnapIn as the RootNode rather than the Conso... | How to get rid of the "Console Root" node in a MMC 3.0 snapin? | [
"",
"c#",
"mmc",
"mmc3",
""
] |
I've been really enjoying Python programming lately. I come from a background of a strong love for C-based coding, where everything is perhaps more complicated than it should be (but puts hair on your chest, at least). So switching from C to Python for more complex things that don't require tons of speed has been more ... | Part of learning a new programming language is learning to read code in that language. A crutch like this may make it easier to read your own code, but it's going to impede the process of learning how to read anyone else's Python code. I really think you'd be better off getting rid of the end of block comments and gett... | I like to put blank lines around blocks to make control flow more obvious. For example:
```
if foo:
bar = baz
while bar not biz:
bar = i_am_going_to_find_you_biz_i_swear_on_my_life()
did_i_not_warn_you_biz()
my_father_is_avenged()
``` | Improving Python readability? | [
"",
"python",
"readability",
""
] |
We have fairly large C++ application which is composed of about 60 projects in Visual Studio 2005. It currently takes 7 minutes to link in Release mode and I would like to try to reduce the time. Are there any tips for improving the link time?
Most of the projects compile to static libraries, this makes testing easier... | If you're using the [`/GL`](http://msdn.microsoft.com/en-us/library/0zza0de8.aspx) flag to enable Whole Program Optimization (WPO) or the [`/LTCG`](http://msdn.microsoft.com/en-us/library/xbf3tbeh.aspx) flag to enable Link Time Code Generation, turning them off will improve link times significantly, at the expense of s... | See my suggestion made at Microsoft : <https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=511300>
You should vote for it ! Here is my last comment on it :
Yes we are using incremental linking to build most of our projects. For the biggest projects, it's useless. In fact, it takes more ti... | How to improve link performance for a large C++ application in VS2005 | [
"",
"c++",
"visual-studio-2005",
""
] |
I have this line in a useful Bash script that I haven't managed to translate into Python, where 'a' is a user-input number of days' worth of files to archive:
```
find ~/podcasts/current -mindepth 2 -mtime '+`a`+' -exec mv {} ~/podcasts/old \;
```
I am familiar with the os.name and getpass.getuser for the most genera... | ```
import os
import shutil
from os import path
from os.path import join, getmtime
from time import time
archive = "bak"
current = "cur"
def archive_old_versions(days = 3):
for root, dirs, files in os.walk(current):
for name in files:
fullname = join(root, name)
if (getmtime(fullna... | ```
import subprocess
subprocess.call(['find', '~/podcasts/current', '-mindepth', '2', '-mtime', '+5',
'-exec', 'mv', '{}', '~/podcasts/old', ';'], shell=True)
```
That is not a joke. This python script will do exactly what the bash one does.
**EDIT**: Dropped the backslash on the last param because ... | How to express this Bash command in pure Python | [
"",
"python",
"shell",
"language-comparisons",
""
] |
My question is possibly a subtle one:
Web services - are they extensions of the presentation/web layer? ..or are they extensions of the biz/data layer?
That may seem like a dumb question. *Web* services are an extension of the *web* tier. I'm not so sure though. I'm building a pretty standard webform with some AJAX-y... | In my mind, a web service has 2 characteristics:
1. it exposes data to external sources, i.e. other sources than the application they reside within. In this sense I agree with [@Pete](https://stackoverflow.com/questions/118595/ajax-webservices-extensions-of-web-or-biz-layer#118814) in that you're not really designing ... | I would say definitely not #2, but #1 is valid.
I also think (and this is opinion) that web services as a data access layer is not ideal. The service has to have a little bit more value (in general - I am sure there are notable exceptions to this). | AJAX webservices - extensions of web or biz layer? | [
"",
"asp.net",
"javascript",
"ajax",
"web-services",
""
] |
I'm trying to store a password in a file that I'd like to retrieve for later. Hashing is not an option as I need the password for connecting to a remote server for later.
The following code works well, but it creates a different output each time even though the key is the same. This is bad as when the application shut... | I believe that what's happening is that the crypto provider is randomly generating an IV. Specify this and it should no longer differ.
Edit: You can do this in your 'keyProvider' by setting the IV property. | According to the docs of CreateEncryptor:
> If the current IV property is a null
> reference (Nothing in Visual Basic),
> the GenerateIV method is called to
> create a new random IV.
This will make the ciphertext different every time.
Note: a way around this is discussed [here](https://stackoverflow.com/questions/65... | Encryption output always different even with same key | [
"",
"c#",
"encryption",
"cryptography",
""
] |
Can I use JavaScript to check (irrespective of scrollbars) if an HTML element has overflowed its content? For example, a long div with small, fixed size, the overflow property set to visible, and no scrollbars on the element. | Normally, you can compare the `client[Height|Width]` with `scroll[Height|Width]` in order to detect this... but the values will be the same when overflow is visible. So, a detection routine must account for this:
```
// Determines if the passed element is overflowing its bounds,
// either vertically or horizontally.
/... | Try comparing `element.scrollHeight` / `element.scrollWidth` to `element.offsetHeight` / `element.offsetWidth` :
```
if (element.scrollHeight > element.offsetHeight) {
console.log('element overflows')
}
```
See MDN docs :
* [offsetWidth](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetWidth)
* [... | Determine if an HTML element's content overflows | [
"",
"javascript",
"html",
"css",
""
] |
What is the best way to find if an object is in an array?
This is the best way I know:
```
function include(arr, obj) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] == obj) return true;
}
}
console.log(include([1, 2, 3, 4], 3)); // true
console.log(include([1, 2, 3, 4], 6)); // undefined
``` | As of ECMAScript 2016 you can use [`includes()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes)
```
arr.includes(obj);
```
If you want to support IE or other older browsers:
```
function include(arr,obj) {
return (arr.indexOf(obj) != -1);
}
```
EDIT:
This will n... | If you are using jQuery:
```
$.inArray(5 + 5, [ "8", "9", "10", 10 + "" ]);
```
For more information: <http://api.jquery.com/jQuery.inArray/> | Best way to find if an item is in a JavaScript array? | [
"",
"javascript",
"arrays",
""
] |
let's say we have a c++ class like:
```
class MyClass
{
void processArray( <an array of 255 integers> )
{
int i ;
for (i=0;i<255;i++)
{
// do something with values in the array
}
}
}
```
and one instance of the class like:
```
MyClass myInstance ;
```
and 2 threads which call th... | `i` is allocated on the stack. Since each thread has its own separate stack, each thread gets its own copy of `i`. | Be careful. In the example provided the method **processArray** seems to be *reentrant* (it's not clear what happens in *// do something with values in the array*). If so, no race occurs while two or more threads invoke it simultaneously and therefore it's safe to call it without any locking mechanism.
To enforce this,... | How does Multiple C++ Threads execute on a class method | [
"",
"c++",
"multithreading",
""
] |
```
string percentage = e.Row.Cells[7].Text;
```
I am trying to do some dynamic stuff with my GridView, so I have wired up some code to the RowDataBound event. I am trying to get the value from a particular cell, which is a TemplateField. But the code above always seems to be returning an empty string.
Any ideas?
To... | First you need to wrap your code in a `Label` or `Literal` control so that you can reference it properly. What's happening is that there's no way for the system to keep track of it, because there's no control associated with the text. It's the control's responsibility to add its contents to viewstate.
You need to use ... | why not pull the data directly out of the data source.
```
DataBinder.Eval(e.Row.DataItem, "ColumnName")
``` | Getting value from a cell from a gridview on RowDataBound event | [
"",
"c#",
"asp.net",
"gridview",
""
] |
Here's the idea, I'd like to make a service? that will look for a certain program starting up and dissallow it unless certain conditions are met.
Let's say I have a game I want to stop myself from playing during the week. So if I start it up on any day other than Friday/Saturday/Sunday, it will intercept and cancel. I... | Well, you can definitely determine which programs are running by looking for the process names you want (GetProcessesByName()) and killing them.
```
Process[] processes = Process.GetProcessesByName(processName);
foreach(Process process in processes)
{
process.Kill();
}
```
You could just have a list of them you di... | I don't know about C# in particular here but one why you could accomplish this (I'll be it is a dangerous way) is by using the Image File Execution Options (<http://blogs.msdn.com/junfeng/archive/2004/04/28/121871.aspx>) in the registry. For whatever executable you are interested in intercepting you could set the Debug... | Way to stop a program from starting up using c#? | [
"",
"c#",
"windows",
"service",
""
] |
I know there is a function somewhere that will accept a client rect and it will convert it into a window rect for you. I just can't find / remember it!
Does anyone know what it is?
It will do something similar to:
```
const CRect client(0, 0, 200, 200);
const CRect window = ClientRectToWindowRect(client);
SetWindowP... | You're probably thinking of [`AdjustWindowRectEx()`](http://msdn.microsoft.com/en-us/library/ms632667(VS.85).aspx). Keep in mind, this is intended for use when *creating* a window - there's no guarantee that it will produce an accurate set of window dimensions for an existing window; for that, use [`GetWindowRect()`](h... | Is this what you are looking for?
ClientToScreen
<http://msdn.microsoft.com/en-us/library/ms532670(VS.85).aspx> | Win32/MFC Get window rect from client rect | [
"",
"c++",
"windows",
"winapi",
"mfc",
""
] |
Yacc does not permit objects to be passed around. Because the %union can only contain POD types, complex objects must be new'd and passed around by pointer. If a syntax error occurs, the yacc parser just stops running, and references to all of those created objects are lost.
The only solution I've come up with is that... | I love Yacc, but the discriminating union stack does present a challenge.
I don't know whether you are using C or C++. I've modified Yacc to generate C++ for my own purposes, but this solution can be adapted to C.
My preferred solution is to pass an interface to the owner down the parse tree, rather than constructed ... | If it suits your project, consider using the Boehm Garbage collector. That way you can freely allocate new objects and let the collector handle the deletes. Of course there are tradeoffs involved in using a garbage collector. You would have to weigh the costs and benefits. | What is the best way of preventing memory leaks in a yacc-based parser? | [
"",
"c++",
"yacc",
""
] |
I've come across this term POD-type a few times.
What does it mean? | *POD* stands for *Plain Old Data* - that is, a class (whether defined with the keyword `struct` or the keyword `class`) without constructors, destructors and virtual members functions. [Wikipedia's article on POD](http://en.wikipedia.org/wiki/Plain_Old_Data_Structures) goes into a bit more detail and defines it as:
> ... | ### Very informally:
A POD is a type (including classes) where the C++ compiler guarantees that there will be no "magic" going on in the structure: for example hidden pointers to vtables, offsets that get applied to the address when it is cast to other types (at least if the target's POD too), constructors, or destruc... | What are POD types in C++? | [
"",
"c++",
"types",
"c++-faq",
""
] |
I keep hearing that
```
catch (Exception ex)
```
Is bad practise, however, I often use it in event handlers where an operation may for example go to network, allowing the possibility of many different types of failure. In this case, I catch all exceptions and display the error message to the user in a message box.
I... | The bad practice is
```
catch (Exception ex){}
```
and variants:
```
catch (Exception ex){ return false; }
```
etc.
Catching all exceptions on the top-level and passing them on to the user (by either logging them or displaying them in a message-box, depending on whether you are writing a server- or a client-applic... | I find the arguments that generic catches are always bad to be overly dogmatic. They, like everything else, have a place.
That place is **not** your library code, nor the classes you custom-develop for your app. That place is, as many have mentioned, the very top level of the app, where if **any** exception is raised,... | Catching base Exception class in .NET | [
"",
"c#",
"exception",
""
] |
i'm wondering if there is any nice and neat tool to replace the GNU Autotools or Make to build a very large C++ project, which are such a complicated thing to use.
It is simple to generate all the files that de Autotools require if the project is small, but if the source code is divided in many directories, with multi... | The [Google V8 JavaScript Engine](http://code.google.com/p/v8/) is written in C++ and uses [SCons](http://www.scons.org/), so I guess that's one vote for it. | [CMake](http://www.cmake.org/)? (generates makefiles, so technically not a replacement as such).
I've also seen "[SCons](http://www.scons.org/)" pop up in a few places recently. Haven't created anything with it myself though. | Any good building tools for a C++ project, which can replace make? | [
"",
"c++",
"build-process",
"makefile",
""
] |
Does any one know how do I get the current open windows or process of a local machine using Java?
What I'm trying to do is: list the current open task, windows or process open, like in Windows Taskmanager, but using a multi-platform approach - using only Java if it's possible. | Finally, with Java 9+ it is possible with [`ProcessHandle`](https://docs.oracle.com/javase/9/docs/api/java/lang/ProcessHandle.html):
```
public static void main(String[] args) {
ProcessHandle.allProcesses()
.forEach(process -> System.out.println(processDetails(process)));
}
private static String proce... | This is another approach to parse the the process list from the command "**ps -e**":
```
try {
String line;
Process p = Runtime.getRuntime().exec("ps -e");
BufferedReader input =
new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
... | How to get a list of current open windows/process with Java? | [
"",
"java",
"process",
""
] |
How do I create a unique constraint on an existing table in SQL Server 2005?
I am looking for both the TSQL and how to do it in the Database Diagram. | The SQL command is:
```
ALTER TABLE <tablename> ADD CONSTRAINT
<constraintname> UNIQUE NONCLUSTERED
(
<columnname>
)
```
See the full syntax [here](http://msdn.microsoft.com/en-us/library/ms190273.aspx).
If you want to do it from a Database Diagram:
* right-click on the table and... | In SQL Server Management Studio Express:
* Right-click table, choose **Modify** or **Design(For Later Versions)**
* Right-click field, choose **Indexes/Keys...**
* Click **Add**
* For **Columns**, select the **field name** you want to be unique.
* For **Type**, choose **Unique Key**.
* Click **Close**, **Save** the ta... | SQL Server 2005 How Create a Unique Constraint? | [
"",
"sql",
"sql-server",
"constraints",
""
] |
Comparing string in C# is pretty simple. In fact there are several ways to do it. I have listed some in the block below. What I am curious about are the differences between them and when one should be used over the others? Should one be avoided at all costs? Are there more I haven't listed?
```
string testString = "Te... | Here are the rules for how these functions work:
**`stringValue.CompareTo(otherStringValue)`**
1. `null` comes before a string
2. it uses `CultureInfo.CurrentCulture.CompareInfo.Compare`, which means it will use a culture-dependent comparison. This might mean that `ß` will compare equal to `SS` in Germany, or similar... | From MSDN:
> "The CompareTo method was designed primarily for use in sorting or
> alphabetizing operations. It should not be used when the primary
> purpose of the method call is to determine whether two strings are
> equivalent. To determine whether two strings are equivalent, call
> the Equals method."
They suggest... | Differences in string compare methods in C# | [
"",
"c#",
"string",
"comparison",
""
] |
In Python, given a module X and a class Y, how can I iterate or generate a list of all subclasses of Y that exist in module X? | Here's one way to do it:
```
import inspect
def get_subclasses(mod, cls):
"""Yield the classes in module ``mod`` that inherit from ``cls``"""
for name, obj in inspect.getmembers(mod):
if hasattr(obj, "__bases__") and cls in obj.__bases__:
yield obj
``` | Although Quamrana's suggestion works fine, there are a couple of possible improvements I'd like to suggest to make it more pythonic. They rely on using the inspect module from the standard library.
1. You can avoid the getattr call by using `inspect.getmembers()`
2. The try/catch can be avoided by using `inspect.iscla... | Iterate over subclasses of a given class in a given module | [
"",
"python",
"oop",
""
] |
I have a dict, that looks like this:
```
{
'foo': {
'opt1': 1,
'opt2': 2,
},
'foo/bar': {
'opt3': 3,
'opt4': 4,
},
'foo/bar/baz': {
'opt5': 5,
'opt6': 6,
}
}
```
And I need to get it to look like:
```
{
'foo': {
'opt1... | Like this:
```
def nest(d):
rv = {}
for key, value in d.iteritems():
node = rv
for part in key.split('/'):
node = node.setdefault(part, {})
node.update(value)
return rv
``` | ```
def layer(dict):
for k,v in dict:
if '/' in k:
del dict[k]
subdict = dict.get(k[:k.find('/')],{})
subdict[k[k.find('/')+1:]] = v
layer(subdict)
``` | Need to create a layered dict from a flat one | [
"",
"python",
"algorithm",
"performance",
""
] |
Is it really viable to use GCJ to publish server-side applications? Webapps?
My boss is convinced that compiling our (***my***) webapp into a binary executable is a brilliant idea. (Then again, he likes nice, small simple things with blinky lights that he can understand.) He instinctively sees no issues with this, whi... | FWIW: I have never had good luck with GCJ, I have had a lot of problems using it and have had some obscure issues pop up that took forever to diagnose to GCJ rather than me (I am always very very reluctant to blame things on external libraries). I will openly admit this happened several years ago and I have never wante... | I don't know about GCJ, but my company uses Excelsior JET with success. We haven't done it with a webapp (yet) but it should be able to handle anything that the Sun JRE can. In fact JET is a Sun-certified Java implementation. | Is GCJ (GNU Compiler for Java) a viable tool for publishing a webapp? | [
"",
"java",
"gcj",
""
] |
I am looking for a method of reading emails using Pop3 in C# 2.0. Currently, I am using code found in [CodeProject](http://www.codeproject.com/KB/IP/Pop3MimeClient.aspx?fid=341657). However, this solution is less than ideal. The biggest problem is that it doesn't support emails written in unicode. | I've successfully used [OpenPop.NET](http://sourceforge.net/projects/hpop/) to access emails via POP3. | downloading the email via the POP3 protocol is the easy part of the task. The protocol is quite simple and the only hard part could be advanced authentication methods if you don't want to send a clear text password over the network (and cannot use the SSL encrypted communication channel). See [RFC 1939: Post Office Pro... | Reading Email using Pop3 in C# | [
"",
"c#",
"unicode",
"pop3",
""
] |
I use Eclipse, Maven, and Java in my development. I use Maven to download dependencies (jar files and javadoc when available) and Maven's eclipse plug-in to generate the .project and .classpath files for Eclipse. When the dependency downloaded does not have attached javadoc I manually add a link for the javadoc in the ... | You might consider just avoiding this problem completely by installing the javadoc jar into your local repository manually using the [install-file goal](http://maven.apache.org/plugins/maven-install-plugin/usage.html) and passing in the -Dclassifier=javadoc option. Once you do that the .classpath that mvn generates sho... | From the Maven Eclipse Plugin [FAQ](http://maven.apache.org/plugins/maven-eclipse-plugin/examples/attach-library-sources.html)
> The following example shows how to do
> this in the command-line:
>
> ```
> mvn eclipse:eclipse -DdownloadSources=true -DdownloadJavadocs=true
> ```
>
> or in your pom.xml:
>
> ```
> <proje... | How to reference javadocs to dependencies in Maven's eclipse plugin when javadoc not attached to dependency | [
"",
"java",
"eclipse",
"maven-2",
""
] |
I've got a sign up form that requires the user to enter their email and password, both are in two separate text boxes. I want to provide a button that the user can click so that the password (which is masked) will appear in a popup when the user clicks the button.
Currently my JavaScript code for this is as follows:
... | I did a quick example up of a working version:
```
<html>
<head>
<script type="text/javascript" src="prototype.js"></script>
<script type="text/javascript">
function toggleShowPassword() {
var textBox = $('PasswordText');
if (textBox)
... | I would assume that the browser has some issue with the script attempting to set the value of a password field:
```
button.value = password;
```
This line of code has no real purpose. `password.value` is not affected in the previous lines where you are reading the value and using it in the `alert()`.
This should be ... | catching button clicks in javascript without server interaction | [
"",
"javascript",
"ajax",
""
] |
I would like to generate a random floating point number between 2 values. What is the best way to do this in C#? | The only thing I'd add to [Eric](https://stackoverflow.com/questions/44408/how-do-you-generate-a-random-number-in-c#44428)'s response is an explanation; I feel that knowledge of why code works is better than knowing what code works.
The explanation is this: let's say you want a number between 2.5 and 4.5. The range is... | ```
System.Random r = new System.Random();
double rnd( double a, double b )
{
return a + r.NextDouble()*(b-a);
}
``` | How do you generate a random number in C#? | [
"",
"c#",
"floating-point",
"random",
""
] |
I have a web application developed with ASP.net and C# that is running on my companies' intranet. Because all the users for this application are all using Microsoft Outlook without exception, I would like for the the application to open up an Outlook message on the client-side. **I understand that Office is designed to... | You cannot open something on the client from server side code. You'd have to use script on the page to do what you're wanting (or something else client-side like ActiveX or embedded .NET or something)
Here's a sample Javascript that invokes an Outlook MailItem from an webpage. This could easily be injected into the pa... | (hint: formatting in your question)
I'm not understanding what's wrong with a mailto link or a formmail-type page. | Outlook Email via a Webpage | [
"",
"c#",
"asp.net",
"outlook",
"ms-office",
""
] |
I have a small to medium project that is in C++/CLI. I really hate the syntax extensions of C++/CLI and I would prefer to work in C#. Is there a tool that does a decent job of translating one to the other?
**EDIT:** When I said Managed c++ before I apparently meant c++/CLI | You can only translate Managed C++ code (and C++/CLI code) to C# if the C++ code is pure managed. If it is not -- i.e. if there is native code included in the sources -- tools like .NET Reflector won't be able to translate the code for you.
If you do have native C++ code mixed in, then I'd recommend trying to move the... | .NET Managed C++ is like a train wreck. But have you looked into C++ CLI? I think Microsoft did a great job in this field to make C++ a first class .NET citizen.
<http://msdn.microsoft.com/en-us/magazine/cc163852.aspx> | Translate C++/CLI to C# | [
"",
"c#",
".net",
"c++-cli",
""
] |
Currently, I am working on a new version control system as part of a final year project at University. The idea is to make it highly adaptable and pluggable.
We're using the OSGi framework (Equinox implementation) to manage our plug ins. My problem is that I can't find a simple & easy to use method for testing OSGi bu... | Spring Dynamic Modules has excellent support for [testing OSGi bundles](http://static.springframework.org/osgi/docs/current/reference/html/testing.html). | More recently, you should have a look at Pax Exam:
<http://team.ops4j.org/wiki/display/paxexam/Pax+Exam>
This is the current effort at OPS4J related to testing. | Quick and easy way to test OSGi bundles | [
"",
"java",
"testing",
"osgi",
""
] |
I understand the difference between `String` and `StringBuilder` (`StringBuilder` being mutable) but is there a large performance difference between the two?
The program I’m working on has a lot of case driven string appends (500+). Is using `StringBuilder` a better choice? | Yes, the performance difference is significant. See the KB article "[How to improve string concatenation performance in Visual C#](http://support.microsoft.com/kb/306822)".
I have always tried to code for clarity first, and then optimize for performance later. That's much easier than doing it the other way around! How... | To clarify what Gillian said about 4 string, if you have something like this:
```
string a,b,c,d;
a = b + c + d;
```
then it would be faster using strings and the plus operator. This is because (like Java, as Eric points out), it internally uses StringBuilder automatically (Actually, it uses a primitive that StringB... | String vs. StringBuilder | [
"",
"c#",
".net",
"performance",
""
] |
I see a lot of example code for C# classes that does this:
```
public class Point {
public int x { get; set; }
public int y { get; set; }
}
```
Or, in older code, the same with an explicit private backing value and without the new auto-implemented properties:
```
public class Point {
private int _x;
... | I tend to agree (that it seems needlessly verbose), although this has been an issue our team hasn't yet resolved and so our coding standards still insist on verbose properties for all classes.
[Jeff Atwood](https://blog.codinghorror.com/properties-vs-public-variables/) dealt with this a few years ago. The most importa... | It's also much simpler to change it to this later:
```
public int x { get; private set; }
``` | Auto-implemented getters and setters vs. public fields | [
"",
"c#",
"oop",
"properties",
"field",
""
] |
We are attempting to use a SQL Server 2003 database for our test records and want a quick way to take NUnit and NAnt output and produce SQL schema and data. Is there a simple way to generate SQL Schema using the XSD file describing these XML documents? | You could use XSD. No, I'm serious. Go to a command prompt and type xsd and press Enter.
Here's what you will see (truncated):
```
I:\>xsd
Microsoft (R) Xml Schemas/DataTypes support utility
[Microsoft (R) .NET Framework, Version 1.0.3705.0]
Copyright (C) Microsoft Corporation 1998-2001. All rights reserved.
xsd.ex... | As XSD in ambiguous in terms of master-detail relations, I doubt an automatic generation is possible.
For example, a declaration such as
```
<xs:element name="foo" type="footype" minOccurs="0" maxOccurs="unbounded" />
```
can be interpreted as child table "foo" (1:n) or as an n:m relation.
minOccurs="0" maxOccurs="... | Automatically Generating SQL Schema from XML | [
"",
"sql",
"xml",
"unit-testing",
""
] |
Given a path such as `"mydir/myfile.txt"`, how do I find the file's absolute path in Python? E.g. on Windows, I might end up with:
```
"C:/example/cwd/mydir/myfile.txt"
``` | ```
>>> import os
>>> os.path.abspath("mydir/myfile.txt")
'C:/example/cwd/mydir/myfile.txt'
```
Also works if it is already an absolute path:
```
>>> import os
>>> os.path.abspath("C:/example/cwd/mydir/myfile.txt")
'C:/example/cwd/mydir/myfile.txt'
``` | You could use the new Python 3.4 library `pathlib`. (You can also get it for Python 2.6 or 2.7 using `pip install pathlib`.) The authors [wrote](http://www.python.org/dev/peps/pep-0428/#abstract): "The aim of this library is to provide a simple hierarchy of classes to handle filesystem paths and the common operations u... | How to get an absolute file path in Python | [
"",
"python",
"path",
"relative-path",
"absolute-path",
""
] |
I'm currently playing around with [HTML\_QuickForm](http://pear.php.net/package/HTML_QuickForm) for generating forms in PHP. It seems kind of limited in that it's hard to insert my own javascript or customizing the display and grouping of certain elements.
Are there any alternatives to QuickForm that might provide mor... | If you find it hard to insert Javascript into the form elements, consider using a JavaScript framework such as [Prototype](http://www.prototypejs.org/) or [jQuery](http://jquery.com/). There, you can centralize the task of injecting event handling into form controls.
By that, I mean that you won't need to insert event... | I've found the [Zend\_Form](http://framework.zend.com/manual/en/zend.form.html) package of the [Zend Framework](http://framework.zend.com) to be particulary flexible. This component can also be used with [Zend\_Dojo](http://framework.zend.com/manual/en/zend.dojo.html) to rapidly implement common javascript form helpers... | Alternative to PHP QuickForm? | [
"",
"php",
""
] |
Given a small set of entities (say, 10 or fewer) to insert, delete, or update in an application, what is the best way to perform the necessary database operations? Should multiple queries be issued, one for each entity to be affected? Or should some sort of XML construct that can be parsed by the database engine be use... | It depends on how many you need to do, and how fast the operations need to run. If it's only a few, then doing them one at a time with whatever mechanism you have for doing single operations will work fine.
If you need to do thousands or more, and it needs to run quickly, you should re-use the connection and command, ... | You didn't mention what database you are using, but in SQL Server 2008, you can use table variables to pass complex data like this to a stored procedure. Parse it there and perform your operations. For more info, see Scott Allen's article on [ode to code](http://www.odetocode.com/articles/365.aspx). | What's the best way to insert/update/delete multiple records in a database from an application? | [
"",
"sql",
"database",
""
] |
Is there an XSLT library that is pure Python?
Installing libxml2+libxslt or any similar C libraries is a problem on some of the platforms I need to support.
I really only need basic XSLT support, and speed is not a major issue. | Unfortunately there are no pure-python XSLT processors at the moment. If you need something that is more platform independent, you may want to use a Java-based XSLT processor like [Saxon](http://saxon.sourceforge.net/). 4Suite is working on a pure-python XPath parser, but it doesn't look like a pure XSLT processor will... | I don't think you can do it in cpython: there are no pure python XSLT implementations.
But you can trivially do it in jython, using the inbuilt XSLT APIs of the JVM. I wrote a blog post for the specific case of doing it on Google AppEngine, but the code given should work under jython in anyn circumstances.
Transformi... | Pure Python XSLT library | [
"",
"python",
"xml",
"xslt",
""
] |
I'm trying to convert a multipage color tiff file to a c# CompressionCCITT3 tiff in C#. I realize that I need to make sure that all pixels are 1 bit. I have not found a useful example of this online. | You need this conversion as CCITT3 and CCITT4 don't support color (if I remember right). | Pimping disclaimer: I work for [Atalasoft](http://www.atalasoft.com), a company that makes .NET imaging software.
Using [dotImage](http://www.atalasoft.com/products/dotimage/documentimaging/default.aspx), this task becomes something like this:
```
FileSystemImageSource source = new FileSystemImageSource("path-to-your... | Compressing a TIF file | [
"",
"c#",
"tiff",
""
] |
My understanding of the MVC is as follows (incase it's horribly wrong, I am afterall new to it)
1. Models are the things that interface with the database
2. Views are the design/layout of the page
3. Controllers are where everything starts and are essentially the page logic
I'm using [CodeIgniter](http://codeigniter.... | Model is the wrong word to use when discussing what to do with products: each product is a **value object (VO)** (or data transfer objet/DTO, whatever fits in your mouth better). Value objects generally have the same fields that a table contains. In your case ProductVO should have the fields that are in Products table.... | **Model** is part of your application where business logic happens. Model represents real life relations and dependencies between objects, like: Employee reports to a Manager, Manager supervises many Employees, Manager can assign Task to Employee, Task sends out notification when overdue. Model CAN and most often DO in... | MVC, where do the classes go? | [
"",
"php",
"model-view-controller",
"oop",
""
] |
I know there's some `JAVA_OPTS` to set to remotely debug a Java program.
What are they and what do they mean ? | I have [this article](http://www.eclipsezone.com/eclipse/forums/t53459.html) bookmarked on setting this up for Java 5 and below.
Basically [run it with](http://download.oracle.com/otn_hosted_doc/jdeveloper/904preview/jdk14doc/docs/tooldocs/windows/jdb.html):
```
-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=... | Before Java 5.0, use `-Xdebug` and `-Xrunjdwp` arguments. These options will still work in later versions, but it will run in interpreted mode instead of JIT, which will be slower.
From Java 5.0, it is better to use the `-agentlib:jdwp` single option:
```
-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=... | What are Java command line options to set to allow JVM to be remotely debugged? | [
"",
"java",
"debugging",
""
] |
Ok, do you do `Business.Name` or `Business.BusinessName`
`SubCategory.ID` or `SubCategory.SubCategoryID`
What about in your database?
Why?
I'm torn with both. Would love there to be a "right answer" | The main drawback of using ID, Name etc is that you have to qualify them with the table name if you are writing an SQL join which overlaps two tables.
Despite that, I find it far more concise and readable to just use ID and Name - your code and tables will 'flow' much more easily past the eyes. Easier to type and less... | The only "right" answer is to be consistent. Decide upfront which one you will be using in a project, and stick to it. | Arbitrary Naming Convention (Business Objects) | [
"",
"c#",
"oop",
"object",
"naming",
""
] |
How feasible would it be to compile Python (possibly via an intermediate C representation) into machine code?
Presumably it would need to link to a Python runtime library, and any parts of the Python standard library which were Python themselves would need to be compiled (and linked in) too.
Also, you would need to b... | Try [ShedSkin](https://shedskin.readthedocs.io/en/latest/) Python-to-C++ compiler, but it is far from perfect. Also there is Psyco - Python JIT if only speedup is needed. But IMHO this is not worth the effort. For speed-critical parts of code best solution would be to write them as C/C++ extensions. | As @Greg Hewgill says it, there are good reasons why this is not always possible. However, certain kinds of code (like very algorithmic code) can be turned into "real" machine code.
There are several options:
* Use [Psyco](http://psyco.sourceforge.net/), which emits machine code dynamically. You should choose careful... | Is it feasible to compile Python to machine code? | [
"",
"python",
"c",
"linker",
"compilation",
""
] |
I have created a webservice in .net 2.0, C#. I need to log some information to a file whenever different methods are called by the web service clients.
The problem comes when one user process is writing to a file and another process tries to write to it. I get the following error:
> The process cannot access the file... | The locking is probably failing because your webservice is being run by more than one worker process.
You could protect the access with a named mutex, which is shared across processes, unlike the locks you get by using `lock(someobject) {...}`:
```
Mutex lock = new Mutex("mymutex", false);
lock.WaitOne();
// access ... | You don't say how your web service is hosted, so I'll assume it's in IIS. I don't think the file should be accessed by multiple processes unless your service runs in multiple application pools. Nevertheless, I guess you could get this error when multiple threads in one process are trying to write.
I think I'd go for t... | Issue writing to single file in Web service in .NET | [
"",
"c#",
"web-services",
""
] |
I have a list of structs and I want to change one element. For example :
```
MyList.Add(new MyStruct("john");
MyList.Add(new MyStruct("peter");
```
Now I want to change one element:
```
MyList[1].Name = "bob"
```
However, whenever I try and do this I get the following error:
> Cannot modify the return value of
> S... | ```
MyList[1] = new MyStruct("bob");
```
structs in C# should almost always be designed to be immutable (that is, have no way to change their internal state once they have been created).
In your case, what you want to do is to replace the entire struct in specified array index, not to try to change just a single prop... | Not quite. Designing a type as class or struct shouldn't be driven by your need to store it in collections :) You should look at the 'semantics' needed
The problem you're seeing is due to value type semantics. Each value type variable/reference is a new instance. When you say
```
Struct obItem = MyList[1];
```
what ... | Changing the value of an element in a list of structs | [
"",
"c#",
"struct",
"value-type",
""
] |
I am trying to make a `JTable` that has column spans available. Specifically, I am looking to nest a `JTable` inside another `JTable`, and when the user clicks to view the nested table, it should expand to push down the rows below and fill the empty space. This is similar to what you see in MS Access where you can nest... | As a pointer in the right direction, try [this article](http://www.swingwiki.org/howto:column_spanning) at SwingWiki that explains the TableUI method of column spanning quite well. Before this, I also tried some alternatives such as overriding the TableCellRenderer paint methods without much success. | You need to write your own TableUI for the master table. It can also helpful to use your own TableModel to save additional data like if a row is expanded. But this is optional.
I write an equals TableUI that expand a row and show an text editor. In the TableUI you need to change the the row hight dynamically with tabl... | JTable column spanning | [
"",
"java",
"swing",
"jtable",
""
] |
More than about LINQ to [insert your favorite provider here], this question is about searching or filtering in-memory collections.
I know LINQ (or searching/filtering extension methods) works in objects implementing `IEnumerable` or `IEnumerable<T>`. The question is: *because of the nature of enumeration, is every que... | Even with parallelisation, it's still O(n). The constant factor would be different (depending on your number of cores) but as n varied the total time would still vary linearly.
Of course, you could write your own implementations of the various LINQ operators over your own data types, but they'd only be appropriate in ... | Yes, the generic case is always O(n), as Sklivvz said.
However, many LINQ methods special case for when the object implementing IEnumerable actually implements e.g. ICollection. (I've seen this for IEnumerable.Contains at least.)
In practice this means that LINQ IEnumerable.Contains calls the fast HashSet.Contains fo... | In-memory LINQ performance | [
"",
"c#",
"linq",
"performance",
"complexity-theory",
""
] |
Under VS's external tools settings there is a "Use Output Window" check box that captures the tools command line output and dumps it to a VS tab.
The question is: *can I get the same processing for my program when I hit F5?*
**Edit:** FWIW I'm in C# but if that makes a difference to your answer then it's unlikely tha... | I'm going to make a few assumptions here. First, I presume that you are talking about printf output from an application (whether it be from a console app or from a windows GUI app). My second assumption is the C language.
*To my knowledge, you cannot direct printf output to the output window in dev studio, not directl... | You should be able to capture the output in a text file and use that.
I don't have a VS handy, so this is from memory:
1. Create a C++ project
2. Open the project settings, debugging tab
3. Enable managed debugging
4. Edit command line to add "`> output.txt`"
5. Run your program under the debugger
If things work the... | Capture console output for debugging in VS? | [
"",
"c#",
"visual-studio",
"debugging",
""
] |
I'm looking to have two versions of BOOST compiled into a project at the same time. Ideally they should be usable along these lines:
```
boost_1_36_0::boost::shared_ptr<SomeClass> someClass = new SomeClass();
boost_1_35_0::boost::regex expression("[0-9]", boost_1_35_0::boost::regex_constants::basic);
``` | I read (well scanned) through the [development list discussion](http://thread.gmane.org/gmane.comp.lib.boost.devel/180008). There's no easy solution. To sum up:
1. Wrapping header files in a namespace declaration
```
namespace boost_1_36_0 {
#include <boost_1_36_0/boost/regex.hpp>
}
namespace boost... | Using [bcp](http://www.boost.org/doc/libs/1_55_0b1/tools/bcp/doc/html/index.html) can install boost library to a specific location and can replace all 'namespace boost' in their code to a custom alias. Assuming our alias is 'boost\_1\_36\_0' all 'namespace boost' code blocks will start with 'boost\_1\_36\_0'. Something... | How can I wrap BOOST in a separate namespace? | [
"",
"c++",
"boost",
"namespaces",
""
] |
I had assumed that the canonical form for operator+, assuming the existence of an overloaded operator+= member function, was like this:
```
const T operator+(const T& lhs, const T& rhs)
{
return T(lhs) +=rhs;
}
```
But it was pointed out to me that this would also work:
```
const T operator+ (T lhs, const T& rhs... | With the edited question, the first form would be preferred. The compiler will more likely optimize the return value (you could verify this by placing a breakpoint in the constructor for T). The first form also takes both parameters as const, which would be more desirable.
Research on the topic of **return value optim... | I'm not sure if there is much difference in the generated code for either.
Between these two, I would (personally) prefer the first form since it better conveys the intention. This is with respect to both your reuse of the += operator and the idiom of passing templatized types by const&. | What is the best signature for overloaded arithmetic operators in C++? | [
"",
"c++",
"operator-keyword",
""
] |
Considering this code, can I be *absolutely sure* that the `finally` block always executes, no matter what `something()` is?
```
try {
something();
return success;
}
catch (Exception e) {
return failure;
}
finally {
System.out.println("I don't know if this will get printed out");
}
``` | Yes, `finally` will be called after the execution of the `try` or `catch` code blocks.
The only times `finally` won't be called are:
1. If you invoke `System.exit()`
2. If you invoke `Runtime.getRuntime().halt(exitStatus)`
3. If the JVM crashes first
4. If the JVM reaches an infinite loop (or some other non-interrupt... | Example code:
```
public static void main(String[] args) {
System.out.println(Test.test());
}
public static int test() {
try {
return 0;
}
finally {
System.out.println("something is printed");
}
}
```
Output:
```
something is printed.
0
``` | Does a finally block always get executed in Java? | [
"",
"java",
"error-handling",
"return",
"try-catch-finally",
""
] |
I need to convert HTML documents into valid XML, preferably XHTML. What's the best way to do this? Does anybody know a toolkit/library/sample/...whatever that helps me to get that task done?
To be a bit more clear here, my application has to do the conversion automatically at runtime. I don't look for a tool that help... | [**Convert from HTML to XML with HTML Tidy**](http://www.ibm.com/developerworks/library/tiptidy.html)
[**Downloadable Binaries**](http://tidy.sourceforge.net/#binaries)
JRoppert, For your need, i guess you might want to look at the [Sources](http://sourceforge.net/cvs/?group_id=27659)
```
c:\temp>tidy -help
tidy [op... | You can use a [HTML Agility Pack](http://www.codeplex.com/htmlagilitypack). Its open-source project from CodePlex. | How to convert HTML to XHTML? | [
"",
"c#",
".net",
"html",
"xhtml",
"converters",
""
] |
As far as I know, in gcc you can write something like:
```
#define DBGPRINT(fmt...) printf(fmt);
```
Is there a way to do that in VC++? | Yes but only since VC++ 2005. The syntax for your example would be:
```
#define DBGPRINT(fmt, ...) printf(fmt, __VA_ARGS__)
```
A full reference is [here](http://msdn.microsoft.com/en-us/library/ms177415(VS.80).aspx). | Yes, you can do this in Visual Studio C++ in versions 2005 and beyond (not sure about VS 2003). Take a look at **VA\_ARGS**. You can basically do something like this:
```
#define DBGPRINTF(fmt, ...) printf(fmt, __VA_ARGS__)
```
and the variable arguments to the macro will get passed to the function provided as '...'... | is there a way to write macros with a variable argument list in visual C++? | [
"",
"c++",
"visual-c++",
"c-preprocessor",
"variadic-macros",
""
] |
I happened upon a brief discussion recently on another site about C# runtime compilation recently while searching for something else and thought the idea was interesting. Have you ever used this? I'm trying to determine how/when one might use this and what problem it solves. I'd be very interested in hearing how you've... | Typically, I see this used in cases where you are currently using Reflection and need to optimize for performance.
For example, instead of using reflection to call method X, you generate a Dynamic Method at runtime to do this for you. | You can use this to add scripting support to your application. For examples look [here](http://www.codeproject.com/KB/cs/cs-script_for_cp.aspx) or [here](http://www.vsj.co.uk/articles/display.asp?id=417).
It is quite easily possible to publish parts of your internal object framework to the scripting part, so you could... | Where would you use C# Runtime Compilation? | [
"",
"c#",
"optimization",
"runtime-compilation",
""
] |
For a new project that I'm doing in PHP I've created an SQLMethods class to connect to the database and perform queries. Tonight was the first night that I actually got to test it (I wrote it a week or so ago and forgot about it) and an unexpected error occured: When it was calling my ExecuteQuery() function, it wouldn... | you should declare $SQLConnection in your class, and you should refer to it as
```
$this->SQLConnection
```
and not simply $SQLConnection. | `$SQLConnection` doesn't exist within the `ExecuteQuery` method.
You can either pass it directly as a parameter to `ExecuteQuery`, or add an `sqlConnection` class property that is set in the constructor and accessed as `$this->sqlConnection` inside your class methods. | PHP Class Database Connection Scope Issue | [
"",
"php",
"mysql",
"class",
"scope",
"code-reuse",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.