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 standard submit button).
**Is there some way to get the dynamically added fields posted/recognized as a part of the form?**
```
<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();">Add option</a>
<script>
var optionNumber = 3; //The first option to be added is number 3
function addOption() {
var theForm = document.getElementById("myForm");
var newOption = document.createElement("input");
newOption.name = "poll[option"+optionNumber+"]"; // poll[optionX]
newOption.type = "text";
theForm.appendChild(newOption);
optionNumber++;
}
</script>
```
|
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();">Add option</a>
<script>
var optionNumber = 3; //The first option to be added is number 3
function addOption() {
var theForm = document.getElementById("myForm");
var newOption = document.createElement("input");
newOption.name = "poll[option"+optionNumber+"]"; // poll[optionX]
newOption.type = "text";
theForm.appendChild(newOption);
optionNumber++;
}
</script>
</body>
</html>
```
click Add Option twice and you get
Array ( [poll] => Array ( [question] => [option1] => [option2] => [option3] => [option4] => ) )
|
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, with malformed html, but you can still break things, like this, by having not having properly formatted html. Maybe I should start using mod\_tidy!
|
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/javascript/jsmin.py.txt) for CSS. A single script with no dependencies.
Any ideas?
|
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 ) # preserve IE<6 comment hack
css = re.sub( r'/\*[\s\S]*?\*/', "", css )
css = css.replace( "$$HACK1$$", '/**/' ) # preserve IE<6 comment hack
# url() doesn't need quotes
css = re.sub( r'url\((["\'])([^)]*)\1\)', r'url(\2)', css )
# spaces may be safely collapsed as generated content will collapse them anyway
css = re.sub( r'\s+', ' ', css )
# shorten collapsable colors: #aabbcc to #abc
css = re.sub( r'#([0-9a-f])\1([0-9a-f])\2([0-9a-f])\3(\s|;)', r'#\1\2\3\4', css )
# fragment values can loose zeros
css = re.sub( r':\s*0(\.\d+([cm]m|e[mx]|in|p[ctx]))\s*;', r':\1;', css )
for rule in re.findall( r'([^{]+){([^}]*)}', css ):
# we don't need spaces around operators
selectors = [re.sub( r'(?<=[\[\(>+=])\s+|\s+(?=[=~^$*|>+\]\)])', r'', selector.strip() ) for selector in rule[0].split( ',' )]
# order is important, but we still want to discard repetitions
properties = {}
porder = []
for prop in re.findall( '(.*?):(.*?)(;|$)', rule[1] ):
key = prop[0].strip().lower()
if key not in porder: porder.append( key )
properties[ key ] = prop[1].strip()
# output rule if it contains any declarations
if properties:
print "%s{%s}" % ( ','.join( selectors ), ''.join(['%s:%s;' % (key, properties[key]) for key in porder])[:-1] )
```
I believe this to work, and output it tests fine on recent Safari, Opera, and Firefox. It will break CSS hacks other than the underscore & /\*\*/ hacks! Do not use a minifier if you have a lot of hacks going on (or put them in a separate file).
Any tips on my python appreciated. Please be gentle though, it's my first time. :-)
|
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 client system). If someone extracts it or sniffs the network traffic he will have access to my email account. Maybe the second threat could be eliminated using a secure connection. However, it is still possible to get the password out of the application regardless if it is obfuscated or not.
So is there are 'secure' concept enabling me to send e-mail messages out of my program, which runs on the client pc without the need to store a password in accessible form and not requirering a special web service?
|
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 server. If your program can send emails, so can the user with another program. (the same goes for a web service.) What you can do is use an open smtp server (smtp relay) but that is just asking for trouble.
|
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.
I haven't used Java in years and I'm getting back up to speed on it but surely Java has a way to easily do this without delving deep into the Reflection APIs?
Thanks in advance for answers. I have searched both here and other places but the keywords involved are so generic that even though I'm sure this has a simple answer, googling for it is hard.
|
```
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 opens the URL but it screws up the entire layout of the browser.
What's the correct way to do this?
|
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 returns tab/current/window based on the users preferences and modifiers.
```
openUILinkIn(url, whereToOpenLink(event));
```
Thus I use:
```
<menuitem label="Visit homepage"
oncommand="openUILinkIn('http://example.com/', whereToOpenLink(event))"/>
```
If you aren't in the context of a menuitem you might want to check out another built-in XBL that adds linking and opening HREFs for a label:
```
<label value="google" class="text-link" href="http://google.com/" />
```
|
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 generate a WSDL that I can give our web developers. I might add that the stored procedure only returns one value.
Here's some example code:
```
#!/usr/bin/python
import SOAPpy
import MySQLdb
def getNEXTVAL():
cursor = db.cursor()
cursor.execute( "CALL my_stored_procedure()" ) # Returns a number
result=cursor.fetchall()
for record in result:
return record[0]
db=MySQLdb.connect(host="localhost", user="myuser", passwd="********", db="testing")
server = SOAPpy.SOAPServer(("10.1.22.29", 8080))
server.registerFunction(getNEXTVAL)
server.serve_forever()
```
I want to generate a WSDL that I can give to the web folks, and I'm wondering if it's possible to have SOAPpy just generate one for me. Is this possible?
|
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 for my client and server code. I wouldn't describe the experience as pleasant, but the application did work.
|
> 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 test and if so what is the justification for it?
|
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 this automatically in VS by using a separate project/assembly. However you can have it in the same assembly, but then just not compile that code if you're using nant or msbuild. Bit messy though, keep things tidy, use a separate assembly :)
|
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,
to_char(ad.origin_date,'YYYY') AS origin_date
FROM archivalie AS a
LEFT JOIN archivalie_dating AS ad ON a.id = ad.archivalie_id
LEFT JOIN internal_project AS ip ON a.internal_project_id = ip.id
LEFT JOIN origin AS o ON a.origin_id = o.id
WHERE a.id = $archivalie_id";
$result = pg_query($db, $query);
while ($row = pg_fetch_object($result))
{
$no_data = '<span class="no-data">No data</span>';
$internal_project = ($row->internal_project != '') ? $row->internal_project : $no_data;
$incoming_date = ($row->incoming_date != '') ? $row->incoming_date : $no_data;
$origin = ($row->origin != '') ? $row->origin : $no_data;
}
```
|
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 '\_MYPROJECT\_NODATA' so you can easily change the way your no data label looks or implement internationalisation.
You would then use
```
define('_MYPROJECT_NODATA', '<span class="no-data">No data</span>');
```
|
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 me),
* number of methods per class? (this project has 6.54 methods per class...
* number of lines per method? (this project has about 7 lines per method (seems pretty good to me, maybe a bit low))
I should note that this question is only dealing with volumetry. I have a bunch of reports from quality tools (checkstyle, jdepend, cpd, pmd, ncss) that give me more vision about code redundancy, classes usage, bugs, etc.
|
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 classes function
correctly and efficiently?
Surely other than memory usage, it doesn't matter whether the method is large or not? the other thing to look for in very protracted methods is whether the stack trace is going to be bigger than adding that functionality to a parent method. I'd be wary of measuring a projects success based on the lines of code.
|
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, the monospace font looks really terrible in chrome, whats up with that?
|
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(kIMEventAlert, text.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
}
```
|
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 the order the initializers are listed). So parent classes first, then members. Compilers sometime helpfully warn you if you don't list the initializers in the order they will actually be executed. So provided you get that right, the rule is "don't use anything you haven't initialized". This code uses alertText before it is initialized.
|
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<ICloneable>();
List<ICloneable> newList = new List<ICloneable>(oldList.Count);
oldList.ForEach((item) =>
{
newList.Add((ICloneable)item.Clone());
});
```
Obviously, replace `ICloneable` in the above generics and cast with whatever your element type is that implements `ICloneable`.
If your element type doesn't support `ICloneable` but does have a copy-constructor, you could do this instead:
```
List<YourType> oldList = new List<YourType>();
List<YourType> newList = new List<YourType>(oldList.Count);
oldList.ForEach((item)=>
{
newList.Add(new YourType(item));
});
```
Personally, I would avoid `ICloneable` because of the need to guarantee a deep copy of all members. Instead, I'd suggest the copy-constructor or a factory method like `YourType.CopyFrom(YourType itemToCopy)` that returns a new instance of `YourType`.
Any of these options could be wrapped by a method (extension or otherwise).
|
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";
break;
case Type.B:
string variable = "y";
break;
}
```
However, per the logic, the initial declaration should not be hit if the type is `Type.B`. Do all variables within a switch statement exist in a single scope, and are they created/allocated before any logic is processed?
|
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 variable */
}
break;
}
```
|
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
```
namespace {
const std::vector<const T> v(??);
}
```
since v won't be used outside of this compilation unit.
|
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::assign; // bring 'operator+=()' into scope
vector<int> v;
v += 1,2,3,4,5;
```
|
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 template to initialise from some other kind of container or an array. If an array, then that could have been defined with an initialisation list.
Something like this is hopefully close to what you want:
```
const T ra[3] = {t1, t2, t3};
const vector<const T> v(ra, ra+3);
```
If you're asking how to pass a const vector into a function which takes a vector then the answer is either:
* you can't, because the function might alter the vector and your object/reference is const. Make a non-const copy of the original, and pass that in.
or
* use `const_cast` to remove the constness in order to pass it into a function which takes a non-const vector but which you just so happen to know will not modify the vector.
The latter is one of those things which will, quite rightly, cause anyone who sees it to make comments about goggles, and the fact that they do nothing. It's exactly what `const_cast` is for, but there's a reasonably strong argument that says if you need `const_cast`, you have already lost.
Doing both of those things (creating a const vector from a non-const one with the copy constructor, and then casting away constness) is definitely wrong - you should have just used a non-const vector. So pick at most one of these to do...
[**Edit:** just noticed that you're talking about a difference between `vector<T>` and `const vector<const T>`. Unfortunately in the STL, `vector<const T>` and `vector<T>` are completely unrelated types, and the only way to convert between them is by copying. This is a difference between vectors and arrays - a `T**` can be silently and safely converted to `const T *const *`]
|
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 video_*
{'input_filename': 'video_1.wmv'}
```
there are video\_[1-6].wmv in the current folder.
Question is why video\_\* become video\_1.wmv. What i'm doing wrong?
|
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` only attaches to the immediate next parameter.
That said, your best bet might to be just read your input filenames from `args`, rather than using `options.input`.
|
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 method of the static class, and everything works fine.
Is this a .NET defect, or is there some obscure generic rule I'm breaking here?
For the sake of completeness, I've included the method which fails, and the method which passes. Note that this uses a number of other classes from my own library (eg GridUtils), and these classes are not explained here. I don't think the actual meaning matters: the question is why the runtime crashes before the method even starts.
(I'm programming with Visual Studio 2005, so maybe this has gone away in Visual Studio 2008.)
**This throws an exception before the first line is invoked:**
```
private delegate void PROG_Delegate<TGridLine>(DataGridView dgv, IEnumerable<TGridLine> gridLines, string[] columns);
public static void PopulateReadOnlyGrid<TGridLine>(DataGridView dgv, IEnumerable<TGridLine> gridLines, string[] columns)
{
if (dgv.InvokeRequired)
{
dgv.BeginInvoke
(
new PROG_Delegate<TGridLine>(PopulateReadOnlyGrid<TGridLine>),
new object[] { dgv, gridLines, columns }
);
return;
}
GridUtils.StatePreserver statePreserver = new GridUtils.StatePreserver(dgv);
System.Data.DataTable dt = CollectionHelper.ConvertToDataTable<TGridLine>((gridLines));
dgv.DataSource = dt;
dgv.DataMember = "";
dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
GridUtils.OrderColumns<TGridLine>(dgv, columns);
statePreserver.RestoreState();
dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;
}
```
**This works fine:**
```
public static class Populator<TGridLine>
{
private delegate void PROG_Delegate(DataGridView dgv, IEnumerable<TGridLine> gridLines, string[] columns);
public static void PopulateReadOnlyGrid(DataGridView dgv, IEnumerable<TGridLine> gridLines, string[] columns)
{
if (dgv.InvokeRequired)
{
dgv.BeginInvoke
(
new PROG_Delegate(PopulateReadOnlyGrid),
new object[] { dgv, gridLines, columns }
);
return;
}
GridUtils.StatePreserver statePreserver = new GridUtils.StatePreserver(dgv);
System.Data.DataTable dt = CollectionHelper.ConvertToDataTable<TGridLine>((gridLines));
dgv.DataSource = dt;
dgv.DataMember = "";
dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
GridUtils.OrderColumns<TGridLine>(dgv, columns);
statePreserver.RestoreState();
dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;
}
}
```
|
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 form (after commenting out your GridUtils stuff). I even call the method both from the gui thread and the non-gui thread. I tried it in 3.5 and 2.0. Works fine.... (!?)
Try this code:
```
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using System.Threading;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private delegate void PROG_Delegate<TGridLine>(Control dgv, IEnumerable<TGridLine> gridLines, string[] columns);
public static void PopulateReadOnlyGrid<TGridLine>(Control dgv, IEnumerable<TGridLine> gridLines, string[] columns)
{
if (dgv.InvokeRequired)
{
dgv.BeginInvoke
(
new PROG_Delegate<TGridLine>(PopulateReadOnlyGrid<TGridLine>),
new object[] { dgv, gridLines, columns }
);
return;
}
MessageBox.Show("hi");
//GridUtils.StatePreserver statePreserver = new GridUtils.StatePreserver(dgv);
//System.Data.DataTable dt = CollectionHelper.ConvertToDataTable<TGridLine>((gridLines));
//dgv.DataSource = dt;
//dgv.DataMember = "";
//dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
//GridUtils.OrderColumns<TGridLine>(dgv, columns);
//statePreserver.RestoreState();
//dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;
}
private void button1_Click(object sender, EventArgs e)
{
PopulateReadOnlyGrid(this, new int[] { 1, 2, 3 }, new string[] { "a" });
ThreadPool.QueueUserWorkItem(new WaitCallback((a) =>
{
PopulateReadOnlyGrid(this, new int[] { 1, 2, 3 }, new string[] { "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 everywhere. So now where I had two lines of space between some code, it now has 3. Where I had a bunch of lines sticking together because they were part of the same for loop or such, they're all scattered around now and there's no way to distinguish them.
Is there any program/utility to fix this?
|
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 = "Computer1"
ip = "0.0.0.0"
screenSize = 17
def Computer(compName, compIp, compScreenSize):
name = compName
ip = compIp
screenSize = compScreenSize
printStats()
return
def Computer():
printStats()
return
def printStats():
print "Computer Statistics: --------------------------------"
print "Name:" + name
print "IP:" + ip
print "ScreenSize:" , screenSize // cannot concatenate 'str' and 'tuple' objects
print "-----------------------------------------------------"
return
comp1 = Computer()
comp2 = Computer("The best computer in the world", "27.1.0.128",22)
```
Any thoughts?
|
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 make it a "new-style" class.
There are reasons for this that are a bit complex to explain."""
# everything down here is a static variable, unlike in Java or C# where
# declarations here are for what members a class has. All instance
# variables in Python are dynamic, unless you specifically tell Python
# otherwise.
defaultName = "belinda"
defaultRes = (1024, 768)
defaultIP = "192.168.5.307"
def __init__(self, name=defaultName, resolution=defaultRes, ip=defaultIP):
"""Constructors in Python are called __init__. Methods with names
like __something__ often have special significance to the Python
interpreter.
The first argument to any class method is a reference to the current
object, called "self" by convention.
You can use default function arguments instead of function
overloading."""
self.name = name
self.resolution = resolution
self.ip = ip
# and so on
def printStats(self):
"""You could instead use a __str__(self, ...) function to return this
string. Then you could simply do "print(str(computer))" if you wanted
to."""
print "Computer Statistics: --------------------------------"
print "Name:" + self.name
print "IP:" + self.ip
print "ScreenSize:" , self.resolution //cannot concatenate 'str' and 'tuple' objects
print "-----------------------------------------------------"
```
|
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
self.ip = compIp
self.screenSize = compScreenSize
self.printStats()
def printStats(self):
print "Computer Statistics: --------------------------------"
print "Name:", self.name
print "IP:", self.ip
print "ScreenSize:", self.screenSize
print "-----------------------------------------------------"
comp1 = Computer()
comp2 = Computer("The best computer in the world", "27.1.0.128",22)
```
|
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 rollback never occurred. So essentially there are gaps in the identity sequence. Is there any way to have the `Rollback()` method reclaim the missing identity?
Am I not approaching this the right way?
|
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 auto-number field for the ID column:
```
User 1
------------
begin transaction
insert into A ...
insert into B ...
update C ...
insert into D ...
commit
User 2
-----------
begin transaction
insert into A ...
insert into B ...
commit
```
If user 2's transaction starts a millisecond after user 1's, then their insert into table A would have to wait for user 1's entire transaction to complete just to see if the auto-number from the first insert into A was used.
This is a feature, not a bug. I would recommend using another scheme to generate auto-numbers if you need them to be tightly sequential.
|
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 performance consequences of blocking other inserts).
|
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
FROM
table_two
WHERE
some_id = '<id>'
UNION ALL
SELECT
info_field, data_field
FROM
table_three
WHERE
some_id = '<id>'
UNION ALL
...
```
Given that I'm no SP expert I've been unable to figure out a good solution to loop through all the involved tables (12 aprox.).
Any ideas would be helpful. Thanks much!
|
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_field, data_field
FROM table_three
...
```
The users could then type:
```
SELECT info_field, data_field
FROM info_and_data
WHERE some_id = <id>
```
|
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 different views that show or hide specific columns and grant access to those views to different users/roles.
If you don't know in advance which combination of columns a user may be allowed to see, then you could use dynamic sql: You assemble the SQL statment in the stored procedure based on the access privileges of your user (look up from some other table you create to hold this info), meaning that you only include the proper columns in the SELECT portion of your statement. See this [document from Orace](http://download-uk.oracle.com/docs/cd/B10501_01/appdev.920/a96590/adg09dyn.htm)
for more info.
If you are using Oracle 10g, then you may find this [Oracle article](http://www.oracle.com/technology/pub/articles/10gdba/week14_10gdba.html) interesting. It introduces the topic of the Virtual Private Database, or VPD for short, where you can hide certain rows, or columns or even individual *column values* depending on who is accessing a table.
|
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 <= 'Z'; c4++)
{
yield return "" + c1 + c2 + c3 + c4;
}
}
}
}
}
```
if the length is a parameter, this recursive solution would handle it:
```
public static IEnumerable<String> GetWords(Int32 length)
{
if (length <= 0)
yield break;
for (Char c = 'A'; c <= 'Z'; c++)
{
if (length > 1)
{
foreach (String restWord in GetWords(length - 1))
yield return c + restWord;
}
else
yield return "" + c;
}
}
```
|
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 letters
from four in letters
orderby one, two, three, four
select new string(new[] { one, two, three, four });
```
'sequence' will now be an IQueryable that contains AAAA to ZZZZ.
Edit:
Ok, so it was bugging me that it should be possible to make a sequence of configurable length with a configurable alphabet using LINQ. So here it is. Again, completely pointless but it was bugging me.
```
public void Nonsense()
{
var letters = new[]{"A","B","C","D","E","F",
"G","H","I","J","K","L",
"M","N","O","P","Q","R","S",
"T","U","V","W","X","Y","Z"};
foreach (var val in Sequence(letters, 4))
Console.WriteLine(val);
}
private IQueryable<string> Sequence(string[] alphabet, int size)
{
// create the first level
var sequence = alphabet.AsQueryable();
// add each subsequent level
for (var i = 1; i < size; i++)
sequence = AddLevel(sequence, alphabet);
return from value in sequence
orderby value
select value;
}
private IQueryable<string> AddLevel(IQueryable<string> current, string[] characters)
{
return from one in current
from character in characters
select one + character;
}
```
The call to the Sequence method produces the same AAAA to ZZZZ list as before but now you can change the dictionary used and how long the produced words will be.
|
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 dropdownlist.
I think the problem lies here, that
I'm using ItemCreatedCommand to
populate it - but the strange things
is that if I choose the color "green",
the page will autopostback, and I will
see that the dropdown is still on the
color green, but when trying to use
it's SelectedIndex, I always get 0...
```
protected void DataListProducts_ItemCreatedCommand(object
source, DataListItemEventArgs e)
var itemId = (String)DataListProducts.DataKeys[e.Item.ItemIndex];
var item = itemBLL.GetFullItem(itemId);
var DropDownListColor = (DropDownList)e.Item.FindControl("DropDownListColor");
//Also tried with :
//if(!isPostBack) {
DropDownListColor.DataSource = item.ColorList;
DropDownList.Color.Databind();
// } End !isPostBack)
Label1.test = DropDownListColor.SelectedIndex.toString();
// <- THIS IS ALWAYS 0! *grr*
```
I've narrowed down the code a bit for
viewing, but still you can see what
I'm trying to do :) The reason for
why I'm doing this, and not declaring
the datasource for the colors directly
i aspx-page, is that I need to run a
test if(showColors), but I do not want
to clutter up the html-page with code
that I feel should be in the code
behind-file.
EDIT: After trying to alter
SelectedIndexChange - I'm having a
"logical" confusion in my head now -
how am I to alter elements inside the
datalist? Since, as far as I know - I
do not have any way to check which of
the items in the datalist this
particular dropdownlist belongs to...
Or? I'm going to try out a few ways
and see what I end up with ;) But do
please post your thoughts on this
question :)
**SOLUTION:**
Either bubble the event to ItemCommand, or Handle the event, get the senders parent(which is a datalistItem and manipulate elements in there.
```
protected void DropDownListColor_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList dropDownListColor = (DropDownList)sender;
DataListItem dataListItem = (DataListItem)dropDownListColor.Parent;
var item = items[dataListItem.ItemIndex];
var color = item.ItemColor[dropDownListColor.SelectedIndex];
var LabelPrice = (Label)dataListItem.FindControl("LabelPrice");
LabelPrice.Text = color.Price;
}
```
|
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 on the first element of each pair?
I know i can do it manually, providing a hand-made function object that will be a wrapper around the standard container iterator, deferencing it to the first member of the pair intend of the pair itself,but I think there is also a clever one-liner to do it for me. What would it be?
|
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>
int main() {
typedef std::map<std::string, int>::value_type value_type;
std::map<std::string, int> a;
a["one"] = 1;
a["two"] = 2;
// returns the second element
boost::function<int(value_type&)> f = boost::bind(&value_type::second, _1);
std::copy(boost::make_transform_iterator(a.begin(), f),
boost::make_transform_iterator(a.end(), f),
std::ostream_iterator<int>(std::cout, " "));
}
```
It's printing `"1 2 "` to the standard output.
|
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 rather crude and needs some tweaking of the generated `.java` and `.hbm.xml` files.
For example (based on what my script does), having a table `statement`:
```
Object_Name Type_Name Base_Type Nulls Identity
------------ --------- --------- ----- --------
id id_int int no yes
id_user id_tiny tinyint no no
value float float no no
```
I would like the program to autogenerate the following java:
```
package com.some.company.schema;
import java.io.Serializable;
public class Statement implements Serializable {
private static final long serialVersionUID = 1227171190L;
private Integer id;
private User user;
private Float value;
public void setId(Integer id){
this.id = id;
}
public Integer getId(){
return this.id;
}
public void setUser(User user){
this.user = user;
}
public User getUser(){
return this.user;
}
public void setValue(Float value){
this.value = value;
}
public Float getValue(){
return this.value;
}
}
```
And the corresponding Hibernate mapping file:
```
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.some.company.schema.Statement" table="statement">
<id name="id" column="id">
<generator class="native" />
</id>
<many-to-one name="user" class="com.some.company.schema.User" column="id_user" not-null="true" />
<property name="value" column="value" not-null="true" />
</class>
</hibernate-mapping>
```
|
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
```
Does SQLite support SCOPE\_IDENTITY?
If so, how do I use it?
If not, what are my (preferably "thread-safe") alternatives?
|
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 performance but without having open connection for too long. Is there a best practice here?
|
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, asynchronous fetches, or denormalization. There's really no general use case I can think of for keeping a DB connecton around.
|
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 ) . Why is that ?
|
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 necessarily wrong with that.
In fact, one would argue that beans and entity beans are essentially that - data containers with getters and setters.
I have seen certain sources (e.g., the book "clean code") arguing that one should avoid methods with multiple parameters and instead pass them as a single object with getters and setters. This is also closer to the "smalltalk model" of named parameters where order does not matter.
So I think that when used appropriately, your design makes sense.
|
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 and setters) *may* represent a real-world thing.
However, most real-world things have rules, constraints, behaviors, and basic verbs in which they engage. A struct-like class is rarely a good match for a real-world thing, it's usually some technical thing. That makes it less than ideal OO design.
**Multiple returns from a method**
While Python has this, Java doesn't. Multiple return values isn't an OO question, *per se*. It's a question of working through the language limitations.
Multiple return values may mean that an object has changed state. Perhaps one method changes the state and some group of getters return the values stemming from this state change.
|
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 frameworks](http://www-128.ibm.com/developerworks/java/library/os-lightweight9/)
|
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():
print "pass"
```
Edit: I realize this is basically a specialization of real continuations, but it should be sufficient for most purposes. Use `yield` to return the continuation and the `.next()` message on the generator (returned by just calling `loop()`) to reenter.
|
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 example of what I am trying to do:
I receive a string from a socket and place it in an unsigned char array. I can ignore the first byte and then the next 2 bytes should be converted to an unsigned char. This will be on windows only so there are no Big/Little Endian issues (that I am aware of).
Here is what I have now (not working obviously):
```
//packetBuffer is an unsigned char array containing the string "123456789" for testing
//I need to convert bytes 2 and 3 into the short, 2 being the most significant byte
//so I would expect to get 515 (2*256 + 3) instead all the code I have tried gives me
//either errors or 2 (only converting one byte
unsigned short myShort;
myShort = static_cast<unsigned_short>(packetBuffer[1])
```
|
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]));
```
Now, you can dereference p and get the short value. But the problem with this approach is that you cast from unsigned char\*, to void\* and then to some different type. The Standard doesn't guarantee the address remains the same (and in addition, dereferencing that pointer would be undefined behavior). A better approach is to use bit-shifting, which will always work:
```
unsigned short p = (packetBuffer[1] << 8) | packetBuffer[2];
```
|
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 significantly slower than an aligned access). If, however, this code will run on a non-x86 (you don't mention the target platform, so I'm assuming x86 desktop Windows), then doing this will cause a processor data abort and you'll have to manually copy the data to an aligned address before trying to cast it.
In short, if you're going to be doing this access a lot, you might look at making adjustments to the code so as not to have unaligned reads and you'll see a perfromance benefit.
|
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 picking the correct data structures algorithmically has much higher performance gains that micro-optimization due to more efficient compiled code layouts, etc. If you search in a list in O(n) instead of in a dict in O(1), micro-optimizations won't save you.
|
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 these kinds of micro-optimizations until you've profiled your code and identified a section of code that is a bottleneck.
|
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 Studio and .Net. Then, an **E-mail** class is created that depends on **Utilities**. Instead of adding both projects to a single solution, a new solution is created and a reference to *Utilities.dll* is added. Then, some time later, someone decides that they want the **Utilities** class to send an e-mail and adds a reference to *Email.dll*. Visual Studio is perfectly happy to let you do this, but now the source won't compile as-is without one of the binaries.
At my place of work it is standard procedure to copy-and-paste binaries when doing development and then only building the projects you're working on. This has led to at least one circular reference in the codebase that has gone unnoticed for over 3 years.
This seems like a very bad practice to me because there is no way to build either project from source without having the DLLs first. That argument falls a little flat to the "practical" people I work with since it seems highly unlikely that we will lose all copies of our binaries simultaneously. The binaries aren't stored in version control at any point, which only makes me more worried.
This seems like a situation that should be avoided, but not a situation that poses any appreciable threat. **Are circular references between projects really a big deal or am I blowing it out of proportion?**
|
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 all those dependencies was so complicated that we wasted a ton of time trying (unsuccessfully, I might add) to set maven projects to automatically fetch all the correct libraries (and the correct versions) for all those little micro-projects.
The funny thing (to me) was that it was really only one project, and it wasn't even something we distributed to the outside world. It was a hosted application, with a web front-end, running on a single server cluster.
Sheesh.
Another side-effect of the architecture was that the same kinds of functionality got duplicated over and over again (not always with the same algorithms, or results, for that matter) in several different projects. I think part of the reason was because people didn't want to introduce a new dependency on an entire sub-project just to get access to a few of its classes. But I think another reason was the people just didn't know what code existed where, and rather than go to the trouble of finding the code they wanted to reuse, they'd just rewrite it in their own project.
Of course, modularity is generally a good thing.
But like all good things, it can be taken to ridiculous extremes.
My advice is to find those circular dependencies and merge the projects into bigger chunks, since the current project breakdown probably represents a false modularity. Better to divide your big project into a few well-separated modules than to have a zillion pseudo-modules creating artificial boundaries between logically-coupled classes.
|
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);
}
catch (XPathException)
{
}
```
|
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 tried putting
```
App::import('Component', 'Email');
```
at the top, to no avail. The error I get is:
> Fatal error: Call to undefined method stdClass::send() in E:\xampp\htdocs8080\app\models\debug.php on line 23
Any ideas?
I'm running CakePHP 1.2
|
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.com';
$this->Email->from = 'MyName <noreply@domain.com>';
$this->Email->template = $template;
$this->Email->sendAs = 'text'; //Send as 'html', 'text' or 'both' (default is 'text')
$this->Email->send();
}
```
Then use it from ANY controller like this:
```
$this->_sendMail($this->data['User']['email'],'Thanks for registering!','register');
```
And don't forget to place
```
var $components = array('Email');
```
in controllers, in which you 're using \_sendMail function.
|
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 email templates and layouts.
With a method like this in your model
```
function sendEmail(&$controller) {
App::import('Component', 'Email');
$email = new EmailComponent();
$email->startup($controller);
}
```
You can use it in your Controller like this:
$this->Model->sendEmail($this);
(omit the & in the method signature if you're on PHP5)
|
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

|
We've successfully used the following approach in the past...
```
SELECT [p].ProductID,
[p].Name,
MAX(CASE [m].MetaKey
WHEN 'A'
THEN [m].MetaValue
END) AS A,
MAX(CASE [m].MetaKey
WHEN 'B'
THEN [m].MetaValue
END) AS B,
MAX(CASE [m].MetaKey
WHEN 'C'
THEN [m].MetaValue
END) AS C
FROM Products [p]
INNER JOIN ProductMeta [m]
ON [p].ProductId = [m].ProductId
GROUP BY [p].ProductID,
[p].Name
```
It can also be useful transposing aggregations with the use of...
```
SUM(CASE x WHEN 'y' THEN yVal ELSE 0 END) AS SUMYVal
```
**EDIT**
Also worth noting this is using ANSI standard SQL and so it will work across platforms :)
|
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( Case When PM.MetaKey = 'C' Then PM.MetaValue End ) As C
From Products As P
Join ProductMeta As PM
On PM.ProductId = P.ProductId
Group By P.ProductId, P.Name
```
You *must* use a Group By or you will get a staggered result. If you are using a Group By, you must wrap each column that is not in the Group By clause in an aggregate function (or a subquery).
|
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 RandomLetter()
{
return RandomChar("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
}
public static char RandomStringInSpecialFormat()
{
char[] text = new char[6];
char[0] = RandomLetter();
char[1] = RandomDigit();
char[2] = RandomLetter();
char[3] = RandomDigit();
char[4] = RandomLetter();
char[5] = RandomDigit();
return new string(text);
}
```
(You could use a 3-iteration loop in RandomStringInSpecialFormat, but it doesn't have much benefit.)
If you need it to be thread-safe, you'll need some way of making sure you don't access the Random from multiple threads at the same time. The simplest way to do this (in my view) is to use [StaticRandom](http://www.yoda.arachsys.com/csharp/miscutil/usage/staticrandom.html) from [MiscUtil](http://pobox.com/~skeet/csharp/miscutil).
|
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 letter you need to call `RandomNumber(65,90);` and for the number you call : `RandomNumber(1,9);` You just need to concatenate.
Than you call these methods to create your string, Hope this help you.
## Update
You should put the random object in your class... it was just to show you how to do it. You still need to work a little but I think it's a good start to show you how to manipulate char from ascii.
|
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 Press** Problem no longer occurs. Chrome appears to have patched the error.
|
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 a sub-folder `http://host/X/` the variable `{{ R }}` would be `/X/` (or `http://host/X/`).
It seems painfully simple, but I can't find an answer. :) Thank you!
|
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 versions of Django require quotation marks around the name of the view:
```
<a href="{% url 'index' %}">...
```
This note in the Django Book has some tips about deploying your applications to a subdirectory:
<http://www.djangobook.com/en/1.0/chapter20/#cn43>
|
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 for future reference: what does `functools.wraps` do, exactly?
|
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(x):
"""does some math"""
return x + x * x
```
it's exactly the same as saying
```
def f(x):
"""does some math"""
return x + x * x
f = logged(f)
```
and your function `f` is replaced with the function `with_logging`. Unfortunately, this means that if you then say
```
print(f.__name__)
```
it will print `with_logging` because that's the name of your new function. In fact, if you look at the docstring for `f`, it will be blank because `with_logging` has no docstring, and so the docstring you wrote won't be there anymore. Also, if you look at the pydoc result for that function, it won't be listed as taking one argument `x`; instead it'll be listed as taking `*args` and `**kwargs` because that's what with\_logging takes.
If using a decorator always meant losing this information about a function, it would be a serious problem. That's why we have `functools.wraps`. This takes a function used in a decorator and adds the functionality of copying over the function name, docstring, arguments list, etc. And since `wraps` is itself a decorator, the following code does the correct thing:
```
from functools import wraps
def logged(func):
@wraps(func)
def with_logging(*args, **kwargs):
print(func.__name__ + " was called")
return func(*args, **kwargs)
return with_logging
@logged
def f(x):
"""does some math"""
return x + x * x
print(f.__name__) # prints 'f'
print(f.__doc__) # prints 'does some math'
```
|
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 can see it in the [functools source](https://github.com/python/cpython/blob/master/Lib/functools.py).
* it updates the `__dict__` of `g` with all elements from `f.__dict__`. (see `WRAPPER_UPDATES` in the source)
* it sets a new `__wrapped__=f` attribute on `g`
The consequence is that `g` appears as having the same name, docstring, module name, and signature than `f`. The only problem is that concerning the signature this is not actually true: it is just that `inspect.signature` follows wrapper chains by default. You can check it by using `inspect.signature(g, follow_wrapped=False)` as explained in the [doc](https://docs.python.org/3/library/inspect.html#inspect.signature). This has annoying consequences:
* the wrapper code will execute even when the provided arguments are invalid.
* the wrapper code can not easily access an argument using its name, from the received \*args, \*\*kwargs. Indeed one would have to handle all cases (positional, keyword, default) and therefore to use something like `Signature.bind()`.
Now there is a bit of confusion between `functools.wraps` and decorators, because a very frequent use case for developing decorators is to wrap functions. But both are completely independent concepts. If you're interested in understanding the difference, I implemented helper libraries for both: [decopatch](https://smarie.github.io/python-decopatch/) to write decorators easily, and [makefun](https://smarie.github.io/python-makefun/) to provide a signature-preserving replacement for `@wraps`. Note that `makefun` relies on the same proven trick than the famous `decorator` library.
|
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 capture deletion by other editor windows and notifying the user ("Item has been deleted in another editor window.").
If the user deletes it in the current window, this message would be stupid, so I'd like to unregister the event before:
```
Business business = (Business)businessBindingSource.DataSource;
business.Deleted -= new EventHandler<EventArgs>(business_Deleted);
```
My problem is simple: The message is displayed anyway, so unregistering does not work. I tried storing the EventHandler in a separate member. Does not work either.
Any help would be cool.
Matthias
P.S. Reading [this post](https://stackoverflow.com/questions/99790/is-it-safe-to-add-delegates-to-events-with-keyword-new#100719), I'm afraid that properly unregistering the event could make it unregistered for all editor windows. Could be the next problem. ;-)
|
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;
if ( e is DeletedEventArgs ) { isDeletedFromMe = object.ReferenceEquals( this, e.Author ); }
if ( false == isDeletedFromMe ) {
MessageBox.Show("Item has been deleted in another editor window.",
"...", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
Close();
}
}
```
or you can do it thiw way:
```
void business_Deleted(object sender, EventArgs e)
{
if ( false == object.ReferenceEquals( sender, this.currentlyDeletingBusiness ) ) {
MessageBox.Show("Item has been deleted in another editor window.",
"...", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
Close();
}
Business currentlyDeletingBusiness;
private void deleteButton_Activate(object sender, EventArgs e)
{
Business c = (Business)businessBindingSource.DataSource;
try {
this.currentlyDeletingBusiness = c;
c.Delete();
}
finally {
this.currentlyDeletingBusiness = null;
}
}
```
|
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 */
}
}
void deleteButton_Activate(object sender, EventArgs e)
{
otherUser = false;
/* Delete record */
}
```
|
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/JDCTechTips/2001/tt1220.html) for an explanation using internal frames that should be applicable to JFrame also.
Edit:
Oups, my answer seems a bit off, since your code example shows you are already using a Dialog subclass for this.
|
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-criminal in my book.
Ignoring the fact that most people like to multi-task between several apps, what about the scenario where you open a globally modal dialog and then your application freezes? Ctrl+Alt+Del should work on Windows to kill the app, but I'm not sure about Cmd+Opt+Escape on Mac with a globally modal dialog (does Cocoa even *have* global modality?). None of the Linux platforms have any nice way of killing apps which have taken over complete control of the UI as you are suggesting (you would have to kill X11 completely and start a new instance from scratch).
My answer: **find another way.** I don't care what your client is asking for, they don't want this.
|
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 constructs.
(The "requirements listed above" include the + operator applied to two constant expressions.)
See also [this question](https://stackoverflow.com/questions/242695/long-strings).
|
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 result = String.Concat( x, y, z);
```
rather than the more naive possibility:
```
string result = String.Concat( String.Concat( x, y), z);
```
Nothing earth-shattering, but just wanted to add this bit to the discussion about string literal concatenation optimization. I don't know whether this behavior is mandated by the language standard or not.
|
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 arguments in template instantiations the best I was able to use was to create a small library, ( just showing relevant parts )
```
// library header
class MyFunctionBase<R,T>
{
public:
virtual ~MyFunctionBase();
virtual R operator()(const T &) const=0;
};
class MyFunction<R,T>
{
MyFunctionBase<R,T> *b;
public:
~MyFunction()
{
delete b;
}
virtual R operator()(const T &) const
{
return (*b)(T);
}
};
// source file
....
class func: public MyFunctionBase ...
std::stl_alg(.... MyFunction(new funct));
```
This has always seemed unwieldly to me. I guess to the people on the ISO committee believe so too and added a lambda to C++.
In the meantime how have compilers addressed this problem? ( Especially Windows compilers. )
A correction which might clarify a bit.
Changelog:
Nov 2
replaced to clarify
Since the C++ standard forbids local classes as function objects
|
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 things like 'binary\_operator' as well as maintain state for more advanced functors.
|
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 these methods (and maybe others I haven't listed) and talk about the pros and cons of each - right now, ExternalInterface *seems* like the way to go in terms of flexibility, but is it right for all situations? Are there concrete benefits in terms of execution speed or anything like that? I'm curious - what do we think?
|
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 SWF in which you want to call some JS from is inside a container that offers an external interface. In otherwords, if using ExternalInterface will work. If its not available then just use flash.net.sendToUrl. Never use fscommand() as it uses VBScript and can cause conflicts with other VBScript on a page. Additionally, you can only send one argument string with fscommand and have to split it on the JS side.
|
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 ActionScript, you can do the following on the HTML page:
>
> * Call any JavaScript function.
> * Pass any number of arguments, with any names.
> * Pass various data types (Boolean, Number, String, and so on).
> * Receive a return value from the JavaScript function.
>
> From JavaScript on the HTML page, you can:
>
> * Call an ActionScript function.
> * Pass arguments using standard function call notation.
> * Return a value to the JavaScript function.
The `flash.external.ExternalInterface` class is a direct replacement for the `flash.system.fscommand` class.
So using ExternalInterface is the preferred method or communication between flash and a Javascript function, though if the call is merely Asynchronous it is ok to use `flash.net.navigateToURL`.
|
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 snippet from UnrealScript source):
```
native(278) final function actor Spawn
(
class<actor> SpawnClass,
optional actor SpawnOwner,
optional name SpawnTag,
optional vector SpawnLocation,
optional rotator SpawnRotation
);
```
Now in UScript you would call it like this...
```
local ActorChild myChildRef; //Ref to ActorChild which Extends 'actor'
myChildRef = Spawn(class'ActorChild' ...); //rest of parameters taken out
myChildRef.ChildMethod(); //method call to method existing inside class 'ActorChild'
```
Which will return a reference to an object of class 'ActorChild' and set it to variable 'myChildRef.' I need to do something similar within C#.
I've looked into Generics but it seems that to use them, I need create an instace of the class where my function lies and pass the 'generic' parameter to it. This isn't very desirable however as I won't need to use the 'Spawn' function for certain classes but I would still need to add the generic parameter to the class whenever I use it.
I guess a simplified question would be, how can I return a type that I do not know at compile time and when the different classes could be far too many to trap.
Pseudo-Code (sticking to UScript class names, i.e. Actor):
```
//Function Sig
public class<Actor> Create(class<Actor> CreatedClass)
{
return new CreatedClass;
}
//Function call
ActorChild myChild = Create(class'ActorChild');
```
Any ideas?
EDIT: I would like to avoid explicit typecasts that would occur from the class calling Created. If I can typecast to the desired object within the Created method and return the 'unknown type' whatever that may be, I would be extremely happy.
EDIT 2: Thanks for your answers.
|
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("NamespaceFoo.ActorChild");
```
You can then use the reflection API to create an instance
```
public object Create(System.Type ClassToCreate)
{
return ClassToCreate.GetConstructor(Type.EmptyTypes).Invoke(null);
}
```
|
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 about those events, you would use a signals and slots pattern.
When the sender signals an event (usually by calling the function associated with that event/signal) all the receivers for that event are automatically called. This allows you to connect and disconnect receivers as necessary during the lifetime of the program.
Since this question was tagged C++, here is a link to the [Boost.Signals](http://www.boost.org/doc/libs/1_37_0/doc/html/signals.html) library which has a much more thorough explanation.
|
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 is pressed, all slots that are connected to that signal are called. Slots are on the Subscriber Side. A slot could for example be `sendMail(IdType)` .
Along with the event "button pressed", the slot would know which button was pressed, since the id would have been handed over. `IdType` represents the type of the data sent over the connection between the Publisher and the Subscriber. An operation possible for the Subscriber would be `connect(signal, slot)` which could connect `buttonPressed(IdType)` with `sendMail(IdType)`, so that if the button is pressed, that particular slot is called.
The good thing about this is that the subscriber (the slot side) doesn't need to care about details of the signal. It just needs to connect. Thus, here we have a great deal of *loose coupling*. You can change the buttons implementation, but the interface for the slots would still be the same.
Look at [Qt Signals/Slots](http://doc.trolltech.com/4.5/signalsandslots.html) or [Boost Signals](http://www.boost.org/doc/html/signals.html) for more informations.
|
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 kill anything. Do you know why this happens?
```
<script language="JavaScript" type="text/javascript">
var numDivs, layerName;
layerName = "lnavLayer";
catLinkName = "category";
numDivs = 2;
function toggleLayer(layerID){
if (!(navigator.appName == "Netscape" && navigator.appVersion.substr(0, 1) < 5)){
thisLayer = document.getElementById(layerName + layerID);
categoryLink = document.getElementById(catLinkName + layerID);
closeThem();
if (thisLayer.className == 'subnavDefault'){
thisLayer.className = 'subnavToggled';
categoryLink.className = 'leftnavLinkSelectedSection';
}
}
}
function closeThem(){
for(x = 0; x < numDivs; x++){
theLayer = document.getElementById(layerName + (x
+ 1));
thecategoryLink = document.getElementById(catLinkName + (x + 1));
theLayer.className = 'subnavDefault';
thecategoryLink.className = 'leftnavLink';
}
} var flag = 0; var lastClicked = 0
//-->
</script>
```
it even keeps looping with an online Java regex tool (such as [www.fileformat.info/tool/regex.htm](http://www.fileformat.info/tool/regex.htm)) or a utility like [RegexBuddy](http://www.regexbuddy.com/).
|
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 with A and B:
```
A|B
```
Then a string of three spaces could be matched as AAA, AAB, ABA, ABB, BAA, BAB, BBA, or BBB. In other words the complexity of this part of the regex is 2^N. This will kill any regex engine that doesn't have any safeguards against what I call [catastrophic backtracking](http://www.regular-expressions.info/catastrophic.html "Catastrophic backtracking").
When using alternation (vertical bar) in a regex, always make sure the alternatives are mutually exclusive. That is, at most one of the alternatives may be allowed to match any given bit of text.
|
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 thought I'd point this out.
|
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 annoying to work with for a lot of reasons, not the least of which is that it just looks downright aesthetically unpleasing.
But maybe its me that's stupid - why would anyone do this? Is it a database compatibility issue or some design pattern that I am not aware of?
Can anyone enlighten me?
|
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 Server. It limited the usage of data types to a common subset available on both platforms.
They did diverge in a few places between Oracle and SQL Server but for the most part they used a common schema between the databases to minimize the development work needed to support both DBs.
|
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 your way through it (and watch your case)!
|
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't seem to work.
|
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 other hand, the variance story is stronger - if more confusing - in Java than in .NET.)
|
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 parameter.
Since type parameters are erased at compile time, they do not exist at runtime (sorry Jon, at [*execution* time](http://safari.oreilly.com/9781933988368/pref04)): Hence you cannot get generic type info via reflection in java.
There is a case for more [**reification**](http://blogs.oracle.com/ahe/entry/reification) which is on the table (Java 7 ?), and would facilitate what you are after.
One would hope that a bad type, casted into T, would provoke a Cast exception that would, at execution time, reveal the original type used for T, but alas, that does not work either.
Consider the following test class:
```
import java.util.ArrayList;
/**
* @param <T>
*/
public class StoreGerenericTypeInField<T>
{
private T myT = null;
private ArrayList<T> list = new ArrayList<T>();
private void setT(final T aT) { myT = aT; }
/**
* Attempt to do private strange initialization with T, in the hope to provoke a cast exception
*/
public StoreGerenericTypeInField()
{
StringBuilder aFirstType = new StringBuilder();
StringBuffer aSecondType = new StringBuffer();
this.list.add((T)aFirstType);
this.list.add((T)aSecondType);
System.out.println(this.list.get(0).getClass().getName());
System.out.println(this.list.get(1).getClass().getName());
setT((T)aFirstType);
System.out.println(this.myT.getClass().getName());
setT((T)aSecondType);
System.out.println(this.myT.getClass().getName());
}
/**
* @param args
*/
public static void main(String[] args)
{
StoreGerenericTypeInField<Integer> s = new StoreGerenericTypeInField<Integer>();
}
}
```
The constructor attempt to store nasty thing into its T variable (or its List of T)... and everything run smoothly!?
It prints:
```
java.lang.StringBuilder
java.lang.StringBuffer
java.lang.StringBuilder
java.lang.StringBuffer
```
The type erasure in in itself is [not to blame](http://cakoose.com/wiki/type_erasure_is_not_evil)... that is the **combination** of type erasure (new to java) and ***unsafe casting*** (java legacy old feature) which makes T truly out of reach at execution time (until you actually try to use it with '`T`' specific methods)
|
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:
```
setVisible(true);
toFront();
```
Under Windows XP, this works the first time it is called, on the second time only the tab in the taskbar flashes, the frame doesn't come to the front anymore. Same goes for Win2k. On Vista it seems to work fine.
Do you have any ideas?
|
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 `setAlwaysOnTop(false)`.
---
So, here is the code that could be placed into a base `JFrame`, which is used to derive all application frames.
```
@Override
public void setVisible(final boolean visible) {
// make sure that frame is marked as not disposed if it is asked to be visible
if (visible) {
setDisposed(false);
}
// let's handle visibility...
if (!visible || !isVisible()) { // have to check this condition simply because super.setVisible(true) invokes toFront if frame was already visible
super.setVisible(visible);
}
// ...and bring frame to the front.. in a strange and weird way
if (visible) {
toFront();
}
}
@Override
public void toFront() {
super.setVisible(true);
int state = super.getExtendedState();
state &= ~JFrame.ICONIFIED;
super.setExtendedState(state);
super.setAlwaysOnTop(true);
super.toFront();
super.requestFocus();
super.setAlwaysOnTop(false);
}
```
Whenever your frame should be displayed or brought to front call `frame.setVisible(true)`.
Since I moved to Ubuntu 9.04 there seems to be no need in having a `WindowListener` for invoking `super.setAlwaysOnTop(false)` -- as can be observed; this code was moved to the methods `toFront()` and `setVisible()`.
Please note that method `setVisible()` should always be invoked on EDT.
|
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 multicasts from our middle-tier server to keep local cache's up-to-date. Short of writing another process to listen for us I'm at a loss what else I can do.
So the question is, should this work? Are there inherent restrictions about doing this kind of thing with IIS?
|
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 the request. Code that runs for longer will be at the mercy of IIS' recycling of application pools.
Your best bet is to have another process that does the listening for notifications, and maintain your cache in that process. You can then use shared memory (see [Boost.Interprocess](http://www.boost.org/doc/libs/1_37_0/doc/html/interprocess.html)) to access that cache from your Web service.
|
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 this. So the question is, is there?
|
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 KeyDown event of their container ("Event Bubbling").
|
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 setting the marquee speed and then having a start() and stop() but it doesn't appear to be that simple. Do I have to run an empty loop in the background? How do I best do this? Thanks
|
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 how long it will take the little block of color to animate across your progress bar.
|
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:
virtual std::iostream& transform(std::iostream&) {
/* extract, change and put into again */
}
};
class echo : public transformer {
public:
virtual std::iostream& transform(std::iostream&) {
/* extract, change and put into again */
}
};
std::iostream& operator>>(std::iostream& io, transformer& ts) {
return ts.transform(io);
}
int main() {
std::stringstream data;
std::ifstream file("sound.wav");
noise n; echo e;
data << file.rdbuf();
data >> n >> e;
/* pipelined data now ready to be played back */
}
```
The problem with using a pure `std::istream` is that you would read, but then you wouldn't have a way to put the transformed data back for the next step in the pipeline. Thus i'm using `std::iostream` here. This approach doesn't seem to be efficient, as every operator>> call would extract the whole data, and put into again.
To have a more performant way to stream this would be to create an `expression template`. This means, while `operator>>` is called, you don't do the transforming yet, but you return expression types that will record the chain of operations within its type:
```
typedef transform< echo< noise< istream > > > pipeline;
std::ifstream file("file.wav");
pipeline pipe(file);
int byte = pipe.get();
```
would be an example of such a type. The pipelines' structure is decoded into the type itself. Therefore, no virtual functions are needed anymore in the pipeline. It's not constructed on-demand, but using typedef here, to show the principle. Programming such a system is not easy. So you probably should look into existing systems, like Boost.Iostreams (see below). To give you an idea how it would look like, here is an example i just coded up for you :) :
```
#include <iostream>
template<typename T>
struct transformer {
int get() {
return static_cast<T*>(this)->read();
}
};
struct echot {
template<typename Chain>
struct chain : transformer< chain<Chain> > {
Chain c;
int read() {
return c.get() + 1;
}
chain(Chain const& c):c(c) { }
};
} echo;
struct noiset {
template<typename Chain>
struct chain : transformer< chain<Chain> > {
Chain c;
int read() {
return c.get() * 2;
}
chain(Chain c):c(c) { }
};
} noise;
template<typename T>
typename T::template chain<std::istream&> operator>>(std::istream& is, T) {
return typename T::template chain<std::istream&>(is);
}
template<typename T, typename U>
typename U::template chain<T> operator>>(T t, U u) {
return typename U::template chain<T>(t);
}
int main() {
std::cout << (std::cin >> echo >> noise).get() << std::endl;
}
```
Entering 0 yields the ASCII code 48 here, which is added 1, and multiplied by 2, yielding a value of 98, which is also finally output. I think you agree this is not some code a starter would want to write. So maybe look into boost.
Boost has an sophisticated iostreams library, which can do many things. I'm sure you would find something fitting to this. [Boost.Iostreams](http://www.boost.org/doc/libs/1_37_0/libs/iostreams/doc/index.html)
|
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 filedecrypter until you get to whitespace, and then from infile into metadataparser until more whitespace, and so on.
It looks like you are proposing something different, where metadataparser reads from filedecrypter, audiodecoder from metadataparser, etc. In which case I think the answer to your question needs to be qualified a bit.
**Can you use operator >>** to express this construct? **Probably yes**.
**Can you use iostreams** for this? **Probably not**.
I suggest you clarify what it means when you say A >> B. Perhaps express it as regular methods rather than operator overloads first, and that may clarify the question.
|
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 `mscorlib` which implements `IEnumerable`. Note that life is somewhat harder when the base type is generic...
```
using System;
using System.Collections;
using System.Linq;
using System.Reflection;
class Test
{
static void Main()
{
Assembly assembly = typeof(string).Assembly;
Type target = typeof(IEnumerable);
var types = assembly.GetTypes()
.Where(type => target.IsAssignableFrom(type));
foreach (Type type in types)
{
Console.WriteLine(type.Name);
}
}
}
```
|
```
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 it writes to the stream. In my case I have to make sure the number I want to write is kept in a short datatype, this will make the Write function write 2 bytes.
|
```
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 the bytes, use `Encoding`:
```
byte[] raw = Encoding.UTF8.GetBytes(s);
```
(obviously different encodings may give different results; UTF8 will give 2 bytes for this data)
Actually, a shorter version of the first bit is:
```
string s = number.ToString("00");
```
But the `string.Format` version is more flexible.
|
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 sqr.CanRender() method to return true if the input is of type Square and false otherwise.
|
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) delegates then you'll need to define your own delegate.
Add to the class member:
```
private delegate bool CanRenderDelegate(Shape shape)
```
The expectation becomes:
```
Expect.Call(sqr.CanRender(null))
.IgnoreArguments()
.Do((CanRenderDelegate) delegate(Agent x){return x.GetType() == typeof(Square);})
.Repeat.Any();
```
|
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)
... w = f(42)
...
>>> C.v
'<9>'
>>> C.w
'<42>'
>>> C.f(4)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unbound method f() must be called with C instance as first argument (got int instance instead)
```
Oops! I've inadvertently exposed `f` to the outside world, but it doesn't take a `self` argument (and can't for obvious reasons). One possibility would be to `del` the function after I use it:
```
>>> class C(object):
... def f(num):
... return '<' + str(num) + '>'
... v = f(9)
... del f
...
>>> C.v
'<9>'
>>> C.f
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: type object 'C' has no attribute 'f'
```
But what if I want to use `f` again later, after the declaration? It won't do to delete the function. I could make it "private" (i.e., prefix its name with `__`) and give it the `@staticmethod` treatment, but invoking `staticmethod` objects through abnormal channels gets very funky:
```
>>> class C(object):
... @staticmethod
... def __f(num):
... return '<' + str(num) + '>'
... v = __f.__get__(1)(9) # argument to __get__ is ignored...
...
>>> C.v
'<9>'
```
I have to use the above craziness because `staticmethod` objects, which are descriptors, are not themselves callable. I need to recover the function wrapped by the `staticmethod` object before I can call it.
There has got to be a better way to do this. How can I cleanly declare a function in a class, use it during its declaration, and also use it later from within the class? Should I even be doing this?
|
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)
```
Then when you want to use f again, just use it
```
>>> f(4)
'<4>'
```
I think the moral of the tale is "In Python, you don't *have* to force everything into a class".
|
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 class within a closure.
```
def create_C():
def f(num):
return '<' + str(num) + '>'
class C(object):
v = f(9)
def method_using_f(self, x): return f(x*2)
return C
C=create_C()
del create_C
```
This way C has access to f within its definition and methods, but nothing else does (barring fairly involved introspection
of its methods (`C.method_using_f.im_func.func_closure`))
This is probably overkill for most purposes though - documenting that f is internal by using the "\_" prefix nameing convention should
generally be sufficient.
**[Edit]** One other option is to hold a reference to the pre-wrapped function object in the methods you wish to use it in. For example, by setting it as a default argument:
```
class C(object):
def f(num):
return '<' + str(num) + '>'
v = f(9)
def method_using_f(self, x, f=f): return f(x*2)
del f
```
(Though I think the closure approach is probably better)
|
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.__init__(self, failures)
Exception.__init__(self)
print isinstance(ConstraintFailureSet(), Exception)
True
raise ConstraintFailureSet()
TypeError: exceptions must be classes, instances, or strings (deprecated), not ConstraintFailureSet
```
What the heck ?
And the worst is that I can't try super() since Exception are old based class...
EDIT : And, yes, I've tried to switch the order of inheritance / init.
EDIT2 : I am using CPython 2.4 on Ubuntu8.10. You newer know is this kind of infos is usefull ;-). Anyway, this little riddle has shut the mouth of 3 of my collegues. You'd be my best-friend-of-the day...
|
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 store their data internally, they are not compatible and thus you cannot inherit from both at the same time.
In later versions of Python you should get an Exception the moment you try to define the class:
```
>>> class foo(dict, Exception):
... pass
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Error when calling the metaclass bases
multiple bases have instance lay-out conflict
```
|
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 internal dictionary named `failures`.
Could you update your problem to list some some specific thing this can't do?
```
try:
raise ConstraintFailure( x=ValueError, y=Exception )
except ConstraintFailure, e:
print e['x']
print e['y']
<type 'exceptions.ValueError'>
<type 'exceptions.Exception'>
```
|
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 have instantiated no Animals, because this is supposed to be a virtual class. I have instantiated Cats and Dogs, but in the Admin Page for AnimalHome, my choices for Animals are displayed as "Animal object" (the default \_\_unicode\_\_(), I guess) as opposed to the \_\_unicode\_\_ I have defined for the two subclasses. Help.
---
The abstract base class issue is a red herring wrt to this question, I think. Even if Animal was not supposed to be abstract, I still have the problem that, for some reason, since the ForeignKey is defined on Animal and not one of its subclasses, the superclass method is being called instead of the subclass. In OO programming when you call object.method() you're supposed to get the lowest-subclass's implementation, and you have to do extra work to get any superclass's implementation. So why is it that having \_\_unicode\_\_ defined on the subclasses is not sufficient for --- actually the problem might be that \_\_unicode\_\_ is not getting called at all because introspection on the Animal class reveals that it's not defined. So maybe if I define \_\_unicode\_\_ for Animal and have it call subclasses' \_\_unicode\_\_ I could get the desired effect.
---
Okay, I think that I understand the ORM issues. Both these answers have helped me understand this, thank you. While experimenting with this, I discovered that when Django saves a subclassed model, it does two things: (1) it creates a row for the subclassed object in the superclass's table, and (2) it makes the PK in the subclass table identical to the PK assigned in the superclass table. This PK in the subclass table is named superclass\_ptr. Based upon this I've concocted the following. I'd appreciate feedback.
```
Class Animal(models.Model)
def __unicode__(self):
if Dog.objects.filter(pk=self.pk).count() > 0:
return unicode(Dog.objects.get(pk=self.pk))
elif Cat.objects.filter(pk=self.pk).count() > 0:
return unicode(Cat.objects.get(pk=self.pk))
else:
return "An Animal!"
```
---
It seems that Lawrence is most on-point wrt this question. Cat and Dog will have disjoint PK sets (and any subclass of Animal will have a PK identical to the record of its superclass), but unfortunately Django does not perform any work behind the scenes a la: "I'm an Animal. I know Animals have subclasses Dog and Cat. Specifically, I'm Animal number 3, and furthermore I just checked and there's a Cat number 3 too. That means that I'm actually Cat number 3". Even though this seems entirely possible and very reasonable (since a Cat won't do anything an Animal couldn't do itself) using Python's introspection. Thank you all.
|
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 for the ForeignKey anyway, and also ensures that Dog and Cat will have disjunct primary key sets.
Now, Django implements inheritance using a OneToOneField. Because of this, **an instance of a base class that has a subclass instance gets a reference to that instance, named appropriately.** This means you can do:
```
class Animal(models.Model):
def __unicode__(self):
if hasattr(self, 'dog'):
return self.dog.__unicode__()
elif hasattr(self, 'cat'):
return self.cat.__unicode__()
else:
return 'Animal'
```
This also answers your question to Ber about a **unicode**() that's dependent on other subclass attributes. You're actually calling the appropriate method on the subclass instance now.
Now, this does suggest that, since Django's already looking for subclass instances behind the scenes, the code could just go all the way and return a Cat or Dog instance instead of an Animal. You'll have to take up that question with the devs. :)
|
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 = True
```
---
Edit
"In OO programming when you call object.method() you're supposed to get the lowest-subclass's implementation."
True. But not the whole story.
This is not a OO issue. Or even a Python or Django issue. This is an ORM issue.
The question is "What object is reconstructed at the end of the FK reference?" And the answer is that there's no standard, obvious answer of how to handle the transformation from FK value to object.
I've got a row in `AnimalHome` with an `animals` value of 42. It refers to `Animal.objects.get(pk=42)`. Which subclass of Animal? Cat? Dog? How does the ORM layer know if it should do `Dog.objects.get(pk=42)` or `Cat.objects.get(pk=42)`?
"But wait," you say. "It should fetch the Animal object, not a Dog or Cat object." You can hope for that, but that's not how the Django ORM works. Each class is a distinct table. Cat and Dog are -- by definition -- separate tables, with separate queries. You're not using an object store. You're using ORM to relational tables.
---
Edit
First, your query only works if Dog and Cat share a common key generator, and don't have an overlapping set of PK's.
If you have a Dog with PK of 42 AND a Cat with PK of 42, you've got a problem. And since you can't easily control the key generation, your solution can't work.
Run Time Type Identification is bad. It's not Object-Oriented in a number of ways. Almost anything you can do to avoid RTTI is better than an ever-expanding sequence of if-statements to distinguish subclasses.
However, the model you're trying to build is -- specifically -- a pathological problem for ORM systems. Indeed, so specifically pathological that I'm almost willing to bet it's homework. [There are pathological problems for pure SQL systems, also. They often show up as homework.]
The issue is that the ORM cannot do what you think it should do. So you have two choices.
* Stop using Django.
* Do something Django does directly.
* Break OO design guidelines and resort to brittle things like RTTI, which make it remarkably hard to add another subclass of animals.
Consider this way to do RTTI -- it includes the class name as well as the PK
```
KIND_CHOICES = (
( "DOG", "Dog" ),
( "CAT", "Cat" ),
)
class Animal( models.Model ):
kind = models.CharField( max_length= 1, choices=KIND_CHOICES )
fk = models.IntegerField()
def get_kind( self ):
if kind == "DOG":
return Dog.objects.get( pk = fk )
elif kind == "CAT":
return Cat.objects.get( pk = fk )
```
|
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 App Engine") (direct: [here](http://abaditya.com/2008/04/19/a-pseudo-ide-for-google-app-engine-komodo-edit/ "A pseudo IDE for Google App Engine") and [here](http://www.toddnemet.com/using-komodo-edit-as-an-ide-for-google-app-engine/ "Using Komodo Edit as an IDE for Google App Engine")).
* Komodo supports the basic
organization of your work into
Projects, which Notepad++ does not
(apart from physical folder
organization).
* The custom commands
toolbar is useful to keep track of
numerous frequently-used commands
and even link to URLs (like online
documentation and the like).
* It has a working (if sometimes clunky)
code-completion mechanism.
In short, it's an IDE which provides all the benefits thereof.
Notepad++ is simpler, much MUCH faster to load, and does support some basic configurable run commands; it's a fine choice if you like doing all your execution and debugging right in the commandline or Python shell. My advice is to try both!
|
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 the current file on the side. Notepad++ used to have a plugin like this, but it no longer works with the current version and hasn't been updated in a while.
Notepad++ Pros:
* If you select a word, it will highlight all of those words in the current document (makes it easier to find misspellings), without having to hit `Ctrl`+`F`.
* When working with HTML, when the cursor is on/in a tag, the starting and ending tags are both highlighted
Anyone know if either of those last 2 things is possible in Komodo Edit?
|
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()`), Java’s `isInstance` takes an object as its argument, whereas C#’s `IsAssignableFrom` expects another `System.Type` object.
|
```
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)
{
var handler = SomethingHappened;
if (handler != null)
handler(this, e);
}
```
Recently in some other question on this board (which I can't find now), someone pointed out that extension methods could be used nicely in this scenario. Here's one way to do it:
```
static public class EventExtensions
{
static public void RaiseEvent(this EventHandler @event, object sender, EventArgs e)
{
var handler = @event;
if (handler != null)
handler(sender, e);
}
static public void RaiseEvent<T>(this EventHandler<T> @event, object sender, T e)
where T : EventArgs
{
var handler = @event;
if (handler != null)
handler(sender, e);
}
}
```
With these extension methods in place, all you need to declare and raise an event is something like this:
```
public event EventHandler SomethingHappened;
void SomeMethod()
{
this.SomethingHappened.RaiseEvent(this, EventArgs.Empty);
}
```
My question: Is this a good idea? Are we missing anything by not having the standard On method? (One thing I notice is that it doesn't work with events that have explicit add/remove code.)
|
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 = delegate {};
```
The performance hit of calling an extra delegate will be negligible, and it sure makes the code easier.
By the way, in your extension method you don't need an extra local variable - you could just do:
```
static public void RaiseEvent(this EventHandler @event, object sender, EventArgs e)
{
if (@event != null)
@event(sender, e);
}
static public void RaiseEvent<T>(this EventHandler<T> @event, object sender, T e)
where T : EventArgs
{
if (@event != null)
@event(sender, e);
}
```
Personally I wouldn't use a keyword as a parameter name, but it doesn't really change the calling side at all, so do what you want :)
EDIT: As for the "OnXXX" method: are you planning on your classes being derived from? In my view, most classes should be sealed. If you *do*, do you want those derived classes to be able to raise the event? If the answer to either of these questions is "no" then don't bother. If the answer to both is "yes" then do :)
|
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 sets out to solve is sidestepped here because, like in that code, `SomethingHappened` is only accessed once, so there is no possibility of it being set to null between test and invocation.
This answer is perhaps tangential to the original question, but very relevent for those looking for a simpler method to raise events.
|
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 (green, light green for example).
Any ideas on how this could be solved and how it would be possibler to generate distinctly different colors?
I'd be great if any examples (feel free to just discuss the problem and solution without examples if you find that easier) were in C# and RGB based colors.
|
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 add 64 to 128 => 192
follow the pattern.
Straightforward to program and gives you fairly distinct colours.
**EDIT: Request for code sample**
Also - adding in the additional pattern as below if gray is an acceptable colour:
```
255, 255, 255
128, 128, 128
```
There are a number of ways you can handle generating these in code.
# The Easy Way
If you can guarantee that you will never need more than a fixed number of colours, just generate an array of colours following this pattern and use those:
```
static string[] ColourValues = new string[] {
"FF0000", "00FF00", "0000FF", "FFFF00", "FF00FF", "00FFFF", "000000",
"800000", "008000", "000080", "808000", "800080", "008080", "808080",
"C00000", "00C000", "0000C0", "C0C000", "C000C0", "00C0C0", "C0C0C0",
"400000", "004000", "000040", "404000", "400040", "004040", "404040",
"200000", "002000", "000020", "202000", "200020", "002020", "202020",
"600000", "006000", "000060", "606000", "600060", "006060", "606060",
"A00000", "00A000", "0000A0", "A0A000", "A000A0", "00A0A0", "A0A0A0",
"E00000", "00E000", "0000E0", "E0E000", "E000E0", "00E0E0", "E0E0E0",
};
```
# The Hard Way
If you don't know how many colours you are going to need, the code below will generate up to 896 colours using this pattern. (896 = 256 \* 7 / 2) 256 is the colour space per channel, we have 7 patterns and we stop before we get to colours separated by only 1 colour value.
I've probably made harder work of this code than I needed to. First, there is an intensity generator which starts at 255, then generates the values as per the pattern described above. The pattern generator just loops through the seven colour patterns.
```
using System;
class Program {
static void Main(string[] args) {
ColourGenerator generator = new ColourGenerator();
for (int i = 0; i < 896; i++) {
Console.WriteLine(string.Format("{0}: {1}", i, generator.NextColour()));
}
}
}
public class ColourGenerator {
private int index = 0;
private IntensityGenerator intensityGenerator = new IntensityGenerator();
public string NextColour() {
string colour = string.Format(PatternGenerator.NextPattern(index),
intensityGenerator.NextIntensity(index));
index++;
return colour;
}
}
public class PatternGenerator {
public static string NextPattern(int index) {
switch (index % 7) {
case 0: return "{0}0000";
case 1: return "00{0}00";
case 2: return "0000{0}";
case 3: return "{0}{0}00";
case 4: return "{0}00{0}";
case 5: return "00{0}{0}";
case 6: return "{0}{0}{0}";
default: throw new Exception("Math error");
}
}
}
public class IntensityGenerator {
private IntensityValueWalker walker;
private int current;
public string NextIntensity(int index) {
if (index == 0) {
current = 255;
}
else if (index % 7 == 0) {
if (walker == null) {
walker = new IntensityValueWalker();
}
else {
walker.MoveNext();
}
current = walker.Current.Value;
}
string currentText = current.ToString("X");
if (currentText.Length == 1) currentText = "0" + currentText;
return currentText;
}
}
public class IntensityValue {
private IntensityValue mChildA;
private IntensityValue mChildB;
public IntensityValue(IntensityValue parent, int value, int level) {
if (level > 7) throw new Exception("There are no more colours left");
Value = value;
Parent = parent;
Level = level;
}
public int Level { get; set; }
public int Value { get; set; }
public IntensityValue Parent { get; set; }
public IntensityValue ChildA {
get {
return mChildA ?? (mChildA = new IntensityValue(this, this.Value - (1<<(7-Level)), Level+1));
}
}
public IntensityValue ChildB {
get {
return mChildB ?? (mChildB = new IntensityValue(this, Value + (1<<(7-Level)), Level+1));
}
}
}
public class IntensityValueWalker {
public IntensityValueWalker() {
Current = new IntensityValue(null, 1<<7, 1);
}
public IntensityValue Current { get; set; }
public void MoveNext() {
if (Current.Parent == null) {
Current = Current.ChildA;
}
else if (Current.Parent.ChildA == Current) {
Current = Current.Parent.ChildB;
}
else {
int levelsUp = 1;
Current = Current.Parent;
while (Current.Parent != null && Current == Current.Parent.ChildB) {
Current = Current.Parent;
levelsUp++;
}
if (Current.Parent != null) {
Current = Current.Parent.ChildB;
}
else {
levelsUp++;
}
for (int i = 0; i < levelsUp; i++) {
Current = Current.ChildA;
}
}
}
}
```
|
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 getRGB(int index) {
int[] p = getPattern(index);
return getElement(p[0]) << 16 | getElement(p[1]) << 8 | getElement(p[2]);
}
public int getElement(int index) {
int value = index - 1;
int v = 0;
for (int i = 0; i < 8; i++) {
v = v | (value & 1);
v <<= 1;
value >>= 1;
}
v >>= 1;
return v & 0xFF;
}
public int[] getPattern(int index) {
int n = (int)Math.cbrt(index);
index -= (n*n*n);
int[] p = new int[3];
Arrays.fill(p,n);
if (index == 0) {
return p;
}
index--;
int v = index % 3;
index = index / 3;
if (index < n) {
p[v] = index % n;
return p;
}
index -= n;
p[v ] = index / n;
p[++v % 3] = index % n;
return p;
}
```
This will produce patterns of that type infinitely (2^24) into the future. However, after a hundred or so spots you likely won't see much of a difference between a color with 0 or 32 in the blue's place.
You might be better off normalizing this into a different color space. LAB color space for example with the L,A,B values normalized and converted. So the distinctness of the color is pushed through something more akin to the human eye.
getElement() reverses the endian of an 8 bit number, and starts counting from -1 rather than 0 (masking with 255). So it goes 255,0,127,192,64,... as the number grows it moves less and less significant bits, subdividing the number.
getPattern() determines what the most significant element in the pattern should be (it's the cube root). Then proceeds to break down the 3N²+3N+1 different patterns that involve that most significant element.
This algorithm will produce (first 128 values):
```
#FFFFFF
#000000
#FF0000
#00FF00
#0000FF
#FFFF00
#00FFFF
#FF00FF
#808080
#FF8080
#80FF80
#8080FF
#008080
#800080
#808000
#FFFF80
#80FFFF
#FF80FF
#FF0080
#80FF00
#0080FF
#00FF80
#8000FF
#FF8000
#000080
#800000
#008000
#404040
#FF4040
#40FF40
#4040FF
#004040
#400040
#404000
#804040
#408040
#404080
#FFFF40
#40FFFF
#FF40FF
#FF0040
#40FF00
#0040FF
#FF8040
#40FF80
#8040FF
#00FF40
#4000FF
#FF4000
#000040
#400000
#004000
#008040
#400080
#804000
#80FF40
#4080FF
#FF4080
#800040
#408000
#004080
#808040
#408080
#804080
#C0C0C0
#FFC0C0
#C0FFC0
#C0C0FF
#00C0C0
#C000C0
#C0C000
#80C0C0
#C080C0
#C0C080
#40C0C0
#C040C0
#C0C040
#FFFFC0
#C0FFFF
#FFC0FF
#FF00C0
#C0FF00
#00C0FF
#FF80C0
#C0FF80
#80C0FF
#FF40C0
#C0FF40
#40C0FF
#00FFC0
#C000FF
#FFC000
#0000C0
#C00000
#00C000
#0080C0
#C00080
#80C000
#0040C0
#C00040
#40C000
#80FFC0
#C080FF
#FFC080
#8000C0
#C08000
#00C080
#8080C0
#C08080
#80C080
#8040C0
#C08040
#40C080
#40FFC0
#C040FF
#FFC040
#4000C0
#C04000
#00C040
#4080C0
#C04080
#80C040
#4040C0
#C04040
#40C040
#202020
#FF2020
#20FF20
```
Read left to right, top to bottom. 729 colors (9³). So all the patterns up to n = 9. You'll notice the speed at which they start to clash. There's only so many WRGBCYMK variations. And this solution, while clever basically only does different shades of primary colors.

Much of the clashing is due to green and how similar most greens look to most people. The demand that each be maximally different at start rather than just different enough to not be the same color. And basic flaws in the idea resulting in primary colors patterns, and identical hues.
---
Using CIELab2000 Color Space and Distance Routine to randomly select and try 10k different colors and find the maximally-distant minimum-distance from previous colors, (pretty much the definition of the request) avoids clashing longer than the above solution:

Which could be just called a static list for the Easy Way. It took an hour and a half to generate 729 entries:
```
#9BC4E5
#310106
#04640D
#FEFB0A
#FB5514
#E115C0
#00587F
#0BC582
#FEB8C8
#9E8317
#01190F
#847D81
#58018B
#B70639
#703B01
#F7F1DF
#118B8A
#4AFEFA
#FCB164
#796EE6
#000D2C
#53495F
#F95475
#61FC03
#5D9608
#DE98FD
#98A088
#4F584E
#248AD0
#5C5300
#9F6551
#BCFEC6
#932C70
#2B1B04
#B5AFC4
#D4C67A
#AE7AA1
#C2A393
#0232FD
#6A3A35
#BA6801
#168E5C
#16C0D0
#C62100
#014347
#233809
#42083B
#82785D
#023087
#B7DAD2
#196956
#8C41BB
#ECEDFE
#2B2D32
#94C661
#F8907D
#895E6B
#788E95
#FB6AB8
#576094
#DB1474
#8489AE
#860E04
#FBC206
#6EAB9B
#F2CDFE
#645341
#760035
#647A41
#496E76
#E3F894
#F9D7CD
#876128
#A1A711
#01FB92
#FD0F31
#BE8485
#C660FB
#120104
#D48958
#05AEE8
#C3C1BE
#9F98F8
#1167D9
#D19012
#B7D802
#826392
#5E7A6A
#B29869
#1D0051
#8BE7FC
#76E0C1
#BACFA7
#11BA09
#462C36
#65407D
#491803
#F5D2A8
#03422C
#72A46E
#128EAC
#47545E
#B95C69
#A14D12
#C4C8FA
#372A55
#3F3610
#D3A2C6
#719FFA
#0D841A
#4C5B32
#9DB3B7
#B14F8F
#747103
#9F816D
#D26A5B
#8B934B
#F98500
#002935
#D7F3FE
#FCB899
#1C0720
#6B5F61
#F98A9D
#9B72C2
#A6919D
#2C3729
#D7C70B
#9F9992
#EFFBD0
#FDE2F1
#923A52
#5140A7
#BC14FD
#6D706C
#0007C4
#C6A62F
#000C14
#904431
#600013
#1C1B08
#693955
#5E7C99
#6C6E82
#D0AFB3
#493B36
#AC93CE
#C4BA9C
#09C4B8
#69A5B8
#374869
#F868ED
#E70850
#C04841
#C36333
#700366
#8A7A93
#52351D
#B503A2
#D17190
#A0F086
#7B41FC
#0EA64F
#017499
#08A882
#7300CD
#A9B074
#4E6301
#AB7E41
#547FF4
#134DAC
#FDEC87
#056164
#FE12A0
#C264BA
#939DAD
#0BCDFA
#277442
#1BDE4A
#826958
#977678
#BAFCE8
#7D8475
#8CCF95
#726638
#FEA8EB
#EAFEF0
#6B9279
#C2FE4B
#304041
#1EA6A7
#022403
#062A47
#054B17
#F4C673
#02FEC7
#9DBAA8
#775551
#835536
#565BCC
#80D7D2
#7AD607
#696F54
#87089A
#664B19
#242235
#7DB00D
#BFC7D6
#D5A97E
#433F31
#311A18
#FDB2AB
#D586C9
#7A5FB1
#32544A
#EFE3AF
#859D96
#2B8570
#8B282D
#E16A07
#4B0125
#021083
#114558
#F707F9
#C78571
#7FB9BC
#FC7F4B
#8D4A92
#6B3119
#884F74
#994E4F
#9DA9D3
#867B40
#CED5C4
#1CA2FE
#D9C5B4
#FEAA00
#507B01
#A7D0DB
#53858D
#588F4A
#FBEEEC
#FC93C1
#D7CCD4
#3E4A02
#C8B1E2
#7A8B62
#9A5AE2
#896C04
#B1121C
#402D7D
#858701
#D498A6
#B484EF
#5C474C
#067881
#C0F9FC
#726075
#8D3101
#6C93B2
#A26B3F
#AA6582
#4F4C4F
#5A563D
#E83005
#32492D
#FC7272
#B9C457
#552A5B
#B50464
#616E79
#DCE2E4
#CF8028
#0AE2F0
#4F1E24
#FD5E46
#4B694E
#C5DEFC
#5DC262
#022D26
#7776B8
#FD9F66
#B049B8
#988F73
#BE385A
#2B2126
#54805A
#141B55
#67C09B
#456989
#DDC1D9
#166175
#C1E29C
#A397B5
#2E2922
#ABDBBE
#B4A6A8
#A06B07
#A99949
#0A0618
#B14E2E
#60557D
#D4A556
#82A752
#4A005B
#3C404F
#6E6657
#7E8BD5
#1275B8
#D79E92
#230735
#661849
#7A8391
#FE0F7B
#B0B6A9
#629591
#D05591
#97B68A
#97939A
#035E38
#53E19E
#DFD7F9
#02436C
#525A72
#059A0E
#3E736C
#AC8E87
#D10C92
#B9906E
#66BDFD
#C0ABFD
#0734BC
#341224
#8AAAC1
#0E0B03
#414522
#6A2F3E
#2D9A8A
#4568FD
#FDE6D2
#FEE007
#9A003C
#AC8190
#DCDD58
#B7903D
#1F2927
#9B02E6
#827A71
#878B8A
#8F724F
#AC4B70
#37233B
#385559
#F347C7
#9DB4FE
#D57179
#DE505A
#37F7DD
#503500
#1C2401
#DD0323
#00A4BA
#955602
#FA5B94
#AA766C
#B8E067
#6A807E
#4D2E27
#73BED7
#D7BC8A
#614539
#526861
#716D96
#829A17
#210109
#436C2D
#784955
#987BAB
#8F0152
#0452FA
#B67757
#A1659F
#D4F8D8
#48416F
#DEBAAF
#A5A9AA
#8C6B83
#403740
#70872B
#D9744D
#151E2C
#5C5E5E
#B47C02
#F4CBD0
#E49D7D
#DD9954
#B0A18B
#2B5308
#EDFD64
#9D72FC
#2A3351
#68496C
#C94801
#EED05E
#826F6D
#E0D6BB
#5B6DB4
#662F98
#0C97CA
#C1CA89
#755A03
#DFA619
#CD70A8
#BBC9C7
#F6BCE3
#A16462
#01D0AA
#87C6B3
#E7B2FA
#D85379
#643AD5
#D18AAE
#13FD5E
#B3E3FD
#C977DB
#C1A7BB
#9286CB
#A19B6A
#8FFED7
#6B1F17
#DF503A
#10DDD7
#9A8457
#60672F
#7D327D
#DD8782
#59AC42
#82FDB8
#FC8AE7
#909F6F
#B691AE
#B811CD
#BCB24E
#CB4BD9
#2B2304
#AA9501
#5D5096
#403221
#F9FAB4
#3990FC
#70DE7F
#95857F
#84A385
#50996F
#797B53
#7B6142
#81D5FE
#9CC428
#0B0438
#3E2005
#4B7C91
#523854
#005EA9
#F0C7AD
#ACB799
#FAC08E
#502239
#BFAB6A
#2B3C48
#0EB5D8
#8A5647
#49AF74
#067AE9
#F19509
#554628
#4426A4
#7352C9
#3F4287
#8B655E
#B480BF
#9BA74C
#5F514C
#CC9BDC
#BA7942
#1C4138
#3C3C3A
#29B09C
#02923F
#701D2B
#36577C
#3F00EA
#3D959E
#440601
#8AEFF3
#6D442A
#BEB1A8
#A11C02
#8383FE
#A73839
#DBDE8A
#0283B3
#888597
#32592E
#F5FDFA
#01191B
#AC707A
#B6BD03
#027B59
#7B4F08
#957737
#83727D
#035543
#6F7E64
#C39999
#52847A
#925AAC
#77CEDA
#516369
#E0D7D0
#FCDD97
#555424
#96E6B6
#85BB74
#5E2074
#BD5E48
#9BEE53
#1A351E
#3148CD
#71575F
#69A6D0
#391A62
#E79EA0
#1C0F03
#1B1636
#D20C39
#765396
#7402FE
#447F3E
#CFD0A8
#3A2600
#685AFC
#A4B3C6
#534302
#9AA097
#FD5154
#9B0085
#403956
#80A1A7
#6E7A9A
#605E6A
#86F0E2
#5A2B01
#7E3D43
#ED823B
#32331B
#424837
#40755E
#524F48
#B75807
#B40080
#5B8CA1
#FDCFE5
#CCFEAC
#755847
#CAB296
#C0D6E3
#2D7100
#D5E4DE
#362823
#69C63C
#AC3801
#163132
#4750A6
#61B8B2
#FCC4B5
#DEBA2E
#FE0449
#737930
#8470AB
#687D87
#D7B760
#6AAB86
#8398B8
#B7B6BF
#92C4A1
#B6084F
#853B5E
#D0BCBA
#92826D
#C6DDC6
#BE5F5A
#280021
#435743
#874514
#63675A
#E97963
#8F9C9E
#985262
#909081
#023508
#DDADBF
#D78493
#363900
#5B0120
#603C47
#C3955D
#AC61CB
#FD7BA7
#716C74
#8D895B
#071001
#82B4F2
#B6BBD8
#71887A
#8B9FE3
#997158
#65A6AB
#2E3067
#321301
#FEECCB
#3B5E72
#C8FE85
#A1DCDF
#CB49A6
#B1C5E4
#3E5EB0
#88AEA7
#04504C
#975232
#6786B9
#068797
#9A98C4
#A1C3C2
#1C3967
#DBEA07
#789658
#E7E7C6
#A6C886
#957F89
#752E62
#171518
#A75648
#01D26F
#0F535D
#047E76
#C54754
#5D6E88
#AB9483
#803B99
#FA9C48
#4A8A22
#654A5C
#965F86
#9D0CBB
#A0E8A0
#D3DBFA
#FD908F
#AEAB85
#A13B89
#F1B350
#066898
#948A42
#C8BEDE
#19252C
#7046AA
#E1EEFC
#3E6557
#CD3F26
#2B1925
#DDAD94
#C0B109
#37DFFE
#039676
#907468
#9E86A5
#3A1B49
#BEE5B7
#C29501
#9E3645
#DC580A
#645631
#444B4B
#FD1A63
#DDE5AE
#887800
#36006F
#3A6260
#784637
#FEA0B7
#A3E0D2
#6D6316
#5F7172
#B99EC7
#777A7E
#E0FEFD
#E16DC5
#01344B
#F8F8FC
#9F9FB5
#182617
#FE3D21
#7D0017
#822F21
#EFD9DC
#6E68C4
#35473E
#007523
#767667
#A6825D
#83DC5F
#227285
#A95E34
#526172
#979730
#756F6D
#716259
#E8B2B5
#B6C9BB
#9078DA
#4F326E
#B2387B
#888C6F
#314B5F
#E5B678
#38A3C6
#586148
#5C515B
#CDCCE1
#C8977F
```
Using brute force to (testing all 16,777,216 RGB colors through CIELab Delta2000 / Starting with black) produces a series. Which starts to clash at around 26 but could make it to 30 or 40 with visual inspection and manual dropping (which can't be done with a computer). So doing the absolute maximum one can programmatically only makes a couple dozen distinct colors. A discrete list is your best bet. You will get more discrete colors with a list than you would programmatically. The easy way is the best solution, start mixing and matching with other ways to alter your data than color.

```
#000000
#00FF00
#0000FF
#FF0000
#01FFFE
#FFA6FE
#FFDB66
#006401
#010067
#95003A
#007DB5
#FF00F6
#FFEEE8
#774D00
#90FB92
#0076FF
#D5FF00
#FF937E
#6A826C
#FF029D
#FE8900
#7A4782
#7E2DD2
#85A900
#FF0056
#A42400
#00AE7E
#683D3B
#BDC6FF
#263400
#BDD393
#00B917
#9E008E
#001544
#C28C9F
#FF74A3
#01D0FF
#004754
#E56FFE
#788231
#0E4CA1
#91D0CB
#BE9970
#968AE8
#BB8800
#43002C
#DEFF74
#00FFC6
#FFE502
#620E00
#008F9C
#98FF52
#7544B1
#B500FF
#00FF78
#FF6E41
#005F39
#6B6882
#5FAD4E
#A75740
#A5FFD2
#FFB167
#009BFF
#E85EBE
```
Update:
I continued this for about a month so, at 1024 brute force.
[](https://i.stack.imgur.com/cuF3C.png)
```
public static final String[] indexcolors = new String[]{
"#000000", "#FFFF00", "#1CE6FF", "#FF34FF", "#FF4A46", "#008941", "#006FA6", "#A30059",
"#FFDBE5", "#7A4900", "#0000A6", "#63FFAC", "#B79762", "#004D43", "#8FB0FF", "#997D87",
"#5A0007", "#809693", "#FEFFE6", "#1B4400", "#4FC601", "#3B5DFF", "#4A3B53", "#FF2F80",
"#61615A", "#BA0900", "#6B7900", "#00C2A0", "#FFAA92", "#FF90C9", "#B903AA", "#D16100",
"#DDEFFF", "#000035", "#7B4F4B", "#A1C299", "#300018", "#0AA6D8", "#013349", "#00846F",
"#372101", "#FFB500", "#C2FFED", "#A079BF", "#CC0744", "#C0B9B2", "#C2FF99", "#001E09",
"#00489C", "#6F0062", "#0CBD66", "#EEC3FF", "#456D75", "#B77B68", "#7A87A1", "#788D66",
"#885578", "#FAD09F", "#FF8A9A", "#D157A0", "#BEC459", "#456648", "#0086ED", "#886F4C",
"#34362D", "#B4A8BD", "#00A6AA", "#452C2C", "#636375", "#A3C8C9", "#FF913F", "#938A81",
"#575329", "#00FECF", "#B05B6F", "#8CD0FF", "#3B9700", "#04F757", "#C8A1A1", "#1E6E00",
"#7900D7", "#A77500", "#6367A9", "#A05837", "#6B002C", "#772600", "#D790FF", "#9B9700",
"#549E79", "#FFF69F", "#201625", "#72418F", "#BC23FF", "#99ADC0", "#3A2465", "#922329",
"#5B4534", "#FDE8DC", "#404E55", "#0089A3", "#CB7E98", "#A4E804", "#324E72", "#6A3A4C",
"#83AB58", "#001C1E", "#D1F7CE", "#004B28", "#C8D0F6", "#A3A489", "#806C66", "#222800",
"#BF5650", "#E83000", "#66796D", "#DA007C", "#FF1A59", "#8ADBB4", "#1E0200", "#5B4E51",
"#C895C5", "#320033", "#FF6832", "#66E1D3", "#CFCDAC", "#D0AC94", "#7ED379", "#012C58",
"#7A7BFF", "#D68E01", "#353339", "#78AFA1", "#FEB2C6", "#75797C", "#837393", "#943A4D",
"#B5F4FF", "#D2DCD5", "#9556BD", "#6A714A", "#001325", "#02525F", "#0AA3F7", "#E98176",
"#DBD5DD", "#5EBCD1", "#3D4F44", "#7E6405", "#02684E", "#962B75", "#8D8546", "#9695C5",
"#E773CE", "#D86A78", "#3E89BE", "#CA834E", "#518A87", "#5B113C", "#55813B", "#E704C4",
"#00005F", "#A97399", "#4B8160", "#59738A", "#FF5DA7", "#F7C9BF", "#643127", "#513A01",
"#6B94AA", "#51A058", "#A45B02", "#1D1702", "#E20027", "#E7AB63", "#4C6001", "#9C6966",
"#64547B", "#97979E", "#006A66", "#391406", "#F4D749", "#0045D2", "#006C31", "#DDB6D0",
"#7C6571", "#9FB2A4", "#00D891", "#15A08A", "#BC65E9", "#FFFFFE", "#C6DC99", "#203B3C",
"#671190", "#6B3A64", "#F5E1FF", "#FFA0F2", "#CCAA35", "#374527", "#8BB400", "#797868",
"#C6005A", "#3B000A", "#C86240", "#29607C", "#402334", "#7D5A44", "#CCB87C", "#B88183",
"#AA5199", "#B5D6C3", "#A38469", "#9F94F0", "#A74571", "#B894A6", "#71BB8C", "#00B433",
"#789EC9", "#6D80BA", "#953F00", "#5EFF03", "#E4FFFC", "#1BE177", "#BCB1E5", "#76912F",
"#003109", "#0060CD", "#D20096", "#895563", "#29201D", "#5B3213", "#A76F42", "#89412E",
"#1A3A2A", "#494B5A", "#A88C85", "#F4ABAA", "#A3F3AB", "#00C6C8", "#EA8B66", "#958A9F",
"#BDC9D2", "#9FA064", "#BE4700", "#658188", "#83A485", "#453C23", "#47675D", "#3A3F00",
"#061203", "#DFFB71", "#868E7E", "#98D058", "#6C8F7D", "#D7BFC2", "#3C3E6E", "#D83D66",
"#2F5D9B", "#6C5E46", "#D25B88", "#5B656C", "#00B57F", "#545C46", "#866097", "#365D25",
"#252F99", "#00CCFF", "#674E60", "#FC009C", "#92896B", "#1E2324", "#DEC9B2", "#9D4948",
"#85ABB4", "#342142", "#D09685", "#A4ACAC", "#00FFFF", "#AE9C86", "#742A33", "#0E72C5",
"#AFD8EC", "#C064B9", "#91028C", "#FEEDBF", "#FFB789", "#9CB8E4", "#AFFFD1", "#2A364C",
"#4F4A43", "#647095", "#34BBFF", "#807781", "#920003", "#B3A5A7", "#018615", "#F1FFC8",
"#976F5C", "#FF3BC1", "#FF5F6B", "#077D84", "#F56D93", "#5771DA", "#4E1E2A", "#830055",
"#02D346", "#BE452D", "#00905E", "#BE0028", "#6E96E3", "#007699", "#FEC96D", "#9C6A7D",
"#3FA1B8", "#893DE3", "#79B4D6", "#7FD4D9", "#6751BB", "#B28D2D", "#E27A05", "#DD9CB8",
"#AABC7A", "#980034", "#561A02", "#8F7F00", "#635000", "#CD7DAE", "#8A5E2D", "#FFB3E1",
"#6B6466", "#C6D300", "#0100E2", "#88EC69", "#8FCCBE", "#21001C", "#511F4D", "#E3F6E3",
"#FF8EB1", "#6B4F29", "#A37F46", "#6A5950", "#1F2A1A", "#04784D", "#101835", "#E6E0D0",
"#FF74FE", "#00A45F", "#8F5DF8", "#4B0059", "#412F23", "#D8939E", "#DB9D72", "#604143",
"#B5BACE", "#989EB7", "#D2C4DB", "#A587AF", "#77D796", "#7F8C94", "#FF9B03", "#555196",
"#31DDAE", "#74B671", "#802647", "#2A373F", "#014A68", "#696628", "#4C7B6D", "#002C27",
"#7A4522", "#3B5859", "#E5D381", "#FFF3FF", "#679FA0", "#261300", "#2C5742", "#9131AF",
"#AF5D88", "#C7706A", "#61AB1F", "#8CF2D4", "#C5D9B8", "#9FFFFB", "#BF45CC", "#493941",
"#863B60", "#B90076", "#003177", "#C582D2", "#C1B394", "#602B70", "#887868", "#BABFB0",
"#030012", "#D1ACFE", "#7FDEFE", "#4B5C71", "#A3A097", "#E66D53", "#637B5D", "#92BEA5",
"#00F8B3", "#BEDDFF", "#3DB5A7", "#DD3248", "#B6E4DE", "#427745", "#598C5A", "#B94C59",
"#8181D5", "#94888B", "#FED6BD", "#536D31", "#6EFF92", "#E4E8FF", "#20E200", "#FFD0F2",
"#4C83A1", "#BD7322", "#915C4E", "#8C4787", "#025117", "#A2AA45", "#2D1B21", "#A9DDB0",
"#FF4F78", "#528500", "#009A2E", "#17FCE4", "#71555A", "#525D82", "#00195A", "#967874",
"#555558", "#0B212C", "#1E202B", "#EFBFC4", "#6F9755", "#6F7586", "#501D1D", "#372D00",
"#741D16", "#5EB393", "#B5B400", "#DD4A38", "#363DFF", "#AD6552", "#6635AF", "#836BBA",
"#98AA7F", "#464836", "#322C3E", "#7CB9BA", "#5B6965", "#707D3D", "#7A001D", "#6E4636",
"#443A38", "#AE81FF", "#489079", "#897334", "#009087", "#DA713C", "#361618", "#FF6F01",
"#006679", "#370E77", "#4B3A83", "#C9E2E6", "#C44170", "#FF4526", "#73BE54", "#C4DF72",
"#ADFF60", "#00447D", "#DCCEC9", "#BD9479", "#656E5B", "#EC5200", "#FF6EC2", "#7A617E",
"#DDAEA2", "#77837F", "#A53327", "#608EFF", "#B599D7", "#A50149", "#4E0025", "#C9B1A9",
"#03919A", "#1B2A25", "#E500F1", "#982E0B", "#B67180", "#E05859", "#006039", "#578F9B",
"#305230", "#CE934C", "#B3C2BE", "#C0BAC0", "#B506D3", "#170C10", "#4C534F", "#224451",
"#3E4141", "#78726D", "#B6602B", "#200441", "#DDB588", "#497200", "#C5AAB6", "#033C61",
"#71B2F5", "#A9E088", "#4979B0", "#A2C3DF", "#784149", "#2D2B17", "#3E0E2F", "#57344C",
"#0091BE", "#E451D1", "#4B4B6A", "#5C011A", "#7C8060", "#FF9491", "#4C325D", "#005C8B",
"#E5FDA4", "#68D1B6", "#032641", "#140023", "#8683A9", "#CFFF00", "#A72C3E", "#34475A",
"#B1BB9A", "#B4A04F", "#8D918E", "#A168A6", "#813D3A", "#425218", "#DA8386", "#776133",
"#563930", "#8498AE", "#90C1D3", "#B5666B", "#9B585E", "#856465", "#AD7C90", "#E2BC00",
"#E3AAE0", "#B2C2FE", "#FD0039", "#009B75", "#FFF46D", "#E87EAC", "#DFE3E6", "#848590",
"#AA9297", "#83A193", "#577977", "#3E7158", "#C64289", "#EA0072", "#C4A8CB", "#55C899",
"#E78FCF", "#004547", "#F6E2E3", "#966716", "#378FDB", "#435E6A", "#DA0004", "#1B000F",
"#5B9C8F", "#6E2B52", "#011115", "#E3E8C4", "#AE3B85", "#EA1CA9", "#FF9E6B", "#457D8B",
"#92678B", "#00CDBB", "#9CCC04", "#002E38", "#96C57F", "#CFF6B4", "#492818", "#766E52",
"#20370E", "#E3D19F", "#2E3C30", "#B2EACE", "#F3BDA4", "#A24E3D", "#976FD9", "#8C9FA8",
"#7C2B73", "#4E5F37", "#5D5462", "#90956F", "#6AA776", "#DBCBF6", "#DA71FF", "#987C95",
"#52323C", "#BB3C42", "#584D39", "#4FC15F", "#A2B9C1", "#79DB21", "#1D5958", "#BD744E",
"#160B00", "#20221A", "#6B8295", "#00E0E4", "#102401", "#1B782A", "#DAA9B5", "#B0415D",
"#859253", "#97A094", "#06E3C4", "#47688C", "#7C6755", "#075C00", "#7560D5", "#7D9F00",
"#C36D96", "#4D913E", "#5F4276", "#FCE4C8", "#303052", "#4F381B", "#E5A532", "#706690",
"#AA9A92", "#237363", "#73013E", "#FF9079", "#A79A74", "#029BDB", "#FF0169", "#C7D2E7",
"#CA8869", "#80FFCD", "#BB1F69", "#90B0AB", "#7D74A9", "#FCC7DB", "#99375B", "#00AB4D",
"#ABAED1", "#BE9D91", "#E6E5A7", "#332C22", "#DD587B", "#F5FFF7", "#5D3033", "#6D3800",
"#FF0020", "#B57BB3", "#D7FFE6", "#C535A9", "#260009", "#6A8781", "#A8ABB4", "#D45262",
"#794B61", "#4621B2", "#8DA4DB", "#C7C890", "#6FE9AD", "#A243A7", "#B2B081", "#181B00",
"#286154", "#4CA43B", "#6A9573", "#A8441D", "#5C727B", "#738671", "#D0CFCB", "#897B77",
"#1F3F22", "#4145A7", "#DA9894", "#A1757A", "#63243C", "#ADAAFF", "#00CDE2", "#DDBC62",
"#698EB1", "#208462", "#00B7E0", "#614A44", "#9BBB57", "#7A5C54", "#857A50", "#766B7E",
"#014833", "#FF8347", "#7A8EBA", "#274740", "#946444", "#EBD8E6", "#646241", "#373917",
"#6AD450", "#81817B", "#D499E3", "#979440", "#011A12", "#526554", "#B5885C", "#A499A5",
"#03AD89", "#B3008B", "#E3C4B5", "#96531F", "#867175", "#74569E", "#617D9F", "#E70452",
"#067EAF", "#A697B6", "#B787A8", "#9CFF93", "#311D19", "#3A9459", "#6E746E", "#B0C5AE",
"#84EDF7", "#ED3488", "#754C78", "#384644", "#C7847B", "#00B6C5", "#7FA670", "#C1AF9E",
"#2A7FFF", "#72A58C", "#FFC07F", "#9DEBDD", "#D97C8E", "#7E7C93", "#62E674", "#B5639E",
"#FFA861", "#C2A580", "#8D9C83", "#B70546", "#372B2E", "#0098FF", "#985975", "#20204C",
"#FF6C60", "#445083", "#8502AA", "#72361F", "#9676A3", "#484449", "#CED6C2", "#3B164A",
"#CCA763", "#2C7F77", "#02227B", "#A37E6F", "#CDE6DC", "#CDFFFB", "#BE811A", "#F77183",
"#EDE6E2", "#CDC6B4", "#FFE09E", "#3A7271", "#FF7B59", "#4E4E01", "#4AC684", "#8BC891",
"#BC8A96", "#CF6353", "#DCDE5C", "#5EAADD", "#F6A0AD", "#E269AA", "#A3DAE4", "#436E83",
"#002E17", "#ECFBFF", "#A1C2B6", "#50003F", "#71695B", "#67C4BB", "#536EFF", "#5D5A48",
"#890039", "#969381", "#371521", "#5E4665", "#AA62C3", "#8D6F81", "#2C6135", "#410601",
"#564620", "#E69034", "#6DA6BD", "#E58E56", "#E3A68B", "#48B176", "#D27D67", "#B5B268",
"#7F8427", "#FF84E6", "#435740", "#EAE408", "#F4F5FF", "#325800", "#4B6BA5", "#ADCEFF",
"#9B8ACC", "#885138", "#5875C1", "#7E7311", "#FEA5CA", "#9F8B5B", "#A55B54", "#89006A",
"#AF756F", "#2A2000", "#576E4A", "#7F9EFF", "#7499A1", "#FFB550", "#00011E", "#D1511C",
"#688151", "#BC908A", "#78C8EB", "#8502FF", "#483D30", "#C42221", "#5EA7FF", "#785715",
"#0CEA91", "#FFFAED", "#B3AF9D", "#3E3D52", "#5A9BC2", "#9C2F90", "#8D5700", "#ADD79C",
"#00768B", "#337D00", "#C59700", "#3156DC", "#944575", "#ECFFDC", "#D24CB2", "#97703C",
"#4C257F", "#9E0366", "#88FFEC", "#B56481", "#396D2B", "#56735F", "#988376", "#9BB195",
"#A9795C", "#E4C5D3", "#9F4F67", "#1E2B39", "#664327", "#AFCE78", "#322EDF", "#86B487",
"#C23000", "#ABE86B", "#96656D", "#250E35", "#A60019", "#0080CF", "#CAEFFF", "#323F61",
"#A449DC", "#6A9D3B", "#FF5AE4", "#636A01", "#D16CDA", "#736060", "#FFBAAD", "#D369B4",
"#FFDED6", "#6C6D74", "#927D5E", "#845D70", "#5B62C1", "#2F4A36", "#E45F35", "#FF3B53",
"#AC84DD", "#762988", "#70EC98", "#408543", "#2C3533", "#2E182D", "#323925", "#19181B",
"#2F2E2C", "#023C32", "#9B9EE2", "#58AFAD", "#5C424D", "#7AC5A6", "#685D75", "#B9BCBD",
"#834357", "#1A7B42", "#2E57AA", "#E55199", "#316E47", "#CD00C5", "#6A004D", "#7FBBEC",
"#F35691", "#D7C54A", "#62ACB7", "#CBA1BC", "#A28A9A", "#6C3F3B", "#FFE47D", "#DCBAE3",
"#5F816D", "#3A404A", "#7DBF32", "#E6ECDC", "#852C19", "#285366", "#B8CB9C", "#0E0D00",
"#4B5D56", "#6B543F", "#E27172", "#0568EC", "#2EB500", "#D21656", "#EFAFFF", "#682021",
"#2D2011", "#DA4CFF", "#70968E", "#FF7B7D", "#4A1930", "#E8C282", "#E7DBBC", "#A68486",
"#1F263C", "#36574E", "#52CE79", "#ADAAA9", "#8A9F45", "#6542D2", "#00FB8C", "#5D697B",
"#CCD27F", "#94A5A1", "#790229", "#E383E6", "#7EA4C1", "#4E4452", "#4B2C00", "#620B70",
"#314C1E", "#874AA6", "#E30091", "#66460A", "#EB9A8B", "#EAC3A3", "#98EAB3", "#AB9180",
"#B8552F", "#1A2B2F", "#94DDC5", "#9D8C76", "#9C8333", "#94A9C9", "#392935", "#8C675E",
"#CCE93A", "#917100", "#01400B", "#449896", "#1CA370", "#E08DA7", "#8B4A4E", "#667776",
"#4692AD", "#67BDA8", "#69255C", "#D3BFFF", "#4A5132", "#7E9285", "#77733C", "#E7A0CC",
"#51A288", "#2C656A", "#4D5C5E", "#C9403A", "#DDD7F3", "#005844", "#B4A200", "#488F69",
"#858182", "#D4E9B9", "#3D7397", "#CAE8CE", "#D60034", "#AA6746", "#9E5585", "#BA6200"
};
```
|
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 "\_":
```
public MyType(int arg)
{
_arg = arg;
}
```
|
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 useTimezone, serverTimzone, useGmtMillisForDatetimes, useLegacyDatetimeCode, ...
|
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.getTimeZone("UTC")));
* either synchronize your servers with NTP, or rely only on the database server to tell you what time it is.
---
The long answer is this:
When dealing with dates and timezones in any database and with any client code, I usually recommend the following policy:
1. **Configure your database to use UTC timezone**, instead of using the server's local timezone (unless it is UTC of course).
* How to do so depends on your database server. Instructions for MySQL can be found here: <http://dev.mysql.com/doc/refman/5.0/en/time-zone-support.html>. Basically you need to write this in my.cnf: default-time-zone=utc
* This way you can host your database servers anywhere, change your hosting location easily, and more generally manipulate dates on your servers without any ambiguity.
* If you really prefer to use a local timezone, I recommend at least turning off Daylight Saving Time, because having ambiguous dates in your database can be a real nightmare.
+ *For example, if you are building a telephony service and you are using Daylight Saving Time on your database server then you are asking for trouble: there will be no way to tell whether a customer who called from "2008-10-26 02:30:00" to "2008-10-26 02:35:00" actually called for 5 minutes or for 1 hour and 5 minutes (supposing Daylight Saving occurred on Oct. 26th at 3am)!*
2. **Inside your application code, always use UTC dates, except when displaying dates to your users.**
* In Java, when reading from the database, always use:
Timestamp myDate = resultSet.getTimestamp("my\_date", Calendar.getInstance(TimeZone.getTimeZone("UTC")));
* If you do not do this, the timestamp will be assumed to be in your local TimeZone, instead of UTC.
3. **Synchronize your servers or only rely on the database server's time**
* If you have your Web server on one server (or more) and your database server on some other server, then I strongly recommend you synchronize their clocks with NTP.
* OR, only rely on one server to tell you what time it is. Usually, the database server is the best one to ask for time. In other words, avoid code such as this:
preparedStatement = connection.prepareStatement("UPDATE my\_table SET my\_time = ? WHERE [...]");
java.util.Date now = new java.util.Date(); // local time! :-(
preparedStatement.setTimestamp(1, new Timestamp(now.getTime()));
int result = preparedStatement.execute();
* Instead, rely on the database server's time:
preparedStatement = connection.prepareStatement("UPDATE my\_table SET my\_time = NOW() WHERE [...]");
int result = preparedStatement.execute();
Hope this helps! :-)
|
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 make it look like the same local time in the database's time zone.
Example: Your database if configured to UTC. Your application is EST. You pass a java.util.Date object for 5:00 (EST). The database will convert it to 5:00 UTC and store it. Awesome.
You'd have to adjust the time before you pass the data to "undo" this automatic adjustment. Something like...
```
long originalTime = originalDate.getTime();
Date newDate = new Date(originalTime - TimeZone.getDefault().getOffset(originalTime));
ps.setDate(1, newDate);
```
Reading the data back out requires a similar conversion..
```
long dbTime = rs.getTimestamp(1).getTime();
Date originalDate = new Date(dbTime + TimeZone.getDefault().getOffset(dbTime));
```
Here's another fun quirk...
> In Java, when reading from the database, always use: Timestamp myDate
> = resultSet.getTimestamp("my\_date", Calendar.getInstance(TimeZone.getTimeZone("UTC")));
MySql actually ignores that Calendar parameter. This returns the same value regardless of what calendar you pass it.
|
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;
$newheight = 197;
$thumb = imagecreatetruecolor($newwidth, $newheight);
imagealphablending($thumb, true);
$source = imagecreatefrompng($fileName);
imagealphablending($source, true);
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
imagesavealpha($thumb, true);
imagepng($thumb,$newFilename);
```
|
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, $newheight, $width, $height);
imagepng($thumb,$newFilename);
```
I found the output image quality much better using `imagecopyresampled()` than `imagecopyresized()`
|
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($image, 0, 0, $trans_layer_overlay);
```
|
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="wikiedit" action="[[script_name]]" method="post">
<textarea name="content" rows="25" cols="90" wrap="virtual">[[content]]</textarea>
<input type="button" onclick="document.wikiedit.content.wrap='off';" value="No Wrap">
<input type="submit" value="Save">
</form>
```
It works with IE, but not with Firefox or Opera. How should I do this?
|
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.setAttribute('wrap', wrap);
var newarea= area.cloneNode(true);
newarea.value= area.value;
area.parentNode.replaceChild(newarea, area);
}
}
```
Unrelated: try to avoid accessing elements straight out of the document object, it is unreliable on some browsers and causes name clash problems. ‘document.forms.wikiedit’ is better, and moving to ‘id’ on the form instead of ‘name’ and then using ‘document.getElementById('wikiedit')’ better still.
form.elements.content is also more reliable than form.content for similar reasons... or, indeed, you could give the textarea an ID and go straight to the textarea with getElementById without having to bother look at the form.
|
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.style.whiteSpace = 'pre';
textarea.style.overflow = 'auto';
}
</script>
<form name="wikiedit" action="[[script_name]]" method="post">
<textarea name="content" rows="25" cols="90" wrap="virtual">[[content]]</textarea>
<input type="button" onclick="setNoWrap(this);" value="No Wrap">
<input type="submit" value="Save">
</form>
```
|
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
```
I wonder if there is any way to get the final SQL statment as a String, which should look like this:
```
UPDATE someTable SET Value = "myValue" WHERE Id = 1234
```
If anyone wonders why I would do this:
* for logging (failed) statements
* for having the possibility to copy & paste it to the Enterprise Manager for testing purposes
|
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 the "text" command doesn't account for parameters etc
```
public static String ParameterValueForSQL(this SqlParameter sp)
{
String retval = "";
switch (sp.SqlDbType)
{
case SqlDbType.Char:
case SqlDbType.NChar:
case SqlDbType.NText:
case SqlDbType.NVarChar:
case SqlDbType.Text:
case SqlDbType.Time:
case SqlDbType.VarChar:
case SqlDbType.Xml:
case SqlDbType.Date:
case SqlDbType.DateTime:
case SqlDbType.DateTime2:
case SqlDbType.DateTimeOffset:
retval = "'" + sp.Value.ToString().Replace("'", "''") + "'";
break;
case SqlDbType.Bit:
retval = (sp.Value.ToBooleanOrDefault(false)) ? "1" : "0";
break;
default:
retval = sp.Value.ToString().Replace("'", "''");
break;
}
return retval;
}
public static String CommandAsSql(this SqlCommand sc)
{
StringBuilder sql = new StringBuilder();
Boolean FirstParam = true;
sql.AppendLine("use " + sc.Connection.Database + ";");
switch (sc.CommandType)
{
case CommandType.StoredProcedure:
sql.AppendLine("declare @return_value int;");
foreach (SqlParameter sp in sc.Parameters)
{
if ((sp.Direction == ParameterDirection.InputOutput) || (sp.Direction == ParameterDirection.Output))
{
sql.Append("declare " + sp.ParameterName + "\t" + sp.SqlDbType.ToString() + "\t= ");
sql.AppendLine(((sp.Direction == ParameterDirection.Output) ? "null" : sp.ParameterValueForSQL()) + ";");
}
}
sql.AppendLine("exec [" + sc.CommandText + "]");
foreach (SqlParameter sp in sc.Parameters)
{
if (sp.Direction != ParameterDirection.ReturnValue)
{
sql.Append((FirstParam) ? "\t" : "\t, ");
if (FirstParam) FirstParam = false;
if (sp.Direction == ParameterDirection.Input)
sql.AppendLine(sp.ParameterName + " = " + sp.ParameterValueForSQL());
else
sql.AppendLine(sp.ParameterName + " = " + sp.ParameterName + " output");
}
}
sql.AppendLine(";");
sql.AppendLine("select 'Return Value' = convert(varchar, @return_value);");
foreach (SqlParameter sp in sc.Parameters)
{
if ((sp.Direction == ParameterDirection.InputOutput) || (sp.Direction == ParameterDirection.Output))
{
sql.AppendLine("select '" + sp.ParameterName + "' = convert(varchar, " + sp.ParameterName + ");");
}
}
break;
case CommandType.Text:
sql.AppendLine(sc.CommandText);
break;
}
return sql.ToString();
}
```
this generates output along these lines...
```
use dbMyDatabase;
declare @return_value int;
declare @OutTotalRows BigInt = null;
exec [spMyStoredProc]
@InEmployeeID = 1000686
, @InPageSize = 20
, @InPage = 1
, @OutTotalRows = @OutTotalRows output
;
select 'Return Value' = convert(varchar, @return_value);
select '@OutTotalRows' = convert(varchar, @OutTotalRows);
```
|
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, but under the hood, can be set up to work with either an SVN or CVS repository?
I'm aiming to develop such a library in either .NET or Java (most likely .NET), but I wanted to get some thoughts on how feasible this would be, and if there's a better way to approach the problem.
The context of this is: I'm building a web-based service that will involve source control hosting, and I want to support both SVN and CVS so as to serve the largest amount of developers possible.
|
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.begin(); pm_it != port_map.end(); pm_it++)
{
if (pm_it->second == delete_this_id) {
port_map.erase(pm_it->first);
}
}
```
UPDATE: Of course, I then [read this question](https://stackoverflow.com/questions/52714/stl-vector-vs-map-erase) which I didn't think would be related but answers my question.
|
## 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);
}
else
{
++pm_it;
}
}
```
## C++03
Erasing elements in a map does not invalidate any iterators.
(apart from iterators on the element that was deleted)
Actually inserting or deleting does not invalidate any of the iterators:
Also see this answer:
[Mark Ransom Technique](https://stackoverflow.com/a/180616/14065)
But you do need to update your code:
In your code you increment pm\_it after calling erase. At this point it is too late and is already invalidated.
```
map<string, SerialdMsg::SerialFunction_t>::iterator pm_it = port_map.begin();
while(pm_it != port_map.end())
{
if (pm_it->second == delete_this_id)
{
port_map.erase(pm_it++); // Use iterator.
// Note the post increment.
// Increments the iterator but returns the
// original value for use by erase
}
else
{
++pm_it; // Can use pre-increment in this case
// To make sure you have the efficient version
}
}
```
|
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()
{
StringsMapIter itBegin = m_TheMap.begin();
StringsMapIter itEnd = m_TheMap.end();
StringsMapIter itTemp;
while (itBegin != itEnd)
{
if (IsTheOneToDelete(itBegin->second)) // Criteria checking here
{
itTemp = itBegin; // Keep a reference to the iter
++itBegin; // Advance in the map
m_TheMap.erase(itTemp); // Erase it !!!
}
else
++itBegin; // Just move on ...
}
}
```
|
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 corruption. Is there any way to know the last line of Python source code it executed, given a core file? Or if it is attached in GDB? I realize it is probably all compiled bytecode, but I'm hoping there someone out there may have dealt with this. Currently it is running with the trace module active and we're hoping it will happen again, but it could be a long while.
|
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 defined in the python [gdbinit](http://svn.python.org/view/python/trunk/Misc/gdbinit?view=auto) file, but it's not working for me. It's discussed [here](http://wiki.python.org/moin/DebuggingWithGdb) if you want to look into it.
Also, if you suspect memory issues, it's worth noting that you can use [`valgrind`](http://valgrind.org/) with python, if you're prepared to recompile it. The procedure is described [here.](http://svn.python.org/projects/python/trunk/Misc/README.valgrind)
|
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, then you can [import gc](http://www.python.org/doc/2.5.2/lib/module-gc.html) and enable debugging which you can then put out to a log file.
To specifically answer your question regarding debugging with GDB you might want to read "[Debugging With GDB](http://wiki.python.org/moin/DebuggingWithGdb)" on the python wiki.
|
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 strings is much faster for small strings
string tmp = "";
for (int j = 0; j < 1000; j++)
{
tmp += i.ToString();
i++;
}
fraction += tmp;
}
```
**EDIT:** Some people suggested using `StringBuilder`, which is an excellent suggestion also, and this comes out at 0.06s:
```
int i = 1;
StringBuilder fraction = new StringBuilder();
while (fraction.Length < 1000000)
{
fraction.Append(i);
i++;
}
```
Playing around to find the optimum value of `j` is a topic for another time, but why exactly does this non-obvious optimisation work so well? Also, on a related topic, I've heard it said that you should never use the `+` operator with strings, in favour of `string.Format()`, is this true?
|
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 compared to what you usually do with streams, you use a buffer. Larger chunks will usually result in better performance until you hit the critical size where it no longer makes any difference, and starts to be a downside when your handling small amounts of data.
If you however would have defined a char-array with the appropriate size from the beginning, it would probably be blazing fast, because then it won't have to copy it over and over again.
|
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 box to be usefully measurable.
```
using System;
using System.Diagnostics;
using System.Text;
public class Test
{
const int Limit = 4000000;
static void Main()
{
Time(Concatenation, "Concat");
Time(SimpleStringBuilder, "StringBuilder as in post");
Time(SimpleStringBuilderNoToString, "StringBuilder calling Append(i)");
Time(CapacityStringBuilder, "StringBuilder with appropriate capacity");
}
static void Time(Action action, string name)
{
Stopwatch sw = Stopwatch.StartNew();
action();
sw.Stop();
Console.WriteLine("{0}: {1}ms", name, sw.ElapsedMilliseconds);
GC.Collect();
GC.WaitForPendingFinalizers();
}
static void Concatenation()
{
int i = 1;
string fraction = "";
while (fraction.Length < Limit)
{
// concatenating strings is much faster for small strings
string tmp = "";
for (int j = 0; j < 1000; j++)
{
tmp += i.ToString();
i++;
}
fraction += tmp;
}
}
static void SimpleStringBuilder()
{
int i = 1;
StringBuilder fraction = new StringBuilder();
while (fraction.Length < Limit)
{
fraction.Append(i.ToString());
i++;
}
}
static void SimpleStringBuilderNoToString()
{
int i = 1;
StringBuilder fraction = new StringBuilder();
while (fraction.Length < Limit)
{
fraction.Append(i);
i++;
}
}
static void CapacityStringBuilder()
{
int i = 1;
StringBuilder fraction = new StringBuilder(Limit + 10);
while (fraction.Length < Limit)
{
fraction.Append(i);
i++;
}
}
}
```
And the results:
```
Concat: 5879ms
StringBuilder as in post: 206ms
StringBuilder calling Append(i): 196ms
StringBuilder with appropriate capacity: 184ms
```
The reason your concatenation is faster than the very first solution is simple though - you're doing several "cheap" concatenations (where relatively little data is being copied each time) and relatively few "large" concatenations (of the whole string so far). In the original, *every step* would copy all of the data obtained so far, which is obviously more expensive.
|
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 thoughts / experiences with this product?
|
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. You only have to write few lines of code to build complete and really good administration panel.
The only thing I didn't like about this framework is that you can't really control everything (things going under the hood) and the fact that it doesn't have support for UNIX TIMESTAMPS (I've tried to generate date field but it didn't want to accept time stamp so I had to change some things, add a class).
ATK community is really great, and with my co-worker helping me - I've learned lots of things about this framework in only 3 hours.
**HOWEVER** if you're looking for universal framework to code your whole site - you might want to avoid this one.
Personally, I'm going to go (really soon) for ATK+Zend Framework combo - ATK for backend and Zend for frontend.
|
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. Django is a better general framework. But I found ATK to be a more thorough business logic framework. Django's admin interface is only meant to be rough back end interface for managing a websites content it's original design isn't meant to be the front end for a large database driven website.
For creating a web interface to a data centric database (out of the box) ATK seems to better match what is necessary to create a complete UI. The biggest problem with them both is when you will want to do things that aren't part of the framework. Either one will some times seem to fight you from doing things you know you should be able to do.
ATK Cons
* Small Dev Team (But reasonably responsive)
* Lack of Marketing (no buz)
* Small User Base (Getting help)
* PHP (Python is the current craze but there isn't anything wrong with PHP)
* Documentation (Limited but after working through the tutorial most of it is API after that.)
If I were to start a project today I might pick either one. If the project were small with few table relationships and I knew ahead of time a custom user ui was necessary I'd pick Django. Think a simple personal bank register. If I were to start a project with many table relationships and the database admin was the user interface then I'd pick ATK. Think customer management with invoicing. If I were to start a highly complex project where I might need to do some things not thought of by the framework architects then I'd pick a more general and open framework like Pyramid or Ruby on Rails (still trying to answer this one myself). Think electronic medical record.
|
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 functions in Windows Win32 API.
Thanks in advance.
/Robert
|
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 file system filter via the
> VxD service,
> IFSMGR\_InstallFileSystemApiHook, to
> insert itself onto the call chain of
> all file system requests. On Windows
> NT the heart of FileMon is a file
> system driver that creates and
> attaches filter device objects to
> target file system device objects so
> that FileMon will see all IRPs and
> FastIO requests directed at drives.
> When FileMon sees an open, create or
> close call, it updates an internal
> hash table that serves as the mapping
> between internal file handles and file
> path names. Whenever it sees calls
> that are handle based, it looks up the
> handle in the hash table to obtain the
> full name for display. If a
> handle-based access references a file
> opened before FileMon started, FileMon
> will fail to find the mapping in its
> hash table and will simply present the
> handle's value instead.
-Adam
|
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 :
```
pattern = Pattern.compile(
"^(.+?)" +
File.separator +
"js" +
File.separator +
"(.+?).js$" );
```
Throwing
```
java.util.regex.PatternSyntaxException: Illegal/unsupported escape sequence
```
Is there any way to use a common regular expression that works in both Windows and UNIX systems ?
|
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 them to their special meaning or lead to a [PatternSyntaxException](http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex/PatternSyntaxException.html). *(Thanks [Alan M](https://stackoverflow.com/users/20938/alan-m) for pointing this out in the comments!)*
|
> 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 permits those characters in a file or directory name.
|
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:
```
private static int[] unique(int[] ids)
{
IDictionary<int, object> d = new Dictionary<int, object>();
foreach(int i in ids)
d[i] = null;
int[] results = new int[d.Count];
int j = 0;
foreach(int id in d.Keys)
results[j++] = id;
return results;
}
```
|
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:
```
int[] x = new[] { 1, 4, 23, 4, 1 };
int[] distinct = x.Distinct().ToArray();
// distinct is now { 1, 4, 23 } (but not necessarily in that order)
```
|
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);
vals.Add(2);
...
vals.Sort();
List<int> uniques = new List<int>();
vals.ForEach(delegate(int v) {
if (!uniques.Contains(v)) uniques.Add(v);
});
```
|
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 error logging macro. I really do not want my source's full path making its way into the executable.
|
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 -o file.o src/file.c
```
This will allow you to use `MYFILE` in your code instead of `__FILE__`.
The use of `basename` of the source file `$<` means you can use it in generalized rules such as `.c.o`. The following code illustrates how it works. First, a `makefile`:
```
mainprog: main.o makefile
gcc -o mainprog main.o
main.o: src/main.c makefile
gcc "-DMYFILE=\"`basename $<`\"" -c -o main.o src/main.c
```
Then a file in a subdirectory, `src/main.c`:
```
#include <stdio.h>
int main (int argc, char *argv[]) {
printf ("file = %s\n", MYFILE);
return 0;
}
```
Finally, a transcript showing it running:
```
pax:~$ mainprog
file = main.c
```
Note the `file =` line which contains *only* the base name of the file, not the directory name as well.
|
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 and $(shell basename $<)
Edit: If you use a #define or the -D option, you should create your own new name and not try to redefine `__FILE__`.
|
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 anything.
Other than polling how can I do a similar thing in Google Chrome?
|
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 just under 512 bytes when it worked.
|
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 picking the data from another XML document that represents our current account and copying the data into a transient XML DOM document.
What I'd like to do is clone the relevant node of the account document (i.e. customer info) and use it as the basis for the transform. I don't want to use the account document directly as I'd like to be able to add transform specific input, without making changes to the account object.
How efficient is using .cloneNode(true) for a desired node of about typically less than 200 elements from a document of typically 2000+ elements? The target platform is IE6 with no external tools (i.e. ActiveX).
|
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 require fairly significant mods the XSL though.
|
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 will actually return, try replacing the url with this in the Address Bar of one of your pages, and press enter.
```
javascript:'<xmp>'+window.document.body.outerHTML+'</xmp>';
```
If you are happy with the results, great!, but I think you'll end up less than satisfied at what IE returns (both in the DOM, and this "string" value equivelant.
|
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 able to use the databinding syntax so I won't have to use Labels or Literals. Something like:
```
<div>
Wheels: <%# (int)Eval("Wheels") %><br />
Model: <%# (string)Eval("Model") %>
</div>
```
Does anybody know about a control out there that does just that?
And I am not ready to switch to ASP.NET MVC just yet.
---
Unfortunately, the DetailsView control doesn't satisfy my needs because it doesn't seem to support the template-style syntax that I am after. It, too, needs to be bound to a DataSource object of a kind.
I liked better the solution Maxim and Torkel suggested. I will try to go for that.
|
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>
```
That allow you to have type safety. Just make sure to have a valid object assigned before the actual rendering.
|
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 not to be actively maintained so heavily any more.
Are there any alternatives that are more actively maintained and more reliable?
|
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 example, given `2` the result should be `Visible`.
|
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 start the container as:
```
>startup.bat -Dcom.sun.management.jmxremote
```
You could then start JConsole as a standalone application
```
>jconsole
```
and then attach jconsole to the Java process that is running Tomcat.
Similar steps apply to other application servers.
|
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=009a8ca0 esi=09fbf698 edi=09fbf594
eip=005ae2f7 esp=09fbf4a4 ebp=09fbf594 iopl=0 nv up ei ng nz na pe nc
cs=001b ss=0023 ds=0023 es=0023 fs=003b gs=0000 efl=00010286
TestApplication!std::_Container_base::_Orphan_all+0x57:
005ae2f7 c70100000000 mov dword ptr [ecx],0 ds:0023:dddddddd=????????
```
Call stack:
```
TestApplication!std::_Container_base::_Orphan_all+0x57
TestApplication!std::vector >::operator=+0x37
TestApplication!boost::asio::detail::win_iocp_io_service::do_one+0x189
TestApplication!boost::asio::detail::win_iocp_io_service::run+0xa2
TestApplication!boost::asio::io_service::run+0x3a
```
|
**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 read / write from an illegal memory location.
3. Access violations are serious coz it could be corrupting some memory which is critical for your program and this would be the likely reason that your program hangs.
4. From the faulting instruction it seems as if you are trying to get the contents of a 4 byte value from an illegal instruction.
**Debugging the Problem**
5. If this is your code then you can easily debug this issue by setting the debug symbol location to the output folder of your compiler (this would contain the relevant pdb files)
6. When you get this exception get the call stack (one of the view windows would have it)
7. This would show you the location in your code where the faulting stack has originated.
8. Now open the file that contains this source and set a breakpoint there and the program would hit this point and stop inside the windebugger. Debug from this point and you would know exactly from which line of code this violation is thrown
Tip : Boost comes with source so you can easily put a break point inside this code. Be sure to press F11 while debugging when you get to asio::detail::win\_iocp\_io\_service::do\_one.
|
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 makes sense to use one over the other.
Any help would be useful.
|
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 recommend reading about the [Enterprise Integration Patterns](http://www.enterpriseintegrationpatterns.com/toc.html) which gives an overview of common patterns you'll tend to use in integration problems which are all based above a message bus (though can be used with other networking technologies too).
For example using open source; [Apache ActiveMQ](http://activemq.apache.org/) provides a loosely coupled reliable exchange of messages. Then you can use [Apache Camel](http://activemq.apache.org/camel/) to implement the [Enterprise Integration Patterns](http://activemq.apache.org/camel/enterprise-integration-patterns.html) for smart routing, transformation, orchestration, [working with other technologies](http://activemq.apache.org/camel/components.html) and so forth.
|
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 for data/events distribution at customized level of QoSs (according to the specific vendor implementation), instead ESBs represent solutions providing capabilities to realize complex orchestrations in a SOA scenario (where we have multiple providers offering their services, and multiple consumers interested in consuming the services offered by the first ones).
Complex orchestrations imply communication between legacy systems, everyone of these with its own data domain representation (rules and services on specific data) and its own communication paradigm (one consumer interact with the ESB using CORBA, another one using WS, and so on).
It is clear that ESB represents a more complex architectural solution aimed to provide the abstraction of **data-bus** (such as the electronic buses that everyone have in his own pc), able to connect a plethora of service providers to a not well specified plethora of service consumers, **hiding heterogeneity** in (i) data representation and (ii) communication.
Sorry for the long post, but the concepts are complex and it is very difficult to be effective and efficient in a short statement.
|
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 this? For example, can I substitute a stub for `System.exit()`?
The class in question is actually a command-line tool which I'm attempting to test inside JUnit. Maybe JUnit is simply not the right tool for the job? Suggestions for complementary regression testing tools are welcome (preferably something that integrates well with JUnit and EclEmma).
|
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 catcher and shut your script down (unless you decide to catch it somewhere along the way, which might be useful someday).
>
> In the JUnit scenario it will be caught by the JUnit framework, which will report that such-and-such test failed and move smoothly along to the next.
> * Prevent `System.exit()` to actually exit the JVM:
>
> Try modifying the TestCase to run with a security manager that prevents calling System.exit, then catch the SecurityException.
```
public class NoExitTestCase extends TestCase
{
protected static class ExitException extends SecurityException
{
public final int status;
public ExitException(int status)
{
super("There is no escape!");
this.status = status;
}
}
private static class NoExitSecurityManager extends SecurityManager
{
@Override
public void checkPermission(Permission perm)
{
// allow anything.
}
@Override
public void checkPermission(Permission perm, Object context)
{
// allow anything.
}
@Override
public void checkExit(int status)
{
super.checkExit(status);
throw new ExitException(status);
}
}
@Override
protected void setUp() throws Exception
{
super.setUp();
System.setSecurityManager(new NoExitSecurityManager());
}
@Override
protected void tearDown() throws Exception
{
System.setSecurityManager(null); // or save and restore original
super.tearDown();
}
public void testNoExit() throws Exception
{
System.out.println("Printing works");
}
public void testExit() throws Exception
{
try
{
System.exit(42);
} catch (ExitException e)
{
assertEquals("Exit status", 42, e.status);
}
}
}
```
---
Update December 2012:
[Will](https://stackoverflow.com/users/557117/will) proposes [in the comments](https://stackoverflow.com/questions/309396/java-how-to-test-methods-that-call-system-exit/309427#comment19186122_309427) using [**System Rules**](https://stefanbirkner.github.io/system-rules), a collection of JUnit(4.9+) rules for testing code which uses `java.lang.System`.
This was initially mentioned by **[Stefan Birkner](https://stackoverflow.com/users/557091/stefan-birkner)** in [his answer](https://stackoverflow.com/a/8658497/6309) in December 2011.
```
System.exit(…)
```
> Use the [`ExpectedSystemExit`](https://stefanbirkner.github.io/system-rules/#ExpectedSystemExit) rule to verify that `System.exit(…)` is called.
> You could verify the exit status, too.
For instance:
```
public void MyTest {
@Rule
public final ExpectedSystemExit exit = ExpectedSystemExit.none();
@Test
public void noSystemExit() {
//passes
}
@Test
public void systemExitWithArbitraryStatusCode() {
exit.expectSystemExit();
System.exit(0);
}
@Test
public void systemExitWithSelectedStatusCode0() {
exit.expectSystemExitWithStatus(0);
System.exit(0);
}
}
```
---
2023: [Emmanuel Bourg](https://stackoverflow.com/users/525725/emmanuel-bourg) reports in [the comments](https://stackoverflow.com/questions/309396/how-to-test-methods-that-call-system-exit/309427#comment136226933_309427):
> For this to work with Java 21 this system property must be set `-Djava.security.manager=allow`
|
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(() -> {
//the code under test, which calls System.exit(...);
});
}
@Test
public void systemExitWithSelectedStatusCode0() {
int status = SystemLambda.catchSystemExit(() -> {
//the code under test, which calls System.exit(0);
});
assertEquals(0, status);
}
}
```
For Java 5 to 7 the library [System Rules](https://stefanbirkner.github.com/system-rules/) has a JUnit rule called ExpectedSystemExit. With this rule you are able to test code, that calls System.exit(...):
```
public class MyTest {
@Rule
public final ExpectedSystemExit exit = ExpectedSystemExit.none();
@Test
public void systemExitWithArbitraryStatusCode() {
exit.expectSystemExit();
//the code under test, which calls System.exit(...);
}
@Test
public void systemExitWithSelectedStatusCode0() {
exit.expectSystemExitWithStatus(0);
//the code under test, which calls System.exit(0);
}
}
```
Full disclosure: I'm the author of both libraries.
|
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 folder
3. Go the folder (refer step 2) and run ez\_setup.py from the corresponding dos (command) prompt
4. Ensure that your PATH includes the appropriate C:\Python2X\Scripts directory
Second Option:
1. Download [setuptools-0.6c9.tar.gz](https://pypi.org/project/setuptools/0.6c9/)
2. Download [setuptools-0.6c9-py2.6.egg](http://pypi.python.org/packages/2.6/s/setuptools/setuptools-0.6c9-py2.6.egg#md5=ca37b1ff16fa2ede6e19383e7b59245a) to a folder(directory) outside your Windows Python installation folder
3. Use [7-zip](http://www.7-zip.org/) to extract ez\_setup.py in the same folder as [setuptools-0.6c9-py2.6.egg](http://pypi.python.org/packages/2.6/s/setuptools/setuptools-0.6c9-py2.6.egg#md5=ca37b1ff16fa2ede6e19383e7b59245a)
4. Go to the corresponding dos prompt and run python ez\_setup.py setuptools-0.6c9-py2.6.egg from the command prompt
5. Ensure that your PATH includes the appropriate C:\Python2X\Scripts directory
Third Option (assuming that you have Visual Studio 2005 or MinGW on your machine)
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 folder
3. Go the folder (refer step 2) and run python setup.py install from the corresponding dos (command) prompt
Please provide feedback.
|
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 latest version - the script also does some md5 checking, I haven't looked into it any further.
|
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 to a `String`?
```
public String convertStreamToString(InputStream is) {
// ???
}
```
|
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 close inputStream, you'll have to use try-with-resources for that
String theString = IOUtils.toString(inputStream, encoding);
```
Alternatively, you could use `ByteArrayOutputStream` if you don't want to mix your Streams and Writers.
|
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. Using `CharStreams` (Guava)
```
String result = CharStreams.toString(new InputStreamReader(
inputStream, Charsets.UTF_8));
```
3. Using `Scanner` (JDK)
```
Scanner s = new Scanner(inputStream).useDelimiter("\\A");
String result = s.hasNext() ? s.next() : "";
```
4. Using **Stream API** (Java 8). **Warning**: This solution converts different line breaks (like `\r\n`) to `\n`.
```
String result = new BufferedReader(new InputStreamReader(inputStream))
.lines().collect(Collectors.joining("\n"));
```
5. Using **parallel Stream API** (Java 8). **Warning**: This solution converts different line breaks (like `\r\n`) to `\n`.
```
String result = new BufferedReader(new InputStreamReader(inputStream))
.lines().parallel().collect(Collectors.joining("\n"));
```
6. Using `InputStreamReader` and `StringBuilder` (JDK)
```
int bufferSize = 1024;
char[] buffer = new char[bufferSize];
StringBuilder out = new StringBuilder();
Reader in = new InputStreamReader(stream, StandardCharsets.UTF_8);
for (int numRead; (numRead = in.read(buffer, 0, buffer.length)) > 0; ) {
out.append(buffer, 0, numRead);
}
return out.toString();
```
7. Using `StringWriter` and `IOUtils.copy` (Apache Commons)
```
StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, "UTF-8");
return writer.toString();
```
8. Using `ByteArrayOutputStream` and `inputStream.read` (JDK)
```
ByteArrayOutputStream result = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
for (int length; (length = inputStream.read(buffer)) != -1; ) {
result.write(buffer, 0, length);
}
// StandardCharsets.UTF_8.name() > JDK 7
return result.toString("UTF-8");
```
9. Using `BufferedReader` (JDK). **Warning:** This solution converts different line breaks (like `\n\r`) to `line.separator` system property (for example, in Windows to "\r\n").
```
String newLine = System.getProperty("line.separator");
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream));
StringBuilder result = new StringBuilder();
for (String line; (line = reader.readLine()) != null; ) {
if (result.length() > 0) {
result.append(newLine);
}
result.append(line);
}
return result.toString();
```
10. Using `BufferedInputStream` and `ByteArrayOutputStream` (JDK)
```
BufferedInputStream bis = new BufferedInputStream(inputStream);
ByteArrayOutputStream buf = new ByteArrayOutputStream();
for (int result = bis.read(); result != -1; result = bis.read()) {
buf.write((byte) result);
}
// StandardCharsets.UTF_8.name() > JDK 7
return buf.toString("UTF-8");
```
11. Using `inputStream.read()` and `StringBuilder` (JDK). **Warning**: This solution has problems with Unicode, for example with Russian text (works correctly only with non-Unicode text)
```
StringBuilder sb = new StringBuilder();
for (int ch; (ch = inputStream.read()) != -1; ) {
sb.append((char) ch);
}
return sb.toString();
```
**Warning**:
1. Solutions 4, 5 and 9 convert different line breaks to one.
2. Solution 11 can't work correctly with Unicode text
**Performance tests**
Performance tests for small `String` (length = 175), url in [github](https://github.com/Vedenin/useful-java-links/blob/master/helloworlds/5.0-other-examples/src/main/java/other_examples/ConvertInputStreamToStringBenchmark.java) (mode = Average Time, system = Linux, score 1,343 is the best):
```
Benchmark Mode Cnt Score Error Units
8. ByteArrayOutputStream and read (JDK) avgt 10 1,343 ± 0,028 us/op
6. InputStreamReader and StringBuilder (JDK) avgt 10 6,980 ± 0,404 us/op
10. BufferedInputStream, ByteArrayOutputStream avgt 10 7,437 ± 0,735 us/op
11. InputStream.read() and StringBuilder (JDK) avgt 10 8,977 ± 0,328 us/op
7. StringWriter and IOUtils.copy (Apache) avgt 10 10,613 ± 0,599 us/op
1. IOUtils.toString (Apache Utils) avgt 10 10,605 ± 0,527 us/op
3. Scanner (JDK) avgt 10 12,083 ± 0,293 us/op
2. CharStreams (guava) avgt 10 12,999 ± 0,514 us/op
4. Stream Api (Java 8) avgt 10 15,811 ± 0,605 us/op
9. BufferedReader (JDK) avgt 10 16,038 ± 0,711 us/op
5. parallel Stream Api (Java 8) avgt 10 21,544 ± 0,583 us/op
```
Performance tests for big `String` (length = 50100), url in [github](https://github.com/Vedenin/useful-java-links/blob/master/helloworlds/5.0-other-examples/src/main/java/other_examples/ConvertBigStringToInputStreamBenchmark.java) (mode = Average Time, system = Linux, score 200,715 is the best):
```
Benchmark Mode Cnt Score Error Units
8. ByteArrayOutputStream and read (JDK) avgt 10 200,715 ± 18,103 us/op
1. IOUtils.toString (Apache Utils) avgt 10 300,019 ± 8,751 us/op
6. InputStreamReader and StringBuilder (JDK) avgt 10 347,616 ± 130,348 us/op
7. StringWriter and IOUtils.copy (Apache) avgt 10 352,791 ± 105,337 us/op
2. CharStreams (guava) avgt 10 420,137 ± 59,877 us/op
9. BufferedReader (JDK) avgt 10 632,028 ± 17,002 us/op
5. parallel Stream Api (Java 8) avgt 10 662,999 ± 46,199 us/op
4. Stream Api (Java 8) avgt 10 701,269 ± 82,296 us/op
10. BufferedInputStream, ByteArrayOutputStream avgt 10 740,837 ± 5,613 us/op
3. Scanner (JDK) avgt 10 751,417 ± 62,026 us/op
11. InputStream.read() and StringBuilder (JDK) avgt 10 2919,350 ± 1101,942 us/op
```
Graphs (performance tests depending on Input Stream length in Windows 7 system)
[](https://i.stack.imgur.com/AYYhz.png)
Performance test (Average Time) depending on Input Stream length in Windows 7 system:
```
length 182 546 1092 3276 9828 29484 58968
test8 0.38 0.938 1.868 4.448 13.412 36.459 72.708
test4 2.362 3.609 5.573 12.769 40.74 81.415 159.864
test5 3.881 5.075 6.904 14.123 50.258 129.937 166.162
test9 2.237 3.493 5.422 11.977 45.98 89.336 177.39
test6 1.261 2.12 4.38 10.698 31.821 86.106 186.636
test7 1.601 2.391 3.646 8.367 38.196 110.221 211.016
test1 1.529 2.381 3.527 8.411 40.551 105.16 212.573
test3 3.035 3.934 8.606 20.858 61.571 118.744 235.428
test2 3.136 6.238 10.508 33.48 43.532 118.044 239.481
test10 1.593 4.736 7.527 20.557 59.856 162.907 323.147
test11 3.913 11.506 23.26 68.644 207.591 600.444 1211.545
```
|
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 some other class (your domain model requirements)?
Btw good application frameworks, like spring.net always make sure you DON'T have to inherit from this class no matter what kind of infrastructure you need to apply to your class.
**I would like to know what am I getting -3 votes here for?? :)**
|
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, because to be remoted an object must inherit from MarshalByRefObject, and your original general type didn't. Suppose you can't change it because you're doing binary inheritance, or because it itself derives from a base class you can't change? As the questioner points out, since C# (and .NET in general) doesn't allow MI, you can't inherit from both.
The short answer is that you're sort-of screwed. You either change the general type to inhert from MarshalByRefObject (or go far enough up the chain that you can insert it somewhere effective), or else you can think about mucking about with proxy objects.
You could for example create an interface contract that describes your type's interface, and then build a proxy type inheriting from MarshalByRefObject that also implements that interface by composition and delegation to an instance of your type (ie a wrapper). You could then remote an instance of that proxy type which would instantiate your type and do the work as expected - but all return types from methods have to be [Serializable].
```
public interface IMyType
{
string SayHello();
string BaseTypeMethodIWantToUse();
}
public class MyType : MyBaseType, IMyType
{
public string SayHello()
{
return "Hello!";
}
}
public class MyRemoteableType : MarshalByRefObject, IMyType
{
private MyType _instance = new MyType();
public string SayHello()
{
return _instance.SayHello();
}
public string BaseTypeMethodIWantToUse()
{
return _instance.BaseTypeMethodIWantToUse();
}
}
```
Seems like a lot of work, though. Ultimately if you're in this scenario I'd suggest a redesign or a rethink.
|
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 content (or close to), then I've found that putting them as embedded resources in a helper C# assembly to be a pretty clean way of doing it.
|
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 tidiest except that if your schema changes this can break without you knowing it. [Scott Colestock](http://www.traceofthought.net/CommentView.aspx?guid=c1164c59-72e2-49e2-be7a-47e4e8dc46d4) describes some methods of mitigating that risk.
The BizTalk Mapping method is probably the simplest to understand and won't break when the schema changes. For small schemas this can be a good choice.
For all of these methods an important thing to remember is that if you want to use distinguished fields or promoted properties you will want to create empty elements to populate. You will hit runtime `XLANG` errors if you try to assign values to elements that are missing (even though those elements may be optional)
## BizTalk Map
The simplest option is to just use a BizTalk map - you don't even necessarily need to map anything into the created instance.
To create empty elements you can just map in a string concatenation functoid with an empty string parameter.
## Assign one message to another
If you want to create a new instance of a message you can simply copy one mesage to another message of the same schema, in a message assignment shape.
## Use an XMLDocument variable
For this you create an orchestration variable of type `XMLDocument` and then in a `message assignment` use the `LoadXML` method to load an XML snippet that matches your schema. You then assign the `XMLDocument` to the desired BizTalk message.
```
varXMLDoc.LoadXml(@"<ns0:SomeXML><AnElementToPopulate></AnElementToPopulate></SomeXML>");
msgYourMessage = varXMLDom;
```
The inclusion of `AnElementToPopulate` allows you to using property promotion to assign to it.
I seldom remember the syntax to do this off the top of my head, [this](http://blogs.objectsharp.com/post/2004/11/09/Constructing-BizTalk-2004-XML-Messages-(In-an-Orchestration)-Choices.aspx) is my go to blog entry for reminding myself of the syntax.
Another link [here](http://www.sabratech.co.uk/blogs/yossidahan/2008/03/creating-message-from-scratch.html) details some methods.
|
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 errors reading the results
std::cerr << "Could not execute command: df" << std::endl;
exit(1);
}
// get the size of the results
fseek(fp, 0, SEEK_END);
bufSize = ftell(fp);
rewind(fp);
// allocate the memory to contain the results
buffer = (char*)malloc( sizeof(char) * bufSize );
if(buffer == NULL) {
std::cerr << "Memory error." << std::endl;
exit(2);
}
// read the results into the buffer
ret_code = fread(buffer, 1, sizeof(buffer), fp);
if(ret_code != bufSize) {
std::cerr << "Error reading output." << std::endl;
exit(3);
}
// print the results
std::cout << buffer << std::endl;
// clean up
pclose(fp);
free(buffer);
return (EXIT_SUCCESS);
}
```
This code is giving me a "Memory error" with an exit status of '2', so I can see *where* it's failing, I just don't understand *why*.
I put this together from example code that I found on [Ubuntu Forums](http://ubuntuforums.org/showthread.php?t=285287) and [C++ Reference](http://en.cppreference.com/w/cpp/io/c/fread), so I'm not married to it. If anyone can suggest a better way to read the results of a system() call, I'm open to new ideas.
**EDIT to the original:** Okay, `bufSize` is coming up negative, and now I understand why. You can't randomly access a pipe, as I naively tried to do.
I can't be the first person to try to do this. Can someone give (or point me to) an example of how to read the results of a system() call into a variable in C++?
|
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 that *you cannot seek in a pipe or FIFO*.
There is no escape; you cannot know the length of the command output without reading it, and you can only read it once. You have to read it in chunks, either growing your buffer as needed or parsing on the fly.
But, of course, you can simply avoid the whole issue by directly using the system call `df` probably uses to get its information: `statvfs()`.
|
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) {
// error processing and return
}
// ...
while(fgets(bfr,BUFSIZ,fp) != NULL){
// process a line
}
```
In C++ it's even easier --
```
#include <cstdio>
#include <iostream>
#include <string>
FILE * fp ;
if((fp= popen("/bin/df","r")) == NULL) {
// error processing and exit
}
ifstream ins(fileno(fp)); // ifstream ctor using a file descriptor
string s;
while (! ins.eof()){
getline(ins,s);
// do something
}
```
There's some more error handling there, but that's the idea. The point is that you treat the `FILE *` from *popen* just like *any* `FILE *`, and read it line by line.
|
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 "public" but for some reason i get these errors upon build:
"The name 'MyArrayObjectNameHere' does not exist in the current context"
When I try to access the objects member variables inside a load file dialog event in which I am trying to load data from a file into the member variables of the object array.
Is there a certain place the object array needs to be declared and constructed so it exists in every context? If so, can you tell me where this is?
I currently declare it in the main function before form1 is run.
My class definition looks like this in its own .cs file and the programs namespace:
```
public class MyClass
{
public int MyInt1;
public int MyInt2;
}
```
I declare the array of objects like this inside the main function before the form load:
```
MyClass[] MyArrayObject;
MyArrayObject = new MyClass[50];
for (int i = 0; i < 50; i++)
{
MyArrayObject[i] = new MyClass();
}
```
Thanks in advance for any help.
|
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()
{
//instantiate it here
MyArrayObject = new MyClass[50];
for (int i = 0; i
```
|
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
{
get
{
if(_myclasses == null)
{
_myClasses = new MyClass[50];
for(int i = 0; i < 50;i++)
_myClasses[i] = new MyClass();
}
return _myclasses;
}
}
}
```
Do yourself a fav and grab CLR Via C# by Jeffrey Richter. Skip the first couple chapters and read the rest.
|
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 the web does turn up mentions of this error message, but always in connection with `JFileChooser`. I'm not using `JFileChooser`, I just need to resolve a `.lnk` file to its destination.
Does anyone know of a 3rd-party parser for `.lnk` files written in Java I could use?
I've since found unofficial documentation for the .lnk format [here](http://mediasrv.ns.ac.yu/extra/fileformat/windows/lnk/shortcut.pdf), but I'd rather not have to do the work if anyone has done it before, since the format is rather scary.
|
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 is too small, did some general clean-up.
Source [here](https://raw.github.com/codebling/WindowsShortcuts/master/org/stackoverflowusers/file/WindowsShortcut.java) (if you have any changes, push them right to the GitHub [repo](https://git@github.com/codebling/WindowsShortcuts.git)/[project](https://github.com/codebling/WindowsShortcuts).
```
package org.stackoverflowusers.file;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
/**
* Represents a Windows shortcut (typically visible to Java only as a '.lnk' file).
*
* Retrieved 2011-09-23 from http://stackoverflow.com/questions/309495/windows-shortcut-lnk-parser-in-java/672775#672775
* Originally called LnkParser
*
* Written by: (the stack overflow users, obviously!)
* Apache Commons VFS dependency removed by crysxd (why were we using that!?) https://github.com/crysxd
* Headerified, refactored and commented by Code Bling http://stackoverflow.com/users/675721/code-bling
* Network file support added by Stefan Cordes http://stackoverflow.com/users/81330/stefan-cordes
* Adapted by Sam Brightman http://stackoverflow.com/users/2492/sam-brightman
* Based on information in 'The Windows Shortcut File Format' by Jesse Hager <jessehager@iname.com>
* And somewhat based on code from the book 'Swing Hacks: Tips and Tools for Killer GUIs'
* by Joshua Marinacci and Chris Adamson
* ISBN: 0-596-00907-0
* http://www.oreilly.com/catalog/swinghks/
*/
public class WindowsShortcut
{
private boolean isDirectory;
private boolean isLocal;
private String real_file;
/**
* Provides a quick test to see if this could be a valid link !
* If you try to instantiate a new WindowShortcut and the link is not valid,
* Exceptions may be thrown and Exceptions are extremely slow to generate,
* therefore any code needing to loop through several files should first check this.
*
* @param file the potential link
* @return true if may be a link, false otherwise
* @throws IOException if an IOException is thrown while reading from the file
*/
public static boolean isPotentialValidLink(File file) throws IOException {
final int minimum_length = 0x64;
InputStream fis = new FileInputStream(file);
boolean isPotentiallyValid = false;
try {
isPotentiallyValid = file.isFile()
&& file.getName().toLowerCase().endsWith(".lnk")
&& fis.available() >= minimum_length
&& isMagicPresent(getBytes(fis, 32));
} finally {
fis.close();
}
return isPotentiallyValid;
}
public WindowsShortcut(File file) throws IOException, ParseException {
InputStream in = new FileInputStream(file);
try {
parseLink(getBytes(in));
} finally {
in.close();
}
}
/**
* @return the name of the filesystem object pointed to by this shortcut
*/
public String getRealFilename() {
return real_file;
}
/**
* Tests if the shortcut points to a local resource.
* @return true if the 'local' bit is set in this shortcut, false otherwise
*/
public boolean isLocal() {
return isLocal;
}
/**
* Tests if the shortcut points to a directory.
* @return true if the 'directory' bit is set in this shortcut, false otherwise
*/
public boolean isDirectory() {
return isDirectory;
}
/**
* Gets all the bytes from an InputStream
* @param in the InputStream from which to read bytes
* @return array of all the bytes contained in 'in'
* @throws IOException if an IOException is encountered while reading the data from the InputStream
*/
private static byte[] getBytes(InputStream in) throws IOException {
return getBytes(in, null);
}
/**
* Gets up to max bytes from an InputStream
* @param in the InputStream from which to read bytes
* @param max maximum number of bytes to read
* @return array of all the bytes contained in 'in'
* @throws IOException if an IOException is encountered while reading the data from the InputStream
*/
private static byte[] getBytes(InputStream in, Integer max) throws IOException {
// read the entire file into a byte buffer
ByteArrayOutputStream bout = new ByteArrayOutputStream();
byte[] buff = new byte[256];
while (max == null || max > 0) {
int n = in.read(buff);
if (n == -1) {
break;
}
bout.write(buff, 0, n);
if (max != null)
max -= n;
}
in.close();
return bout.toByteArray();
}
private static boolean isMagicPresent(byte[] link) {
final int magic = 0x0000004C;
final int magic_offset = 0x00;
return link.length >= 32 && bytesToDword(link, magic_offset) == magic;
}
/**
* Gobbles up link data by parsing it and storing info in member fields
* @param link all the bytes from the .lnk file
*/
private void parseLink(byte[] link) throws ParseException {
try {
if (!isMagicPresent(link))
throw new ParseException("Invalid shortcut; magic is missing", 0);
// get the flags byte
byte flags = link[0x14];
// get the file attributes byte
final int file_atts_offset = 0x18;
byte file_atts = link[file_atts_offset];
byte is_dir_mask = (byte)0x10;
if ((file_atts & is_dir_mask) > 0) {
isDirectory = true;
} else {
isDirectory = false;
}
// if the shell settings are present, skip them
final int shell_offset = 0x4c;
final byte has_shell_mask = (byte)0x01;
int shell_len = 0;
if ((flags & has_shell_mask) > 0) {
// the plus 2 accounts for the length marker itself
shell_len = bytesToWord(link, shell_offset) + 2;
}
// get to the file settings
int file_start = 0x4c + shell_len;
final int file_location_info_flag_offset_offset = 0x08;
int file_location_info_flag = link[file_start + file_location_info_flag_offset_offset];
isLocal = (file_location_info_flag & 2) == 0;
// get the local volume and local system values
//final int localVolumeTable_offset_offset = 0x0C;
final int basename_offset_offset = 0x10;
final int networkVolumeTable_offset_offset = 0x14;
final int finalname_offset_offset = 0x18;
int finalname_offset = link[file_start + finalname_offset_offset] + file_start;
String finalname = getNullDelimitedString(link, finalname_offset);
if (isLocal) {
int basename_offset = link[file_start + basename_offset_offset] + file_start;
String basename = getNullDelimitedString(link, basename_offset);
real_file = basename + finalname;
} else {
int networkVolumeTable_offset = link[file_start + networkVolumeTable_offset_offset] + file_start;
int shareName_offset_offset = 0x08;
int shareName_offset = link[networkVolumeTable_offset + shareName_offset_offset]
+ networkVolumeTable_offset;
String shareName = getNullDelimitedString(link, shareName_offset);
real_file = shareName + "\\" + finalname;
}
} catch (ArrayIndexOutOfBoundsException e) {
throw new ParseException("Could not be parsed, probably not a valid WindowsShortcut", 0);
}
}
private static String getNullDelimitedString(byte[] bytes, int off) {
int len = 0;
// count bytes until the null character (0)
while (true) {
if (bytes[off + len] == 0) {
break;
}
len++;
}
return new String(bytes, off, len);
}
/*
* convert two bytes into a short note, this is little endian because it's
* for an Intel only OS.
*/
private static int bytesToWord(byte[] bytes, int off) {
return ((bytes[off + 1] & 0xff) << 8) | (bytes[off] & 0xff);
}
private static int bytesToDword(byte[] bytes, int off) {
return (bytesToWord(bytes, off + 2) << 16) | bytesToWord(bytes, off);
}
}
```
|
[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_Windows_Shortcut_File_Format.pdf>
* <http://www.javafaq.nu/java-example-code-468.html>
```
public class LnkParser {
public LnkParser(File f) throws IOException {
parse(f);
}
private boolean isDirectory;
private boolean isLocal;
public boolean isDirectory() {
return isDirectory;
}
private String real_file;
public String getRealFilename() {
return real_file;
}
private void parse(File f) throws IOException {
// read the entire file into a byte buffer
FileInputStream fin = new FileInputStream(f);
ByteArrayOutputStream bout = new ByteArrayOutputStream();
byte[] buff = new byte[256];
while (true) {
int n = fin.read(buff);
if (n == -1) {
break;
}
bout.write(buff, 0, n);
}
fin.close();
byte[] link = bout.toByteArray();
parseLink(link);
}
private void parseLink(byte[] link) {
// get the flags byte
byte flags = link[0x14];
// get the file attributes byte
final int file_atts_offset = 0x18;
byte file_atts = link[file_atts_offset];
byte is_dir_mask = (byte)0x10;
if ((file_atts & is_dir_mask) > 0) {
isDirectory = true;
} else {
isDirectory = false;
}
// if the shell settings are present, skip them
final int shell_offset = 0x4c;
final byte has_shell_mask = (byte)0x01;
int shell_len = 0;
if ((flags & has_shell_mask) > 0) {
// the plus 2 accounts for the length marker itself
shell_len = bytes2short(link, shell_offset) + 2;
}
// get to the file settings
int file_start = 0x4c + shell_len;
final int file_location_info_flag_offset_offset = 0x08;
int file_location_info_flag = link[file_start + file_location_info_flag_offset_offset];
isLocal = (file_location_info_flag & 2) == 0;
// get the local volume and local system values
//final int localVolumeTable_offset_offset = 0x0C;
final int basename_offset_offset = 0x10;
final int networkVolumeTable_offset_offset = 0x14;
final int finalname_offset_offset = 0x18;
int finalname_offset = link[file_start + finalname_offset_offset] + file_start;
String finalname = getNullDelimitedString(link, finalname_offset);
if (isLocal) {
int basename_offset = link[file_start + basename_offset_offset] + file_start;
String basename = getNullDelimitedString(link, basename_offset);
real_file = basename + finalname;
} else {
int networkVolumeTable_offset = link[file_start + networkVolumeTable_offset_offset] + file_start;
int shareName_offset_offset = 0x08;
int shareName_offset = link[networkVolumeTable_offset + shareName_offset_offset]
+ networkVolumeTable_offset;
String shareName = getNullDelimitedString(link, shareName_offset);
real_file = shareName + "\\" + finalname;
}
}
private static String getNullDelimitedString(byte[] bytes, int off) {
int len = 0;
// count bytes until the null character (0)
while (true) {
if (bytes[off + len] == 0) {
break;
}
len++;
}
return new String(bytes, off, len);
}
/*
* convert two bytes into a short note, this is little endian because it's
* for an Intel only OS.
*/
private static int bytes2short(byte[] bytes, int off) {
return ((bytes[off + 1] & 0xff) << 8) | (bytes[off] & 0xff);
}
/**
* Returns the value of the instance variable 'isLocal'.
*
* @return Returns the isLocal.
*/
public boolean isLocal() {
return isLocal;
}
}
```
|
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 constructor taking the two bits of data:
```
class SomeClass
{
struct MyStruct
{
private readonly string label;
private readonly int id;
public MyStruct (string label, int id)
{
this.label = label;
this.id = id;
}
public string Label { get { return label; } }
public string Id { get { return id; } }
}
static readonly IList<MyStruct> MyArray = new ReadOnlyCollection<MyStruct>
(new[] {
new MyStruct ("a", 1),
new MyStruct ("b", 5),
new MyStruct ("q", 29)
});
}
```
Note the use of [ReadOnlyCollection](http://msdn.microsoft.com/en-us/library/ms132474.aspx) instead of exposing the array itself - this will make it immutable, avoiding [the problem exposing arrays directly](http://blogs.msdn.com/ericlippert/archive/2008/09/22/arrays-considered-somewhat-harmful.aspx). (The code show does initialize an array of structs - it then just passes the reference to the constructor of `ReadOnlyCollection<>`.)
|
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 field of a reference type other than string can only be initialized with null.
|
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 reference but also the items in the collection) then you will have to create a readonly dictionary class that implements IDictionary<K, V>.
Check out ReadOnlyCollection for reference.
You cannot use const with the Dictionary type, only with scalar values. <https://msdn.microsoft.com/en-us/library/e6w8fe1b(VS.71).aspx>.
|
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.