Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I filled up a combobox with the values from an Enum.
Now a combobox is text right? So I'm using a getter and a setter. I'm having problems reading the text.
Here's the code:
```
public BookType type
{
get
{
return (BookType)Enum.Parse(typeof(BookType), this.typeComboBox.Text);
}
set
{
... | I just created a simple windows form, and everything worked okay for me. Here is the code.
```
public enum Test
{
One, Two, Three
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.comboBox1.DataSource = Enum.GetNames(typeof(Test));
}
public Test T... | ```
string selectedText = this.ComboBox.GetItemText(this.ComboBox.SelectedItem);
```
The GetItemText method analyzes the item and returns the text of the bound to that item. | Get the combobox text in C# | [
"",
"c#",
".net",
"winforms",
"combobox",
""
] |
In C++, how can I establish an SQL connection to store data in an SQL database? | You should have a look at C preprocessors that exists traditionaly with databases ([ecpg](http://www.postgresql.org/docs/8.3/interactive/ecpg.html) for postgres, [Pro\*C](http://www.cs.umbc.edu/help/oracle8/server.815/a68022/toc.htm) for oracle ... which lets you embed straight SQL directly in your source files) or an ... | IF you are targetting Windows, then you might want to use ODBC. | How to create database connectivity through C++ | [
"",
"c++",
""
] |
I'm writing a Python application that takes a command as an argument, for example:
```
$ python myapp.py command1
```
I want the application to be extensible, that is, to be able to add new modules that implement new commands without having to change the main application source. The tree looks something like:
```
my... | With Python older than 2.7/3.1, that's pretty much how you do it.
For newer versions, see `importlib.import_module` for [Python 2](https://docs.python.org/2/library/importlib.html#importlib.import_module) and [Python 3](https://docs.python.org/3/library/importlib.html#importlib.import_module).
Or using `__import__` y... | The [recommended](https://docs.python.org/3/library/functions.html#__import__) way for Python 2.7 and 3.1 and later is to use [`importlib`](http://docs.python.org/3/library/importlib.html#importlib.import_module) module:
> **`importlib.import_module(`*****`name, package=None)`***
>
> Import a module. The name argument... | How can I import a module dynamically given its name as string? | [
"",
"python",
"python-import",
""
] |
I'm using a logging module that can have reporting enabled/disabled at runtime. Calls generally go something like:
```
WARN(
"Danger Will Robinson! There are "
+ boost::lexical_cast<string>(minutes)
+ " minutes of oxygen left!"
);
```
I'm using an inline function for WARN, but I'm curious as to how muc... | If you need to be able to selectively enable and disable the warnings at run-time, the compiler will *not* be able to optimize out the call.
What you need is to rename your *function* to `WARN2` and add a macro something like:
```
#define WARN(s) do {if (WARNINGS_ENABLED) WARN2(s);} while (false)
```
This will preve... | You can check what GCC/G++ do by using the **-S** option. This will output the code before it actually gets assembled – see [gcc(1)](http://linux.die.net/man/1/gcc).
GCC and G++ more or less behave the same in this case.
So I first translated the code into C to make some further tests:
```
char WARNINGS_ENABLED = 0;
... | C++ compiler optimization of passed arguments | [
"",
"c++",
"optimization",
"compiler-construction",
"arguments",
""
] |
How do I get:
```
id Name Value
1 A 4
1 B 8
2 C 9
```
to
```
id Column
1 A:4, B:8
2 C:9
``` | **No CURSOR, WHILE loop, or User-Defined Function needed**.
Just need to be creative with FOR XML and PATH.
[Note: This solution only works on SQL 2005 and later. Original question didn't specify the version in use.]
```
CREATE TABLE #YourTable ([ID] INT, [Name] CHAR(1), [Value] INT)
INSERT INTO #YourTable ([ID],[N... | If it is SQL Server 2017 or SQL Server Vnext, SQL Azure you can use `STRING_AGG` as below:
```
SELECT id, STRING_AGG(CONCAT(name, ':', [value]), ', ')
FROM #YourTable
GROUP BY id
``` | How to use GROUP BY to concatenate strings in SQL Server? | [
"",
"sql",
"sql-server",
"string-concatenation",
"sql-server-group-concat",
""
] |
I don't have much experience with databases, so I don't know which is better for long-term performance, better practice, etc.
Here is my (hypothetical) case: imagine you have a database of customer information and history of purchase orders for each. You want to keep track of how much each customer is buying. I can th... | In database terms, there is no elegance in option 2 - it would be considered a hack that you might use as a last resort if your database gets to be truly humongous - not likely to happen for a novice setting it up for the first time (but possible).
There would be a lot of work maintaining the totals; and you'd be fore... | What you're describing in option #2 is a case of premature optimization. Using the SUM() of all purchases is going to work for a really long time (years). When (if) you start to see this function degrade, you can add indexes or a totals table to your database to speed things up. Don't complicate things when a simple so... | use SUM() or caching | [
"",
"sql",
"performance",
""
] |
Does anyone has a good solution for a C# version of the C++ \_\_FUNCTION\_\_ macro? The compiler does not seem to like it. | Try using this instead.
```
System.Reflection.MethodBase.GetCurrentMethod().Name
```
C# doesn't have `__LINE__` or `__FUNCTION__` macros like C++ but there are equivalents | What I currently use is a function like this:
```
using System.Diagnostics;
public string __Function() {
StackTrace stackTrace = new StackTrace();
return stackTrace.GetFrame(1).GetMethod().Name;
}
```
When I need \_\_FUNCTION\_\_, I just call the \_\_Function() instead. For example:
```
Debug.Assert(false, ... | C# version of __FUNCTION__ macro | [
"",
"c#",
".net",
"macros",
""
] |
With .net 3.5, there is a SyndicationFeed that will load in a RSS feed and allow you to run LINQ on it.
Here is an example of the RSS that I am loading:
```
<rss version="2.0" xmlns:media="http://search.yahoo.com/mrss/">
<channel>
<title>Title of RSS feed</title>
<link>http://www.google.com</link>
<de... | Your missing the namespace. Using [LINQPad](http://www.linqpad.net/ "LINQPad") and your example feed:
```
string xml = @"
<rss version='2.0' xmlns:media='http://search.yahoo.com/mrss/'>
<channel>
<title>Title of RSS feed</title>
<link>http://www.google.com</link>
<description>Detail... | This should give you an idea on how to do it:
```
using System.Linq;
using System.ServiceModel.Syndication;
using System.Xml;
using System.Xml.Linq;
```
---
```
SyndicationFeed feed = reader.Read();
foreach (var item in feed.Items)
{
foreach (SyndicationElementExtension extension in item.ElementExtensions)
... | Reading non-standard elements in a SyndicationItem with SyndicationFeed | [
"",
"c#",
"rss",
"syndication-feed",
"syndication-item",
""
] |
I am working on my website, and I am trying to get the url parameter "page" which is an integer that tells which entry to read in the MySQL database that hols the HTML for all the pages. Here is my code, with the MySQL username and password removed for security reasons:
```
if ($_GET["page"]) {
$con = mysql_connec... | Apart from the injection vulnerability (see John's answer) you should get the title from the mysql\_query using
```
$res = mysql_query("SELECT title FROM pageContent WHERE pageID=" . $escapedpage);
$title = mysql_fetch_assoc($res);
$title = $title['title']
$res2 = mysql_query("SELECT content FROM pageContent WHERE... | You've obviously got a lot to learn *(we all had to start somewhere!)*, so a single answer on SO won't be able to teach you everything, but here's a starter:
When you run `mysql_query` on a SELECT query, it will return one of two things:
* if there was an error in your query, it will return **false**.
+ Details abo... | php url parameters | [
"",
"php",
"mysql",
""
] |
void (int a[]) {
a[5] = 3; // this is wrong?
}
Can I do this so that the array that is passed in is modified?
Sorry for deleting, a bit new here...
I have another question which might answer my question:
If I have
```
void Test(int a) {
}
void Best(int &a) {
}
```
are these two statements equivalent?
```
Test(a... | ```
void Test(int a[])
{
a[5] = 3;
}
```
just alternate syntax for:
```
void Test(int* a)
{
*(a+5) = 3;
}
```
No array is passed, just a pointer. The original array is modified.
As for your second revision, given:
```
void Test(int a)
{
}
void Best(int &a)
{
}
```
then
```
Test(aa); // Passes a... | If you get the variable not by reference and not by pointer, it means that the function is essentially isolated, getting an ad-hoc copy of a. No matter what you do (without trying to hack the stack or things like that) you wouldn't have access to that value in the calling context.
If you know something about the calli... | C++ Parameter Reference | [
"",
"c++",
"parameters",
"reference",
""
] |
I have several C# projects along with some internal library components that I'm trying to document together. Sandcastle seems to be the place to go to generate documentation from C#. I would like to know which of the two, DocProject or Sandcastle Help File Builder GUI is better and supports the features I need.
I woul... | I can vouch for Sandcastle Help File Builder. It works really well and you can document any number of assemblies within a Sandcastle Help File Builder project. In theory, you could have a Builder project and generate a doc for each C# project and then have a master Builder project which documents everything. | Here are some useful links for Sandcastle based .NET documentation:
[Tutorial on Sandcastle](http://blogs.msdn.com/sandcastle/archive/2006/07/29/682398.aspx)
[Sandcastle Help File Builder](http://www.codeplex.com/SHFB) (SHFB)
[Tutorial on SHFB](http://www.codeproject.com/KB/cs/SandcastleBuilder.aspx)
[Web Project ... | DocProject vs Sandcastle Help File Builder GUI | [
"",
"c#",
"sandcastle",
""
] |
Is there a tool out there which can convert SQL syntax to LINQ syntax?
I just want to rewrite basic queries with join, etc., to [LINQ](http://en.wikipedia.org/wiki/Language_Integrated_Query). It would save me a lot of time. | Edit 7/17/2020: I cannot delete this accepted answer. It used to be good, but now it isn't. Beware really old posts, guys. I'm removing the link.
[**Linqer**] is a SQL to LINQ converter tool. It helps you to learn LINQ and convert your existing SQL statements.
Not every SQL statement can be converted to LINQ, but Lin... | I know that this isn't what you asked for but [LINQPad](http://en.wikipedia.org/wiki/LINQPad) is a really great tool to teach yourself [LINQ](http://en.wikipedia.org/wiki/Language_Integrated_Query) (and it's free :o).
When time isn't critical, I have been using it for the last week or so instead or a query window in [... | SQL to LINQ Tool | [
"",
"sql",
"linq",
""
] |
I am writing a windows service. This service runs another process I've developed through Process class methods, but I want to run this process on debug mode also, using breakpoints, for instance.
How can I do this? | When debugging a service, DebugBreak() is very nice. You can even debug the startup of the service, which can be very hard to time if you try to attach the process.
In C#
```
#if DEBUG
System.Diagnostics.Debugger.Break();
#endif
```
In C++
```
#if DEBUG
System.Diagnostics.Debugger.Break();
#endif
```
Also see ... | From the main menu "Debug->Attach Process". | How to run another process at debug mode? | [
"",
"c#",
"visual-studio",
"debugging",
"visual-studio-2005",
""
] |
Working with a traditional listener callback model. I have several listeners that collect various stuff. Each listener's collected stuff is inside the listener in internal structures.
The problem is that I want some of the listeners to be aware of some of the "stuff" in the other listeners.
I enforce listener registr... | Why not have a central object that will keep track of how many times the onEvent method was fired for all the listener classes
```
public interface CountObserver {
public void updateCount(String className);
public int getCount(String className);
}
public class CentralObserver implements CountObserver {
private ... | You've describing a lot of coupling here. Best would be to eliminate all this back-channel dependency, but failing that maybe you could have those with dependencies listening not on the initial listener list, but on whatever they are dependent on. Or you could have them wait till they have all the signals.
You could a... | Proper coupling for multiple listeners that need to accessed shared state data | [
"",
"java",
"design-patterns",
"listener",
""
] |
I have a database with one table, like so:
```
UserID (int), MovieID (int), Rating (real)
```
The userIDs and movieIDs are large numbers, but my database only has a sample of the many possible values (4000 unique users, and 3000 unique movies)
I am going to do a matrix SVD (singular value decomposition) on it, so I ... | ```
SELECT m.UserID, m.MovieID, r.Rating
FROM (SELECT a.userid, b.movieid
FROM (SELECT DISTINCT UserID FROM Ratings) AS a,
(SELECT DISTINCT MovieID FROM Ratings) AS b
) AS m LEFT OUTER JOIN Ratings AS r
ON (m.MovieID = r.MovieID AND m.UserID = r.UserID)
ORDER B... | Sometimes the best thing to do is refactor the table/normalize your data (if that is an option).
Normalize the data structure:
Users Table: (all distinct users)
UserId, FirstName, LastName
Movies Table: (all distinct movies)
MovieId, Name
UserMovieRatings: (ratings that users have given to movies)
UserId, Mov... | Novice SQL query question for a movie ratings database | [
"",
"sql",
"database",
"sql-server-2005",
""
] |
I'm having a bit of a problem with converting the result of a MySQL query to a Java class when using SUM.
When performing a simple SUM in MySQL
```
SELECT SUM(price) FROM cakes WHERE ingredient = 'chocolate';
```
with `price` being an integer, it appears that the `SUM` sometimes returns a string and sometimes an int... | This is just a guess, but maybe casting to integer will force MySQL to always tell it is an integer.
```
SELECT CAST(SUM(price) AS SIGNED) FROM cakes WHERE ingredient = 'marshmallows';
``` | I have never worked with MySQL before so I cannot say why but If you say:
```
ResultSet rs = statement.executeQuery("SELECT SUM(price) FROM cakes WHERE ingredient = 'chocolate'");
int sum = 0;
if(rs.next())
size = Integer.parseInt(rs.getString(1));
```
Then you should not have a problem regardless of the returned dat... | Datatype of SUM result in MySQL | [
"",
"java",
"mysql",
"sum",
"return-type",
""
] |
I was using GetWindowLong like this:
```
[DllImport("user32.dll")]
private static extern IntPtr GetWindowLong(IntPtr hWnd, int nIndex);
```
But according to the MSDN docs I am supposed to be using GetWindowLongPtr to be 64bit compatible.
<http://msdn.microsoft.com/en-us/library/ms633584(VS.85).aspx>
The MSDN docs fo... | Unfortunately it's not that easy, because GetWindowLongPtr doesn't exist in 32bit Windows. On 32bit systems GetWindowLongPtr is just a C macro that points to GetWindowLong. If you really need to use GetWindowLongPtr on both 32 and 64 bit systems you'll have to determine the correct one to call at run time. See the desc... | You should define GetWindowLongPtr using an IntPtr. In C/C++ a LONG\_PTR is 32-bits on a 32-bit system and 64-bits on a 64-bit system (see [here](http://msdn.microsoft.com/en-us/library/aa383751(VS.85).aspx)). IntPtr in C# is designed to work the same way (see [here](http://msdn.microsoft.com/en-us/library/system.intpt... | GetWindowLong vs GetWindowLongPtr in C# | [
"",
"c#",
"getwindowlong",
""
] |
Are there any good JavaScript frameworks out there which primary audience is not web programming? Especially frameworks/libraries which improves the object orientation?
The framework should be usable within an desktop application embedding a JavaScript engine (such as Spidermonkey or JavaScriptCore), so no external dep... | [Dojo](http://dojotoolkit.org/) can be used (and is used) in non-browser environments (e.g., Rhino, Jaxer, SpiderMonkey). It can be easily adapted for other environments too — all DOM-related functions are separated from functions dealing with global language features.
[dojo.declare()](http://api.dojotoolkit.org/jsdoc... | As far as "improving object orientation" goes, Javascript is already great. You just need to get used to thinking in prototypes instead of classes.
After reading Douglas Crawford's [great page on prototypal inheritance](http://javascript.crockford.com/prototypal.html) I really started to enjoy working with javascript.... | Non-web Javascript frameworks | [
"",
"javascript",
"frameworks",
"desktop",
""
] |
I have a .NET 2.0 server that seems to be running into scaling problems, probably due to poor design of the socket-handling code, and I am looking for guidance on how I might redesign it to improve performance.
**Usage scenario:** 50 - 150 clients, high rate (up to 100s / second) of small messages (10s of bytes each) ... | A lot of this has to do with many threads running on your system and the kernel giving each of them a time slice. The design is simple, but does not scale well.
You probably should look at using Socket.BeginReceive which will execute on the .net thread pools (you can specify somehow the number of threads it uses), and... | Socket I/O performance has improved in .NET 3.5 environment. You can use ReceiveAsync/SendAsync instead of BeginReceive/BeginSend for better performance. Chech this out:
<http://msdn.microsoft.com/en-us/library/bb968780.aspx> | Tips / techniques for high-performance C# server sockets | [
"",
"c#",
".net",
"performance",
"sockets",
""
] |
In our database, we have a system set up to keep track of applications. We have a bool column that indicates whether or not the application is approved. Then there's another column that indicates whether or not the application is denied. If neither column is true, then the application is considered to be pending.
Is t... | you could use a case statement in your query:
select case approved when 1 then 'Approved' else ...
Case statements can be nested so you can delve into the different options.
Why not rather use an int column with 3 distinct values, or you can even go as far as using one bool column, with null enabled. When null it is ... | You can use a case statement like this:
```
select case
when Approved = 1 then 'Approved'
when Denied = 1 then 'Denied'
else 'Pending'
end 'Status'
``` | Building a view column out of separate columns | [
"",
"sql",
"sql-server",
"view",
""
] |
How do I get a platform-independent newline in Java? I can’t use `"\n"` everywhere. | In addition to the line.separator property, if you are using java 1.5 or later and the **String.format** (or other **formatting** methods) you can use `%n` as in
```
Calendar c = ...;
String s = String.format("Duke's Birthday: %1$tm %1$te,%1$tY%n", c);
//Note `%n` at end of line ^^
S... | Java 7 now has a [`System.lineSeparator()`](http://docs.oracle.com/javase/8/docs/api/java/lang/System.html#lineSeparator--) method. | How do I get a platform-independent new line character? | [
"",
"java",
"cross-platform",
"newline",
"eol",
""
] |
I have a large query in a PostgreSQL database.
The Query is something like this:
```
SELECT * FROM table1, table2, ... WHERE table1.id = table2.id...
```
When I run this query as a sql query, the it returns the wanted row.
But when I tries to use the same query to create a view, it returns an error:
> error: column... | That happens because a view would have two id named columns, one from table1 and one from table2, because of the select \*.
You need to specify which id you want in the view.
```
SELECT table1.id, column2, column3, ... FROM table1, table2
WHERE table1.id = table2.id
```
The query works because it can have equally n... | If only join columns are duplicated (i.e. have the same names), then you can get away with changing:
```
select *
from a, b
where a.id = b.id
```
to:
```
select *
from a join b using (id)
``` | `column "..." specified more than once` error of view in PostgreSQL | [
"",
"sql",
"database",
"postgresql",
"pgadmin",
"sql-view",
""
] |
This question is about using getter methods of a singleton object in worker threads. Here is some pseudo code first:
```
// Singleton class which contains data
class MyData
{
static MyData* sMyData ;
int mData1[1024];
int mData2[1024];
int mData3[1024];
MyData* getInstance()
{
// s... | Provided that no other thread will try to write to the data in your singleton object, you don't need to protect them: by definition, multiple readers in the absence of a writer is thread-safe. This is a common pattern where the program's initialization code sets up a singleton, which is then only read from by worker th... | It is not possible to tell if this could is threadsafe. If the data is initialized during object creation and never changes than this will run correctly. If you are mutating the underlying data through other methods then the readers will have to perform some sort of synchronization against the writers, there is no way ... | Singleton getInstance in thread worker methods | [
"",
"c++",
"multithreading",
""
] |
I have an application that uses `window.open()` to generate dynamic popups. Unfortunately, I've had trouble creating the content of the new windows using the standard DOM functions (`createElement`, `appendChild`), and I've gone to using `document.write()` to generate the page.
Concretely, how can I go from this:
```... | Why not use a library function such as <http://plugins.jquery.com/project/modaldialog> instead of reinventing the wheel?
[EDIT] OR
```
function writePopup(){
var popup = window.open("", "_blank", "height=400px, width=400px");
var doc = popup.document;
doc.title = 'Written Popup';
var p = doc.createEl... | Just doing quick tests, I can get doc to append DOM created HTML to my popup like so:
```
var popup = window.open("", "popup", "height=400px, width=400px");
var doc = popup.document.documentElement;
var p = document.createElement("p");
p.innerHTML = "blah";
doc.appendChild(p);
```
My example produces totally inval... | Refactoring a function that uses window.open to use the DOM rather than write() | [
"",
"javascript",
"dom",
"web-standards",
""
] |
I came across a class instance function that needed to temporarily change a class instance variable, and then restore it when the function completed. The function had return statements all over the place, and before each return there was a restoring statement. That seemed messy to me, not to mention scary when a except... | I revised the sample a bit more based on the comments, and placed as an Community Wiki answer instead of editing the question.
```
/// c++ code sample
#ifndef UTIL_RESTORER_HPP
#define UTIL_RESTORER_HPP
namespace Utility {
/// A Restorer instance ("inst") uses the stack to restore a saved
/// value to the named vari... | I agree with Adam Pierce and also think that you should prefer references over pointers:
```
template<typename T>
class restorer {
T& ref_;
T save_;
public:
restorer(T& perm) : ref_(perm), save_(ref_) {};
~restorer() { ref_ = save_; }
};
``` | General way to reset a member variable to its original value using the stack? | [
"",
"c++",
"callstack",
""
] |
How do I make the XDocument object save an attribute value of a element with single quotes? | If it is absolutely necessary to have single quotes you could write your XML document to a string and then use a string replace to change from single to double quotes. | I'm not sure that any of the formatting options for LINQ to XML allow you to specify that. Why do you need to? It's a pretty poor kind of XML handler which is going to care about it... | Save attribute value of xml element with single quotes using linq to xml | [
"",
"c#",
"xml",
".net-3.5",
"linq-to-xml",
""
] |
I am developing a .NET CF based Graphics Application, my project involves a lot of drawing images, We have decided to go for porting the application on different handset resolution.(240 X 240 , 480 X 640) etc.
How would i go onto achieve this within single solution/project?
Is there a need to create different project... | Don't listen to that idiot MusiGenesis. A much better way of handling different screen resolutions for Windows Mobile devices is to use **forms inheritance**, which can be tacked onto an existing CF application with minimal effort.
Basically, you design each form for a standard 240x320 screen. When you need to re-arra... | Anchoring and Docking is the most common mechanism for handling different resolutions (remember also that many devices can rotate the screen, so you need to handle changes even on a single device). Getting screen size, if needed after that, is as simple as querying the Screen object:
```
int screenWidth = Screen.Prima... | Handling Different Resolutions in Visual Studio 2008 for .NET CF | [
"",
"c#",
"visual-studio",
"compact-framework",
""
] |
If I have the following code,
```
Foo *f = new Foo();
vector<Foo*> vect;
vect.push_back(f);
// do stuff
vect.erase(f);
```
Did I create a memory leak?
I guess so, but the word *erase* gives the feeling that it is deleting it.
Writing this, I am wondering if it is not a mistake to put a pointer in a STL vector. What ... | Yes, you created a memory leak by that. std::vector and other containers will just remove the pointer, they won't free the memory the pointer points to.
It's not unusual to put a pointer into a standard library container. The problem, however, is that you have to keep track of deleting it when removing it from the con... | Another option is to use the Boost [Pointer Containers](http://www.boost.org/doc/libs/1_37_0/libs/ptr_container/doc/ptr_container.html). They are designed to do exactly what you want. | Does myVector.erase(myPtr) delete the object pointed by myPtr? | [
"",
"c++",
"vector",
"stl",
""
] |
A common pattern in C++ is to create a class that wraps a lock - the lock is either implicitly taken when object is created, or taken explicitly afterwards. When object goes out of scope, dtor automatically releases the lock.
Is it possible to do this in C#? As far as I understand there are no guarantees on when dtor i... | Your understanding regarding `using` is incorrect, this is a way to have scoped actions happen in a deterministic fashion (no queuing to the GC takes place).
C# supplies the `lock` keyword which provides an exclusive lock and if you want to have different types (e.g. Read/Write) you'll have to use the `using` statemen... | To amplify Timothy's answer, the lock statement does create a scoped lock using a monitor. Essentially, this translates into something like this:
```
lock(_lockKey)
{
// Code under lock
}
// is equivalent to this
Monitor.Enter(_lockKey)
try
{
// Code under lock
}
finally
{
Monitor.Exit(_lockKey)
}
```
I... | Is it possible to implement scoped lock in C#? | [
"",
"c#",
"locking",
""
] |
Is there any way to check if a given index of an array exists?
I am trying to set numerical index but something like 1, 5, 6,10. And so I want to see if these indexes already exist and if they do just increase another counter.
I normally work with php but I am trying to do this in c++, so basically I am trying to ask ... | In C++, the size of an array is fixed when it is declared, and while you can access off the end of the declared array size, this is very dangerous and the source of hard-to-track-down bugs:
```
int i[10];
i[10] = 2; // Legal but very dangerous! Writing on memory you don't know about
```
It seems that you want array-l... | My personal vote is for using a vector. They will resize dynamically, and as long as you don't do something stupid (like try and access an element that doesn't exist) they are quite friendly to use.
As for tutorials the best thing I could point you towards is a [google search](http://www.google.com.au/search?q=C%2B%2B... | Check if array index exists | [
"",
"c++",
"arrays",
""
] |
Is there any way other than using reflection to access the members of a anonymous inner class? | Anonymous inner classes have a type but no name.
You can access fields not defined by the named supertype. However once assigned to a named type variable, the interface is lost.
Obviously, you can access the fields from within the inner class itself. One way of adding code is through an instance initialiser:
```
fin... | You can use local classes instead anonymous class. Look:
```
public class Test {
public static void main(String... args) {
class MyInner {
private int value = 10;
}
MyInner inner = new MyInner();
System.out.println(inner.value);
}
}
```
You can have reference of `M... | Accessing inner anonymous class members | [
"",
"java",
"anonymous-class",
""
] |
I'm interested in compressing data using Python's `gzip` module. It happens that I want the compressed output to be deterministic, because that's often a really convenient property for things to have in general -- if some non-gzip-aware process is going to be looking for changes in the output, say, or if the output is ... | From Python 2.7 onwards you can specify the time to be used in the gzip header. N.B. filename is also included in the header and can also be specified manually.
```
import gzip
content = b"Some content"
f = open("/tmp/f.gz", "wb")
gz = gzip.GzipFile(fileobj=f,mode="wb",filename="",mtime=0)
gz.write(content)
gz.close(... | Yeah, you don't have any pretty options. The time is written with this line in \_write\_gzip\_header:
```
write32u(self.fileobj, long(time.time()))
```
Since they don't give you a way to override the time, you can do one of these things:
1. Derive a class from GzipFile, and copy the `_write_gzip_header` function int... | setting the gzip timestamp from Python | [
"",
"python",
"gzip",
""
] |
There are a number of great Javascript libraries\frameworks out there (jQuery, Prototype, MooTools, etc.), but they all seem to focus on DOM interaction and AJAX functionality. I haven't found any that focus on extending the built-in data types (String, Date, Number, etc.). And by "Extending" I mean methods to solve ty... | The Microsoft AJAX Library has quite a few handy extensions to the JavaScript base types, including String.Format():
<http://www.asp.net/AJAX/Documentation/Live/ClientReference/Global/> | There's a good reason the big javascript libraries steer clear of extending common object prototypes with functions which should really exist (String.trim, Array.shuffle !!)... If each library extended the String object to have a trim() function, then they'd overwrite each other - not good!
Instead, what jQuery has do... | Javascript libraries to extend built in data type objects | [
"",
"javascript",
""
] |
Could someone please point me toward a cleaner method to generate a random enum member. This works but seems ugly.
Thanks!
```
public T RandomEnum<T>()
{
string[] items = Enum.GetNames(typeof( T ));
Random r = new Random();
string e = items[r.Next(0, items.Length - 1)];
return (T)Enum.Parse(typeof (T), e, tru... | ```
public T RandomEnum<T>()
{
T[] values = (T[]) Enum.GetValues(typeof(T));
return values[new Random().Next(0,values.Length)];
}
```
Thanks to @[Marc Gravell] for ponting out that the max in Random.Next(min,max) is exclusive. | Marxidad's answer is good (note you only need `Next(0,values.Length)`, since the upper bound is exclusive) - but watch out for timing. If you do this in a tight loop, you will get lots of repeats. To make it more random, consider keeping the Random object in a field - i.e.
```
private Random rand = new Random();
publi... | Generate random enum in C# 2.0 | [
"",
"c#",
"enums",
""
] |
I'm programming a class that implements the observable pattern (not the interface) and I'm thinking about whether or not the copy constructor should also copy the listeners.
On the one hand the copy constructor should create an instance that is as close as possible to the original instance so that it can be swapped ou... | The answer is **it depends on what you want to happen**.
There are technically three things you can do:
1. Copy nothing. Any observers will know nothing about the new object.
2. Have the new object add itself to the list of things the old observers are observing. The existing observers will respond to the new object ... | Don't copy. The listeners are not aware of the new object and are not expecting to receive messages related to it. | Copying listeners/observers in a copy constructor | [
"",
"java",
""
] |
I've got a small piece of code that is parsing an index value to determine a cell input into Excel. It's got me thinking...
What's the difference between
```
xlsSheet.Write("C" + rowIndex.ToString(), null, title);
```
and
```
xlsSheet.Write(string.Format("C{0}", rowIndex), null, title);
```
Is one "better" than th... | **Before C# 6**
To be honest, I think the first version is simpler - although I'd simplify it to:
```
xlsSheet.Write("C" + rowIndex, null, title);
```
I suspect other answers *may* talk about the performance hit, but to be honest it'll be minimal *if present at all* - and this concatenation version doesn't need to p... | My initial preference (coming from a C++ background) was for String.Format. I dropped this later on due to the following reasons:
* String concatenation is arguably "safer". It happened to me (and I've seen it happen to several other developers) to remove a parameter, or mess up the parameter order by mistake. The com... | When is it better to use String.Format vs string concatenation? | [
"",
"c#",
".net",
"string",
""
] |
I wonder if anyone could suggest the best way of looping through all the `<option>` s in a `<select>` element with jQuery, and building an array.
Eg.
Instead of the following, whereby a string ins passed to the autoCompleteArray(),
```
$("#CityLocal").autocompleteArray(
[
"Aberdeen", "Ada", "Adam... | This should work:
```
$(document).ready(function(){
// array of option elements' values
var optionValues = [];
// array of option elements' text
var optionTexts = [];
// iterate through all option elements
$('#sel > option').each(function() {
// get value/text and push it into respective array
opt... | The [jQuery.map](http://docs.jquery.com/Utilities/jQuery.map#arraycallback) function might be what you're looking for. The code below will create an array that contains all of the values or text values for the `<select>` options.
```
var values = jQuery.map(jQuery("#select")[0].options, function(option)
{... | Loop through <select> and build array in the format: "value1","value2","value3" | [
"",
"javascript",
"jquery",
"autocomplete",
""
] |
I am writing a java program that needs a file open dialog. The file open dialog isn't difficult, I'm hoping to use a `JFileChooser`. My problem is that I would like to have a dual pane `JFrame` (consisting of 2 `JPanels`). The left panel would have a `JList`, and the right panel would have a file open dialog.
When I u... | JFileChooser extends JComponent and Component so you should be able to add it directly to your frame.
```
JFileChooser fc = ...
JPanel panel ...
panel.add(fc);
``` | To access the "buttons" in the file chooser, you will have to add an ActionListener to it:
```
fileChooser.addActionListener(this);
[...]
public void actionPerformed(ActionEvent action)
{
if (action.getActionCommand().equals("CancelSelection"))
{
System.out.printf("CancelSelection\n");
this.se... | JFileChooser embedded in a JPanel | [
"",
"java",
"jpanel",
"jfilechooser",
"fileopendialog",
""
] |
I am looking for a redistributable component to convert HTML to PDF.
I would - at the moment - like to avoid using a "PDF printer", as this requires a printer installation and some user "playing around" in the printers panel might break that feature.
The HTML is available in a Browser control or as external file. The... | [PDFCreator](http://sourceforge.net/projects/pdfcreator/) can function as a virtual printer but it's also usable via COM. The default setup even includes COM examples.
You can check the COM samples in the SourceForge SVN repository right here: <http://pdfcreator.svn.sourceforge.net/viewvc/pdfcreator/trunk/COM/> | If you have Microsoft Word installed, I guess you could automate the whole process using the "save as pdf" plugin that can be downloaded from the Microsoft Office Site.
You would automate word then open the HTML document inside word, then output as PDF. Might be worth a shot, if you're developing in a Microsoft Enviro... | Export HTML to PDF (C++, Windows) | [
"",
"c++",
"winapi",
"pdf",
"pdf-generation",
""
] |
As the title suggests, I am having trouble maintaining my code on postback. I have a bunch of jQuery code in the Head section and this works fine until a postback occurs after which it ceases to function!
How can I fix this? Does the head not get read on postback, and is there a way in which I can force this to happen... | If you just have that code hard coded into your page's head then a post back won't affect it. I would check the following by debugging (FireBug in FireFox is a good debugger):
* Verify the script is still in the head on postback.
* verify that the css classes are in fact attached to some element in the page.
* verify ... | put your code in
```
function pageLoad(sender, args) {
/* code here */
}
```
instead of in `$(document).ready(function() { ... });`
`pageLoad()` is a function that will execute after all postbacks, synchronous and asynchronous. See this answer for more details
* [**How to have a javascript callback executed a... | Maintaining JavaScript Code in the <Head> after ASP.Net Postback. | [
"",
"asp.net",
"javascript",
"jquery",
"postback",
""
] |
We're using Spring/Hibernate on a Websphere Application Server for AIX. On my Windows machine, the problem doesn't occur--only when running off AIX. When a user logs in with an account number, if they prefix the '0' to their login ID, the application rejects the login. In the DB2 table, the column is of numeric type, a... | # SOLUTION
A co-worker did some research on Spring updates, and apparently this error was correct in v. 2.5.3:
> CustomNumberEditor treats number with leading zeros as decimal (removed unwanted octal support while preserving hex)
We were using Spring 2.0.5. We simply replaced the jars with Spring 2.5.4, and it worke... | Well there's an awful lot of things going on there. You really need to try to isolate the problem - work out what's being sent to the database, what's being seen by Java etc.
Try to pin it down in a short but complete program which *just* shows the problem - then you'll be in a much stronger position to file a bug or ... | Java Not Converting String to Long Object Properly | [
"",
"java",
"hibernate",
"spring",
"websphere",
"aix",
""
] |
I need to compare build outputs of VS2005 in order to be sure I can reproduce the exact same product.
when I do two builds one after the other in release and compare the produced files I get different files, doing text comparison it seems that more than just the datetime is different
how can I build in order to repro... | Whenever you build, the compiler embeds:
* The date and time
* A GUID (used for debugging etc, I believe)
* Potentially the assembly version (which may have "1.2.3.\*" and populated automatically)
* Potentially a strong hash
A couple of options:
* Find out where the files are "known to differ immaterially", wipe tho... | One question: you did ***text*** comparison for binary build outputs?
As I know most of compilers never produces binary identical build output for the same project. Compiler encodes into binary time of compilation, special ordinal, etc. | comparing products of builds in release | [
"",
"c#",
"visual-studio-2005",
"build-process",
""
] |
Suppose `a` and `b` are both of type `int`, and `b` is nonzero. Consider the result of performing `a/b` in the following cases:
1. `a` and `b` are both nonnegative.
2. `a` and `b` are both negative.
3. Exactly one of them is negative.
In Case 1 the result is rounded down to the nearest integer. But what does the stan... | According to the May 2008 revision,
You're right:
> The binary / operator yields the quotient, and the binary % operator yields the remainder from the division of the first expression by the second. If the second operand of / or % is zero the behavior is undefined; otherwise (a/b)\*b + a%b is equal to a. If both oper... | As an update to the other answers:
The last draft of C++11, [n3242](http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2011/n3242.pdf) which is for most practical purposes identical to the actual C++11 standard, says this in 5.6 point 4 (page 118):
> For integral operands the / operator yields the algebraic quotient
... | Integer division rounding with negatives in C++ | [
"",
"c++",
"rounding",
""
] |
using jython
I have a situation where emails come in with different attachments. Certain file types I process others I ignore and dont write to file.
I am caught in a rather nasty situation, because sometimes people send an email as an attachment, and that attached email has legal attachments.
What I want to do is sk... | The problem with existing suggestions is the walk method. This recursively, depth-first, walks the entire tree, including children.
Look at the source of the walk method, and adapt it to skip the recursive part. A cursory reading suggests:
```
if msg.is_multipart():
for part in msg.get_payload():
""" Pr... | What about the example named "[Here’s an example of how to unpack a MIME message like the one above, into a directory of files](http://docs.python.org/library/email-examples.html)"? It looks close from what you want.
```
import email
...
msg = email.message_from_file(fp)
...
for part in msg.walk():
# multipart/* a... | How do I skip processing the attachments of an email which is an attachment of a different email | [
"",
"python",
"email",
"jython",
"attachment",
""
] |
How does the C/C++ compiler manipulate the escape character ["\"] in source code? How is compiler grammar written for processing that character? What does the compiler do after encountering that character? | Most compilers are divided into parts: the compiler front-end is called a [lexical analyzer](http://en.wikipedia.org/wiki/Lexical_analyzer) or a scanner. This part of the compiler reads the actual characters and creates tokens. It has a state machine which decides, upon seeing an escape character, whether it is genuine... | An interesting note on this subject is [On Trusting Trust [PDF link]](http://www.ece.cmu.edu/~ganger/712.fall02/papers/p761-thompson.pdf).
The paper describes one way a compiler could handle this problem exactly, shows how the c-written-in-c compiler does not have an explicit translation of the codes into ASCII values... | What's the Magic Behind Escape(\) Character | [
"",
"c++",
"c",
"compiler-construction",
"escaping",
"backslash",
""
] |
Do you know a simple script to count NLOCs (netto lines of code). The script should count lines of C Code. It should not count empty lines or lines with just braces. But it doesn't need to be overly exact either. | I would do that using **awk** & **cpp** (preprocessor) & **wc** . awk removes all braces and blanks, the preprocessor removes all comments and wc counts the lines:
```
find . -name \*.cpp -o -name \*.h | xargs -n1 cpp -fpreprocessed -P |
awk '!/^[{[:space:]}]*$/' | wc -l
```
If you want to have comments included... | Looking NLOC on the Net, I found mostly "Non-commented lines of code".
You don't specify if comments must be skipped...
So if I stick to your current message, the following one-liner in Perl should do the job:
```
perl -pe "s/^\s*[{}]?\s*\n//" Dialog.java | wc -l
```
I can extend it to handle line comments:
```
... | Simple script to count NLOC? | [
"",
"c++",
"c",
"metrics",
"lines-of-code",
""
] |
I'm looking for a way to upload a file to s3. I am using django. I am currently using amazon's python library for uploading along with the following code:
View:
```
def submitpicture(request):
fuser = request.session["login"]
copied_data = request.POST.copy()
copied_data.update(request.FILES)
content... | You will have to provide the enctype attribute to the FORM element (I've been bitten by this before). For example, your FORM tag should look like:
```
<form action="/submitpicture/" method="POST" enctype="multipart/form-data" >
```
Without the enctype, you will find yourself with an empty request.FILES. | Instead of doing this manually I would take a look at the storage backend David Larlet has written for Django, [django-storages](https://django-storages.readthedocs.io/en/latest/) | How to upload a file with django (python) and s3? | [
"",
"python",
"django",
"file-upload",
"amazon-s3",
""
] |
I am using python 2.6 on XP. I have just installed py2exe, and I can successfully create a simple hello.exe from a hello.py. However, when I try using py2exe on my real program, py2exe produces a few information messages but fails to generate anything in the dist folder.
My setup.py looks like this:
```
from distutil... | I've discovered that py2exe works just fine if I comment out the part of my program that uses wxPython. Also, when I use py2exe on the 'simple' sample that comes with its download (i.e. in Python26\Lib\site-packages\py2exe\samples\simple), I get this error message:
```
*** finding dlls needed ***
error: MSVCP90.dll: N... | I put this in all my setup.py scripts:
```
distutils.core.setup(
options = {
"py2exe": {
"dll_excludes": ["MSVCP90.dll"]
}
},
...
)
```
This keeps py2exe quiet, but you still need to make sure that dll is on the user's machine. | py2exe fails to generate an executable | [
"",
"python",
"wxpython",
"py2exe",
""
] |
How do I connect to the database(MYSQL) in connection bean using JSF to retrieve its contents. Also please let me know how do I configure the web.xml file? | To get connected to mysql:
```
public void open() {
try {
String databaseName = "custom";
String userName = "root";
String password = "welcome";
//
String url = "jdbc:mysql://localhost/" + databaseName;
Class.forName("com.mysql.jdbc.Dri... | Here is a very good tutorial on how to use DAO with JSF in the best way:
<http://balusc.blogspot.com/2008/07/dao-tutorial-use-in-jsf.html>
If you are using JSF, that website can be a good place to find solutions for common problems. There are great and complete examples.
Anyway, JSF is a framework that manages the v... | Connect to database using jsf | [
"",
"java",
"mysql",
"database",
"maven-2",
""
] |
I'm using two commercial libraries that are produced by the same vendor, called VendorLibA and VendorLibB. The libraries are distributed as many DLLs that depend on the compiler version (e.g. VC7, VC8). Both libraries depend on a another library, produced by this vendor, called VendorLibUtils and contained in one DLL.
... | As you are not using VendorLibUtils directly, I assume you can't use [LoadLibrary](http://msdn.microsoft.com/en-us/library/ms684175(VS.85).aspx) etc.
If the VendorLibUtils DLLs only have exports by ordinal, you could probably rename one of the the libraries and patch the corresponding VendorLib*X* to use a different f... | I think your most promising option is to complain, loudly, to the vendor who is distributing mutually incompatible products. That rather goes against the idea of a DLL.
You can't just put the DLLs in different directories. Once a DLL with a given name is loaded, all other attempts to load another DLL with the same mod... | Can I use two incompatible versions of the same DLL in the same process? | [
"",
"c++",
"windows",
"winapi",
"dll",
""
] |
I've got a message contained in an byte[], encrypted with "RSA/ECB/PKCS1Padding". To decrypt it I create a Cipher c and initiate it with
```
c = Cipher.getInstance("RSA/ECB/PKCS1Padding");
```
Untill now I have only decrypted small messages, using the *doFinal()* method, returning an byte[] with the decrypted bytes.
... | I think using RSA encryption for anything but key transport is abuse.
Generate a new key for a symmetric cipher and encrypt your bulk data with that. Then encrypt the key with RSA. Send the symmetrically-encrypted cipher-text along with the asymmetrically-encrypted content encryption key to your recipient. | With RSA you can only encrypt/decrypt block with size up to your key length minus padding length. If you have data longer than your key maybe it is just merged in one array so you should split it into chunks with size of your key (128 bytes suggests 1024 key with no padding, I'm not sure if it's possible). Using update... | Java/JCE: Decrypting "long" message encrypted with RSA | [
"",
"java",
"rsa",
"encryption",
"jce",
""
] |
I need to test a function that needs to query a page on an external server using urllib.urlopen (it also uses urllib.urlencode). The server could be down, the page could change; I can't rely on it for a test.
What is the best way to control what urllib.urlopen returns? | Another simple approach is to have your test override urllib's `urlopen()` function. For example, if your module has
```
import urllib
def some_function_that_uses_urllib():
...
urllib.urlopen()
...
```
You could define your test like this:
```
import mymodule
def dummy_urlopen(url):
...
mymodule.u... | I am using [Mock's](http://www.voidspace.org.uk/python/mock/) patch decorator:
```
from mock import patch
[...]
@patch('urllib.urlopen')
def test_foo(self, urlopen_mock):
urlopen_mock.return_value = MyUrlOpenMock()
``` | How can one mock/stub python module like urllib | [
"",
"python",
"unit-testing",
"testing",
"mocking",
""
] |
This is to all the C# gurus. I have been banging my head on this for some time already, tried all kinds of advice on the net with no avail. The action is happening in Windows Mobile 5.0.
I have a DLL named MyDll.dll. In the MyDll.h I have:
```
extern "C" __declspec(dllexport) int MyDllFunction(int one, int two);
```
... | Maybe this seems like an obvious thing to check, but are you compiling the native DLL for the correct CPU architecture? IIRC, Windows Mobile runs on multiple CPU architectures. | I have the same problem, but this time there is no obvious difference in the platforms involved. Why is it something that is supposed to be 'normal' is so badly documented, so difficult and worst of all so 'flaky'.
Are there ANY tools that allow me to go onto my PPC emulator, and stop by step check (a) that the dll is ... | How do I solve the .NET CF exception "Can't find PInvoke DLL"? | [
"",
"c#",
".net",
"windows-mobile",
"pinvoke",
""
] |
I would like to use Linq to query a bus schedule in my project, so that at any time I can get the next 5 bus arrival times. How can I limit my query to the first 5 results?
More generally, how can I take a slice of a list in C#? (In Python I would use `mylist[:5]` to get the first 5 elements.) | ```
var firstFiveItems = myList.Take(5);
```
Or to slice:
```
var secondFiveItems = myList.Skip(5).Take(5);
```
And of course often it's convenient to get the first five items according to some kind of order:
```
var firstFiveArrivals = myList.OrderBy(i => i.ArrivalTime).Take(5);
``` | In case anyone is interested (even if the question does not ask for this version), in C# 2 would be: (I have edited the answer, following some suggestions)
```
myList.Sort(CLASS_FOR_COMPARER);
List<string> fiveElements = myList.GetRange(0, 5);
``` | How to get first N elements of a list in C#? | [
"",
"c#",
""
] |
This is a [follow up question](https://stackoverflow.com/questions/319199/why-is-java-able-to-store-0xff000000-as-an-int). So, Java store's integers in [two's-complements](http://en.wikipedia.org/wiki/Two%27s_complement) and you can do the following:
```
int ALPHA_MASK = 0xff000000;
```
In C# this requires the use of... | C# (rather, .NET) also uses the two's complement, but it supports both signed and unsigned types (which Java doesn't). A bit mask is more naturally an unsigned thing - why should one bit be different than all the other bits?
In this specific case, it is safe to use an unchecked cast:
```
int ALPHA_MASK = unchecked((i... | Well, you can use an unchecked block and a cast:
```
unchecked
{
int ALPHA_MASK = (int)0xff000000;
}
```
or
```
int ALPHA_MASK = unchecked((int)0xff000000);
```
Not terribly convenient, though... perhaps just use a literal integer? | Hexadecimal notation and signed integers | [
"",
"c#",
"types",
"hex",
""
] |
Given a couple of simple tables like so:
```
create table R(foo text);
create table S(bar text);
```
If I were to union them together in a query, what do I call the column?
```
select T.????
from (
select foo
from R
union
select bar
from S) as T;
```
Now, in mysql, I can apparently refer to the ... | Although there is no spelled rule, we can use the column names from the first subquery in the union query to fetch the union results. | Try to give an alias to columns;
```
select T.Col1
from (
select foo as Col1
from R
union
select bar as Col1
from S) as T;
```
or If the name of column is not necessary then T.\* will be enough. | Column names for a table formed by a UNION | [
"",
"sql",
"sqlite",
"union",
""
] |
In C++, I code this way:
```
//foo.h
class cBar
{
void foobar();
}
```
---
```
//foo.cpp
void cBar::foobar()
{
//Code
}
```
I tried to do this on PHP but the parser would complain. PHP's documentation also doesn't help. Can this be done in PHP? | No. You need to including all your function definitions inside the class block. If defining your functions in a separate structure makes you feel better you could use an interface.
```
interface iBar
{
function foobar();
}
class cBar implements iBar
{
function foobar()
{
//Code
}
}
```
I'd s... | You can't really do this in the same manner.
You can use [class abstraction](http://nl2.php.net/manual/en/language.oop5.abstract.php) and [interfaces](http://nl2.php.net/manual/en/language.oop5.interfaces.php), though. The main difference between the two is that and interface does not allow you to specify the function... | Can you code a class function outside of a class in PHP? | [
"",
"php",
""
] |
Does the HTML "select" element have an on select event? what exactly is the name of the event? | Is [`onchange`](http://www.w3.org/TR/html401/interact/scripts.html#adef-onchange) what you're looking for? | It's also worth mentioning that this doesn't fire if the selection doesn't change (seems self explanatory). As far as I know there is no event that fires when a user drops down the selectbox and then reselects the original value. | HTML <select> what is the name of on select event? | [
"",
"javascript",
"jquery",
"html",
"html-select",
""
] |
How do I execute the following shell command using the Python [`subprocess`](https://docs.python.org/library/subprocess.html) module?
```
echo "input data" | awk -f script.awk | sort > outfile.txt
```
The input data will come from a string, so I don't actually need `echo`. I've got this far, can anyone explain how I ... | You'd be a little happier with the following.
```
import subprocess
awk_sort = subprocess.Popen( "awk -f script.awk | sort > outfile.txt",
stdin=subprocess.PIPE, shell=True )
awk_sort.communicate( b"input data\n" )
```
Delegate part of the work to the shell. Let it connect two processes with a pipeline.
You'd b... | ```
import subprocess
some_string = b'input_data'
sort_out = open('outfile.txt', 'wb', 0)
sort_in = subprocess.Popen('sort', stdin=subprocess.PIPE, stdout=sort_out).stdin
subprocess.Popen(['awk', '-f', 'script.awk'], stdout=sort_in,
stdin=subprocess.PIPE).communicate(some_string)
``` | How do I use subprocess.Popen to connect multiple processes by pipes? | [
"",
"python",
"pipe",
"subprocess",
""
] |
I'm pretty sure this is a simple question in regards to formatting but here's what I want to accomplish:
I want to output data onto the screen using `cout`. I want to output this in the form of a table format. What I mean by this is the columns and rows should be properly aligned. Example:
```
Test 1
... | [setw](http://www.cplusplus.com/reference/iomanip/setw/).
```
#include <iostream>
#include <iomanip>
using namespace std;
int main () {
cout << setw(21) << left << "Test" << 1 << endl;
cout << setw(21) << left << "Test2" << 2 << endl;
cout << setw(21) << left << "Iamlongverylongblah" << 2 << endl;
co... | I advise using [Boost Format](http://www.boost.org/doc/libs/1_37_0/libs/format/index.html). Use something like this:
```
cout << format("%|1$30| %2%") % var1 % var2;
``` | Align cout format as table's columns | [
"",
"c++",
"string",
"format",
""
] |
I am using the webbrowser control in visual studio. I think it is a wrapper around internet explorer. Anyway all is going well I am using it in edit mode however I can't get he document's keydown event to fire (in order to catch ctrl+v) anyone had similar problems with it?
Anyone have a solution? | Indeed the webbrowser control is just a wrapper of the IE browser control.
Is your problem that the controls PreviewKeyDown not working? Seems to be working for me as long as the control has focus.
```
webBrowser1.PreviewKeyDown += new PreviewKeyDownEventHandler(webBrowser1_PreviewKeyDown);
....
private voi... | You should override a "WndProc()" method in derived class from WebBrowser control or in form, which contains a webbrowser. Or you can catch the keys with custom message filter ( Application.AddMessageFilter ). With this way you can also filter a mouse actions.
I had same problems years ago, but I don't remember which ... | .net webbrowser control | [
"",
"c#",
".net",
""
] |
I try to build a gui (Swing) for a simple java application. The application should have a start window like a menu. From there I would like to navigate to several other windows.
My question is what is the best-practice to achieve such a navigation? Should I build several JFrames and switch the visibility of them on/of... | If each of your windows correspond to different task (possibly nested), you could present your application as a SDI, with on the left a **task panel** like:

Each of the task would display one JFrame with the associated window.
Other solution: a **[table of content](http:/... | I recommend
* Do *not* do a MDI application with sub-frames like those found in the old Windows days. They suck as they make the matter confusing.
* Do design a tabbed interface. The welcome page/menu will be displayed on a first tab that is always created on the start.
All cool kids do that nowadays:
* Visual Studi... | Gui - Best way to navigate between windows? | [
"",
"java",
"user-interface",
"swing",
""
] |
What is your preferred method of traversing a tree data structure, since recursive method calls can be pretty inefficient in some circumstances. I am simply using a generator like the one above. Do you have any hints to make it faster?
```
def children(self):
stack = [self.entities]
while stack:
for e... | I can't think of any big algorithmic improvements, but a simple microoptimisation you can make is to bind frequently called methods (such as stack.append / stack.pop) to locals (this saves a dictionary lookup)
```
def children(self):
stack = [self.entities]
push = stack.append
pop = stack.pop
while sta... | Unless your tree is really large or you have really high (real) requirements for speed, I would choose the recursive method. Easier to read, easier to code. | How do you iterate over a tree? | [
"",
"python",
"algorithm",
""
] |
What is the correct way to convert ASP.NET SOAP-based web services to JSON-based responses?
...And then call these from jQuery?
What are "best practices" when integrating jQuery based AJAX and ASP.NET?
Articles? Books? | JSON conversion to .NET classes can be done with **System.Runtime.Serialization** and **System.Runtime.Serialization.JSON**. I suspect you're more interested in setting up function calls from client to server. I think it is worth trying [this tutorial](http://asp.net/AJAX/Documentation/Live/tutorials/ASPNETAJAXWebServi... | The following article [Extending an existing ASP.NET Web Service to support JSON](http://www.codeproject.com/KB/webservices/XML_and_JSON_on_same_We_S.aspx) by Bobby Soares on codproject.com talks about using custom method attributes to achieve desired result. | ASP.NET - What is the correct approach to JSON based web services with jQuery? | [
"",
"asp.net",
"javascript",
"jquery",
"web-services",
"json",
""
] |
In PHP, I can write:
```
$vname = 'phone';
$$vname = '555-1234';
print $phone;
```
... And the script will output "555-1234".
Is there any equivalent in Perl?
Is there any way to constrain `$phone` to the scope of the local block, as if I'd written `my $phone`? Using `my $$vname` gives me "Can't declare scalar dere... | What you're attempting to do is called a "symbolic reference." While you can do this in Perl [you shouldn't](http://perl.plover.com/varvarname.html). Symbolic references only work with global variables -- not lexical (`my`) ones. There is no way to restrict their scope. **Symbolic references are dangerous.** For that r... | Read Mark-Jason Dominus's rants against doing this in *[Why it's stupid to `use a variable as a variable name'](http://www.plover.com/perl/varvarname.html)*.
You would limit the scope of your changes to $phone by starting the block with
```
local $phone;
```
or even
```
local $$vname;
```
(Though either changes $p... | Does Perl have PHP-like dynamic variables? | [
"",
"php",
"perl",
"dynamic",
"variables",
""
] |
I'm used to work with Java where large amounts of examples are available. For various reasons I had to switch to C# and trying to do the following in SharpDevelop:
```
// Form has a menu containing a combobox added via SharpDevelop's GUI
// --- Variables
languages = new string[2];
languages[0] = "English";
languages[... | You need to set the binding context of the ToolStripComboBox.ComboBox.
Here is a slightly modified version of the code that I have just recreated using Visual Studio. The menu item combo box is called toolStripComboBox1 in my case. Note the last line of code to set the binding context.
I noticed that if the combo is ... | ```
string strConn = "Data Source=SEZSW08;Initial Catalog=Nidhi;Integrated Security=True";
SqlConnection Con = new SqlConnection(strConn);
Con.Open();
string strCmd = "select companyName from companyinfo where CompanyName='" + cmbCompName.SelectedValue + "';";
SqlDataAdapter da = new SqlDataAdapter(strCmd, Con);
DataSe... | C# - Fill a combo box with a DataTable | [
"",
"c#",
".net",
"combobox",
"datatable",
"sharpdevelop",
""
] |
I am porting some queries from Access to T-SQL and those who wrote the queries used the Avg aggregate function on datetime columns. This is not supported in T-SQL and I can understand why - it doesn't make sense. What is getting averaged?
So I was about to start reverse engineering what Access does when it aggregates ... | I'd imagine that Access is averaging the numeric representation of the dates. You could do similar in T-SQL with the following...
```
select AverageDate = cast(avg(cast(MyDateColumn as decimal(20, 10))) as datetime)
from MyTable
``` | I'm more familiar with non-MS DBMS, but... Since you cannot add two DATETIME values, you cannot ordinarily average them. However, you could do something similar to:
```
SELECT AVG(datetime_column - TIMESTAMP '2000-01-01 00:00:00.000000') +
TIMESTAMP '2000-01-01 00:00:00.000000'
FROM table_containing_... | Avg on datetime in Access | [
"",
"sql",
"sql-server",
"t-sql",
"ms-access",
""
] |
My WPF application generates sets of data which may have a different number of columns each time. Included in the output is a description of each column that will be used to apply formatting. A simplified version of the output might be something like:
```
class Data
{
IList<ColumnDescription> ColumnDescriptions { ... | Here's a workaround for Binding Columns in the DataGrid. Since the Columns property is ReadOnly, like everyone noticed, I made an Attached Property called BindableColumns which updates the Columns in the DataGrid everytime the collection changes through the CollectionChanged event.
If we have this Collection of DataGr... | I've continued my research and have not found any reasonable way to do this. The Columns property on the DataGrid isn't something I can bind against, in fact it's read only.
Bryan suggested something might be done with AutoGenerateColumns so I had a look. It uses simple .Net reflection to look at the properties of the... | How do I bind a WPF DataGrid to a variable number of columns? | [
"",
"c#",
"wpf",
"xaml",
"data-binding",
"datagrid",
""
] |
Something that confuses me, but has never caused any problems... the recommended way to dispatch an event is as follows:
```
public event EventHandler SomeEvent;
...
{
....
if(SomeEvent!=null)SomeEvent();
}
```
In a multi-threaded environment, how does this code guarantee that another thread will not alter th... | In C# 6.0 you can use monadic Null-conditional operator `?.` to check for null and raise events in easy and thread-safe way.
```
SomeEvent?.Invoke(this, args);
```
It’s thread-safe because it evaluates the left-hand side only once, and keeps it in a temporary variable. You can read more [here](https://learn.microsoft... | As you point out, where multiple threads can access `SomeEvent` simultaneously, one thread could check whether `SomeEvent`is null and determine that it isn't. Just after doing so, another thread could remove the last registered delegate from `SomeEvent`. When the first thread attempts to raise `SomeEvent`, an exception... | Checking for null before event dispatching... thread safe? | [
"",
"c#",
"multithreading",
"events",
""
] |
I have to build an HTML table that shows data for users versus pages visited. It seems klunky to use for and/or foreach loops, but I can't think of anything better. I'm using PHP, but I would assume that this is language agnostic. | Avoiding loops is probably not possible, if not in implementation, then it will still happen at machine level.
However, if you want to try stay 'pure' without nasty code, you can at least do:
```
$tableformat = '<table><thead>%s</thead><tbody>%s</tbody></table>';
$rowformat = '<tr>%s</tr>';
$cellformat = '<td>%s<... | Well, if you have multiple rows, with data formatted similarly in each row, I can't think of a way to create a table that avoids using a loop. That type of thing is basically what loops were invented for.
If you gave us more details on the table you want to build, maybe we can formulate a better method. | Are loops the best way to build a table? | [
"",
"php",
"html",
"loops",
"html-table",
""
] |
I have a page P1 loading from site S1 which contains an iframe. That iframe loads a page P2 from another site S2. At some point P2 would like to close the browser window, which contains P1 loaded from S1. Of course, since P2 is loaded from another site, it can't just do parent.close().
I have full control over P1 and ... | It's impossible, I am afraid. JavaScript from an iframe that is loaded to a different site then the one it is being rendered on is strictly prohibited due to security issues.
However, if the iframe is pointed to the same site you can get to it like:
```
<iframe name = "frame1" src = "http://yoursite">
</iframe>
<scr... | If they originated from the same domain, you can modify the security-restrictions to allow modification between sub-domains.
set document.domain = "domain.com"; //on both pages and they are allowed to modify eachother.
It might work to just set them to a bogus-domain, haven't tried that, or just simply ".com" or some... | JavaScript: closing window from iframe | [
"",
"javascript",
"iframe",
""
] |
So let's say I'm using Python 2.5's built-in default sqlite3 and I have a Django model class with the following code:
```
class SomeEntity(models.Model):
some_field = models.CharField(max_length=50, db_index=True, unique=True)
```
I've got the admin interface setup and everything appears to be working fine except... | Yes this can easily be done by adding a unique index to the table with the following command:
CREATE UNIQUE INDEX uidxName ON mytable (myfield COLLATE NOCASE)
If you need case insensitivity for nonASCII letters, you will need to register your own COLLATION with commands similar to the following:
The following exampl... | Perhaps you can create and use a custom model field; it would be a subclass of CharField but providing a [db\_type](http://docs.djangoproject.com/en/dev/howto/custom-model-fields/#db_type) method returning "text collate nocase" | Can you achieve a case insensitive 'unique' constraint in Sqlite3 (with Django)? | [
"",
"python",
"django",
"sqlite",
"django-models",
""
] |
I need to warn users about unsaved changes before they leave a page (a pretty common problem).
```
window.onbeforeunload = handler
```
This works but it raises a default dialog with an irritating standard message that wraps my own text. I need to either completely replace the standard message, so my text is clear, or... | You can't modify the default dialogue for `onbeforeunload`, so your best bet may be to work with it.
```
window.onbeforeunload = function() {
return 'You have unsaved changes!';
}
```
[Here's a reference](http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx) to this from Microsoft:
> When a string is ass... | What worked for me, using [jQuery](https://jquery.com/) and tested in IE8, Chrome and Firefox, is:
```
$(window).bind("beforeunload",function(event) {
if(hasChanged) return "You have unsaved changes";
});
```
It is important not to return anything if no prompt is required as there are differences between IE and o... | How can I override the OnBeforeUnload dialog and replace it with my own? | [
"",
"javascript",
"jquery",
"onbeforeunload",
""
] |
Is there a 4 byte unsigned int data type in MS SQL Server?
Am I forced to use a bigint? | It doesn't seem so.
Here's an article describing how to create your own rules restricting an `int` to positive values. But that doesn't grant you positive values above `2^31-1`.
<http://www.julian-kuiters.id.au/article.php/sqlserver2005-unsigned-integer> | Can you just add/subtract 2,147,483,648 (2^31) to the regular int ? (subtract on the way in, & add coming out)
I know it sounds silly, but if you declare a custom datatype that does this, it's integer arithmetic and very fast.... It just won't be readable directly from the table | 4 byte unsigned int in SQL Server? | [
"",
"sql",
"sql-server-2005",
"types",
""
] |
We've got a WinForms app written in C# that has a very custom GUI. The user is not allowed to run any other applications and the user cannot go into the OS (WinXP Pro) at all. We're planning on allowing the user to connect to available wireless networks. We're going to have to create a configuration screen that display... | [Managed Wifi API](http://www.codeplex.com/managedwifi) should work.
This might not be ideal - you have XP, which is good, but you would have to deploy a hotfix. I'd go for it, because all the wifi code I've dealt with (for the Compact Framework) is hideous. This code is as simple as could be.
Their sample code doesn... | It is possible to connect available wireless networks using native wifi.
<http://www.codeproject.com/KB/gadgets/SignalStrenghth.aspx>
Check the link, Which was developed by me. | Managing wireless network connection in C# | [
"",
"c#",
".net",
"networking",
"wireless",
""
] |
I need to know how to return a default row if no rows exist in a table. What would be the best way to do this? I'm only returning a single column from this particular table to get its value.
Edit: This would be SQL Server. | One approach for Oracle:
```
SELECT val
FROM myTable
UNION ALL
SELECT 'DEFAULT'
FROM dual
WHERE NOT EXISTS (SELECT * FROM myTable)
```
Or alternatively in Oracle:
```
SELECT NVL(MIN(val), 'DEFAULT')
FROM myTable
```
Or alternatively in SqlServer:
```
SELECT ISNULL(MIN(val), 'DEFAULT')
FROM myTable
```
These use t... | If your base query is expected to return only one row, then you could use this trick:
```
select NVL( MIN(rate), 0 ) AS rate
from d_payment_index
where fy = 2007
and payment_year = 2008
and program_id = 18
```
(Oracle code, not sure if NVL is the right function for SQL Server.) | How to set a default row for a query that returns no rows? | [
"",
"sql",
"sql-server",
""
] |
We have had issues with Mootools not being very backward compatible specifically in the area of drag and drop functionality. I was wondering if anyone has had any similar problems with jQuery not being backward compatible. We are starting to use it quite heavily and are thinking about upgrading to a newer version to st... | jQuery seems to be nicely backward compatible. I have been using it for more than a couple of years now through several versions of the core and have not had issues when upgrading except a few minor ones with some plugins. I would say that the core seems to be fine but if you're using a lot of plugins you might run int... | jQuery is so serious about backwards compatibility that they produce a "backwards compatibility" plugin for each release: <http://docs.jquery.com/Release:jQuery_1.2#jQuery_1.1_Compatibility_Plugin>. It let people who don't need backwards compatibility save on page weight. | How well does jQuery support backward compatibility? | [
"",
"javascript",
"jquery",
"jquery-plugins",
"mootools",
"backwards-compatibility",
""
] |
At the moment I'm creating a `DateTime` for each month and formatting it to only include the month.
Is there another or any better way to do this? | You can use the [`DateTimeFormatInfo`](http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.aspx) to get that information:
```
// Will return January
string name = DateTimeFormatInfo.CurrentInfo.GetMonthName(1);
```
or to get all names:
```
string[] names = DateTimeFormatInfo.CurrentInfo.M... | This method will allow you to apply a list of key value pairs of months to their `int` counterparts. We generate it with a single line using Enumerable Ranges and LINQ. Hooray, LINQ code-golfing!
```
var months = Enumerable.Range(1, 12).Select(i => new { I = i, M = DateTimeFormatInfo.CurrentInfo.GetMonthName(i) });
``... | How to list all month names, e.g. for a combo? | [
"",
"c#",
"asp.net",
".net",
"datetime",
""
] |
I understand that BigDecimal is recommended best practice for representing monetary values in Java. What do you use? Is there a better library that you prefer to use instead? | `BigDecimal` all the way. I've heard of some folks creating their own `Cash` or `Money` classes which encapsulate a cash value with the currency, but under the skin it's still a `BigDecimal`, probably with [`BigDecimal.ROUND_HALF_EVEN`](http://java.sun.com/j2se/1.5.0/docs/api/java/math/BigDecimal.html#ROUND_HALF_EVEN) ... | It can be useful to people arriving here by search engines to know about JodaMoney: <http://www.joda.org/joda-money/>. | Representing Monetary Values in Java | [
"",
"java",
"currency",
"bigdecimal",
""
] |
Question: Is exception handling in Java actually slow?
Conventional wisdom, as well as a lot of Google results, says that exceptional logic shouldn't be used for normal program flow in Java. Two reasons are usually given,
1. it is really slow - even an order of magnitude slower than regular code (the reasons given va... | It depends how exceptions are implemented. The simplest way is using setjmp and longjmp. That means all registers of the CPU are written to the stack (which already takes some time) and possibly some other data needs to be created... all this already happens in the try statement. The throw statement needs to unwind the... | FYI, I extended the experiment that Mecki did:
```
method1 took 1733 ms, result was 2
method2 took 1248 ms, result was 2
method3 took 83997 ms, result was 2
method4 took 1692 ms, result was 2
method5 took 60946 ms, result was 2
method6 took 25746 ms, result was 2
```
The first 3 are the same as Mecki's (my laptop is ... | What are the effects of exceptions on performance in Java? | [
"",
"java",
"performance",
"exception",
""
] |
Here is a nice underhand lob pitch to you guys.
So basically I've got my content table with unique primary key IDs and I've got my tag table with unique primary key IDs.
I've got a table that has an identity column as a primary key but the two other columes are the contentID and tagID. What do I need to do to the tab... | There's no reason from a data modeling perspective that you need an identity column in the mapping table. The primary key constraint should be a two-column constraint over `contentID`, `tagID`.
Some frameworks (e.g. Rails) demand that *every* table have a surrogate key named `id`, even if it makes no sense for the ent... | There is one reason to have a numeric (surrogate) key on a many-to-many join table... That is, when there are other child derived tables that would need Foreign Keys back to the records in this table... i.e., say you have Table PetStores w/StoreId, table Breeds w/BreedId, and many-to-many join table StoreBreeds that ha... | SQL many to many realtion table, but unique entires | [
"",
"sql",
""
] |
I want to debug an application in Linux.
The application is created in C++. The GUI is created using QT.
The GUI is linked with a static library that can be treated as the back end of the application.
I want to debug the static library but am not sure how to do that.
I tried using gdb
```
gdb GUI
```
But how can I ... | gdb will automatically debug functions in the library when they are called. just call it like
```
gdb ./foo
run
```
:) . Be sure you build foo with debugging flags (`-g3` will enable all debugging stuffs for gcc :). You should not optimize when debugging (pass at most `-O1` to gcc, do not optimize further). It can co... | If you want to debug the library code itself, you'll need to build the library with the `-g` compiler flag (as well as building the executable with `-g` as [litb pointed out](https://stackoverflow.com/questions/320124/debugging-application-in-linux#320136)). Otherwise gdb will step through your code fine but will throw... | Debugging an application in Linux | [
"",
"c++",
"linux",
"debugging",
"gdb",
""
] |
Example C API signature:
`void Func(unsigned char* bytes);`
In C, when I want to pass a pointer to an array, I can do:
```
unsigned char* bytes = new unsigned char[1000];
Func(bytes); // call
```
How do I translate the above API to P/Invoke such that I can pass a pointer to C# byte array? | The easiest way to pass an array of bytes is to declare the parameter in your import statement as a byte array.
```
[DllImport EntryPoint="func" CharSet=CharSet.Auto, SetLastError=true]
public extern static void Func(byte[]);
byte[] ar = new byte[1000];
Func(ar);
```
You should also be able to declare the parameter ... | You can use unsafe code:
```
unsafe
{
fixed(byte* pByte = byteArray)
IntPtr intPtr = new IntPtr((void *) pByte);
Func(intPtr);
}
```
If you need to use safe code, you can use a few tricks:
```
IntPtr intPtr = Marshal.AllocHGlobal(Marshal.SizeOf(byteArray));
Marshal.Copy(byteArray, 0, intPtr, Marshal.... | How can I pass a pointer to an array using p/invoke in C#? | [
"",
"c#",
"c",
"api",
"pinvoke",
""
] |
I have a series of Eclipse projects containing a number of plugins and features that are checked into CVS. I now need to run an automated build of these plugins. Ideally I'd like to do it without having to hardcode large numbers of Eclipse library locations by hand, which has been the problem with the automatically gen... | There are a few options for you to look at, depending on which build scripting language you're using:
* For [Maven2](http://books.sonatype.com/maven-book/reference/multimodule.html), the way forward seems to be Spring Dynamic Modules. Other options are [Pax Construct](http://www.ops4j.org/projects/pax/maven/), [m2ecli... | The standard way to make an Eclipse Build is to use the PDE Build Plugin.
<http://help.eclipse.org/help32/index.jsp?topic=/org.eclipse.pde.doc.user/guide/tasks/pde_feature_build.htm>
<http://wiki.eclipse.org/index.php/PDEBuild>
The PDU plugin is normally included with the Eclipse IDE and contains a series of templat... | How can I build an Eclipse plugin outside of Eclipse? | [
"",
"java",
"eclipse",
"build-process",
""
] |
If I have a list like this:
```
<ul id="mylist">
<li id="list-item1">text 1</li>
<li id="list-item2">text 2</li>
<li id="list-item3">text 3</li>
<li id="list-item4">text 4</li>
</ul>
```
What's the easiest way to re-arrange the DOM nodes to my preference? (This needs to happen automatically when the p... | Though there's probably an easier way to do this using a JS Library, here's a working solution using vanilla js.
```
var list = document.getElementById('mylist');
var items = list.childNodes;
var itemsArr = [];
for (var i in items) {
if (items[i].nodeType == 1) { // get rid of the whitespace text nodes
it... | You can use this to re-sort an element's children:
```
const list = document.querySelector('#test-list');
[...list.children]
.sort((a, b) => a.innerText > b.innerText ? 1 : -1)
.forEach(node => list.appendChild(node));
```
* [`list.children`](https://developer.mozilla.org/en-US/docs/Web/API/Element/children) is ... | Easiest way to sort DOM nodes? | [
"",
"javascript",
"dom",
""
] |
I'm looking for a way to select until a sum is reached.
My "documents" table has "`tag_id`" and "`size`" fields.
I want to select all of the documents with `tag_id = 26` but I know I can only handle 600 units of size. So, there's no point in selecting 100 documents and discarding 90 of them when I could have known th... | You need some way to order which records get priority over others when adding up to your max units. Otherwise, how do you know which set of records that totals up to 600 do you keep?
```
SELECT d.id, d.size, d.date_created
FROM documents d
INNER JOIN documents d2 ON d2.tag_id=d.tag_id AND d2.date_created >= d.date_cre... | This is much less efficient, but it does avoid a cursor (assuming your documents table also has a serial id column):
```
select a.id, (select sum(b.size) from documents b where b.id <= a.id and b.tag_id = 26)
from documents a
where a.tag_id = 26
order by a.id
```
Also, this was done in pgsql, so I'm not sure if this ... | How to "select until" a sum is reached | [
"",
"mysql",
"sql",
""
] |
Does anyone have a good algorithm for taking an ordered list of integers, i.e.:
[1, 3, 6, 7, 8, 10, 11, 13, 14, 17, 19, 23, 25, 27, 28]
into a given number of evenly sized ordered sublists, i.e. for 4 it will be:
[1, 3, 6] [7, 8, 10, 11] [13, 14, 17, 19] [23, 25, 27, 28]
The requirement being that each of the sub... | Splitting the lists evenly means you will have two sizes of lists - size S and S+1.
With N sublists, and X elements in the original, you would get:
floor(X/N) number of elements in the smaller sublists (S), and X % N is the number of larger sublists (S+1).
Then iterate over the original array, and (looking at your e... | Here is my own recursive solution, inspired by merge sort and breadth first tree traversal:
```
private static void splitOrderedDurationsIntoIntervals(Integer[] durations, List<Integer[]> intervals, int numberOfInterals) {
int middle = durations.length / 2;
Integer[] lowerHalf = Arrays.copyOfRange(durations, 0... | How do I divide an ordered list of integers into evenly sized sublists? | [
"",
"java",
"algorithm",
"sorting",
""
] |
I'm looking for a small and fast library implementing an HTTP server in .NET
My general requirements are:
* Supports multiple simultaneous connections
* Only needs to support static content (no server side processing)
* HTTP only, HTTPS not needed
* Preferably be able to serve a page from an in memory source. I want ... | Use [Cassini](http://www.asp.net/downloads/archived/cassini/).
Free, Open Source.
It would take trivial hacking to serve from memory. | Well, how complicated of a HTTP server do you need? .NET 2.0 has the [HttpListener Class](http://msdn.microsoft.com/en-us/library/system.net.httplistener.aspx) which you can use to [roll your own basic library](http://bartdesmet.net/blogs/bart/archive/2007/02/22/httplistener-for-dummies-a-simple-http-request-reflector.... | Light weight HTTP Server library in .NET | [
"",
"c#",
".net",
"http",
""
] |
I'm working with some schema which defines an abstract complex type, eg.
```
<xs:complexType name="MyComplexType" abstract="true">
```
This type is then referenced by another complex type in the schema:
```
<xs:complexType name="AnotherType">
<xs:sequence>
<xs:element name="Data" type="MyComplexType" maxOccurs... | After evaluating several different schema-to-code tools the only one we found that was able to deal with our schema (very large and extremely complicated) was Liquid XML (<http://www.liquid-technologies.com/>). | I have never run into this problem, but I quickly learned that xsd.exe has a lot of shortcomings. We started using [CodeXS](http://www.bware.biz/CodeXS/) a long time ago. The product is a web service, but the code is available as a command-line tool.
It has its own warts, but the code it generates is much better and i... | Generate class for schema with abstract complex type | [
"",
"c#",
".net",
"xml",
"xsd",
"schema",
""
] |
Here's a relatively common task for me, and, I think, for many a .NET programmer:
I want to use the .NET ThreadPool for scheduling worker threads that need to process a given type of tasks.
As a refresher, the signatures for the queueing method of the ThreadPool and its associated delegate are:
```
public static bo... | It sounds like you are talking about a work queue? (and I sound like clippy...)
For the record, thread-pool threads should typically be used for short pieces of work. You should ideally create your own threads for a long-lived queue. Note that .NET 4.0 may be adopting the CCR/TPL libraries, so we'll get some inbuilt w... | Since it's trivial to package whatever state you like by passing an anonymous delegate or lambda to the threadpool (through variable capture), there's no need for a generic version.
For example, you could write a utility function:
```
static void QueueItem<T>(Action<T> action, T state)
{
ThreadPool.QueueUserWorkI... | Generic ThreadPool in .NET | [
"",
"c#",
".net",
"multithreading",
"generics",
"threadpool",
""
] |
I know how to disable [WSDL-cache](https://stackoverflow.com/questions/303488/in-php-how-can-you-clear-a-wsdl-cache) in PHP, but what about force a re-caching of the WSDL?
This is what i tried: I run my code with caching set to disabled, and the new methods showed up as espected. Then I activated caching, but of some ... | I guess when you disable caching it will also stop writing to the cache. So when you re-enable the cache the old cached copy will still be there and valid. You could try (with caching enabled)
```
ini_set('soap.wsdl_cache_ttl', 1);
```
I put in a time-to-live of one second in because I think if you put zero in it wil... | In my php.ini there's an entry which looks like this:
```
soap.wsdl_cache_dir="/tmp"
```
In /tmp, I found a bunch of files named wsdl-[some hexadecimal string]
I can flush the cached wsdl files with this command:
```
rm /tmp/wsdl-*
``` | Force re-cache of WSDL in php | [
"",
"php",
"web-services",
"caching",
"wsdl",
""
] |
I want to be able to read from an unsorted source text file (one record in each line), and insert the line/record into a destination text file by specifying the line number where it should be inserted.
Where to insert the line/record into the destination file will be determined by comparing the incoming line from the ... | The basic problem is that under common OSs, files are just streams of bytes. There is no concept of lines at the filesystem level. Those semantics have to be added as an additional layer on top of the OS provided facilities. Although I have never used it, I believe that VMS has a record oriented filesystem that would m... | A [distinctly-no-c++] solution would be to use the \*nix `sort` tool, sorting on the second column of data. It might look something like this:
```
cat <file> | sort -k 2,2 > <file2> ; mv <file2> <file>
```
It's not exactly in-place, and it fails the request of using C++, but it does work :)
Might even be able to do:... | C++ inserting a line into a file at a specific line number | [
"",
"c++",
"algorithm",
"file-io",
""
] |
Some of the platforms that I develop on, don't have profiling tools. I am looking for suggestions/techniques that you have personally used to help you identify hotspots, without the use of a profiler.
The target language is C++.
I am interested in what you have personally used. | I've found the following quite useful:
```
#ifdef PROFILING
# define PROFILE_CALL(x) do{ \
const DWORD t1 = timeGetTime(); \
x; \
const DWORD t2 = timeGetTime(); \
std::cout << "Call to '" << #x << "' took " << (t2 - t1) << " ms.\n"; \
}while(false)
#else
# define PROFILE_CALL(x) x
#endif
```
Which ... | No joke: In addition to dumping timings to std::cout and other text/data oriented approaches I also use the Beep() function. There's something about hearing the gap of silence between two "Beep" checkpoints that makes a different kind of impression.
It's like the difference between looking at a written sheet music, an... | What techniques can you use to profile your code | [
"",
"c++",
"profile",
"profiler",
"homebrew",
""
] |
What is the memory model for concurrency in C++03?
(And, does C++11 change the memory model to support concurrency better?) | The C++ memory model is the specification of when and why physical memory is read/written with respect to C++ code.
Until the next C++ standard, the C++ memory model is the same as C. In the C++0x standard, a proper memory model for multithreading is expected to be included (see [here](http://en.wikipedia.org/wiki/C%2... | *Seeing some other answers, it seems many C++ programmers are not even aware what the "memory model" you are asking about means.*
*The questions is about memory model in the sense: what guarantees (if any) are there about write / read reordering (which may happen on the compiler side or on the runtime side)? This ques... | What is the C++03 memory model for concurrency? | [
"",
"c++",
"concurrency",
"c++03",
"memory-model",
""
] |
What, if any, is the performance difference between the following two loops?
```
for (Object o: objectArrayList) {
o.DoSomething();
}
```
and
```
for (int i=0; i<objectArrayList.size(); i++) {
objectArrayList.get(i).DoSomething();
}
``` | From Item 46 in [Effective Java](https://rads.stackoverflow.com/amzn/click/com/0321356683) by Joshua Bloch :
> The for-each loop, introduced in
> release 1.5, gets rid of the clutter
> and the opportunity for error by
> hiding the iterator or index variable
> completely. The resulting idiom
> applies equally to collec... | All these loops do the exact same, I just want to show these before throwing in my two cents.
First, the classic way of looping through List:
```
for (int i=0; i < strings.size(); i++) { /* do something using strings.get(i) */ }
```
Second, the preferred way since it's less error prone (how many times have YOU done ... | Is there a performance difference between a for loop and a for-each loop? | [
"",
"java",
"performance",
"for-loop",
""
] |
I want to build an Axis2 client (I'm only accessing a remote web service, I'm *not* implementing one!) with Maven2 and I don't want to add 21MB of JARs to my project. What do I have to put in my pom.xml to compile the code when I've converted the WSDL with ADB? | (**Note:** This response was provided by Aaron Digulla himself. What follows is the exact text of his own answer.)
In maven2, the minimum dependency set to make an ADB client work ("ADB" as in the way you created the Java classes from the WSDL) is this:
```
<dependency>
<groupId>org.apache.axis2</grou... | The minimum jars for the client are:
* activation-1.1.jar
* axiom-api-1.2.8.jar
* axiom-impl-1.2.8.jar
* axis2-adb-1.5.1.jar
* axis2-kernel-1.5.1.jar
* axis2-transport-http-1.5.1.jar
* axis2-transport-local-1.5.1.jar
* commons-codec-1.3.jar
* commons-httpclient-3.1.jar
* commons-logging-1.1.1.jar
* httpcore-4.0.jar
* ... | What's the minimum classpath for an Axis2 client? | [
"",
"java",
"maven-2",
"classpath",
"apache-axis",
""
] |
I'm trying to understand the differences between Assembly.Load and Assembly.ReflectionOnlyLoad.
In the code below I am attempting to find all of the objects in a given assembly that inherit from a given interface:
```
var myTypes = new List<Type>();
var assembly = Assembly.Load("MyProject.Components");
foreach (var... | As per Jon's reply, it would be helpful to know what's in `LoaderExceptions`. In lieu of this information, I think I can hazard a guess. From [MSDN](http://msdn.microsoft.com/en-us/library/ms172331(VS.80).aspx):
> If the assembly has dependencies, the
> ReflectionOnlyLoad method does not
> load them. If you need to ex... | The ReflectionOnly methods are the only way you can load a specific Assembly on disk to examine without going via the usual Load/LoadFrom rules. For example, you can load a disk-based assembly with the same identity as one in the GAC. If you tried this with LoadFrom or LoadFile, the GAC assembly is ALWAYS loaded.
Addi... | C# Assembly.Load vs Assembly.ReflectionOnlyLoad | [
"",
"c#",
"reflection",
"assembly.load",
"assembly.reflectiononly",
""
] |
How exactly do you make an auto-refreshing `div` with JavaScript (specifically, jQuery)?
I know about the `setTimeout` method, but is it really a good practice ? Is there a better method?
```
function update() {
$.get("response.php", function(data) {
$("#some_div").html(data);
});
window.setTimeou... | Another modification:
```
function update() {
$.get("response.php", function(data) {
$("#some_div").html(data);
window.setTimeout(update, 10000);
});
}
```
The difference with this is that it waits 10 seconds AFTER the ajax call is one. So really the time between refreshes is 10 seconds + length of ajax c... | ```
$(document).ready(function() {
$.ajaxSetup({ cache: false }); // This part addresses an IE bug. without it, IE will only load the first number and will never refresh
setInterval(function() {
$('#notice_div').load('response.php');
}, 3000); // the "3000"
});
``` | Auto-refreshing div with jQuery - setTimeout or another method? | [
"",
"javascript",
"jquery",
""
] |
How do I send mail via PHP with attachment of HTML file? -> Content of HTML file (code) is in string in DB. Is there some easy way or free script to do this? I don't want to store the file localy, I need to read it out of DB and send it straightaway as attachment (not included in body). | If you have a hard time getting the headers right, you can always use something like [PHP Mailer](https://github.com/PHPMailer/PHPMailer) instead of reinventing the wheel. | I like pear.
```
<?
include('Mail.php');
include('Mail/mime.php');
$text = 'Text version of email';
$html = '<html><body>HTML version of email</body></html>';
$file = './files/example.zip';
$crlf = "rn";
$hdrs = array(
'From' => 'someone@domain.pl',
'To' => 'someone@domain.pl',
... | How to attach HTML file to email using content taken from DB in PHP? | [
"",
"php",
"html",
"database",
"email",
"attachment",
""
] |
I have a `JFrame` that contains a "display" `JPanel` with `JTextField` and a "control" `JPanel` with buttons that should access the contents of the display `JPanel`. I think my problem is related on how to use the observer pattern, which in principle I understand. You need to place listeners and update messages, but I ... | You need to reduce the coupling between these objects.
You can have a master object, that owns all the text fields and the button ( the panels are irrelevant )
Then a separete actionlistener within that master object ( I call it mediator see mediator pattern )
That action listener performs a method on the mediator w... | It does make the code cleaner if you create the models in one layer and add a layer or two above to create the components and layout. Certainly do not extend the likes of `JFrame` and `JPanel`.
Do not feel the need to make the composition hierarchy in the model layer exactly match the display. Then it's just a matter ... | How to access multiple JPanels inside JFrame? | [
"",
"java",
"design-patterns",
"swing",
"controller",
"jpanel",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.