Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I'm making a simple form to create polls, therefore I want the possibility to add additional input fields in case the user wants more options in the poll.
I've made Javascript code that adds a new input field to the form, but the dynamically added input fields are not posted when the form is submitted (I use a standar... | Your code works fine as is:
```
<?php
print_r($_REQUEST)
?>
<html>
<body>
<form id="myForm" method="post">
<input type="submit">
<input type="text" name="poll[question]">
<input type="text" name="poll[option1]">
<input type="text" name="poll[option2]">
</form>
<a href="javascript:addOption();... | I just debugged my site where I was having a similar issue. For me it turned out that having my table and form tags in the "wrong" order caused the issue.
Broken:
```
table
form
```
Working:
```
form
table
```
This points out something pretty important. The browser may render fine, and the form may work fine, ... | Submit form input fields added with javascript | [
"",
"javascript",
"form-submit",
""
] |
I'm looking for a simple Python script that can minify CSS as part of a web-site deployment process. (Python is the only scripting language supported on the server and full-blown parsers like [CSS Utils](http://cthedot.de/cssutils/) are overkill for this project).
Basically I'd like [jsmin.py](http://www.crockford.com... | This seemed like a good task for me to get into python, which has been pending for a while. I hereby present my first ever python script:
```
import sys, re
with open( sys.argv[1] , 'r' ) as f:
css = f.read()
# remove comments - this will break a lot of hacks :-P
css = re.sub( r'\s*/\*\s*\*/', "$$HACK1$$", css )... | There is a port of YUI's CSS compressor available for python.
Here is its project page on PyPi:
<http://pypi.python.org/pypi/cssmin/0.1.1> | Python script for minifying CSS? | [
"",
"python",
"css",
"compression",
"minify",
""
] |
My Aim: Sending an email (e.g. support request, error report) out of a C# Windows forms application. I know how do do this technically but here is the catch:
In order to authenticate myself on the mail server (e.g. gmx, yahoo, own website) I need to store the login details inside the application (which runs on the cli... | I had such a requirement in the past which we solved by using a web service to post messages.
If for example a user wanted to submit a bug report it would be turned into a web service call to our web server and it would then be forwarded accordingly.
To answer your question:
There is no way you can hide you mail serv... | If you are sending a message to a domain that the mail server is the final destination for you do not need to authenticate the sender, you only need to do this when you are relaying mail to another domain. | Sending e-mail out of client application without storing password | [
"",
"c#",
"security",
"email",
""
] |
Many languages have a facility to check to see if an Object is of a certain type (including parent subclasses), implemented with 'is' and used like this:
```
if(obj is MyType)
```
Or slightly more tediously you can in other languages check by using the 'as' keyword to do a soft typecast and seeing if the result null.... | ```
if (objectReference instanceof type){
//Your code goes here
}
```
More info [here](http://www.java2s.com/Tutorial/Java/0060__Operators/TheinstanceofKeyword.htm). | You can only use `instanceof` with a class literal: that is:
```
Class type = String.class;
if (myObj instanceof String) // will compile
if (myObj instanceof type) //will not compile
```
The alternative is to use the method `Class.isInstance`
```
if (type.isInstance(myObj)) // will compile
``` | What is the easiest way to do 'is' in Java? | [
"",
"java",
"typechecking",
""
] |
I am creating a Firefox Extension...what would be the javascript to open a URL in the current tab from a menuitem?
e.g. in my overlay.xul file i have the following line:
```
<menuitem label="Visit homepage" oncommand="window.location='http://www.somepage.com'"/>
```
but in firefox, when i click on the menu item, it ... | After browsing around, I found that I had to replace the above code with this:
```
<menuitem label="Visit homepage" oncommand="content.wrappedJSObject.location='http://www.somepage.com'"/>
``` | From a menuitem you can use **openUILinkIn**. It works like:
```
openUILinkIn(url, where);
```
where can be: tab, current, window (and a few other seldom used options)
If you want to behave differently based on what keyboard modifiers a user is pressing, you can use another function **whereToOpenLink**, which return... | Opening a URL in current tab/window from a Firefox Extension | [
"",
"javascript",
"firefox",
"xul",
""
] |
First of all, I will admit I am a novice to web services, although I'm familiar with HTML and basic web stuff. I created a quick-and-dirty web service using Python that calls a stored procedure in a MySQL database, that simply returns a BIGINT value. I want to return this value in the web service, and I want to generat... | When I tried to write Python web service last year, I ended up using [ZSI-2.0](http://pywebsvcs.sourceforge.net/) (which is something like heir of SOAPpy) and a [paper available on its web](http://pywebsvcs.sourceforge.net/holger.pdf).
Basically I wrote my WSDL file by hand and then used ZSI stuff to generate stubs fo... | > I want to generate a WSDL that I can give to the web folks, ....
You can try [soaplib](http://soaplib.github.com/soaplib/2_0/). It has on-demand WSDL generation. | Generating a WSDL using Python and SOAPpy | [
"",
"python",
"soap",
"wsdl",
"soappy",
"zsi",
""
] |
I need to select a datetime column in a table. However, I want the select statement to return the datetime as a nvarchar with the format DD/MM/YYYY. | Here is the convert documentation:
> <https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql>
Looking through that, it looks like you want style 103:
```
SELECT CONVERT(nvarchar(10), getdate(), 103)
``` | This should help. It contains all (or most anyway) the different date formats
<http://wiki.lessthandot.com/index.php/Formatting_Dates>
I think you'd be better off handling the string conversion in client if possible. | How do I convert a datetime column to nvarchar with the format DD/MM/YYYY? | [
"",
"sql",
"sql-server",
""
] |
When writing unit tests, do you place your tests inside the assembly you wish to test or in a separate test assembly? I have written an application with the tests in classes in a separate assembly for ease of deloyment as I can just exclude the assembly. Does anyone write there tests within the assembly you wish to tes... | I have a single solution with an interface project, a tests project, a domain project and a data project. When I release I just publish the interface, which doesn't reference Tests so it doesn't get compiled in.
Edit: The bottom line is really that you don't want it to be part of your final release. You can achieve th... | This is widely debated all over the net.
We use separate assemblies and the InternalsVisibleTo attribute to help the tester assemblies see all the innards of the tested assemblies. We tend to make one test assembly for each assembly we're testing. | Write Unit tests into an assembly or in a separate assembly? | [
"",
"c#",
"unit-testing",
""
] |
Is there a better way to write this code?
I want to show a default value ('No data') for any empty fields returned by the query:
```
$archivalie_id = $_GET['archivalie_id'];
$query = "SELECT
a.*,
ip.description AS internal_project,
o.description AS origin,
... | You could use a small helper function
```
function dbValue($value, $default=null)
{
if ($default===null) {
$default='<span class="no-data">No data</span>';
}
if (!empty($value)) {
return $value;
} else {
return $default;
}
}
``` | If this is not just example code then you surely want to sanitize this query by writing...
```
$archivalie_id = pg_escape_string($_GET['archivalie_id']);
```
or you want to convert $archivalie\_id with intval() if it is clearly always an integer.
furthermore I suggest to replace 'No data' with a constant like '\_MYP... | Best way to show default values for empty fields returned from a database query? | [
"",
"php",
"database",
""
] |
What is a good use case for uncaught\_exception? | Herb Sutter seems to give good advice [here](http://www.gotw.ca/gotw/047.htm). He doesn't know of a good use for it and says that some cases where it appears to be useful don't really work. | [Probably none](http://www.gotw.ca/gotw/047.htm) | When would I use uncaught_exception? | [
"",
"c++",
"exception",
"error-handling",
""
] |
I have to give a general note to some huge Java project for which I have but little visibility and I was wondering if there were any guidelines for determining:
* what number of classes per package can be considered right, to low, or to high (this project has 3.89 classes per package, which seems a bit too small for m... | Steve McConnell in his book Code Complete recommends about 7 methods per class and no more lines in a method then can be viewed in a single screen without scrolling.
I'm not sure about classes per package.
I would highly recommend reading Code Complete for more information on such topics. | I think stats like that are pretty useless, how does knowing the lines per method show whether its any use to the project or not; i think you should be looking more along the lines of:
1. Do your packages encompass like
classes?
2. Do your classes work as an
entity on their own?
3. Do the methods
within the c... | how many classes per package? methods per class? lines per method? | [
"",
"java",
""
] |
```
AlertEvent::AlertEvent(const std::string& text) :
IMEvent(kIMEventAlert, alertText.c_str()),
alertText(text)
{
//inspection at time of crash shows alertText is a valid string
}
IMEvent::IMEvent(long eventID, const char* details)
{
//during construction, details==0xcccccccc
}
```
on a related note... | alertText may be shown as a string in a debugger, but it has not been constructed yet (and therefore alertText.c\_str() will return an indeterminate pointer).
To avoid this, one could initialize use text.c\_str() as an argument to the IMEvent ctor.
```
AlertEvent::AlertEvent(const std::string& text) :
IMEvent(kIM... | The IMEvent constructor is called before alertText's constructor is called. In particular therefore its argument `alertText.c_str()` is evaluated before alertText's constructor is called. This ain't good.
Initializer expressions are called in the order that the things being initialized are declared (not necessarily th... | C++ construction weird uninitialized pointer | [
"",
"c++",
""
] |
I have a generic list of objects in C#, and wish to clone the list. The items within the list are cloneable, but there doesn't seem to be an option to do `list.Clone()`.
Is there an easy way around this? | You can use an extension method.
```
static class Extensions
{
public static IList<T> Clone<T>(this IList<T> listToClone) where T: ICloneable
{
return listToClone.Select(item => (T)item.Clone()).ToList();
}
}
``` | If your elements are value types, then you can just do:
```
List<YourType> newList = new List<YourType>(oldList);
```
However, if they are reference types and you want a deep copy (assuming your elements properly implement `ICloneable`), you could do something like this:
```
List<ICloneable> oldList = new List<IClon... | How do I clone a generic list in C#? | [
"",
"c#",
"generics",
"list",
"clone",
""
] |
Why is it that in a C# switch statement, for a variable used in multiple cases, you only declare it in the first case?
For example, the following throws the error "A local variable named 'variable' is already defined in this scope".
```
switch (Type)
{
case Type.A:
string variable = "x";
... | I believe it has to do with the overall scope of the variable, it is a block level scope that is defined at the switch level.
Personally if you are setting a value to something inside a switch in your example for it to really be of any benefit, you would want to declare it outside the switch anyway. | If you want a variable scoped to a particular case, simply enclose the case in its own block:
```
switch (Type)
{
case Type.A:
{
string variable = "x";
/* Do other stuff with variable */
}
break;
case Type.B:
{
string variable = "y";
/* Do other stuff with varia... | Variable declaration in a C# switch statement | [
"",
"c#",
"switch-statement",
""
] |
Is there an elegant way to create and initialize a `const std::vector<const T>` like `const T a[] = { ... }` to a fixed (and small) number of values?
I need to call a function frequently which expects a `vector<T>`, but these values will never change in my case.
In principle I thought of something like
```
namespac... | For C++11:
```
vector<int> luggage_combo = { 1, 2, 3, 4, 5 };
```
**Original answer:**
You would either have to wait for C++0x or use something like [Boost.Assign](http://www.boost.org/doc/libs/1_36_0/libs/assign/doc/index.html) to do that.
e.g.:
```
#include <boost/assign/std/vector.hpp>
using namespace boost::as... | If you're asking how to initialise a const vector so that it has interesting contents, then the answer is probably to use the copy constructor. First you laboriously fill in a vector, then you create your new const vector from it. Or you can use the `vector<InputIterator>(InputIterator, InputIterator)` constructor temp... | how-to initialize 'const std::vector<T>' like a c array | [
"",
"c++",
"stl",
""
] |
```
if __name__=='__main__':
parser = OptionParser()
parser.add_option("-i", "--input_file",
dest="input_filename",
help="Read input from FILE", metavar="FILE")
(options, args) = parser.parse_args()
print options
```
result is
```
$ python convert.py -i vide... | Python has nothing to do with this -- it's the shell.
Call
```
$ python convert.py -i 'video_*'
```
and it will pass in that wildcard.
The other six values were passed in as args, not attached to the `-i`, exactly as if you'd run `python convert.py -i video_1 video_2 video_3 video_4 video_5 video_6`, and the `-i` o... | Print out args and you'll see where the other files are going...
They are being converted to separate arguments in argv, and optparse only takes the first one as the value for the input\_filename option. | Python, optparse and file mask | [
"",
"python",
"optparse",
""
] |
I write a large static method that takes a generic as a parameter argument. I call this method, and the framework throws a System.InvalidProgramException. This exception is thrown even before the first line of the method is executed.
I can create a static class which takes the generic argument, and then make this a me... | Just FYI, not sure if it'll fix anything, but your Invoke method can be simplified. This also removes the need for that delegate (possibly leading to a fix?):
```
dgv.BeginInvoke(new MethodInvoker(delegate()
{
PopulateReadOnlyGrid(dgv, gridLines, columns);
}));
```
Your code runs fine for me when I paste it in a ... | *Updated due to me misinterpreting the code example.*
Try wrapping the delegate with a MethodInvoker:
<http://msdn.microsoft.com/en-us/library/system.windows.forms.methodinvoker.aspx> | "CLR detected an invalid program." when calling Generic Methods | [
"",
"c#",
"generics",
".net-2.0",
""
] |
This happens repeatedly and is very annoying. I upload some PHP code to a client's server. A few weeks pass. They ask for a change to be made and I re-download the code as they've made some changes. However, my code which used to be neat and tidy the last time I looked at it now has an extra lines of whitespace added e... | Upload in binary mode instead of ascii. Ascii mode is changing all your linefeeds (unix end of line character) into carriage returns + linefeeds (Windows end of line characters). | You may also be having a problem with the other editor using tabs when you are using spaces (you are using spaces, right?). I have seen similar problems when sharing source between developers on Linux/OSX and Windows. | How to remove excess whitespace added to code by FTP program? | [
"",
"php",
"ftp",
"whitespace",
""
] |
WARNING: I have been learning Python for all of 10 minutes so apologies for any stupid questions!
I have written the following code, however I get the following exception:
> Message File
> Name Line Position Traceback Node
> 31
> exceptions.TypeError: this constructor takes no arguments
```
class Computer:
name... | I'm going to assume you're coming from a Java-ish background, so there are a few key differences to point out.
```
class Computer(object):
"""Docstrings are used kind of like Javadoc to document classes and
members. They are the first thing inside a class or method.
You probably want to extend object, to... | Constructors in Python are called `__init__`. You must also use "self" as the first argument for all methods in your class, and use that to set instance variables in the class.
```
class Computer:
def __init__(self, compName = "Computer1", compIp = "0.0.0.0", compScreenSize = 22):
self.name = compName
... | Python: Problem with overloaded constructors | [
"",
"python",
"exception",
"constructor-overloading",
""
] |
I have a .net transaction with a SQL insert to a SQL Server 2005 database. The table has an identity primary key.
When an error occurs within the transaction, `Rollback()` is called. The row inserts are rolled back correctly, however the next time I insert data to the table, the identity is incremented as if the rollb... | If you think about it, the auto-increment number **should not** be transactional. If other transactions had to wait to see if the auto-number was going to be used or "rolled back", they would be blocked by the existing transaction using the auto-number. For example, consider my psuedo code below with table A using an a... | If you depend on your identity values being gapless, then yes - you are doing it wrong. The whole point of a [surrogate key](http://en.wikipedia.org/wiki/Surrogate_key) to is to have *no business meaning*.
And, no, there is no way to change this behaivor (short of rolling your own autoincrement, and suffering the perf... | SQL Identity (autonumber) is Incremented Even with a Transaction Rollback | [
"",
".net",
"sql",
"sql-server-2005",
"transactions",
"identity-column",
""
] |
I need to transform an Oracle SQL statement into a Stored Procedure therefore users with less privileges can access certain data field:
```
SELECT
info_field, data_field
FROM
table_one
WHERE
some_id = '<id>' -- I need this <id> to be the procedure's parameter
UNION ALL
SELECT
info_field, data_field
FR... | If you just want to restrict users' access you could create a view and grant them select on the view but not the tables:
```
CREATE VIEW info_and_data AS
SELECT info_field, data_field
FROM table_one
UNION ALL
SELECT info_field, data_field
FROM table_two
UNION ALL
SELECT info_fie... | There are other ways to achieve your goal besides my suggestions below, but I would warn against splitting up data that really belongs in one table just to implement a data access policy that may change in the future.
The simplest solution to limit which table columns a user sees is through views on those tables. Use ... | How to transform an Oracle SQL into a Stored Procedure that should iterate through some tables fetching a certain data field? | [
"",
"sql",
"oracle",
"stored-procedures",
"plsql",
""
] |
I'm trying to create an algorithm in C# which produces the following output strings:
```
AAAA
AAAB
AAAC
...and so on...
ZZZX
ZZZY
ZZZZ
```
What is the best way to accomplish this?
```
public static IEnumerable<string> GetWords()
{
//Perform algorithm
yield return word;
}
``` | well, if the length is a constant 4, then this would handle it:
```
public static IEnumerable<String> GetWords()
{
for (Char c1 = 'A'; c1 <= 'Z'; c1++)
{
for (Char c2 = 'A'; c2 <= 'Z'; c2++)
{
for (Char c3 = 'A'; c3 <= 'Z'; c3++)
{
for (Char c4 = 'A'; c4 ... | There's always the obligatory LINQ implementation. Most likely rubbish performance, but since when did performance get in the way of using cool new features?
```
var letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();
var sequence = from one in letters
from two in letters
from three in... | What's a good way for figuring out all possible words of a given length | [
"",
"c#",
"string",
"algorithm",
"iterator",
""
] |
**(Scroll down to bottom of post to find solution.)**
Got a asp.net page which contains a
Datalist. Inside this datalist, there
is a template containing a
dropdownlist and each time the
datalist is filled with an item, a
ItemCreatedCommand is called. The
itemCreatedCommand is responsible for
databinding the dropdownli... | When the DataList is data-bound, the AutoPostBack has not been handled yet, i.e. the values in the ItemCreated event are still the original values.
You need to handle the SelectedIndexChange event of the dropdown control. | Regarding your 2nd question:
I suggest you remove the AutoPostBack from the dropdown, add an "Update" button, and update the data in the button Click event.
The button can hold Command and CommandArgument values, so it's easy to associate with a database record. | DropdownList.selectedIndex always 0 (yes, I do have !isPostBack) | [
"",
"c#",
"asp.net",
"drop-down-menu",
"postback",
""
] |
I have a container filled with pairs. I want to iterate in it using the STL generic algorithms (in my case it would be inner\_product, but consider it as a generic problem).
The algorithm I am using expects iterators first and last. Can I provide special iterators first and last that will iterate not on the pairs but o... | I've looked around and found `boost::transform_iterator`. I've come up with this code. Surprising how well it works:
```
#include <map>
#include <algorithm>
#include <iostream>
#include <string>
#include <iterator>
#include <boost/iterator/transform_iterator.hpp>
#include <boost/bind.hpp>
#include <boost/function.hpp>... | You can subclass e.g. std::vector::const\_iterator yourself, reimplementing operator\* and operator-> to return the first of the pair. You'd also need to create your own begin() and end() functions to return your custom iterator.
You can also create to binary function classes and pass those to inner\_product. | Providing an iterator for the first element of a container of pairs | [
"",
"c++",
"generics",
"templates",
"stl",
""
] |
Are there any tools that auto-generate the hibernate POJOs by gathering information from the database?
I made a perl script to do this after the schema got changed for the third or fourth time in a project i'm working with and just wondered if there is any established tool that will do this for me as my script is rath... | See [hibernate reverse engineering](https://docs.jboss.org/tools/latest/en/hibernatetools/html/reverseengineering.html) | Netbeans does a nice job of generating annotations entities that will work with hibernate-annotations/entitmanager. I've also used the Hibernate Tools/JBoss IDE in Eclipse to generate them and it worked pretty well. | hibernate auto-discovery and generation of of database mappings to POJOs | [
"",
"java",
"hibernate",
"automation",
"code-generation",
"pojo",
""
] |
I'm trying to perform a simple INSERT and return the identity (auto-incrementing primary key). I've tried
```
cmd.CommandText = "INSERT INTO Prototype ( ParentID ) VALUES ( NULL ); SELECT SCOPE_IDENTITY();";
```
and I receive the following error
```
EnvironmentError: SQLite error
no such function: SCOPE_IDENTITY
```... | Check out the [FAQ](http://www.sqlite.org/faq.html#q1). The [sqlite3\_last\_insert\_rowid()](http://www.sqlite.org/c3ref/last_insert_rowid.html) function will do it. Careful of triggers though. | If you're not using the C interface for programming and want to do the process from an SQL Command try: `SELECT last_insert_rowid()`
<http://www.sqlite.org/lang_corefunc.html> | Does SQLite support SCOPE_IDENTITY? | [
"",
"sql",
"sqlite",
""
] |
I have a winforms application that is doing the following:
on each query:
1. Db connect
2. Db query
3. Db disconnect
as we are trying to avoid having to keep the db connection open. This suffers from performance as we have to connect / disconnect everytime.
What is the idealized model here to have the fastest perfo... | The most efficient means is connection pooling, and [ADO.NET does this automatically for you](http://msdn.microsoft.com/en-us/library/8xx3tyca.aspx) as long as you make sure to close your connections. Just wrap your `SqlConnection` objects into `using` statements, and you won't have to worry about it. | There is *very* little overhead in connecting/disconnecting with connection pooling. Your bottleneck is most definitely the DB queries themselves, so leaving a global connection open isn't going to help.
If your queries are too slow, try to optimize them. If that doesn't work, you'll be looking at caching, asynchronou... | ideal design for winforms connecting to SQL Server . | [
"",
"c#",
"sql-server",
"winforms",
""
] |
I am trying to locate an evil plugin that includes a stoneage version of a certain jar file. How do I do that ? | also, mvn -X will spit out all kinds of info, i believe it includes dependency versions. | `mvn dependency:resolve-plugins` gives a list of dependencies for each plugin | How do I track plugin dependencies in maven2? | [
"",
"java",
"maven-2",
"maven-plugin",
""
] |
We recently had a code review . One of my classes was used so that I could return/pass more than one type of data from/to methods . The only methods that the class had were getters/setters . One of the team's members ( whose opinion I respect ) said that having a class like that is bad practice ( and not very OOP ) . W... | There's an argument that classes should either be "data structures" (i.e., focus on storing data with no functionality) or "functionality oriented" (i.e., focus on performing certain actions while storing minimal state). If you follow that argument (which makes sense but isn't always easy to do) then there is nothing n... | Note that there are two separate issues here.
1. Is a "struct-like" class sensible?
2. Is creating a class to return multiple values from a method sensible?
**Struct-like classes**
An object class should -- for the most part -- represent a class of real-world objects. A passive, struct-like java bean (all getters an... | Why is using a class as a struct bad practice in Java? | [
"",
"java",
"oop",
"class",
"struct",
""
] |
What is the Python equivalent of the following code in Ruby?
```
def loop
cont=nil
for i in 1..4
puts i
callcc {|continuation| cont=continuation} if i==2
end
return cont
end
> c=loop
1
2
3
4
> c.call
3
4
```
Reference: [Secrets of lightweight development success, Part 9: Continuations-based framework... | The article you quoted contains a link to [Continuations Made Simple And Illustrated](http://www.ps.uni-sb.de/~duchier/python/continuations.html) in the Resources section, which talks about continuations in the Python language. | take a look at the [yield](http://www.python.org/doc/2.6/reference/simple_stmts.html#the-yield-statement) statement to make generators.
I don't speak any ruby, but it seems like you're looking for this:
```
def loop():
for i in xrange(1,5):
print i
if i == 2:
yield
for i in loop():
... | Python equivalent of continuations with Ruby | [
"",
"python",
"ruby",
"continuations",
""
] |
I have been working on a legacy C++ application and am definitely outside of my comfort-zone (a good thing). I was wondering if anyone out there would be so kind as to give me a few pointers (pun intended).
I need to cast 2 bytes in an unsigned char array to an unsigned short. The bytes are consecutive.
For an exampl... | Well, you are widening the char into a short value. What you want is to interpret two bytes as an short. `static_cast` cannot cast from `unsigned char*` to `unsigned short*`. You have to cast to `void*`, then to `unsigned short*`:
```
unsigned short *p = static_cast<unsigned short*>(static_cast<void*>(&packetBuffer[1]... | This is probably well below what you care about, but keep in mind that you could easily get an unaligned access doing this. x86 is forgiving and the abort that the unaligned access causes will be caught internally and will end up with a copy and return of the value so your app won't know any different (though it's sign... | C++: how to cast 2 bytes in an array to an unsigned short | [
"",
"c++",
"pointers",
"casting",
""
] |
Is there any performance advantage to using lists over dictionaries over tuples in Python?
If I'm optimising for speed, is there any reason to prefer one over another? | Rich,
Lists and dicts are beasts suitable for different needs. Make sure you don't use lists for linear searches where dicts hashes are perfect, because it's way slower. Also, if you just need a list of elements to traverse, don't use dicts because it will take much more space than lists.
That may sound obvious, but ... | Tuples will be slightly faster to construct for a small number of elements. Although actually most of the gains will be in memory used rather than CPU cycles, since tuples require less space than lists.
With that being said, the performance difference should be negligible, and in general you shouldn't worry about thes... | Python data structures overhead/performance | [
"",
"python",
"optimization",
""
] |
# Why are circular references in Visual Studio a bad practice?
First, I will describe an example of how this can happen using C# in Visual Studio, since VS will typically inform you if you have a circular reference and prevent it.
First, a **Utilities** class is created relying only on the code given to you by Visual... | Yes, this is a bad practice for precisely the reason you've stated - you cannot rebuild from the source. | This is one of the symptoms of over-modularization.
I worked at a company once with about twenty developers and more than sixty different active projects in the SVN repository. Every project had its own build script and produced a JAR file that was a dependency of at least a half-dozen or so other projects. Managing a... | Why are circular references in Visual Studio a bad practice? | [
"",
"c#",
"visual-studio",
""
] |
How can I verify a given xpath string is valid in C#/.NET?
I'm not sure just running the XPath and catching exceptions is a valid solution (putting aside the bile in my throat for a moment) - what if tomorrow I run into some other input I haven't tested against? | > How can I verify a given XPath string is valid in C#/.NET?
You try to build an `XPathExpression` from it and catch the exception.
```
try
{
XPathExpression.Compile(xPathString);
}
catch (XPathException ex)
{
MessageBox.Show("XPath syntax error: " + ex.Message);
}
``` | For a shorter version than [@Tomalak's answer](https://stackoverflow.com/a/308953/225292), you can just use the [XPathExpression.Compile](http://msdn.microsoft.com/en-us/library/ms163317%28v=vs.80%29.aspx) method:
```
string xpath = "/some/xpath";
try
{
XPathExpression expr = XPathExpression.Compile(xpath);
}
cat... | Verify an XPath in .NET | [
"",
"c#",
".net",
"xpath",
""
] |
I have a very simple model. I want to add a send email routine to on of the methods for the model:
```
$this->Email->delivery = 'smtp';
$this->Email->template = 'default';
$this->Email->sendAs = 'text';
$this->Email->from = 'email';
$this->Email->to = 'email';
$this->Email->subject = 'Error';
```
I've tr... | Well, you're doing it wrong way. You should place email send routine in your AppController:
```
function _sendMail($to,$subject,$template) {
$this->Email->to = $to;
// $this->Email->bcc = array('secret@example.com'); // copies
$this->Email->subject = $subject;
$this->Email->replyTo = 'noreply@domain.co... | even if it is not best practice, you actually can use the EmailComponent in a model, but you need to instanciate it (in the Models there is no automatic Component loading) and you need to pass it a controller. The EmailComponent relies on the Controller because of the connection it needs to the view, for rendering emai... | How do I use the email component from a model in CakePHP? | [
"",
"php",
"cakephp",
""
] |
I put together a sample scenario of my issue and I hope its enough for someone to point me in the right direction.
I have two tables
Products

Product Meta

I need a result set of the following
 AS A,
MAX(CASE [m].MetaKey
WHEN 'B'
THEN [m].MetaValue
END) AS B,
... | I realize this is two years old, but it bugs me that the accepted answer calls for using dynamic SQL and the most upvoted answer won't work:
```
Select P.ProductId, P.Name
, Min( Case When PM.MetaKey = 'A' Then PM.MetaValue End ) As A
, Min( Case When PM.MetaKey = 'B' Then PM.MetaValue End ) As B
, Min( Ca... | Pivot using SQL Server 2000 | [
"",
"sql",
"sql-server",
"t-sql",
"sql-server-2000",
""
] |
I need a method to return a random string in the format:
Letter Number Letter Number Letter Number | Assuming you don't need it to be threadsafe:
```
private static readonly Random rng = new Random();
private static RandomChar(string domain)
{
int selection = rng.Next(domain.Length);
return domain[selection];
}
private static char RandomDigit()
{
return RandomChar("0123456789");
}
private static char R... | You just need 2 methods.
1) Random a char (You can use [ASCII](http://asciitable.com/) to random between number than cast to char)
2) Random number.
Both can use this utility method:
```
private int RandomNumber(int min, int max)
{
Random random = new Random();
return random.Next(min, max);
}
```
For the ... | How to make a method to return random string in the format A1A 1A1? | [
"",
"c#",
"methods",
""
] |
My Facebook application contains Javascript that works in Firefox and IE, but aborts in Chrome.
In the Javascript console it gives several errors.including:
```
Uncaught TypeError: Object onloadhooks has no method 'replace'
```
There are similar errors complaining about a missing method for 'toLowerCase'.
**Stop Pr... | According to the Chrome developers ([Issue 1717](http://code.google.com/p/chromium/issues/detail?id=1717)), this is an issue with the Facebook FBJS library, and something they plan to escalate to Facebook.
I don't have a workaround for this in the meantime. | Facebook itself has problems in Chrome. On some pages the buttons just don't work (like deleting a news entry on your own page). | My Facebook application's Javascript doesn't work in Google Chrome | [
"",
"javascript",
"facebook",
"google-chrome",
""
] |
In Django templates, is there a variable in the context (e.g. `{{ BASE\_URL }}`, `{{ ROOT\_URL }}`, or `{{ MEDIA\_URL }}` that one can use to link to the `home` url of a project?
I.e. if Django is running in the root of a project, the variable (let's call it R) `{{ R }}` in a template would be `/`. If the root url is ... | You could give the URL configuration which you're using to handle the home page a name and use that:
urls.py:
```
from django.conf.urls.defaults import *
urlpatterns = patterns('myproject.views',
url(r'^$', 'index', name='index'),
)
```
Templates:
```
<a href="{% url index %}">...
```
**UPDATE:** Newer versio... | I always use something like `<a href="/">` (assuming your home is at the root, of course). I seem to recall looking this up once, and couldn't find a Django variable for this path; at any rate, `/` seemed pretty easy, anyway. | How does one put a link / url to the web-site's home page in Django? | [
"",
"python",
"django",
"django-urls",
""
] |
In a comment on this [answer to another question](https://stackoverflow.com/questions/306130/python-decorator-makes-function-forget-that-it-belongs-to-a-class#306277), someone said that they weren't sure what `functools.wraps` was doing. So, I'm asking this question so that there will be a record of it on StackOverflow... | When you use a decorator, you're replacing one function with another. In other words, if you have a decorator
```
def logged(func):
def with_logging(*args, **kwargs):
print(func.__name__ + " was called")
return func(*args, **kwargs)
return with_logging
```
then when you say
```
@logged
def f(... | As of python 3.5+:
```
@functools.wraps(f)
def g():
pass
```
Is an alias for `g = functools.update_wrapper(g, f)`. It does exactly three things:
* it copies the `__module__`, `__name__`, `__qualname__`, `__doc__`, and `__annotations__` attributes of `f` on `g`. This default list is in `WRAPPER_ASSIGNMENTS`, you ... | What does functools.wraps do? | [
"",
"python",
"decorator",
"functools",
""
] |
When opening a window, I register a Deleted-event-handler on my business object. It is passed to the constructor as `business`:
```
business.Deleted += new EventHandler<EventArgs>(business_Deleted);
```
Now the user can click a button to delete it (removing the record, you know). The event handler is registered to ca... | If you realy want this behaviour ( I don't think, this is good pattern, bud its not matter ), you can derive from EventArgs class and add property for author of deletion.
Then you can do:
```
c.Delete( this ); //this = window
// ...
void business_Deleted(object sender, EventArgs e) {
bool isDeletedFromMe = false;
... | I'm not sure why your sample code does not work as expected but you could try adding a private member variable to check if this user is deleting the record or another user.
```
private bool otherUser = true;
void business_Deleted(object sender, EventArgs e)
{
if(otherUser) {
/* Show message */
}
}
vo... | Unregistering Event with -=-Operator | [
"",
"c#",
"winforms",
"events",
"event-handling",
""
] |
Simple question:
Can a swing frame be completely modal ( block all others windows ) ?
I tried the following, but I can still click on other apps windows ( like this browser )
```
JDialog myDialog = ....
myDialog.setModalityType(Dialog.ModalityType.APPLICATION_MODAL);
```
Plase paste some code if this is possible. | JFrame is not designed to be modal. Use JDialog for it, but you will loose some JFrame functionality doing so.
If you can't live with the loss, you have to block the EventQueue and replace it with your own to only accept events from the blocking one.
See [Creating Modal Internal Frames](http://java.sun.com/developer/J... | Dialogs are not meant to be globally modal. Every modern OS strongly discourages global modality in its HIG, and they may even have deprecated the functionality (as indicated by the fact that you can't get it to work). Your app should *never* steal events from the entire system; that's not only bad design, it's near-cr... | Swing app global modal | [
"",
"java",
"swing",
"modal-dialog",
""
] |
For instance, does the compiler know to translate
```
string s = "test " + "this " + "function";
```
to
```
string s = "test this function";
```
and thus avoid the performance hit with the string concatenation? | Yes. This is guaranteed by the C# specification. It's in section 7.18 (of the C# 3.0 spec):
> Whenever an expression fulfills the
> requirements listed above, the
> expression is evaluated at
> compile-time. This is true even if the
> expression is a sub-expression of a
> larger expression that contains
> non-constant... | Just a side note on a related subject - the C# compiler will also 'optimize' multiple concatenations involving non-literals using the '`+`' operator to a single call to a multi-parameter overload of the String.Concat() method.
So
```
string result = x + y + z;
```
compiles to something equivalent to
```
string resu... | Does C# optimize the concatenation of string literals? | [
"",
"c#",
".net",
"performance",
"optimization",
""
] |
One of the things that seems to be necessary with use of STL is a way to specify local functions.
Many of the functions that I would normally provide cannot be created using STL function object creation tools ( eg bind ), I have to hand roll my function object.
Since the C++ standard forbids local types to be used as ... | Boost.Bind, Boost.Function, and Boost.Lambda are your friends. | The standard way is a "functor" - basically, a `struct` that supplies an `operator()`
For example:
```
struct MyMinFunctor {
bool operator()(const int& a, const int& b) { return a > b; }
};
vector<int> v;
sort(v.begin(), v.end(), MyMinFunctor());
```
Because it is a struct/class, you can subclass any of the thing... | Approaching STL algorithms, lambda, local classes and other approaches | [
"",
"c++",
"stl",
"lambda",
""
] |
On a more abstract level then [a previous question](https://stackoverflow.com/questions/299729/javascript-to-flash-communication), in my experience there are 3 ways to call a javascript function on an html page from an embedded .swf using AS3: ExternalInterface, fscommand, and navigateToURL.
Let's compare and contrast... | ExternalInferface was created to make communication between JS and Flash easier, so it doens't really make sense to use anything else. Common practice is to check if its available first by evaluating the value of the ExternalInterface.available property before making a call to some JS. This property tells you if the SW... | It all depends on if you want the communication to be synchronous or not as `ExternaInterface` can return data as where `navigatoToURL` and `fscommand` are asynchronous and can only call a javascript function; they cannot return values or a response.
From live docs in relation to External Interface:
> From ActionScri... | Actionscript3 to JavaScript communication: best practices | [
"",
"javascript",
"actionscript-3",
"externalinterface",
""
] |
I'm trying to create a function in C# which will allow me to, when called, return a reference to a given class type. The only types of functions like this that I have seen are in UnrealScript and even then the functionality is hard coded into its compiler. I'm wondering if I can do this in C#. Here's what I mean (code ... | Rather than use a generic *class*, use a generic *method*:
```
public T Spawn<T>() where T : new()
{
return new T();
}
```
Having said that, I assume you want to do more than just blindly create an instance, otherwise you could just call `new MyClass()` yourself. | You can use the class System.Type to represent classes. To get references to type objects, you either use typeof (in a scope where the class is actually defined)
```
System.Type t = typeof(ActorChild);
```
or the Type.GetType function (if you only know the name of the type)
```
System.Type t = Type.GetType("Namespac... | Class Limiting and Archetypes | [
"",
"c#",
""
] |
Can someone explain in simple terms the "signals and slots" pattern? | Signals and slots are a way of decoupling a sender (the signal) and zero or more receivers (the slots). Let's say you a system which has events that you want to make available to any other part of the system interested in those events. Rather than hard-wiring the code that generates event to the code that wants to know... | I think one can describe signals and slots best when you are looking at them as a possible implementation vehicle for the [Observer Pattern or Publish/Subscriber Pattern](http://en.wikipedia.org/wiki/Observer_pattern). There is one `signal`, for example `buttonPressed(IdType)` on the Publisher Side. Whenever the button... | What are signals and slots? | [
"",
"c++",
"design-patterns",
"signals-slots",
""
] |
I have this naive regex "<([\s]|[^<])+?>" (excluding the quotation marks). It seems so
straightforward but it is indeed evil when it works against the below HTML text. It sends the Java regular expression engine to an infinite loop.
I have another regex ("<.+?>"), which does somewhat the same thing, but it doesn't kil... | The reason the Java regex engine crashes is that this part of your regex causes a stack overflow (indeed!):
```
[\s]|[^<]
```
What happens here is that every character matched by \s can also be matched by [^<]. That means there are two ways to match each whitespace character. If we represent the two character classes... | The regex `([\s]|[^<])` in plain terms means any single character that IS white-space or IS NOT a `<` character, which is redundant because white-space characters are NOT a `<` character. It appears to me that what you really mean is:
```
`"<([^<])+?>"`
```
I am not sure if this will solve the infinite loop, but I th... | Why does this regular expression kill the Java regex engine? | [
"",
"java",
"regex",
""
] |
I'm working on an application developed by another mob and am confounded by the use of a char field instead of bit for all the boolean columns in the database. It uses "Y" for true and "N" for false (these have to be uppercase). The type name itself is then aliased with some obscure name like *ybln*.
This is very anno... | I've seen this practice in older database schemas quite often. One advantage I've seen is that using CHAR(1) fields provides support for more than Y/N options, like "Yes", "No", "Maybe".
Other posters have mentioned that Oracle might have been used. The schema I referred to was in-fact deployed on Oracle and SQL Serve... | Welcome to brownfield. You've inherited an app designed by old-schoolers. It's not a design pattern (at least not a design pattern with something good going for it), it's a vestige of coders who cut their teeth on databases with limited data types. Short of refactoring the DB and lots of code, grit your teeth and gut y... | Why use "Y"/"N" instead of a bit field in Microsoft SQL Server? | [
"",
"sql",
"sql-server",
"boolean",
""
] |
Assuming the following class stub:
```
public class Foo<T> {
private Class<T> type;
public Foo<T> () {}
}
```
Can I store the generic type `T` into the field `type` in the constructor, without changing the constructor's signature to "`public Foo<T> (Class<T> type)`"?
If yes, how? If no, why?
"`type = T`" doesn... | No - type erasure means that you have to provide *something* at execution time. You could provide either an instance of `T` or `Class<T>` but the class itself will just have every occurrence of T replaced with `Object`.
This kind of thing is one of the biggest disadvantages of Java's generics vs those in .NET. (On the... | As said in this [thread](http://forums.sun.com/thread.jspa?threadID=5284624),
for Example List<Integer>
```
list.get (index).getClass()
```
will ***not*** give you type of object stored in list:
* when the list is empty
* even when the list is NOT empty, because any element can be any subclass of the generic type p... | Can I store the generics attribute into an object's field | [
"",
"java",
"generics",
""
] |
We have a Java application that needs to be brought to the foreground when a telecontrol mechanism activates something in the application.
In order to get this, we have realized in the called method of the class which represents the frame of our application (extension of a `JFrame`) following implementation:
```
setV... | A possible solution is:
```
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
myFrame.toFront();
myFrame.repaint();
}
});
``` | I had the same problem with bringing a `JFrame` to the front under Ubuntu (Java 1.6.0\_10). And the only way I could resolve it is by providing a `WindowListener`. Specifically, I had to set my `JFrame` to always stay on top whenever `toFront()` is invoked, and provide `windowDeactivated` event handler to `setAlwaysOnT... | How to bring a window to the front? | [
"",
"java",
"windows",
"swing",
"awt",
""
] |
We host a C++ based WebServices application in IIS and we're finding that when we try to start our own C++ threads IIS has a fit and crashes. The threads are based on boost.thread which clearly dribbles down to the standard Windows threading API underneath.
The reason I need to start the thread is to listen for multic... | It sounds like you're creating a persistent thread, which lives longer than the lifetime of the request that initiates it. You don't mention whether it's ASP.NET C++/CLI, Managed C++ or an ISAPI extension or filter, or even CGI.
Conceptually, code that is called by IIS is only supposed to "live" for the lifetime of th... | I don't know about C++, but in my C# ASP.NET application, I am creating threads and it's working fine. Are .NET "real" threads? I don't know... but they behave like you'd want a thread to behave. Maybe you can have just that part of your app be ASP.NET C#? | Is it possible to start a custom thread in an IIS hosted C++ application? | [
"",
"c++",
"multithreading",
"iis",
"multicast",
""
] |
I am working on a silverlight app that you need to enter information into a textbox and then just hit enter. Well there is no onclick event, that I could find, so what I did was use the onkeypressup event and check if it was the enter key that was pressed if so do "blah".
It just feels like there is a better way to do... | I thinks that's the way to catch Key.Enter.
Also, you're code will be more readable if you use the KeyDown event instead of the KeyUp event.
If you only care about catching Key.Enter for a single control then your approach is correct.
You can also catch the Key.Enter for a group of related controls by using the KeyD... | Do you really want it in the textbox? I would put a onkeyup handler on the container (e.g. Grid, Canvas) to press the button anywhere on the form. | Pressing Enter on TextBox in Silverlight | [
"",
"c#",
"silverlight",
"silverlight-2.0",
""
] |
I am using C# and Windows Forms. I have a normal progress bar working fine in the program, but now I have another operation where the duration cannot be easily calculated. I would like to display a progress bar but don't know the best way to start/stop the scrolling marquee. I was hoping for something as simple as sett... | Use a progress bar with the style set to `Marquee`. This represents an indeterminate progress bar.
```
myProgressBar.Style = ProgressBarStyle.Marquee;
```
You can also use the [`MarqueeAnimationSpeed`](http://msdn.microsoft.com/en-us/library/system.windows.forms.progressbar.marqueeanimationspeed.aspx) property to set... | To start/stop the animation, you should do this:
To start:
```
progressBar1.Style = ProgressBarStyle.Marquee;
progressBar1.MarqueeAnimationSpeed = 30;
```
To stop:
```
progressBar1.Style = ProgressBarStyle.Continuous;
progressBar1.MarqueeAnimationSpeed = 0;
``` | Windows Forms ProgressBar: Easiest way to start/stop marquee? | [
"",
"c#",
"winforms",
"progress-bar",
""
] |
Is there a way to use these operators to input and output binary data? The reason I want to do this is that it makes the code readable.
Ex: infile >> filedecrypter >> metadataparser >> audiodecoder >> effects >> soundplayer; | Indeed that can be done, if the library or your code provides the overloads for `operator<<` and `operator>>` for it to work. Simple example on how one could do it:
```
class transformer {
public:
virtual std::iostream& transform(std::iostream&) = 0;
};
class noise : public transformer {
public:
virtu... | Just to be clear, are you intending to duplicate the semantics of iostreams? Because it looks like you are proposing something different. In the example you give:
```
infile >> filedecrypter >> metadataparser >> audiodecoder >> effects >> soundplayer;
```
In iostreams, the meaning here is to read from infile into fil... | How would I use the >> and << operators for binary data in C++? | [
"",
"c++",
"stream",
""
] |
I'd like to find all the types inheriting from a base/interface. Anyone have a good method to do this? Ideas?
I know this is a strange request but its something I'm playing with none-the-less. | Use Assembly.GetTypes() to get all the types, and Type.IsAssignableFrom() to check for inheritance. Let me know if you need code - and also whether or not you're using .NET 3.5. (A lot of reflection tasks like this are simpler with LINQ to Objects.)
EDIT: As requested, here's an example - it finds everything in `mscor... | ```
var a = Assembly.Load("My.Assembly");
foreach (var t in a.GetTypes().Where(t => t is IMyInterface))
{
// there you have it
}
``` | Search an assembly for all child types? | [
"",
"c#",
"reflection",
""
] |
Is there something similar to `sprintf()` in C#?
I would for instance like to convert an integer to a 2-byte byte-array.
Something like:
```
int number = 17;
byte[] s = sprintf("%2c", number);
``` | It turned out, that what I really wanted was this:
```
short number = 17;
System.IO.BinaryWriter writer = new System.IO.BinaryWriter(stream);
writer.Write(number);
writer.Flush();
```
The key here is the Write-function of the BinaryWriter class. It has 18 overloads, converting different formats to a byte array which ... | ```
string s = string.Format("{0:00}", number)
```
The first 0 means "the first argument" (i.e. number); the 00 after the colon is the format specifier (2 numeric digits).
However, note that .NET strings are UTF-16, so a 2-character string is 4 bytes, not 2
(edit: question changed from `string` to `byte[]`)
To get ... | Equivalent of sprintf in C#? | [
"",
"c#",
"string",
"printf",
""
] |
How do I get the `GridView` control to render the `<thead>` `<tbody>` tags? I know `.UseAccessibleHeaders` makes it put `<th>` instead of `<td>`, but I cant get the `<thead>` to appear. | This should do it:
```
gv.HeaderRow.TableSection = TableRowSection.TableHeader;
``` | I use this in `OnRowDataBound` event:
```
protected void GridViewResults_OnRowDataBound(object sender, GridViewRowEventArgs e) {
if (e.Row.RowType == DataControlRowType.Header) {
e.Row.TableSection = TableRowSection.TableHeader;
}
}
``` | How do I get Gridview to render THEAD? | [
"",
"c#",
".net",
"asp.net",
"gridview",
""
] |
I would like to do something like the following but can't seem to get the syntax for the Do method quite right.
```
var sqr = new _mocks.CreateRenderer<ShapeRenderer>();
Expect.Call(sqr.CanRender(null)).IgnoreArguments().Do(x =>x.GetType() == typeof(Square)).Repeat.Any();
```
So basically, I would like to set up the ... | Are you looking for this?
```
Expect.Call(sqr.CanRender(null)).IgnoreArguments()
.Do((Func<Shape, bool>) delegate(Agent x){return x.GetType() == typeof(Square);})
.Repeat.Any();
```
EDIT: The answer was correct in spirit bu the original syntax did not quite work. | If you aren't able to use .Net Framework 3.5 (required by [Cristian's answer](https://stackoverflow.com/questions/313030/rhino-mocks-how-to-return-conditonal-result-from-a-mock-object-method/313080#313080)) and therefore don't have access to the [System.Func](http://msdn.microsoft.com/en-us/library/bb534960.aspx) deleg... | Rhino Mocks: How to return conditional result from a mock object method | [
"",
"c#",
"rhino-mocks",
"anonymous-methods",
""
] |
Say I am declaring a class `C` and a few of the declarations are very similar. I'd like to use a function `f` to reduce code repetition for these declarations. It's possible to just declare and use `f` as usual:
```
>>> class C(object):
... def f(num):
... return '<' + str(num) + '>'
... v = f(9)
.... | Quite simply, the solution is that f does not need to be a member of the class. I am assuming that your thought-process has gone through a Javaish language filter causing the mental block. It goes a little something like this:
```
def f(n):
return '<' + str(num) + '>'
class C(object):
v = f(9)
w = f(42)
... | Extending [Ali A](https://stackoverflow.com/questions/304655/the-best-way-to-invoke-methods-in-python-class-declarations#304679)'s answer,
if you really want to avoid f in the module namespace (and using a non-exported name like \_f, or setting \_\_all\_\_ isn't sufficient), then
you could achieve this by creating the ... | The best way to invoke methods in Python class declarations? | [
"",
"python",
"class",
"declaration",
"static-methods",
"invocation",
""
] |
I got the following class :
```
class ConstraintFailureSet(dict, Exception) :
"""
Container for constraint failures. It act as a constraint failure itself
but can contain other constraint failures that can be accessed with a dict syntax.
"""
def __init__(self, **failures) :
dict.__... | Both `Exception` and `dict` are implemented in C.
I think you can test this the follwing way:
```
>>> class C(object): pass
...
>>> '__module__' in C.__dict__
True
>>> '__module__' in dict.__dict__
False
>>> '__module__' in Exception.__dict__
False
```
Since `Exception` and `dict` have different ideas of how to stor... | What's wrong with this?
```
class ConstraintFailure( Exception ):
def __init__( self, **failures ):
self.failures= failures # already a dict, don't need to do anything
def __getitem__( self, key ):
return self.failures.get(key)
```
This is an Exception, and it contains other exceptions in an i... | Why can't I inherit from dict AND Exception in Python? | [
"",
"python",
"multiple-inheritance",
""
] |
(Django 1.x, Python 2.6.x)
I have models to the tune of:
```
class Animal(models.Model):
pass
class Cat(Animal):
def __unicode__(self):
return "This is a cat"
class Dog(Animal):
def __unicode__(self):
return "This is a dog"
class AnimalHome(models.Model):
animal = models.ForeignKey(Animal)
```
I h... | ForeignKey(Animal) is just that, a foreign key reference to a row in the Animal table. There's nothing in the underlying SQL schema that indicates that the table is being used as a superclass, so you get back an Animal object.
To work around this:
First, you want the base class to be non-abstract. This is necessary f... | You want an [Abstract base class](http://docs.djangoproject.com/en/dev/topics/db/models/#id5) ("virtual" doesn't mean anything in Python.)
From the documentation:
```
class CommonInfo(models.Model):
name = models.CharField(max_length=100)
age = models.PositiveIntegerField()
class Meta:
abstract =... | Django Admin Interface Does Not Use Subclass's __unicode__() | [
"",
"python",
"django",
"django-admin",
""
] |
I'm using Notepad++ for python development, and few days ago I found out about free Komodo Edit.
I need Pros and Cons for Python development between this two editors... | I have worked a bit with Python programming for Google App Engine, which I started out in Notepad++ and then recently shifted over to Komodo using two excellent startup tutorials - both of which are conveniently linked from [this blog post](http://blogs.activestate.com/2008/04/komodo-does-it "Komodo does it all: Google... | I just downloaded and started using Komodo Edit. I've been using Notepad++ for awhile. Here is what I think about some of the features:
Komodo Edit Pros:
* You can jump to a function definition, even if it's in another file (I love this)
* There is a plugin that displays the list of classes, functions and such for th... | Komodo Edit and Notepad++ ::: Pros & Cons ::: Python dev | [
"",
"python",
"editor",
"notepad++",
"komodo",
"komodoedit",
""
] |
I know of `is` and `as` for `instanceof`, but what about the reflective [isInstance()](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Class.html#isInstance(java.lang.Object)) method? | The equivalent of Java’s `obj.getClass().isInstance(otherObj)` in C# is as follows:
```
bool result = obj.GetType().IsAssignableFrom(otherObj.GetType());
```
Note that while both Java and C# work on the runtime type object (Java `java.lang.Class` ≣ C# `System.Type`) of an `obj` (via `.getClass()` vs `.getType()`), Ja... | ```
bool result = (obj is MyClass); // Better than using 'as'
``` | What is the C# equivalent to Java's isInstance()? | [
"",
"c#",
"reflection",
"introspection",
"instanceof",
""
] |
We're all familiar with the horror that is C# event declaration. To ensure thread-safety, [the standard is to write something like this](http://blogs.msdn.com/brada/archive/2005/01/14/353132.aspx):
```
public event EventHandler SomethingHappened;
protected virtual void OnSomethingHappened(EventArgs e)
{
... | It will still work with events that have an explicit add/remove - you just need to use the delegate variable (or however you've stored the delegate) instead of the event name.
However, there's an easier way to make it thread-safe - initialize it with a no-op handler:
```
public event EventHandler SomethingHappened = ... | Now C# 6 is here, there is a more compact, thread-safe way to fire an event:
```
SomethingHappened?.Invoke(this, e);
```
`Invoke()` is only called if delegates are registered for the event (i.e. it's not null), thanks to the null-conditional operator, "?".
The threading problem the "handler" code in the question set... | Raising C# events with an extension method - is it bad? | [
"",
"c#",
".net",
"events",
"event-handling",
"extension-methods",
""
] |
When generating graphs and showing different sets of data it usually a good idea to difference the sets by color. So one line is red and the next is green and so on. The problem is then that when the number of datasets is unknown one needs to randomly generate these colors and often they end up very close to each other... | You have three colour channels 0 to 255 R, G and B.
First go through
```
0, 0, 255
0, 255, 0
255, 0, 0
```
Then go through
```
0, 255, 255
255, 0, 255
255, 255, 0
```
Then divide by 2 => 128 and start again:
```
0, 0, 128
0, 128, 0
128, 0, 0
0, 128, 128
128, 0, 128
128, 128, 0
```
Divide by 2 => 64
Next time ad... | To implement a variation list where by your colors go, 255 then use all possibilities of that up, then add 0 and all RGB patterns with those two values. Then add 128 and all RGB combinations with those. Then 64. Then 192. Etc.
In Java,
```
public Color getColor(int i) {
return new Color(getRGB(i));
}
public int ... | Generate distinctly different RGB colors in graphs | [
"",
"c#",
"random",
"graph",
"colors",
""
] |
Is it a simple case of just never using the this.XYZ construct? | It's only considered poor style if it violates your style guidelines. Sometimes using `this` is necessary to qualify a member variable over a local variable:
```
public MyType(int arg)
{
this.arg = arg;
}
```
This problem can also be mitigated with style guidelines. For example, prefix members with "\_":
```
pub... | I wouldn't say it's poor style - but it's not particularly idiomatic.
My almost sole use of `this.foo` is when copying parameters into fields:
```
public Person (string name, string occupation)
{
this.name = name;
this.occupation = occupation;
}
``` | In C#, is accessing the current object's properties through this.XYZ considered poor style compared to just XYZ | [
"",
"c#",
"coding-style",
""
] |
Let's say I have an int with the value of 1. How can I convert that int to a zero padded string, such as `00000001`? | ```
Declare @MyInt integer Set @MyInt = 123
Declare @StrLen TinyInt Set @StrLen = 8
Select Replace(Str(@MyInt, @StrLen), ' ' , '0')
``` | as of SQL Server 2012 you can now do this:
```
format(@int, '0000#')
``` | How do I convert an int to a zero padded string in T-SQL? | [
"",
"sql",
"t-sql",
""
] |
I used a new Date() object to fill a field in a MySQL DB, but the actual value stored in that field is in my local timezone.
How can I configure MySQL to store it in the UTC/GMT timezone?
I think, configuring the connection string will help but I don't know how. There are many properties in the connection string like... | The short answer is:
* add "default-time-zone=utc" to my.cnf
* in your code, always "think" in UTC, except when displaying dates for your users
* when getting/setting dates or timestamps with JDBC, always use the Calendar parameter, set to UTC:
resultset.getTimestamp("my\_date", Calendar.getInstance(TimeZone.getTim... | MiniQuark gave some good answers for databases in general, but there are some MySql specific quirks to consider...
> Configure your database to use UTC timezone
That actually won't be enough to fix the problem. If you pass a java.util.Date to MySql as the OP was asking, the MySql driver will **change the value** to m... | How to store a java.util.Date into a MySQL timestamp field in the UTC/GMT timezone? | [
"",
"java",
"mysql",
""
] |
Hey having some trouble trying to maintain transparency on a png when i create a thumbnail from it, anyone any experience with this? any help would be great, here's what i am currently doing:
```
$fileName= "../js/ajaxupload/tees/".$fileName;
list($width, $height) = getimagesize($fileName);
$newwidth = 257;
$newheig... | I have had success doing it like this in the past:
```
$thumb = imagecreatetruecolor($newwidth, $newheight);
imagealphablending($thumb, false);
imagesavealpha($thumb, true);
$source = imagecreatefrompng($fileName);
imagealphablending($source, true);
imagecopyresampled($thumb, $source, 0, 0, 0, 0, $newwidth, $newhe... | Forget the color transparency index, it never works in all rendering products. Instead use an alpha layer mask:
```
$image = imagecreatetruecolor($size, $size);
imagealphablending($image, false);
imagesavealpha($image, true);
$trans_layer_overlay = imagecolorallocatealpha($image, 220, 220, 220, 127);
imagefill($imag... | PNG Transparency with PHP | [
"",
"php",
"png",
"transparency",
""
] |
For my small wiki application, I mostly need to have the textarea used to edit the contents to use soft (or virtual) wrapping. However, in some cases, not wrapping the content would be preferable. I thought I would do this by simply having a button to turn off wrapping. Here is the simplified code:
```
<form name="w... | See bug 41464: <https://bugzilla.mozilla.org/show_bug.cgi?id=41464>
Nasty workaround for now is to replace the textarea with a clone of itself:
```
function setWrap(area, wrap) {
if (area.wrap) {
area.wrap= wrap;
} else { // wrap attribute not supported - try Mozilla workaround
area.setAttribu... | Here is a primer on textarea wrap, including a CSS solution:
<http://www.web-wise-wizard.com/html-tutorials/html-form-forms-textarea-wrap.html>
The CSS solution they cite is:
```
white-space: pre; overflow: auto;
```
Which would be:
```
<script type="text/javascript">
function setNoWrap(textarea) {
textarea.st... | Changing textarea wrapping using javascript | [
"",
"javascript",
"dom",
""
] |
I have the following code:
```
Using cmd As SqlCommand = Connection.CreateCommand
cmd.CommandText = "UPDATE someTable SET Value = @Value"
cmd.CommandText &= " WHERE Id = @Id"
cmd.Parameters.AddWithValue("@Id", 1234)
cmd.Parameters.AddWithValue("@Value", "myValue")
cmd.ExecuteNonQuery
End Using
```
... | Whilst not perfect, here's something I knocked up for TSQL - could be easily tweaked for other flavors... If nothing else it will give you a start point for your own improvements :)
This does an OK job on data types and output parameters etc similar to using "execute stored procedure" in SSMS. We mostly used SPs so th... | For logging purposes, I'm afraid there's no nicer way of doing this but to construct the string yourself:
```
string query = cmd.CommandText;
foreach (SqlParameter p in cmd.Parameters)
{
query = query.Replace(p.ParameterName, p.Value.ToString());
}
``` | Get the generated SQL statement from a SqlCommand object? | [
"",
"c#",
"vb.net",
"ado.net",
""
] |
SVN and CVS are two very different systems that aim to address the same basic issue - source control.
They both work in distinct ways, so it's probably difficult to deal with them exactly the same.
What I'm wondering is, would it be conceivable to develop a programming library or API that exposes the same interface, ... | Personally I would ignore CVS for a new product. My feeling would be that the enormous extra effort to coerce it into looking like SVN would be better spent on other other stuff. I don't know your market, so I might be wrong, but that's got to be worth thinking about. | The MSSCCI API does something very similar:
<http://alinconstantin.homeip.net/webdocs/scc/msscci.htm>
The MSSCCI tries to make all source controls look the same from the perspective of the IDE. | Providing a common interface to SVN and CVS | [
"",
"java",
".net",
"svn",
"interface",
"cvs",
""
] |
In the following code I loop through a map and test if an element needs to be erased. Is it safe to erase the element and keep iterating or do I need to collect the keys in another container and do a second loop to call the erase()?
```
map<string, SerialdMsg::SerialFunction_t>::iterator pm_it;
for (pm_it = port_map.b... | ## C++11
This has been fixed in C++11 (or erase has been improved/made consistent across all container types).
The erase method now returns the next iterator.
```
auto pm_it = port_map.begin();
while(pm_it != port_map.end())
{
if (pm_it->second == delete_this_id)
{
pm_it = port_map.erase(pm_it);
... | Here's how I do that ...
```
typedef map<string, string> StringsMap;
typedef StringsMap::iterator StrinsMapIterator;
StringsMap m_TheMap; // Your map, fill it up with data
bool IsTheOneToDelete(string str)
{
return true; // Add your deletion criteria logic here
}
void SelectiveDelete()
{
StringsMap... | What happens if you call erase() on a map element while iterating from begin to end? | [
"",
"c++",
"stl",
"iterator",
""
] |
We have a Linux application that makes use of OpenSSL's Python bindings and I suspect it is causing random crashes. Occasionally, we see it crash with the message:
> Python Fatal Error: GC Object already tracked
which would appear to be either a programming error on the part of the library, or a symptom of memory cor... | Yes, you can do this kind of thing:
```
(gdb) print PyRun_SimpleString("import traceback; traceback.print_stack()")
File "<string>", line 1, in <module>
File "/var/tmp/foo.py", line 2, in <module>
i**2
File "<string>", line 1, in <module>
$1 = 0
```
It should also be possible to use the `pystack` command de... | If you have mac or sun box kicking around you could use [dtrace](http://en.wikipedia.org/wiki/DTrace) and a version of python compiled with dtrace to figure out what the application was doing at the time. Note: in 10.5 python is pre-compiled with dtrace which is really nice and handy.
If that isn't available to you, t... | Python memory debugging with GDB | [
"",
"python",
"linux",
"debugging",
"openssl",
""
] |
The following C# code takes 5 minutes to run:
```
int i = 1;
string fraction = "";
while (fraction.Length < 1000000)
{
fraction += i.ToString();
i++;
}
```
"Optimising it" like this causes it to run in 1.5 seconds:
```
int i = 1;
string fraction = "";
while (fraction.Length < 1000000)
{
// concatenating ... | You will probably see that the first 1000 chars will take almost no time opposed to the last 1000 chars.
I would assume that the time-consuming part is the actual copying of the large string into a new memory-area every time you add a char that is the tough work for your computer.
Your optimization can easily be comp... | I don't get your results at all. On my box StringBuilder wins hands down. Could you post your full test program? Here's mine, with three variants - your string concatenation optimisation, the "simple" StringBuilder one, and StringBuilder with an initial capacity. I've increased the limit as it was going too fast on my ... | String operation optimisation in C# | [
"",
"c#",
"string",
"optimization",
"performance",
""
] |
Has anybody used the ATK Framework? It is claimed to be geared toward developing apps for business use. Manipulating data, knowledge bases, etc... This is what I primarily develop (on the side-for my own use). The site hasn't given me a great overview of why it may be better than other frameworks.
What are your though... | First of all, let me say that I've been using ATK for only few days now, while my co-workers have been using it for almost 6 months.
ATK Framework is really, excellent framework - but with quite special purpose.
If your looking for framework to help you build Administration panel - ATK will save you loads of time. ... | ATK is a great framework. I used it to create [MySHI](http://sourceforge.net/apps/mediawiki/myshi/index.php?title=Main_Page). An open source project I spent some time on back in 2008. I've not yet built anything with Django but have worked through the tutorial once or twice.
ATK is similar to Django's admin interface.... | Considering ATK Framework | [
"",
"php",
"frameworks",
""
] |
From kernel mode in Windows I'm able to intercept and monitor virtually all actions performed on a particular disk. When a file is opened for any purpose I get an event.
Now I want to trace which application that opened it. I think this should be possible but don't know how.
I'm using the standard file management fun... | Just use Win32 N.API to get the pid from the File handle.
It's a FAQ for 15 years... | [Sysinternals Filemon](http://technet.microsoft.com/en-us/sysinternals/bb896642.aspx) (free) does this, and better yet they describe how they did it:
> For the Windows 9x driver, the heart
> of FileMon is in the virtual device
> driver, Filevxd.vxd. It is dynamically
> loaded, and in its initialization it
> installs a... | Tracing which process that has opened a particular file | [
"",
"c++",
"winapi",
"file",
"process-management",
""
] |
I need to write a regular expression that finds javascript files that match
```
<anypath><slash>js<slash><anything>.js
```
For example, it should work for both :
* c:\mysite\js\common.js (Windows)
* /var/www/mysite/js/common.js (UNIX)
The problem is that the file separator in Windows is not being properly escaped :... | Does `Pattern.quote(File.separator)` do the trick?
EDIT: This is available as of Java 1.5 or later. For 1.4, you need to simply escape the file separator char:
```
"\\" + File.separator
```
Escaping punctuation characters will not break anything, but escaping letters or numbers unconditionally will either change the... | > Is there any way to use a common regular expression that works in both Windows and UNIX systems ?
Yes, just use a regex that matches both kinds of separator.
```
pattern = Pattern.compile(
"^(.+?)" +
"[/\\\\]" +
"js" +
"[/\\\\]" +
"(.+?)\\.js$" );
```
It's safe because neither Windows nor Unix... | Escape path separator in a regular expression | [
"",
"java",
"regex",
"escaping",
""
] |
I have a list of integers in C#. I wish to remove duplicates.
In C++ I would run it through the std::sort and then std::unique algorithms for a very efficient way of obtaining the unique list.
What's the best way to do the same thing in C#? In other words, I'm looking for a more elegant way to do the following code:
... | What version of .NET are you using?
In .NET 3.5 that's as simple as calling the [Distinct()](http://msdn.microsoft.com/en-us/library/system.linq.enumerable.distinct.aspx) extension method and then [ToArray()](http://msdn.microsoft.com/en-us/library/bb298736.aspx) if you really need an array again.
For example:
```
i... | if you considering STL methods as "very efficient", so use following:
```
var vals = new List<int> { 1, 2, 3, 2, 1, 2, 3, 2, 3, 4, 3, 2, 3 };
vals.Sort();
var uniques = new HashSet<int>(vals);
```
For 2.0 equivalent
```
List<int> vals = new List<int>();
vals.Add(1);
vals.Add(2);
vals.Add(3);
val... | C# equivalent of std::sort and std::unique | [
"",
"c#",
".net",
"sorting",
"unique",
""
] |
I'm using GCC; \_\_FILE\_\_ returns the current source file's entire path and name: `/path/to/file.cpp`. Is there a way to get just the file's name `file.cpp` (without its path) at compile time? Is it possible to do this in a portable way? Can template meta programming be applied to strings?
I am using this in an erro... | If you're using a `make` program, you should be able to munge the filename beforehand and pass it as a macro to `gcc` to be used in your program. For example, in your `makefile`, change the line:
```
file.o: file.c
gcc -c -o file.o src/file.c
```
to:
```
file.o: src/file.c
gcc "-DMYFILE=\"`basename $<`\"" -c... | I don't know of a direct way. You could use:
```
#line 1 "filename.c"
```
at the top of the source file to set the value of `__FILE__`, but I'm not sure that that's much better than hard coding it. or just using a #define to create your own macro.
Another option might be to pass the name from your Makefile using -D ... | Getting base name of the source file at compile time | [
"",
"c++",
"c",
"makefile",
"macros",
"compiler-construction",
""
] |
Google chrome doesn't behave the same as other browsers when encountering this nugget:
```
<?php
while (true) {
echo "<script type='text/javascript'>\n";
echo "alert('hello');\n";
echo "</script>";
flush();
sleep(5);
}
?>
```
It seems that it's waiting for the connection to terminate before doing... | Some browsers require a certain number of bytes to be downloaded before rendering available data. I remember the last time I tried to do what you're doing I ended up having to dump something like 300 spaces to be sure the browser would bother with it. | I had a similar issue to this, and solved it by adding an HTML tag (in my case <br />) before each flush.
My guess would be that Chrome waits for an element *which is being displayed* to close before triggering a re-render. That's only a guess though.
It didn't seem to require 1024 bytes - I think I would have had ju... | Google Chrome and Streaming HTTP connections? | [
"",
"php",
"ajax",
"http",
"google-chrome",
"streaming",
""
] |
In a Web application, is it possible to force a PDF file to be printed on the client? If the browser is configured to open the PDF inside the window, I guess that calling window.print() will work, but some browsers (like mine) are configured to open the PDF externally. | The way google docs does it is by embedding JavaScript into the PDF that tells Acrobat Reader or any other compliant reader to print it.
You would need a PDF toolkit to do this with a random PDF. | ```
<html>
<script language="javascript">
timerID = setTimeout("exPDF.print();", 1000);
</script>
<body>
<object id="exPDF" type="application/pdf" data="111.pdf" width="100%" height="500"/>
</body>
</html>
``` | How to print a PDF from the browser | [
"",
"javascript",
"html",
"pdf",
""
] |
I'm building the HTML code within an XML DOM object to be used as the contents of the innerHTML of a div element using an XSL template. Traditionally we create a new XML DOM document and add the input parameters as XML Elements for the transform via javascript. This is all very time-consuming as we are basically hand p... | CloneNode is pretty efficient but it will be consuming more memory doing it that way.
Another approach to consider is to use a Template object and a processor, pass your additional/changed data as parameters to the processor and the element that you would have otherwise cloned as the input element. This approach would... | IE will fail on certain things.
e.g. checked radio/checkboxes will not be checked when you add your copy to the DOM.
Example:
<http://webbugtrack.blogspot.com/2008/03/bug-199-cant-clone-form-element-in-ie.html>
<http://webbugtrack.blogspot.com/2007/08/bug-242-setattribute-doesnt-always-work.html>
To see what IE wi... | How efficient is element.cloneNode(true) (deep clone)? | [
"",
"javascript",
"xml",
"clonenode",
""
] |
Lets say I have a single object of type Car which I want to render as HTML:
```
class Car {
public int Wheels { get; set; }
public string Model { get; set; }
}
```
I don't want to use the ASP.NET Repeater or ListView controls to bind because it seems too verbose. I just have the one object. But I still want to be... | if the page is about a specific item (For exemple, Car.aspx?CarID=ABC123), I normally have a public property on the page called "CurrentCar"
```
public Car CurrentCar { get; set; }
```
And I can then have the following:
```
<div>
Wheels: <%= CurrentCar.Wheels %><br />
Model: <%= CurrentCar.Model %>
</div>
```
T... | I would suggest you make car a protected property on the page, this will allow you to access it directly in the aspx page:
```
<div>
Wheels: <%= Car.Wheels %>
Wheels: <%= Car.Models %>
</div>
```
This approach is actually better for single item databinding scenarios as the "binding" is strongly typed. | Is there a way to data bind a single item without eg. a Repeater control? | [
"",
"c#",
"asp.net",
"webforms",
""
] |
> **Possible Duplicate:**
> [How can I convert my java program to an .exe file ?](https://stackoverflow.com/questions/147181/how-can-i-convert-my-java-program-to-an-exe-file)
I've used JSmoothGen in the past, but recently we've seen a number of machines that refuse to run the .exes that it generates. It also seems n... | I use [Launch4J](http://launch4j.sourceforge.net/) which supports Windows, Mac and Linux. I suggest forgoing the somewhat flaky GUI tool and just writing the (short, readable) config file yourself. | The gnu compiler
gcj | Best free tool to build an exe from Java code? | [
"",
"java",
"deployment",
"exe",
""
] |
I have an enum construct like this:
```
public enum EnumDisplayStatus
{
None = 1,
Visible = 2,
Hidden = 3,
MarkedForDeletion = 4
}
```
In my database, the enumerations are referenced by value. My question is, how can I turn the number representation of the enum back to the string name.
For exampl... | You can convert the `int` back to an enumeration member with a simple cast, and then call `ToString()`:
```
int value = GetValueFromDb();
var enumDisplayStatus = (EnumDisplayStatus)value;
string stringValue = enumDisplayStatus.ToString();
``` | If you need to get a string `"Visible"` without getting `EnumDisplayStatus` instance you can do this:
```
int dbValue = GetDBValue();
string stringValue = Enum.GetName(typeof(EnumDisplayStatus), dbValue);
``` | Enum String Name from Value | [
"",
"c#",
"enums",
""
] |
All the examples I see are for Java SE applications by passing your JAR file at the command line. Can JConsole attach to a WAR or EAR and monitor application performance? | JConsole is for monitoring JVMs. I'm assuming that you would like to monitor the performance of your application server. To do so, you'll have to set the com.sun.management.jmxremote property, when initializing your application server.
For example, in Tomcat (I know this is not a complete Java EE container), you would... | If you are using Tomcat you should try [lambda probe](http://www.lambdaprobe.org). It's a war file that once installed on tomcat enables a web-app with similar monitoring capabilities as jconsole.
On the lambda probe web there is also a JBoss download, but I only tested on tomcat. | Can jconsole be used with Java EE? | [
"",
"java",
"jakarta-ee",
"jmx",
"jconsole",
""
] |
Strange program hang, what does this mean in debug?
After attaching windbg I found the following:
```
(1714.258): Access violation - code c0000005 (first chance)
First chance exceptions are reported before any exception handling.
This exception may be expected and handled.
eax=015b5c74 ebx=178a13e0 ecx=dddddddd edx=0... | **The problem**
1. First chance exceptions means that the debugger is giving you, the person who is using the debugger, the first chance to debug the exception, before it throws it back at the program to handle the issue.
2. In this case the exception is "Access violation". This means that your program is trying to re... | If you are using MSVC and the Debug build configuration, `0xdddddddd` usually means that you are attempting to access freed memory. The debug CRT memory manager fills free memory with `0xdd`. | Strange program hang, what does this mean in debug? | [
"",
"c++",
"c",
"boost-asio",
"freeze",
""
] |
I come from a background of MoM. I think I understand ESB conceptually. However, I'm not too sure about the practical differences between the two when it comes to making a choice architecturally.
Here is what I want to know
1) Any good links online which can help me in this regard.
2) Can someone tell me where it ma... | Messaging tends to concentrate on the reliable exchange of messages around a network; using queues as a reliable load balancer and topics to implement publish and subscribe.
An ESB typically tends to add different features above and beyond messaging such as orchestration, routing, transformation and mediation.
I'd re... | I put MOM solutions and ESB solutions on two distinct planes.
I consider MOM a building block for ESB solutions. In fact, ESB solutions reach their own loose coupling and asynchronous communication capabilities, just using the paradigm offered by the specific MOM implementation.
Therefore, MOMs represent solutions fo... | Message Oriented Middleware (MoM) Vs. Enterprise Service Bus (ESB) | [
"",
"java",
"soa",
"messaging",
"esb",
"mom",
""
] |
I've got a few methods that should call `System.exit()` on certain inputs. Unfortunately, testing these cases causes JUnit to terminate! Putting the method calls in a new Thread doesn't seem to help, since `System.exit()` terminates the JVM, not just the current thread. Are there any common patterns for dealing with th... | Indeed, [Derkeiler.com](http://coding.derkeiler.com/Archive/Java/comp.lang.java.programmer/2008-04/msg02603.html) suggests:
> * Why `System.exit()` ?
>
> Instead of terminating with System.exit(whateverValue), why not throw an unchecked exception? In normal use it will drift all the way out to the JVM's last-ditch c... | The library [System Lambda](https://github.com/stefanbirkner/system-lambda/) has a method `catchSystemExit`.With this rule you are able to test code, that calls System.exit(...):
```
public class MyTest {
@Test
public void systemExitWithArbitraryStatusCode() {
SystemLambda.catchSystemExit(() -> {
... | How to test methods that call System.exit()? | [
"",
"java",
"multithreading",
"unit-testing",
"junit",
"testability",
""
] |
Is there any way to install Setuptools for Python 2.6 in Windows without having an exe installer?
There isn't one built at the moment, and the maintainer of Setuptools has stated that it will probably be a while before he'll get to it.
Does anyone know of a way to install it anyway? | First Option - Online Installation (i.e. remaining connected to the Internet during the entire installation process):
1. Download [setuptools-0.6c9.tar.gz](https://pypi.org/project/setuptools/0.6c9/)
2. Use [7-zip](http://www.7-zip.org/) to extract it to a folder(directory) outside your Windows Python installation fol... | You could download and run <http://peak.telecommunity.com/dist/ez_setup.py>. This will download and install setuptools.
[update]
This script no longer works - the version of setuptools the it downloads is not at the URI specified in ez\_setup.py -navigate to <http://pypi.python.org/packages/2.7/s/setuptools/> for the... | How do I set up Setuptools for Python 2.6 on Windows? | [
"",
"python",
"windows",
"setuptools",
""
] |
If you have a `java.io.InputStream` object, how should you process that object and produce a `String`?
---
Suppose I have an `InputStream` that contains text data, and I want to convert it to a `String`, so for example I can write that to a log file.
What is the easiest way to take the `InputStream` and convert it t... | A nice way to do this is using [Apache Commons](http://commons.apache.org/) `IOUtils` to copy the `InputStream` into a `StringWriter`... Something like
```
StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, encoding);
String theString = writer.toString();
```
or even
```
// NB: does not clos... | To summarize the other answers, I found 11 main ways to do this (see below). And I wrote some performance tests (see results below):
**Ways to convert an InputStream to a String:**
1. Using `IOUtils.toString` (Apache Utils)
```
String result = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
```
2. U... | How do I read / convert an InputStream into a String in Java? | [
"",
"java",
"string",
"io",
"stream",
"inputstream",
""
] |
How to solve "Must be MarshalByRefObject" in a good but multiple-inheritance amputated language like C#?
The problem is very simple, in several cases you just have to inherit from this class (infrastructure requirements).
It does not matter here really, which cases.
So, what do you do if you've already inherited from ... | In general you only want to make an object MarshalByRef if you're going to use it in a Remoting / WCF context. This is usually a special-enough case that it's not a pain.
Suppose you had a general type, and you wanted to derive from it and specialise it, and then remote the derived type - now you have a problem, becau... | It depends on how you need to get at it. Using a base class that derives from MarshalByRefObject might do it. Aggregation might do it. Without a more concrete example of what you need it's hard to say, but it's a rare case that multiple inheritance would be the only solution to a problem. | How to solve "Must be MarshalByRefObject" in a good but multiple-inheritance amputated language like C#? | [
"",
"c#",
"multiple-inheritance",
"marshalbyrefobject",
""
] |
I'm looking for your best solutions for creating a new message instance based on a pre-defined XSD schema to be used within a Biztalk orchestration.
Extra votes go to answers with clear & efficient examples or answers with quality referenced links. | What exactly are you looking for? Is it just creating a new message with a fixed content (like a sort of template)? Or based on something else? You really need to clarify the question and be more specific to get a proper answer.
If you're referring to just creating a message from scratch based with sort of hardcoded c... | There are several options when wanting to create a new instance of a message in a BizTalk orchestration.
I've described the three I usually end up using as well as adding some links at the bottom of the answer.
How to define which is the best method really depends - the XMLDocument method is in some regards the tidie... | What is the best way to create a new message within a Biztalk Orchestration? | [
"",
"c#",
"biztalk",
""
] |
I'm using the following code to try to read the results of a `df` command in Linux using `popen`.
```
#include <iostream> // file and std I/O functions
int main(int argc, char** argv) {
FILE* fp;
char * buffer;
long bufSize;
size_t ret_code;
fp = popen("df", "r");
if(fp == NULL) { // head off... | Why would `std::malloc()` fail?
The obvious reason is "because `std::ftell()` returned a negative signed number, which was then treated as a huge unsigned number".
According to [the documentation](http://en.cppreference.com/w/cpp/io/c/ftell), `std::ftell()` returns -1 on failure. One obvious reason it would fail is t... | You're making this all too hard. *popen(3)* returns a regular old `FILE *` for a standard pipe file, which is to say, newline terminated records. You can read it with very high efficiency by using *fgets(3)* like so in C:
```
#include <stdio.h>
char bfr[BUFSIZ] ;
FILE * fp;
// ...
if((fp=popen("/bin/df", "r")) ==NULL)... | How do I read the results of a system() call in C++? | [
"",
"c++",
"linux",
"operating-system",
"system-calls",
""
] |
I'm trying to make a program in Visual C# that has my one created class, and at application launch it creates an array of my class object, and this array of my object can be used all over the program. So any function, or a control's event can access the array of objects and their member variables.
I created my class as... | Your problem is that you are defining it within the main function, hence it will only exist inside the main function. you need to define it inside the class, not inside the function
```
public partial class Form1:Form
{
MyClass[] MyArrayObject; // declare it here and it will be available everywhere
public Form1()
{
... | Only static objects are available in all contexts. While your design lacks... er, just lacks in general, the way you could do this is to add a second, static class that maintains the array of your MyClass:
```
public static class MyClassManager
{
private MyClass[] _myclasses;
public MyClass[] MyClassArray
{
... | In Visual C# I cannot make my public class public | [
"",
"c#",
".net",
""
] |
I'm currently using `Win32ShellFolderManager2` and `ShellFolder.getLinkLocation` to resolve windows shortcuts in Java. Unfortunately, if the Java program is running as a service under Vista, `getLinkLocation`, this does not work. Specifically, I get an exception stating "Could not get shell folder ID list".
Searching ... | Added comments (some explanation as well as credit to each contributor so far),additional check on the file magic, a quick test to see if a given file might be a valid link (without reading all of the bytes), a fix to throw a ParseException with appropriate message instead of ArrayIndexOutOfBoundsException if the file ... | [Sam Brightman's solution](https://stackoverflow.com/a/352738/675721) is for local files only.
I added support for Network files:
* [Windows shortcut (.lnk) parser in Java?](https://stackoverflow.com/questions/309495/windows-shortcut-lnk-parser-in-java)
* <http://code.google.com/p/8bits/downloads/detail?name=The_Windo... | Windows shortcut (.lnk) parser in Java? | [
"",
"java",
"windows",
"windows-vista",
"shortcut",
"lnk",
""
] |
How can I initialize a const / static array of structs as clearly as possible?
```
class SomeClass
{
struct MyStruct
{
public string label;
public int id;
};
const MyStruct[] MyArray = {
{"a", 1}
{"b", 5}
{"q", 29}
};
};
``` | Firstly, do you *really* have to have a mutable struct? They're almost always a bad idea. Likewise public fields. There are some very occasional contexts in which they're reasonable (usually both parts together, as with `ValueTuple`) but they're pretty rare in my experience.
Other than that, I'd just create a construc... | Are you using C# 3.0? You can use object initializers like so:
```
static MyStruct[] myArray =
new MyStruct[]{
new MyStruct() { id = 1, label = "1" },
new MyStruct() { id = 2, label = "2" },
new MyStruct() { id = 3, label = "3" }
};
``` | Initializing an Array of Structs in C# | [
"",
"c#",
"arrays",
"struct",
""
] |
How to declare a static dictionary object inside a static class? I tried
```
public static class ErrorCode
{
public const IDictionary<string, string> ErrorCodeDic = new Dictionary<string, string>()
{
{ "1", "User name or password problem" }
};
}
```
But the compiler complains that
> A const ... | If you want to declare the dictionary once and never change it then declare it as readonly:
```
private static readonly Dictionary<string, string> ErrorCodes
= new Dictionary<string, string>
{
{ "1", "Error One" },
{ "2", "Error Two" }
};
```
If you want to dictionary items to be readonly (not just the re... | The correct syntax ( as tested in VS 2008 SP1), is this:
```
public static class ErrorCode
{
public static IDictionary<string, string> ErrorCodeDic;
static ErrorCode()
{
ErrorCodeDic = new Dictionary<string, string>()
{ {"1", "User name or password problem"} };
}
}
``` | Declare a dictionary inside a static class | [
"",
"c#",
".net",
"dictionary",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.