Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I have a web page with tabs or accordion, generated with YUI or jquery or another javascript+css framework.
Say an HTML form is processed in one tab. What should the server do? Send back all the tabs, with the tab that submitted the form having the results and all the other tabs unmodified? Or what? | As you select each new tab, you can send a jQuery AJAX request for just the content you require, e.g. if your user clicks on a tab titled "Sports", you can make a request to "sports.html" on your server, and display it in the tab.
There's a good walk-through [here](http://jetlogs.org/2008/03/17/jquery-ajax-tabs/) that describe how to achieve this, all built upon a basic function like:
```
// Clicked on "sports" tab
$("#sports").click(function()
{
// Make ajax call
$.ajax(
{
url: "sports.html", // page to be called
cache: false,
success: function(message)
{
// Success code returned, clear sports
// content area and inject server response
$("#sportscontent").empty().append(message);
}
});
});
``` | You should always send documents that are still usable when JavaScript support is not available. And as most of such navigation use the fragment identifier of the URI to identify the part of a document that should be displayed, you could use this too and target your form to this fragment:
```
<form action="#tab3" method="post">
```
Or you use JavaScript to send the data, fetch the response and display it inside the current tab. | Tab or accordion based page - how is it done in the server side? | [
"",
"javascript",
"html",
"css",
""
] |
I have created a webpart in c# for sharepoint.
its basically a form with text boxes, literals, validators and buttons.
im not sure how to render this form to make it look pretty.
The layout etc is being done entirely within this c# class.
At the moment to get started im just overrinding `CreateChildControls()` method
and adding each form control using something like: `this.Controls.Add(submitButton);`
any ideas on how best to layout this form?
Thanks. | When creating custom webparts I also prefer to implement them by overriding the **CreateChildControls()** and **Render()** methods. In the **Render()** method I have full control of the html output and I can render my inner controls by calling **this.someInnerControl.RenderControl(writer)**.
Having full control of the html output also makes it easy to style the html using CSS. As other people suggests, use an external CSS file and apply the styes to the *class* attribute on html elements or *CssClass* property on ASP.NET web control.
When I implement webparts, that does not require special branding, I prefer to reuse the CSS classes defined by SharePoint. This will ensure that my webpart is visually similar to the webpart provided by SharePoint and that I keep a consistent look and feel.
When using the SharePoint defined CSS styles, you should be aware of your html output. Some of the CSS classes requires a specific html structure to properly render. You can always use the browsers "View Source" to check the html of the SharePoint element you are trying to imitate. | I would recommend grabbing the source from an existing sharepoint page and using the styles defined by sharepoint. [This link to the styles in 2003](http://www.sharepointcustomization.com/resources/tipstricks/wss_cssguide.htm) is old, but still a good guide to get started. Most of the CSS class names haven't changed. | laying out a form using c# for a webpart in sharepoint | [
"",
"c#",
"sharepoint",
"web-parts",
""
] |
I'd like to pass a value type to a function and set it to a repeating bit pattern (FF, AA, etc.) across the entire width of the variable. Right now, I'm passing the value with
void foo(T val) where T : struct
so I can use any value type. The problem is, the compiler won't let me use sizeof(T), because T could be a reference type (except that it *can't*, thanks to the "where" constraint). I could hard code all the value types and check against them myself, but that obviously seems like overkill. Is there a simpler way to do this?
Just to clarify: if I pass a `byteInt64`, I want to set it to 0xFFFFFFFF.
I tried `Convert.ChangeType(0xFFFFFFFF, typeof(T))`, but it throws if `val` is e.g. a Char. I could solve the problem by a) figuring out how wide the type-parameter is and "building" a big-enough value to stuff in, b) figuring out how to accept any value type (and only value types), such that sizeof() would work, or c) figuring out how to automagically truncate 0xFFFFFFFF down to the correct width for the variable. | Can you use the Marshal.SizeOf method?
<http://msdn.microsoft.com/en-us/library/y3ybkfb3.aspx>
EDIT: NB! Read Tor Haugen's comment prior to actually doing this. | You could also cast -1 as whatever you are handing through. No matter the length of the variable, -1 is always all F's. As long as you are using primitive types, this should never really cause too much of an issue.
A quick explanation of why this works:
All integers in a system are held in 2's complement notation. This means negative numbers aren't just the number with a sign bit. To create a 2's complement, you simply flip all the bits and add 1.
ergo:
-1 = not (1) + 1
so
0000 0001 > 1111 1110 > 1111 1111 = 0xFF
This will always give you all 1's for any length item.
EDIT:
use the [sizeof](http://msdn.microsoft.com/en-us/library/eahchzkf(VS.71).aspx) operator to get the size of the type in bytes, use [typeof](http://msdn.microsoft.com/en-us/library/58918ffs(VS.71).aspx) to get the type, then I would use bit shifting in a loop to fill the item sooo...
```
for (int i = 0; i < sizeof(typeof(input)); i++)
{
input = (input << 8) | Ox<Pattern>
}
```
please forgive my syntactic errors, been a while, but that should do what you want. | Byte width of a value type | [
"",
"c#",
"generics",
""
] |
Whats the relationship between a [`JTable`](http://java.sun.com/javase/6/docs/api/javax/swing/JTable.html), [`TableModel`](http://java.sun.com/javase/6/docs/api/javax/swing/table/TableModel.html) and `TableData`? If i just modify the `TableData`, does that also change the data display on the `JTable` component or I have to call some method to sync the two. I have looked at [this](http://java.sun.com/docs/books/tutorial/uiswing/components/table.html), but it does not explicitly tell or show me the relationship in terms of updates | When you change a value in the TableModel data, you must fire this event. eg. changing the value of one cell, you call `fireTableCellUpdated(row, col);`.
Look at [this](http://docs.oracle.com/javase/tutorial/uiswing/components/table.html#fire) more specifically. | I presume you're using the phrase "TableData" to just mean the data being shown in the JTable. To answer your question, whether you see automatic updates or not depends upon your TableModel and how it interacts with your data.
A TableModel should fire events when the underlying data model has changed, this in turn will notify the JTable that a change has occurred and it should be redrawn. So in terms of a relationship, the JTable listens to event changes on the TableModel; the TableModel has no knowledge of the JTable.
Depending on how your model is organised, the data underneath it could change without the TableModel knowing. In this instance, if you have a direct passthrough from the TableModel to the data, the values onscreen will change when a repaint naturally occurs (screen resize, mouse moving over etc.), but it you want to force the event you should get the TableModel to notify the JTable through the aforementioned events. In terms of relationship, the TableModel knows about the table data, but the table data has no knowledge of model (usually). The TableModel may or may not be listening on the data for changes. | Relationship between JTable, TableModel & TableData | [
"",
"java",
"swing",
"jtable",
""
] |
I found a simple function to remove some undesired characters from a string.
```
function strClean($input){
$input = strtolower($input);
$b = array("á","é","í","ó","ú", "ñ", " "); //etc...
$c = array("a","e","i","o","u","n", "-"); //etc...
$input = str_replace($b, $c, $input);
return $input;
}
```
When I use it on accents or other characters, like this word 'á é ñ í' it prints out those question marks or weird characters, like:
[output http://img217.imageshack.us/img217/6794/59472278.jpg](http://img217.imageshack.us/img217/6794/59472278.jpg)
Note: I'm using strclean.php (which contains this function) and index.php, both in UTF-8. index.php looks as follows:
```
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
<?php
include('strclean.php');
echo 'óóóáà';
echo strClean('óóóáà');
?>
</body>
</html>
```
What am I doing wrong? | I have tested your code, and error is in strtolower function...
Replace it with mb\_strtolower, like bellow
```
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
</head>
<body>
<?php
function strClean($input) {
$input = mb_strtolower($input, 'UTF-8');
$b = array("á","é","í","ó","ú", "n", " ");
$c = array("a","e","i","o","u","n", "-");
return str_replace($b, $c, $input);
}
$string = 'á é í ó ú n abcdef ghij';
echo $string ."<br />". strClean($string);
?>
</body>
</html>
``` | Use
```
iconv('UTF-8', 'ASCII//TRANSLIT', $input);
``` | Problem with function removing accents and other characters in PHP | [
"",
"php",
"string",
"unicode",
"utf-8",
""
] |
What does the '=>' in this statement signify?
```
del = new SomeDelegate(() => SomeAction());
```
Is the above declaration the same as this one?
```
del = new SomeDelegate(this.SomeAction);
```
Thanks. | Basically it's specifying an anonymous function, that takes no parameters that calls SomeAction. So yes, they are functionally equivalent. Though not equal. Using the lambda is more equivalent to:
```
del = new SomeDelegate(this.CallSomeAction);
```
where CallSomeAction is defined as:
```
public void CallSomeAction()
{
this.SomeAction();
}
```
Hope that helps! | They *do* the same thing but the "() => ..." syntax is what is called a lambda expression and as such is the same as an anonymous function. You could probably leave out the delegate part altogether and just let the compiler infer the delegate type for you.
```
del = this.SomeAction;
```
Depending on what type "del" is seclared as.
**Edit**
Using lambdas or anonymous methods or just a regular method for starters enables you to map methods that didn't have the delegate's signature to the delegate.
For example, say you have a delegate with the signature bool myDelegate(int, int) but you wanted to have a method with the signature bool myMethod(string, string) handle the delegate. You could then use the lambda expression to let you do this inline with a short syntax like so.
```
delegate bool myDelegate(int x, int y);
// With lambdas...
myDelegate del = (int a, int b) => myMethod(a.ToString(), b.ToString());
// With anonymous methods...
myDelegate del2 = delegate(int a, int b) { return myMethod(a.ToString(), b.ToString()); };
// The good ol' way without lambdas or anonymous methods...
myDelegate del3 = SomeDelegateHandler;
... then write a method somewhere else ...
// Handler method
private bool SomeDelegateHandler(int a, int b)
{
return myMethod(a.ToString(), b.ToString());
}
```
So as you can see lambdas and anonymous methods are basically just a shorter/inline way of making a method to handle the delegate. In you case you might not need to make an extra method. It just depends on if the delegate signature is the same as your method signature, and to me, it seems like it is. | What does the operator '=>' mean in C#? | [
"",
"c#",
"delegates",
"lambda",
""
] |
I am using a dictionary to perform lookups for a program I am working on. I run a bunch of keys through the dictionary, and I expect some keys to not have a value. I catch the [`KeyNotFoundException`](http://msdn.microsoft.com/en-us/library/system.collections.generic.keynotfoundexception.aspx) right where it occurs, and absorb it. All other exceptions will propagate to the top. Is this the best way to handle this? Or should I use a different lookup? The dictionary uses an int as its key, and a custom class as its value. | Use [`Dictionary.TryGetValue`](http://msdn.microsoft.com/en-us/library/bb347013.aspx) instead:
```
Dictionary<int,string> dictionary = new Dictionary<int,string>();
int key = 0;
dictionary[key] = "Yes";
string value;
if (dictionary.TryGetValue(key, out value))
{
Console.WriteLine("Fetched value: {0}", value);
}
else
{
Console.WriteLine("No such key: {0}", key);
}
``` | Try using:
Dict.ContainsKey
Edit:
Performance wise i think `Dictionary.TryGetValue` is better as some other suggested but i don't like to use Out when i don't have to so in my opinion ContainsKey is more readable but requires more lines of code if you need the value also. | Best way to handle a KeyNotFoundException | [
"",
"c#",
"exception",
"keynotfoundexception",
""
] |
I have a bat file with the following contents:
```
set logfile= D:\log.txt
java com.stuff.MyClass %1 %2 %3 >> %logfile%
```
when I run the bat file though, I get the following:
```
C:\>set logfile= D:\log.txt
C:\>java com.stuff.MyClass <val of %1> <val of %2> <val of %3> 1>>D:\log.txt
The parameter is incorrect.
```
I'm almost positive the "The parameter is incorrect." is due to the extraneous 1 in there. I also think this might have something with the encoding of the .bat file, but I can't quite figure out what is causing it. Anyone ever run into this before or know what might be causing it and how to fix it?
**Edit**
And the lesson, as always, is check if its plugged in first before you go asking for help. The bat file, in version control, uses D:\log.txt because it is intended to be run from the server which contains a D drive. When testing my changes and running locally, on my computer which doesn't have a D drive, I failed to make the change to use C:\log.txt which is what caused the error. Sorry for wasting you time, thanks for the help, try to resist the urge to downvote me too much. | This may seem like a stupid question, but is there an existing D: drive in the context that the bat file runs in?
Once I had a case where a bat file was used as the command line of a task within the Task Manager, but the Run As user was set to a local user on the box, giving no access to network drives.
Interpolated for your case, if the D: drive were a network drive, running the bat file as, say, the local administrator account on that machine instead of a domain user account would likely fail to have access to D:. | I doubt that that's the problem - I expect the command processor to deal with that part for you.
Here's evidence of it working for me:
Test.java:
```
public class Test
{
public static void main(String args[]) throws Exception
{
System.out.println(args.length);
for (String arg : args)
{
System.out.println(arg);
}
}
}
```
test.bat:
```
set logfile= c:\users\jon\test\test.log
java Test %1 %2 %3 >> %logfile%
```
On the command line:
```
c:\Users\Jon\Test> [User input] test.bat first second third
c:\Users\Jon\Test>set logfile= c:\users\jon\test\test.log
c:\Users\Jon\Test>java Test first second third 1>>c:\users\jon\test\test.log
c:\Users\Jon\Test> [User input] type test.log
3
first
second
third
``` | odd .bat file behavior | [
"",
"java",
"windows",
"character-encoding",
"batch-file",
""
] |
The query:
```
SELECT tbl1.*
FROM tbl1
JOIN tbl2
ON (tbl1.t1_pk = tbl2.t2_fk_t1_pk
AND tbl2.t2_strt_dt <= sysdate
AND tbl2.t2_end_dt >= sysdate)
JOIN tbl3 on (tbl3.t3_pk = tbl2.t2_fk_t3_pk
AND tbl3.t3_lkup_1 = 2577304
AND tbl3.t3_lkup_2 = 1220833)
where tbl2.t2_lkup_1 = 1020000002981587;
```
Facts:
* Oracle XE
* tbl1.t1\_pk is a primary key.
* tbl2.t2\_fk\_t1\_pk is a foreign key on that t1\_pk column.
* tbl2.t2\_lkup\_1 is indexed.
* tbl3.t3\_pk is a primary key.
* tbl2.t2\_fk\_t3\_pk is a foreign key on that t3\_pk column.
Explain plan on a database with 11,000 rows in tbl1 and 3500 rows in
tbl2 shows that it's doing a full table scan on tbl1. Seems to me that
it should be faster if it could do a index query on tbl1.
Explain plan on a database with 11,000 rows in tbl1 and 3500 rows in
tbl2 shows that it's doing a full table scan on tbl1. Seems to me that
it should be faster if it could do a index query on tbl1.
Update: I tried the hint a few of you suggested, and the explain cost got much worse! Now I'm really confused.
Further Update: I finally got access to a copy of the production database,
and "explain plan" showed it using indexes and with a much lower cost
query. I guess having more data (over 100,000 rows in tbl1 and 50,000 rows
in tbl2) were what it took to make it decide that indexes were worth it. Thanks to everybody who helped. I still think Oracle performance tuning is a black art, but I'm glad some of you understand it.
Further update: I've updated the question at the request of my former employer. They don't like their table names showing up in google queries. I should have known better. | It would be useful to see the optimizer's row count estimates, which are not in the SQL Developer output you posted.
I note that the two index lookups it is doing are RANGE SCAN not UNIQUE SCAN. So its estimates of how many rows are being returned could easily be far off (whether statistics are up to date or not).
My guess is that its estimate of the final row count from the TABLE ACCESS of TBL2 is fairly high, so it thinks that it will find a large number of matches in TBL1 and therefore decides on doing a full scan/hash join rather than a nested loop/index scan.
For some real fun, you could run the query with event 10053 enabled and get a trace showing the calculations performed by the optimizer. | The easy answer: Because the optimizer expects more rows to find then it actually does find.
Check the statistics, are they up to date?
Check the expected cardinality in the explain plan do they match the actual results? If not fix the statistics relevant for that step.
Histogramms for the joined columns might help. Oracle will use those to estimate the cardinality resulting from a join.
Of course you can always force index usage with a hint | Why is this query doing a full table scan? | [
"",
"sql",
"oracle",
"query-optimization",
""
] |
I know using .NET languages such as C#, one can do something like
```
Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)
```
to find the redirected location of the Desktop. However, under Java, I cannot think of a good way to do this. What is the most appropriate way to find a redirected user Desktop directory from Java, without using JNI? The specific purpose here is for the purposes of managing a desktop shortcut, if the user wants one, for a Java Web Start application.
This application needs to write to the "Application Data" tree as well as optionally to the Desktop. I am making the assumption that `%APPDATA%` is always correctly populated, even when folders are redirected, for finding the "Application Data" tree. So my open question is how to reliably find the Desktop folder.
NOTE: I believe that the Java system property `${user.home}` actually ([and erroneously](https://bugs.java.com/bugdatabase/view_bug?bug_id=4787931)) locates the user's Desktop directory via registry keys and then tries to navigate up one directory to find the "home" directory. This works fine when no directories are redirected, and otherwise may or may not return something useful. | ```
FileSystemView filesys = FileSystemView.getFileSystemView();
filesys.getHomeDirectory()
``` | ```
String desktopPath = System.getProperty("user.home") + File.separator + "Desktop";
``` | In java under Windows, how do I find a redirected Desktop folder? | [
"",
"java",
"windows",
"redirect",
"find",
"desktop",
""
] |
```
$id = $_REQUEST['id'];
$Section = $_REQUEST['section'];
$Subject = $_REQUEST['subject'];
$type = $_REQUEST['type'];
$Start_date1 = isset($_REQUEST['startTxt'])?($_REQUEST['startTxt']):"";
$Venue = isset($_REQUEST['venTxt'])?($_REQUEST['venTxt']):"";
$Facilitator = isset($_REQUEST['faciTxt'])?($_REQUEST['faciTxt']):"";
$Level = isset($_REQUEST['lvlLst'])?($_REQUEST['lvlLst']):"";
$Date1 = $_REQUEST['date1'];
if(isset($_REQUEST['EDIT']))
{
mysql_query("UPDATE service SET Start_date='$Date1', Venue='$Venue', Facilitator='$Faci' WHERE ServiceID ='$id'");
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo '<script type="text/javascript">';
echo 'alert("Changes have been save!");';
echo 'window.location="Admin_RecSchedMapLst.php";';
echo '</script>';
mysql_close($con);
}
```
When I click save it returns "Error: Query was empty" - why is this? | You're calling `mysql_query()` twice, once with a non-existent `$sql` parameter:
```
mysql_query("UPDATE service SET Start_date='$Date1', Venue='$Venue', Facilitator='$Faci' WHERE ServiceID ='$id'");
if (!mysql_query($sql,$con))
```
should be:
```
if (!mysql_query("UPDATE service SET Start_date='$Date1', Venue='$Venue', Facilitator='$Faci' WHERE ServiceID ='$id'"))
```
You're also not escaping your input, leaving you open to SQL injection.
You should use bound parameters ideally, or at the very least run your parameters through [`mysql_real_escape_string()`](http://www.php.net/mysql_real_escape_string).
For example:
```
$Date1 = mysql_real_escape_string($Date1, $conn);
``` | Please, for the love of the internet, don't built an SQL query yourself. Use [PDO](http://php.net/pdo). | Why do I get the MySQL Error "Query was empty"? | [
"",
"php",
"mysql",
""
] |
I'm trying to write a stored procedure and depending on a certain column value, I want to be able to change what table I select from. I'll try to give an example:
```
SELECT ItemNumber,
ItemType,
Description
FROM
CASE ItemType
WHEN 'A' THEN TableA
ELSE TableB
END
WHERE
CASE ItemType
WHEN 'A' THEN ItemNumber = @itemNumber
ELSE PartNumber = @itemNumber
END
```
As you can see, not only am I dynamically changing the table I select from, but since these two tables were made at two different times by two different people, the column names are different as well.
So, my question is: What is the best way to accomplish this, since SQL Server doesn't seem to like my query I have constructed.
If anyone who sees what I'm trying to do can suggest a better way to do this, I'd be all ears :-) | You can not use CASE statement in FROM clause, but you can use the following instead:
```
SELECT itemnumber, itemtype, description
FROM tablea
WHERE itemnumber = @itemnumber AND itemtype = 'A'
UNION ALL
SELECT itemnumber, itemtype, description
FROM tableb
WHERE partnumber = @itemnumber AND itemtype <> 'A'
``` | I'm not sure why you want to do things in one SQL Statement .. I'm not a SQL Server person, but in an Oracle stored procedure you could write something like this
```
If itemtype = 'A'
Then
<statement for table A>
Else
<statement for Table B>
End if
```
Something like this should work in SQL Server, too .. maybe someone could expand on this? | Dynamically Changing what table to select from with SQL CASE statement | [
"",
"sql",
"sql-server",
"dynamic-sql",
""
] |
I'm using jQuery and jqGrid.
I'm trying to populate a select list dynamically, one for each row and I need to add a click event to it. When the select list is being populated I grab the index of the item I want selected, and then after all items are add I'm trying to set the selected item.
I've tried
```
$("#taskList")[0].selectedIndex = taskIndex;
$("#taskList").selectOptions(taskIndex, true);
$("#taskList").val(1); //Tried to see if I could select any index and no luck.
$("#taskList option[value=" + taskIndex + "]").attr("selected", true);
```
So this means I'm probably populating the list incorrectly...
```
var taskList = document.createElement("select");
var taskIndex = 0;
for (var i = 0; i < result.TaskTypes.length; i++) {
$(taskList).addOption(result.TaskTypes[i].TaskId, result.TaskTypes[i].TaskName);
if (result.TaskTypes[i].TaskName == rowData.TaskType)
taskIndex = i;
}
```
Is there a better way?
I tried this but I couldn't add the click event to it. The proper item was selected though.
```
var taskList = "<select name='taskList' Enabled='true'>";
for (var i = 0; i < result.TaskTypes.length; i++) {
if (result.TaskTypes[i].TaskName == rowData.TaskType)
taskList += "<option selected> " + result.TaskTypes[i].TaskName + "</option>";
else
taskList += "<option>" + result.TaskTypes[i].TaskName + "</option>";
}
taskList += "</select>";
``` | Got it- a good solid 8 hours later.
```
var taskList = "<select name='taskList' Enabled='true' onClick='$(\"#hoursBx\").valid()' >";
for (var i = 0; i < result.TaskTypes.length; i++) {
if (result.TaskTypes[i].TaskName == rowData.TaskType)
taskList += "<option selected> " + result.TaskTypes[i].TaskName + "</option>";
else
taskList += "<option>" + result.TaskTypes[i].TaskName + "</option>";
}
taskList += "</select>";
```
I'm using [jQuery's Validator](http://bassistance.de/jquery-plugins/jquery-plugin-validation/) to verify the value in the $("#hoursBx") (a text box in the current row).
Adding the onClick works. | The way I would have done it, is in your first example - instead of using the jQuery API for addOption, use the DOM API, like this:
```
var option = document.createElement("option");
option.innerHTML = result.TaskTypes[i].TaskName;
option.value = result.TaskTypes[i].TaskId;
option.onclick = myClickHandler;
taskList.add(option, null);
```
Then after the loop you can just use:
```
taskList.selectedIndex = taskIndex;
```
to have the select list positioned to your required default selection.
I haven't used jQuery extensively, but I think its a good idea not to neglect the DOM API - its often not as convenient as the shortcuts that jQuery and other libraries offer, but these extend DOM capabilities and should not come instead of the DOM. | Best way to create a dynamic Select (Dropdown) list? | [
"",
"javascript",
"jquery",
"list",
"drop-down-menu",
"selectlist",
""
] |
I have a javascript function which passes as a query string value another query string.
In other words, I want the query string to be:
```
http://www.somesite.com/?somequery=%3fkey%3dvalue1%2520%26%2520key2%3value3
```
However, if I redirect like this:
```
var url = 'http://www.somesite.com/?somequery=';
url += escape('?key=value1&key2=value2');
window.location = url;
```
it ends up as `http://www.somesite.com?somequery=?key1=value1&key2=value2` in firefox and IE7 which means that I can't parse the query string correctly.
I also tried using encodeURIComponent which didn't work either.
Is there another function or a hack to force the redirect to keep the `somequery` value escaped?? | encodeURIComponent will work. (You may or may not want the leading ‘?’, depending on what the script is expecting.)
```
var c= 'd e'
var query= '?a=b&c='+encodeURIComponent(c);
var uri= 'http://www.example.com/script?query='+encodeURIComponent(query);
window.location= uri;
```
Takes me to:
> <http://www.example.com/script?query=%3Fa%3Db%26c%3Dd%2520e>
When you hover over that it may appear once-decoded in the browser's status bar, but you will end up in the right place.
escape/unescape() is the wrong thing for encoding query parameters, it gets Unicode characters and pluses wrong. There is almost never a case where escape() is what you really need. | Native `escape` method does that. but also you can create a custom encoder like:
```
function encodeUriSegment(val) {
return encodeUriQuery(val, true).
replace(/%26/gi, '&').
replace(/%3D/gi, '=').
replace(/%2B/gi, '+');
}
```
this will replace keys used in query strings. further more you can apply it to any other custom encodings by adding needed key-values pairs. | How to encode a query string so that it is the value of another query string in javascript? | [
"",
"javascript",
"encoding",
"query-string",
""
] |
Trying to find some examples on the intertubes. I am thinking of state or strategy pattern but if anyone has any war stories, examples or resources that they could point me to it would be appreciated.
I don't/can't use windows workflow.
My example is that i have a complex wizard that changes the state of the process based on what user is doing and by who the user is.
For example:
* Cancelled
* Requested by user
* Request by manager
* Confirmed
* Refereed
* Administrator Received
* Administrator Confirmed
* Administrator Cancelled
Cheers
John | How about the [State](http://www.sloppycode.net/articles/csharp-design-patterns.aspx#state) pattern ([wikipedia link](http://en.wikipedia.org/wiki/State_pattern))?
```
public abstract class State
{
/// <summary>
/// Holds the current state we're in.
/// </summary>
public State CurrentState
{
get;
set;
}
public virtual string Cancelled(State context)
{
return "";
}
public virtual string RequestedByUser(State context)
{
return "";
}
public virtual string RequestedByManager(State context)
{
return "";
}
}
public class CancelledState : State
{
public override string Cancelled(State context)
{
context.CurrentState = new SittingState();
return "Cancelled.";
}
public override string RequestedByUser(State context)
{
context.CurrentState = new RequestedByUserState();
return "Requested by User.";
}
public override string RequestedByManager(State context)
{
return "You can't do this before it's been requested by the User";
}
}
// (RequestedByUserState and RequestedByManagerState classes have been cut out)
```
*As you can see, the pattern does fit exactly though.*
[Chain of Responsibility](http://en.wikipedia.org/wiki/Chain-of-responsibility_pattern) might be also be relevant if there's security concerns. If the wikipedia article makes no sense then [this book](http://www.amazon.co.uk/3-0-Design-Patterns-Judith-Bishop/dp/059652773X/ref=sr_1_4?ie=UTF8&s=books&qid=1216066920&sr=8-4) has a good examples of both. Another is the Command pattern for wizards. None of them fit perfectly but they give you some good ideas to start with. | Design Pattern's are not specific to any language (C# design pattern?).
I suggest you should focus on building a framework for your workflow implementation, by using different patterns, instead of just thinking about an ideal pattern that may suit all your needs.
Recently read an article in Javaworld about using Dispatcher pattern to implement the workflow.
See <http://www.javaworld.com/javaworld/jw-10-2001/jw-1019-dispatcher.html>
You might also consider evaluating alternate, existing open source workflow frameworks in C#, like NetBPM <http://www.netbpm.org/> | Which C# design pattern would suit writing custom workflow in asp.net | [
"",
"c#",
"asp.net",
"design-patterns",
"workflow",
""
] |
I have IQueryable Products.
now i want to add new product to this IQueryable object.
so how do i do this? | IQueryable doesn't have any methods for adding. [See MSDN](http://msdn.microsoft.com/en-us/library/system.linq.iqueryable_members.aspx). | I've never tried this, but try products.Union(moreProducts). | how can i add another object to an already defined IQueryable object? | [
"",
"c#",
""
] |
I am trying to query a mysql table which contains strings of numbers
(i.e. '1,2,3,4,5').
How do I search to see if it has '1' but not '11' bearing in mind if it is '9,10' '9%' doesnt work??
Fixed!
```
(field like '10' OR field like '%,10,%' OR field like '%,10' OR field like '10,%')
``` | You need the function [FIND\_IN\_SET](http://dev.mysql.com/doc/refman/5.1/de/string-functions.html#id1242404). Btw, '9%' should work, if the column contains the values you specified, are you sure you're querying
```
SELECT * FROM table WHERE field LIKE '9%'?
``` | You could try the function find\_in\_set
```
select find_in_set('1','1,2,3,11,12')
``` | Mysql query with wildcard on number strings | [
"",
"sql",
"mysql",
"wildcard",
""
] |
[alt text http://agricam.net/test.gif](http://agricam.net/test.gif)
I need to add a row dynamically in SQL after the Marketer number changes with the header "Marketer Total" that should add only the "Total" column. For example, after the last row of Marketer 22 row, there should be "Marketer Total" and then under the Total column should be 1804. The same should occur after the last row of Marketer 500.
See image at <http://agricam.net/test.gif>
Current Query:
select Marketer,
SubMarketer,
Grade,
Total,
Convert(varchar,Date,101)[Date]
from SomeTable
where Date >= '2/25/2009' and Date < '2/26/2009'
and Marketer in ('22','500')
group by SubMarketer,Grade,Marketer, Date , total
order by Marketer
Thanks. | see [Using ROLLUP to aggregate data in SQL](http://www.odetocode.com/Articles/85.aspx)
implementation:
```
DECLARE @SOMETABLE TABLE (SUBMARKETER INT, GRADE CHAR, MARKETER INT,
DATE DATETIME, TOTAL INT)
INSERT INTO @SOMETABLE
SELECT 1415, 'A', 22, '02/25/2009', 26 UNION
SELECT 1415, 'B', 22, '02/25/2009', 93 UNION
SELECT 1415, 'C', 22, '02/25/2009', 1175 UNION
SELECT 1415, 'D', 22, '02/25/2009', 510 UNION
SELECT 1169, 'B', 500, '02/25/2009', 1 UNION
SELECT 1169, 'C', 500, '02/25/2009', 3 UNION
SELECT 1393, 'C', 500, '02/25/2009', 2 UNION
SELECT 2, 'B', 500, '02/25/2009', 5 UNION
SELECT 2, 'C', 500, '02/25/2009', 111 UNION
SELECT 2, 'D', 500, '02/25/2009', 18
SELECT
CASE WHEN SUBMARKETER IS NULL THEN 'Marketer Total'
ELSE CONVERT(VARCHAR, MARKETER) END MARKETER,
SUBMARKETER, GRADE, TOTAL, DATE
FROM (
SELECT MARKETER, SUBMARKETER, GRADE, SUM(TOTAL) AS TOTAL,
CONVERT(VARCHAR,DATE,101)[DATE]
FROM @SOMETABLE
WHERE DATE >= '2/25/2009' AND DATE < '2/26/2009'
AND MARKETER IN ('22','500')
GROUP BY MARKETER, SUBMARKETER, GRADE, DATE WITH ROLLUP
)M
WHERE M.MARKETER IS NOT NULL
AND NOT (SUBMARKETER IS NOT NULL AND DATE IS NULL)
```
**attention**: this will work fine if MARKETER, SUBMARKETER and DATE columns are NOT NULL. If there will be NULL values of theese fields in table, that will became an issue to filter out useless grouping. | Coldice's answer is the correct one. Unless you have a compelling reason to store aggregate data in the table, the query engine is sufficiently powerful enough to do this for you. Can you explain why you need this row in the table? Is it for display purposes? You can use the ROLLUP function to put the aggregate results in a query or you can run a separate query a such to sow the totals:
```
SELECT marketer, SUM(total) FROM TablenameHere GROUP BY marketer
``` | Sql Grouping | [
"",
"sql",
"t-sql",
"grouping",
"sum",
""
] |
I have a control (derived from System.Windows.Forms.Control) which needs to be transparent in some areas. I have implemented this by using SetStyle():
```
public TransparentControl()
{
SetStyle(ControlStyles.SupportsTransparentBackColor, true);
this.BackColor = Color.Transparent.
}
```
Now, this works if there are no controls between the form and the transparent control. However, if there happens to be another control below the transparent control (which is the use case here), it does not work. The intermediate control is not draw, but the form below does show through. I can get the effect that I need by overriding CreateParams and setting the WS\_EX\_TRANSPARENT flasg like so:
```
protected override CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;
cp.ExStyle |= 0x20; // WS_EX_TRANSPARENT
return cp;
}
}
```
The problem here is that it *really* slows down the painting of the control. The control is already double buffered, so nothing to do there. The performance hit is so bad that it is unacceptable. Has anyone else encountered this problem? All of the resources that I can find suggest using method #1, but again, that does not work in my case.
EDIT: I should note that I do have a workaround. The child (transparent) controls could simply draw themselves onto the parent's Graphics object, but it is really ungly and I don't like the solution at all (though it may be all I have).
EDIT2: So, following the advice that I got on how transparency works in .NET, I have implemented the IContainer interface in my user control which contains the transparent controls. I have created a class which implements ISite, I add my child controls to the Components collection of the UserControl, the Container property lines up correctly in the debugger, but I still do not get a transparency effect. Does anyone have any ideas? | I decided to simply paint the parent under my child controls manually. [Here is a good article.](http://componentfactory.blogspot.com/2005/06/net2-transparent-controls.html) | This is just a simple thing I cooked up.. The only issue I've found is that it doesn't update when the intersecting controls are updated..
It works by drawing a control that's behind/intersects with the current control to a bitmap, then drawing that bitmap to the current control..
```
protected override void OnPaint(PaintEventArgs e)
{
if (Parent != null)
{
Bitmap behind = new Bitmap(Parent.Width, Parent.Height);
foreach (Control c in Parent.Controls)
if (c.Bounds.IntersectsWith(this.Bounds) & c != this)
c.DrawToBitmap(behind, c.Bounds);
e.Graphics.DrawImage(behind, -Left, -Top);
behind.Dispose();
}
}
``` | How to create a transparent control which works when on top of other controls? | [
"",
"c#",
"winforms",
"transparent-control",
""
] |
Our business sends a newsletter to a vast number of subscribers every week. When the business was very young, before I joined, they used a "free" version of some mass mailer that took six hours to send 5K mails and fell foul of every reverse DNS check on the internet.
I upgraded this to a bespoke .Net widget that ran on the correct server and could send up to about 20k mails in half an hour with full DNS compliance. Unfortunately (or fortunately depending on your standpoint) our mail list has now outgrown this simple tool. In particular its lack of adequate throttling, it can make more mails than the server can comfortably send at once. I need to actually monitor how full the IIS SMTP server's available outgoing mail storage allocation is and throttle the load accordingly.
Unfortunately I can find no information on where a mail object goes when (or even if) it is turned into a mail. I can implement a filesystemwatcher if I have a place to watch, currently I don't. If no actual mail file is ever created I guess I will have to create one to implement the functionality but I need to know where to put it. It would also be more reassuring to allow the system to confirm sending somehow but I have no idea how to go about retrieving data from the system that says a mail has been sent.
Extensive Googling has proven vague on these points; so I was wondering if anyone here knew where I could get a guide to these problems, or could otherwise point me in the right direction.
Many thanks.
EDIT: In the end I gave up trying to measure throughput on the IIS SMTP server as a bad job. It just didn't seem to want to play. I'm now carrying out my logging in a separate location and just shunting it through to the SMTP server thereafter. I still don't know of anyone who really bothers trying to keep tabs on the doings of the IIS SMTP server and so this question as of this writing goes unanswered.
Oh well... | Okay so I've been working on this project for ages now and I thought I might share my findings with the world.
**The IIS SMTP Server**
All mails created using the IIS SMTP server are sent, in the first instance, to the Pickup Directory. If you are sending one mail then you will have to operate in Matrix time to actually ever see it there because it will probably just go, straight away.
On an individual mail's way out of the door it passes through the queue folder in IIS.
If you wanted to watch the Performance Counter to monitor this process you ould look at the "Remote Queue Length". (The reason for this is that the "Local Queue Length" monitors mails sent "Locally" within the network. "Remote" in this instance refers to "Outside into the world". The specific definition of "Local" escapes me as we send no local mail but I imagine it means queued to go to mailboxes contained within the specific installation of IIS on the server or any local grouping thereof.)
From an Exchange point of view it seems to be the equivalent of mails sent within the Exchange Domain and those sent out of that domain into the wider world.
Anyhow. The Remote Queue Length doesn't tell the whole story. You also have to look at the Remote Retry Queue, the number of Current Outbound Connections and, for belt and braces sake the actual number of files in the queue directory.
Here's why:
* Remote Queue: All messages that have not
yet been sent, however many times
this has been tried. The number of
mails currently assigned to any open
connections are not counted as they
are in a state of "being tried".
* Remote Retry Queue: All messages that
have not yet been sent that have, at
some point in the past, been assigned
to an open connection for delivery.
Obviously the delivery must have
failed or the message would have been
delivered. Any messages currently
assigned to an open connection for a
retry are not counted.
* Current Outbound Connections: Shows when the
server is attempting to send queued
mails, more than one message can be
assigned to an outbound connection.
Messages thus assigned are not
counted in either the Remote Queue or
the Remote Retry queue. Physical
* Files in the queue directory: This
shows the number of mails still in
the Queue directory. This will
decrease as mails are successfully
delivered.
*Example:* If you have 0 outbound connections and 50 mails in the Queue directory then the Remote Queue, Retry Queue and Physical files will all read at 50. When a retry flag is raised (this is a setting in IIS) the number of connections increases and the number of mails in the queues decreases. Until a mail is delivered the number of physical files remains the same. However as more than one mail can be sent on a current connection 1 connection may result in Remote Queue and Retry Queue lengths of 47 or lower. If, during the retry event, any mails are successfully delivered the number of physical files in the Queue directory will then decrease. When the connection closes the queue counters should all stabilise again.
**Logging**
It is possible with .Net's Mail library to Specify a Pickup directory separate from the IIS default. Here you can queue mails and get a bespoke service to occasionally move the mails into the IIS directory where the IIS service will take over and send out queued mails.
To do this you will be looking for the SmtpClient object's "DeliveryMethod" property which should be set to SmtpDeliveryMethod.SpecifiedPickupDirectory.
To actually set the SpecifiedPickupDirectory you should set the SmtpClient's PickupDirectoryLocation property.
When mails are delivered to this location they are stored as .eml files. The filename is a GUID. This means that multiple emails will be despatched in an essentially random order. You could, in theory, write code to address this situation if desired. The .eml file follows a standard format which can be read by opening the .eml in notepad. Parsing this will allow you to extract information for a log.
I hope this high level overview of the way the SMTP server in IIS works is of some assistance to someone in a similar position to the one I was in in March. | I would use the [PerformanceCounter](http://msdn.microsoft.com/en-us/library/system.diagnostics.performancecounter.aspx) component to read the SMTP Service's **Local Queue Length** counter. That should keep you in control :-) | Meaningful interaction with IIS SMTP Server in .Net | [
"",
"c#",
"iis",
"smtp",
""
] |
My work company has a MSSQL server 2005. I have two questions about finding out current log user and any way to send out a warning message:
First question is if there is any T-SQL or SP available to find out current login user name and machine name. If the user is using SQL server sa name to remotely access to SQL server, is there any way to find out that user's windows name (the name to log to the windows)?
My next question is that if I can get the user name or id, is there any way to send out a warning message such as "currently SQL server is clean up or backup, please do not log in at this time". I guess it may be difficult. I may have to send an email out to the user.
The SQL server is only accessible in the company. The SQL server has a list of users as login users: windows users, SQL users and sa. | ```
SELECT SUSER_SNAME(), HOST_NAME()
```
If the connection is "sa" (or any other SQL login) then you can't find the domain/windows user name. SQL Server only knows it's "sa" or that SQL login.
HOST\_NAME may not be reliable either, it can be set in the connection string ("Application Name"). Or it could be vague eg "Microsoft Office" for by default for Access, Excel etc
You could backtrack via `client_net_address` in [`sys.dm_exec_connections`](http://msdn.microsoft.com/en-us/library/ms181509.aspx) and match MAC address to IP and find out who is logged on... | An easy way to find out both host and user is
```
EXEC sp_who2;
```
where you get some other information that can be good to know, as if the user is active and so on...
It does not resolve the issues that gbn announced. | How to find out user name and machine name to access to SQL server | [
"",
"sql",
"sql-server",
"sql-server-2005",
"t-sql",
""
] |
I used the "pull interface" refactoring feature of Eclipse today to create an interface based on an existing class. The dialog box offered to create all the new methods of the new interface as "abstract" methods.
What would be the benefit of that?
I thought that the fact that you were allowed to declare interface methods as abstract was a superfluous and harmless feature of the language that is not particularly encouraged.
Why would Eclipse support such a style, or why would someone voluntarily choose to do so?
Clarification: I am not asking why interface methods are abstract, that is obvious. I am asking why one would explicitly choose to mark them as abstract since if they're in an interface they are abstract anyway. | According to the [Java Language Specification](http://docs.oracle.com/javase/specs/jls/se7/html/jls-9.html#jls-9.1.1.1), the `abstract` keyword for interfaces is obsolete and should no longer be used. (Section 9.1.1.1)
That said, with Java's propensity for backwards compatibility, I really doubt it will ever make a difference whether the `abstract` keyword is present. | "The benefice of that" (adding abstract on interface methods declaration) in eclipse would be an old compatibility issue with [jdt eclipse compiler in jdk1.3](https://bugs.eclipse.org/bugs/show_bug.cgi?id=11435)
> Since 1.4, jdk libraries are no longer containing default abstract methods (on abstract classes implementing interfaces).
> This is fooling the Eclipse 1.3 compiler diagnosis since their implementation is relying on their existence.
> Note that Javac 1.3 would refuse altogether to perform against 1.4 libraries (using -bootclasspath option).
Since the Eclipse compiler is likely to be in 1.4 compliance level (see `Workbench>Preferences>Java>Compiler>JDK Compliance`), or use at least 1.3 class libraries if using 1.3 compliance mode, the presence of "abstract" is not required in most of the current eclipse projects. | Why would one declare a Java interface method as abstract? | [
"",
"java",
"eclipse",
"interface",
"abstract",
""
] |
First of all, i'd to establish that i do have the text file in my Folders directory. Im using visual studio and it is where my source code is compiling.
The code below should demonstate why its not working. In visual studio.
```
int main( const int argc, const char **argv )
{
char usrMenuOption;
const char *cFileName = argv[ 1 ];
checkName( cFileName ); // supplying the checkName function with contents of argv[1]
usrMenuOption = getUsrOption(); // calling another function
fgetc(stdin);
return 0;
}
ifstream *openInputFile( const char *cFileName )
{
// this function might be the pronblem.
ifstream *inFile;
inFile = new ifstream;
inFile->open( cFileName, ios::in );
return inFile;
}
bool checkName( const char *cFileName )
{
// it works fine if i use a regular ifstream obj and not the one from the function
ifstream *inFile;
inFile = openInputFile( cFileName );
inFile->open( cFileName, ios::in );
if ( inFile->good() )
{
return true;
}
else
{
cout << '"' << cFileName << '"' << ": File does not exist! " << endl;
return false;
}
}
```
It does work if i use a non-pointer object for the ifstream.
however i need to open all of my input files this way, using the function i made.
I'm a little confused because i did not have this issue compiling in dev-cpp | I always check ifs.is\_open() where ifs is a ifstream. | You have a few options:
1. The one you've tried - opening the file.
2. Using [stat](http://www.techbytes.ca/techbyte103.html).
3. Using [GetFileAttributes](http://msdn.microsoft.com/en-us/library/aa364944(VS.85).aspx).
4. Using [FindFirstFile](http://msdn.microsoft.com/en-us/library/aa364418(VS.85).aspx).
The only way to guarantee that it exists **and that you can use it** is to open it. If you use other methods you end up with a race condition (because the file could be deleted or locked after you check to see if it exists.
**EDIT**: You have a couple of other issues in your code. Firstly, you allocate a `infile` via `new`, but you never `delete` it. Secondly, you call `open` twice. | Checking existence of a txt file with C++ code | [
"",
"c++",
"visual-studio",
"file",
""
] |
Here is my script code:
```
// ==UserScript==
// @name test
// @description test
// @include http://*
// @copyright Bruno Tyndall
// ==/UserScript==
var main = function() {
var b = document.getElementsByTagName('body')[0];
var t = document.createElement('div');
t.innerHTML = '<a href="javascript:void(0);" style="color:white;">Hello World</a>';
t.style.position = 'absolute';
t.style.zIndex = 1000;
t.style.bottom = '5px';
t.style.right = '5px';
t.firstChild.setAttribute('onclick', 'test();');
b.appendChild(t);
}
var test = function() {
alert("Hello World");
}
main();
```
The only issue I have is when Hello World is clicked the page cannot find the test() function. Please tell me I don't have to solve it by innerHTML'ing the function onto the page like [this](http://userscripts.org/scripts/review/40443). Is there another way?
Thanks. | Greasemonkey executes the script in a sandbox - the page doesn't have access to it for security reasons. All acceses to dom and window are via wrappers.
If you want to access the unsecured objects you can use `wrappedJSObject` property.
For your case you can use `unsafeWindow` (or `window.wrappedJSObject`):
```
unsafeWindow.test = function() { ....
```
There are some security issues with this, see: <http://wiki.greasespot.net/UnsafeWindow>
Also, greasemonkey executes the script after the DOMContentLoaded (when the dom is ready) event so you don't need that onload nonsense.
Also, you can't use attributes to set event listeners, or properties for that matter - you must use dom api for that. Eg:
```
t.firstChild.addEventListener('click', test, false);
```
or:
```
t.firstChild.addEventListener('click', function(event){ blabla }, false);
``` | iirc, greasemonkey runs within it's own scope, so test will not be in the global namespace.
Instead of poluting the global though, why not create your anchor element through DOM manipulation? That will return you a refernece which you can bind an anonymous function (or the greasemonkey scoped test). | Greasemonkey Script and Function Scope | [
"",
"javascript",
"firefox",
"scope",
"greasemonkey",
""
] |
I'm developing an application in which distributed components talk to one another over a network, in an asynchronous, pub/sub kind of way.
For this, I like the idea of sending XML over sockets - it's asynchronous, I don't need a server of any kind, and it can work locally or over a network. I would have to roll my own pub/sub mechanism, which probably won't be too onerous - I could use the IP address as the id of the subscriber. The implementation language will be C++. I've used this method before with good results. But, I wonder if there is a better way? Any advice welcome.
Edit: I haven't made a decision yet, but I'm interested in cparcode's comment on protobuf:
"I never understood the popularity of using XML for network comms. Any way, I realize that the protocol is only part of your problem but on that subject, there's Google's protobuf too: <http://code.google.com/p/protobuf/> – caparcode (Mar 11 at 1:01)" | Instead of using XML it might be best to use an existing message passing framework. Have a look at [libt2n](http://www.intra2net.com/en/developer/libt2n/index.php) or [d-bus](http://www.freedesktop.org/wiki/Software/dbus)
But it you have used your own socket implementation in the past with good results i don't see a reason why you should change. If it ain't broke don't fix it :) | Take a look at [ActiveMQ](http://activemq.apache.org/). It's a [JMS](http://java.sun.com/products/jms/) provider and also has bindings in lots of other languages, works on several transports, and has a selection of protocols that it uses for its messages. | What is the best way for distributed processes to communicate asynchronously? | [
"",
"c++",
"sockets",
"messaging",
""
] |
Is it wrong to use m\_varname as public and the same class with \_variable as private | Some concerns:
* Why do you have public variables?
* Identifiers starting with \_ and \_\_ are reserved for system libraries. In practice this doesn't matter very often, but it's nice to be aware.
With those things said, there's nothing wrong with creating a naming convention, regardless of how it looks. Just be consistent. | The same goes for C++ and for Java: you do not need any hungarian notation nor any prefixes/suffixes. You got keyword "this"!
```
class MyClass {
private:
int value;
public:
MyClass(int value) {
this->value = value;
}
}
```
Of course in this simple example you can (should!) use constructor initialization list ;)
So, instead using any awkward notations just employ language's possibilities. When you know the name of your member variable - you know that it is perfect. Why would you obfuscate it with "\_"?
As for using the same names for public and private members: this absolutely wrong thinking! Why would one need two things to represent the same in the same class? Make it private, name it perfectly and give getters and setters public. | naming convention for public and private variable? | [
"",
"c++",
""
] |
How I could determine if JDBC driver is `TYPE_FORWARD_ONLY`? In my program the user configures connection parameters to database and he could use any JDBC driver in the class path. I want to know if the driver is `TYPE_FORWARD_ONLY` before executing any statements. Is this possible? | DatabaseMetaData has a method supportsResultSetType(int type) that you could use to check if the ResultSet supports `TYPE_FORWARD_ONLY`. | By [querying the type](http://java.sun.com/j2se/1.4.2/docs/api/java/sql/ResultSet.html#getType()) of result set. For example:
```
Statement stmt = con.createStatement(
ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_UPDATABLE
);
ResultSet rs = stmt.executeQuery("SELECT a, b FROM TABLE2");
System.out.println(
"Is Type Forward Only: " +
(rs.getType() == ResultSet.TYPE_FORWARD_ONLY)
);
``` | Java JDBC driver and TYPE_FORWARD_ONLY | [
"",
"java",
"jdbc",
""
] |
I have written code to save cookies in JavaScript. Now I need to clear the cookies irrespective of values that I assigned.
Are there any script modules to delete all cookies that were generated by [Javascript](http://en.wikipedia.org/wiki/JavaScript)?
### My Sample Code:
```
document.cookie = 'ppkcookie2=another test; expires=Fri, 3 Aug 2001 20:47:11 UTC; path=/'
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
```
How else could I clear all of the cookies?
Will there will be any problems when I test the code on the webserver? | On the face of it, it looks okay - if you call `eraseCookie()` on each cookie that is read from `document.cookie`, then all of your cookies will be gone.
**Try this:**
```
var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++)
eraseCookie(cookies[i].split("=")[0]);
```
All of this with the following caveat:
* JavaScript ***cannot*** remove cookies that have the **[HttpOnly](https://en.wikipedia.org/wiki/HTTP_cookie#Secure_and_HttpOnly)** flag set. | There is no 100% solution to delete browser cookies.
The problem is that cookies are uniquely identified by not just by their key "name" but also their "domain" and "path".
Without knowing the "domain" and "path" of a cookie, you cannot reliably delete it. This information is not available through JavaScript's `document.cookie`. It's not available through the HTTP Cookie header either!
However, if you know the name, path and domain of a cookie, then you can clear it by setting an empty cookie with an expiry date in the past, for example:
```
function clearCookie(name, domain, path){
var domain = domain || document.domain;
var path = path || "/";
document.cookie = name + "=; expires=" + +new Date + "; domain=" + domain + "; path=" + path;
};
``` | How can I delete all cookies with JavaScript? | [
"",
"javascript",
"cookies",
""
] |
I have a method where I want to have a parameter that is a Type, but of a certain interface.
E.g.:
```
public static ConvertFile(Type fileType)
```
where I can specify fileType inherits IFileConvert.
Is this possible? | One option is generics:
```
public static ConvertFile<T>() where T : IFileConvert
{
Type type = typeof(T); // if you need it
}
```
and call as:
```
ConvertFile<SomeFileType>();
``` | Nope, it's not possible. However you could do:
```
public static void ConvertFile<T>() where T : IFileConvert {
Type fileType = typeof(T);
}
```
instead. | How do you specify to pass a Type that is of a specific interface? | [
"",
"c#",
".net",
".net-2.0",
""
] |
Do you know how expensive exception throwing and handling in java is?
We had several discussions about the real cost of exceptions in our team. Some avoid them as often as possible, some say the loss of performance by using exceptions is overrated.
Today I found the following piece of code in our software:
```
private void doSomething()
{
try
{
doSomethingElse();
}
catch(DidNotWorkException e)
{
log("A Message");
}
goOn();
}
private void doSomethingElse()
{
if(isSoAndSo())
{
throw new DidNotWorkException();
}
goOnAgain();
}
```
How is the performance of this compared to
```
private void doSomething()
{
doSomethingElse();
goOn();
}
private void doSomethingElse()
{
if(isSoAndSo())
{
log("A Message");
return;
}
goOnAgain();
}
```
I don't want to discuss code aesthetic or anything, it's just about runtime behaviour!
Do you have real experiences/measurements? | I haven't bothered to read up on Exceptions but doing a very quick test with some modified code of yours I come to the conclusion that the Exception circumstance quite a lot slower than the boolean case.
I got the following results:
```
Exception:20891ms
Boolean:62ms
```
From this code:
```
public class Test {
public static void main(String args[]) {
Test t = new Test();
t.testException();
t.testBoolean();
}
public void testException() {
long start = System.currentTimeMillis();
for(long i = 0; i <= 10000000L; ++i)
doSomethingException();
System.out.println("Exception:" + (System.currentTimeMillis()-start) + "ms");
}
public void testBoolean() {
long start = System.currentTimeMillis();
for(long i = 0; i <= 10000000L; ++i)
doSomething();
System.out.println("Boolean:" + (System.currentTimeMillis()-start) + "ms");
}
private void doSomethingException() {
try {
doSomethingElseException();
} catch(DidNotWorkException e) {
//Msg
}
}
private void doSomethingElseException() throws DidNotWorkException {
if(!isSoAndSo()) {
throw new DidNotWorkException();
}
}
private void doSomething() {
if(!doSomethingElse())
;//Msg
}
private boolean doSomethingElse() {
if(!isSoAndSo())
return false;
return true;
}
private boolean isSoAndSo() { return false; }
public class DidNotWorkException extends Exception {}
}
```
I foolishly didn't read my code well enough and previously had a bug in it (how embarassing), if someone could triple check this code I'd very much appriciate it, just in case I'm going senile.
My specification is:
* Compiled and run on 1.5.0\_16
* Sun JVM
* WinXP SP3
* Intel Centrino Duo T7200 (2.00Ghz, 977Mhz)
* 2.00 GB Ram
In my opinion you should notice that the non-exception methods don't give the log error in doSomethingElse but instead return a boolean so that the calling code can deal with a failure. If there are multiple areas in which this can fail then logging an error inside or throwing an Exception might be needed. | Exceptions are not free... so they are expensive :-)
The book [Effective Java](http://books.google.com/books?id=ZZOiqZQIbRMC&pg=PA97&sig=JgnunNhNb8MYDcx60Kq4IyHUC58#PPP1,M1) covers this in good detail.
* Item 39 Use exceptions only for exceptional conditions.
* Item 40 Use exceptions for recoverable conditions
The author found that exceptions resulted in the code tunning 70 times slower for his test case on his machine with his particular VM and OS combo. | How expensive are Exceptions | [
"",
"java",
"performance",
"exception",
""
] |
I want to get smarter in AJAX, but not sure which way to go. I have done some DHTML programming back in the day - like 8 years ago!, before it was called AJAX. I used emacs and hand-coded all the javascript, debugged via "Alert".
At this point I think there are frameworks out there that make things nicer and easier, but which ones? Where to start? Recommendations?
1. is jQuery indispensable? Just nice to have?
2. What about project SACK?
3. Firebug?
4. any other free libraries or frameworks you recommend? or disrecommend?
5. for a very simple project I found tons of pitfalls with FF vs IE compat. Without getting into a religious debate about who is right and who is wrong, what are some tips for navigating that minefield to produce apps that work and look mostly similar on any browser. One guy had a tip: insert \* {padding:0; margin:0;} at the top of his .css stack, because FF and IE both have different default padding and margins for elements like UL OL etc. Is there a list of tips like this? Guidance?
6. I don't have a Mac and really don't wanna incur the test cost of IE, FF, Opera, Safari, Chrome, across all the myriad versions and platforms. Hints? Is there a 80% solution here? Like if I test on FF & IE, can I guess it will work on the others?
7. tips on tutorial sites, getting started? There's tons of info out there, which are the good places to go. In particular, because DHTML was around 10 yrs ago, my google searches are turning up some really stale information.
8. Debugging and development tools? I found an xpath just-in-time evaluator on the web on zvon.org. It was good but not as flexible as i wanted it to be. This is something I think would be invaluable. xsl and xpath have got to be the most opaque languages I have ever used. When I started with regex, there were just-in-time regex tools available, like Expresso, etc. Those were invaluable for developing and learning regex in the early days. Last night I spent waaaay too long fiddling with an xpath expression, and I'm wondering if there are similar JIT tools for xpath. And what about debugging and developing Javascript itself?
Mostly I am interested in the client-side aspects. I am not so much interested in integrated client+server approaches like ASP.NET AJAX, for now. If you told me about a client AJAX framework or development tool that worked only with Ruby, I wouldn't be interested.
Thanks!
EDIT: why did I get voted down? Is this a bad question to ask? It seemed perfectly reasonable to me? is it impolite? | it's usually even easier than the ajax() function above. mostly i just do ....
```
$('#mydiv').load('http://getsomehtml.php?op=loadmeup');
```
once in awhile add a callback
```
document.body.style.cursor = "wait";
$('#mydiv').load('http://getsomehtml.php?op=loadmeup', function() {
document.body.style.cursor = "default";
});
```
and I agree [jQuery](http://jquery.com/) is indispensable. or something like it .. using raw javascript is a minefield of problems with all the browsers these days. I like [visualjquery.com](http://visualjquery.com/) as a handy reference (but I wish Remy would update it to 1.3.2)
And I could not do my job w/o [Firebug](http://getfirebug.com/) so that's totally required.
I run [xampplite](http://www.apachefriends.org/en/xampp-windows.html#646) on a PC for testing. And I use [NotePad++](http://notepad-plus.sourceforge.net/uk/site.htm) or [Eclipse PDT 2.0](http://www.eclipse.org/pdt/downloads/) for editing (esp for server-side PHP) and CVS and i'm good to go...
The way I do multi-browser testing is via a VM. I use Sun's [VirtualBox](http://www.virtualbox.org/wiki/Downloads) and an XP virtual machine with all the browsers loaded up. I regularly use FF3 and IE7, so my VM has in it IE6, FF2, Chrome, Opera, and Safari. I sometimes use a Ubuntu 8.10 image but not really all that often.
For Regex get a copy of [RegexBuddy](http://www.regexbuddy.com/) - easily worth the $40 | Personally I think jQuery is indispensable. There are a lot of browser differences with XMLHttpRequest. jQuery simplifies all that. Here is an [example](http://www.ibm.com/developerworks/library/x-ajaxjquery.html):
```
$.ajax({
url: 'document.xml',
type: 'GET',
dataType: 'xml',
timeout: 1000,
error: function(){
alert('Error loading XML document');
},
success: function(xml){
// do something with xml
}
});
```
You can easily change this to return JSON, HTML, etcj.
Also there are wrapper methods for this that greatly reduce the number of parameters like `$.load()`, `$.post()` and so on.
In reference to browser differences, I strongly suggest you start with a CSS reset like [Yahoo's reset CSS](http://developer.yahoo.com/yui/reset/) (there are others).
In terms of development, Firefox is the standard, combined with Firebug (and typically YSlow). HttpFox and Web Developer are popular plug-ins too. | Recommendations for simple AJAX? | [
"",
"javascript",
"jquery",
"ajax",
"dhtml",
""
] |
Do you implement an interface for every public class in your domain model? Pros and Cons?
Update: If Repositories interfaces and domain model classes are defined in separate assemblies, wouldn't there be circular dependency if we do not define interfaces for every domain class. | No.
Cons.
1. Noise code.
2. More to write.
3. YAGNI. | You should define interfaces for dependencies between layers, not for every class. So your Service layer should depend on a repository interface, and your presentation layer should depend on a service interface. Past that, there aren't many hard and fast rules, other then use them where it makes sense.
Common sense is a good part of any good design. | Do you define an interface for every public class in your domain model? Pros and Cons? | [
"",
"c#",
"interface",
"dependencies",
"loose-coupling",
""
] |
I am writing a fairly large and complex data analysis program and I have reached the point where I think it is about time to build a GUI for the program. So my question is:
Which GUI toolkit should I use?
I am completely new to coding and building GUIs and would appreciate any guidance that can be offered. It doesn't have to be the simplest tool kit in the world, I learn rather fast. However, it does need to be able to do the following things (some if not all of these are probably incredibly basic for any given toolkit but I thought that it would be good to throw all this out there just in case).
It has to allow me to draw directly to the screen so that I can put graphs (spectra really), plots and things like them up for the user to see. I need to be able to collect position information on where they clicked on aforementioned spectra. I need to be able to display text and take text input from the user. It needs to be able to generate menus (you know File, Edit, etc). If it were to have some built in widget for generating tables that would be handy (though I can surmount a lack of that if I can draw directly to the screen). It needs to be able to pop up warnings, dialogue boxes, save and open boxes, etc. That is pretty much it, most of these seem pretty basic when I write them out but I don't want to get the GUI partly coded and then realize that I I need to rewrite it with a different toolkit.
It should be noted that I have written this program in C++ and that I don't want to have to write the GUI part in C or something else so the toolkit needs to support C++.
Additionally a cross platform toolkit would be preferable over a single platform toolkit. However if it must be a single platform toolkit then I would prefer it be for Linux.
Finally, I would DRAMATICALLY prefer an open source toolkit to a closed source toolkit.
Beyond that I cannot think of anything to add. Thank you in advance for your time and answers.
Hmmm based on the answers I shall look at both Qt and wxWidgets and see which appeals to me more. I with I could accept multiple answers as accepted but I can't, and since I am looking at two things it would be unfair to only accept one of the answers, perhaps in a week or two then I have looked at the toolkits and figured out which I want to use. | For C++, in my opinion, Qt is the least frustrating and most fully featured toolkit. Its also fully cross platform. Note that Qt will be LGPL licensed some time in March 2009, when version 4.5 becomes available. Currently, its only offered in a GPL and commercial license version.
Qt's GUI designer is good. It has lots of utility functions (scene graph library, translation support, built-in Javascript engine, built-in WebKit library). Via the MOC (a special pre-compiler) it also brings a few run-time binding capabilities and introspection to C++.
For your technical application, you might find that Qwt ([http://qwt.sourceforge.net/](http://qwt.sf.net)) provides what you need. It is built upon Qt.
Qt can even be used "headless" if you want its utility support (such as networking, etc) without a GUI.
The other cross platform C++ option is wxWidgets, which is usable but not really comparable to Qt. Its a much lower level toolkit, and isn't as easy to use or fully rounded. Gtkmm is another option, in the spirit of GTK+. | Try WxWidgets. Cross platform (compile on Linux, Mac OS X, and Windows) and widely accepted.
<http://www.wxwidgets.org/>
Open Source too! | Gui toolkits, which should I use? | [
"",
"c++",
"user-interface",
"qt",
"wxwidgets",
""
] |
How can I enable users to resize a panel at runtime by dragging a corner? | You could intercept the mouse location and the click.. if it's in a corner then set a resizing boolean and then on the mousemove event you could implement something like this..
```
if (_resizing)
{
this.Height = top + e.Y;
this.Width = width + e.X;
}
``` | I don't know about dragging corners, but you could dock the panel and use splitters to provide a place for users to resize the docked regions. | Resizing a panel in C#, Windows Forms | [
"",
"c#",
"winforms",
"visual-studio",
""
] |
I have a Python web client that uses urllib2. It is easy enough to add HTTP headers to my outgoing requests. I just create a dictionary of the headers I want to add, and pass it to the Request initializer.
However, other "standard" HTTP headers get added to the request as well as the custom ones I explicitly add. When I sniff the request using Wireshark, I see headers besides the ones I add myself. My question is how do a I get access to these headers? I want to log every request (including the *full* set of HTTP headers), and can't figure out how.
any pointers?
in a nutshell: How do I get all the outgoing headers from an HTTP request created by urllib2? | If you want to see the literal HTTP request that is sent out, and therefore see every last header exactly as it is represented on the wire, then you can tell `urllib2` to use your own version of an `HTTPHandler` that prints out (or saves, or whatever) the outgoing HTTP request.
```
# For Python 2, switch these imports to:
#
# import httplib as client
# import urllib2 as request
from http import client
from urllib import request
class MyHTTPConnection(client.HTTPConnection):
def send(self, s):
print(s.decode('utf-8')) # or save them, or whatever
client.HTTPConnection.send(self, s)
class MyHTTPHandler(request.HTTPHandler):
def http_open(self, req):
return self.do_open(MyHTTPConnection, req)
opener = request.build_opener(MyHTTPHandler)
response = opener.open('http://www.google.com/')
```
The result of running this code is:
```
GET / HTTP/1.1
Accept-Encoding: identity
Host: www.google.com
User-Agent: Python-urllib/3.9
Connection: close
``` | The urllib2 library uses OpenerDirector objects to handle the actual opening. Fortunately, the python library provides defaults so you don't have to. It is, however, these OpenerDirector objects that are adding the extra headers.
To see what they are after the request has been sent (so that you can log it, for example):
```
req = urllib2.Request(url='http://google.com')
response = urllib2.urlopen(req)
print req.unredirected_hdrs
(produces {'Host': 'google.com', 'User-agent': 'Python-urllib/2.5'} etc)
```
The unredirected\_hdrs is where the OpenerDirectors dump their extra headers. Simply looking at `req.headers` will show only your own headers - the library leaves those unmolested for you.
If you need to see the headers before you send the request, you'll need to subclass the OpenerDirector in order to intercept the transmission.
Hope that helps.
EDIT: I forgot to mention that, once the request as been sent, `req.header_items()` will give you a list of tuples of ALL the headers, with both your own and the ones added by the OpenerDirector. I should have mentioned this first since it's the most straightforward :-) Sorry.
EDIT 2: After your question about an example for defining your own handler, here's the sample I came up with. The concern in any monkeying with the request chain is that we need to be sure that the handler is safe for multiple requests, which is why I'm uncomfortable just replacing the definition of putheader on the HTTPConnection class directly.
Sadly, because the internals of HTTPConnection and the AbstractHTTPHandler are very internal, we have to reproduce much of the code from the python library to inject our custom behaviour. Assuming I've not goofed below and this works as well as it did in my 5 minutes of testing, please be careful to revisit this override if you update your Python version to a revision number (ie: 2.5.x to 2.5.y or 2.5 to 2.6, etc).
I should therefore mention that I am on Python 2.5.1. If you have 2.6 or, particularly, 3.0, you may need to adjust this accordingly.
Please let me know if this doesn't work. I'm having waaaayyyy too much fun with this question:
```
import urllib2
import httplib
import socket
class CustomHTTPConnection(httplib.HTTPConnection):
def __init__(self, *args, **kwargs):
httplib.HTTPConnection.__init__(self, *args, **kwargs)
self.stored_headers = []
def putheader(self, header, value):
self.stored_headers.append((header, value))
httplib.HTTPConnection.putheader(self, header, value)
class HTTPCaptureHeaderHandler(urllib2.AbstractHTTPHandler):
def http_open(self, req):
return self.do_open(CustomHTTPConnection, req)
http_request = urllib2.AbstractHTTPHandler.do_request_
def do_open(self, http_class, req):
# All code here lifted directly from the python library
host = req.get_host()
if not host:
raise URLError('no host given')
h = http_class(host) # will parse host:port
h.set_debuglevel(self._debuglevel)
headers = dict(req.headers)
headers.update(req.unredirected_hdrs)
headers["Connection"] = "close"
headers = dict(
(name.title(), val) for name, val in headers.items())
try:
h.request(req.get_method(), req.get_selector(), req.data, headers)
r = h.getresponse()
except socket.error, err: # XXX what error?
raise urllib2.URLError(err)
r.recv = r.read
fp = socket._fileobject(r, close=True)
resp = urllib2.addinfourl(fp, r.msg, req.get_full_url())
resp.code = r.status
resp.msg = r.reason
# This is the line we're adding
req.all_sent_headers = h.stored_headers
return resp
my_handler = HTTPCaptureHeaderHandler()
opener = urllib2.OpenerDirector()
opener.add_handler(my_handler)
req = urllib2.Request(url='http://www.google.com')
resp = opener.open(req)
print req.all_sent_headers
shows: [('Accept-Encoding', 'identity'), ('Host', 'www.google.com'), ('Connection', 'close'), ('User-Agent', 'Python-urllib/2.5')]
``` | How do you get default headers in a urllib2 Request? | [
"",
"python",
"urllib2",
""
] |
I mean:
```
Table PHONE_CODES:
ID CODE_NAME PHONE_CODE
1 USA 8101
2 USA 8102
3 PERU 8103
4 PERU_MOB 81031
5 PERU_MOB 81032
```
And I want via select to get something like this:
```
CODE_NAME ZONE_CODES
USA 8101; 8102;
PERU 8103
PERU_MOB 81031; 81032;
```
I could get it via the function below, but perhaps there is a better way:
```
select distinct(CODE_NAME) as CODE_NAME, get_code_names_by_ZONE(CODE_NAME) as ZONE_CODES from PHONE_CODES;
```
Function:
```
create or replace function get_code_names_by_ZONE
(
ZONE_CODE_NAME in varchar2
)
return varchar2
as
codes_list varchar2(4000);
cursor cur_codes_list is
select p.PHONE_CODE
from PHONE_CODES p
where p.CODE_NAME = ZONE_CODE_NAME;
begin
for codes_list_rec in cur_codes_list
LOOP
-- dbms_output.put_line('PHONE_CODE:[' || codes_list_rec.PHONE_CODE || ']');
codes_list := codes_list || codes_list_rec.PHONE_CODE || '; ';
end loop;
return codes_list;
EXCEPTION
when NO_DATA_FOUND then
return 'notfound';
WHEN others then
dbms_output.put_line('Error code:' || SQLCODE || ' msg:' || SQLERRM);
return null;
end get_code_names_by_ZONE;
/
``` | Tim Hall has an excellent discussion on the various [string aggregation techniques](http://www.oracle-base.com/articles/10g/StringAggregationTechniques.php) that are available in Oracle. | A function would be my preferred method of achieving what you want. | What is a simple way to combine grouped values in one field? | [
"",
"sql",
"oracle",
"plsql",
""
] |
I'm trying to make a site where the user can click on any element to edit it's CSS. I use the following to add the click function to all `<li>`, `<div>` and `<ul>`.
```
$('li,div,ul').click(function () {
alert(this.id);
});
```
The problem is if I click on a `<li>` element, then I get the alert for that and any element underneath it. (all the containers).
Is it possible to have only the top element trigger when clicked? | You want to stop event propagation, you do this in jQuery by calling the [stopPropagation](http://docs.jquery.com/Events/jQuery.Event#event.stopPropagation.28.29) method on the event object.
```
$('li,div,ul').click(function (e) {
e.stopPropagation();
alert(this.id);
});
``` | I believe you'd want to use stopPropagation(); inside the click function. | Is it possible to have jQuery.click trigger on the top element only? | [
"",
"javascript",
"jquery",
""
] |
Symbian has a stack limit of 8kB. Does this also apply to the function calling in PyS60 apps? | There is a difference between python runtime and python apps. Also from PyS60 app developer point of view, it's the heapsize that's more interesting...
Version 1.9.5 comes by default with heapsize 100k min and 4M max. Of course you can define those by yourself when creating the SIS package to release and distribute your application.
Sorry if I answered right question with wrong answer (stack vs heap).
Stack is usually "enough", but with deep enough recursion you can run out of it. Have done it - and fixed some endless loops :) Never had any real stack problems. Usually it's the heap that runs out, esp with graphics manipulation. | Yes, PyS60 is based on CPython, thus uses the C stack. | Does the stack limit of Symbian also apply to PyS60? | [
"",
"python",
"symbian",
"nokia",
"pys60",
""
] |
In the following code `MessageReceived` is on a different thread to `label1` and when trying to access it I will get this error:
> Cross-thread operation not valid:
> Control 'label1' accessed from a
> thread other than the thread it was
> created on.
```
foo.MessageReceived += new Agent.MessageReceivedHandler(foo_MessageReceived);
void foo_MessageReceived(Message message)
{
label1.Text = message.Body;
}
```
**How can I solve this?**
**More**: apparently I need to use `delegate` and `invoke`, but I don't know how, can you please explain in more detail? | Make always sure you update your GUI on the main thread (GUI thread).
foo.MessageReceived += new Agent.MessageReceivedHandler(foo\_MessageReceived);
```
public delegate void MyDelegate(Message msg);
void foo_MessageReceived(Message message)
{
if (InvokeRequired)
{
BeginInvoke(new MyDelegate(foo_MessageReceived),new object[]{message});
}
else
{
label1.Text = message.Body;
}
}
``` | Hopefully this will be closed as an exact duplicate, but if not:
Don't touch the GUI from a non-GUI thread. Use BackgroundWorker and report progress appropriately, or read [the WinForms page of my threading article](http://pobox.com/~skeet/csharp/threads/winforms.shtml) for more direct control (Control.Invoke/BeginInvoke). | Help needed for 'cross-thread operation error' in C# | [
"",
"c#",
".net",
"multithreading",
"debugging",
""
] |
I am trying to insert a chunk of HTML into a div. I want to see if plain JavaScript way is faster than using jQuery. Unfortunately, I forgot how to do it the 'old' way. :P
```
var test2 = function(){
var cb = function(html){
var t1 = document.getElementById("test2");
var d = document.createElement("div");
d.id ="oiio";
d.innerHtml = html;
t1.appendChild(d);
console.timeEnd("load data with javascript");
};
console.time("load data with javascript");
$.get("test1.html", cb);
}
```
what am i doing wrong here guys?
**edit**:
Someone asked which is faster, jquery or plain js so i wrote up a test:
<https://jsben.ch/FBQYM>
plain js is 10% faster | I think this is what you want:
```
document.getElementById('tag-id').innerHTML = '<ol><li>html data</li></ol>';
```
Keep in mind that innerHTML is not accessible for all types of tags when using IE. (table elements for example) | Using JQuery would take care of that browser inconsistency. With the jquery library included in your project simply write:
```
$('#yourDivName').html('yourtHTML');
```
You may also consider using:
```
$('#yourDivName').append('yourtHTML');
```
This will add your gallery as the last item in the selected div. Or:
```
$('#yourDivName').prepend('yourtHTML');
```
This will add it as the first item in the selected div.
See the JQuery docs for these functions:
* <http://api.jquery.com/append/>
* <http://api.jquery.com/prepend/> | Inserting HTML into a div | [
"",
"javascript",
""
] |
How can you detect if a browser supports the CSS attribute display:inline-block? | There is no way to detect that with Javascript as it is a pure CSS attribute that does not relate to any object or function in Javascript. The best thing I can tell you is to check [here](http://www.quirksmode.org/css/display.html#inlineblock) for a pretty good compatibility list and use CSS to create a workaround. | Well, here's what you can go if you want to do it purely by examining the bavhiour of the browser w/ javascript instead of user agent sniffing:
Set up a test scenario, and a control scenario. With, say, the following structure:
* div
+ div w/ content "test"
+ div w/ content "test2"
Insert one copy into the document with the two internal divs set to inline-block, and insert another copy into the document with the two internal divs set to block. If the browser supports inline-block, then the containing divs will have different heights.
Alternate answer:
You can also use getComputedStyle to see how the browser is treating a given element's css. So, in theory, you could add an element with "display: inline-block," and then check the computedStyle to see if it survived. Only problem: IE doesn't support getComputedStyle. Instead, it has currentStyle. I don't know if currentStyle functions identically (presumably it functions similarly to the behaviour we want: disregarding "invalid" values). | Detect Browser Support for display:inline-block | [
"",
"javascript",
"css",
"cross-browser",
"browser-detection",
""
] |
In an app with a small number of POJOs and lots of helper methods that operate on them, what's better performance-wise: to make the helper classes singletons or to make the methods static? | Static methods would be very slightly better performance and memory wise:
1. Avoid (potential) overhead of virtual function calls.
2. Eliminates memory needed for an actual instance of the class.
3. Eliminates need to get an instance of the class when you use it.
But honestly I'd probably still make it a `singleton` anyways. The gains you'd get by not doing it are likely so small that they would make zero difference, even in a mobile environment. | Can you avoid either situation and make them regular classes?
Ignoring the performance question, I'd recommend avoiding singeltons and static methods to improve your testability.
Singletons and static methods can be very hard to test; in this regard singletons are essentially static methods but with a different name. [Misko Hevery](http://misko.hevery.com/), who works on the [Google Test team](http://googletesting.blogspot.com/), has a few good articles on this subject:
* [Singletons are Pathological Liars](http://misko.hevery.com/2008/08/17/singletons-are-pathological-liars/)
* [Static Methods are Death to Stability](http://misko.hevery.com/2008/12/15/static-methods-are-death-to-testability/) | Static methods or Singletons performance-wise (Android)? | [
"",
"java",
"android",
"performance",
"singleton",
"static-methods",
""
] |
I am coding a small Python module composed of two parts:
* some functions defining a public interface,
* an implementation class used by the above functions, but which is not meaningful outside the module.
At first, I decided to "hide" this implementation class by defining it inside the function using it, but this hampers readability and cannot be used if multiple functions reuse the same class.
So, in addition to comments and docstrings, is there a mechanism to mark a class as "private" or "internal"? I am aware of the underscore mechanism, but as I understand it it only applies to variables, function and methods name. | Use a single underscore prefix:
```
class _Internal:
...
```
This is the official Python convention for 'internal' symbols; `from module import *` does not import underscore-prefixed objects.
Reference to the single-underscore convention in the [Python 2](https://docs.python.org/2/tutorial/classes.html#private-variables-and-class-local-references) and [Python 3](https://docs.python.org/3/tutorial/classes.html#tut-private) documentation. | In short:
1. **You cannot enforce privacy**. There are no private classes/methods/functions in Python. At least, not strict privacy as in other languages, such as Java.
2. **You can only indicate/suggest privacy**. This follows a convention. The Python convention for marking a class/function/method as private is to preface it with an \_ (underscore). For example, `def _myfunc()` or `class _MyClass:`. You can also create pseudo-privacy by prefacing the method with two underscores (for example, `__foo`). You cannot access the method directly, but you can still call it through a special prefix using the classname (for example, `_classname__foo`). So the best you can do is indicate/suggest privacy, not enforce it.
Python is like [Perl](https://en.wikipedia.org/wiki/Perl) in this respect. To paraphrase a famous line about privacy from the Perl book, the philosophy is that you should stay out of the living room because you weren't invited, not because it is defended with a shotgun.
For more information:
* [Private variables](http://docs.python.org/tutorial/classes.html#private-variables) *Python Documentation*
* [Why are Python’s ‘private’ methods not actually private?](https://stackoverflow.com/questions/70528/why-are-pythons-private-methods-not-actually-private) *Stack Overflow question 70528* | "Private" (implementation) class in Python | [
"",
"python",
"access-modifiers",
""
] |
I have a data object (let's say it's called 'Entry') that has a set of potential states that look something like this:
```
1 - Created
2 - File added
3 - Approved
4 - Invalid
```
This is represented in the database with a 'Status' table with an autonumber primary key, then a 'StatusId' field in the main table, with the appropriate relationships set up.
In my (custom) data layer, I have the 'Entry' object, and, currently, I also declare an Enum with the states listed above specified. Finally I declare a private instance of this Enum along with the appropriate public property.
In my 'Commit()' method I cast the instance of the Enum to an integer and pass it to an Update stored procedure.
In my static 'GetEntry()' method I will obviously have an integer passed back from the database. I then use the 'Enum.Parse()' method to extract an object which is an instance of my Enum which corresponds to the returned status integer. I cast this to the type of my Enum and assign it to the local private variable.
My question is pretty simple - is this approach appropriate, and if not what alternative, other than just storing the raw integer value (which i'm not necessarily averse to), is better.
My reason for asking is that this all just seems incredibly messy to me, what with all the casting and maintaining two lists of the same set of values. I accept the benefit lies in a better experience for the consumer of the data object, but even so...
Thanks! | We have something familiar in one of our projects.
We have a table containting types of items. These types have an id, in the code we have an enum with the same id's.
The thing is, in the database we don't use autonumber (identity) so we have full control of the id.
And when saving our object we just take the id of the enum to save the object.
I also thought this approach was messy but it's not that bad afterall. | That method seems fine to me.
In the past I've done the same thing but also had a table that contained a row for each member of the enum that table was then the foreign key for any table that used the enum value, just so someone reading the database could understand what each status was without having to see the actual enum.
for example if I had an enum like
```
enum status
{
Active,
Deleted,
Inactive
}
```
I would have a table called status that would have the following records
ID Name
0 Active
1 Deleted
2 Inactive
That table would then be the foreign key to any tables that used that enum. | Using Enum for a data layer object's 'status' in C# | [
"",
"c#",
".net",
"sql-server",
"enums",
""
] |
I have a question I don't know if it can be solved. I have one C# project on Visual Studio 2005 and I want to create different DLL names depending on a preprocessor constant. What I have in this moment is the preprocessor constant, two snk files and two assembly's guid. I also create two configurations (Debug and Debug Preprocessor) and they compile perfectly using the snk and guid appropriate.
```
#if PREPROCESSOR_CONSTANT
[assembly: AssemblyTitle("MyLibraryConstant")]
[assembly: AssemblyProduct("MyLibraryConstant")]
#else
[assembly: AssemblyTitle("MyLibrary")]
[assembly: AssemblyProduct("MyLibrary")]
#endif
```
Now, I have to put the two assemblies into the GAC. The first assembly is added without problems but the second isn't.
What can I do to create two or more different assemblies from one Visual Studio project?
It's possible that I forgot to include a new line on "AssemblyInfo.cs" to change the DLL name depending on the preprocessor constant? | Here is a sample Post-Build event:
```
if "$(ConfigurationName)" == "Debug" goto Debug
if "$(ConfigurationName)" == "Release" goto Release
goto End
:Debug
del "$(TargetDir)DebugOutput.dll"
rename "$(TargetPath)" "DebugOutput.dll"
:Release
del "$(TargetDir)ReleaseOutput.dll"
rename "$(TargetPath)" "ReleaseOutput.dll"
:End
```
Change `DebugOutput.dll` and `ReleaseOutput.dll` to the proper filenames. you can change `"Debug"` and `"Release"` to support other configurations, and add sections to support more configurations.
---
That script will create two dlls with different file names; to create two different AssemblyNames, you have two options.
The assembly name is built as [follows](http://msdn.microsoft.com/en-us/library/system.reflection.assemblyname.aspx):
```
Name <,Culture = CultureInfo> <,Version = Major.Minor.Build.Revision> <, StrongName> <,PublicKeyToken> '\0'
```
So you have to either change the culture info, the version or the strong name.
The two simplest options are:
1. Change the assembly version:
```
#if SOME_COMPILER_SYMBOL
[assembly: AssemblyVersion("1.0.0.0")]
#else
[assembly: AssemblyVersion("1.0.0.1")]
#endif
```
2. Change the keyfile - create two keyfiles with the `sn` tool, and in `AssemblyInfo.cs`:
```
#if SOME_COMPILER_SYMBOL
[assembly: AssemblyKeyFile("FirstKey.snk")]
#else
[assembly: AssemblyKeyFile("SecondKey.snk")]
#endif
```
Both these options will result in two different assemblies as far as the GAC knows - since it compares the full assembly name, and not the 'simple' name. | Visual Studio does not allow per-configuration output filenames. However, you could rename the output file as part of your build script. You could do this in your MSBuild script for the particular project in question.
For example, put this at the end of your *.csproj* file:
```
<Target Name="AfterBuild">
<Copy SourceFiles="$(OutputPath)\YourAssembly.dll" DestinationFiles="$(OutputPath)\YourAssemblyRenamed.dll"/>
<Delete Files="$(OutputPath)\YourAssembly.dll"/>
</Target>
``` | How can I create different DLLs in one project? | [
"",
"c#",
"visual-studio",
"c-preprocessor",
"visual-studio-2005",
"assemblies",
""
] |
I'm really new to mocks and am trying to replace a private field with a mock object. Currently the instance of the private field is created in the constructor. My code looks like...
```
public class Cache {
private ISnapshot _lastest_snapshot;
public ISnapshot LatestSnapshot {
get { return this._lastest_snapshot; }
private set { this._latest_snapshot = value; }
}
public Cache() {
this.LatestSnapshot = new Snapshot();
}
public void Freeze(IUpdates Updates) {
ISnapshot _next = this.LastestSnapshot.CreateNext();
_next.FreezeFrom(Updates);
this.LastestSnapshot = _next;
}
}
```
What I'm trying to do is create a unit test that asserts `ISnapshot.FreezeFrom(IUpdates)` is called from within `Cache.Freeze(IUpdates)`. I'm guessing I should replace the private field `_latest_snapshot` with a mock object (maybe wrong assumption?). How would I go about that while still retaining a parameterless constructor and not resorting to making `LatestSnapshot`'s set public?
If I'm totally going about writing the test the wrong way then please do point out as well.
The actual implementation of `ISnapshot.FreezeFrom` itself calls a heirarchy of other methods with a deep object graph so I'm not too keen on asserting the object graph.
Thanks in advance. | I'm almost citing techniques from ["Working Effectively with Legacy Code"](https://rads.stackoverflow.com/amzn/click/com/0131177052):
1. Sub-class your class in a unit test and supersede your private variable with a mock object in it (by adding a public setter or in the constructor). You probably have to make the variable protected.
2. Make a protected getter for this private variable, and override it in testing subclass to return a mock object instead of the actual private variable.
3. Create a protected factory method for creating `ISnapshot` object, and override it in testing subclass to return an instance of a mock object instead of the real one. This way the constructor will get the right value from the start.
4. Parametrize constructor to take an instance of `ISnapshot`. | I'm not sure that you can do that. If you're wanting to test `_next` then you're probably going to have to pass it in as a parameter and then in your unit test pass in a Mock object which you can then test using an Expectation. That's what I'd be doing if I were trying to do it in Moq.
As an example of what I might try using the Moq framework:
```
Mock<ISnapshot> snapshotMock = new Mock<ISnapshot>();
snapshotMock.Expect(p => p.FreezeFrom(expectedUpdate)).AtMostOnce();
Cache c = new Cache(snapshotMock.Object);
c.Freeze(expectedUpdate);
```
Note: I haven't tried to compile the above code. Its just there to give an example of how I'd approach solving this. | How do I mock a private field? | [
"",
"c#",
"unit-testing",
"mocking",
""
] |
I will first describe the problem and then what I currently look at, in terms of libraries.
In my application, we have a set of variables that are always available. For example: TOTAL\_ITEMS, PRICE, CONTRACTS, ETC (we have around 15 of them). A clients of the application would like to have certain calculations performed and displayed, using those variables. Up until now, I have been constantly adding those calculations to the app. It's pain in the butt, and I would like to make it more generic by way of creating a template, where the user can specify a set of formulas that the application will parse and calculate.
Here is one case:
```
total_cost = CONTRACTS*PRICE*TOTAL_ITEMS
```
So, want to do something like that for the user to define in the template file:
`total_cost = CONTRACTS*PRICE*TOTAL_ITEMS` and some meta-date, like screen to display it on. Hence they will be specifying the formula with a screen. And the file will contain many formulas of this nature.
Right now, I am looking at two libraies: [Spirit](http://www.boost.org/doc/libs/1_38_0/libs/spirit/classic/index.html) and [matheval](http://sourceforge.net/projects/matheval)
Would anyone make recommendations what's better for this task, as well as references, examples, links?
Please let me know if the question is unclear, and I will try to further clarify it .
Thanks,
Sasha | If you have a fixed number of variables it may be a bit overkill to invoke a parser. Though Spirit is cool and I've been wanting to use it in a project.
I would probably just tokenize the string, make a map of your variables keyed by name (assuming all your variables are ints):
```
map<const char*,int*> vars;
vars["CONTRACTS"] = &contracts;
...
```
Then use a simple postfix calculator function to do the actual math.
Edit:
Looking at MathEval, it seems to do exactly what you want; set variables and evaluate mathematical functions using those variables. I'm not sure why you would want to create a solution at the level of a syntax parser. Do you have any requirements that MathEval does not fulfill? | Looks like it shouldn't be too hard to generate a simple parser using [yacc](http://dinosaur.compilertools.net/) and [bison](http://www.gnu.org/software/bison/) and integrate it into your code. | parser: parsing formulas in template files | [
"",
"c++",
"parsing",
"boost",
"boost-spirit",
""
] |
I'm getting a strange 5 to 7 second pause when executing PHP scripts from the command-line PHP client (PHP 5.2 on Windows).
During this pause the PHP script just appears to 'freeze' for a while before returning to the command prompt. It is not using any significant CPU time, it's like it is waiting for some delay.
After experimenting with PHP.ini, I've narrowed this down to the fact that the mysql or mysqli extension is enabled. If these extensions are both disabled, no annoying pause and the PHP script terminates in mere milliseconds.
The command I'm using is:
```
"C:\Program Files\PHP\php.exe" -f %1
```
Where %1 is the PHP script.
The pause still occurs even if the PHP script being executed is essentially empty:
```
<?php
?>
```
Do you know what is causing this pause and how I can remove it while still allowing mysql or mysqli support for PHP on the command line? | it's a [bug in mysql](http://bugs.mysql.com/bug.php?id=37226). you can solve it by getting the latest libmysql.dll (5.1.31 or higher. some older versions also work - see second link). make sure that's the libmysql.dll actually used and there are no other libmysql.dlls in your path. see the related [php issue](http://bugs.php.net/bug.php?id=41350) for details. | For me (Zend Server CE on Mac OS X), the imap exetension was the culprit. Disabling it solved the problem.
Anoyone wants to write a PHP extension bisecting script? :) | Strange 5 second pause with PHP command line interface (related to mysql/mysqli extension) | [
"",
"php",
"windows",
"command-line",
""
] |
I'm brand new with log4j and I can't seem to figure this out. If I set log4j.configuration to some garbage file that doesn't exist, the following program works as I expect. But if I don't then it's silent (other than printing out the properties):
```
package com.example.test;
import org.apache.log4j.*;
public class Log4jExample2 {
final static Logger logger = Logger.getLogger("test.Log4jExample2");
static void kvshow(String[] karray)
{
for (String k : karray)
{
String v = System.getProperty(k);
System.out.println(k+"="+v);
}
}
public static void main(String[] args) {
kvshow(new String[] {"log4j.configuration", "log4j.properties"});
BasicConfigurator.configure();
logger.debug("Hello world.");
}
}
```
Here's a runtime session:
```
>java -cp test-20090219.jar com.example.test.Log4jExample2
log4j.configuration=null
log4j.properties=null
>java -cp test-20090219.jar -Dlog4j.configuration=blah.cfg com.example.test.Log4jExample2
log4j.configuration=blah.cfg
log4j.properties=null
0 [main] DEBUG test.Log4jExample2 - Hello world.
```
I'm stumped. (again, there is no file called blah.cfg, this was the simplest way I could get things to work) Where is the log4j getting its instructions from? | Hmm, I have a lead... I was looking through the log4j manual and randomly tried this:
```
>java -Dlog4j.debug=true com.example.test.Log4jExample2
log4j: Trying to find [log4j.xml] using context classloader sun.misc.Launcher$AppClassLoader@11b86e7.
log4j: Trying to find [log4j.xml] using sun.misc.Launcher$ExtClassLoader@35ce36 class loader.
log4j: Trying to find [log4j.xml] using ClassLoader.getSystemResource().
log4j: Trying to find [log4j.properties] using context classloader sun.misc.Launcher$AppClassLoader@11b86e7.
log4j: Using URL [jar:file:/C:/appl/Java/jre6u10/lib/ext/bsf.jar!/log4j.properties] for automatic log4j configuration.
log4j: Reading configuration from URL jar:file:/C:/appl/Java/jre6u10/lib/ext/bsf.jar!/log4j.properties
log4j: Parsing for [root] with value=[FATAL, CONSOLE].
log4j: Level token is [FATAL].
log4j: Category root set to FATAL
log4j: Parsing appender named "CONSOLE".
log4j: Parsing layout options for "CONSOLE".
log4j: End of parsing for "CONSOLE".
log4j: Parsed "CONSOLE" options.
log4j: Finished configuring.
log4j.configuration=null
log4j.properties=null
```
Looks like the bean scripting framework is overriding me.
How can I stop this? What I want is, if the JRE is not invoked explicitly with a properties file, then I want it to use the settings included in my .jar file. I tried putting my own log4j.properties file in the root of my .jar file but that doesn't seem to work.
edit: aha! I think I got it: I have to do a System.setProperty before the first use of the Logger.getLogger(), something like:
```
static
{
System.setProperty("log4j.configuration",
"jar:file:my_jar_file_name_here.jar!/log4j.properties");
}
``` | The [BasicConfigurator](http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/BasicConfigurator.html) sets up default values for Log4J. So there is no reading from a configuration file when you use the BasicConfigurator. To configure from a properties file, use the [PropertiesConfigurator](http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/PropertyConfigurator.html) | log4j output suppressed? | [
"",
"java",
"log4j",
""
] |
To make it simpler for a webapp to share files with another app on a different server, I'm using a base href tag in my master page. As many people have discovered, this breaks webform paths. I have a working Form Adaptor class but am not sure how to get the absolute path of the url. Currently, my program is hardcoded to use something akin to :
```
HttpContext Context = HttpContext.Current;
value = "http://localhost" + Context.Request.RawUrl;
```
It is worth noting that I'm currently testing on my local IIS server, so there's a strange tendency for a lot of things I've tried using in order what the absolute path do not include the domain name (my local IIS is not visible externally). Which means it isn't an absolute path and thus the base href will wreck it.
Is there a good way to handle this such that it will work locally without hardcoding but will also work properly when uploaded to a server? I'd prefer to avoid anything that involves doing something different on the server-side copy.
Yes, I realize I could use separate web.config files locally and on the server to get this information but this is ugly and violates DRY. | I have used this in the past:
```
// Gets the base url in the following format:
// "http(s)://domain(:port)/AppPath"
HttpContext.Current.Request.Url.Scheme
+ "://"
+ HttpContext.Current.Request.Url.Authority
+ HttpContext.Current.Request.ApplicationPath;
``` | Old post but here is another slightly less verbose method
```
var baseUri = new Uri(HttpContext.Current.Request.Url, "/");
``` | Asp.Net Absolute Path of a URL | [
"",
"c#",
"asp.net",
"absolute-path",
""
] |
Given these two tables:
```
Foo (id, name) -- PK = id
Bar (fooId, value) -- PK = composite, fooId + value
-- value is a non-negative int
```
How can I find all the `Foo.name`s where there is no corresponding `Bar,value` above 0?
eg:
```
Foo
id name
1 a
2 b
3 c
Bar
fooid value
1 0
1 1
2 0
3 4
Result:
b
``` | I find the following the easiest to read and understand...
```
SELECT foo.name
FROM foo
WHERE NOT EXISTS (SELECT 'x'
FROM bar
WHERE bar.fooid = foo.id
AND bar.value > 0)
``` | ```
SELECT Name
FROM Bar
INNER JOIN Foo ON Foo.Id = Bar.fooId
GROUP BY fooId, name
HAVING SUM(Value) = 0
```
This query and the one posted by zodeus take about the same length of time to execute, however this one will not include any Foo records which are not referenced by the Bar table. For example if you also had the record Foo ( 4, d ), this query would still return 'b', where as zodeus's query would return 'b' and 'd'. | Mysql subquery question | [
"",
"sql",
"mysql",
"subquery",
""
] |
I'm able to get the value in the image tag (see XML below), but not the Category tag. The difference is one is a CDATA section and the other is just a string. Any help would be appreciated.
```
from xml.dom import minidom
xml = """<?xml version="1.0" ?>
<ProductData>
<ITEM Id="0471195">
<Category>
<![CDATA[Homogenizers]]>
</Category>
<Image>
0471195.jpg
</Image>
</ITEM>
<ITEM Id="0471195">
<Category>
<![CDATA[Homogenizers]]>
</Category>
<Image>
0471196.jpg
</Image>
</ITEM>
</ProductData>
"""
bad_xml_item_count = 0
data = {}
xml_data = minidom.parseString(xml).getElementsByTagName('ProductData')
parts = xml_data[0].getElementsByTagName('ITEM')
for p in parts:
try:
part_id = p.attributes['Id'].value.strip()
except(KeyError):
bad_xml_item_count += 1
continue
if not part_id:
bad_xml_item_count += 1
continue
part_image = p.getElementsByTagName('Image')[0].firstChild.nodeValue.strip()
part_category = p.getElementsByTagName('Category')[0].firstChild.data.strip()
print '\t'.join([part_id, part_category, part_image])
``` | > p.getElementsByTagName('Category')[0].firstChild
minidom does not flatten away <![CDATA[ sections to plain text, it leaves them as DOM CDATASection nodes. (Arguably it should, at least optionally. DOM Level 3 LS defaults to flattening them, for what it's worth, but minidom is much older than DOM L3.)
So the firstChild of Category is a Text node representing the whitespace between the <Category> open tag and the start of the CDATA section. It has two siblings: the CDATASection node, and another trailing whitespace Text node.
What you probably want is the textual data of all children of Category. In DOM Level 3 Core you'd just call:
```
p.getElementsByTagName('Category')[0].textContent
```
but minidom doesn't support that yet. Recent versions do, however, support another Level 3 method you can use to do the same thing in a more roundabout way:
```
p.getElementsByTagName('Category')[0].firstChild.wholeText
``` | CDATA is its own node, so the Category elements here actually have three children, a whitespace text node, the CDATA node, and another whitespace node. You're just looking at the wrong one, is all. I don't see any more obvious way to query for the CDATA node, but you can pull it out like this:
```
[n for n in category.childNodes if n.nodeType==category.CDATA_SECTION_NODE][0]
``` | xml.dom.minidom: Getting CDATA values | [
"",
"python",
"xml",
""
] |
I have a problem with a Java application running under Linux.
When I launch the application, using the default maximum heap size (64 MB), I see using the tops application that 240 MB of virtual Memory are allocated to the application. This creates some issues with some other software on the computer, which is relatively resource-limited.
The reserved virtual memory will not be used anyway, as far as I understand, because once we reach the heap limit an `OutOfMemoryError` is thrown. I ran the same application under windows and I see that the Virtual Memory size and the Heap size are similar.
Is there anyway that I can configure the Virtual Memory in use for a Java process under Linux?
**Edit 1**: The problem is not the Heap. The problem is that if I set a Heap of 128 MB, for example, still Linux allocates 210 MB of Virtual Memory, which is not needed, ever.\*\*
**Edit 2**: Using `ulimit -v` allows limiting the amount of virtual memory. If the size set is below 204 MB, then the application won't run even though it doesn't need 204 MB, only 64 MB. So I want to understand why Java requires so much virtual memory. Can this be changed?
**Edit 3**: There are several other applications running in the system, which is embedded. And the system does have a virtual memory limit (from comments, important detail). | This has been a long-standing complaint with Java, but it's largely meaningless, and usually based on looking at the wrong information. The usual phrasing is something like "Hello World on Java takes 10 megabytes! Why does it need that?" Well, here's a way to make Hello World on a 64-bit JVM claim to take over 4 gigabytes ... at least by one form of measurement.
```
java -Xms1024m -Xmx4096m com.example.Hello
```
# Different Ways to Measure Memory
On Linux, the [top](http://linux.die.net/man/1/top) command gives you several different numbers for memory. Here's what it says about the Hello World example:
```
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
2120 kgregory 20 0 4373m 15m 7152 S 0 0.2 0:00.10 java
```
* VIRT is the virtual memory space: the sum of everything in the virtual memory map (see below). It is largely meaningless, except when it isn't (see below).
* RES is the resident set size: the number of pages that are currently resident in RAM. In almost all cases, this is the only number that you should use when saying "too big." But it's still not a very good number, especially when talking about Java.
* SHR is the amount of resident memory that is shared with other processes. For a Java process, this is typically limited to shared libraries and memory-mapped JARfiles. In this example, I only had one Java process running, so I suspect that the 7k is a result of libraries used by the OS.
* SWAP isn't turned on by default, and isn't shown here. It indicates the amount of virtual memory that is currently resident on disk, *whether or not it's actually in the swap space*. The OS is very good about keeping active pages in RAM, and the only cures for swapping are (1) buy more memory, or (2) reduce the number of processes, so it's best to ignore this number.
The situation for Windows Task Manager is a bit more complicated. Under Windows XP, there are "Memory Usage" and "Virtual Memory Size" columns, but the [official documentation](http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/taskman_whats_there_w.mspx?mfr=true) is silent on what they mean. Windows Vista and Windows 7 add more columns, and they're actually [documented](http://windows.microsoft.com/en-US/windows7/see-details-about-your-computers-performance-using-task-manager). Of these, the "Working Set" measurement is the most useful; it roughly corresponds to the sum of RES and SHR on Linux.
# Understanding the Virtual Memory Map
The virtual memory consumed by a process is the total of everything that's in the process memory map. This includes data (eg, the Java heap), but also all of the shared libraries and memory-mapped files used by the program. On Linux, you can use the [pmap](http://linux.die.net/man/1/pmap) command to see all of the things mapped into the process space (from here on out I'm only going to refer to Linux, because it's what I use; I'm sure there are equivalent tools for Windows). Here's an excerpt from the memory map of the "Hello World" program; the entire memory map is over 100 lines long, and it's not unusual to have a thousand-line list.
```
0000000040000000 36K r-x-- /usr/local/java/jdk-1.6-x64/bin/java
0000000040108000 8K rwx-- /usr/local/java/jdk-1.6-x64/bin/java
0000000040eba000 676K rwx-- [ anon ]
00000006fae00000 21248K rwx-- [ anon ]
00000006fc2c0000 62720K rwx-- [ anon ]
0000000700000000 699072K rwx-- [ anon ]
000000072aab0000 2097152K rwx-- [ anon ]
00000007aaab0000 349504K rwx-- [ anon ]
00000007c0000000 1048576K rwx-- [ anon ]
...
00007fa1ed00d000 1652K r-xs- /usr/local/java/jdk-1.6-x64/jre/lib/rt.jar
...
00007fa1ed1d3000 1024K rwx-- [ anon ]
00007fa1ed2d3000 4K ----- [ anon ]
00007fa1ed2d4000 1024K rwx-- [ anon ]
00007fa1ed3d4000 4K ----- [ anon ]
...
00007fa1f20d3000 164K r-x-- /usr/local/java/jdk-1.6-x64/jre/lib/amd64/libjava.so
00007fa1f20fc000 1020K ----- /usr/local/java/jdk-1.6-x64/jre/lib/amd64/libjava.so
00007fa1f21fb000 28K rwx-- /usr/local/java/jdk-1.6-x64/jre/lib/amd64/libjava.so
...
00007fa1f34aa000 1576K r-x-- /lib/x86_64-linux-gnu/libc-2.13.so
00007fa1f3634000 2044K ----- /lib/x86_64-linux-gnu/libc-2.13.so
00007fa1f3833000 16K r-x-- /lib/x86_64-linux-gnu/libc-2.13.so
00007fa1f3837000 4K rwx-- /lib/x86_64-linux-gnu/libc-2.13.so
...
```
A quick explanation of the format: each row starts with the virtual memory address of the segment. This is followed by the segment size, permissions, and the source of the segment. This last item is either a file or "anon", which indicates a block of memory allocated via [mmap](http://linux.die.net/man/2/mmap).
Starting from the top, we have
* The JVM loader (ie, the program that gets run when you type `java`). This is very small; all it does is load in the shared libraries where the real JVM code is stored.
* A bunch of anon blocks holding the Java heap and internal data. This is a Sun JVM, so the heap is broken into multiple generations, each of which is its own memory block. Note that the JVM allocates virtual memory space based on the `-Xmx` value; this allows it to have a contiguous heap. The `-Xms` value is used internally to say how much of the heap is "in use" when the program starts, and to trigger garbage collection as that limit is approached.
* A memory-mapped JARfile, in this case the file that holds the "JDK classes." When you memory-map a JAR, you can access the files within it very efficiently (versus reading it from the start each time). The Sun JVM will memory-map all JARs on the classpath; if your application code needs to access a JAR, you can also memory-map it.
* Per-thread data for two threads. The 1M block is the thread stack. I didn't have a good explanation for the 4k block, but @ericsoe identified it as a "guard block": it does not have read/write permissions, so will cause a segment fault if accessed, and the JVM catches that and translates it to a `StackOverFlowError`. For a real app, you will see dozens if not hundreds of these entries repeated through the memory map.
* One of the shared libraries that holds the actual JVM code. There are several of these.
* The shared library for the C standard library. This is just one of many things that the JVM loads that are not strictly part of Java.
The shared libraries are particularly interesting: each shared library has at least two segments: a read-only segment containing the library code, and a read-write segment that contains global per-process data for the library (I don't know what the segment with no permissions is; I've only seen it on x64 Linux). The read-only portion of the library can be shared between all processes that use the library; for example, `libc` has 1.5M of virtual memory space that can be shared.
# When is Virtual Memory Size Important?
The virtual memory map contains a lot of stuff. Some of it is read-only, some of it is shared, and some of it is allocated but never touched (eg, almost all of the 4Gb of heap in this example). But the operating system is smart enough to only load what it needs, so the virtual memory size is largely irrelevant.
Where virtual memory size is important is if you're running on a 32-bit operating system, where you can only allocate 2Gb (or, in some cases, 3Gb) of process address space. In that case you're dealing with a scarce resource, and might have to make tradeoffs, such as reducing your heap size in order to memory-map a large file or create lots of threads.
But, given that 64-bit machines are ubiquitous, I don't think it will be long before Virtual Memory Size is a completely irrelevant statistic.
# When is Resident Set Size Important?
Resident Set size is that portion of the virtual memory space that is actually in RAM. If your RSS grows to be a significant portion of your total physical memory, it might be time to start worrying. If your RSS grows to take up all your physical memory, and your system starts swapping, it's well past time to start worrying.
But RSS is also misleading, especially on a lightly loaded machine. The operating system doesn't expend a lot of effort to reclaiming the pages used by a process. There's little benefit to be gained by doing so, and the potential for an expensive page fault if the process touches the page in the future. As a result, the RSS statistic may include lots of pages that aren't in active use.
# Bottom Line
Unless you're swapping, don't get overly concerned about what the various memory statistics are telling you. With the caveat that an ever-growing RSS may indicate some sort of memory leak.
With a Java program, it's far more important to pay attention to what's happening in the heap. The total amount of space consumed is important, and there are some steps that you can take to reduce that. More important is the amount of time that you spend in garbage collection, and which parts of the heap are getting collected.
Accessing the disk (ie, a database) is expensive, and memory is cheap. If you can trade one for the other, do so. | There is a known problem with Java and glibc >= 2.10 (includes Ubuntu >= 10.04, RHEL >= 6).
The cure is to set this env. variable:
```
export MALLOC_ARENA_MAX=4
```
If you are running Tomcat, you can add this to `TOMCAT_HOME/bin/setenv.sh` file.
For Docker, add this to Dockerfile
```
ENV MALLOC_ARENA_MAX=4
```
There is an IBM article about setting MALLOC\_ARENA\_MAX
<https://www.ibm.com/developerworks/community/blogs/kevgrig/entry/linux_glibc_2_10_rhel_6_malloc_may_show_excessive_virtual_memory_usage?lang=en>
[This blog post says](https://web.archive.org/web/20161228221330/https://infobright.com/blog/malloc_arena_max/)
> resident memory has been known to creep in a manner similar to a
> memory leak or memory fragmentation.
There is also an open JDK bug [JDK-8193521 "glibc wastes memory with default configuration"](https://bugs.openjdk.java.net/browse/JDK-8193521)
search for MALLOC\_ARENA\_MAX on Google or SO for more references.
You might want to tune also other malloc options to optimize for low fragmentation of allocated memory:
```
# tune glibc memory allocation, optimize for low fragmentation
# limit the number of arenas
export MALLOC_ARENA_MAX=2
# disable dynamic mmap threshold, see M_MMAP_THRESHOLD in "man mallopt"
export MALLOC_MMAP_THRESHOLD_=131072
export MALLOC_TRIM_THRESHOLD_=131072
export MALLOC_TOP_PAD_=131072
export MALLOC_MMAP_MAX_=65536
``` | Virtual Memory Usage from Java under Linux, too much memory used | [
"",
"java",
"linux",
"memory",
"virtual-memory",
""
] |
I am looking for information on the best practices or project layout for software that uses SQL embedded inside VB.NET or C#. The software will connect to a full SQL DB. The software was written in VB6 and ported to VB.NET, we want to update it to use .NET functionality but I am not sure where to start with my research. We are using Visual Studio 2005. All database manipulations are done from VB.
Update: To clarify. We are currently using SqlConnection, SqlDataAdapter, SqlDataReader to connect to the database. What I mean by embed is that the SQL stored procedures are scripted inside our VB code and then run on the db. All of our tables, stored procs, views, etc are all manipulated in the VB code. The layout of our code is quite messy. I am looking for a better architecture or pattern that we can use to organize our code.
Can you recommend any books, webpages, topics that I can google, etc to help me better understand the best way for us to do this. | Would it be possible to convert it to using [LINQ](http://en.wikipedia.org/wiki/Language_Integrated_Query)? It's safer than converting it to using regular old embedded SQL statements. | > I am looking for a better architecture or pattern that we can use to organize our code
> ...
>
> topics that I can google
Take a look at DAL (Data Access Layer) for database transactions
Here is a link to a StackOverflow question posted by someone who is facing a similar situation
[Creating a Class Library in VB.NET](https://stackoverflow.com/questions/600962/creating-a-class-library-in-vb-net/601227#601227)
When you google ["How to create DAL"](http://tinyurl.com/ama3to), you will see list of how to create a DAL as well as what DAL is.
And here is a nice article that shows how DAL fits into an N-Tier achitecture
* [What is n-Tier Architecture?](http://www.developerfusion.com/article/3058/boosting-your-net-application-performance/2/)
* [Webopedia: N-Tier Application Architecture](http://www.webopedia.com/quick_ref/app.arch.asp) - Shows a nice graphical representation | What is the best way to embed SQL in VB.NET | [
"",
"sql",
"vb.net",
""
] |
ignore this, i thought of a workaround involving header generation. It isnt the nicest solution but it works. This question is to weird to understand. Basically i want to call a virtual function that hasnt been declared in the lib or dll and use it as normal (but have it not implemented/empty func).
I have an abstract base class in my library. All my plugins inherit from it, the user plugin inherits from this class and his application uses this class as a plugin pointer. I want that user to be able to extend the class and add his functions. The problem is, I am sure if he adds a virtual function and try to call it, the code will crash due to my objects not having the extra data in its vtable. How can I work around that? I thought of inheriting it but that would lead to ugly problems when a 3rd user comes to play. I dont want him to typecast to send the extended functions.
I was thinking of a msg function like intptr\_t sendMsg(enum msgName, void\* argv); But that removes the safty and I'd need to typecast everything. Whats the best solution for this? I would much rather use vtables then use a sendMsg function. How can I work around this? | Are you asking if you can add virtual functions to the **base** class without recompiling? The short answer to that is "no". The long answer is in your question, you'd have to provide some kind of generic "call\_func" interface that would allow you to call functions "dynamically". | I am not 100% sure I see the problem.
If the user1 derived type extends your base class (with more virtual methods) then that should be fine (of course your code will never know or understand these new methods but presumably you would not be calling them:
```
class B
{
virtual void doStuff() { /* Nothing */}
};
// User 1 version:
class U1: public B
{
virtual void doStuff()
{
this->doA();
this->doB();
}
virtual void doA() {}
virtual void doB() {}
};
// User 2 version can extend it differently.
```
Note:
If you are worried by slicing because you are storing objects in a vector that is a slightly different problem.
```
std::vector<B> objs;
objs.push_back(U1());
std::for_each(objs.begin(),objs.end(),std::mem_fun_ref(&B::doStuff));
```
Here the problem is that a user defined type U1 can not be copied into the vector because the vector holds only B objects. This slices off the extra data held in U1.
The solution to this problem is that you need to hold pointers in the vector. This of course leads to other problems with exception safety. So boost has the ptr\_vector<> container to hold objects correctly but still let them be used like objects.
```
#include <boost/ptr_container/ptr_vector.hpp>
......
boost::ptr_vector<B> objs;
objs.push_back(new U1());
std::for_each(objs.begin(),objs.end(),std::mem_fun_ref(&B::doStuff));
``` | extend a abstract base class w/o source recompilation? | [
"",
"c++",
""
] |
I know how to draw a button in C++ but how would i make an icon on it can someone post source or give reference please? by SendMessage() or if not that way just please paste
Please need easier anwsers without so many files im new a bit | If you use MFC then I would recommend you to use the following `CButton` method `SetIcon`:
```
CButton myButton;
// Create an icon button.
myButton.Create(_T("My button"), WS_CHILD|WS_VISIBLE|BS_ICON,
CRect(10,10,60,50), pParentWnd, 1);
// Set the icon of the button to be the system question mark icon.
myButton.SetIcon( ::LoadIcon(NULL, IDI_QUESTION) );
```
This works very well. | Since you're new, you may also wish to consult the MSDN Library. You can find information on [Button Styles](http://msdn.microsoft.com/en-us/library/bb775951(VS.85).aspx) (see, specifically, the BS ICON and BS BITMAP styles) and the [BM\_SETIMAGE message](http://msdn.microsoft.com/en-us/library/bb761822(VS.85).aspx) . | How to make an icon button in C++ | [
"",
"c++",
"winapi",
"button",
"reference",
"icons",
""
] |
I want to be able to detect when a write to memory address occurs -- for example by setting a callback attached to an interrupt. Does anyone know how?
I'd like to be able to do this at runtime (possibly gdb has this feature, but my particular
application causes gdb to crash). | If you want to intercept writes to a range of addresses, you can use [`mprotect()`](http://linux.die.net/man/2/mprotect) to mark the memory in question as non-writeable, and install a signal handler using [`sigaction()`](http://linux.die.net/man/2/sigaction) to catch the resulting SIGSEGV, do your logging or whatever and mark the page as writeable again. | What you need is access to the X86 debug registers: <http://en.wikipedia.org/wiki/Debug_register>
You'll need to set the breakpoint address in one of DR0 to DR3, and then the condition (data write) in DR7. The interrupt will occur and you can run your debug code to read DR6 and find what caused the breakpoint.
If GDB doesn't work, you might try a simpler/smaller debugger such as <http://sourceforge.net/projects/minibug/> - if that isn't working, you can at least go through the code and understand how to use the debugging hardware on the processor yourself.
Also, there's a great IBM developer resource on mastering linux debugging techniques which should provide some additional options:
<http://www.ibm.com/developerworks/linux/library/l-debug/>
A reasonably good article on doing this is windows is here (I know you're running on linux, but others might come along to this question wanting to do it in windows):
<http://www.codeproject.com/KB/debug/hardwarebreakpoint.aspx>
-Adam | Possible to trap write to address (x86 - linux) | [
"",
"c++",
"c",
"linux",
"x86",
""
] |
I've been reading the articles on MSDN about Unity (Dependency Injection, Inversion of Control), but I think I need it explained in simple terms (or simple examples). I'm familiar with the MVPC pattern (we use it here), but I just can't really grasp this Unity thing yet, and I think it's the next step in our application design. | Unity is just an IoC "container". Google StructureMap and try it out instead. A bit easier to grok, I think, when the IoC stuff is new to you.
Basically, if you understand IoC then you understand that what you're doing is inverting the control for when an object gets created.
Without IoC:
```
public class MyClass
{
IMyService _myService;
public MyClass()
{
_myService = new SomeConcreteService();
}
}
```
With IoC container:
```
public class MyClass
{
IMyService _myService;
public MyClass(IMyService myService)
{
_myService = myService;
}
}
```
Without IoC, your class that relies on the IMyService has to new-up a concrete version of the service to use. And that is bad for a number of reasons (you've coupled your class to a specific concrete version of the IMyService, you can't unit test it easily, you can't change it easily, etc.)
With an IoC container you "configure" the container to resolve those dependencies for you. So with a constructor-based injection scheme, you just pass the interface to the IMyService dependency into the constructor. When you create the MyClass with your container, your container will resolve the IMyService dependency for you.
Using StructureMap, configuring the container looks like this:
```
StructureMapConfiguration.ForRequestedType<MyClass>().TheDefaultIsConcreteType<MyClass>();
StructureMapConfiguration.ForRequestedType<IMyService>().TheDefaultIsConcreteType<SomeConcreteService>();
```
So what you've done is told the container, "When someone requests the IMyService, give them a copy of the SomeConcreteService." And you've also specified that when someone asks for a MyClass, they get a concrete MyClass.
That's all an IoC container really does. They can do more, but that's the thrust of it - they resolve dependencies for you, so you don't have to (and you don't have to use the "new" keyword throughout your code).
Final step: when you create your MyClass, you would do this:
```
var myClass = ObjectFactory.GetInstance<MyClass>();
``` | I just watched the 30 minute Unity Dependency Injection IoC Screencast by David Hayden and felt that was a good explaination with examples. Here is a snippet from the show notes:
The screencast shows several common usages of the Unity IoC, such as:
* Creating Types Not In Container
* Registering and Resolving TypeMappings
* Registering and Resolving Named TypeMappings
* Singletons, LifetimeManagers, and the ContainerControlledLifetimeManager
* Registering Existing Instances
* Injecting Dependencies into Existing Instances
* Populating the UnityContainer via App.config / Web.config
* Specifying Dependencies via Injection API as opposed to Dependency Attributes
* Using Nested ( Parent-Child ) Containers | Can someone explain Microsoft Unity? | [
"",
"c#",
"dependency-injection",
"inversion-of-control",
"unity-container",
""
] |
I want to show a selection in a WPF TextBox even when it's not in focus. How can I do this? | I have used this solution for a RichTextBox, but I assume it will also work for a standard text box. Basically, you need to handle the LostFocus event and mark it as handled.
```
protected void MyTextBox_LostFocus(object sender, RoutedEventArgs e)
{
// When the RichTextBox loses focus the user can no longer see the selection.
// This is a hack to make the RichTextBox think it did not lose focus.
e.Handled = true;
}
```
The TextBox will not realize it lost the focus and will still show the highlighted selection.
I'm not using data binding in this case, so it may be possible that this will mess up the two way binding. You may have to force binding in your LostFocus event handler. Something like this:
```
Binding binding = BindingOperations.GetBinding(this, TextProperty);
if (binding.UpdateSourceTrigger == UpdateSourceTrigger.Default ||
binding.UpdateSourceTrigger == UpdateSourceTrigger.LostFocus)
{
BindingOperations.GetBindingExpression(this, TextProperty).UpdateSource();
}
``` | [TextBoxBase.IsInactiveSelectionHighlightEnabled](https://msdn.microsoft.com/en-us/library/system.windows.controls.primitives.textboxbase.isinactiveselectionhighlightenabled(v=vs.110).aspx) Property has available since .NET Framework 4.5
```
public bool IsInactiveSelectionHighlightEnabled { get; set; }
``` | How to keep WPF TextBox selection when not focused? | [
"",
"c#",
"wpf",
"textbox",
""
] |
I have a problem with combining or calculating common/equal part of these two dictionaries. In my dictionaries, values are lists:
```
d1 = {0:['11','18','25','38'],
1:['11','18','25','38'],
2:['11','18','25','38'],
3:['11','18','25','38']}
d2 = {0:['05','08','11','13','16','25','34','38','40', '43'],
1:['05', '08', '09','13','15','20','32','36','38', '40','41'],
2:['02', '08', '11', '13', '18', '20', '22','33','36','39'],
3:['06', '11', '12', '25', '26', '27', '28', '30', '31', '37']}
```
I'd like to check "d2" and know if there are numbers from "d1". If there are some, I'd like to update one of them with new data or receive 3rd dictionary "d3" with only the values that are identical/equal in both "d1" and "d2" like:
```
d3 = {0:['11','25','38'], 1:['38'], 2:['11','18'], 3:['11','25']}
```
Can anyone help me with this?
My fault I forgot to be more specific. I'm looking for a solution in Python. | Assuming this is Python, you want:
```
dict((x, set(y) & set(d1.get(x, ()))) for (x, y) in d2.iteritems())
```
to generate the resulting dictionary "d3".
### Python 3.0+ version
```
>>> d3 = {k: list(set(d1.get(k,[])).intersection(v)) for k, v in d2.items()}
{0: ['11', '25', '38'], 1: ['38'], 2: ['11', '18'], 3: ['11', '25']}
```
The above version (as well as Python 2.x version) allows empty intersections therefore additional filtering is required in general case:
```
>>> d3 = {k: v for k, v in d3.items() if v}
```
Combining the above in one pass:
```
d3 = {}
for k, v in d2.items():
# find common elements for d1 & d2
v3 = set(d1.get(k,[])).intersection(v)
if v3: # whether there are common elements
d3[k] = list(v3)
```
---
[Edit: I made this post community wiki so that people can improve it if desired. I concede it might be a little hard to read if you're not used to reading this sort of thing in Python.] | Offering a more readable solution:
```
d3= {}
for common_key in set(d1) & set(d2):
common_values= set(d1[common_key]) & set(d2[common_key])
d3[common_key]= list(common_values)
```
### EDIT after suggestion:
If you want only keys having at least one common value item:
```
d3= {}
for common_key in set(d1) & set(d2):
common_values= set(d1[common_key]) & set(d2[common_key])
if common_values:
d3[common_key]= list(common_values)
```
You could keep the d1 and d2 values as sets instead of lists, if order and duplicates are not important. | Python - How to calculate equal parts of two dictionaries? | [
"",
"python",
"list",
"dictionary",
"merge",
""
] |
**Duplicate Question**
[Passing null arguments to C# methods](https://stackoverflow.com/questions/271588/passing-null-arguments-to-c-methods/271600)
Can I do this in c# for .Net 2.0?
```
public void myMethod(string astring, int? anint)
{
//some code in which I may have an int to work with
//or I may not...
}
```
If not, is there something similar I can do? | Yes, assuming you added the chevrons deliberately and you really meant:
```
public void myMethod(string astring, int? anint)
```
`anint` will now have a `HasValue` property. | Depends on what you want to achieve. If you want to be able to drop the `anint` parameter, you have to create an overload:
```
public void myMethod(string astring, int anint)
{
}
public void myMethod(string astring)
{
myMethod(astring, 0); // or some other default value for anint
}
```
You can now do:
```
myMethod("boo"); // equivalent to myMethod("boo", 0);
myMethod("boo", 12);
```
If you want to pass a nullable int, well, see the other answers. ;) | Nullable Method Arguments in C# | [
"",
"c#",
"arguments",
"nullable",
""
] |
I've seen a few JavaScript image rotators that use either the HTML5 canvas element or an AJAX call to a server-side script, but is it possible to do it without using those methods? Internet Explorer doesn't support canvas (I'm aware of excanvas, but I'd like to do without if possible) and I'm not sure if AJAX will be fluid enough. If there is a way, are there any open source scripts, examples, or resources that you could point me to? | Alas, CSS does not support rotating images in any way, shape or form (unless you count [CSS Transforms](http://webkit.org/blog/130/css-transforms/), which are only supported by Safari 4 and Firefox 3.1).
Your best bet is to use [Raphael](http://raphaeljs.com)'s image() and rotate(), which should support all semi-modern browsers (using SVG) and most versions of IE (using VML). | This jQuery plugin works in major browsers including IE: <http://wilq32.googlepages.com/wilq32.rollimage222> . It makes use of excanvas, but at least it allows you to evaluate if that method is good enough for your purposes. | Can an image be rotated by JavaScript without canvas or AJAX? | [
"",
"javascript",
"image-rotation",
""
] |
I've got a strange thing happening with my app.config file. My ConnectionStrings section contains this:
```
<connectionStrings>
<add name="Connection" connectionString="Data Source=TheServer;
Initial Catalog=TheDatabase;IntegratedSecurity=SSPI"
providerName="System.Data.SqlClient"/>
</connectionStrings>
```
However, when I query the section via ConfigurationManager.ConnectionStrings[0], I get back this connection string:
```
Data Source=.\\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true
```
Where is it getting this value from? | It is read from machine.config, you can either make sure to clear all connection strings before adding your own:
```
<connectionStrings>
<clear/>
<add name="Connection" connectionString="Data Source=TheServer;
Initial Catalog=TheDatabase;IntegratedSecurity=SSPI"
providerName="System.Data.SqlClient"/>
</connectionStrings>
```
Or just never reference your connection strings by indexes, use names you give them:
```
ConfigurationManager.ConnectionStrings["Connection"]
``` | It comes from machine.config. .NET Automatically merges the connection string sections (and some others I believe) of your application config (or web config) and your machine.config.
You can read about how it works in ASP.NET [here](http://msdn.microsoft.com/en-us/library/ms178685.aspx). | app.config weirdness | [
"",
"c#",
"app-config",
""
] |
I'm extending an entities' partial class to have a method. How do I get a reference to the context that the entity is attached to (if any) to get more entities from the same context.
If that's not clear, basically the code I'm looking to write is along these lines (air code):
```
public void AssignSize(int width, int height)
{
var size = (from s in this.context.Sizes
where s.width == width && s.height == height
select s).FirstOrDefault();
...
}
```
Nb: This doesn't work. | You need to pass the context to this method, or, better yet, rather than pass in width and height, pass in the size object itself. | Take a look at this article:
[how-to-get-the-objectcontext-from-an-entity](http://blogs.msdn.com/b/alexj/archive/2009/06/08/tip-24-how-to-get-the-objectcontext-from-an-entity.aspx)
It shows a workaround to get the context from an entity. | Entity Framework get CurrentContext | [
"",
"c#",
"entity-framework",
""
] |
To prevent actions from happening, I frequently type
```
function(){return false;}
```
Is there a shortcut? | You could declare a named function like this:
```
function always_false() { return false; }
```
then use `always_false()` wherever you would have previously created the anonymous function. | I often have a ["no op" function](http://en.wikipedia.org/wiki/NOP) defined at the top of my common js file:
```
function nop() { return false }
```
I use it whenever I need a "do nothing" or a "cancel event" handler (eg `div.oncontextmenu = nop`). In IE this has the added benefit that memory does not leak when creating similar [anonymous] functions on the fly and assigning them to event handlers. At least that's what [IE Drip](http://www.outofhanwell.com/ieleak/index.php?title=Main_Page) tells me. | Is there a JavaScript (or jQuery) shortcut for "function(){return false;}"? | [
"",
"javascript",
"jquery",
""
] |
I'm a total newbie when it comes to SQL. I'm making a site in ASP.NET for doing surveys. A privileged admin user will be able to build a survey. Then lots of other people will respond to the survey.
Once I have the set of questions for a new survey, what is the best way to automatically construct a table and an INSERT query to store the responses?
UPDATE
Thanks for the quick responses! I'm still a little unclear on how survey responses would best be stored in this scenario. Would each respondent get a row of the table? And if so, would the columns be "answer given for question k of the survey identified by the entry in column 1"? | You dont want to build a new table for each survey.
Create a surveys table (SurveyID, UserID, Name, etc)
Create a Questions Table (QuestionID, SurveyID, QuestionText, SortOrder, etc)
optionally, Create an Options table, assuming you have multiple choice type questions (OptionID, QuestionID, OptionText, etc)
Then when someone creates a survey, you insert into the Surveys Table, referencing that person's UserID as the foriegn key, then get the newly inserted SurveyID,
Then for each question they add, insert it into the Questions table, using the above SurveyID as the foriegn key.. and so on.
**EDIT to answer your edit:**
Sorry I should have followed through to cover storing answers as well.
You would want another table called SurveyResponses (ResponseID, Name, etc)
And another table I'll call ResponseAnswers(ResponseAnswerID, SurveyID, ResponseID, QuestionID, AnswerText/AnswerID) Where SurveyID and ResponseID are foriegn keys to thier respective tables, and depending on wether users have multiple choice, or enter an answer, you would either store thier answer as text(varchar) or as another foriegn key to the options table. | You probably don't want to be programatically generating the schema.
Instead, have a table for surveys, for questions (which belong to surveys), for response sets (one per user), and question responses (which belong to the response sets). | SQL Structure to Store Surveys and Answers - Build Tables and Queries Based on User Data? | [
"",
"sql",
"survey",
"auto-generate",
""
] |
If I have a table containing schedule information that implies particular dates, is there a SQL statement that can be written to convert that information into actual rows, using some sort of CROSS JOIN, perhaps?
Consider a payment schedule table with these columns:
* **StartDate** - the date the schedule begins (1st payment is due on this date)
* **Term** - the length in months of the schedule
* **Frequency** - the number of months between recurrences
* **PaymentAmt** - the payment amount :-)
```
SchedID StartDate Term Frequency PaymentAmt
-------------------------------------------------
1 05-Jan-2003 48 12 1000.00
2 20-Dec-2008 42 6 25.00
```
Is there a single SQL statement to allow me to go from the above to the following?
```
Running
SchedID Payment Due Expected
Num Date Total
--------------------------------------
1 1 05-Jan-2003 1000.00
1 2 05-Jan-2004 2000.00
1 3 05-Jan-2005 3000.00
1 4 05-Jan-2006 4000.00
1 5 05-Jan-2007 5000.00
2 1 20-Dec-2008 25.00
2 2 20-Jun-2009 50.00
2 3 20-Dec-2009 75.00
2 4 20-Jun-2010 100.00
2 5 20-Dec-2010 125.00
2 6 20-Jun-2011 150.00
2 7 20-Dec-2011 175.00
```
I'm using MS SQL Server 2005 (no hope for an upgrade soon) and I can already do this using a table variable and while loop, but it seemed like some sort of CROSS JOIN would apply but I don't know how that might work.
Your thoughts are appreciated.
*EDIT: I'm actually using SQL Server **2005** though I initially said 2000. We aren't quite as backwards as I thought. Sorry.* | I cannot test the code right now, so take it with a pinch of salt, but I think that something looking more or less like the following should answer the question:
```
with q(SchedId, PaymentNum, DueDate, RunningExpectedTotal) as
(select SchedId,
1 as PaymentNum,
StartDate as DueDate,
PaymentAmt as RunningExpectedTotal
from PaymentScheduleTable
union all
select q.SchedId,
1 + q.PaymentNum as PaymentNum,
DATEADD(month, s.Frequency, q.DueDate) as DueDate,
q.RunningExpectedTotal + s.PaymentAmt as RunningExpectedTotal
from q
inner join PaymentScheduleTable s
on s.SchedId = q.SchedId
where q.PaymentNum <= s.Term / s.Frequency)
select *
from q
order by SchedId, PaymentNum
``` | I've used table-valued functions to achieve a similar result. Basically the same as using a table variable I know, but I remember being really pleased with the design.
The usage ends up reading very well, in my opinion:
```
/* assumes @startdate and @enddate schedule limits */
SELECT
p.paymentid,
ps.paymentnum,
ps.duedate,
ps.ret
FROM
payment p,
dbo.FUNC_get_payment_schedule(p.paymentid, @startdate, @enddate) ps
ORDER BY p.paymentid, ps.paymentnum
``` | Can I use SQL to plot actual dates based on schedule information? | [
"",
"sql",
"sql-server",
"sql-server-2005",
"t-sql",
""
] |
I have this test app:
```
import java.applet.*;
import java.awt.*;
import java.net.URL;
public class Test extends Applet
{
public void init()
{
URL some=Test.class.getClass().getClassLoader().getResource("/assets/pacman.png");
System.out.println(some.toString());
System.out.println(some.getFile());
System.out.println(some.getPath());
}
}
```
When I run it from Eclipse, I get the error:
```
java.lang.NullPointerException
at Test.init(Test.java:9)
at sun.applet.AppletPanel.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
```
Classpath (from .CLASSPATH file)
```
<classpathentry kind="src" path="src"/>
```
In my c:\project\src folder, I have only the Test.java file and the 'assets' directory which contains pacman.png.
What am I doing wrong and how to resolve it? | I would do it this way:
```
final InputStream stream;
stream = Test.class.getResourceAsStream("assets/pacman.png");
System.out.println("Stream = " + stream);
```
"/assets/pacman.png" is an absolute location whle "assets/pacman.png" is a relative location. | You don't need the slash at the start when getting a resource from a `ClassLoader`, because there's no idea of a "relative" part to start with. You only need it when you're getting a resource from a `Class` where relative paths go from the class's package level.
In addition, you don't want `Test.class.getClass()` as that gets the class *of* Test.class, which will be `Class<Class>`.
In other words, try either of these lines:
```
URL viaClass=Test.class.getResource("/assets/pacman.png");
URL viaLoader=Test.class.getClassLoader().getResource("assets/pacman.png");
``` | getClassLoader().getResource() returns null | [
"",
"java",
"applet",
""
] |
How to retrieve a webpage and diplay the html to the console with C# ? | Use the `System.Net.WebClient` class.
```
System.Console.WriteLine(new System.Net.WebClient().DownloadString(url));
``` | I have knocked up an example:
```
WebRequest r = WebRequest.Create("http://www.msn.com");
WebResponse resp = r.GetResponse();
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
Console.WriteLine(sr.ReadToEnd());
}
Console.ReadKey();
```
Here is another option, using the WebClient this time and do it asynchronously:
```
static void Main(string[] args)
{
System.Net.WebClient c = new WebClient();
c.DownloadDataCompleted +=
new DownloadDataCompletedEventHandler(c_DownloadDataCompleted);
c.DownloadDataAsync(new Uri("http://www.msn.com"));
Console.ReadKey();
}
static void c_DownloadDataCompleted(object sender,
DownloadDataCompletedEventArgs e)
{
Console.WriteLine(Encoding.ASCII.GetString(e.Result));
}
```
The second option is handy as it will not block the UI Thread, giving a better experience. | How to retrieve a webpage with C#? | [
"",
"c#",
"http",
""
] |
So, I'm playing with decorators in Python 2.6, and I'm having some trouble getting them to work. Here is my class file:
```
class testDec:
@property
def x(self):
print 'called getter'
return self._x
@x.setter
def x(self, value):
print 'called setter'
self._x = value
```
What I thought this meant is to treat `x` like a property, but call these functions on get and set. So, I fired up IDLE and checked it:
```
>>> from testDec import testDec
from testDec import testDec
>>> t = testDec()
t = testDec()
>>> t.x
t.x
called getter
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "testDec.py", line 18, in x
return self._x
AttributeError: testDec instance has no attribute '_x'
>>> t.x = 5
t.x = 5
>>> t.x
t.x
5
```
Clearly the first call works as expected, since I call the getter, and there is no default value, and it fails. OK, good, I understand. However, the call to assign `t.x = 5` seems to create a new property `x`, and now the getter doesn't work!
What am I missing? | You seem to be using [classic old-style classes](https://docs.python.org/2/glossary.html#term-classic-class "term-classic-class") in python 2. In order for [properties](https://docs.python.org/2/library/functions.html#property "property") to work correctly you need to use [new-style classes](https://docs.python.org/2/glossary.html#term-new-style-class "term-new-style-class") instead (in python 2 you must [inherit from `object`](https://docs.python.org/2/reference/datamodel.html#newstyle "newstyle")). Just declare your class as `MyClass(object)`:
```
class testDec(object):
@property
def x(self):
print 'called getter'
return self._x
@x.setter
def x(self, value):
print 'called setter'
self._x = value
```
It works:
```
>>> k = testDec()
>>> k.x
called getter
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/devel/class_test.py", line 6, in x
return self._x
AttributeError: 'testDec' object has no attribute '_x'
>>> k.x = 5
called setter
>>> k.x
called getter
5
>>>
```
Another detail that might cause problems is that both methods need the same name for the property to work. **If you define the setter with a different name like this it won't work**:
```
@x.setter
def x_setter(self, value):
...
```
And one more thing that is not completely easy to spot at first, is the order: The getter **must be defined first**. If you define the setter first, you get `name 'x' is not defined` error. | Just a note for other people who stumble here looking for this exception: both functions need to have the same name. Naming the methods as follows will result in an exception:
```
@property
def x(self): pass
@x.setter
def x_setter(self, value): pass
```
Instead give both methods the same name
```
@property
def x(self): pass
@x.setter
def x(self, value): pass
```
It is also important to note that the order of the declaration matters. The getter must be defined before the setter in the file or else you will get a `NameError: name 'x' is not defined` | Why does @foo.setter in Python not work for me? | [
"",
"python",
"decorator",
"new-style-class",
""
] |
I am trying to pass an array of values from php to mysql stored procedures as parameter list and how to use the array inside the stored procedure. The query in the procedure has three IN statements in in there so I would like to do `IN(@listOfids)` where @listOfids is 1,2,3,4 (an imploded array from php). | So I got a workaround which is to concatenate the query and the parameters so the pseudo code is
```
CREATE PROCEDURE `related_stories`(IN param1 VARCHAR(255), IN param2 VARCHAR(255), IN param3 VARCHAR(255), IN publishDate INT(11), IN tlimit INT(11))
BEGIN
SET @query =CONCAT( '
select s.* from
(
select * from
(
SELECT something where condition IN (',param1,')
) as table1
UNION ALL
select * from
(
SELECT something where condition IN (',param2,')
) as table2
UNION ALL
select * from
(
SELECT something where condition IN (',param3,')
) as table3
) as s
WHERE (s.publish_date < ',publishDate,')
GROUP BY id limit ',tlimit,';');
PREPARE stmtInsert FROM @query;
EXECUTE stmtInsert;
END
```
param1,param2,param3 are imploded arrays that is passed in via php e.g.('1,2,3,4'). Hope this helps someone | I think the main problem here is that MySQL doesn't support arrays as a data type. You need to form a [one-to-many](http://en.wikipedia.org/wiki/One-to-many) relationship to another table that contains a foreign key back to your main data and the array's data. | Pass array into a stored procedure | [
"",
"php",
"mysql",
"stored-procedures",
""
] |
Python's [`sum()`](http://docs.python.org/library/functions.html#sum) function returns the sum of numbers in an iterable.
```
sum([3,4,5]) == 3 + 4 + 5 == 12
```
I'm looking for the function that returns the product instead.
```
somelib.somefunc([3,4,5]) == 3 * 4 * 5 == 60
```
I'm pretty sure such a function exists, but I can't find it. | # **Update:**
In Python 3.8, the *prod* function was added to the *math* module. See: [math.prod()](https://docs.python.org/3.8/library/math.html#math.prod).
## Older info: Python 3.7 and prior
The function you're looking for would be called *prod()* or *product()* but Python doesn't have that function. So, you need to write your own (which is easy).
## Pronouncement on prod()
Yes, that's right. Guido [rejected the idea](http://bugs.python.org/issue1093) for a built-in prod() function because he thought it was rarely needed.
## Alternative with reduce()
As you suggested, it is not hard to make your own using [*reduce()*](https://docs.python.org/2.7/library/functions.html#reduce) and [*operator.mul()*](https://docs.python.org/3/library/operator.html#operator.mul):
```
from functools import reduce # Required in Python 3
import operator
def prod(iterable):
return reduce(operator.mul, iterable, 1)
>>> prod(range(1, 5))
24
```
Note, in Python 3, the [*reduce()*](https://docs.python.org/3/library/functools.html#functools.reduce) function was moved to the [functools module](https://docs.python.org/3/library/functools.html).
## Specific case: Factorials
As a side note, the primary motivating use case for *prod()* is to compute factorials. We already have support for that in the [math module](https://docs.python.org/2.7/library/math.html#math.factorial):
```
>>> import math
>>> math.factorial(10)
3628800
```
## Alternative with logarithms
If your data consists of floats, you can compute a product using *sum()* with exponents and logarithms:
```
>>> from math import log, exp
>>> data = [1.2, 1.5, 2.5, 0.9, 14.2, 3.8]
>>> exp(sum(map(log, data)))
218.53799999999993
>>> 1.2 * 1.5 * 2.5 * 0.9 * 14.2 * 3.8
218.53799999999998
```
Note, the use of *log()* requires that all the inputs are positive. | Historically, Guido vetoed the idea: <http://bugs.python.org/issue1093>
As noted in that issue, you can make your own:
```
from functools import reduce # Valid in Python 2.6+, required in Python 3
import operator
reduce(operator.mul, (3, 4, 5), 1)
``` | What's the function like sum() but for multiplication? product()? | [
"",
"python",
"multiplication",
""
] |
I have a python script which is querying a MySQL server on a shared linux host. For some reason, queries to MySQL often return a "server has gone away" error:
```
_mysql_exceptions.OperationalError: (2006, 'MySQL server has gone away')
```
If you try the query again immediately afterwards, it usually succeeds. So, I'd like to know if there's a sensible way in python to try to execute a query, and if it fails, to try again, up to a fixed number of tries. Probably I'd want it to try 5 times before giving up altogether.
Here's the kind of code I have:
```
conn = MySQLdb.connect(host, user, password, database)
cursor = conn.cursor()
try:
cursor.execute(query)
rows = cursor.fetchall()
for row in rows:
# do something with the data
except MySQLdb.Error, e:
print "MySQL Error %d: %s" % (e.args[0], e.args[1])
```
Clearly I could do it by having another attempt in the except clause, but that's incredibly ugly, and I have a feeling there must be a decent way to achieve this. | How about:
```
conn = MySQLdb.connect(host, user, password, database)
cursor = conn.cursor()
attempts = 0
while attempts < 3:
try:
cursor.execute(query)
rows = cursor.fetchall()
for row in rows:
# do something with the data
break
except MySQLdb.Error, e:
attempts += 1
print "MySQL Error %d: %s" % (e.args[0], e.args[1])
``` | Building on Dana's answer, you might want to do this as a decorator:
```
def retry(howmany):
def tryIt(func):
def f():
attempts = 0
while attempts < howmany:
try:
return func()
except:
attempts += 1
return f
return tryIt
```
Then...
```
@retry(5)
def the_db_func():
# [...]
```
### Enhanced version that uses the `decorator` module
```
import decorator, time
def retry(howmany, *exception_types, **kwargs):
timeout = kwargs.get('timeout', 0.0) # seconds
@decorator.decorator
def tryIt(func, *fargs, **fkwargs):
for _ in xrange(howmany):
try: return func(*fargs, **fkwargs)
except exception_types or Exception:
if timeout is not None: time.sleep(timeout)
return tryIt
```
Then...
```
@retry(5, MySQLdb.Error, timeout=0.5)
def the_db_func():
# [...]
```
To install [the `decorator` module](http://pypi.python.org/pypi/decorator):
```
$ easy_install decorator
``` | is there a pythonic way to try something up to a maximum number of times? | [
"",
"python",
"exception",
""
] |
When writing a class to act as a wrapper around a heap-allocated object, I encountered a problem with implicit type conversion that can be reduced to this simple example.
In the code below the wrapper class manages a heap-allocated object and implicitly converts to a reference to that object. This allows the wrapper object to be passed as the argument to the function write(...) since implicit conversion takes place.
The compiler fails, however, when trying to resolve the call to operator<<(...), unless an explicit cast is made (checked with MSVC8.0, Intel 9.1 and gcc 4.2.1 compilers).
So, (1) why does the implicit conversion fail in this case? (2) could it be related to argument-dependent lookup? and (3) is there anything that can be done to make this work without the explicit cast?
```
#include <fstream>
template <typename T>
class wrapper
{
T* t;
public:
explicit wrapper(T * const p) : t(p) { }
~wrapper() { delete t; }
operator T & () const { return *t; }
};
void write(std::ostream& os)
{
os << "(1) Hello, world!\n";
}
int main()
{
wrapper<std::ostream> file(new std::ofstream("test.txt"));
write(file);
static_cast<std::ostream&>( file ) << "(2) Hello, world!\n";
// file << "(3) This line doesn't compile!\n";
}
``` | It fails because you're trying to resolve an operator of your `wrapper<T>` class that doesn't exist. If you want it to work without the cast, you could put together something like this:
```
template<typename X> wrapper<T> &operator <<(X ¶m) const {
return t << param;
}
```
Unfortunately I don't know of a way to resolve the return type at compile time. Fortunately in most cases it's the same type as the object, including in this case with `ostream`.
**EDIT:** Modified code by suggestion from dash-tom-bang. Changed return type to `wrapper<T> &`. | After some testing, an even simpler example identifies the source of the problem. The compiler cannot deduce the template argument `T` in `f2(const bar<T>&)` below from implicit conversion of `wrapper<bar<int> >` to `bar<int>&`.
```
template <typename T>
class wrapper
{
T* t;
public:
explicit wrapper(T * const p) : t(p) { }
~wrapper() { delete t; }
operator T & () const { return *t; }
};
class foo { };
template <typename T> class bar { };
void f1(const foo& s) { }
template <typename T> void f2(const bar<T>& s) { }
void f3(const bar<int>& s) { }
int main()
{
wrapper<foo> s1(new foo());
f1(s1);
wrapper<bar<int> > s2(new bar<int>());
//f2(s2); // FAILS
f2<int>(s2); // OK
f3(s2);
}
```
In the original example, `std::ostream` is actually a `typedef` for the templated class `std::basic_ostream<..>`, and the same situation applies when calling the templated function `operator<<`. | Unable to find operator via implicit conversion in C++ | [
"",
"c++",
"type-conversion",
"operator-keyword",
"implicit-conversion",
""
] |
I need to hard code an array of points in my C# program. The C-style initializer did not work.
```
PointF[] points = new PointF{
/* what goes here? */
};
```
How is it done? | Like this:
```
PointF[] points = new PointF[]{
new PointF(0,0), new PointF(1,1)
};
```
In c# 3.0 you can write it even shorter:
```
PointF[] points = {
new PointF(0,0), new PointF(1,1)
};
```
**update** Guffa pointed out that I was to short with the `var points`, it's indeed not possible to "implicitly typed variable with an array initializer". | You need to instantiate each PointF with new.
Something like
Pointf[] points = { new PointF(0,0), new PointF(1,1), etc...
Syntax may not be 100% here... I'm reaching back to when I last had to do it years ago. | C#: PointF() Array Initializer | [
"",
"c#",
"arrays",
"array-initialize",
""
] |
I have two tables in an XML Dataset. T1, T2. Each of the tables has a ID column.
T1 has a list of Customers
T2 has a list of Orders
I want to build a LINQ query that returns only the ID of the customers that do not have orders. In other words customer ID's that do not exist in the T2 table.
Oh yea, I'm using C#
Thanks! | I think this will work (please adapt to your DataSets):
```
var query = from c in T1
where !(from o in T2 select o.CustomerID)
.Contains(c.CustomerID)
select c;
``` | This requires an outer join and a check on null.
```
var result = from c in Customers
join d in Details on d.CustomerID equals c.ID into g
where !g.Any()
select c;
``` | Need help with an Opposite to Inner join Query using LINQ | [
"",
"c#",
"linq-to-xml",
"outer-join",
""
] |
Presuming that your C++ compiler supports them, is there any particular reason *not* to use `__FILE__`, `__LINE__` and `__FUNCTION__` for logging and debugging purposes?
I'm primarily concerned with giving the user misleading data—for example, reporting the incorrect line number or function as a result of optimization—or taking a performance hit as a result.
Basically, can I trust `__FILE__`, `__LINE__` and `__FUNCTION__` to *always* do the right thing? | `__FUNCTION__` is non standard, `__func__` exists in C99 / C++11. The others (`__LINE__` and `__FILE__`) are just fine.
It will always report the right file and line (and function if you choose to use `__FUNCTION__`/`__func__`). Optimization is a non-factor since it is a compile time macro expansion; it will **never** affect performance in any way. | In rare cases, it can be useful to change the line that is given by `__LINE__` to something else. I've seen GNU configure does that for some tests to report appropriate line numbers after it inserted some voodoo between lines that do not appear in original source files. For example:
```
#line 100
```
Will make the following lines start with `__LINE__` 100. You can optionally add a new file-name
```
#line 100 "file.c"
```
It's only rarely useful. But if it is needed, there are no alternatives I know of. Actually, instead of the line, a macro can be used too which must result in any of the above two forms. Using the boost preprocessor library, you can increment the current line by 50:
```
#line BOOST_PP_ADD(__LINE__, 50)
```
I thought it's useful to mention it since you asked about the usage of `__LINE__` and `__FILE__`. One never gets enough surprises out of C++ :)
**Edit:** @Jonathan Leffler provides some more good use-cases in the comments:
> Messing with #line is very useful for pre-processors that want to keep errors reported in the user's C code in line with the user's source file. Yacc, Lex, and (more at home to me) ESQL/C preprocessors do that. | __FILE__, __LINE__, and __FUNCTION__ usage in C++ | [
"",
"c++",
"debugging",
"logging",
"c-preprocessor",
""
] |
I just read the top answer at this post:
[Problem inserting string or NULL into SQL Server database](https://stackoverflow.com/questions/374522/problem-inserting-string-or-null-into-sql-server-database)
Correct me if I'm wrong, but can the ??-operator not only be used on two variables of the same type, if not I would greatly appreciate it, if anyone could solve my minor problem.
I tried to insert some code in my project similar to the one below.
```
Dictionary<string, string> strings = new Dictionary<string, string>()
{
{"@param0", strParam0},
{"@param1", strParam1},
{"@param2", strParam2}
};
foreach (string param in strings.Keys)
{
cmd.Parameters.AddWithValue(param, strings[param] ?? DBNull.Value);
}
```
But Visual Studio complains with the following message:
"Operator '??' cannot be applied to operands of type 'string' and 'System.DBNull'" | DBNull and Null are not the same type, nor are nullable types or reference types and DBNull. You can only use ?? with values of the same type.
One can think of the ?? operator as syntactic sugar for:
```
(left != null) ? left : right
```
And the ternary operation requires both left and right to be of the same type, so therefore left and right of the ?? operator must also be of the same type.
So, unfortunately, no.. you can't do it this way, at least not without some ugly casting. | Try:
```
cmd.Parameters.AddWithValue(param, (object)strings[param] ?? DBNull.Value);
``` | Problem inserting string or NULL into SQL Server database | [
"",
"c#",
"operators",
"dbnull",
""
] |
I have an application that has a backoffice.
This backoffice was isolated with the use of roles like this:
```
<location path="backoffice">
<system.web>
<authorization>
<allow roles="admin"/>
<deny users="*"/>
</authorization>
</system.web>
</location>
```
But now we have another type of role that needs access. The companyadmin role.
Can I just say?:
```
<location path="backoffice">
<system.web>
<authorization>
<allow roles="admin,companyadmin"/>
<deny users="*"/>
</authorization>
</system.web>
</location>
``` | Yes, exactly so (assuming you properly authenticated your users, and set their roles accordingly).
Check the MSDN article: <https://learn.microsoft.com/en-us/previous-versions/dotnet/netframework-1.1/8d82143t(v=vs.71)> | yes, you can add n roles like that.
If you prefer, you can also:
```
<allow roles="admin"/>
<allow roles="admin1"/>
<deny users="*"/>
``` | Authorization Asp.net web.config | [
"",
"c#",
"asp.net",
"security",
"web-config",
"roles",
""
] |
jQuery, when i use it to create a modal window which contains form elemets,
it takes out those elements when i submit the form.
example of the form:
```
<form enctype="multipart/form-data" action="/system/article/add/" class="from" method="post">
<label for="article_title" class="required">Title:</label>
<input class="formfield" id="article_title" name="article_title" value="" type="text">
<label for="url" class="required">Url:</label>
<input class="formfield" id="url" name="url" value="" type="text">
<div id="add_photo" style="width: auto;" class="ui-dialog-content ui-widget-content" title="Add Photo">
<label for="photo_title" class="optional">Photo title:</label>
<input class="formfield" id="photo_title" name="photo_title" value="" type="text">
<label for="photot" class="optional">Photo thumb:</label>
<input type="file" name="photot" id="photot" class="formfield">
<label for="photo_checkbox" class="optional">Include lighbox?</label>
<input name="photo_checkbox" value="0" type="hidden">
<input class="checkbox" id="photo_checkbox" name="photo_checkbox" value="1" type="checkbox">
<label for="photo_big" class="optional">Photo:</label>
<input type="file" name="photo_big" id="photo_big" class="formfield">
</div>
</form>
```
exaple of JS:
```
<script>
$(document).ready(function(){
$("#add_photo").dialog({
autoOpen: false,
buttons: {
"Ok": function() {
$(this).dialog("close");
}
}
});
});
```
So what i nocited during the inspetion via firebug, is that jquery actually removes my form elements within #add\_photo and puts them outside the form in DOM, so even tough in html the modal dialog is within my form, in DOM it isn't ....
An this is the reason why i'm having the issue!
Have anyone encountered simmilar problem?
Any solution?! Thank you very much! | I just had the same problem. I solved it by adding another
```
<div id="beforesubmit" style="display:none"></div>
```
at the end (but inside) of the form and then you have to add this to jQuery:
```
$("form").submit(function() {
$("#add_photo").prependTo("#beforesubmit");
});
```
This will make sure that before the form is submit your dialog div will be put back in between the form tags. Thanks to *arnorhs* I came to this solution.
Cheers! | The form needs to be inside the div. That's how it is in all the Dialog examples. Not sure how you're going to do that with the title and url inputs not being on the dialog. Couldn't you put them on it too?
This wouldn't have the problem:
```
<div id="add_photo" style="width: auto;" class="ui-dialog-content ui-widget-content" title="Add Photo">
<form enctype="multipart/form-data" action="/system/article/add/" class="from" method="post">
<label for="article_title" class="required">Title:</label>
<input class="formfield" id="article_title" name="article_title" value="" type="text">
<label for="url" class="required">Url:</label>
<input class="formfield" id="url" name="url" value="" type="text">
<label for="photo_title" class="optional">Photo title:</label>
<input class="formfield" id="photo_title" name="photo_title" value="" type="text">
<label for="photot" class="optional">Photo thumb:</label>
<input type="file" name="photot" id="photot" class="formfield">
<label for="photo_checkbox" class="optional">Include lighbox?</label>
<input name="photo_checkbox" value="0" type="hidden">
<input class="checkbox" id="photo_checkbox" name="photo_checkbox" value="1" type="checkbox">
<label for="photo_big" class="optional">Photo:</label>
<input type="file" name="photo_big" id="photo_big" class="formfield">
</form>
</div>
``` | jQuery modal window removes elements from my form | [
"",
"javascript",
"jquery",
"dom",
""
] |
I am new to SQL and relational DBMS.
I want to retrieve records from a relational database if they satisfy 3 given properties.
For example, if there is a table containing info about solids:
```
table_solid : |s_id|s_name|description|
table_width : |w_id|w_name|
table_height: |h_id|h_name|
table_length: |l_id|l_name|
```
where \*\_id are all primary keys.
I have 3 more tables for relating these tables with Foreign Keys.
```
table_s_h: |s_id|h_id|
table_s_w: |s_id|w_id|
table_s_l: |s_id|l_id|
```
Would you please explain how do I join these.
Thanks in advance.
```
--------- table_length
table_SOLID ----
----------- table_width
------------table_height
```
table\_length contains valid lengths that solid can take (and similarly with other tables). | From a single table:
```
Select *
FROM TABLE_NAME
WHERE table_width = SOME_VALUE3
AND table_height= SOME_VALUE2
AND table_length = SOME_VALUE3
```
Is that what you are looking for? Or are you trying to query multiple tables? If so try this:
```
Select *
FROM TABLE_SOLID solid
Inner join table_width width on solid.w_id = width.w_id
inner join table_height height on solid.h_id = height.h_id
inner join table_length length on solid.l_id = length.l_id
```
This link may be of use to you <http://dev.mysql.com/doc/refman/5.0/en/join.html> | Your DB schema is not clear to me.
Are these four different tables? If yes, how are they linked up, ie how do you retrieve width, height, length for a given solid?
Or are those four columns in 1 table, identified by s\_id?
Please clarify. | How to: MySQL How to retrieve record based on three properties? | [
"",
"sql",
"rdbms",
""
] |
Assuming I have a left outer join as such:
```
from f in Foo
join b in Bar on f.Foo_Id equals b.Foo_Id into g
from result in g.DefaultIfEmpty()
select new { Foo = f, Bar = result }
```
How would I express the same task using extension methods? E.g.
```
Foo.GroupJoin(Bar, f => f.Foo_Id, b => b.Foo_Id, (f,b) => ???)
.Select(???)
``` | For a (left outer) join of a table `Bar` with a table `Foo` on `Foo.Foo_Id = Bar.Foo_Id` in lambda notation:
```
var qry = Foo.GroupJoin(
Bar,
foo => foo.Foo_Id,
bar => bar.Foo_Id,
(x,y) => new { Foo = x, Bars = y })
.SelectMany(
x => x.Bars.DefaultIfEmpty(),
(x,y) => new { Foo=x.Foo, Bar=y});
``` | Since this seems to be the de facto SO question for left outer joins using the method (extension) syntax, I thought I would add an alternative to the currently selected answer that (in my experience at least) has been more commonly what I'm after
```
// Option 1: Expecting either 0 or 1 matches from the "Right"
// table (Bars in this case):
var qry = Foos.GroupJoin(
Bars,
foo => foo.Foo_Id,
bar => bar.Foo_Id,
(f,bs) => new { Foo = f, Bar = bs.SingleOrDefault() });
// Option 2: Expecting either 0 or more matches from the "Right" table
// (courtesy of currently selected answer):
var qry = Foos.GroupJoin(
Bars,
foo => foo.Foo_Id,
bar => bar.Foo_Id,
(f,bs) => new { Foo = f, Bars = bs })
.SelectMany(
fooBars => fooBars.Bars.DefaultIfEmpty(),
(x,y) => new { Foo = x.Foo, Bar = y });
```
To display the difference using a simple data set (assuming we're joining on the values themselves):
```
List<int> tableA = new List<int> { 1, 2, 3 };
List<int?> tableB = new List<int?> { 3, 4, 5 };
// Result using both Option 1 and 2. Option 1 would be a better choice
// if we didn't expect multiple matches in tableB.
{ A = 1, B = null }
{ A = 2, B = null }
{ A = 3, B = 3 }
List<int> tableA = new List<int> { 1, 2, 3 };
List<int?> tableB = new List<int?> { 3, 3, 4 };
// Result using Option 1 would be that an exception gets thrown on
// SingleOrDefault(), but if we use FirstOrDefault() instead to illustrate:
{ A = 1, B = null }
{ A = 2, B = null }
{ A = 3, B = 3 } // Misleading, we had multiple matches.
// Which 3 should get selected (not arbitrarily the first)?.
// Result using Option 2:
{ A = 1, B = null }
{ A = 2, B = null }
{ A = 3, B = 3 }
{ A = 3, B = 3 }
```
Option 2 is true to the typical left outer join definition, but as I mentioned earlier is often unnecessarily complex depending on the data set. | How do you perform a left outer join using linq extension methods | [
"",
"c#",
"linq",
"left-join",
""
] |
Does C++ provide a guarantee for the lifetime of a temporary variable that is created within a function call but not used as a parameter? Here's an example class:
```
class StringBuffer
{
public:
StringBuffer(std::string & str) : m_str(str)
{
m_buffer.push_back(0);
}
~StringBuffer()
{
m_str = &m_buffer[0];
}
char * Size(int maxlength)
{
m_buffer.resize(maxlength + 1, 0);
return &m_buffer[0];
}
private:
std::string & m_str;
std::vector<char> m_buffer;
};
```
And here's how you would use it:
```
// this is from a crusty old API that can't be changed
void GetString(char * str, int maxlength);
std::string mystring;
GetString(StringBuffer(mystring).Size(MAXLEN), MAXLEN);
```
When will the destructor for the temporary StringBuffer object get called? Is it:
* Before the call to GetString?
* After GetString returns?
* Compiler dependent?
I know that C++ guarantees that a local temporary variable will be valid as long as there's a reference to it - does this apply to parent objects when there's a reference to a member variable?
Thanks. | The destructor for that sort of temporaries is called at the end of the full-expression. That's the most outer expression which is not part of any other expression. That is in your case after the function returns and the value is evaluated. So, it will work all nice.
It's in fact what makes expression templates work: They can keep hold references to that sort of temporaries in an expression like
```
e = a + b * c / d
```
Because every temporary will last until the expression
```
x = y
```
Is evaluated completely. It's quite concisely described in `12.2 Temporary objects` in the Standard. | litb's answer is accurate. The lifetime of the temporary object (also known as an rvalue) is tied to the expression and the destructor for the temporary object is called at the end of the full expression and when the destructor on StringBuffer is called, the destructor on m\_buffer will also be called, but not the destructor on m\_str since it is a reference.
Note that C++0x changes things just a little bit because it adds rvalue references and move semantics. Essentially by using an rvalue reference parameter (notated with &&) I can 'move' the rvalue into the function (instead of copying it) and the lifetime of the rvalue can be bound to the object it moves into, not the expression. There is a really good [blog post from the MSVC team on that walks through this in great detail](http://blogs.msdn.com/vcblog/archive/2009/02/03/rvalue-references-c-0x-features-in-vc10-part-2.aspx) and I encourage folks to read it.
The pedagogical example for moving rvalue's is temporary strings and I'll show assignment in a constructor. If I have a class MyType that contains a string member variable, it can be initialized with an rvalue in the constructor like so:
```
class MyType{
const std::string m_name;
public:
MyType(const std::string&& name):m_name(name){};
}
```
This is nice because when I declare an instance of this class with a temporary object:
```
void foo(){
MyType instance("hello");
}
```
what happens is that we avoid copying and destroying the temporary object and "hello" is placed directly inside the owning class instance's member variable. If the object is heavier weight than a 'string' then the extra copy and destructor call can be significant. | Guaranteed lifetime of temporary in C++? | [
"",
"c++",
""
] |
This is a follow up question to "[Is there a basic Java Set implementation that does not permit nulls?](https://stackoverflow.com/questions/591115/is-there-a-basic-java-set-implementation-that-does-not-permit-nulls)". (thank you to all of those who helped with the answer)
It seems that the way to do this, since Sun didn't provide something simple like this OOTB, is with a wrapper / proxy. This seems nearly straight forward. What I am wondering is what are the pros/cons of the following two approaches of adding a collection, or is there another better approach?
Approach #1
```
public boolean addAll( Collection<? extends E> c) {
if ( null == c ) {
throw new NullPointerException( "c cannot be null" );
}
/*
* This seems like a terrible abuse of exceptions when
* all I want to do is check the set for a null.
*
* However, simply running through each element of the
* Collection may provide much worse performance for large
* collections. And according to the Collection API, the
* contains method may throw NullPointerExceptions if the
* collection implementation does not allow null elements.
*/
boolean collectionContainsNull = false;
try {
collectionContainsNull = c.contains(null);
} catch (NullPointerException safeToIgnore) {
/* Safe to ignore since we do not want nulls */
}
if (collectionContainsNull) {
throw new NullPointerException("c cannot contain null elements");
}
this.wrapperSet.addAll(c);
}
```
Approach #2
```
public boolean addAll( Collection<? extends E> c) {
if ( null == c ) {
throw new NullPointerException( "c cannot be null" );
}
E[] a = ( E[] )c.toArray();
/*
* We have to iterate through the entire collection to check for
* a null. This won't take advantage of any optimizations that
* c.contains may be using.
*
* We don't call add(e) here because if we hit a null midway through
* we would violate the condition that the set remains unchanged
* on error.
*/
for ( E e : a ) {
if (null == e) {
throw new NullPointerException("c cannot contain nulls");
}
}
this.wrapperSet.addAll(a);
}
```
Thanks in advance! | The second approach is better. Never hide exceptions - you are relying on the assumption that c.contains(null) only throws a NullPointerException in the case that there is a null in the collection. However if the NullPointeException is thrown because of a problem with an equals method you will have a bug in your code - and you will have hidden it.
Edit:
From the JavaDoc for contains, NullPointerException is thrown - if the specified element is null and this collection does not permit null elements (optional).
Given that it is an optional method you may wind up with an UnsupportedOperationException being thrown instead of the NullPointerExcepion (in addition to hiding the an error in equals). | What's the point of converting to an array first, and then iterating through the array, rather than just iterating the collection? I'd do the second one without the extraneous conversion.
Or maybe do the add to a temporary set:
```
public boolean addAll( Collection<? extends E> c) {
if ( null == c ) {
throw new NullPointerException( "c cannot be null" );
}
Set<E> tempSet = new HashSet<E>();
/*
* We have to iterate through the entire collection to check for
* a null. This won't take advantage of any optimizations that
* c.contains may be using.
*
*/
for ( E e : c) {
if (null == e) {
throw new NullPointerException("c cannot contain nulls");
}
tempSet.add(e);
}
this.wrapperSet = tempSet;
}
``` | What are the pros and cons for different methods of checking a Collection for a null before adding to a Set? | [
"",
"java",
"api",
"exception",
"collections",
""
] |
Okay, I'm trying to load a file in Java using this code:
```
String file = "map.mp";
URL url = this.getClass().getResource(file);
System.out.println("url = " + url);
FileInputStream x = new FileInputStream("" + url);
```
and despite the file being in the same folder as the class it says it can't find it (yes, it **is** in a try catch block in the full code).
However, it finds another file using the same code with a different name:
```
URL url = this.getClass().getResource("default.png");
System.out.println("url2 = " + this.getClass().getResource("default.png"));
BufferedImage img = ImageIO.read(url);
```
Why can't my code find my map.mp file? | You're trying to use a url as if it's a filename. It won't be. It'll be something starting with `file://`. In other deployment scenarios there may not be an actual file to open at all - it may be within a jar file, for example. You can use `URL.getFile()` if you really, really have to - but it's better not to.
Use `getResourceAsStream` instead of `getResource()` - that gives you an `InputStream` directly. Alternatively, keep using `getResource()` if you want the URL for something else, but then use `URL.openStream()` to get at the data. | `FileInputStream` takes a file name as parameter, not a URL string.
The usual way to get at the contents that a `URL` points to is with `openStream`. You can open a stream to a resource without touching a `URL` yourself with `Class`/`ClassLoader.getResourceAsStream` (it opens the URL within the implementation).
Alternatively, you can open **file** URLs with:
```
InputStream in = FileInputStream(new File(url.toURI()));
```
For a resource this would require that you have raw class files outside of a jar on your filesystem. JNLP (Java WebStart) has an API for opening files is a safe manner.
In general: When converting to a `String` use `toString` or `String.valueOf` to be clear about what you are doing. Also note that `String` is somewhat weakly typed, in that the type gives no indication as to the format of the data it contains, so favour the likes of `URI` or `File`. | File not found. Why not? | [
"",
"java",
"file",
"file-io",
"io",
""
] |
Say for a Point2 class, and the following Equals:
```
public override bool Equals ( object obj )
public bool Equals ( Point2 obj )
```
This is the one that is shown in the Effective C# 3:
```
public override bool Equals ( object obj )
{
// STEP 1: Check for null
if ( obj == null )
{
return false;
}
// STEP 3: equivalent data types
if ( this.GetType ( ) != obj.GetType ( ) )
{
return false;
}
return Equals ( ( Point2 ) obj );
}
public bool Equals ( Point2 obj )
{
// STEP 1: Check for null if nullable (e.g., a reference type)
if ( obj == null )
{
return false;
}
// STEP 2: Check for ReferenceEquals if this is a reference type
if ( ReferenceEquals ( this, obj ) )
{
return true;
}
// STEP 4: Possibly check for equivalent hash codes
if ( this.GetHashCode ( ) != obj.GetHashCode ( ) )
{
return false;
}
// STEP 5: Check base.Equals if base overrides Equals()
System.Diagnostics.Debug.Assert (
base.GetType ( ) != typeof ( object ) );
if ( !base.Equals ( obj ) )
{
return false;
}
// STEP 6: Compare identifying fields for equality.
return ( ( this.X.Equals ( obj.X ) ) && ( this.Y.Equals ( obj.Y ) ) );
}
``` | There is a whole set of [guidelines on MSDN](https://learn.microsoft.com/en-us/visualstudio/ide/reference/generate-equals-gethashcode-methods) as well. You should read them well, it is both tricky and important.
A few points I found most helpful:
* Value Types don't have Identity, so in a **`struct Point`** you will usually do a member by member compare.
* Reference Types usually do have identity, and therefore the Equals test usually stops at ReferenceEquals (the default, no need to override). But there are exceptions, like string and your **`class Point2`**, where an object has no useful identity and then you override the Equality members to provide your own semantics. In that situation, follow the guidelines to get through the null and other-type cases first.
* And there are good reasons to keep `GethashCode()` and `operator==` in sync as well. | In the one that takes an obj, if the type of obj is Point2, call the type specific Equals. Inside the type specific Equals, make sure that all the members have the same value.
```
public override bool Equals ( object obj )
{
return Equals(obj as Point2);
}
public bool Equals ( Point2 obj )
{
return obj != null && obj.X == this.X && obj.Y == this.Y ...
// Or whatever you think qualifies as the objects being equal.
}
```
You probably ought to override GetHashCode as well to make sure that objects that are "equal" have the same hash code. | How to best implement Equals for custom types? | [
"",
"c#",
".net",
"class",
""
] |
I'm using reporting services to make a report graph. However my data looks like this:
```
Table1
C01 C02 C03 C04
1 2 3 4
I need to do a sql query to return data that looks like this:
Any_Col_name
1
2
3
4
```
I'm using MS Reporting Services with a Oracle DB. I cannot restructure the table. | ```
select c01 from table
union all
select c02 from table
union all
select c03 from table
union all
select c04 from table
``` | If you are using Oracle 11G and above, you can also use unpivot for this, it should be more efficient than the union all (haven't tested this cause I do not have oracle around)
```
SELECT Any_Col_name FROM table
UNPIVOT INCLUDE NULLS (Any_Col_name FOR Col IN (C01,C02,C03,C04))
``` | SQL Query make columns results into rows | [
"",
"sql",
"reporting",
"service",
""
] |
Does Firebug have something built-in to disable all javascript for a site/page? | Not that I know of. But you can use the [web developer toolbar](https://addons.mozilla.org/en-US/firefox/addon/60) or [noscript](https://addons.mozilla.org/en-US/firefox/addon/722) addons to do that. | In firefox 4 you can just disable javascript in the content tab of the options dialog.
Just uncheck "Enable Javascript". | Does Firebug have something built-in to disable all javascript for a site/page? | [
"",
"javascript",
"firebug",
""
] |
Is there any way to determine (programatically, of course) if a given pointer is "valid"? Checking for NULL is easy, but what about things like 0x00001234? When trying to dereference this kind of pointer an exception/crash occurs.
A cross-platform method is preferred, but platform-specific (for Windows and Linux) is also ok.
**Update for clarification:**
The problem is not with stale/freed/uninitialized pointers; instead, I'm implementing an API that takes pointers from the caller (like a pointer to a string, a file handle, etc.). The caller can send (in purpose or by mistake) an invalid value as the pointer. How do I prevent a crash? | > **Update for clarification:** The problem is not with stale, freed or uninitialized pointers; instead, I'm implementing an API that takes pointers from the caller (like a pointer to a string, a file handle, etc.). The caller can send (in purpose or by mistake) an invalid value as the pointer. How do I prevent a crash?
You can't make that check. There is simply no way you can check whether a pointer is "valid". You have to trust that when people use a function that takes a pointer, those people know what they are doing. If they pass you 0x4211 as a pointer value, then you have to trust it points to address 0x4211. And if they "accidentally" hit an object, then even if you would use some scary operation system function (IsValidPtr or whatever), you would still slip into a bug and not fail fast.
Start using null pointers for signaling this kind of thing and tell the user of your library that they should not use pointers if they tend to accidentally pass invalid pointers, seriously :) | Here are three easy ways for a C program under Linux to get introspective about the status of the memory in which it is running, and why the question has appropriate sophisticated answers in some contexts.
1. After calling getpagesize() and rounding the pointer to a page
boundary, you can call mincore() to find out if a page is valid and
if it happens to be part of the process working set. Note that this requires
some kernel resources, so you should benchmark it and determine if
calling this function is really appropriate in your api. If your api
is going to be handling interrupts, or reading from serial ports
into memory, it is appropriate to call this to avoid unpredictable
behaviors.
2. After calling stat() to determine if there is a /proc/self directory available, you can fopen and read through /proc/self/maps
to find information about the region in which a pointer resides.
Study the man page for proc, the process information pseudo-file
system. Obviously this is relatively expensive, but you might be
able to get away with caching the result of the parse into an array
you can efficiently lookup using a binary search. Also consider the
/proc/self/smaps. If your api is for high-performance computing then
the program will want to know about the /proc/self/numa which is
documented under the man page for numa, the non-uniform memory
architecture.
3. The get\_mempolicy(MPOL\_F\_ADDR) call is appropriate for high performance computing api work where there are multiple threads of
execution and you are managing your work to have affinity for non-uniform memory
as it relates to the cpu cores and socket resources. Such an api
will of course also tell you if a pointer is valid.
Under Microsoft Windows there is the function QueryWorkingSetEx that is documented under the Process Status API (also in the NUMA API).
As a corollary to sophisticated NUMA API programming this function will also let you do simple "testing pointers for validity (C/C++)" work, as such it is unlikely to be deprecated for at least 15 years. | Testing pointers for validity (C/C++) | [
"",
"c++",
"c",
"validation",
"pointers",
"null",
""
] |
As discussed in similar questions [here](https://stackoverflow.com/questions/506282/protect-net-code-from-reverse-engineering/506301#506301) and [here](https://stackoverflow.com/questions/71195/should-you-obfuscate-a-commercial-net-application) I want to protect my code from reverse engineering.
My situation is as [Simucal](https://stackoverflow.com/users/2635/simucal) describes in his (excellent) answer [here](https://stackoverflow.com/questions/506282/protect-net-code-from-reverse-engineering/506301#506301):
> Basically, what it comes down to is
> the only chance you have of being
> targeted for source theft is if you
> have some very specific, hard to
> engineer, algorithm related to your
> domain that gives you a leg up on your
> competition. This is just about the
> only time it would be cost-effective
> to attempt to reverse engineer a small
> portion of your application.
I have exactly this situation. A hard to engineer algorithm which is elegant and valuable for our specific domain.
After spending months fine tuning and developing this the end result is very compact (approx. 100 lines of code) and elegant. I want to protect this specific part of the code from reverse engineering or at least make it reasonable difficult.
The scenario is a rich-client application written in C# and I have to deploy this part of the code - I cannot execute it from a webservice.
I think extracting the code and rewriting it in a unmanaged native binary is not an option due to performance reasons (and cross boundary issues).
Initially I wanted to do simple obfuscation but given the small size of the code I don't think this will offer much protection.
Ideally I would like to protect my whole application but there are two main issues that seem to make ordinary obfuscaters and 3rd party packers difficult to use:
1. The application offers a plugin interface and therefore some assemblies (and interfaces/classes) should not be obfuscated and packed
2. We still want to be able to get to a real stack trace when receiving error reports - potentially this could be done my mapping obfuscation to the real code.
Setting these issues aside (although I would appreciate any input on this as well), what is a good way to protect a tiny part of my code from reverse engineering? I am not concerned about anyone altering or hacking the code but want to make it difficult to understand and reverse engineer it. | You should obfuscate the complete code since it gets harder to reach that small valuable part. The smaller the code gets, the easier it becomes to understand it. Most obfuscators should not mess with public interfaces since there are many obfuscated libraries out there.
However I think you should rather convince users that there are no special tricks there instead of trying to hide it. To quote Kaiser Soze, "the greatest trick The Devil has ever pulled is to convince the world that he doesn't exist".
And of course you can always file a patent for your invention and protect yourself legally. | It cannot be done. If your code can be run, then it can be read and reverse-engineered. All you can do is make it a little harder and, believe me, it will only be a *little* harder. You may not like the fact but most crackers are far better at cracking than anyone else is at making things hard to crack. The amount of effort to protect your code is usually not worth it, especially if it disadvantages your paying customers. Witness the stunning non-successes of DRM.
My advice is to not worry about it. If your algorithm is truly novel, seek a patent (although that got a little harder with the Bilski decision unless you tie it to a specific hardware implementation). Relying on trade secrets is also useless unless you only distribute your software to those that sign contracts that ensure they will not allow unfettered access. And then, you have to have a way to police this. The minute you put the binaries up on the internet or distributed them without a contract, I believe you'll be deemed to have lost trade secret status.
Relying on licensing is also fraught with danger - you may think that you can insert clauses in your license that prohibit reverse-engineering but many jurisdictions around the world specifically disallow those provisions. And the Russian mobsters who whoever are responsible for most of the cracking are unlikely to honor said provisions anyway.
Why don't you just concentrate on making your product the best it can be? The goal is to stay ahead of the crowd rather than lock them out altogether. Being the first to deliver and always having the best product in a competitive group will ensure your prosperity far more than wasting a lot of effort on useless protection (IMNSHO).
This is just my opinion. I may be wrong. I've been wrong before, you only need ask my wife :-) | Protecting my code from reverse engineering | [
"",
"c#",
"obfuscation",
"reverse-engineering",
""
] |
As the title states, I have a session variable that is set during a login script with asp.net and vb.net code-behind. Can I call a javascript function when a link is clicked that will destroy that session variable?
If it is possible, can I use jQuery to make that process easier? | Yes, use `$.post("logout.aspx");` in your Javascript, and create the file logout.aspx that destroys the session. | Server-side code (VB.NET in your case) is the only thing that can access the session and its variables. Your best bet is to create a WebService/WebMethod and use jQuery to call it.
This article should help you get started: [Using jQuery to Consume ASP.NET JSON Web Services](http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/) | Is it possible to destroy a session variable set by ASP.NET (VB.NET) with Javascript? | [
"",
"asp.net",
"javascript",
"jquery",
"vb.net",
"session",
""
] |
Why won't this simple subtraction work?
```
int MyPageNumber = Convert.ToInt32(cboPageNumber.SelectedItem);
MyPageNumber += (MyPageNumber - 1); //does not work
int MyNewPageNumber = MyPageNumber - 1; /works
```
I was also hoping someone could tell me why this gives me a "red line" for not being able to do a cast:
```
short MyPageNumber = Convert.ToInt16(cboPageNumber.SelectedItem);
MyPageNumber += MyPageNumber - ((short) 1); //does not work says can't cast
```
What am I not understanding? Is the + turning it into a String in the examples?
Thank you. | Look at exactly what this does:
```
MyPageNumber += (MyPageNumber - 1);
```
It *adds* MyPageNumber-1 to the existing value. So if MyPageNumber is 5, you end up with 9 instead of the 4 which you presumably want.
Now for the second problem, you've basically got a situation equivalent to this:
```
short x = 5;
short y = 10;
short z = x - y;
```
It looks okay, but C# doesn't actually have a subtraction operator for shorts - it only has it on ints, so it's implicitly converting both `x` and `y` to `int`. The result is then an `int` too, which you can't assign back to `z`. You need:
```
short z = (short) (x - y);
```
(or the equivalent with your real variable names). | Define "doesn't work" - seems fine to me... in particular:
```
int MyPageNumber = Convert.ToInt32("3");
MyPageNumber += (MyPageNumber - 1); // 5 as expected
```
Re the second; all `short` arithmetic results in an int, due to CPU efficiencies etc; try:
```
MyPageNumber += (short)(MyPageNumber - ((short)1));
``` | Simple subtraction and cast question | [
"",
"c#",
"casting",
""
] |
This code:
```
abstract class C
{
protected abstract void F(D d);
}
class D : C
{
protected override void F(D d) { }
void G(C c)
{
c.F(this);
}
}
```
Generates this error:
> Cannot access protected member 'C.F(D)' via a qualifier of type 'C'; the qualifier must be of type 'D' (or derived from it)
What in the world were they thinking? (Would altering that rule break something?) And is there a way around that aside from making F public?
---
Edit: I now get the reason for why this is (Thanks [Greg](https://stackoverflow.com/questions/567705/why-cant-i-access-c-protected-members-except-like-this/567732#567732)) but I'm still a bit perplexed as to the rational; given:
```
class E : C
{
protected override void F(D d) { }
}
```
Why *shouldn't* D be able to be able to call E.F?
---
The error message is edited so I might have put a typo in there. | The "protected" keyword means that only a type and types that derive from that type can access the member. D has no relationship to C therefore cannot access the member.
You have a couple of options if you want to be able to access that member
* Make it public
* Make it internal. This will allow any types to access the member within the same assembly (or other assemblies should you add friend's)
* Derive D from C
**EDIT**
This scenario is called out in section 3.5.3 of the C# spec.
The reason this is not allowed is because it would allow for cross hierarchy calls. Imagine that in addition to D, there was another base class of C called E. If your code could compile it would allow D to access the member E.F. This type of scenario is not allowed in C# (and I *believe* the CLR but I don't 100% know).
**EDIT2** Why this is bad
Caveat, this is my opinion
The reason this is now allowed is it makes it very difficult to reason about the behavior of a class. The goal of access modifiers is to give the developer control over exactly who can access specific methods. Imagine the following class
```
sealed class MyClass : C {
override F(D d) { ... }
}
```
Consider what happens if F is a somewhat time critical function. With the current behavior I can reason about the correctness of my class. After all there are only two cases where MyClass.F will be called.
1. Where it's invoked in C
2. Where I explicitly invoke it in MyClass
I can examine these calls and come to a reasonable conclusion about how MyClass functions.
Now, if C# does allow cross hierarchy protected access I can make no such guarantee. Anyone in a completely different assembly can come by and derive from C. Then they can call MyClass.F at will. This makes it completely impossible to reason about the correctness of my class. | The reason this doesn't work is because C# doesn't allow cross-hierarchy calling of protected methods. Say there was a class `E` that also derived from `C`:
```
C
/ \
D E
```
Then the reference you're trying to call the method on could actually be an instance of type `E` and thus the method could resolve at runtime to `E.F`. This is not permitted in C# as `D` cannot call `E`'s protected methods, because `E` is in another branch of the hierarchy, i.e.
```
var d = new D();
var e = new E();
d.G(e); // oops, now this will call E.F which isn't allowed from D
```
This makes sense because the keyword `protected` means the member "[is accessible within its class and by derived class instances](http://msdn.microsoft.com/en-us/library/bcd5672a.aspx)" and E.F is not a member of D. | Why can't I access C# protected members except like this? | [
"",
"c#",
"overriding",
"protected",
"access-modifiers",
""
] |
I'm dealing with a `WriteableBitmap` in C#. I'm currently using an unsafe code block to directly access the pixels via `WriteableBitmap.BackBuffer`. I'd rather not depend on the `/unsafe` option, however, so I'm considering using `WriteableBitmap.WritePixels` instead.
Is there some way of conditionally compiling in the "unsafe" version such that it can be used when the /unsafe option for compilation was used, without requiring manual integration into my project file?
In short I'm looking for something along the lines of:
```
#if UNSAFE
//my unsafe version
#else
//the supposedly safe version goes here
#endif
```
Detection at runtime is nice too; but that means I always need to compile *with* `/unsafe`, and that means the library code would require project file updates, which is less handy.
Basically, I want to keep the fast version for when it matters, but have a reasonable version that just works no matter what. | I recommend you create one or more new configurations using the configuration manager, say "Unsafe Debug" and "Unsafe Release", that have the existing options plus check Unsafe and add a conditional symbol of UNSAFE. Instead of toggling the Unsafe options you would use the Unsafe configuration.
You could also have the configurations change the output name of the unsafe assembly so you would have two assemblies, say Bitmaps.dll and Bitmaps.Unsafe.dll, and a client of the assembly can decide which fits its needs best by specifying which assembly it references. | I'd suggest that you compile with `/unsafe /define:SAFE`. Perhaps there is another way I'm not aware of. | Is there a "preprocessor" symbol corresponding to the /unsafe flag? | [
"",
"c#",
"wpf",
"c-preprocessor",
"unsafe",
""
] |
Can anyone clearly articulate when you use a field and when to use a property in class design?
Consider:
```
public string Name;
```
Or:
```
private string _Name;
public string Name
{
get { return _Name; }
set { _Name = value; }
}
```
I realize that the second method is more proper and flexible, so that's what I try to use, generally.
But then why do I see people use the first method? Are they just lazy, or is there some specific situation where it's the correct choice? Is it just a matter of preference? | Well in C# 3.0 you can actually write:
```
public string Name {get; set;}
```
Which allows you to be proper and lazy.
Generally speaking, with properties, you get proper encapsulation. You have the choice to allow setting a value, or getting it, or both. Using a public member, you don't have that option.
It's probably one-part preference, and one-part how your team decides to handle quick and dirty class definitions, but I would say, use properties for get/sets.
To answer
> Can anyone clearly articulate when you use an attribute and when to use a property in class design?
You shouldn't ever use a public attribute. You should always use a property instead. It's safer and more flexible. That said, people will be lazy, and just use a public member. However, with C# 3.0 you can use a more terse syntax to define properties, which should satisfy your inner laziness.
Simply type `prop` and hit `<tab>` to expedite the laziness in adding a property. | Just some additional information to Alan's reply:
```
public string Name {get; set;}
```
is the same as
```
private string _Name;
public string Name{
get { return _Name; }
set { _Name = value; }
}
```
If you want to disallow the set function of Name, you can have
public string Name {get; **private** set;} | When should you use a field rather than a property? | [
"",
"c#",
"theory",
""
] |
I have Enterprise Application with EJB3 and JSF on Glassfish server. After running this application for more than 2 weeks I realized that I have problem with Class Loading. I don't think this is a problem with permgen. The classes loaded every time when I open a page but then they never erased from the memory. Here is the snapshot of or my server's memory:
[Snapshot](http://vasura.s3.amazonaws.com/classLoadingProblem.JPG)
So, i just need some pointers of how I can debug this problem. | There's a [nice explanation](http://blogs.oracle.com/fkieviet/entry/classloader_leaks_the_dreaded_java) of why this sort of things happen, and a more recent account of similar problem [here](http://drorbr.blogspot.com/2008/11/javalangoutofmemoryerror-permgen-space.html).
Using [jhat](http://java.sun.com/javase/6/docs/technotes/tools/share/jhat.html) might help to find out what classes are occupying the memory, and then look for a static reference that may hold them/or the classloader, preventing proper unloading. | It doesn't look like you are reloading your application, which would be the obvious answer. Really you want to find out what those classes are.
Reflection and XSLT[C] are obvious targets for creating classes, but this seems incredibly regular. Presumably there is some time based cache somewhere that is leaking in some way. | Class Loading problem in Java Enterprise application | [
"",
"java",
"memory-leaks",
"glassfish",
"ejb-3.0",
""
] |
I have a superclass with two subclasses. The two subclasses both have a method with checks whether a chapter has content. For subclass 1 this method is HasContent(int chapterID) and for subclass 2 this is HasContent(int chapterID, int institution). As you can see subclass 2 has an extra parameter. The purpose of both methods is the same.
I was thinking to put the method HasContent in the superclass. Do you think i need to do this? If so, how should i implement this? Or is it more wisely to put both methods in their own subclass?
EDIT:
The body of HasDocuments looks like this:
Subclass1:
```
Database DB = new Database();
int res = DB.ExecuteSpRetVal(chapterID, mInstitutionID);
if (res > 0)
return true;
else
return false;
```
Subclass2:
```
Database DB = new Database();
int res = DB.ExecuteSpRetVal(chapterID);
if (res > 0)
return true;
else
return false;
``` | **Edit:** Updated according to the question update.
Since you are clearly having almost the same logic in both methods, I'd refactor it like this:
```
abstract class SuperClass
{
protected bool HasContentImpl(int chapterID, int institution)
{
Database db = new Database();
int result;
if (institution >= 0) // assuming negative numbers are out of range
result = db.ExecuteSpRetVal(chapterID, institution);
else
result = db.ExecuteSpRetVal(chapterID);
return result > 0;
}
}
class SubClass1 : SuperClass
{
public bool HasContent(int chapterID)
{
return base.HasContentImpl(chapterID, -1);
}
}
class SubClass2 : SuperClass
{
public bool HasContent(int chapterID, int institution)
{
return base.HasContentImpl(chapterID, institution);
}
}
``` | Use method overloading by placing two identically named methods with different arguments into the superclass. When you call HasContent, it will use whichever one matches the number and types of arguments you have provided. Because it is in the superclass, you now won't have to make yet another copy of it if you decide later to make a new subclass that uses this method as well. See below for example code;
```
protected bool HasContent(int chapterID, int institution)
{
Database db = new Database();
int result;
result = db.ExecuteSpRetVal(chapterID, institution);
return result > 0;
}
protected bool HasContent(int chapterID)
{
Database db = new Database();
int result;
result = db.ExecuteSpRetVal(chapterID);
return result > 0;
}
``` | C# Subclass with same method | [
"",
"c#",
"methods",
"subclass",
""
] |
Python has a standard library module `ftplib` to run FTP communications. It has two means of getting a listing of directory contents. One, `FTP.nlst()`, will return a list of the contents of a directory given a directory name as an argument. (It will return the name of a file if given a file name instead.) This is a robust way to list the contents of a directory but does not give any indication whether each item in the list is a file or directory. The other method is `FTP.dir()`, which gives a string formatted listing of the directory contents of the directory given as an argument (or of the file attributes, given a file name).
According to [a previous question on Stack Overflow](https://stackoverflow.com/questions/111954/using-pythons-ftplib-to-get-a-directory-listing-portably), parsing the results of `dir()` can be fragile (different servers may return different strings). I'm looking for some way to list just the directories contained within another directory over FTP, though. To the best of my knowledge, scraping for a `d` in the permissions part of the string is the only solution I've come up with, but I guess I can't guarantee that the permissions will appear in the same place between different servers. Is there a more robust solution to identifying directories over FTP? | Unfortunately FTP doesn't have a command to list just folders so parsing the results you get from ftp.dir() would be 'best'.
A simple app assuming a standard result from ls (not a windows ftp)
```
from ftplib import FTP
ftp = FTP(host, user, passwd)
for r in ftp.dir():
if r.upper().startswith('D'):
print r[58:] # Starting point
```
[Standard FTP Commands](http://www.hiteksoftware.com/help/English/FtpCommands.htm#ftp%20commands)
[Custom FTP Commands](http://www.hiteksoftware.com/help/English/FtpCommands.htm#custom%20commands) | If the FTP server supports the `MLSD` command, then please check [that](https://stackoverflow.com/questions/2867217/how-to-delete-files-with-a-python-script-from-a-ftp-server-which-are-older-than-7/3114477#3114477) answer for a couple of useful classes (`FTPDirectory` and `FTPTree`). | Determine if a listing is a directory or file in Python over FTP | [
"",
"python",
"ftp",
""
] |
I am refactoring a page that uses `<body onload="myJS();">` to a user control. I understand I can do it using server side script registration on load.
If I want to do it on the client side (ascx), how would I do this? | Taken from <http://snipplr.com/view/3116/cross-browser-add-event-listener/>
```
// Cross-browser implementation of element.addEventListener()
function addEvent(evnt, elem, func) {
if (elem.addEventListener) // W3C DOM
elem.addEventListener(evnt,func,false);
else if (elem.attachEvent) { // IE DOM
var r = elem.attachEvent("on"+evnt, func);
return r;
}
```
Use it like this: `addEvent(window, your_onload_handler)`. Or you could just use jquery for this and a lot of other things. | Romme's client-side approach is best. But just in case somebody wanted to know how to do it using server-side code in the ASCX file, stick this in at the top of your template:
```
<script runat="server">
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
string strScript = "myJS();";
Page.ClientScript.RegisterStartupScript(this.GetType(), "OnLoadScript_" + this.ClientID, strScript, true);
}
</script>
``` | Replacing body.onload in a user control | [
"",
"asp.net",
"javascript",
""
] |
Okay, this is something that should be a simple matrix question, but my understanding of matrices is somewhat limited. Here's the scenario: I have a 1px by 1px sprite that I want to scale by some amount x and y (different amounts on each side), and then I want to rotate that sprite by some angle, and then I want to be able to precisely position the whole thing (from the top left or the center, makes no difference to me).
So far my code is vaguely close, but it tends to be off by some random amount depending on the angle I pass in.
I would think that this would do it:
```
Point center = new Point( 50, 50 );
float width = 60;
float height = 100;
float angle = 0.5;
Vector3 axis = new Vector3( center.X, center.Y, 0 );
axis.Normalize();
Matrix m = Matrix.Scaling( width, height, 0 ) *
Matrix.RotationAxis( axis, angle ) *
Matrix.Translation( center.X, center.Y, 0 );
```
But it tends to shrink the scale of the rotated line way down, even though I think it's positioning it sort of right.
I've also tried this:
```
Matrix m = Matrix.Transformation2D( new Vector2( center.X, center.Y ), 0f,
new Vector2( width, height ), new Vector2( center.X, center.Y ),
angle, Vector2.Zero );
```
The line looks exactly right, with the exact right size and shape, but I can't position it correctly at all. If I use the translation vector at the end of the call above, or if I set a position using Sprite.Draw, neither works right.
This is all in SlimDX. What am I doing wrong? | I just went through the pain of learning matrix transformation, but using XNA.
I found [these](http://www.ziggyware.com/readarticle.php?article_id=100) [articles](http://www.riemers.net/eng/ExtraReading/matrices_geometrical.php) [to](http://www.riemers.net/eng/Tutorials/XNA/Csharp/Series1/Rotation_-_translation.php) [be](http://msdn.microsoft.com/en-us/library/ms536397(VS.85).aspx) [very](http://msdn.microsoft.com/en-us/library/eews39w7.aspx) helpful in understanding what happens. The method calls are very similar in XNA and the theory behind it all should apply to you, even with SlimDX.
From glancing at your code, I think you should be translating at the start, to the origin, and then translating again at the end, to the final position, though I'm still a little bit of a newbie at this as well.
The order I would do it in is:
* Translate to origin
* Scale
* Rotate
* Translate to desired location
The reason for translating to the origin first is that *rotations are based from the origin*. Therefore to rotate something about a certain point, place that point on the origin before rotating. | Okay, this is now working. Here's my working code for this, in case someone else needs it:
```
Point sourceLoc = new Point ( 50, 50 );
float length = 60;
float thickness = 2;
float angle = 0.5;
Matrix m = Matrix.Scaling( length, thickness, 0 ) *
Matrix.RotationZ( angle ) *
Matrix.Translation( sourceLoc.X, sourceLoc.Y, 0 );
sprite.Transform = m;
sprite.Draw( this.tx, Vector3.Zero, Vector3.Zero, Color.Red );
```
This will draw an angled line of your chosen length, with a thickness equal to your chosen thickness (presuming your texture is a 1x1 pixel white image). The source location is where the line will emit from, with whatever angle you specify (in radians). So if you start at zero and increment by something like 0.1 until you hit 2PI, and then reset to 0, you'll have a line that rotates around a center like a clock hand or radar sweep. This is what I was looking for -- thanks to all who contributed! | How to rotate, scale, and translate a matrix all at once in C#? | [
"",
"c#",
"matrix",
"translation",
"slimdx",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.