qid int64 4 8.14M | question stringlengths 20 48.3k | answers list | date stringlengths 10 10 | metadata list | input stringlengths 12 45k | output stringlengths 2 31.8k |
|---|---|---|---|---|---|---|
6,430 | <p>I'm suddenly back to WinForms, after years of web development, and am having trouble with something that should be simple. I have an <code>ArrayList</code> of business objects bound to a Windows Forms <code>DataGrid</code>. I'd like the user to be able to edit the cells, and when finished, press a Save button. At that point I'd like to iterate the all the rows and columns in the <code>DataGrid</code> to find any changes, and save them to the database. But I can't find a way to access the <code>DataGrid</code> rows. </p>
<p>I'll also want to validate individual cells real time, as they are edited, but I'm pretty sure that can be done. (Maybe not with an <code>ArrayList</code> as the <code>DataSource</code>?) But as for iterating the <code>DataGrid</code>, I'm quite surprised it doesn't seem possible.</p>
<p>Must I really stuff my business objects data into datatables in order to use the datagrid? </p>
| [
{
"answer_id": 6435,
"author": "NotMyself",
"author_id": 303,
"author_profile": "https://Stackoverflow.com/users/303",
"pm_score": 4,
"selected": true,
"text": "<pre class=\"lang-cs prettyprint-override\"><code>foreach(var row in DataGrid1.Rows)\n{\n DoStuff(row);\n}\n//Or -------------... | 2008/08/08 | [
"https://Stackoverflow.com/questions/6430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/785/"
] | I'm suddenly back to WinForms, after years of web development, and am having trouble with something that should be simple. I have an `ArrayList` of business objects bound to a Windows Forms `DataGrid`. I'd like the user to be able to edit the cells, and when finished, press a Save button. At that point I'd like to iterate the all the rows and columns in the `DataGrid` to find any changes, and save them to the database. But I can't find a way to access the `DataGrid` rows.
I'll also want to validate individual cells real time, as they are edited, but I'm pretty sure that can be done. (Maybe not with an `ArrayList` as the `DataSource`?) But as for iterating the `DataGrid`, I'm quite surprised it doesn't seem possible.
Must I really stuff my business objects data into datatables in order to use the datagrid? | ```cs
foreach(var row in DataGrid1.Rows)
{
DoStuff(row);
}
//Or ---------------------------------------------
foreach(DataGridRow row in DataGrid1.Rows)
{
DoStuff(row);
}
//Or ---------------------------------------------
for(int i = 0; i< DataGrid1.Rows.Count - 1; i++)
{
DoStuff(DataGrid1.Rows[i]);
}
``` |
6,441 | <p>The following code works great in IE, but not in FF or Safari. I can't for the life of me work out why. The code is <em>supposed</em> to disable radio buttons if you select the "Disable 2 radio buttons" option. It should enable the radio buttons if you select the "Enable both radio buttons" option. These both work...</p>
<p>However, if you don't use your mouse to move between the 2 options ("Enable..." and "Disable...") then the radio buttons do not appear to be disabled or enabled correctly, until you click anywhere else on the page (not on the radio buttons themselves).</p>
<p>If anyone has time/is curious/feeling helpful, please paste the code below into an html page and load it up in a browser. It works great in IE, but the problem manifests itself in FF (3 in my case) and Safari, all on Windows XP.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function SetLocationOptions() {
var frmTemp = document.frm;
var selTemp = frmTemp.user;
if (selTemp.selectedIndex >= 0) {
var myOpt = selTemp.options[selTemp.selectedIndex];
if (myOpt.attributes[0].nodeValue == '1') {
frmTemp.transfer_to[0].disabled = true;
frmTemp.transfer_to[1].disabled = true;
frmTemp.transfer_to[2].checked = true;
} else {
frmTemp.transfer_to[0].disabled = false;
frmTemp.transfer_to[1].disabled = false;
}
}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><form name="frm" action="coopfunds_transfer_request.asp" method="post">
<select name="user" onchange="javascript: SetLocationOptions()">
<option value="" />Choose One
<option value="58" user_is_tsm="0" />Enable both radio buttons
<option value="157" user_is_tsm="1" />Disable 2 radio buttons
</select>
<br /><br />
<input type="radio" name="transfer_to" value="fund_amount1" />Premium&nbsp;&nbsp;&nbsp;
<input type="radio" name="transfer_to" value="fund_amount2" />Other&nbsp;&nbsp;&nbsp;
<input type="radio" name="transfer_to" value="both" CHECKED />Both
<br /><br />
<input type="button" class="buttonStyle" value="Submit Request" />
</form></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 6456,
"author": "Polsonby",
"author_id": 137,
"author_profile": "https://Stackoverflow.com/users/137",
"pm_score": 2,
"selected": false,
"text": "<p>Well, IE has a somewhat non-standard object model; what you're doing shouldn't work but you're getting away with it because ... | 2008/08/08 | [
"https://Stackoverflow.com/questions/6441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/232/"
] | The following code works great in IE, but not in FF or Safari. I can't for the life of me work out why. The code is *supposed* to disable radio buttons if you select the "Disable 2 radio buttons" option. It should enable the radio buttons if you select the "Enable both radio buttons" option. These both work...
However, if you don't use your mouse to move between the 2 options ("Enable..." and "Disable...") then the radio buttons do not appear to be disabled or enabled correctly, until you click anywhere else on the page (not on the radio buttons themselves).
If anyone has time/is curious/feeling helpful, please paste the code below into an html page and load it up in a browser. It works great in IE, but the problem manifests itself in FF (3 in my case) and Safari, all on Windows XP.
```js
function SetLocationOptions() {
var frmTemp = document.frm;
var selTemp = frmTemp.user;
if (selTemp.selectedIndex >= 0) {
var myOpt = selTemp.options[selTemp.selectedIndex];
if (myOpt.attributes[0].nodeValue == '1') {
frmTemp.transfer_to[0].disabled = true;
frmTemp.transfer_to[1].disabled = true;
frmTemp.transfer_to[2].checked = true;
} else {
frmTemp.transfer_to[0].disabled = false;
frmTemp.transfer_to[1].disabled = false;
}
}
}
```
```html
<form name="frm" action="coopfunds_transfer_request.asp" method="post">
<select name="user" onchange="javascript: SetLocationOptions()">
<option value="" />Choose One
<option value="58" user_is_tsm="0" />Enable both radio buttons
<option value="157" user_is_tsm="1" />Disable 2 radio buttons
</select>
<br /><br />
<input type="radio" name="transfer_to" value="fund_amount1" />Premium
<input type="radio" name="transfer_to" value="fund_amount2" />Other
<input type="radio" name="transfer_to" value="both" CHECKED />Both
<br /><br />
<input type="button" class="buttonStyle" value="Submit Request" />
</form>
``` | To get FF to mimic IE's behavior when using the keyboard, you can use the keyup event on the select box. In your example (I am not a fan of attaching event handlers this way, but that's another topic), it would be like this:
```
<select name="user" id="selUser" onchange="javascript:SetLocationOptions()" onkeyup="javascript:SetLocationOptions()">
``` |
6,467 | <p>I need to do date arithmetic in Unix shell scripts that I use to control the execution of third party programs. </p>
<p>I'm using a function to increment a day and another to decrement: </p>
<pre><code>IncrementaDia(){
echo $1 | awk '
BEGIN {
diasDelMes[1] = 31
diasDelMes[2] = 28
diasDelMes[3] = 31
diasDelMes[4] = 30
diasDelMes[5] = 31
diasDelMes[6] = 30
diasDelMes[7] = 31
diasDelMes[8] = 31
diasDelMes[9] = 30
diasDelMes[10] = 31
diasDelMes[11] = 30
diasDelMes[12] = 31
}
{
anio=substr($1,1,4)
mes=substr($1,5,2)
dia=substr($1,7,2)
if((anio % 4 == 0 && anio % 100 != 0) || anio % 400 == 0)
{
diasDelMes[2] = 29;
}
if( dia == diasDelMes[int(mes)] ) {
if( int(mes) == 12 ) {
anio = anio + 1
mes = 1
dia = 1
} else {
mes = mes + 1
dia = 1
}
} else {
dia = dia + 1
}
}
END {
printf("%04d%02d%02d", anio, mes, dia)
}
'
}
if [ $# -eq 1 ]; then
tomorrow=$1
else
today=$(date +"%Y%m%d")
tomorrow=$(IncrementaDia $hoy)
fi
</code></pre>
<p>but now I need to do more complex arithmetic. </p>
<p>What it's the best and more compatible way to do this?</p>
| [
{
"answer_id": 6468,
"author": "abyx",
"author_id": 573,
"author_profile": "https://Stackoverflow.com/users/573",
"pm_score": 6,
"selected": false,
"text": "<p>Assuming you have <a href=\"http://www.gnu.org/software/coreutils/manual/coreutils.html#date-invocation\" rel=\"noreferrer\">GNU... | 2008/08/08 | [
"https://Stackoverflow.com/questions/6467",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/527/"
] | I need to do date arithmetic in Unix shell scripts that I use to control the execution of third party programs.
I'm using a function to increment a day and another to decrement:
```
IncrementaDia(){
echo $1 | awk '
BEGIN {
diasDelMes[1] = 31
diasDelMes[2] = 28
diasDelMes[3] = 31
diasDelMes[4] = 30
diasDelMes[5] = 31
diasDelMes[6] = 30
diasDelMes[7] = 31
diasDelMes[8] = 31
diasDelMes[9] = 30
diasDelMes[10] = 31
diasDelMes[11] = 30
diasDelMes[12] = 31
}
{
anio=substr($1,1,4)
mes=substr($1,5,2)
dia=substr($1,7,2)
if((anio % 4 == 0 && anio % 100 != 0) || anio % 400 == 0)
{
diasDelMes[2] = 29;
}
if( dia == diasDelMes[int(mes)] ) {
if( int(mes) == 12 ) {
anio = anio + 1
mes = 1
dia = 1
} else {
mes = mes + 1
dia = 1
}
} else {
dia = dia + 1
}
}
END {
printf("%04d%02d%02d", anio, mes, dia)
}
'
}
if [ $# -eq 1 ]; then
tomorrow=$1
else
today=$(date +"%Y%m%d")
tomorrow=$(IncrementaDia $hoy)
fi
```
but now I need to do more complex arithmetic.
What it's the best and more compatible way to do this? | I have written a bash script for converting dates expressed in English into conventional
mm/dd/yyyy dates. It is called **ComputeDate**.
Here are some examples of its use. For brevity I have placed the output of each invocation
on the same line as the invocation, separarted by a colon (:). The quotes shown below are *not* necessary when running **ComputeDate**:
```
$ ComputeDate 'yesterday': 03/19/2010
$ ComputeDate 'yes': 03/19/2010
$ ComputeDate 'today': 03/20/2010
$ ComputeDate 'tod': 03/20/2010
$ ComputeDate 'now': 03/20/2010
$ ComputeDate 'tomorrow': 03/21/2010
$ ComputeDate 'tom': 03/21/2010
$ ComputeDate '10/29/32': 10/29/2032
$ ComputeDate 'October 29': 10/1/2029
$ ComputeDate 'October 29, 2010': 10/29/2010
$ ComputeDate 'this monday': 'this monday' has passed. Did you mean 'next monday?'
$ ComputeDate 'a week after today': 03/27/2010
$ ComputeDate 'this satu': 03/20/2010
$ ComputeDate 'next monday': 03/22/2010
$ ComputeDate 'next thur': 03/25/2010
$ ComputeDate 'mon in 2 weeks': 03/28/2010
$ ComputeDate 'the last day of the month': 03/31/2010
$ ComputeDate 'the last day of feb': 2/28/2010
$ ComputeDate 'the last day of feb 2000': 2/29/2000
$ ComputeDate '1 week from yesterday': 03/26/2010
$ ComputeDate '1 week from today': 03/27/2010
$ ComputeDate '1 week from tomorrow': 03/28/2010
$ ComputeDate '2 weeks from yesterday': 4/2/2010
$ ComputeDate '2 weeks from today': 4/3/2010
$ ComputeDate '2 weeks from tomorrow': 4/4/2010
$ ComputeDate '1 week after the last day of march': 4/7/2010
$ ComputeDate '1 week after next Thursday': 4/1/2010
$ ComputeDate '2 weeks after the last day of march': 4/14/2010
$ ComputeDate '2 weeks after 1 day after the last day of march': 4/15/2010
$ ComputeDate '1 day after the last day of march': 4/1/2010
$ ComputeDate '1 day after 1 day after 1 day after 1 day after today': 03/24/2010
```
I have included this script as an answer to this problem because it illustrates how
to do date arithmetic via a set of bash functions and these functions may prove useful
for others. It handles leap years and leap centuries correctly:
```
#! /bin/bash
# ConvertDate -- convert a human-readable date to a MM/DD/YY date
#
# Date ::= Month/Day/Year
# | Month/Day
# | DayOfWeek
# | [this|next] DayOfWeek
# | DayofWeek [of|in] [Number|next] weeks[s]
# | Number [day|week][s] from Date
# | the last day of the month
# | the last day of Month
#
# Month ::= January | February | March | April | May | ... | December
# January ::= jan | january | 1
# February ::= feb | january | 2
# ...
# December ::= dec | december | 12
# Day ::= 1 | 2 | ... | 31
# DayOfWeek ::= today | Sunday | Monday | Tuesday | ... | Saturday
# Sunday ::= sun*
# ...
# Saturday ::= sat*
#
# Number ::= Day | a
#
# Author: Larry Morell
if [ $# = 0 ]; then
printdirections $0
exit
fi
# Request the value of a variable
GetVar () {
Var=$1
echo -n "$Var= [${!Var}]: "
local X
read X
if [ ! -z $X ]; then
eval $Var="$X"
fi
}
IsLeapYear () {
local Year=$1
if [ $[20$Year % 4] -eq 0 ]; then
echo yes
else
echo no
fi
}
# AddToDate -- compute another date within the same year
DayNames=(mon tue wed thu fri sat sun ) # To correspond with 'date' output
Day2Int () {
ErrorFlag=
case $1 in
-e )
ErrorFlag=-e; shift
;;
esac
local dow=$1
n=0
while [ $n -lt 7 -a $dow != "${DayNames[n]}" ]; do
let n++
done
if [ -z "$ErrorFlag" -a $n -eq 7 ]; then
echo Cannot convert $dow to a numeric day of wee
exit
fi
echo $[n+1]
}
Months=(31 28 31 30 31 30 31 31 30 31 30 31)
MonthNames=(jan feb mar apr may jun jul aug sep oct nov dec)
# Returns the month (1-12) from a date, or a month name
Month2Int () {
ErrorFlag=
case $1 in
-e )
ErrorFlag=-e; shift
;;
esac
M=$1
Month=${M%%/*} # Remove /...
case $Month in
[a-z]* )
Month=${Month:0:3}
M=0
while [ $M -lt 12 -a ${MonthNames[M]} != $Month ]; do
let M++
done
let M++
esac
if [ -z "$ErrorFlag" -a $M -gt 12 ]; then
echo "'$Month' Is not a valid month."
exit
fi
echo $M
}
# Retrieve month,day,year from a legal date
GetMonth() {
echo ${1%%/*}
}
GetDay() {
echo $1 | col / 2
}
GetYear() {
echo ${1##*/}
}
AddToDate() {
local Date=$1
local days=$2
local Month=`GetMonth $Date`
local Day=`echo $Date | col / 2` # Day of Date
local Year=`echo $Date | col / 3` # Year of Date
local LeapYear=`IsLeapYear $Year`
if [ $LeapYear = "yes" ]; then
let Months[1]++
fi
Day=$[Day+days]
while [ $Day -gt ${Months[$Month-1]} ]; do
Day=$[Day - ${Months[$Month-1]}]
let Month++
done
echo "$Month/$Day/$Year"
}
# Convert a date to normal form
NormalizeDate () {
Date=`echo "$*" | sed 'sX *X/Xg'`
local Day=`date +%d`
local Month=`date +%m`
local Year=`date +%Y`
#echo Normalizing Date=$Date > /dev/tty
case $Date in
*/*/* )
Month=`echo $Date | col / 1 `
Month=`Month2Int $Month`
Day=`echo $Date | col / 2`
Year=`echo $Date | col / 3`
;;
*/* )
Month=`echo $Date | col / 1 `
Month=`Month2Int $Month`
Day=1
Year=`echo $Date | col / 2 `
;;
[a-z]* ) # Better be a month or day of week
Exp=${Date:0:3}
case $Exp in
jan|feb|mar|apr|may|june|jul|aug|sep|oct|nov|dec )
Month=$Exp
Month=`Month2Int $Month`
Day=1
#Year stays the same
;;
mon|tue|wed|thu|fri|sat|sun )
# Compute the next such day
local DayOfWeek=`date +%u`
D=`Day2Int $Exp`
if [ $DayOfWeek -le $D ]; then
Date=`AddToDate $Month/$Day/$Year $[D-DayOfWeek]`
else
Date=`AddToDate $Month/$Day/$Year $[7+D-DayOfWeek]`
fi
# Reset Month/Day/Year
Month=`echo $Date | col / 1 `
Day=`echo $Date | col / 2`
Year=`echo $Date | col / 3`
;;
* ) echo "$Exp is not a valid month or day"
exit
;;
esac
;;
* ) echo "$Date is not a valid date"
exit
;;
esac
case $Day in
[0-9]* );; # Day must be numeric
* ) echo "$Date is not a valid date"
exit
;;
esac
[0-9][0-9][0-9][0-9] );; # Year must be 4 digits
[0-9][0-9] )
Year=20$Year
;;
esac
Date=$Month/$Day/$Year
echo $Date
}
# NormalizeDate jan
# NormalizeDate january
# NormalizeDate jan 2009
# NormalizeDate jan 22 1983
# NormalizeDate 1/22
# NormalizeDate 1 22
# NormalizeDate sat
# NormalizeDate sun
# NormalizeDate mon
ComputeExtension () {
local Date=$1; shift
local Month=`GetMonth $Date`
local Day=`echo $Date | col / 2`
local Year=`echo $Date | col / 3`
local ExtensionExp="$*"
case $ExtensionExp in
*w*d* ) # like 5 weeks 3 days or even 5w2d
ExtensionExp=`echo $ExtensionExp | sed 's/[a-z]/ /g'`
weeks=`echo $ExtensionExp | col 1`
days=`echo $ExtensionExp | col 2`
days=$[7*weeks+days]
Due=`AddToDate $Month/$Day/$Year $days`
;;
*d ) # Like 5 days or 5d
ExtensionExp=`echo $ExtensionExp | sed 's/[a-z]/ /g'`
days=$ExtensionExp
Due=`AddToDate $Month/$Day/$Year $days`
;;
* )
Due=$ExtensionExp
;;
esac
echo $Due
}
# Pop -- remove the first element from an array and shift left
Pop () {
Var=$1
eval "unset $Var[0]"
eval "$Var=(\${$Var[*]})"
}
ComputeDate () {
local Date=`NormalizeDate $1`; shift
local Expression=`echo $* | sed 's/^ *a /1 /;s/,/ /' | tr A-Z a-z `
local Exp=(`echo $Expression `)
local Token=$Exp # first one
local Ans=
#echo "Computing date for ${Exp[*]}" > /dev/tty
case $Token in
*/* ) # Regular date
M=`GetMonth $Token`
D=`GetDay $Token`
Y=`GetYear $Token`
if [ -z "$Y" ]; then
Y=$Year
elif [ ${#Y} -eq 2 ]; then
Y=20$Y
fi
Ans="$M/$D/$Y"
;;
yes* )
Ans=`AddToDate $Date -1`
;;
tod*|now )
Ans=$Date
;;
tom* )
Ans=`AddToDate $Date 1`
;;
the )
case $Expression in
*day*after* ) #the day after Date
Pop Exp; # Skip the
Pop Exp; # Skip day
Pop Exp; # Skip after
#echo Calling ComputeDate $Date ${Exp[*]} > /dev/tty
Date=`ComputeDate $Date ${Exp[*]}` #Recursive call
#echo "New date is " $Date > /dev/tty
Ans=`AddToDate $Date 1`
;;
*last*day*of*th*month|*end*of*th*month )
M=`date +%m`
Day=${Months[M-1]}
if [ $M -eq 2 -a `IsLeapYear $Year` = yes ]; then
let Day++
fi
Ans=$Month/$Day/$Year
;;
*last*day*of* )
D=${Expression##*of }
D=`NormalizeDate $D`
M=`GetMonth $D`
Y=`GetYear $D`
# echo M is $M > /dev/tty
Day=${Months[M-1]}
if [ $M -eq 2 -a `IsLeapYear $Y` = yes ]; then
let Day++
fi
Ans=$[M]/$Day/$Y
;;
* )
echo "Unknown expression: " $Expression
exit
;;
esac
;;
next* ) # next DayOfWeek
Pop Exp
dow=`Day2Int $DayOfWeek` # First 3 chars
tdow=`Day2Int ${Exp:0:3}` # First 3 chars
n=$[7-dow+tdow]
Ans=`AddToDate $Date $n`
;;
this* )
Pop Exp
dow=`Day2Int $DayOfWeek`
tdow=`Day2Int ${Exp:0:3}` # First 3 chars
if [ $dow -gt $tdow ]; then
echo "'this $Exp' has passed. Did you mean 'next $Exp?'"
exit
fi
n=$[tdow-dow]
Ans=`AddToDate $Date $n`
;;
[a-z]* ) # DayOfWeek ...
M=${Exp:0:3}
case $M in
jan|feb|mar|apr|may|june|jul|aug|sep|oct|nov|dec )
ND=`NormalizeDate ${Exp[*]}`
Ans=$ND
;;
mon|tue|wed|thu|fri|sat|sun )
dow=`Day2Int $DayOfWeek`
Ans=`NormalizeDate $Exp`
if [ ${#Exp[*]} -gt 1 ]; then # Just a DayOfWeek
#tdow=`GetDay $Exp` # First 3 chars
#if [ $dow -gt $tdow ]; then
#echo "'this $Exp' has passed. Did you mean 'next $Exp'?"
#exit
#fi
#n=$[tdow-dow]
#else # DayOfWeek in a future week
Pop Exp # toss monday
Pop Exp # toss in/off
if [ $Exp = next ]; then
Exp=2
fi
n=$[7*(Exp-1)] # number of weeks
n=$[n+7-dow+tdow]
Ans=`AddToDate $Date $n`
fi
;;
esac
;;
[0-9]* ) # Number weeks [from|after] Date
n=$Exp
Pop Exp;
case $Exp in
w* ) let n=7*n;;
esac
Pop Exp; Pop Exp
#echo Calling ComputeDate $Date ${Exp[*]} > /dev/tty
Date=`ComputeDate $Date ${Exp[*]}` #Recursive call
#echo "New date is " $Date > /dev/tty
Ans=`AddToDate $Date $n`
;;
esac
echo $Ans
}
Year=`date +%Y`
Month=`date +%m`
Day=`date +%d`
DayOfWeek=`date +%a |tr A-Z a-z`
Date="$Month/$Day/$Year"
ComputeDate $Date $*
```
This script makes extensive use of another script I wrote (called **col** ... many apologies to those who use the standard **col** supplied with Linux). This version of
**col** simplifies extracting columns from the stdin. Thus,
```
$ echo a b c d e | col 5 3 2
```
prints
```
e c b
```
Here it the **col** script:
```
#!/bin/sh
# col -- extract columns from a file
# Usage:
# col [-r] [c] col-1 col-2 ...
# where [c] if supplied defines the field separator
# where each col-i represents a column interpreted according to the presence of -r as follows:
# -r present : counting starts from the right end of the line
# -r absent : counting starts from the left side of the line
Separator=" "
Reverse=false
case "$1" in
-r ) Reverse=true; shift;
;;
[0-9]* )
;;
* )Separator="$1"; shift;
;;
esac
case "$1" in
-r ) Reverse=true; shift;
;;
[0-9]* )
;;
* )Separator="$1"; shift;
;;
esac
# Replace each col-i with $i
Cols=""
for f in $*
do
if [ $Reverse = true ]; then
Cols="$Cols \$(NF-$f+1),"
else
Cols="$Cols \$$f,"
fi
done
Cols=`echo "$Cols" | sed 's/,$//'`
#echo "Using column specifications of $Cols"
awk -F "$Separator" "{print $Cols}"
```
It also uses **printdirections** for printing out directions when the script is invoked improperly:
```
#!/bin/sh
#
# printdirections -- print header lines of a shell script
#
# Usage:
# printdirections path
# where
# path is a *full* path to the shell script in question
# beginning with '/'
#
# To use printdirections, you must include (as comments at the top
# of your shell script) documentation for running the shell script.
if [ $# -eq 0 -o "$*" = "-h" ]; then
printdirections $0
exit
fi
# Delete the command invocation at the top of the file, if any
# Delete from the place where printdirections occurs to the end of the file
# Remove the # comments
# There is a bizarre oddity here.
sed '/#!/d;/.*printdirections/,$d;/ *#/!d;s/# //;s/#//' $1 > /tmp/printdirections.$$
# Count the number of lines
numlines=`wc -l /tmp/printdirections.$$ | awk '{print $1}'`
# Remove the last line
numlines=`expr $numlines - 1`
head -n $numlines /tmp/printdirections.$$
rm /tmp/printdirections.$$
```
To use this place the three scripts in the files **ComputeDate**, **col**, and **printdirections**, respectively. Place the file in directory named by your PATH, typically, ~/bin. Then make them executable with:
```
$ chmod a+x ComputeDate col printdirections
```
Problems? Send me some emaiL: morell AT cs.atu.edu Place **ComputeDate** in the subject. |
6,475 | <p>In a machine with AIX without <code>PERL</code> I need to filter records that will be considered duplicated if they have the same id and if they were registered between a period of four hours. </p>
<p>I implemented this filter using <code>AWK</code> and work pretty well but I need a solution much faster: </p>
<pre>
# Generar lista de Duplicados
awk 'BEGIN {
FS=","
}
/OK/ {
old[$8] = f[$8];
f[$8] = mktime($4, $3, $2, $5, $6, $7);
x[$8]++;
}
/OK/ && x[$8]>1 && f[$8]-old[$8]
<p>Any suggestions? Are there ways to improve the environment (preloading the file or someting like that)? </p>
<p>The input file is already sorted.</p>
<p>With the corrections suggested by <a href="https://stackoverflow.com/questions/6475/faster-way-to-find-duplicates-conditioned-by-time#6869">jj33</a> I made a new version with better treatment of dates, still maintaining a low profile for incorporating more operations: </p>
awk 'BEGIN {
FS=",";
SECSPERMINUTE=60;
SECSPERHOUR=3600;
SECSPERDAY=86400;
split("0 31 59 90 120 151 181 212 243 273 304 334", DAYSTOMONTH, " ");
split("0 366 731 1096 1461 1827 2192 2557 2922 3288 3653 4018 4383 4749 5114 5479 5844 6210 6575 6940 7305", DAYSTOYEAR, " ");
}
/OK/ {
old[$8] = f[$8];
f[$8] = mktime($4, $3, $2, $5, $6, $7);
x[$8]++;
}
/OK/ && x[$8]>1 && f[$8]-old[$8] 2 ) && ( ((y % 4 == 0) && (y % 100 != 0)) || (y % 400 == 0) ) ) {
d2m = d2m + 1;
}
d2y = DAYSTOYEAR[ y - 1999 ];
return ss + (mm*SECSPERMINUTE) + (hh*SECSPEROUR) + (d*SECSPERDAY) + (d2m*SECSPERDAY) + (d2y*SECSPERDAY);
}
'
</pre>
| [
{
"answer_id": 6813,
"author": "David",
"author_id": 381,
"author_profile": "https://Stackoverflow.com/users/381",
"pm_score": 1,
"selected": false,
"text": "<p>If your data file contains all your records (i.e. it includes records that do not have dupicate ids within the file) you could ... | 2008/08/08 | [
"https://Stackoverflow.com/questions/6475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/527/"
] | In a machine with AIX without `PERL` I need to filter records that will be considered duplicated if they have the same id and if they were registered between a period of four hours.
I implemented this filter using `AWK` and work pretty well but I need a solution much faster:
```
# Generar lista de Duplicados
awk 'BEGIN {
FS=","
}
/OK/ {
old[$8] = f[$8];
f[$8] = mktime($4, $3, $2, $5, $6, $7);
x[$8]++;
}
/OK/ && x[$8]>1 && f[$8]-old[$8]
Any suggestions? Are there ways to improve the environment (preloading the file or someting like that)?
The input file is already sorted.
With the corrections suggested by [jj33](https://stackoverflow.com/questions/6475/faster-way-to-find-duplicates-conditioned-by-time#6869) I made a new version with better treatment of dates, still maintaining a low profile for incorporating more operations:
awk 'BEGIN {
FS=",";
SECSPERMINUTE=60;
SECSPERHOUR=3600;
SECSPERDAY=86400;
split("0 31 59 90 120 151 181 212 243 273 304 334", DAYSTOMONTH, " ");
split("0 366 731 1096 1461 1827 2192 2557 2922 3288 3653 4018 4383 4749 5114 5479 5844 6210 6575 6940 7305", DAYSTOYEAR, " ");
}
/OK/ {
old[$8] = f[$8];
f[$8] = mktime($4, $3, $2, $5, $6, $7);
x[$8]++;
}
/OK/ && x[$8]>1 && f[$8]-old[$8] 2 ) && ( ((y % 4 == 0) && (y % 100 != 0)) || (y % 400 == 0) ) ) {
d2m = d2m + 1;
}
d2y = DAYSTOYEAR[ y - 1999 ];
return ss + (mm*SECSPERMINUTE) + (hh*SECSPEROUR) + (d*SECSPERDAY) + (d2m*SECSPERDAY) + (d2y*SECSPERDAY);
}
'
``` | This sounds like a job for an actual database. Even something like SQLite could probably help you reasonably well here. The big problem I see is your definition of "within 4 hours". That's a sliding window problem, which means you can't simply quantize all the data to 4 hour segments... you have to compute all "nearby" elements for every other element separately. Ugh. |
6,499 | <p>There are a few ways to get class-like behavior in javascript, the most common seem to be prototype based like this:</p>
<pre><code>function Vector(x, y, x) {
this.x = x;
this.y = y;
this.z = z;
return this;
}
Vector.prototype.length = function () { return Math.sqrt(this.x * this.x ... ); }
</code></pre>
<p>and closure based approaches similar to</p>
<pre><code>function Vector(x, y, z) {
this.length = function() { return Math.sqrt(x * x + ...); }
}
</code></pre>
<p>For various reasons the latter is faster, but I've seen (and I frequently do write) the prototype version and was curious as to what other people do.</p>
| [
{
"answer_id": 6508,
"author": "Adhip Gupta",
"author_id": 384,
"author_profile": "https://Stackoverflow.com/users/384",
"pm_score": 2,
"selected": false,
"text": "<p>Well, I don't really have an expert opinion on this.\nI usually end up using closures based approach just because it keep... | 2008/08/09 | [
"https://Stackoverflow.com/questions/6499",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/784/"
] | There are a few ways to get class-like behavior in javascript, the most common seem to be prototype based like this:
```
function Vector(x, y, x) {
this.x = x;
this.y = y;
this.z = z;
return this;
}
Vector.prototype.length = function () { return Math.sqrt(this.x * this.x ... ); }
```
and closure based approaches similar to
```
function Vector(x, y, z) {
this.length = function() { return Math.sqrt(x * x + ...); }
}
```
For various reasons the latter is faster, but I've seen (and I frequently do write) the prototype version and was curious as to what other people do. | Assigning functions to the prototype is better (for public methods) because all instances of the class will share the same copy of the method. If you assign the function inside the constructor as in the second example, every time you create a new instance, the constructor creates a new copy of the length function and assigns it to just that one instance.
However this latter technique is useful if you *want* each copy to have it's own copy, the main use of that being to do private/privileges methods which have access to private variables declared inside the constructor and inherited via the closure mechanism.
Douglas Crockford has a good [summary](http://javascript.crockford.com/private.html). |
6,557 | <p>It seems that a List object cannot be stored in a List variable in C#, and can't even be explicitly cast that way.</p>
<pre><code>List<string> sl = new List<string>();
List<object> ol;
ol = sl;
</code></pre>
<p>results in Cannot implicitly convert type <code>System.Collections.Generic.List<string></code> to <code>System.Collections.Generic.List<object></code></p>
<p>And then...</p>
<pre><code>List<string> sl = new List<string>();
List<object> ol;
ol = (List<object>)sl;
</code></pre>
<p>results in Cannot convert type <code>System.Collections.Generic.List<string></code> to <code>System.Collections.Generic.List<object></code></p>
<p>Of course, you can do it by pulling everything out of the string list and putting it back in one at a time, but it is a rather convoluted solution.</p>
| [
{
"answer_id": 6559,
"author": "Rex M",
"author_id": 67,
"author_profile": "https://Stackoverflow.com/users/67",
"pm_score": 4,
"selected": false,
"text": "<p>The reason is that a generic class like <code>List<></code> is, for most purposes, treated externally as a normal class. e.... | 2008/08/09 | [
"https://Stackoverflow.com/questions/6557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/797/"
] | It seems that a List object cannot be stored in a List variable in C#, and can't even be explicitly cast that way.
```
List<string> sl = new List<string>();
List<object> ol;
ol = sl;
```
results in Cannot implicitly convert type `System.Collections.Generic.List<string>` to `System.Collections.Generic.List<object>`
And then...
```
List<string> sl = new List<string>();
List<object> ol;
ol = (List<object>)sl;
```
results in Cannot convert type `System.Collections.Generic.List<string>` to `System.Collections.Generic.List<object>`
Of course, you can do it by pulling everything out of the string list and putting it back in one at a time, but it is a rather convoluted solution. | Think of it this way, if you were to do such a cast, and then add an object of type Foo to the list, the list of strings is no longer consistent. If you were to iterate the first reference, you would get a class cast exception because once you hit the Foo instance, the Foo could not be converted to string!
As a side note, I think it would be more significant whether or not you can do the reverse cast:
```
List<object> ol = new List<object>();
List<string> sl;
sl = (List<string>)ol;
```
I haven't used C# in a while, so I don't know if that is legal, but that sort of cast is actually (potentially) useful. In this case, you are going from a more general class (object) to a more specific class (string) that extends from the general one. In this way, if you add to the list of strings, you are not violating the list of objects.
Does anybody know or can test if such a cast is legal in C#? |
6,578 | <p>I'm just beginning to have a look at Objective-C and Cocoa with a view to playing with the iPhone SDK. I'm reasonably comfortable with C's <code>malloc</code> and <code>free</code> concept, but Cocoa's references counting scheme has me rather confused. I'm told it's very elegant once you understand it, but I'm just not over the hump yet.</p>
<p>How do <code>release</code>, <code>retain</code> and <code>autorelease</code> work and what are the conventions about their use?</p>
<p>(Or failing that, what did you read which helped you get it?)</p>
| [
{
"answer_id": 6592,
"author": "Ecton",
"author_id": 457,
"author_profile": "https://Stackoverflow.com/users/457",
"pm_score": 3,
"selected": false,
"text": "<p>Objective-C uses <a href=\"http://en.wikipedia.org/wiki/Reference_counting\" rel=\"noreferrer\">Reference Counting</a>, which m... | 2008/08/09 | [
"https://Stackoverflow.com/questions/6578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/797/"
] | I'm just beginning to have a look at Objective-C and Cocoa with a view to playing with the iPhone SDK. I'm reasonably comfortable with C's `malloc` and `free` concept, but Cocoa's references counting scheme has me rather confused. I'm told it's very elegant once you understand it, but I'm just not over the hump yet.
How do `release`, `retain` and `autorelease` work and what are the conventions about their use?
(Or failing that, what did you read which helped you get it?) | Let's start with `retain` and `release`; `autorelease` is really just a special case once you understand the basic concepts.
In Cocoa, each object keeps track of how many times it is being referenced (specifically, the `NSObject` base class implements this). By calling `retain` on an object, you are telling it that you want to up its reference count by one. By calling `release`, you tell the object you are letting go of it, and its reference count is decremented. If, after calling `release`, the reference count is now zero, then that object's memory is freed by the system.
The basic way this differs from `malloc` and `free` is that any given object doesn't need to worry about other parts of the system crashing because you've freed memory they were using. Assuming everyone is playing along and retaining/releasing according to the rules, when one piece of code retains and then releases the object, any other piece of code also referencing the object will be unaffected.
What can sometimes be confusing is knowing the circumstances under which you should call `retain` and `release`. My general rule of thumb is that if I want to hang on to an object for some length of time (if it's a member variable in a class, for instance), then I need to make sure the object's reference count knows about me. As described above, an object's reference count is incremented by calling `retain`. By convention, it is also incremented (set to 1, really) when the object is created with an "init" method. In either of these cases, it is my responsibility to call `release` on the object when I'm done with it. If I don't, there will be a memory leak.
Example of object creation:
```
NSString* s = [[NSString alloc] init]; // Ref count is 1
[s retain]; // Ref count is 2 - silly
// to do this after init
[s release]; // Ref count is back to 1
[s release]; // Ref count is 0, object is freed
```
Now for `autorelease`. Autorelease is used as a convenient (and sometimes necessary) way to tell the system to free this object up after a little while. From a plumbing perspective, when `autorelease` is called, the current thread's `NSAutoreleasePool` is alerted of the call. The `NSAutoreleasePool` now knows that once it gets an opportunity (after the current iteration of the event loop), it can call `release` on the object. From our perspective as programmers, it takes care of calling `release` for us, so we don't have to (and in fact, we shouldn't).
What's important to note is that (again, by convention) all object creation *class* methods return an autoreleased object. For example, in the following example, the variable "s" has a reference count of 1, but after the event loop completes, it will be destroyed.
```
NSString* s = [NSString stringWithString:@"Hello World"];
```
If you want to hang onto that string, you'd need to call `retain` explicitly, and then explicitly `release` it when you're done.
Consider the following (very contrived) bit of code, and you'll see a situation where `autorelease` is required:
```
- (NSString*)createHelloWorldString
{
NSString* s = [[NSString alloc] initWithString:@"Hello World"];
// Now what? We want to return s, but we've upped its reference count.
// The caller shouldn't be responsible for releasing it, since we're the
// ones that created it. If we call release, however, the reference
// count will hit zero and bad memory will be returned to the caller.
// The answer is to call autorelease before returning the string. By
// explicitly calling autorelease, we pass the responsibility for
// releasing the string on to the thread's NSAutoreleasePool, which will
// happen at some later time. The consequence is that the returned string
// will still be valid for the caller of this function.
return [s autorelease];
}
```
I realize all of this is a bit confusing - at some point, though, it will click. Here are a few references to get you going:
* [Apple's introduction](http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/MemoryMgmt.html "Apple's introduction to Cocoa's memory management") to memory management.
* [Cocoa Programming for Mac OS X (4th Edition)](https://rads.stackoverflow.com/amzn/click/com/0321774086), by Aaron Hillegas - a very well written book with lots of great examples. It reads like a tutorial.
* If you're truly diving in, you could head to [Big Nerd Ranch](http://www.bignerdranch.com/ "Big Nerd Ranch"). This is a training facility run by Aaron Hillegas - the author of the book mentioned above. I attended the Intro to Cocoa course there several years ago, and it was a great way to learn. |
6,623 | <p>After changing the output directory of a visual studio project it started to fail to build with an error very much like: </p>
<pre><code>C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\bin\sgen.exe /assembly:C:\p4root\Zantaz\trunk\EASDiscovery\EASDiscoveryCaseManagement\obj\Release\EASDiscoveryCaseManagement.dll /proxytypes /reference:C:\p4root\Zantaz\trunk\EASDiscovery\EasDiscovery.Common\target\win_x32\release\results\EASDiscovery.Common.dll /reference:C:\p4root\Zantaz\trunk\EASDiscovery\EasDiscovery.Export\target\win_x32\release\results\EASDiscovery.Export.dll /reference:c:\p4root\Zantaz\trunk\EASDiscovery\ItemCache\target\win_x32\release\results\EasDiscovery.ItemCache.dll /reference:c:\p4root\Zantaz\trunk\EASDiscovery\RetrievalEngine\target\win_x32\release\results\EasDiscovery.RetrievalEngine.dll /reference:C:\p4root\Zantaz\trunk\EASDiscovery\EASDiscoveryJobs\target\win_x32\release\results\EASDiscoveryJobs.dll /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Shared.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.Misc.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinChart.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinDataSource.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinDock.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinEditors.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinGrid.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinListView.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinMaskedEdit.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinStatusBar.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinTabControl.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinToolbars.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinTree.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.v8.1.dll" /reference:"C:\Program Files\Microsoft Visual Studio 8\ReportViewer\Microsoft.ReportViewer.Common.dll" /reference:"C:\Program Files\Microsoft Visual Studio 8\ReportViewer\Microsoft.ReportViewer.WinForms.dll" /reference:C:\p4root\Zantaz\trunk\EASDiscovery\PreviewControl\target\win_x32\release\results\PreviewControl.dll /reference:C:\p4root\Zantaz\trunk\EASDiscovery\Quartz\src\Quartz\target\win_x32\release\results\Scheduler.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.configuration.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Data.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Design.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.DirectoryServices.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Drawing.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Web.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Web.Services.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Windows.Forms.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Xml.dll /compiler:/delaysign-
Error: The specified module could not be found. (Exception from HRESULT: 0x8007007E)
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Microsoft.Common.targets(1902,9): error MSB6006: "sgen.exe" exited with code 1.
</code></pre>
<p>I changed the output directory to target/win_x32/release/results but the path in sgen doesn't seem to have been updated. There seems to be no reference in the project to what path is passed into sgen so I'm unsure how to fix it. As a workaround I have disabled the serialization generation but it would be nice to fix the underlying problem. Has anybody else seen this?</p>
| [
{
"answer_id": 6875,
"author": "pauldoo",
"author_id": 755,
"author_profile": "https://Stackoverflow.com/users/755",
"pm_score": 0,
"selected": false,
"text": "<p>I've not seen this particular problem, but recently for us a \"C1001: An internal error has occurred in the compiler\" type c... | 2008/08/09 | [
"https://Stackoverflow.com/questions/6623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/361/"
] | After changing the output directory of a visual studio project it started to fail to build with an error very much like:
```
C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\bin\sgen.exe /assembly:C:\p4root\Zantaz\trunk\EASDiscovery\EASDiscoveryCaseManagement\obj\Release\EASDiscoveryCaseManagement.dll /proxytypes /reference:C:\p4root\Zantaz\trunk\EASDiscovery\EasDiscovery.Common\target\win_x32\release\results\EASDiscovery.Common.dll /reference:C:\p4root\Zantaz\trunk\EASDiscovery\EasDiscovery.Export\target\win_x32\release\results\EASDiscovery.Export.dll /reference:c:\p4root\Zantaz\trunk\EASDiscovery\ItemCache\target\win_x32\release\results\EasDiscovery.ItemCache.dll /reference:c:\p4root\Zantaz\trunk\EASDiscovery\RetrievalEngine\target\win_x32\release\results\EasDiscovery.RetrievalEngine.dll /reference:C:\p4root\Zantaz\trunk\EASDiscovery\EASDiscoveryJobs\target\win_x32\release\results\EASDiscoveryJobs.dll /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Shared.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.Misc.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinChart.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinDataSource.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinDock.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinEditors.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinGrid.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinListView.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinMaskedEdit.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinStatusBar.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinTabControl.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinToolbars.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinTree.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.v8.1.dll" /reference:"C:\Program Files\Microsoft Visual Studio 8\ReportViewer\Microsoft.ReportViewer.Common.dll" /reference:"C:\Program Files\Microsoft Visual Studio 8\ReportViewer\Microsoft.ReportViewer.WinForms.dll" /reference:C:\p4root\Zantaz\trunk\EASDiscovery\PreviewControl\target\win_x32\release\results\PreviewControl.dll /reference:C:\p4root\Zantaz\trunk\EASDiscovery\Quartz\src\Quartz\target\win_x32\release\results\Scheduler.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.configuration.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Data.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Design.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.DirectoryServices.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Drawing.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Web.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Web.Services.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Windows.Forms.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Xml.dll /compiler:/delaysign-
Error: The specified module could not be found. (Exception from HRESULT: 0x8007007E)
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Microsoft.Common.targets(1902,9): error MSB6006: "sgen.exe" exited with code 1.
```
I changed the output directory to target/win\_x32/release/results but the path in sgen doesn't seem to have been updated. There seems to be no reference in the project to what path is passed into sgen so I'm unsure how to fix it. As a workaround I have disabled the serialization generation but it would be nice to fix the underlying problem. Has anybody else seen this? | see [msdn](http://msdn.microsoft.com/en-us/library/bk3w6240(VS.80).aspx) for the options to sgen.exe [you have the command line, you can play with it manually... delete your .XmlSerializers.dll or use /force though]
Today I also ran across how to more [manually specify the sgen options](http://www.kiwidude.com/blog/2007/02/vs2005-when-sgen-doesnt-work.html). I wanted this to not use the /proxy switch, but it appears it can let you specify the output directory. I don't know enough about msbuild to make it awesome, but this should get you started [open your .csproj/.vbproj in your non-visual studio editor of choice, look at the bottom and you should be able to figure out how/where this goes]
[the below code has had UseProxyTypes set to true for your convenience]
```
<Target Name="GenerateSerializationAssembliesForAllTypes"
DependsOnTargets="AssignTargetPaths;Compile;ResolveKeySource"
Inputs="$(MSBuildAllProjects);@(IntermediateAssembly)"
Outputs="$(OutputPath)$(_SGenDllName)">
<SGen BuildAssemblyName="$(TargetFileName)"
BuildAssemblyPath="$(OutputPath)" References="@(ReferencePath)"
ShouldGenerateSerializer="true" UseProxyTypes="true"
KeyContainer="$(KeyContainerName)" KeyFile="$(KeyOriginatorFile)"
DelaySign="$(DelaySign)" ToolPath="$(SGenToolPath)">
<Output TaskParameter="SerializationAssembly"
ItemName="SerializationAssembly" />
</SGen>
</Target>
<!-- <Target Name="BeforeBuild">
</Target> -->
<Target Name="AfterBuild"
DependsOnTargets="GenerateSerializationAssembliesForAllTypes">
</Target>
``` |
6,628 | <p>What is the difference, if any, between these methods of indexing into a PHP array:</p>
<pre><code>$array[$index]
$array["$index"]
$array["{$index}"]
</code></pre>
<p>I'm interested in both the performance and functional differences.</p>
<h3>Update:</h3>
<p>(In response to @Jeremy) I'm not sure that's right. I ran this code:</p>
<pre><code> $array = array(100, 200, 300);
print_r($array);
$idx = 0;
$array[$idx] = 123;
print_r($array);
$array["$idx"] = 456;
print_r($array);
$array["{$idx}"] = 789;
print_r($array);
</code></pre>
<p>And got this output:</p>
<pre><code>Array
(
[0] => 100
[1] => 200
[2] => 300
)
Array
(
[0] => 123
[1] => 200
[2] => 300
)
Array
(
[0] => 456
[1] => 200
[2] => 300
)
Array
(
[0] => 789
[1] => 200
[2] => 300
)
</code></pre>
| [
{
"answer_id": 6629,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 0,
"selected": false,
"text": "<p>If $index is a string there is no difference because $index, \"$index\", and \"{$index}\" all evaluate to the same string... | 2008/08/09 | [
"https://Stackoverflow.com/questions/6628",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/103/"
] | What is the difference, if any, between these methods of indexing into a PHP array:
```
$array[$index]
$array["$index"]
$array["{$index}"]
```
I'm interested in both the performance and functional differences.
### Update:
(In response to @Jeremy) I'm not sure that's right. I ran this code:
```
$array = array(100, 200, 300);
print_r($array);
$idx = 0;
$array[$idx] = 123;
print_r($array);
$array["$idx"] = 456;
print_r($array);
$array["{$idx}"] = 789;
print_r($array);
```
And got this output:
```
Array
(
[0] => 100
[1] => 200
[2] => 300
)
Array
(
[0] => 123
[1] => 200
[2] => 300
)
Array
(
[0] => 456
[1] => 200
[2] => 300
)
Array
(
[0] => 789
[1] => 200
[2] => 300
)
``` | see @svec and @jeremy above. All array indices are of type 'int' first, then type 'string', and will be cast to that as PHP sees fit.
Performance wise, $index should be faster than "$index" and "{$index}" (which are the same).
Once you start a double-quote string, PHP will go into interpolation mode and treat it as a string first, but looking for variable markers ($, {}, etc) to replace from the local scope. This is why in most discussions, true 'static' strings should always be single quotes unless you need the escape-shortcuts like "\n" or "\t", because PHP will not need to try to interpolate the string at runtime and the full string can be compiled statically.
In this case, doublequoting will first copy the $index into that string, then return the string, where directly using $index will just return the string. |
6,639 | <p>How should I load files into my Java application?</p>
| [
{
"answer_id": 6640,
"author": "Will",
"author_id": 816,
"author_profile": "https://Stackoverflow.com/users/816",
"pm_score": 6,
"selected": false,
"text": "<p><strong>The short answer</strong></p>\n\n<p>Use one of these two methods:</p>\n\n<ul>\n<li><a href=\"http://java.sun.com/javase/... | 2008/08/09 | [
"https://Stackoverflow.com/questions/6639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/816/"
] | How should I load files into my Java application? | **The short answer**
Use one of these two methods:
* [`Class.getResource(String)`](http://java.sun.com/javase/6/docs/api/java/lang/Class.html#getResource(java.lang.String))
* [`Class.getResourceAsStream(String)`](http://java.sun.com/javase/6/docs/api/java/lang/Class.html#getResourceAsStream(java.lang.String))
For example:
```
InputStream inputStream = YourClass.class.getResourceAsStream("image.jpg");
```
--
**The long answer**
Typically, one would not want to load files using absolute paths. For example, don’t do this if you can help it:
```
File file = new File("C:\\Users\\Joe\\image.jpg");
```
This technique is not recommended for at least two reasons. First, it creates a dependency on a particular operating system, which prevents the application from easily moving to another operating system. One of Java’s main benefits is the ability to run the same bytecode on many different platforms. Using an absolute path like this makes the code much less portable.
Second, depending on the relative location of the file, this technique might create an external dependency and limit the application’s mobility. If the file exists outside the application’s current directory, this creates an external dependency and one would have to be aware of the dependency in order to move the application to another machine (error prone).
Instead, use the `getResource()` methods in the `Class` class. This makes the application much more portable. It can be moved to different platforms, machines, or directories and still function correctly. |
6,642 | <p>I was trying to add a favicon to a website earlier and looked for a better way to implement this than to dump a <code>favicon.ico</code> file in the root of the website.</p>
<p>I found this nice little guide: <a href="http://www.w3.org/2005/10/howto-favicon" rel="noreferrer">How to Add a Favicon</a>. However, the preferred method did not work in IE (7) and the second method is the old fashioned way (which I resigned myself to use).</p>
<p>Is there a third method that works across all the most popular browsers?</p>
| [
{
"answer_id": 6643,
"author": "Brandon Wood",
"author_id": 423,
"author_profile": "https://Stackoverflow.com/users/423",
"pm_score": 0,
"selected": false,
"text": "<p>This is how they're doing it right here on Stack Overflow:</p>\n\n<pre><code><link rel=\"shortcut icon\" href=\"/favi... | 2008/08/09 | [
"https://Stackoverflow.com/questions/6642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/810/"
] | I was trying to add a favicon to a website earlier and looked for a better way to implement this than to dump a `favicon.ico` file in the root of the website.
I found this nice little guide: [How to Add a Favicon](http://www.w3.org/2005/10/howto-favicon). However, the preferred method did not work in IE (7) and the second method is the old fashioned way (which I resigned myself to use).
Is there a third method that works across all the most popular browsers? | This is what I always use:
```
<link rel="icon" href="favicon.ico" type="image/x-icon" />
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
```
The second one is for IE. The first one is for other browsers. |
6,681 | <p>I'm still new to the ASP.NET world, so I could be way off base here, but so far this is to the best of my (limited) knowledge!</p>
<p>Let's say I have a standard business object "Contact" in the <em>Business</em> namespace. I write a Web Service to retrieve a Contact's info from a database and return it. I then write a client application to request said details.</p>
<p>Now, I also then create a utility method that takes a "Contact" and does some magic with it, like <code>Utils.BuyContactNewHat()</code> say. Which of course takes the Contact of type <code>Business.Contact</code>.</p>
<p>I then go back to my client application and want to utilise the <code>BuyContactNewHat</code> method, so I add a reference to my <em>Utils</em> namespace and there it is. However, a problem arises with:</p>
<pre><code>Contact c = MyWebService.GetContact("Rob);
Utils.BuyContactNewHat(c); // << Error Here
</code></pre>
<p>Since the return type of <code>GetContact</code> is of <code>MyWebService.Contact</code> and not <code>Business.Contact</code> as expected. I understand why this is because when accessing a web service, you are actually programming against the proxy class generated by the WSDL.</p>
<p>So, is there an "easier" way to deal with this type of mismatch? I was considering perhaps trying to create a generic converter class that uses reflection to ensure two objects have the same structure than simply transferring the values across from one to the other.</p>
| [
{
"answer_id": 6704,
"author": "Lance Fisher",
"author_id": 571,
"author_profile": "https://Stackoverflow.com/users/571",
"pm_score": 4,
"selected": true,
"text": "<p>You are on the right track. To get the data from the proxy object back into one of your own objects, you have to do left... | 2008/08/09 | [
"https://Stackoverflow.com/questions/6681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/832/"
] | I'm still new to the ASP.NET world, so I could be way off base here, but so far this is to the best of my (limited) knowledge!
Let's say I have a standard business object "Contact" in the *Business* namespace. I write a Web Service to retrieve a Contact's info from a database and return it. I then write a client application to request said details.
Now, I also then create a utility method that takes a "Contact" and does some magic with it, like `Utils.BuyContactNewHat()` say. Which of course takes the Contact of type `Business.Contact`.
I then go back to my client application and want to utilise the `BuyContactNewHat` method, so I add a reference to my *Utils* namespace and there it is. However, a problem arises with:
```
Contact c = MyWebService.GetContact("Rob);
Utils.BuyContactNewHat(c); // << Error Here
```
Since the return type of `GetContact` is of `MyWebService.Contact` and not `Business.Contact` as expected. I understand why this is because when accessing a web service, you are actually programming against the proxy class generated by the WSDL.
So, is there an "easier" way to deal with this type of mismatch? I was considering perhaps trying to create a generic converter class that uses reflection to ensure two objects have the same structure than simply transferring the values across from one to the other. | You are on the right track. To get the data from the proxy object back into one of your own objects, you have to do left-hand-right-hand code. i.e. copy property values. I'll bet you that there is already a generic method out there that uses reflection.
Some people will use something other than a web service (.net remoting) if they just want to get a business object across the wire. Or they'll use binary serialization. I'm guessing you are using the web service for a reason, so you'll have to do property copying. |
6,785 | <p>Suppose I have a stringbuilder in C# that does this:</p>
<pre><code>StringBuilder sb = new StringBuilder();
string cat = "cat";
sb.Append("the ").Append(cat).(" in the hat");
string s = sb.ToString();
</code></pre>
<p>would that be as efficient or any more efficient as having:</p>
<pre><code>string cat = "cat";
string s = String.Format("The {0} in the hat", cat);
</code></pre>
<p>If so, why?</p>
<p><strong>EDIT</strong> </p>
<p>After some interesting answers, I realised I probably should have been a little clearer in what I was asking. I wasn't so much asking for which was quicker at concatenating a string, but which is quicker at <strong><em>injecting</em></strong> one string into another.</p>
<p>In both cases above I want to inject one or more strings into the middle of a predefined template string.</p>
<p>Sorry for the confusion</p>
| [
{
"answer_id": 6786,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": -1,
"selected": false,
"text": "<p>I would suggest not, since String.Format was not designed for concatenation, it was design for formatting the output of v... | 2008/08/09 | [
"https://Stackoverflow.com/questions/6785",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/493/"
] | Suppose I have a stringbuilder in C# that does this:
```
StringBuilder sb = new StringBuilder();
string cat = "cat";
sb.Append("the ").Append(cat).(" in the hat");
string s = sb.ToString();
```
would that be as efficient or any more efficient as having:
```
string cat = "cat";
string s = String.Format("The {0} in the hat", cat);
```
If so, why?
**EDIT**
After some interesting answers, I realised I probably should have been a little clearer in what I was asking. I wasn't so much asking for which was quicker at concatenating a string, but which is quicker at ***injecting*** one string into another.
In both cases above I want to inject one or more strings into the middle of a predefined template string.
Sorry for the confusion | **NOTE:** This answer was written when .NET 2.0 was the current version. This may no longer apply to later versions.
`String.Format` uses a `StringBuilder` internally:
```
public static string Format(IFormatProvider provider, string format, params object[] args)
{
if ((format == null) || (args == null))
{
throw new ArgumentNullException((format == null) ? "format" : "args");
}
StringBuilder builder = new StringBuilder(format.Length + (args.Length * 8));
builder.AppendFormat(provider, format, args);
return builder.ToString();
}
```
The above code is a snippet from mscorlib, so the question becomes "is `StringBuilder.Append()` faster than `StringBuilder.AppendFormat()`"?
Without benchmarking I'd probably say that the code sample above would run more quickly using `.Append()`. But it's a guess, try benchmarking and/or profiling the two to get a proper comparison.
This chap, Jerry Dixon, did some benchmarking:
>
> <http://jdixon.dotnetdevelopersjournal.com/string_concatenation_stringbuilder_and_stringformat.htm>
>
>
>
**Updated:**
Sadly the link above has since died. However there's still a copy on the Way Back Machine:
>
> <http://web.archive.org/web/20090417100252/http://jdixon.dotnetdevelopersjournal.com/string_concatenation_stringbuilder_and_stringformat.htm>
>
>
>
At the end of the day it depends whether your string formatting is going to be called repetitively, i.e. you're doing some serious text processing over 100's of megabytes of text, or whether it's being called when a user clicks a button now and again. Unless you're doing some huge batch processing job I'd stick with String.Format, it aids code readability. If you suspect a perf bottleneck then stick a profiler on your code and see where it really is. |
6,811 | <p>Before reading anything else, please take time to read the <a href="https://stackoverflow.com/questions/1615/how-can-i-modify-xfdl-files-update-1">original thread</a>.</p>
<p>Overview: a .xfdl file is a gzipped .xml file which has then been encoded in base64. I wish to de-encode the .xfdl into xml which I can then modify and then re-encode back into a .xfdl file.</p>
<blockquote>
<p>xfdl > xml.gz > xml > xml.gz > xfdl</p>
</blockquote>
<p>I have been able to take a .xfdl file and de-encode it from base64 using uudeview:</p>
<pre><code>uudeview -i yourform.xfdl
</code></pre>
<p>Then decommpressed it using gunzip</p>
<pre><code>gunzip -S "" < UNKNOWN.001 > yourform-unpacked.xml
</code></pre>
<p>The xml produced is 100% readable and looks wonderful. Without modifying the xml then, i should be able to re-compress it using gzip:</p>
<pre><code>gzip yourform-unpacked.xml
</code></pre>
<p>Then re-encoded in base-64:</p>
<pre><code>base64 -e yourform-unpacked.xml.gz yourform_reencoded.xfdl
</code></pre>
<p>If my thinking is correct, the original file and the re-encoded file should be equal. If I put yourform.xfdl and yourform_reencoded.xfdl into beyond compare, however, they do not match up. Also, the original file can be viewed in an http://www.grants.gov/help/download_software.jsp#pureedge">.xfdl viewer. The viewer says that the re-encoded xfdl is unreadable. </p>
<p>I have also tried uuenview to re-encode in base64, it also produces the same results. Any help would be appreciated.</p>
| [
{
"answer_id": 6825,
"author": "John Downey",
"author_id": 200,
"author_profile": "https://Stackoverflow.com/users/200",
"pm_score": 0,
"selected": false,
"text": "<p>Different implementations of the gzip algorithm will always produce slightly different but still correct files, also the ... | 2008/08/09 | [
"https://Stackoverflow.com/questions/6811",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25/"
] | Before reading anything else, please take time to read the [original thread](https://stackoverflow.com/questions/1615/how-can-i-modify-xfdl-files-update-1).
Overview: a .xfdl file is a gzipped .xml file which has then been encoded in base64. I wish to de-encode the .xfdl into xml which I can then modify and then re-encode back into a .xfdl file.
>
> xfdl > xml.gz > xml > xml.gz > xfdl
>
>
>
I have been able to take a .xfdl file and de-encode it from base64 using uudeview:
```
uudeview -i yourform.xfdl
```
Then decommpressed it using gunzip
```
gunzip -S "" < UNKNOWN.001 > yourform-unpacked.xml
```
The xml produced is 100% readable and looks wonderful. Without modifying the xml then, i should be able to re-compress it using gzip:
```
gzip yourform-unpacked.xml
```
Then re-encoded in base-64:
```
base64 -e yourform-unpacked.xml.gz yourform_reencoded.xfdl
```
If my thinking is correct, the original file and the re-encoded file should be equal. If I put yourform.xfdl and yourform\_reencoded.xfdl into beyond compare, however, they do not match up. Also, the original file can be viewed in an http://www.grants.gov/help/download\_software.jsp#pureedge">.xfdl viewer. The viewer says that the re-encoded xfdl is unreadable.
I have also tried uuenview to re-encode in base64, it also produces the same results. Any help would be appreciated. | As far as I know you cannot find the compression level of an already compressed file. When you are compressing the file you can specify the compression level with -# where the # is from 1 to 9 (1 being the fastest compression and 9 being the most compressed file). In practice you should never compare a compressed file with one that has been extracted and recompressed, slight variations can easily crop up. In your case I would compare the base64 encoded versions instead of the gzip'd versions. |
6,816 | <p>I was hoping someone could help me out with a problem I'm having using the java search function in Eclipse on a particular project.</p>
<p>When using the java search on one particular project, I get an error message saying <code>Class file name must end with .class</code> (see stack trace below). This does not seem to be happening on all projects, just one particular one, so perhaps there's something I should try to get rebuilt?</p>
<p>I have already tried <code>Project -> Clean</code>... and Closing Eclipse, deleting all the built class files and restarting Eclipse to no avail.</p>
<p>The only reference I've been able to find on Google for the problem is at <a href="http://www.crazysquirrel.com/computing/java/eclipse/error-during-java-search.jspx" rel="noreferrer">http://www.crazysquirrel.com/computing/java/eclipse/error-during-java-search.jspx</a>, but unfortunately his solution (closing, deleting class files, restarting) did not work for me.</p>
<p>If anyone can suggest something to try, or there's any more info I can gather which might help track it's down, I'd greatly appreciate the pointers.</p>
<pre><code>Version: 3.4.0
Build id: I20080617-2000
</code></pre>
<p>Also just found this thread - <a href="http://www.myeclipseide.com/PNphpBB2-viewtopic-t-20067.html" rel="noreferrer">http://www.myeclipseide.com/PNphpBB2-viewtopic-t-20067.html</a> - which indicates the same problem may occur when the project name contains a period. Unfortunately, that's not the case in my setup, so I'm still stuck.</p>
<pre><code>Caused by: java.lang.IllegalArgumentException: Class file name must end with .class
at org.eclipse.jdt.internal.core.PackageFragment.getClassFile(PackageFragment.java:182)
at org.eclipse.jdt.internal.core.util.HandleFactory.createOpenable(HandleFactory.java:109)
at org.eclipse.jdt.internal.core.search.matching.MatchLocator.locateMatches(MatchLocator.java:1177)
at org.eclipse.jdt.internal.core.search.JavaSearchParticipant.locateMatches(JavaSearchParticipant.java:94)
at org.eclipse.jdt.internal.core.search.BasicSearchEngine.findMatches(BasicSearchEngine.java:223)
at org.eclipse.jdt.internal.core.search.BasicSearchEngine.search(BasicSearchEngine.java:506)
at org.eclipse.jdt.core.search.SearchEngine.search(SearchEngine.java:551)
at org.eclipse.jdt.internal.corext.refactoring.RefactoringSearchEngine.internalSearch(RefactoringSearchEngine.java:142)
at org.eclipse.jdt.internal.corext.refactoring.RefactoringSearchEngine.search(RefactoringSearchEngine.java:129)
at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTypeProcessor.initializeReferences(RenameTypeProcessor.java:594)
at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTypeProcessor.doCheckFinalConditions(RenameTypeProcessor.java:522)
at org.eclipse.jdt.internal.corext.refactoring.rename.JavaRenameProcessor.checkFinalConditions(JavaRenameProcessor.java:45)
at org.eclipse.ltk.core.refactoring.participants.ProcessorBasedRefactoring.checkFinalConditions(ProcessorBasedRefactoring.java:225)
at org.eclipse.ltk.core.refactoring.Refactoring.checkAllConditions(Refactoring.java:160)
at org.eclipse.jdt.internal.ui.refactoring.RefactoringExecutionHelper$Operation.run(RefactoringExecutionHelper.java:77)
at org.eclipse.jdt.internal.core.BatchOperation.executeOperation(BatchOperation.java:39)
at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:709)
at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:1800)
at org.eclipse.jdt.core.JavaCore.run(JavaCore.java:4650)
at org.eclipse.jdt.internal.ui.actions.WorkbenchRunnableAdapter.run(WorkbenchRunnableAdapter.java:92)
at org.eclipse.jface.operation.ModalContext$ModalContextThread.run(ModalContext.java:121)
</code></pre>
<p>Thanks McDowell, closing and opening the project seems to have fixed it (at least for now).</p>
| [
{
"answer_id": 6840,
"author": "McDowell",
"author_id": 304,
"author_profile": "https://Stackoverflow.com/users/304",
"pm_score": 7,
"selected": true,
"text": "<p>Two more general-purpose mechanisms for fixing some of Eclipse's idiosyncrasies:</p>\n\n<ul>\n<li>Close and open the project<... | 2008/08/09 | [
"https://Stackoverflow.com/questions/6816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/797/"
] | I was hoping someone could help me out with a problem I'm having using the java search function in Eclipse on a particular project.
When using the java search on one particular project, I get an error message saying `Class file name must end with .class` (see stack trace below). This does not seem to be happening on all projects, just one particular one, so perhaps there's something I should try to get rebuilt?
I have already tried `Project -> Clean`... and Closing Eclipse, deleting all the built class files and restarting Eclipse to no avail.
The only reference I've been able to find on Google for the problem is at <http://www.crazysquirrel.com/computing/java/eclipse/error-during-java-search.jspx>, but unfortunately his solution (closing, deleting class files, restarting) did not work for me.
If anyone can suggest something to try, or there's any more info I can gather which might help track it's down, I'd greatly appreciate the pointers.
```
Version: 3.4.0
Build id: I20080617-2000
```
Also just found this thread - <http://www.myeclipseide.com/PNphpBB2-viewtopic-t-20067.html> - which indicates the same problem may occur when the project name contains a period. Unfortunately, that's not the case in my setup, so I'm still stuck.
```
Caused by: java.lang.IllegalArgumentException: Class file name must end with .class
at org.eclipse.jdt.internal.core.PackageFragment.getClassFile(PackageFragment.java:182)
at org.eclipse.jdt.internal.core.util.HandleFactory.createOpenable(HandleFactory.java:109)
at org.eclipse.jdt.internal.core.search.matching.MatchLocator.locateMatches(MatchLocator.java:1177)
at org.eclipse.jdt.internal.core.search.JavaSearchParticipant.locateMatches(JavaSearchParticipant.java:94)
at org.eclipse.jdt.internal.core.search.BasicSearchEngine.findMatches(BasicSearchEngine.java:223)
at org.eclipse.jdt.internal.core.search.BasicSearchEngine.search(BasicSearchEngine.java:506)
at org.eclipse.jdt.core.search.SearchEngine.search(SearchEngine.java:551)
at org.eclipse.jdt.internal.corext.refactoring.RefactoringSearchEngine.internalSearch(RefactoringSearchEngine.java:142)
at org.eclipse.jdt.internal.corext.refactoring.RefactoringSearchEngine.search(RefactoringSearchEngine.java:129)
at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTypeProcessor.initializeReferences(RenameTypeProcessor.java:594)
at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTypeProcessor.doCheckFinalConditions(RenameTypeProcessor.java:522)
at org.eclipse.jdt.internal.corext.refactoring.rename.JavaRenameProcessor.checkFinalConditions(JavaRenameProcessor.java:45)
at org.eclipse.ltk.core.refactoring.participants.ProcessorBasedRefactoring.checkFinalConditions(ProcessorBasedRefactoring.java:225)
at org.eclipse.ltk.core.refactoring.Refactoring.checkAllConditions(Refactoring.java:160)
at org.eclipse.jdt.internal.ui.refactoring.RefactoringExecutionHelper$Operation.run(RefactoringExecutionHelper.java:77)
at org.eclipse.jdt.internal.core.BatchOperation.executeOperation(BatchOperation.java:39)
at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:709)
at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:1800)
at org.eclipse.jdt.core.JavaCore.run(JavaCore.java:4650)
at org.eclipse.jdt.internal.ui.actions.WorkbenchRunnableAdapter.run(WorkbenchRunnableAdapter.java:92)
at org.eclipse.jface.operation.ModalContext$ModalContextThread.run(ModalContext.java:121)
```
Thanks McDowell, closing and opening the project seems to have fixed it (at least for now). | Two more general-purpose mechanisms for fixing some of Eclipse's idiosyncrasies:
* Close and open the project
* Delete the project (but not from disk!) and reimport it as an existing project
Failing that, [bugs.eclipse.org](https://bugs.eclipse.org/bugs/buglist.cgi?query_format=specific&order=relevance+desc&bug_status=__all__&product=JDT&content=Class+file+name+must+end+with+.class) might provide the answer.
If the workspace is caching something broken, you may be able to delete it by poking around in **workspace/.metadata/.plugins**. Most of that stuff is fairly transient (though backup and watch for deleted preferences). |
6,890 | <p>I have some code for starting a thread on the .NET CF 2.0:</p>
<pre><code>ThreadStart tStart = new ThreadStart(MyMethod);
Thread t = new Thread(tStart);
t.Start();
</code></pre>
<p>If I call this inside a loop the items completely out of order. How do introduce a wait after <code>t.Start()</code>, so that the work on the thread completes before the code continues? Will BeginInvoke/EndInvoke be a better option for this than manually creating threads?</p>
| [
{
"answer_id": 6935,
"author": "Kev",
"author_id": 419,
"author_profile": "https://Stackoverflow.com/users/419",
"pm_score": 2,
"selected": false,
"text": "<p>If I'm reading this properly, you're starting work items on bunch of threads but you're concerned that the threads are completing... | 2008/08/09 | [
"https://Stackoverflow.com/questions/6890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/636/"
] | I have some code for starting a thread on the .NET CF 2.0:
```
ThreadStart tStart = new ThreadStart(MyMethod);
Thread t = new Thread(tStart);
t.Start();
```
If I call this inside a loop the items completely out of order. How do introduce a wait after `t.Start()`, so that the work on the thread completes before the code continues? Will BeginInvoke/EndInvoke be a better option for this than manually creating threads? | How much order do you need to impose on the threads? If you just need all of the work started in the loop to finish before the code continues, but you don't care about the order the work within the loop finishes, then calling Join is the answer. To add more detail to [Kevin Kenny's answer,](https://stackoverflow.com/questions/6890/compact-framework-how-to-wait-for-thread-complete-before-continuing#6935) you should call Join *outside* the loop. This means you will need a collection to hold references to the threads you started:
```
// Start all of the threads.
List<Thread> startedThreads = new List<Thread>();
foreach (...) {
Thread thread = new Thread(new ThreadStart(MyMethod));
thread.Start();
startedThreads.Add(thread);
}
// Wait for all of the threads to finish.
foreach (Thread thread in startedThreads) {
thread.Join();
}
```
In contrast, if you called Join inside the loop, the result would basically be the same as not using threads at all. Each iteration of the loop body would create and start a thread but then immediately Join it and wait for it to finish.
If the individual threads produce some result (write a message in a log, for example) then the messages may still appear out of order because there's no coordination between the threads. It is possible to get the threads to output their results in order by coordinating them with a Monitor. |
6,891 | <p>I have come across the following type of code many a times, and I wonder if this is a good practice (from Performance perspective) or not:</p>
<pre><code>try
{
... // some code
}
catch (Exception ex)
{
... // Do something
throw new CustomException(ex);
}
</code></pre>
<p>Basically, what the coder is doing is that they are encompassing the exception in a custom exception and throwing that again.</p>
<p>How does this differ in Performance from the following two:</p>
<pre><code>try
{
... // some code
}
catch (Exception ex)
{
.. // Do something
throw ex;
}
</code></pre>
<p>or </p>
<pre><code>try
{
... // some code
}
catch (Exception ex)
{
.. // Do something
throw;
}
</code></pre>
<p>Putting aside any functional or coding best practice arguments, is there any performance difference between the 3 approaches?</p>
| [
{
"answer_id": 6910,
"author": "David",
"author_id": 381,
"author_profile": "https://Stackoverflow.com/users/381",
"pm_score": 0,
"selected": false,
"text": "<p>The throw in your first example has the overhead of the creation of a new CustomException object.</p>\n\n<p>The re-throw in you... | 2008/08/09 | [
"https://Stackoverflow.com/questions/6891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/380/"
] | I have come across the following type of code many a times, and I wonder if this is a good practice (from Performance perspective) or not:
```
try
{
... // some code
}
catch (Exception ex)
{
... // Do something
throw new CustomException(ex);
}
```
Basically, what the coder is doing is that they are encompassing the exception in a custom exception and throwing that again.
How does this differ in Performance from the following two:
```
try
{
... // some code
}
catch (Exception ex)
{
.. // Do something
throw ex;
}
```
or
```
try
{
... // some code
}
catch (Exception ex)
{
.. // Do something
throw;
}
```
Putting aside any functional or coding best practice arguments, is there any performance difference between the 3 approaches? | @Brad Tutterow
The exception is not being lost in the first case, it is being passed in to the constructor. I will agree with you on the rest though, the second approach is a very bad idea because of the loss of stack trace. When I worked with .NET, I ran into many cases where other programmers did just that, and it frustrated me to no end when I needed to see the true cause of an exception, only to find it being rethrown from a huge try block where I now have no idea where the problem originated.
I also second Brad's comment that you shouldn't worry about the performance. This kind of micro optimization is a HORRIBLE idea. Unless you are talking about throwing an exception in every iteration of a for loop that is running for a long time, you will more than likely not run into performance issues by the way of your exception usage.
Always optimize performance when you have metrics that indicate you NEED to optimize performance, and then hit the spots that are proven to be the culprit.
It is much better to have readable code with easy debugging capabilities (IE not hiding the stack trace) rather than make something run a nanosecond faster.
A final note about wrapping exceptions into a custom exception... this can be a very useful construct, especially when dealing with UIs. You can wrap every known and reasonable exceptional case into some base custom exception (or one that extends from said base exception), and then the UI can just catch this base exception. When caught, the exception will need to provide means of displaying information to the user, say a ReadableMessage property, or something along those lines. Thus, any time the UI misses an exception, it is because of a bug you need to fix, and anytime it catches an exception, it is a known error condition that can and should be handled properly by the UI. |
6,899 | <p>To illustrate, assume that I have two tables as follows:</p>
<pre><code>VehicleID Name
1 Chuck
2 Larry
LocationID VehicleID City
1 1 New York
2 1 Seattle
3 1 Vancouver
4 2 Los Angeles
5 2 Houston
</code></pre>
<p>I want to write a query to return the following results:</p>
<pre><code>VehicleID Name Locations
1 Chuck New York, Seattle, Vancouver
2 Larry Los Angeles, Houston
</code></pre>
<p>I know that this can be done using server side cursors, ie:</p>
<pre><code>DECLARE @VehicleID int
DECLARE @VehicleName varchar(100)
DECLARE @LocationCity varchar(100)
DECLARE @Locations varchar(4000)
DECLARE @Results TABLE
(
VehicleID int
Name varchar(100)
Locations varchar(4000)
)
DECLARE VehiclesCursor CURSOR FOR
SELECT
[VehicleID]
, [Name]
FROM [Vehicles]
OPEN VehiclesCursor
FETCH NEXT FROM VehiclesCursor INTO
@VehicleID
, @VehicleName
WHILE @@FETCH_STATUS = 0
BEGIN
SET @Locations = ''
DECLARE LocationsCursor CURSOR FOR
SELECT
[City]
FROM [Locations]
WHERE [VehicleID] = @VehicleID
OPEN LocationsCursor
FETCH NEXT FROM LocationsCursor INTO
@LocationCity
WHILE @@FETCH_STATUS = 0
BEGIN
SET @Locations = @Locations + @LocationCity
FETCH NEXT FROM LocationsCursor INTO
@LocationCity
END
CLOSE LocationsCursor
DEALLOCATE LocationsCursor
INSERT INTO @Results (VehicleID, Name, Locations) SELECT @VehicleID, @Name, @Locations
END
CLOSE VehiclesCursor
DEALLOCATE VehiclesCursor
SELECT * FROM @Results
</code></pre>
<p>However, as you can see, this requires a great deal of code. What I would like is a generic function that would allow me to do something like this:</p>
<pre><code>SELECT VehicleID
, Name
, JOIN(SELECT City FROM Locations WHERE VehicleID = Vehicles.VehicleID, ', ') AS Locations
FROM Vehicles
</code></pre>
<p>Is this possible? Or something similar?</p>
| [
{
"answer_id": 6961,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 6,
"selected": false,
"text": "<p>I don't belive there's a way to do it within one query, but you can play tricks like this with a temporary variable:</p... | 2008/08/09 | [
"https://Stackoverflow.com/questions/6899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/799/"
] | To illustrate, assume that I have two tables as follows:
```
VehicleID Name
1 Chuck
2 Larry
LocationID VehicleID City
1 1 New York
2 1 Seattle
3 1 Vancouver
4 2 Los Angeles
5 2 Houston
```
I want to write a query to return the following results:
```
VehicleID Name Locations
1 Chuck New York, Seattle, Vancouver
2 Larry Los Angeles, Houston
```
I know that this can be done using server side cursors, ie:
```
DECLARE @VehicleID int
DECLARE @VehicleName varchar(100)
DECLARE @LocationCity varchar(100)
DECLARE @Locations varchar(4000)
DECLARE @Results TABLE
(
VehicleID int
Name varchar(100)
Locations varchar(4000)
)
DECLARE VehiclesCursor CURSOR FOR
SELECT
[VehicleID]
, [Name]
FROM [Vehicles]
OPEN VehiclesCursor
FETCH NEXT FROM VehiclesCursor INTO
@VehicleID
, @VehicleName
WHILE @@FETCH_STATUS = 0
BEGIN
SET @Locations = ''
DECLARE LocationsCursor CURSOR FOR
SELECT
[City]
FROM [Locations]
WHERE [VehicleID] = @VehicleID
OPEN LocationsCursor
FETCH NEXT FROM LocationsCursor INTO
@LocationCity
WHILE @@FETCH_STATUS = 0
BEGIN
SET @Locations = @Locations + @LocationCity
FETCH NEXT FROM LocationsCursor INTO
@LocationCity
END
CLOSE LocationsCursor
DEALLOCATE LocationsCursor
INSERT INTO @Results (VehicleID, Name, Locations) SELECT @VehicleID, @Name, @Locations
END
CLOSE VehiclesCursor
DEALLOCATE VehiclesCursor
SELECT * FROM @Results
```
However, as you can see, this requires a great deal of code. What I would like is a generic function that would allow me to do something like this:
```
SELECT VehicleID
, Name
, JOIN(SELECT City FROM Locations WHERE VehicleID = Vehicles.VehicleID, ', ') AS Locations
FROM Vehicles
```
Is this possible? Or something similar? | If you're using SQL Server 2005, you could use the FOR XML PATH command.
```
SELECT [VehicleID]
, [Name]
, (STUFF((SELECT CAST(', ' + [City] AS VARCHAR(MAX))
FROM [Location]
WHERE (VehicleID = Vehicle.VehicleID)
FOR XML PATH ('')), 1, 2, '')) AS Locations
FROM [Vehicle]
```
It's a lot easier than using a cursor, and seems to work fairly well.
**Update**
For anyone still using this method with newer versions of SQL Server, there is another way of doing it which is a bit easier and more performant using the
[`STRING_AGG`](https://learn.microsoft.com/en-us/sql/t-sql/functions/string-agg-transact-sql?view=sql-server-ver15) method that has been available since SQL Server 2017.
```
SELECT [VehicleID]
,[Name]
,(SELECT STRING_AGG([City], ', ')
FROM [Location]
WHERE VehicleID = V.VehicleID) AS Locations
FROM [Vehicle] V
```
This also allows a different separator to be specified as the second parameter, providing a little more flexibility over the former method. |
6,904 | <p>I'm trying to use the CoreCon API in Visual Studio 2008 to programmatically launch device emulators. When I call <code>device.Connect()</code>, I inexplicably get a DirectoryNotFoundException. I get it if I try it in PowerShell or in C# Console Application. Here's the code I'm using:</p>
<pre><code>static void Main(string[] args)
{
DatastoreManager dm = new DatastoreManager(1033);
Collection<Platform> platforms = dm.GetPlatforms();
foreach (var p in platforms)
{
Console.WriteLine("{0} {1}", p.Name, p.Id);
}
Platform platform = platforms[3];
Console.WriteLine("Selected {0}", platform.Name);
Device device = platform.GetDevices()[0];
device.Connect();
Console.WriteLine("Device Connected");
SystemInfo info = device.GetSystemInfo();
Console.WriteLine("System OS Version:{0}.{1}.{2}",info.OSMajor, info.OSMinor, info.OSBuildNo);
Console.ReadLine();
}
</code></pre>
<p>Does anyone know why I'm getting this error? I'm running this on WinXP 32-bit, plain jane Visual Studio 2008 Pro. I imagine it's some config issue since I can't do it from a Console app or PowerShell.</p>
<p>Here's the stack trace:</p>
<pre><code>System.IO.DirectoryNotFoundException was unhandled
Message="The system cannot find the path specified.\r\n"
Source="Device Connection Manager"
StackTrace:
at Microsoft.VisualStudio.DeviceConnectivity.Interop.ConManServerClass.ConnectDevice()
at Microsoft.SmartDevice.Connectivity.Device.Connect()
at ConsoleApplication1.Program.Main(String[] args) in C:\Documents and Settings\Thomas\Local Settings\Application Data\Temporary Projects\ConsoleApplication1\Program.cs:line 23
at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
</code></pre>
| [
{
"answer_id": 6928,
"author": "Kev",
"author_id": 419,
"author_profile": "https://Stackoverflow.com/users/419",
"pm_score": 0,
"selected": false,
"text": "<p>I tried this and it works ok. Can you paste in the whole exception and stack trace?</p>\n\n<p><strong>Updated:</strong> Strangely... | 2008/08/09 | [
"https://Stackoverflow.com/questions/6904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/631/"
] | I'm trying to use the CoreCon API in Visual Studio 2008 to programmatically launch device emulators. When I call `device.Connect()`, I inexplicably get a DirectoryNotFoundException. I get it if I try it in PowerShell or in C# Console Application. Here's the code I'm using:
```
static void Main(string[] args)
{
DatastoreManager dm = new DatastoreManager(1033);
Collection<Platform> platforms = dm.GetPlatforms();
foreach (var p in platforms)
{
Console.WriteLine("{0} {1}", p.Name, p.Id);
}
Platform platform = platforms[3];
Console.WriteLine("Selected {0}", platform.Name);
Device device = platform.GetDevices()[0];
device.Connect();
Console.WriteLine("Device Connected");
SystemInfo info = device.GetSystemInfo();
Console.WriteLine("System OS Version:{0}.{1}.{2}",info.OSMajor, info.OSMinor, info.OSBuildNo);
Console.ReadLine();
}
```
Does anyone know why I'm getting this error? I'm running this on WinXP 32-bit, plain jane Visual Studio 2008 Pro. I imagine it's some config issue since I can't do it from a Console app or PowerShell.
Here's the stack trace:
```
System.IO.DirectoryNotFoundException was unhandled
Message="The system cannot find the path specified.\r\n"
Source="Device Connection Manager"
StackTrace:
at Microsoft.VisualStudio.DeviceConnectivity.Interop.ConManServerClass.ConnectDevice()
at Microsoft.SmartDevice.Connectivity.Device.Connect()
at ConsoleApplication1.Program.Main(String[] args) in C:\Documents and Settings\Thomas\Local Settings\Application Data\Temporary Projects\ConsoleApplication1\Program.cs:line 23
at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
``` | It can be found at `<systemdrive>:\Program files\Common Files\Microsoft Shared\CoreCon\1.0\Bin`.
This is the path where you can get this dll, so add this dll to your project. |
6,973 | <p>When attempting to compile my C# project, I get the following error:</p>
<pre><code>'C:\Documents and Settings\Dan\Desktop\Rowdy Pixel\Apps\CleanerMenu\CleanerMenu\obj\Debug\CSC97.tmp' is not a valid Win32 resource file.
</code></pre>
<p>Having gone through many Google searches, I have determined that this is usually caused by a 256x256 image inside an icon used by the project. I've gone through all the icons and removed the 256x256 versions, but the error persists. Any ideas on how to get rid of this?</p>
<hr>
<p>@Mike: It showed up mysteriously one night. I've searched the csproj file, but there's no mention of a CSC97.tmp (I also checked the solution file, but I had no luck there either). In case it helps, I've posted the <a href="http://pastebin.com/mcd2607b" rel="noreferrer">contents of the csproj file on pastebin</a>.</p>
<p>@Derek: No problem. Here's the compiler output.</p>
<pre><code>------ Build started: Project: Infralution.Licensing, Configuration: Debug Any CPU ------
Infralution.Licensing -> C:\Documents and Settings\Dan\Desktop\Rowdy Pixel\Apps\CleanerMenu\Infralution.Licensing\bin\Debug\Infralution.Licensing.dll
------ Build started: Project: CleanerMenu, Configuration: Debug Any CPU ------
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Csc.exe /noconfig /nowarn:1701,1702 /errorreport:prompt /warn:4 /define:DEBUG;TRACE /main:CleanerMenu.Program /reference:"C:\Documents and Settings\Dan\Desktop\Rowdy Pixel\Apps\CleanerMenu\Infralution.Licensing\bin\Debug\Infralution.Licensing.dll" /reference:..\NotificationBar.dll /reference:..\PSTaskDialog.dll /reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Data.dll /reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.dll /reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Drawing.dll /reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Windows.Forms.dll /reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Xml.dll /reference:obj\Debug\Interop.IWshRuntimeLibrary.dll /debug+ /debug:full /optimize- /out:obj\Debug\CleanerMenu.exe /resource:obj\Debug\CleanerMenu.Form1.resources /resource:obj\Debug\CleanerMenu.frmAbout.resources /resource:obj\Debug\CleanerMenu.ModalProgressWindow.resources /resource:obj\Debug\CleanerMenu.Properties.Resources.resources /resource:obj\Debug\CleanerMenu.ShortcutPropertiesViewer.resources /resource:obj\Debug\CleanerMenu.LocalizedStrings.resources /resource:obj\Debug\CleanerMenu.UpdatedLicenseForm.resources /target:winexe /win32icon:CleanerMenu.ico ErrorHandler.cs Form1.cs Form1.Designer.cs frmAbout.cs frmAbout.Designer.cs Licensing.cs ModalProgressWindow.cs ModalProgressWindow.Designer.cs Program.cs Properties\AssemblyInfo.cs Properties\Resources.Designer.cs Properties\Settings.Designer.cs Scanner.cs ShortcutPropertiesViewer.cs ShortcutPropertiesViewer.Designer.cs LocalizedStrings.Designer.cs UpdatedLicenseForm.cs UpdatedLicenseForm.Designer.cs
error CS1583: 'C:\Documents and Settings\Dan\Desktop\Rowdy Pixel\Apps\CleanerMenu\CleanerMenu\obj\Debug\CSC97.tmp' is not a valid Win32 resource file
Compile complete -- 1 errors, 0 warnings
------ Skipped Build: Project: CleanerMenu Installer, Configuration: Debug ------
Project not selected to build for this solution configuration
========== Build: 1 succeeded or up-to-date, 1 failed, 1 skipped ==========
</code></pre>
<p>I have also uploaded the icon I am using. You can <a href="http://rowdypixel.com/tmp/CleanerMenu.ico" rel="noreferrer">view it here.</a></p>
<hr>
<p>@Mike: Thanks! After removing everything but the 32x32 image, everything worked great. Now I can go back and add the other sizes one-by-one to see which one is causing me grief. :)</p>
<p>@Derek: Since I first got the error, I'd done a complete reinstall of Windows (and along with it, the SDK.) It wasn't the main reason for the reinstall, but I had a slim hope that it would fix the problem.</p>
<p>Now if only I can figure out why it previously worked with all the other sizes...</p>
| [
{
"answer_id": 6977,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 0,
"selected": false,
"text": "<p>Is this a file you created and added to the project or did it mysteriously show up?</p>\n\n<p>You can maybe check your .cs... | 2008/08/10 | [
"https://Stackoverflow.com/questions/6973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/752/"
] | When attempting to compile my C# project, I get the following error:
```
'C:\Documents and Settings\Dan\Desktop\Rowdy Pixel\Apps\CleanerMenu\CleanerMenu\obj\Debug\CSC97.tmp' is not a valid Win32 resource file.
```
Having gone through many Google searches, I have determined that this is usually caused by a 256x256 image inside an icon used by the project. I've gone through all the icons and removed the 256x256 versions, but the error persists. Any ideas on how to get rid of this?
---
@Mike: It showed up mysteriously one night. I've searched the csproj file, but there's no mention of a CSC97.tmp (I also checked the solution file, but I had no luck there either). In case it helps, I've posted the [contents of the csproj file on pastebin](http://pastebin.com/mcd2607b).
@Derek: No problem. Here's the compiler output.
```
------ Build started: Project: Infralution.Licensing, Configuration: Debug Any CPU ------
Infralution.Licensing -> C:\Documents and Settings\Dan\Desktop\Rowdy Pixel\Apps\CleanerMenu\Infralution.Licensing\bin\Debug\Infralution.Licensing.dll
------ Build started: Project: CleanerMenu, Configuration: Debug Any CPU ------
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Csc.exe /noconfig /nowarn:1701,1702 /errorreport:prompt /warn:4 /define:DEBUG;TRACE /main:CleanerMenu.Program /reference:"C:\Documents and Settings\Dan\Desktop\Rowdy Pixel\Apps\CleanerMenu\Infralution.Licensing\bin\Debug\Infralution.Licensing.dll" /reference:..\NotificationBar.dll /reference:..\PSTaskDialog.dll /reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Data.dll /reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.dll /reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Drawing.dll /reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Windows.Forms.dll /reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Xml.dll /reference:obj\Debug\Interop.IWshRuntimeLibrary.dll /debug+ /debug:full /optimize- /out:obj\Debug\CleanerMenu.exe /resource:obj\Debug\CleanerMenu.Form1.resources /resource:obj\Debug\CleanerMenu.frmAbout.resources /resource:obj\Debug\CleanerMenu.ModalProgressWindow.resources /resource:obj\Debug\CleanerMenu.Properties.Resources.resources /resource:obj\Debug\CleanerMenu.ShortcutPropertiesViewer.resources /resource:obj\Debug\CleanerMenu.LocalizedStrings.resources /resource:obj\Debug\CleanerMenu.UpdatedLicenseForm.resources /target:winexe /win32icon:CleanerMenu.ico ErrorHandler.cs Form1.cs Form1.Designer.cs frmAbout.cs frmAbout.Designer.cs Licensing.cs ModalProgressWindow.cs ModalProgressWindow.Designer.cs Program.cs Properties\AssemblyInfo.cs Properties\Resources.Designer.cs Properties\Settings.Designer.cs Scanner.cs ShortcutPropertiesViewer.cs ShortcutPropertiesViewer.Designer.cs LocalizedStrings.Designer.cs UpdatedLicenseForm.cs UpdatedLicenseForm.Designer.cs
error CS1583: 'C:\Documents and Settings\Dan\Desktop\Rowdy Pixel\Apps\CleanerMenu\CleanerMenu\obj\Debug\CSC97.tmp' is not a valid Win32 resource file
Compile complete -- 1 errors, 0 warnings
------ Skipped Build: Project: CleanerMenu Installer, Configuration: Debug ------
Project not selected to build for this solution configuration
========== Build: 1 succeeded or up-to-date, 1 failed, 1 skipped ==========
```
I have also uploaded the icon I am using. You can [view it here.](http://rowdypixel.com/tmp/CleanerMenu.ico)
---
@Mike: Thanks! After removing everything but the 32x32 image, everything worked great. Now I can go back and add the other sizes one-by-one to see which one is causing me grief. :)
@Derek: Since I first got the error, I'd done a complete reinstall of Windows (and along with it, the SDK.) It wasn't the main reason for the reinstall, but I had a slim hope that it would fix the problem.
Now if only I can figure out why it previously worked with all the other sizes... | I don't know if this will help, but from [this forum](http://forums.msdn.microsoft.com/en-US/csharplanguage/thread/4217bec6-ea65-465f-8510-757558b36094/):
>
> Add an .ico file to the application section of the properties page, and recieved the error thats been described, when I checked the Icon file with an icon editor, it turn out that the file had more than one version of the image ie (16 x 16, 24 x 24, 32 x 32, 48 x 48 vista compressed), I removed the other formats that I didnt want resaved the file (just with 32x 32) and the application now compiles without error.
>
>
>
Try opening the icon in an icon editor and see if you see other formats like described (also, try removing the icon and seeing if the project will build again, just to verify the icon is causing it). |
7,034 | <p>I have a data structure that represents a directed graph, and I want to render that dynamically on an HTML page. These graphs will usually be just a few nodes, maybe ten at the very upper end, so my guess is that performance isn't going to be a big deal. Ideally, I'd like to be able to hook it in with jQuery so that users can tweak the layout manually by dragging the nodes around.</p>
<p>Note: I'm not looking for a charting library.</p>
| [
{
"answer_id": 12844,
"author": "Sam Coles",
"author_id": 804,
"author_profile": "https://Stackoverflow.com/users/804",
"pm_score": 5,
"selected": false,
"text": "<p><a href=\"http://www.jsviz.org\" rel=\"nofollow noreferrer\">JsVIS</a> was pretty nice, but slow with larger graphs, and h... | 2008/08/10 | [
"https://Stackoverflow.com/questions/7034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/404/"
] | I have a data structure that represents a directed graph, and I want to render that dynamically on an HTML page. These graphs will usually be just a few nodes, maybe ten at the very upper end, so my guess is that performance isn't going to be a big deal. Ideally, I'd like to be able to hook it in with jQuery so that users can tweak the layout manually by dragging the nodes around.
Note: I'm not looking for a charting library. | I've just put together what you may be looking for: <http://www.graphdracula.net>
It's JavaScript with directed graph layouting, SVG and you can even drag the nodes around. Still needs some tweaking, but is totally usable. You create nodes and edges easily with JavaScript code like this:
```
var g = new Graph();
g.addEdge("strawberry", "cherry");
g.addEdge("cherry", "apple");
g.addEdge("id34", "cherry");
```
I used the previously mentioned Raphael JS library (the graffle example) plus some code for a force based graph layout algorithm I found on the net (everything open source, MIT license). If you have any remarks or need a certain feature, I may implement it, just ask!
---
You may want to have a look at other projects, too! Below are two meta-comparisons:
* [SocialCompare](http://socialcompare.com/en/comparison/javascript-graphs-and-charts-libraries) has an extensive list of libraries, and the "Node / edge graph" line will filter for graph visualization ones.
* DataVisualization.ch has evaluated many libraries, including node/graph ones. Unfortunately there's no direct link so you'll have to filter for "graph":[](http://selection.datavisualization.ch/)
Here's a list of similar projects (some have been already mentioned here):
### Pure JavaScript Libraries
* [vis.js](http://visjs.org/#gallery) supports many types of network/edge graphs, plus timelines and 2D/3D charts. Auto-layout, auto-clustering, springy physics engine, mobile-friendly, keyboard navigation, hierarchical layout, animation etc. [MIT licensed](https://github.com/almende/vis) and developed by a Dutch firm specializing in research on self-organizing networks.
* [Cytoscape.js](http://js.cytoscape.org) - interactive graph analysis and visualization with mobile support, following jQuery conventions. Funded via NIH grants and developed by by [@maxkfranz](https://stackoverflow.com/users/947225/maxkfranz) (see [his answer below](https://stackoverflow.com/a/10319429/1269037)) with help from several universities and other organizations.
* [The JavaScript InfoVis Toolkit](http://thejit.org/demos.html) - Jit, an interactive, multi-purpose graph drawing and layout framework. See for example the [Hyperbolic Tree](http://philogb.github.io/jit/static/v20/Docs/files/Visualizations/Hypertree-js.html). Built by Twitter dataviz architect [Nicolas Garcia Belmonte](http://www.sencha.com/conference/session/sencha-charting-visualization) and [bought by Sencha](http://philogb.github.io/infovis/) in 2010.
* [D3.js](http://d3js.org/) Powerful multi-purpose JS visualization library, the successor of Protovis. See the [force-directed graph](http://bl.ocks.org/mbostock/4062045) example, and other graph examples in the [gallery](https://github.com/mbostock/d3/wiki/Gallery).
* [Plotly's](https://plot.ly./) JS visualization library uses D3.js with JS, Python, R, and MATLAB bindings. See a nexworkx example in IPython [here](https://plot.ly/ipython-notebooks/network-graphs/), human interaction example [here](https://plot.ly/ipython-notebooks/bioinformatics/#In-%5B54%5D), and [JS Embed API](https://github.com/plotly/Embed-API).
* [sigma.js](http://sigmajs.org/) Lightweight but powerful library for drawing graphs
* [jsPlumb](http://jsplumbtoolkit.com/) jQuery plug-in for creating interactive connected graphs
* [Springy](http://getspringy.com/) - a force-directed graph layout algorithm
* [JS Graph It](http://js-graph-it.sourceforge.net/) - drag'n'drop boxes connected by straight lines. Minimal auto-layout of the lines.
* [RaphaelJS's Graffle](http://raphaeljs.com/graffle.html) - interactive graph example of a generic multi-purpose vector drawing library. RaphaelJS can't layout nodes automatically; you'll need another library for that.
* [JointJS Core](http://www.jointjs.com/demos) - David Durman's MPL-licensed open source diagramming library. It can be used to create either static diagrams or fully interactive diagramming tools and application builders. Works in browsers supporting SVG. Layout algorithms not-included in the core package
* [mxGraph](https://github.com/jgraph/mxgraph) Previously commercial HTML 5 diagramming library, now available under Apache v2.0. mxGraph is the base library used in [draw.io](https://www.draw.io?splash=0).
### Commercial libraries
* [GoJS](http://gojs.net/latest/index.html) Interactive graph drawing and layout library
* [yFiles for HTML](http://www.yworks.com/yfileshtml) Commercial graph drawing and layout library
* [KeyLines](http://keylines.com/) Commercial JS network visualization toolkit
* [ZoomCharts](https://zoomcharts.com) Commercial multi-purpose visualization library
* [Syncfusion JavaScript Diagram](https://www.syncfusion.com/javascript-ui-controls/diagram) Commercial diagram library for drawing and visualization.
### Abandoned libraries
* [Cytoscape Web](http://cytoscapeweb.cytoscape.org/) Embeddable JS Network viewer (no new features planned; succeeded by Cytoscape.js)
* [Canviz](http://code.google.com/p/canviz/) JS **renderer** for Graphviz graphs. [Abandoned](https://code.google.com/p/canviz/source/list) in Sep 2013.
* [arbor.js](http://arborjs.org/) Sophisticated graphing with nice physics and eye-candy. Abandoned in May 2012. Several [semi-maintained](https://github.com/samizdatco/arbor/issues/56#issuecomment-62842532) forks exist.
* [jssvggraph](http://github.com/jackrusher/jssvggraph) "The simplest possible force directed graph layout algorithm implemented as a Javascript library that uses SVG objects". Abandoned in 2012.
* [jsdot](https://code.google.com/p/jsdot/) Client side graph drawing application. [Abandoned in 2011](https://code.google.com/p/jsdot/source/list).
* [Protovis](http://vis.stanford.edu/protovis/ex/force.html) Graphical Toolkit for Visualization (JavaScript). Replaced by d3.
* [Moo Wheel](http://labs.unwieldy.net/moowheel/) Interactive JS representation for connections and relations (2008)
* [JSViz](http://www.jsviz.org/) 2007-era graph visualization script
* [dagre](https://github.com/cpettitt/dagre) Graph layout for JavaScript
### Non-Javascript Libraries
* [Graphviz](http://www.graphviz.org/) Sophisticated graph visualization language
+ Graphviz has been compiled to Javascript using Emscripten [here](https://github.com/mdaines/viz.js/) with an [online interactive demo here](http://mdaines.github.io/viz.js/)
* [Flare](http://flare.prefuse.org/) Beautiful and powerful Flash based graph drawing
* [NodeBox](http://nodebox.net/code/index.php/Graph) Python Graph Visualization
* [Processing.js](http://processingjs.org/) Javascript port of the Processing library by John Resig |
7,074 | <p>What are the differences between these two and which one should I use?</p>
<pre><code>string s = "Hello world!";
String s = "Hello world!";
</code></pre>
| [
{
"answer_id": 7077,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 14,
"selected": true,
"text": "<p><a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/string\" rel=\"noreferrer\"><code>st... | 2008/08/10 | [
"https://Stackoverflow.com/questions/7074",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/571/"
] | What are the differences between these two and which one should I use?
```
string s = "Hello world!";
String s = "Hello world!";
``` | [`string`](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/string) is an alias in C# for [`System.String`](https://learn.microsoft.com/en-us/dotnet/api/system.string).
So technically, there is no difference. It's like [`int` *vs.* `System.Int32`](https://stackoverflow.com/questions/62503/c-int-or-int32-should-i-care).
As far as guidelines, it's generally recommended to use `string` any time you're referring to an object.
e.g.
```
string place = "world";
```
Likewise, I think it's generally recommended to use `String` if you need to refer specifically to the class.
e.g.
```
string greet = String.Format("Hello {0}!", place);
```
### This is the style that Microsoft tends to use in [their examples](https://learn.microsoft.com/en-us/dotnet/api/system.string.format#examples).
It appears that the guidance in this area may have changed, as [StyleCop](https://github.com/StyleCop) now enforces the use of the C# specific aliases. |
7,084 | <p>I've worked on a number of different embedded systems. They have all used <code>typedef</code>s (or <code>#defines</code>) for types such as <code>UINT32</code>.</p>
<p>This is a good technique as it drives home the size of the type to the programmer and makes you more conscious of chances for overflow etc.</p>
<p>But on some systems you know that the compiler and processor won't change for the life of the project.</p>
<p>So what should influence your decision to create and enforce project-specific types?</p>
<p>EDIT
I think I managed to lose the gist of my question, and maybe it's really two.</p>
<p>With embedded programming you may need types of specific size for interfaces and also to cope with restricted resources such as RAM. This can't be avoided, but you can choose to use the basic types from the compiler.</p>
<p>For everything else the types have less importance.<br>
You need to be careful not to cause overflow and may need to watch out for register and stack usage. Which may lead you to <code>UINT16</code>, <code>UCHAR</code>.
Using types such as <code>UCHAR</code> can add compiler 'fluff' however. Because registers are typically larger, some compilers may add code to force the result into the type.<br>
<PRE>i++;</PRE>
can become
<PRE>ADD REG,1
AND REG, 0xFF</PRE>
which is unecessary.</p>
<p>So I think my question should have been :-</p>
<p>given the constraints of embedded software what is the best policy to set for a project which will have many people working on it - not all of whom will be of the same level of experience.</p>
| [
{
"answer_id": 7091,
"author": "Zooba",
"author_id": 891,
"author_profile": "https://Stackoverflow.com/users/891",
"pm_score": 1,
"selected": false,
"text": "<p>Consistency, convenience and readability. \"UINT32\" is much more readable and writeable than \"unsigned long long\", which is ... | 2008/08/10 | [
"https://Stackoverflow.com/questions/7084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/888/"
] | I've worked on a number of different embedded systems. They have all used `typedef`s (or `#defines`) for types such as `UINT32`.
This is a good technique as it drives home the size of the type to the programmer and makes you more conscious of chances for overflow etc.
But on some systems you know that the compiler and processor won't change for the life of the project.
So what should influence your decision to create and enforce project-specific types?
EDIT
I think I managed to lose the gist of my question, and maybe it's really two.
With embedded programming you may need types of specific size for interfaces and also to cope with restricted resources such as RAM. This can't be avoided, but you can choose to use the basic types from the compiler.
For everything else the types have less importance.
You need to be careful not to cause overflow and may need to watch out for register and stack usage. Which may lead you to `UINT16`, `UCHAR`.
Using types such as `UCHAR` can add compiler 'fluff' however. Because registers are typically larger, some compilers may add code to force the result into the type.
```
i++;
```
can become
```
ADD REG,1
AND REG, 0xFF
```
which is unecessary.
So I think my question should have been :-
given the constraints of embedded software what is the best policy to set for a project which will have many people working on it - not all of whom will be of the same level of experience. | I use type abstraction very rarely. Here are my arguments, sorted in increasing order of subjectivity:
1. Local variables are different from struct members and arrays in the sense that you want them to fit in a register. On a 32b/64b target, a local `int16_t` can make code slower compared to a local int since the compiler will have to add operations to /force/ overflow according to the semantics of `int16_t`. While C99 defines an `intfast_t` typedef, AFAIK a plain int will fit in a register just as well, and it sure is a shorter name.
2. Organizations which like these typedefs almost invariably end up with several of them (`INT32, int32_t, INT32_T`, ad infinitum). Organizations using built-in types are thus better off, in a way, having just one set of names. I wish people used the typedefs from stdint.h or windows.h or anything existing; and when a target doesn't have that .h file, how hard is it to add one?
3. The typedefs can theoretically aid portability, but I, for one, never gained a thing from them. Is there a useful system you can port from a 32b target to a 16b one? Is there a 16b system that isn't trivial to port to a 32b target? Moreover, if most vars are ints, you'll actually gain something from the 32 bits on the new target, but if they are `int16_t`, you won't. And the places which are hard to port tend to require manual inspection anyway; before you try a port, you don't know where they are. Now, if someone thinks it's so easy to port things if you have typedefs all over the place - when time comes to port, which happens to few systems, write a script converting all names in the code base. This should work according to the "no manual inspection required" logic, and it postpones the effort to the point in time where it actually gives benefit.
4. Now if portability may be a theoretical benefit of the typedefs, *readability* sure goes down the drain. Just look at stdint.h: `{int,uint}{max,fast,least}{8,16,32,64}_t`. Lots of types. A program has lots of variables; is it really that easy to understand which need to be `int_fast16_t` and which need to be `uint_least32_t`? How many times are we silently converting between them, making them entirely pointless? (I particularly like BOOL/Bool/eBool/boolean/bool/int conversions. Every program written by an orderly organization mandating typedefs is littered with that).
5. Of course in C++ we could make the type system more strict, by wrapping numbers in template class instantiations with overloaded operators and stuff. This means that you'll now get error messages of the form "class Number<int,Least,32> has no operator+ overload for argument of type class Number<unsigned long long,Fast,64>, candidates are..." I don't call this "readability", either. Your chances of implementing these wrapper classes correctly are microscopic, and most of the time you'll wait for the innumerable template instantiations to compile. |
7,095 | <p>In other words, is this Singleton implementation thread safe:</p>
<pre><code>public class Singleton
{
private static Singleton instance;
private Singleton() { }
static Singleton()
{
instance = new Singleton();
}
public static Singleton Instance
{
get { return instance; }
}
}
</code></pre>
| [
{
"answer_id": 7104,
"author": "Dominic Cooney",
"author_id": 878,
"author_profile": "https://Stackoverflow.com/users/878",
"pm_score": 2,
"selected": false,
"text": "<p>The <a href=\"http://www.ecma-international.org/publications/standards/Ecma-335.htm\" rel=\"nofollow noreferrer\">Comm... | 2008/08/10 | [
"https://Stackoverflow.com/questions/7095",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/373/"
] | In other words, is this Singleton implementation thread safe:
```
public class Singleton
{
private static Singleton instance;
private Singleton() { }
static Singleton()
{
instance = new Singleton();
}
public static Singleton Instance
{
get { return instance; }
}
}
``` | Static constructors are guaranteed to be run only once per application domain, before any instances of a class are created or any static members are accessed. <https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-constructors>
The implementation shown is thread safe for the initial construction, that is, no locking or null testing is required for constructing the Singleton object. However, this does not mean that any use of the instance will be synchronised. There are a variety of ways that this can be done; I've shown one below.
```
public class Singleton
{
private static Singleton instance;
// Added a static mutex for synchronising use of instance.
private static System.Threading.Mutex mutex;
private Singleton() { }
static Singleton()
{
instance = new Singleton();
mutex = new System.Threading.Mutex();
}
public static Singleton Acquire()
{
mutex.WaitOne();
return instance;
}
// Each call to Acquire() requires a call to Release()
public static void Release()
{
mutex.ReleaseMutex();
}
}
``` |
7,118 | <p>Currently, I don't really have a good method of debugging JavaScript in Internet Explorer and <a href="http://en.wikipedia.org/wiki/Safari_%28web_browser%29" rel="noreferrer">Safari</a>. In Firefox, you can use <a href="http://en.wikipedia.org/wiki/Firebug" rel="noreferrer">Firebug's</a> <a href="http://getfirebug.com/logging.html" rel="noreferrer">logging feature</a> and <a href="http://getfirebug.com/commandline.html" rel="noreferrer">command Line functions</a>. However, this doesn't help me when I move to other browsers.</p>
| [
{
"answer_id": 7126,
"author": "Yaakov Ellis",
"author_id": 51,
"author_profile": "https://Stackoverflow.com/users/51",
"pm_score": 2,
"selected": false,
"text": "<p>A post on the IE Blog, <em><a href=\"http://blogs.msdn.com/ie/archive/2004/10/26/247912.aspx\" rel=\"nofollow noreferrer\"... | 2008/08/10 | [
"https://Stackoverflow.com/questions/7118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/889/"
] | Currently, I don't really have a good method of debugging JavaScript in Internet Explorer and [Safari](http://en.wikipedia.org/wiki/Safari_%28web_browser%29). In Firefox, you can use [Firebug's](http://en.wikipedia.org/wiki/Firebug) [logging feature](http://getfirebug.com/logging.html) and [command Line functions](http://getfirebug.com/commandline.html). However, this doesn't help me when I move to other browsers. | For Safari you need to enable the "Develop" menu via Preferences (in Safari 3.1; see [the entry in Apple's Safari development FAQ](http://developer.apple.com/internet/safari/faq.html#anchor14)) or via
```
$ defaults write com.apple.Safari IncludeDebugMenu 1
```
at the terminal in Mac OS X. Then from the Develop menu choose Show Web Inspector and click on the Console link. Your script can write to the console using window.console.log.
For Internet Explorer, Visual Studio is really the best script debugger but the Microsoft Script Debugger is okay if you don't have Visual Studio. [This post on the IE team blog](http://blogs.msdn.com/ie/archive/2004/10/26/247912.aspx "Scripting Debugging in Internet Explorer") walks you through installing it and connecting to Internet Explorer.
Internet Explorer 8 [looks](http://www.west-wind.com/weblog/posts/271352.aspx) like it will have a very fancy script debugger, so if you're feeling really adventurous you could install the Internet Explorer 8 beta and give that a whirl. |
7,212 | <p>What I'd like to do is something like the following:</p>
<pre><code>FooClass.prototype.method = function():String
{
return "Something";
}
var foo:FooClass = new FooClass();
foo.method();
</code></pre>
<p>Which is to say, I'd like to extend a generated class with a single method, not via inheritance but via the prototype.</p>
<p>The class is generated from a WSDL, it's not a dynamic class, and I don't want to touch the generated code because it will be overwritten anyway.</p>
<p>Long story short, I'd like to have the moral equivalent of C# 3:s Extension Methods for AS3.</p>
<p>Edit: I accepted aib's answer, because it fits what I was asking best -- although upon further reflection it doesn't really solve my problem, but that's my fault for asking the wrong question. :) Also, upmods for the good suggestions.</p>
| [
{
"answer_id": 8886,
"author": "aib",
"author_id": 1088,
"author_profile": "https://Stackoverflow.com/users/1088",
"pm_score": 3,
"selected": true,
"text": "<p>Yes, such a thing is possible.</p>\n\n<p>In fact, your example is very close to the solution.</p>\n\n<p>Try</p>\n\n<pre><code>fo... | 2008/08/10 | [
"https://Stackoverflow.com/questions/7212",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/266/"
] | What I'd like to do is something like the following:
```
FooClass.prototype.method = function():String
{
return "Something";
}
var foo:FooClass = new FooClass();
foo.method();
```
Which is to say, I'd like to extend a generated class with a single method, not via inheritance but via the prototype.
The class is generated from a WSDL, it's not a dynamic class, and I don't want to touch the generated code because it will be overwritten anyway.
Long story short, I'd like to have the moral equivalent of C# 3:s Extension Methods for AS3.
Edit: I accepted aib's answer, because it fits what I was asking best -- although upon further reflection it doesn't really solve my problem, but that's my fault for asking the wrong question. :) Also, upmods for the good suggestions. | Yes, such a thing is possible.
In fact, your example is very close to the solution.
Try
```
foo["method"]();
```
instead of
```
foo.method();
``` |
7,244 | <p>What I want to do is something like this: I have enums with combined flagged values.</p>
<pre><code>public static class EnumExtension
{
public static bool IsSet<T>( this T input, T matchTo )
where T:enum //the constraint I want that doesn't exist in C#3
{
return (input & matchTo) != 0;
}
}
</code></pre>
<p>So then I could do:</p>
<pre><code>MyEnum tester = MyEnum.FlagA | MyEnum.FlagB
if( tester.IsSet( MyEnum.FlagA ) )
//act on flag a
</code></pre>
<p>Unfortunately, C#'s generic where constraints have no enum restriction, only class and struct. C# doesn't see enums as structs (even though they are value types) so I can't add extension types like this.</p>
<p>Does anyone know a workaround?</p>
| [
{
"answer_id": 7385,
"author": "Ronnie",
"author_id": 193,
"author_profile": "https://Stackoverflow.com/users/193",
"pm_score": 4,
"selected": false,
"text": "<p>Darren, that would work if the types were specific enumerations - for general enumerations to work you have to cast them to in... | 2008/08/10 | [
"https://Stackoverflow.com/questions/7244",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/905/"
] | What I want to do is something like this: I have enums with combined flagged values.
```
public static class EnumExtension
{
public static bool IsSet<T>( this T input, T matchTo )
where T:enum //the constraint I want that doesn't exist in C#3
{
return (input & matchTo) != 0;
}
}
```
So then I could do:
```
MyEnum tester = MyEnum.FlagA | MyEnum.FlagB
if( tester.IsSet( MyEnum.FlagA ) )
//act on flag a
```
Unfortunately, C#'s generic where constraints have no enum restriction, only class and struct. C# doesn't see enums as structs (even though they are value types) so I can't add extension types like this.
Does anyone know a workaround? | **EDIT: This is now live in version 0.0.0.2 of UnconstrainedMelody.**
(As requested on my [blog post about enum constraints](http://codeblog.jonskeet.uk/2009/09/10/generic-constraints-for-enums-and-delegates/). I've included the basic facts below for the sake of a standalone answer.)
The best solution is to wait for me to include it in [UnconstrainedMelody](https://github.com/jskeet/unconstrained-melody)1. This is a library which takes C# code with "fake" constraints such as
```
where T : struct, IEnumConstraint
```
and turns it into
```
where T : struct, System.Enum
```
via a postbuild step.
It shouldn't be too hard to write `IsSet`... although catering for both `Int64`-based and `UInt64`-based flags could be the tricky part. (I smell some helper methods coming on, basically allowing me to treat any flags enum as if it had a base type of `UInt64`.)
What would you want the behaviour to be if you called
```
tester.IsSet(MyFlags.A | MyFlags.C)
```
? Should it check that *all* the specified flags are set? That would be my expectation.
I'll try to do this on the way home tonight... I'm hoping to have a quick blitz on useful enum methods to get the library up to a usable standard quickly, then relax a bit.
EDIT: I'm not sure about `IsSet` as a name, by the way. Options:
* Includes
* Contains
* HasFlag (or HasFlags)
* IsSet (it's certainly an option)
Thoughts welcome. I'm sure it'll be a while before anything's set in stone anyway...
---
1 or submit it as a patch, of course... |
7,245 | <p>What's the most efficient algorithm to find the rectangle with the largest area which will fit in the empty space?</p>
<p>Let's say the screen looks like this ('#' represents filled area):</p>
<pre><code>....................
..............######
##..................
.................###
.................###
#####...............
#####...............
#####...............
</code></pre>
<p>A probable solution is:</p>
<pre><code>....................
..............######
##...++++++++++++...
.....++++++++++++###
.....++++++++++++###
#####++++++++++++...
#####++++++++++++...
#####++++++++++++...
</code></pre>
<p>Normally I'd enjoy figuring out a solution. Although this time I'd like to avoid wasting time fumbling around on my own since this has a practical use for a project I'm working on. Is there a well-known solution?</p>
<p><strong>Shog9</strong> wrote:</p>
<blockquote>
<p>Is your input an array (as implied by the other responses), or a list of occlusions in the form of arbitrarily sized, positioned rectangles (as might be the case in a windowing system when dealing with window positions)?</p>
</blockquote>
<p>Yes, I have a structure which keeps track of a set of windows placed on the screen. I also have a grid which keeps track of all the areas between each edge, whether they are empty or filled, and the pixel position of their left or top edge. I think there is some modified form which would take advantage of this property. Do you know of any?</p>
| [
{
"answer_id": 7250,
"author": "Mark Renouf",
"author_id": 758,
"author_profile": "https://Stackoverflow.com/users/758",
"pm_score": 2,
"selected": false,
"text": "<p>@lassevk</p>\n\n<pre><code> // 4. Outer double-for-loop to consider all possible positions \n // for topleft cor... | 2008/08/10 | [
"https://Stackoverflow.com/questions/7245",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/758/"
] | What's the most efficient algorithm to find the rectangle with the largest area which will fit in the empty space?
Let's say the screen looks like this ('#' represents filled area):
```
....................
..............######
##..................
.................###
.................###
#####...............
#####...............
#####...............
```
A probable solution is:
```
....................
..............######
##...++++++++++++...
.....++++++++++++###
.....++++++++++++###
#####++++++++++++...
#####++++++++++++...
#####++++++++++++...
```
Normally I'd enjoy figuring out a solution. Although this time I'd like to avoid wasting time fumbling around on my own since this has a practical use for a project I'm working on. Is there a well-known solution?
**Shog9** wrote:
>
> Is your input an array (as implied by the other responses), or a list of occlusions in the form of arbitrarily sized, positioned rectangles (as might be the case in a windowing system when dealing with window positions)?
>
>
>
Yes, I have a structure which keeps track of a set of windows placed on the screen. I also have a grid which keeps track of all the areas between each edge, whether they are empty or filled, and the pixel position of their left or top edge. I think there is some modified form which would take advantage of this property. Do you know of any? | @lassevk
I found the referenced article, from DDJ: [The Maximal Rectangle Problem](http://www.ddj.com/184410529) |
7,260 | <p>How do I setup Public-Key Authentication for SSH?</p>
| [
{
"answer_id": 7481,
"author": "roo",
"author_id": 716,
"author_profile": "https://Stackoverflow.com/users/716",
"pm_score": 3,
"selected": false,
"text": "<p>For windows <a href=\"http://the.earth.li/~sgtatham/putty/0.53b/htmldoc/Chapter8.html\" rel=\"noreferrer\">this</a> is a good int... | 2008/08/10 | [
"https://Stackoverflow.com/questions/7260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/889/"
] | How do I setup Public-Key Authentication for SSH? | If you have SSH installed, you should be able to run..
```
ssh-keygen
```
Then go through the steps, you'll have two files, `id_rsa` and `id_rsa.pub` (the first is your private key, the second is your public key - the one you copy to remote machines)
Then, connect to the remote machine you want to login to, to the file `~/.ssh/authorized_keys` add the contents of your that `id_rsa.pub` file.
Oh, and `chmod 600` all the `id_rsa*` files (both locally and remote), so no other users can read them:
```
chmod 600 ~/.ssh/id_rsa*
```
Similarly, ensure the remote `~/.ssh/authorized_keys` file is `chmod 600` also:
```
chmod 600 ~/.ssh/authorized_keys
```
Then, when you do `ssh remote.machine`, it should ask you for the key's password, not the remote machine.
---
To make it nicer to use, you can use `ssh-agent` to hold the decrypted keys in memory - this means you don't have to type your keypair's password every single time. To launch the agent, you run (including the back-tick quotes, which eval the output of the `ssh-agent` command)
```
`ssh-agent`
```
On some distros, ssh-agent is started automatically. If you run `echo $SSH_AUTH_SOCK` and it shows a path (probably in /tmp/) it's already setup, so you can skip the previous command.
Then to add your key, you do
```
ssh-add ~/.ssh/id_rsa
```
and enter your passphrase. It's stored until you remove it (using the `ssh-add -D` command, which removes all keys from the agent) |
7,277 | <p>I'm generating some XML documents and when it comes to the address part I have fragments that look like this:</p>
<pre><code><Address>15 Sample St
Example Bay
Some Country</Address>
</code></pre>
<p>The XSLT that I have for converting this to XHTML has some funky recursive template to convert newline characters within strings to <br/> tags.</p>
<p>This is all working fine; but is it considered "bad practice" to rely on linebreaks within XML documents? If so, is it recommended that I do this instead?</p>
<pre><code><Address><Line>15 Sample St</Line>
<Line>Example Bay</Line>
<Line>Some Country</Line></Address>
</code></pre>
<p>Seems like it'd be really awkward to wrap every place where my text may be multiple lines with tags like that..</p>
| [
{
"answer_id": 7280,
"author": "Mark Renouf",
"author_id": 758,
"author_profile": "https://Stackoverflow.com/users/758",
"pm_score": -1,
"selected": false,
"text": "<p>Yes, I think using a <a href=\"http://en.wikipedia.org/wiki/CDATA\" rel=\"nofollow noreferrer\">CDATA</a> block would pr... | 2008/08/10 | [
"https://Stackoverflow.com/questions/7277",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/755/"
] | I'm generating some XML documents and when it comes to the address part I have fragments that look like this:
```
<Address>15 Sample St
Example Bay
Some Country</Address>
```
The XSLT that I have for converting this to XHTML has some funky recursive template to convert newline characters within strings to <br/> tags.
This is all working fine; but is it considered "bad practice" to rely on linebreaks within XML documents? If so, is it recommended that I do this instead?
```
<Address><Line>15 Sample St</Line>
<Line>Example Bay</Line>
<Line>Some Country</Line></Address>
```
Seems like it'd be really awkward to wrap every place where my text may be multiple lines with tags like that.. | It's generally considered bad practice to rely on linebreaks, since it's a fragile way to differentiate data. While most XML processors will preserve any whitespace you put in your XML, it's not guaranteed.
The real problem is that most applications that output your XML into a readable format consider all whitespace in an XML interchangable, and might collapse those linebreaks into a single space. That's why your XSLT has to jump through such hoops to render the data properly. Using a "br" tag would vastly simplify the transform.
Another potential problem is that if you open up your XML document in an XML editor and pretty-print it, you're likely to lose those line breaks.
If you do keep using linebreaks, make sure add an xml:space="preserve" attribute to "address." (You can do this in your DTD, if you're using one.)
**Some suggested reading**
* An [article from XML.com](http://www.xml.com/pub/a/2001/11/07/whitespace.html) says the following:
>
> XML applications often seem to take a
> cavalier attitude toward whitespace
> because the rules about the places in
> an XML document where whitespace
> doesn't matter sometimes give these
> applications free rein to add or
> remove whitespace in certain places.
>
>
>
* [A collection of XSL-list posts regarding whitespace](http://www.dpawson.co.uk/xsl/sect2/N8321.html). |
7,287 | <p>Lately I had to change some code on older systems where not all of the code has unit tests.<br>
Before making the changes I want to write tests, but each class created a lot of dependencies and other anti-patterns which made testing quite hard.<br>
Obviously, I wanted to refactor the code to make it easier to test, write the tests and then change it.<br>
Is this the way you'd do it? Or would you spend a lot of time writing the hard-to-write tests that would be mostly removed after the refactoring will be completed?</p>
| [
{
"answer_id": 7296,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 4,
"selected": true,
"text": "<p>First of all, <a href=\"http://devver.net/blog/2008/07/tips-for-unit-testing/\" rel=\"noreferrer\">here's a great article w... | 2008/08/10 | [
"https://Stackoverflow.com/questions/7287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/573/"
] | Lately I had to change some code on older systems where not all of the code has unit tests.
Before making the changes I want to write tests, but each class created a lot of dependencies and other anti-patterns which made testing quite hard.
Obviously, I wanted to refactor the code to make it easier to test, write the tests and then change it.
Is this the way you'd do it? Or would you spend a lot of time writing the hard-to-write tests that would be mostly removed after the refactoring will be completed? | First of all, [here's a great article with tips on unit testing](http://devver.net/blog/2008/07/tips-for-unit-testing/). Secondly, I found a great way to avoid making tons of changes in old code is to just refactor it a little until you can test it. One easy way to do this is to make private members protected, and then override the protected field.
For example, let's say you have a class that loads some stuff from the database during the constructor. In this case, you can't just override a protected method, but you can extract the DB logic to a protected field and then override it in the test.
```
public class MyClass {
public MyClass() {
// undesirable DB logic
}
}
```
becomes
```
public class MyClass {
public MyClass() {
loadFromDB();
}
protected void loadFromDB() {
// undesirable DB logic
}
}
```
and then your test looks something like this:
```
public class MyClassTest {
public void testSomething() {
MyClass myClass = new MyClassWrapper();
// test it
}
private static class MyClassWrapper extends MyClass {
@Override
protected void loadFromDB() {
// some mock logic
}
}
}
```
This is somewhat of a bad example, because you could use DBUnit in this case, but I actually did this in a similar case recently because I wanted to test some functionality totally unrelated to the data being loaded, so it was very effective. I've also found such exposing of members to be useful in other similar cases where I need to get rid of some dependency that has been in a class for a long time.
I would recommend against this solution if you are writing a framework though, unless you really don't mind exposing the members to users of your framework.
It's a bit of a hack, but I've found it quite useful. |
7,364 | <p>Does anyone know of a good method for editing PDFs in PHP? Preferably open-source/zero-license cost methods. :)</p>
<p>I am thinking along the lines of opening a PDF file, replacing text in the PDF and then writing out the modified version of the PDF?</p>
<p>On the front-end</p>
| [
{
"answer_id": 7377,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": -1,
"selected": false,
"text": "<p>We use <a href=\"http://www.pdflib.com/pdflib-gmbh/\" rel=\"nofollow noreferrer\">pdflib</a> to create PDF files from ... | 2008/08/10 | [
"https://Stackoverflow.com/questions/7364",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/277/"
] | Does anyone know of a good method for editing PDFs in PHP? Preferably open-source/zero-license cost methods. :)
I am thinking along the lines of opening a PDF file, replacing text in the PDF and then writing out the modified version of the PDF?
On the front-end | If you are taking a 'fill in the blank' approach, you can precisely position text anywhere you want on the page. So it's relatively easy (if not a bit tedious) to add the missing text to the document. For example with Zend Framework:
```
<?php
require_once 'Zend/Pdf.php';
$pdf = Zend_Pdf::load('blank.pdf');
$page = $pdf->pages[0];
$font = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA);
$page->setFont($font, 12);
$page->drawText('Hello world!', 72, 720);
$pdf->save('zend.pdf');
```
If you're trying to replace inline content, such as a "[placeholder string]," it gets much more complicated. While it's technically possible to do, you're likely to mess up the layout of the page.
A PDF document is comprised of a set of primitive drawing operations: line here, image here, text chunk there, etc. It does not contain any information about the layout intent of those primitives. |
7,398 | <p>I haven't seen any questions relating to GNU autoconf/automake builds, but I'm hoping at least some of you out there are familiar with it. Here goes:</p>
<p>I have a project (I'll call it myproject) that includes another project (vendor). The vendor project is a standalone project maintained by someone else. Including a project like this is fairly <a href="http://www.gnu.org/software/autoconf/manual/autoconf.html#Subdirectories" rel="nofollow noreferrer">straightforward</a>, but in this case there is a tiny snag: each project generates its own <code>config.h</code> file, each of which defines standard macros such as PACKAGE, VERSION, etc. This means that, during the build, when vendor is being built, I get lots of errors like this:</p>
<pre><code>... warning: "VERSION" redefined
... warning: this is the location of the previous definition
... warning: "PACKAGE" redefined
... warning: this is the location of the previous definition
</code></pre>
<p>These are just warnings, for the time being at least, but I would like to get rid of them. The only relevant information I've been able to turn up with a Google search is <a href="http://sourceware.org/ml/automake/2004-03/msg00130.html" rel="nofollow noreferrer">this</a> thread on the automake mailing list, which isn't a whole lot of help. Does anybody else have any better ideas?</p>
| [
{
"answer_id": 9214,
"author": "David Joyner",
"author_id": 1146,
"author_profile": "https://Stackoverflow.com/users/1146",
"pm_score": 2,
"selected": false,
"text": "<p>It's definitely a hack, but I post-process the autogen'd <code>config.h</code> file:</p>\n\n<pre><code>sed -e 's/.*PAC... | 2008/08/10 | [
"https://Stackoverflow.com/questions/7398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/737/"
] | I haven't seen any questions relating to GNU autoconf/automake builds, but I'm hoping at least some of you out there are familiar with it. Here goes:
I have a project (I'll call it myproject) that includes another project (vendor). The vendor project is a standalone project maintained by someone else. Including a project like this is fairly [straightforward](http://www.gnu.org/software/autoconf/manual/autoconf.html#Subdirectories), but in this case there is a tiny snag: each project generates its own `config.h` file, each of which defines standard macros such as PACKAGE, VERSION, etc. This means that, during the build, when vendor is being built, I get lots of errors like this:
```
... warning: "VERSION" redefined
... warning: this is the location of the previous definition
... warning: "PACKAGE" redefined
... warning: this is the location of the previous definition
```
These are just warnings, for the time being at least, but I would like to get rid of them. The only relevant information I've been able to turn up with a Google search is [this](http://sourceware.org/ml/automake/2004-03/msg00130.html) thread on the automake mailing list, which isn't a whole lot of help. Does anybody else have any better ideas? | Some notes:
* you didn't mention how `config.h` was included - with quotes or angle brackets. See [this other question](https://stackoverflow.com/questions/21593/what-is-the-difference-between-include-filename-and-include-filename) for more information on the difference. In short, `config.h` is typically included with quotes, not angle brackets, and this should make the preprocessor prefer the `config.h` from the project's own directory (which is usually what you want)
* You say that a subproject should be including the enclosing project's `config.h` Normally this is not at all what you want. The subproject is standalone, and its PACKAGE and VERSION should be the one of that subproject, not yours. If you include libxml in your xmlreader project for example, you would still want the libxml code to be compiled with PACKAGE libxml and VERSION (whatever the libxml version is).
* It is usually a big mistake to have `config.h` be included from public headers. `config.h` is always private to your project or the subproject, and should only be included from .c files. So, if your vendor's documentation says to include their "vendor.h" and that public header includes `config.h` somehow, then that is a no-no. Similarly, if your project is a library, don't include `config.h` anywhere from your publically installed headers. |
7,470 | <p>After a couple of hours fighting with the <a href="http://gallery.menalto.com/" rel="nofollow noreferrer">Gallery2</a> <a href="http://codex.gallery2.org/Gallery2:Modules:rss" rel="nofollow noreferrer">RSS module</a> and getting only the message, "no feeds have yet been defined", I gave up. Based on <a href="http://www.google.com/search?q=%22no+feeds+have+yet+been+defined%22" rel="nofollow noreferrer">a Google search for "no feeds have yet been defined"</a>, this is a pretty common problem. Do you have any tips and/or tricks for getting the Gallery2 RSS module to work? Or any tips for a relatively-PHP-ignorant developer trying to debug problems with this PHP application?</p>
| [
{
"answer_id": 7471,
"author": "ESV",
"author_id": 150,
"author_profile": "https://Stackoverflow.com/users/150",
"pm_score": 1,
"selected": false,
"text": "<p>My eventual (and hopefully temporary) solution to this problem was a Python CGI script. My script follows for anyone who might f... | 2008/08/11 | [
"https://Stackoverflow.com/questions/7470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/150/"
] | After a couple of hours fighting with the [Gallery2](http://gallery.menalto.com/) [RSS module](http://codex.gallery2.org/Gallery2:Modules:rss) and getting only the message, "no feeds have yet been defined", I gave up. Based on [a Google search for "no feeds have yet been defined"](http://www.google.com/search?q=%22no+feeds+have+yet+been+defined%22), this is a pretty common problem. Do you have any tips and/or tricks for getting the Gallery2 RSS module to work? Or any tips for a relatively-PHP-ignorant developer trying to debug problems with this PHP application? | My eventual (and hopefully temporary) solution to this problem was a Python CGI script. My script follows for anyone who might find it useful (despite the fact that this is a total hack).
```
#!/usr/bin/python
"""A CGI script to produce an RSS feed of top-level Gallery2 albums."""
#import cgi
#import cgitb; cgitb.enable()
from time import gmtime, strftime
import MySQLdb
ALBUM_QUERY = '''
select g_id, g_title, g_originationTimestamp
from g_Item
where g_canContainChildren = 1
order by g_originationTimestamp desc
limit 0, 20
'''
RSS_TEMPLATE = '''Content-Type: text/xml
<?xml version="1.0"?>
<rss version="2.0">
<channel>
<title>TITLE</title>
<link>http://example.com/gallery2/main.php</link>
<description>DESCRIPTION</description>
<ttl>1440</ttl>
%s
</channel>
</rss>
'''
ITEM_TEMPLATE = '''
<item>
<title>%s</title>
<link>http://example.com/gallery2/main.php?g2_itemId=%s</link>
<description>%s</description>
<pubDate>%s</pubDate>
</item>
'''
def to_item(row):
item_id = row[0]
title = row[1]
date = strftime("%a, %d %b %Y %H:%M:%S GMT", gmtime(row[2]))
return ITEM_TEMPLATE % (title, item_id, title, date)
conn = MySQLdb.connect(host = "HOST",
user = "USER",
passwd = "PASSWORD",
db = "DATABASE")
curs = conn.cursor()
curs.execute(ALBUM_QUERY)
print RSS_TEMPLATE % ''.join([ to_item(row) for row in curs.fetchall() ])
curs.close()
``` |
7,477 | <p>I'm currently working on an internal sales application for the company I work for, and I've got a form that allows the user to change the delivery address.</p>
<p>Now I think it would look much nicer, if the textarea I'm using for the main address details would just take up the area of the text in it, and automatically resize if the text was changed.</p>
<p>Here's a screenshot of it currently.</p>
<p><img src="https://i.stack.imgur.com/XK48E.png" alt="ISO Address"></p>
<p>Any ideas?</p>
<hr>
<p>@Chris</p>
<p>A good point, but there are reasons I want it to resize. I want the area it takes up to be the area of the information contained in it. As you can see in the screen shot, if I have a fixed textarea, it takes up a fair wack of vertical space.</p>
<p>I can reduce the font, but I need address to be large and readable. Now I can reduce the size of the text area, but then I have problems with people who have an address line that takes 3 or 4 (one takes 5) lines. Needing to have the user use a scrollbar is a major no-no.</p>
<p>I guess I should be a bit more specific. I'm after vertical resizing, and the width doesn't matter as much. The only problem that happens with that, is the ISO number (the large "1") gets pushed under the address when the window width is too small (as you can see on the screenshot).</p>
<p>It's not about having a gimick; it's about having a text field the user can edit that won't take up unnecessary space, but will show all the text in it.</p>
<p>Though if someone comes up with another way to approach the problem I'm open to that too.</p>
<hr>
<p>I've modified the code a little because it was acting a little odd. I changed it to activate on keyup, because it wouldn't take into consideration the character that was just typed.</p>
<pre><code>resizeIt = function() {
var str = $('iso_address').value;
var cols = $('iso_address').cols;
var linecount = 0;
$A(str.split("\n")).each(function(l) {
linecount += 1 + Math.floor(l.length / cols); // Take into account long lines
})
$('iso_address').rows = linecount;
};
</code></pre>
| [
{
"answer_id": 7523,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 7,
"selected": true,
"text": "<p>Facebook does it, when you write on people's walls, but only resizes vertically.</p>\n\n<p>Horizontal resize strikes me ... | 2008/08/11 | [
"https://Stackoverflow.com/questions/7477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/841/"
] | I'm currently working on an internal sales application for the company I work for, and I've got a form that allows the user to change the delivery address.
Now I think it would look much nicer, if the textarea I'm using for the main address details would just take up the area of the text in it, and automatically resize if the text was changed.
Here's a screenshot of it currently.

Any ideas?
---
@Chris
A good point, but there are reasons I want it to resize. I want the area it takes up to be the area of the information contained in it. As you can see in the screen shot, if I have a fixed textarea, it takes up a fair wack of vertical space.
I can reduce the font, but I need address to be large and readable. Now I can reduce the size of the text area, but then I have problems with people who have an address line that takes 3 or 4 (one takes 5) lines. Needing to have the user use a scrollbar is a major no-no.
I guess I should be a bit more specific. I'm after vertical resizing, and the width doesn't matter as much. The only problem that happens with that, is the ISO number (the large "1") gets pushed under the address when the window width is too small (as you can see on the screenshot).
It's not about having a gimick; it's about having a text field the user can edit that won't take up unnecessary space, but will show all the text in it.
Though if someone comes up with another way to approach the problem I'm open to that too.
---
I've modified the code a little because it was acting a little odd. I changed it to activate on keyup, because it wouldn't take into consideration the character that was just typed.
```
resizeIt = function() {
var str = $('iso_address').value;
var cols = $('iso_address').cols;
var linecount = 0;
$A(str.split("\n")).each(function(l) {
linecount += 1 + Math.floor(l.length / cols); // Take into account long lines
})
$('iso_address').rows = linecount;
};
``` | Facebook does it, when you write on people's walls, but only resizes vertically.
Horizontal resize strikes me as being a mess, due to word-wrap, long lines, and so on, but vertical resize seems to be pretty safe and nice.
None of the Facebook-using-newbies I know have ever mentioned anything about it or been confused. I'd use this as anecdotal evidence to say 'go ahead, implement it'.
Some JavaScript code to do it, using [Prototype](http://en.wikipedia.org/wiki/Prototype_JavaScript_Framework) (because that's what I'm familiar with):
```
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="http://www.google.com/jsapi"></script>
<script language="javascript">
google.load('prototype', '1.6.0.2');
</script>
</head>
<body>
<textarea id="text-area" rows="1" cols="50"></textarea>
<script type="text/javascript" language="javascript">
resizeIt = function() {
var str = $('text-area').value;
var cols = $('text-area').cols;
var linecount = 0;
$A(str.split("\n")).each( function(l) {
linecount += Math.ceil( l.length / cols ); // Take into account long lines
})
$('text-area').rows = linecount + 1;
};
// You could attach to keyUp, etc. if keydown doesn't work
Event.observe('text-area', 'keydown', resizeIt );
resizeIt(); //Initial on load
</script>
</body>
</html>
```
PS: Obviously this JavaScript code is very naive and not well tested, and you probably don't want to use it on textboxes with novels in them, but you get the general idea. |
7,489 | <p>I've made many different seperate parts of a GUI system for the Nintendo DS, like buttons and textboxes and select boxes, but I need a way of containing these classes in one Gui class, so that I can draw everything to the screen all at once, and check all the buttons at once to check if any are being pressed. My question is what is the best way organize all the classes (such as buttons and textboxes) into one GUI class?</p>
<p>Here's one way I thought of but it doesn't seem right:</p>
<p><strong>Edit:</strong> I'm using C++.</p>
<pre><code>class Gui {
public:
void update_all();
void draw_all() const;
int add_button(Button *button); // Returns button id
void remove_button(int button_id);
private:
Button *buttons[10];
int num_buttons;
}
</code></pre>
<p>This code has a few problems, but I just wanted to give you an idea of what I want.</p>
| [
{
"answer_id": 7506,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>One useful strategy to keep in mind might be the <a href=\"http://en.wikipedia.org/wiki/Composite_pattern\" rel=\"nofollow no... | 2008/08/11 | [
"https://Stackoverflow.com/questions/7489",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/813/"
] | I've made many different seperate parts of a GUI system for the Nintendo DS, like buttons and textboxes and select boxes, but I need a way of containing these classes in one Gui class, so that I can draw everything to the screen all at once, and check all the buttons at once to check if any are being pressed. My question is what is the best way organize all the classes (such as buttons and textboxes) into one GUI class?
Here's one way I thought of but it doesn't seem right:
**Edit:** I'm using C++.
```
class Gui {
public:
void update_all();
void draw_all() const;
int add_button(Button *button); // Returns button id
void remove_button(int button_id);
private:
Button *buttons[10];
int num_buttons;
}
```
This code has a few problems, but I just wanted to give you an idea of what I want. | This question is very similar to one I was going to post, only mine is for Sony PSP programming.
I've been toying with something for a while, I've consulted some books and [VTMs](http://www.3dbuzz.com/xcart/product.php?productid=30&cat=12&page=1), and so far this is a rough idea of a simple ui systems.
```
class uiElement()
{
...
virtual void Update() = 0;
virtual void Draw() = 0;
...
}
class uiButton() public : uiElement
{
...
virtual void Update();
virtual void Draw();
...
}
class uiTextbox() public : uiElement
{
...
virtual void Update();
virtual void Draw();
...
}
... // Other ui Elements
class uiWindow()
{
...
void Update();
void Draw();
void AddElement(uiElement *Element);
void RemoveElement(uiElement *Element);
std::list <uiElement*> Elements;
...
}
void uiWindow::Update()
{
...
for (list <uiElement*>::iterator it = Elements.begin(); it != Elements.end(); it++ )
it->Update();
...
}
void uiWindow::Draw()
{
...
for (list <uiElement*>::iterator it = Elements.begin(); it != Elements.end(); it++ )
it->Draw();
...
}
```
The princple is to create a window and attact ui Elements to it, and call the draw and update methods from the respective main functions.
I don't have anything working yet, as I have issues with drawing code. With different APIs on the PC and PSP, I'm looking at some wrapper code for OpenGL and psp gu.
Hope this helps.
thing2k |
7,503 | <p>I know almost nothing about linq.</p>
<p>I'm doing this:</p>
<pre><code>var apps = from app in Process.GetProcesses()
where app.ProcessName.Contains( "MyAppName" ) && app.MainWindowHandle != IntPtr.Zero
select app;
</code></pre>
<p>Which gets me all the running processes which match that criteria.</p>
<p>But I don't know how to get the first one. The examples I can find on the net seem to imply I have to do this</p>
<pre><code>var matchedApp = (from app in Process.GetProcesses()
where app.ProcessName.Contains( "MyAppName" ) && app.MainWindowHandle != IntPtr.Zero
select app).First();
</code></pre>
<p>which strikes me as somewhat ugly, and also throws an exception if there are no matching processes. Is there a better way?</p>
<p><strong>UPDATE</strong></p>
<p>I'm actually trying to find the first matching item, and call <code>SetForegroundWindow</code> on it</p>
<p>I've come up with this solution, which also strikes me as ugly and awful, but better than above. Any ideas?</p>
<pre><code>var unused = from app in Process.GetProcesses()
where app.ProcessName.Contains( "MyAppName" ) && app.MainWindowHandle != IntPtr.Zero
select SetForegroundWindow( app.MainWindowHandle ); // side-effects in linq-query is technically bad I guess
</code></pre>
| [
{
"answer_id": 7509,
"author": "FryHard",
"author_id": 231,
"author_profile": "https://Stackoverflow.com/users/231",
"pm_score": 0,
"selected": false,
"text": "<p>Assuming that in your first example apps is an IEnumerable you could make use of the .Count and .FirstOrDefault properties to... | 2008/08/11 | [
"https://Stackoverflow.com/questions/7503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/234/"
] | I know almost nothing about linq.
I'm doing this:
```
var apps = from app in Process.GetProcesses()
where app.ProcessName.Contains( "MyAppName" ) && app.MainWindowHandle != IntPtr.Zero
select app;
```
Which gets me all the running processes which match that criteria.
But I don't know how to get the first one. The examples I can find on the net seem to imply I have to do this
```
var matchedApp = (from app in Process.GetProcesses()
where app.ProcessName.Contains( "MyAppName" ) && app.MainWindowHandle != IntPtr.Zero
select app).First();
```
which strikes me as somewhat ugly, and also throws an exception if there are no matching processes. Is there a better way?
**UPDATE**
I'm actually trying to find the first matching item, and call `SetForegroundWindow` on it
I've come up with this solution, which also strikes me as ugly and awful, but better than above. Any ideas?
```
var unused = from app in Process.GetProcesses()
where app.ProcessName.Contains( "MyAppName" ) && app.MainWindowHandle != IntPtr.Zero
select SetForegroundWindow( app.MainWindowHandle ); // side-effects in linq-query is technically bad I guess
``` | @FryHard FirstOrDefault will work but remember that it returns null if none are found. This code isn't tested but should be close to what you want:
```
var app = Process.GetProcesses().FirstOrDefault(p => p.ProcessName.Contains("MyAppName") && p.MainWindowHandle != IntPtr.Zero);
if (app == null)
return;
SetForegroundWindow(app.MainWindowHandle);
``` |
7,525 | <p>So, I need some help. I am working on a project in C++. However, I think I have somehow managed to corrupt my heap. This is based on the fact that I added an <code>std::string</code> to a class and assigning it a value from another <code>std::string</code>:</p>
<pre><code>std::string hello = "Hello, world.\n";
/* exampleString = "Hello, world.\n" would work fine. */
exampleString = hello;
</code></pre>
<p>crashes on my system with a stack dump. So basically I need to <strong>stop</strong> and go through all my code and memory management stuff and find out where I've screwed up. The codebase is still small (about 1000 lines), so this is easily do-able. </p>
<p>Still, I'm over my head with this kind of stuff, so I thought I'd throw it out there. I'm on a Linux system and have poked around with <code>valgrind</code>, and while not knowing completely what I'm doing, it did report that the <code>std::string</code>'s destructor was an invalid free. I have to admit to getting the term 'Heap Corruption' from a Google search; any general purpose articles on this sort of stuff would be appreciated as well.</p>
<p>(In before <code>rm -rf ProjectDir</code>, do again in C# :D)</p>
<p>EDIT:
I haven't made it clear, but what I'm asking for are ways an advice of diagnosing these sort of memory problems. I know the std::string stuff is right, so it's something I've done (or a bug, but there's Not A Problem With Select). I'm sure I could check the code I've written up and you very smart folks would see the problem in no time, but I want to add this kind of code analysis to my 'toolbox', as it were.</p>
| [
{
"answer_id": 7536,
"author": "JimDaniel",
"author_id": 63,
"author_profile": "https://Stackoverflow.com/users/63",
"pm_score": 0,
"selected": false,
"text": "<p>As far as I can tell your code is correct. Assuming exampleString is an std::string that has class scope like you describe, y... | 2008/08/11 | [
"https://Stackoverflow.com/questions/7525",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/61/"
] | So, I need some help. I am working on a project in C++. However, I think I have somehow managed to corrupt my heap. This is based on the fact that I added an `std::string` to a class and assigning it a value from another `std::string`:
```
std::string hello = "Hello, world.\n";
/* exampleString = "Hello, world.\n" would work fine. */
exampleString = hello;
```
crashes on my system with a stack dump. So basically I need to **stop** and go through all my code and memory management stuff and find out where I've screwed up. The codebase is still small (about 1000 lines), so this is easily do-able.
Still, I'm over my head with this kind of stuff, so I thought I'd throw it out there. I'm on a Linux system and have poked around with `valgrind`, and while not knowing completely what I'm doing, it did report that the `std::string`'s destructor was an invalid free. I have to admit to getting the term 'Heap Corruption' from a Google search; any general purpose articles on this sort of stuff would be appreciated as well.
(In before `rm -rf ProjectDir`, do again in C# :D)
EDIT:
I haven't made it clear, but what I'm asking for are ways an advice of diagnosing these sort of memory problems. I know the std::string stuff is right, so it's something I've done (or a bug, but there's Not A Problem With Select). I'm sure I could check the code I've written up and you very smart folks would see the problem in no time, but I want to add this kind of code analysis to my 'toolbox', as it were. | These are relatively cheap mechanisms for possibly solving the problem:
1. Keep an eye on my [heap corruption question](https://stackoverflow.com/questions/1069/heap-corruption-under-win32-how-to-locate) - I'm updating with the answers as they shake out. The first was balancing `new[]` and `delete[]`, but you're already doing that.
2. Give [valgrind](http://valgrind.org/) more of a go; it's an excellent tool, and I only wish it was available under Windows. I only slows your program down by about half, which is pretty good compared to the Windows equivalents.
3. Think about using the [Google Performance Tools](http://code.google.com/p/google-perftools/) as a replacement malloc/new.
4. Have you cleaned out all your object files and started over? Perhaps your make file is... "suboptimal"
5. You're not `assert()`ing enough in your code. How do I know that without having seen it? Like flossing, no-one `assert()`s enough in their code. Add in a validation function for your objects and call that on method start and method end.
6. Are you [compiling -wall](http://gcc.gnu.org/onlinedocs/gcc-4.3.0/cpp/Invocation.html#Invocation)? If not, do so.
7. Find yourself a lint tool like [PC-Lint](http://www.gimpel.com/). A small app like yours might fit in the [PC-lint demo](http://gimpel-online.com/cgi-bin/genPage.py?srcFile=diy.cpp&cgiScript=analyseCode.py&title=Blank+Slate+(C%2B%2B)+&intro=An+empty+page+in+which+to+write+your+own+C%2B%2B+code.&compilerOption=co-gcc.lnt+co-gnu3.lnt&includeOption=%7B%7BquotedIncludeOption%7D%7D) page, meaning no purchase for you!
8. Check you're NULLing out pointers after deleteing them. Nobody likes a dangling pointer. Same gig with declared but unallocated pointers.
9. Stop using arrays. Use a [vector](http://en.wikipedia.org/wiki/Vector_(STL)) instead.
10. Don't use raw pointers. Use a [smart pointer](http://en.wikipedia.org/wiki/Smart_pointer). Don't use `auto_ptr`! That thing is... surprising; its semantics are very odd. Instead, choose one of the [Boost smart pointers](http://www.boost.org/doc/libs/1_35_0/libs/smart_ptr/smart_ptr.htm), or something out of [the Loki library](http://en.wikipedia.org/wiki/Loki_(C%2B%2B)). |
7,535 | <p>What is the best way to use SQL Server 2008 as a development database, but ensure that the database is compatible with SQL Server 2005?</p>
| [
{
"answer_id": 7547,
"author": "vzczc",
"author_id": 224,
"author_profile": "https://Stackoverflow.com/users/224",
"pm_score": 5,
"selected": true,
"text": "<p>This can be done via SQL Enterprise Manager or like this: </p>\n\n<pre><code>ALTER DATABASE <database> \nSET COMPATIBILIT... | 2008/08/11 | [
"https://Stackoverflow.com/questions/7535",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/708/"
] | What is the best way to use SQL Server 2008 as a development database, but ensure that the database is compatible with SQL Server 2005? | This can be done via SQL Enterprise Manager or like this:
```
ALTER DATABASE <database>
SET COMPATIBILITY_LEVEL = { 80 | 90 | 100 }
```
Use 90 for 2005 compatibility.
This replaces the functionality used for previous releases, the stored procedure *sp\_dbcmptlevel*. |
7,539 | <p>Recently I tried understanding the use of <strong>java.math.MathContext</strong> but failed to understand properly. Is it used for rounding in <code>java.math.BigDecimal</code>. If yes why does not it round the decimal digits but even mantissa part.</p>
<p>From API docs, I came to know that it follows the standard specified in <code>ANSI X3.274-1996</code> and <code>ANSI X3.274-1996/AM 1-2000</code> specifications but I did not get them to read online.</p>
<p>Please let me know if you have any idea on this.</p>
| [
{
"answer_id": 7550,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 3,
"selected": false,
"text": "<p>If I'm understanding you correctly, it sounds like you're expecting the MathContext to control how many digits should be k... | 2008/08/11 | [
"https://Stackoverflow.com/questions/7539",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/959/"
] | Recently I tried understanding the use of **java.math.MathContext** but failed to understand properly. Is it used for rounding in `java.math.BigDecimal`. If yes why does not it round the decimal digits but even mantissa part.
From API docs, I came to know that it follows the standard specified in `ANSI X3.274-1996` and `ANSI X3.274-1996/AM 1-2000` specifications but I did not get them to read online.
Please let me know if you have any idea on this. | @jatan
>
> Thanks for you answer. It makes sense. Can you please explain me MathContext in the context of BigDecimal#round method.
>
>
>
There's nothing special about `BigDecimal.round()` *vs.* any other `BigDecimal` method. In all cases, the `MathContext` specifies the number of significant digits and the rounding technique. Basically, there are two parts of every [`MathContext`](http://java.sun.com/j2se/1.5.0/docs/api/java/math/MathContext.html). There's a precision, and there's also a [`RoundingMode`](http://java.sun.com/j2se/1.5.0/docs/api/java/math/RoundingMode.html).
The precision again specifies the number of significant digits. So if you specify `123` as a number, and ask for 2 significant digits, you're going to get `120`. It might be clearer if you think in terms of scientific notation.
`123` would be `1.23e2` in scientific notation. If you only keep 2 significant digits, then you get `1.2e2`, or `120`. By reducing the number of significant digits, we reduce the precision with which we can specify a number.
The `RoundingMode` part specifies how we should handle the loss of precision. To reuse the example, if you use `123` as the number, and ask for 2 significant digits, you've reduced your precision. With a `RoundingMode` of `HALF_UP` (the default mode), `123` will become `120`. With a `RoundingMode` of `CEILING`, you'll get `130`.
For example:
```
System.out.println(new BigDecimal("123.4",
new MathContext(4,RoundingMode.HALF_UP)));
System.out.println(new BigDecimal("123.4",
new MathContext(2,RoundingMode.HALF_UP)));
System.out.println(new BigDecimal("123.4",
new MathContext(2,RoundingMode.CEILING)));
System.out.println(new BigDecimal("123.4",
new MathContext(1,RoundingMode.CEILING)));
```
Outputs:
```
123.4
1.2E+2
1.3E+2
2E+2
```
You can see that both the precision and the rounding mode affect the output. |
7,558 | <p>I am displaying a list of items using a SAP ABAP column tree model, basically a tree of folder and files, with columns.</p>
<p>I want to load the sub-nodes of folders dynamically, so I'm using the EXPAND_NO_CHILDREN event which is firing correctly.</p>
<p>Unfortunately, after I add the new nodes and items to the tree, the folder is automatically collapsing again, requiring a second click to view the sub-nodes.
Do I need to call a method when handling the event so that the folder stays open, or am I doing something else wrong?</p>
<pre><code>* Set up event handling.
LS_EVENT-EVENTID = CL_ITEM_TREE_CONTROL=>EVENTID_EXPAND_NO_CHILDREN.
LS_EVENT-APPL_EVENT = GC_X.
APPEND LS_EVENT TO LT_EVENTS.
CALL METHOD GO_MODEL->SET_REGISTERED_EVENTS
EXPORTING
EVENTS = LT_EVENTS
EXCEPTIONS
ILLEGAL_EVENT_COMBINATION = 1
UNKNOWN_EVENT = 2.
SET HANDLER GO_APPLICATION->HANDLE_EXPAND_NO_CHILDREN
FOR GO_MODEL.
...
* Add new data to tree.
CALL METHOD GO_MODEL->ADD_NODES
EXPORTING
NODE_TABLE = PTI_NODES[]
EXCEPTIONS
ERROR_IN_NODE_TABLE = 1.
CALL METHOD GO_MODEL->ADD_ITEMS
EXPORTING
ITEM_TABLE = PTI_ITEMS[]
EXCEPTIONS
NODE_NOT_FOUND = 1
ERROR_IN_ITEM_TABLE = 2.
</code></pre>
| [
{
"answer_id": 14159,
"author": "Pat Hermens",
"author_id": 1677,
"author_profile": "https://Stackoverflow.com/users/1677",
"pm_score": 2,
"selected": false,
"text": "<p>It's been a while since I've played with SAP, but I always found the SAP Library to be particularly helpful when I got... | 2008/08/11 | [
"https://Stackoverflow.com/questions/7558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I am displaying a list of items using a SAP ABAP column tree model, basically a tree of folder and files, with columns.
I want to load the sub-nodes of folders dynamically, so I'm using the EXPAND\_NO\_CHILDREN event which is firing correctly.
Unfortunately, after I add the new nodes and items to the tree, the folder is automatically collapsing again, requiring a second click to view the sub-nodes.
Do I need to call a method when handling the event so that the folder stays open, or am I doing something else wrong?
```
* Set up event handling.
LS_EVENT-EVENTID = CL_ITEM_TREE_CONTROL=>EVENTID_EXPAND_NO_CHILDREN.
LS_EVENT-APPL_EVENT = GC_X.
APPEND LS_EVENT TO LT_EVENTS.
CALL METHOD GO_MODEL->SET_REGISTERED_EVENTS
EXPORTING
EVENTS = LT_EVENTS
EXCEPTIONS
ILLEGAL_EVENT_COMBINATION = 1
UNKNOWN_EVENT = 2.
SET HANDLER GO_APPLICATION->HANDLE_EXPAND_NO_CHILDREN
FOR GO_MODEL.
...
* Add new data to tree.
CALL METHOD GO_MODEL->ADD_NODES
EXPORTING
NODE_TABLE = PTI_NODES[]
EXCEPTIONS
ERROR_IN_NODE_TABLE = 1.
CALL METHOD GO_MODEL->ADD_ITEMS
EXPORTING
ITEM_TABLE = PTI_ITEMS[]
EXCEPTIONS
NODE_NOT_FOUND = 1
ERROR_IN_ITEM_TABLE = 2.
``` | It's been a while since I've played with SAP, but I always found the SAP Library to be particularly helpful when I got stuck...
I managed to come up with this one for you:
<http://help.sap.com/saphelp_nw04/helpdata/en/47/aa7a18c80a11d3a6f90000e83dd863/frameset.htm>, specifically:
>
> *When you add new nodes to the tree model, set the flag ITEMSINCOM to 'X'.
>
> This informs the tree model that you want to load the items for that node on demand.*
>
>
>
Hope it helps? |
7,586 | <p>I was trying to get my head around XAML and thought that I would try writing some code. </p>
<p>Trying to add a grid with 6 by 6 column definitions then add a text block into one of the grid cells. I don't seem to be able to reference the cell that I want. There is no method on the grid that I can add the text block too. There is only grid.children.add(object), no Cell definition.</p>
<p>XAML:</p>
<pre><code><Page x:Class="WPF_Tester.Page1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Page1"
Loaded="Page_Loaded">
</Page>
</code></pre>
<p>C#:</p>
<pre><code>private void Page_Loaded(object sender, RoutedEventArgs e)
{
//create the structure
Grid g = new Grid();
g.ShowGridLines = true;
g.Visibility = Visibility.Visible;
//add columns
for (int i = 0; i < 6; ++i)
{
ColumnDefinition cd = new ColumnDefinition();
cd.Name = "Column" + i.ToString();
g.ColumnDefinitions.Add(cd);
}
//add rows
for (int i = 0; i < 6; ++i)
{
RowDefinition rd = new RowDefinition();
rd.Name = "Row" + i.ToString();
g.RowDefinitions.Add(rd);
}
TextBlock tb = new TextBlock();
tb.Text = "Hello World";
g.Children.Add(tb);
}
</code></pre>
<p><strong>Update</strong></p>
<p>Here is the spooky bit:</p>
<ul>
<li><p>Using VS2008 Pro on XP</p></li>
<li><p>WPFbrowser Project Template (3.5 verified)</p></li>
</ul>
<p>I don't get the methods in autocomplete.</p>
| [
{
"answer_id": 7590,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 4,
"selected": true,
"text": "<p>WPF makes use of a funky thing called <a href=\"http://msdn.microsoft.com/en-us/library/ms749011.aspx\" rel=\"noreferrer... | 2008/08/11 | [
"https://Stackoverflow.com/questions/7586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I was trying to get my head around XAML and thought that I would try writing some code.
Trying to add a grid with 6 by 6 column definitions then add a text block into one of the grid cells. I don't seem to be able to reference the cell that I want. There is no method on the grid that I can add the text block too. There is only grid.children.add(object), no Cell definition.
XAML:
```
<Page x:Class="WPF_Tester.Page1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Page1"
Loaded="Page_Loaded">
</Page>
```
C#:
```
private void Page_Loaded(object sender, RoutedEventArgs e)
{
//create the structure
Grid g = new Grid();
g.ShowGridLines = true;
g.Visibility = Visibility.Visible;
//add columns
for (int i = 0; i < 6; ++i)
{
ColumnDefinition cd = new ColumnDefinition();
cd.Name = "Column" + i.ToString();
g.ColumnDefinitions.Add(cd);
}
//add rows
for (int i = 0; i < 6; ++i)
{
RowDefinition rd = new RowDefinition();
rd.Name = "Row" + i.ToString();
g.RowDefinitions.Add(rd);
}
TextBlock tb = new TextBlock();
tb.Text = "Hello World";
g.Children.Add(tb);
}
```
**Update**
Here is the spooky bit:
* Using VS2008 Pro on XP
* WPFbrowser Project Template (3.5 verified)
I don't get the methods in autocomplete. | WPF makes use of a funky thing called [attached properties](http://msdn.microsoft.com/en-us/library/ms749011.aspx). So in your XAML you might write this:
```
<TextBlock Grid.Row="0" Grid.Column="0" />
```
And this will effectively move the TextBlock into cell (0,0) of your grid.
In code this looks a little strange. I believe it'd be something like:
```
g.Children.Add(tb);
Grid.SetRow(tb, 0);
Grid.SetColumn(tb, 0);
```
Have a look at that link above - attached properties make things really easy to do in XAML perhaps at the expense of intuitive-looking code. |
7,592 | <p>I want to create a client side mail creator web page. I know the problems of using the mailto action in an html form (not standard, no default mail appication set on the client). But the web page isn't very important, and they don't care very much.</p>
<p>The mail created by the mailto action has the syntax:</p>
<blockquote>
<p>subject: undefined subject<br>
body:</p>
<p>param1=value1<br>
param2=value2<br>
.<br>
.<br>
.<br>
paramn=valuen </p>
</blockquote>
<p>Can I use JavaScript to format the mail like this?</p>
<blockquote>
<p>Subject:XXXXX</p>
<p>Body:
Value1;Value2;Value3...ValueN</p>
</blockquote>
| [
{
"answer_id": 7597,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": -1,
"selected": false,
"text": "<p>Is there a reason you can't just send the data to a page which handles sending the mail? It is pretty easy to send an em... | 2008/08/11 | [
"https://Stackoverflow.com/questions/7592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/518/"
] | I want to create a client side mail creator web page. I know the problems of using the mailto action in an html form (not standard, no default mail appication set on the client). But the web page isn't very important, and they don't care very much.
The mail created by the mailto action has the syntax:
>
> subject: undefined subject
>
> body:
>
>
> param1=value1
>
> param2=value2
>
> .
>
> .
>
> .
>
> paramn=valuen
>
>
>
Can I use JavaScript to format the mail like this?
>
> Subject:XXXXX
>
>
> Body:
> Value1;Value2;Value3...ValueN
>
>
> | What we used in a projet is a popup window that opens a mailto: link, it is the only way we found to compose a mail within the default mail client that works with all mail clients (at least all our clients used).
```
var addresses = "";//between the speech mark goes the receptient. Seperate addresses with a ;
var body = ""//write the message text between the speech marks or put a variable in the place of the speech marks
var subject = ""//between the speech marks goes the subject of the message
var href = "mailto:" + addresses + "?"
+ "subject=" + subject + "&"
+ "body=" + body;
var wndMail;
wndMail = window.open(href, "_blank", "scrollbars=yes,resizable=yes,width=10,height=10");
if(wndMail)
{
wndMail.close();
}
``` |
7,596 | <p>First of all, I know how to build a Java application. But I have always been puzzled about where to put my classes. There are proponents for organizing the packages in a strictly domain oriented fashion, others separate by tier.</p>
<p>I myself have always had problems with </p>
<ul>
<li>naming, </li>
<li>placing</li>
</ul>
<p>So,</p>
<ol>
<li>Where do you put your domain specific constants (and what is the best name for such a class)?</li>
<li>Where do you put classes for stuff which is both infrastructural and domain specific (for instance I have a FileStorageStrategy class, which stores the files either in the database, or alternatively in database)?</li>
<li>Where to put Exceptions?</li>
<li>Are there any standards to which I can refer?</li>
</ol>
| [
{
"answer_id": 7599,
"author": "graham.reeds",
"author_id": 342,
"author_profile": "https://Stackoverflow.com/users/342",
"pm_score": 2,
"selected": false,
"text": "<p>Class names should always be descriptive and self-explanatory. If you have multiple domains of responsibility for your c... | 2008/08/11 | [
"https://Stackoverflow.com/questions/7596",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/917/"
] | First of all, I know how to build a Java application. But I have always been puzzled about where to put my classes. There are proponents for organizing the packages in a strictly domain oriented fashion, others separate by tier.
I myself have always had problems with
* naming,
* placing
So,
1. Where do you put your domain specific constants (and what is the best name for such a class)?
2. Where do you put classes for stuff which is both infrastructural and domain specific (for instance I have a FileStorageStrategy class, which stores the files either in the database, or alternatively in database)?
3. Where to put Exceptions?
4. Are there any standards to which I can refer? | I've really come to like Maven's [Standard Directory Layout](http://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html "S").
One of the key ideas for me is to have two source roots - one for production code and one for test code like so:
```
MyProject/src/main/java/com/acme/Widget.java
MyProject/src/test/java/com/acme/WidgetTest.java
```
(here, both src/main/java and src/test/java are source roots).
Advantages:
* Your tests have package (or "default") level access to your classes under test.
* You can easily package only your production sources into a JAR by dropping src/test/java as a source root.
One rule of thumb about class placement and packages:
Generally speaking, well structured projects will be free of [circular dependencies](http://en.wikipedia.org/wiki/Circular_dependency). Learn when they are bad (and when they are [not](http://beust.com/weblog/archives/000208.html)), and consider a tool like [JDepend](http://www.google.ca/search?q=JDepend&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a) or [SonarJ](http://www.hello2morrow.com/products/sonargraph) that will help you eliminate them. |
7,614 | <p>What is the best way of testing a function that throws on failure? Or testing a function that is fairly immune to failure?</p>
<p>For instance; I have a <code>I/O Completion Port</code> class that throws in the constructor if it can't initialise the port correctly. This uses the <code>Win32</code> function of <code>CreateIoCompletionPort</code> in the initialiser list. If the handle isn't set correctly - a non-null value - then the constructor will throw an exception. I have never seen this function fail.</p>
<p>I am pretty certain that this (and other functions like it in my code) if they fail will behave correctly, the code is 50 lines long including white-space, so my questions are</p>
<p>a) is it worth testing that it will throw<br>
b) and if it is worth testing, how to?<br>
c) should simple wrapper classes as these be unit-tested? </p>
<p>For b) I thought about overriding <code>CreateIoCompletionPort</code> and passing the values through. In the unit test override it and cause it to return 0 when a certain value is passed in. However since this is used in the constructor then this needs to be static. Does this seem valid or not?</p>
| [
{
"answer_id": 7624,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 2,
"selected": false,
"text": "<p>It is definitely worthwhile to test failure conditions, both that your class properly throws an exception when you want it... | 2008/08/11 | [
"https://Stackoverflow.com/questions/7614",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/342/"
] | What is the best way of testing a function that throws on failure? Or testing a function that is fairly immune to failure?
For instance; I have a `I/O Completion Port` class that throws in the constructor if it can't initialise the port correctly. This uses the `Win32` function of `CreateIoCompletionPort` in the initialiser list. If the handle isn't set correctly - a non-null value - then the constructor will throw an exception. I have never seen this function fail.
I am pretty certain that this (and other functions like it in my code) if they fail will behave correctly, the code is 50 lines long including white-space, so my questions are
a) is it worth testing that it will throw
b) and if it is worth testing, how to?
c) should simple wrapper classes as these be unit-tested?
For b) I thought about overriding `CreateIoCompletionPort` and passing the values through. In the unit test override it and cause it to return 0 when a certain value is passed in. However since this is used in the constructor then this needs to be static. Does this seem valid or not? | It is definitely worthwhile to test failure conditions, both that your class properly throws an exception when you want it to and that exceptions are handled properly in the class.
This can easily be done if you are acting on an object passed in to the constructor... just pass in a mock. If not, I tend to prefer to have the functionality moved to a protected method, and override the protected method to evoke my failure case. I will use Java as an example, but it should be easy enough to port the ideas to a C# case:
```
public class MyClass {
public MyClass() throws MyClassException {
// Whatever, including a call to invokeCreateIoCompletionPort
}
protected int invokeCreateIoCompletionPort(String str, int i) {
return StaticClass.createIoCompletionPort(str, i);
}
}
public class MyTest {
public void myTest() {
try {
new MyClass();
fail("MyClassException was not thrown!");
} catch (MyClassException e) {
}
}
private static class MyClassWrapper extends MyClass {
@Override
protected int invokeCreateIoCompletionPort(String str, int i) {
throw new ExpectedException();
}
}
}
```
As you can see, it is pretty easy to test whether an exception is being thrown by the constructor or method you are testing, and it is also pretty easy to inject an exception from an external class that can throw an exception. Sorry I'm not using your actual method, I just used the name to illustrate how it sounded like you are using it, and how I would test the cases it sounded you wanted to test.
Basically, any API details you expose can usually be tested, and if you want to KNOW that exceptional cases work as they should, you probably will want to test it. |
7,651 | <p>I have an array in Perl:</p>
<pre><code>my @my_array = ("one","two","three","two","three");
</code></pre>
<p>How do I remove the duplicates from the array?</p>
| [
{
"answer_id": 7657,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 8,
"selected": true,
"text": "<p>You can do something like this as demonstrated in <a href=\"http://perldoc.perl.org/perlfaq4.html#How-can-I-remove-duplic... | 2008/08/11 | [
"https://Stackoverflow.com/questions/7651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/381/"
] | I have an array in Perl:
```
my @my_array = ("one","two","three","two","three");
```
How do I remove the duplicates from the array? | You can do something like this as demonstrated in [perlfaq4](http://perldoc.perl.org/perlfaq4.html#How-can-I-remove-duplicate-elements-from-a-list-or-array%3f):
```
sub uniq {
my %seen;
grep !$seen{$_}++, @_;
}
my @array = qw(one two three two three);
my @filtered = uniq(@array);
print "@filtered\n";
```
Outputs:
```
one two three
```
If you want to use a module, try the `uniq` function from [`List::MoreUtils`](https://metacpan.org/pod/List::MoreUtils) |
7,664 | <p>I am wrapping existing C++ code from a <strong>BSD</strong> project in our own custom wrapper and I want to integrate it to our code with as few changes as possible. This code uses <code>fprintf</code> to print to <strong>stderr</strong> in order to log / report errors.</p>
<p>I want to redirect this to an alternative place within the same process. On <strong>Unix</strong> I have done this with a <code>socketpair</code> and a <code>thread</code>: one end of the socket is where I send <strong>stderr</strong> (via a call to <code>dup2</code>) and the other end is monitored in a thread, where I can then process the output.</p>
<p>This does not work on <strong>Windows</strong> though because a socket is not the same as a file handle.</p>
<p>All documents I have found on the web show how to redirect output from a child process, which is not what I want. How can I redirect <strong>stderr</strong> within the same process getting a callback of some sort when output is written? (and before you say so, I've tried <code>SetStdHandle</code> but cannot find any way to make this work)...</p>
| [
{
"answer_id": 7669,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 4,
"selected": true,
"text": "<p>You can use a similar technique on Windows, you just need to use different words for the same concepts. :) This article: ... | 2008/08/11 | [
"https://Stackoverflow.com/questions/7664",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/912/"
] | I am wrapping existing C++ code from a **BSD** project in our own custom wrapper and I want to integrate it to our code with as few changes as possible. This code uses `fprintf` to print to **stderr** in order to log / report errors.
I want to redirect this to an alternative place within the same process. On **Unix** I have done this with a `socketpair` and a `thread`: one end of the socket is where I send **stderr** (via a call to `dup2`) and the other end is monitored in a thread, where I can then process the output.
This does not work on **Windows** though because a socket is not the same as a file handle.
All documents I have found on the web show how to redirect output from a child process, which is not what I want. How can I redirect **stderr** within the same process getting a callback of some sort when output is written? (and before you say so, I've tried `SetStdHandle` but cannot find any way to make this work)... | You can use a similar technique on Windows, you just need to use different words for the same concepts. :) This article: <http://msdn.microsoft.com/en-us/library/ms682499.aspx> uses a win32 pipe to handle I/O from another process, you just have to do the same thing with threads within the same process. Of course, in your case all output to stderr from anywhere in the process will be redirected to your consumer.
Actually, other pieces of the puzzle you may need are [\_fdopen](http://msdn.microsoft.com/en-us/library/dye30d82(VS.80).aspx) and [\_open\_osfhandle](http://msdn.microsoft.com/en-us/library/bdts1c9x(VS.71).aspx). In fact, here's a related example from some [code](http://hewgill.com/pilot/copilot/) I released years ago:
```
DWORD CALLBACK DoDebugThread(void *)
{
AllocConsole();
SetConsoleTitle("Copilot Debugger");
// The following is a really disgusting hack to make stdin and stdout attach
// to the newly created console using the MSVC++ libraries. I hope other
// operating systems don't need this kind of kludge.. :)
stdout->_file = _open_osfhandle((long)GetStdHandle(STD_OUTPUT_HANDLE), _O_TEXT);
stdin->_file = _open_osfhandle((long)GetStdHandle(STD_INPUT_HANDLE), _O_TEXT);
debug();
stdout->_file = -1;
stdin->_file = -1;
FreeConsole();
CPU_run();
return 0;
}
```
In this case, the main process was a GUI process which doesn't start with stdio handles at all. It opens a console, then shoves the right handles into stdout and stdin so the debug() function (which was designed as a stdio interactive function) can interact with the newly created console. You should be able to open some pipes and do the same sort of thing to redirect stderr. |
7,665 | <p>Given an absolute or relative path (in a Unix-like system), I would like to determine the full path of the target after resolving any intermediate symlinks. Bonus points for also resolving ~username notation at the same time.</p>
<p>If the target is a directory, it might be possible to chdir() into the directory and then call getcwd(), but I really want to do this from a shell script rather than writing a C helper. Unfortunately, shells have a tendency to try to hide the existence of symlinks from the user (this is bash on OS X):</p>
<pre><code>$ ls -ld foo bar
drwxr-xr-x 2 greg greg 68 Aug 11 22:36 bar
lrwxr-xr-x 1 greg greg 3 Aug 11 22:36 foo -> bar
$ cd foo
$ pwd
/Users/greg/tmp/foo
$
</code></pre>
<p>What I want is a function resolve() such that when executed from the tmp directory in the above example, resolve("foo") == "/Users/greg/tmp/bar".</p>
| [
{
"answer_id": 7666,
"author": "kauppi",
"author_id": 964,
"author_profile": "https://Stackoverflow.com/users/964",
"pm_score": 8,
"selected": true,
"text": "<p>According to the standards, <code>pwd -P</code> should return the path with symlinks resolved.</p>\n\n<p>C function <code>char ... | 2008/08/11 | [
"https://Stackoverflow.com/questions/7665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/893/"
] | Given an absolute or relative path (in a Unix-like system), I would like to determine the full path of the target after resolving any intermediate symlinks. Bonus points for also resolving ~username notation at the same time.
If the target is a directory, it might be possible to chdir() into the directory and then call getcwd(), but I really want to do this from a shell script rather than writing a C helper. Unfortunately, shells have a tendency to try to hide the existence of symlinks from the user (this is bash on OS X):
```
$ ls -ld foo bar
drwxr-xr-x 2 greg greg 68 Aug 11 22:36 bar
lrwxr-xr-x 1 greg greg 3 Aug 11 22:36 foo -> bar
$ cd foo
$ pwd
/Users/greg/tmp/foo
$
```
What I want is a function resolve() such that when executed from the tmp directory in the above example, resolve("foo") == "/Users/greg/tmp/bar". | According to the standards, `pwd -P` should return the path with symlinks resolved.
C function `char *getcwd(char *buf, size_t size)` from `unistd.h` should have the same behaviour.
[getcwd](http://www.opengroup.org/onlinepubs/009695399/functions/getcwd.html)
[pwd](http://www.opengroup.org/onlinepubs/009695399/utilities/pwd.html) |
7,685 | <p>I was recently brushing up on some fundamentals and found merge sorting a linked list to be a pretty good challenge. If you have a good implementation then show it off here.</p>
| [
{
"answer_id": 7802,
"author": "John with waffle",
"author_id": 279,
"author_profile": "https://Stackoverflow.com/users/279",
"pm_score": 3,
"selected": false,
"text": "<p>One interesting way is to maintain a stack, and only merge if the list on the stack has the same number of elements,... | 2008/08/11 | [
"https://Stackoverflow.com/questions/7685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/608/"
] | I was recently brushing up on some fundamentals and found merge sorting a linked list to be a pretty good challenge. If you have a good implementation then show it off here. | Wonder why it should be big challenge as it is stated here, here is a straightforward implementation in Java with out any "clever tricks".
```java
//The main function
public static Node merge_sort(Node head)
{
if(head == null || head.next == null)
return head;
Node middle = getMiddle(head); //get the middle of the list
Node left_head = head;
Node right_head = middle.next;
middle.next = null; //split the list into two halfs
return merge(merge_sort(left_head), merge_sort(right_head)); //recurse on that
}
//Merge subroutine to merge two sorted lists
public static Node merge(Node a, Node b)
{
Node dummyHead = new Node();
for(Node current = dummyHead; a != null && b != null; current = current.next;)
{
if(a.data <= b.data)
{
current.next = a;
a = a.next;
}
else
{
current.next = b;
b = b.next;
}
}
dummyHead.next = (a == null) ? b : a;
return dummyHead.next;
}
//Finding the middle element of the list for splitting
public static Node getMiddle(Node head)
{
if(head == null)
return head;
Node slow = head, fast = head;
while(fast.next != null && fast.next.next != null)
{
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
``` |
7,707 | <p>I have an element which may contain very big amounts of data, but I don't want it to ruin the page layout, so I set <code>max-height: 100px</code> and <code>overflow:auto</code>, hoping for scrollbars to appear when the content does not fit. </p>
<p>It all works fine in Firefox and IE7, but IE8 behaves as if <code>overflow:hidden</code> was present instead of <code>overflow:auto</code>. </p>
<p>I tried <code>overflow:scroll</code>, still does not help, IE8 simply truncates the content without showing scrollbars. Changing <code>max-height</code> declaration to <code>height</code> makes overflow work OK, it's the combination of <code>max-height</code> and <code>overflow:auto</code> that breaks things.</p>
<p>This is also logged as an <a href="http://connect.microsoft.com/IE/feedback/ViewFeedback.aspx?FeedbackID=408759" rel="noreferrer">official bug in the final, release version of IE8</a></p>
<p>Is there a workaround? For now I resorted to using <code>height</code> instead of <code>max-height</code>, but it leaves plenty of empty space in case there isn't much data.</p>
| [
{
"answer_id": 668205,
"author": "James Koch",
"author_id": 79509,
"author_profile": "https://Stackoverflow.com/users/79509",
"pm_score": 2,
"selected": false,
"text": "<p>I saw this logged as a fixed bug in RC1. But I've found a variation that seems to cause a hard assert render failur... | 2008/08/11 | [
"https://Stackoverflow.com/questions/7707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/979/"
] | I have an element which may contain very big amounts of data, but I don't want it to ruin the page layout, so I set `max-height: 100px` and `overflow:auto`, hoping for scrollbars to appear when the content does not fit.
It all works fine in Firefox and IE7, but IE8 behaves as if `overflow:hidden` was present instead of `overflow:auto`.
I tried `overflow:scroll`, still does not help, IE8 simply truncates the content without showing scrollbars. Changing `max-height` declaration to `height` makes overflow work OK, it's the combination of `max-height` and `overflow:auto` that breaks things.
This is also logged as an [official bug in the final, release version of IE8](http://connect.microsoft.com/IE/feedback/ViewFeedback.aspx?FeedbackID=408759)
Is there a workaround? For now I resorted to using `height` instead of `max-height`, but it leaves plenty of empty space in case there isn't much data. | This is a really nasty bug as it affects us heavily on Stack Overflow with `<pre>` code blocks, which have `max-height:600` and `width:auto`.
It is logged as a bug in the final version of IE8 with no fix.
<http://connect.microsoft.com/IE/feedback/ViewFeedback.aspx?FeedbackID=408759>
There is a really, really hacky CSS workaround:
<http://my.opera.com/dbloom/blog/2009/03/11/css-hack-for-ie8-standards-mode>
```css
/*
SUPER nasty IE8 hack to deal with this bug
*/
pre
{
max-height: none\9
}
```
and of course conditional CSS as others have mentioned, but I dislike that because it means you're serving up extra HTML cruft in every page request. |
7,719 | <p>Is there any way to capture the MouseDown even from the .NET 2.0 TextBox control?
I know the inherited Control class has the event, but it's not exposed in TextBox.
Is there a way to override the event handler?</p>
<p>I also tried the OpenNETCF TextBox2 control which does have the MouseDown event exposed, but no matter what I do, it doesn't fire the handler.</p>
<p>Any suggestions?</p>
<hr>
<blockquote>
<p>What kind of crazy mobile device do
you have that has a mouse? :)</p>
</blockquote>
<p>Yes, windows mobile does not have an actual mouse, but you are mistaken that Windows Mobile .NET do not support the Mouse events. A click or move on the screen is still considered a "Mouse" event. It was done this way so that code could port over from full Windows easily. And this is not a Windows Mobile specific issue. The TextBox control on Windows does not have native mouse events either. I just happened to be using Windows Mobile in this case.</p>
<p>Edit: And on a side note...as Windows Mobile is built of the WindowsCE core which is often used for embedded desktop systems and Slim Terminal Services clients or "WinTerms" it has support for a hardware mouse and has for a long time. Most devices just don't have the ports to plug one in.</p>
<hr>
<blockquote>
<p>According to the .Net Framework, the
MouseDown Event Handler on a TextBox
is supported. What happens when you
try to run the code?</p>
</blockquote>
<p>Actually, that's only there because it inherits it from "Control", as does <em>every</em> other Form control. It is, however, overridden (and changed to private I believe) in the TextBox class. So it will not show up in IntelliSense in Visual Studio.</p>
<p>However, you actually can write the code:</p>
<pre><code>textBox1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.textBox1_MouseDown);
</code></pre>
<p>and it will compile and run just fine, the only problem is that textBox1_MouseDown() will not be fired when you tap the TextBox control. I assume this is because of the Event being overridden internally. I don't even want to change what's happening on the event internally, I just want to add my own event handler to that event so I can fire some custom code as you could with any other event.</p>
| [
{
"answer_id": 7799,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 0,
"selected": false,
"text": "<p>According to the .Net Framework, the <a href=\"http://www.csharpfriends.com/quickstart/aspplus/samples/classbrowser/cs/cla... | 2008/08/11 | [
"https://Stackoverflow.com/questions/7719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/194/"
] | Is there any way to capture the MouseDown even from the .NET 2.0 TextBox control?
I know the inherited Control class has the event, but it's not exposed in TextBox.
Is there a way to override the event handler?
I also tried the OpenNETCF TextBox2 control which does have the MouseDown event exposed, but no matter what I do, it doesn't fire the handler.
Any suggestions?
---
>
> What kind of crazy mobile device do
> you have that has a mouse? :)
>
>
>
Yes, windows mobile does not have an actual mouse, but you are mistaken that Windows Mobile .NET do not support the Mouse events. A click or move on the screen is still considered a "Mouse" event. It was done this way so that code could port over from full Windows easily. And this is not a Windows Mobile specific issue. The TextBox control on Windows does not have native mouse events either. I just happened to be using Windows Mobile in this case.
Edit: And on a side note...as Windows Mobile is built of the WindowsCE core which is often used for embedded desktop systems and Slim Terminal Services clients or "WinTerms" it has support for a hardware mouse and has for a long time. Most devices just don't have the ports to plug one in.
---
>
> According to the .Net Framework, the
> MouseDown Event Handler on a TextBox
> is supported. What happens when you
> try to run the code?
>
>
>
Actually, that's only there because it inherits it from "Control", as does *every* other Form control. It is, however, overridden (and changed to private I believe) in the TextBox class. So it will not show up in IntelliSense in Visual Studio.
However, you actually can write the code:
```
textBox1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.textBox1_MouseDown);
```
and it will compile and run just fine, the only problem is that textBox1\_MouseDown() will not be fired when you tap the TextBox control. I assume this is because of the Event being overridden internally. I don't even want to change what's happening on the event internally, I just want to add my own event handler to that event so I can fire some custom code as you could with any other event. | Looks like you're right. Bummer. No MouseOver event.
One of the fallbacks that always works with .NET, though, is P/Invoke. Someone already took the time to do this for the .NET CF TextBox. I found this on CodeProject:
<http://www.codeproject.com/KB/cs/TextBox_subclassing.aspx>
Hope this helps |
7,720 | <p>I am writing an application in Java for the desktop using the Eclipse SWT library for GUI rendering. I think SWT helps Java get over the biggest hurdle for acceptance on the desktop: namely providing a Java application with a consistent, responsive interface that looks like that belonging to any other app on your desktop. However, I feel that packaging an application is still an issue. </p>
<p>OS X natively provides an easy mechanism for wrapping Java apps in native application bundles, but producing an app for Windows/Linux that doesn't require the user to run an ugly batch file or click on a .jar is still a hassle. Possibly that's not such an issue on Linux, where the user is likely to be a little more tech-savvy, but on Windows I'd like to have a regular .exe for him/her to run.</p>
<p>Has anyone had any experience with any of the .exe generation tools for Java that are out there? I've tried JSmooth but had various issues with it. Is there a better solution before I crack out Visual Studio and roll my own?</p>
<p><strong>Edit:</strong> I should perhaps mention that I am unable to spend a lot of money on a commercial solution.</p>
| [
{
"answer_id": 7747,
"author": "basszero",
"author_id": 287,
"author_profile": "https://Stackoverflow.com/users/287",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://www.ej-technologies.com/products/install4j/overview.html\" rel=\"nofollow noreferrer\">Install4J</a>. Not f... | 2008/08/11 | [
"https://Stackoverflow.com/questions/7720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/998/"
] | I am writing an application in Java for the desktop using the Eclipse SWT library for GUI rendering. I think SWT helps Java get over the biggest hurdle for acceptance on the desktop: namely providing a Java application with a consistent, responsive interface that looks like that belonging to any other app on your desktop. However, I feel that packaging an application is still an issue.
OS X natively provides an easy mechanism for wrapping Java apps in native application bundles, but producing an app for Windows/Linux that doesn't require the user to run an ugly batch file or click on a .jar is still a hassle. Possibly that's not such an issue on Linux, where the user is likely to be a little more tech-savvy, but on Windows I'd like to have a regular .exe for him/her to run.
Has anyone had any experience with any of the .exe generation tools for Java that are out there? I've tried JSmooth but had various issues with it. Is there a better solution before I crack out Visual Studio and roll my own?
**Edit:** I should perhaps mention that I am unable to spend a lot of money on a commercial solution. | To follow up on pauxu's answer, I'm using launch4j and NSIS on a project of mine and thought it would be helpful to show just how I'm using them. Here's what I'm doing for Windows. BTW, I'm creating .app and .dmg for Mac, but haven't figured out what to do for Linux yet.
Project Copies of launch4j and NSIS
-----------------------------------
In my project I have a "vendor" directory and underneath it I have a directory for "launch4j" and "nsis". Within each is a copy of the install for each application. I find it easier to have a copy local to the project rather than forcing others to install both products and set up some kind of environment variable to point to each.
Script Files
------------
I also have a "scripts" directory in my project that holds various configuration/script files for my project. First there is the launch4j.xml file:
```
<launch4jConfig>
<dontWrapJar>true</dontWrapJar>
<headerType>gui</headerType>
<jar>rpgam.jar</jar>
<outfile>rpgam.exe</outfile>
<errTitle></errTitle>
<cmdLine></cmdLine>
<chdir>.</chdir>
<priority>normal</priority>
<downloadUrl>http://www.rpgaudiomixer.com/</downloadUrl>
<supportUrl></supportUrl>
<customProcName>false</customProcName>
<stayAlive>false</stayAlive>
<manifest></manifest>
<icon></icon>
<jre>
<path></path>
<minVersion>1.5.0</minVersion>
<maxVersion></maxVersion>
<jdkPreference>preferJre</jdkPreference>
</jre>
<splash>
<file>..\images\splash.bmp</file>
<waitForWindow>true</waitForWindow>
<timeout>60</timeout>
<timeoutErr>true</timeoutErr>
</splash>
</launch4jConfig>
```
And then there's the NSIS script rpgam-setup.nsis. It can take a VERSION argument to help name the file.
```
; The name of the installer
Name "RPG Audio Mixer"
!ifndef VERSION
!define VERSION A.B.C
!endif
; The file to write
outfile "..\dist\installers\windows\rpgam-${VERSION}.exe"
; The default installation directory
InstallDir "$PROGRAMFILES\RPG Audio Mixer"
; Registry key to check for directory (so if you install again, it will
; overwrite the old one automatically)
InstallDirRegKey HKLM "Software\RPG_Audio_Mixer" "Install_Dir"
# create a default section.
section "RPG Audio Mixer"
SectionIn RO
; Set output path to the installation directory.
SetOutPath $INSTDIR
File /r "..\dist\layout\windows\"
; Write the installation path into the registry
WriteRegStr HKLM SOFTWARE\RPG_Audio_Mixer "Install_Dir" "$INSTDIR"
; Write the uninstall keys for Windows
WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\RPGAudioMixer" "DisplayName" "RPG Audio Mixer"
WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\RPGAudioMixer" "UninstallString" '"$INSTDIR\uninstall.exe"'
WriteRegDWORD HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\RPGAudioMixer" "NoModify" 1
WriteRegDWORD HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\RPGAudioMixer" "NoRepair" 1
WriteUninstaller "uninstall.exe"
; read the value from the registry into the $0 register
;readRegStr $0 HKLM "SOFTWARE\JavaSoft\Java Runtime Environment" CurrentVersion
; print the results in a popup message box
;messageBox MB_OK "version: $0"
sectionEnd
Section "Start Menu Shortcuts"
CreateDirectory "$SMPROGRAMS\RPG Audio Mixer"
CreateShortCut "$SMPROGRAMS\RPG Audio Mixer\Uninstall.lnk" "$INSTDIR\uninstall.exe" "" "$INSTDIR\uninstall.exe" 0
CreateShortCut "$SMPROGRAMS\RPG AUdio Mixer\RPG Audio Mixer.lnk" "$INSTDIR\rpgam.exe" "" "$INSTDIR\rpgam.exe" 0
SectionEnd
Section "Uninstall"
; Remove registry keys
DeleteRegKey HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\RPGAudioMixer"
DeleteRegKey HKLM SOFTWARE\RPG_Audio_Mixer
; Remove files and uninstaller
Delete $INSTDIR\rpgam.exe
Delete $INSTDIR\uninstall.exe
; Remove shortcuts, if any
Delete "$SMPROGRAMS\RPG Audio Mixer\*.*"
; Remove directories used
RMDir "$SMPROGRAMS\RPG Audio Mixer"
RMDir "$INSTDIR"
SectionEnd
```
Ant Integration
---------------
I have some targets in my Ant buildfile (build.xml) to handle the above. First I tel Ant to import launch4j's Ant tasks:
```
<property name="launch4j.dir" location="vendor/launch4j" />
<taskdef name="launch4j"
classname="net.sf.launch4j.ant.Launch4jTask"
classpath="${launch4j.dir}/launch4j.jar:${launch4j.dir}/lib/xstream.jar" />
```
I then have a simple target for creating the wrapper executable:
```
<target name="executable-windows" depends="jar" description="Create Windows executable (EXE)">
<launch4j configFile="scripts/launch4j.xml" outfile="${exeFile}" />
</target>
```
And another target for making the installer:
```
<target name="installer-windows" depends="executable-windows" description="Create the installer for Windows (EXE)">
<!-- Lay out files needed for building the installer -->
<mkdir dir="${windowsLayoutDirectory}" />
<copy file="${jarFile}" todir="${windowsLayoutDirectory}" />
<copy todir="${windowsLayoutDirectory}/lib">
<fileset dir="${libraryDirectory}" />
<fileset dir="${windowsLibraryDirectory}" />
</copy>
<copy todir="${windowsLayoutDirectory}/icons">
<fileset dir="${iconsDirectory}" />
</copy>
<copy todir="${windowsLayoutDirectory}" file="${exeFile}" />
<mkdir dir="${windowsInstallerDirectory}" />
<!-- Build the installer using NSIS -->
<exec executable="vendor/nsis/makensis.exe">
<arg value="/DVERSION=${version}" />
<arg value="scripts/rpgam-setup.nsi" />
</exec>
</target>
```
The top portion of that just copies the necessary files for the installer to a temporary location and the second half executes the script that uses all of it to make the installer. |
7,737 | <p>Is there a good way for displaying unicode text in opengl under Windows? For example, when you have to deal with different languages. The most common approach like</p>
<pre><code>#define FONTLISTRANGE 128
GLuint list;
list = glGenLists(FONTLISTRANGE);
wglUseFontBitmapsW(hDC, 0, FONTLISTRANGE, list);
</code></pre>
<p>just won't do because you can't create enough lists for all unicode characters.</p>
| [
{
"answer_id": 7745,
"author": "basszero",
"author_id": 287,
"author_profile": "https://Stackoverflow.com/users/287",
"pm_score": 2,
"selected": false,
"text": "<p>You may have to generate you own \"glyph cache\" in texture memory as you go, potentially with some sort of LRU policy to av... | 2008/08/11 | [
"https://Stackoverflow.com/questions/7737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1007/"
] | Is there a good way for displaying unicode text in opengl under Windows? For example, when you have to deal with different languages. The most common approach like
```
#define FONTLISTRANGE 128
GLuint list;
list = glGenLists(FONTLISTRANGE);
wglUseFontBitmapsW(hDC, 0, FONTLISTRANGE, list);
```
just won't do because you can't create enough lists for all unicode characters. | You could also group the characters by language. Load each language table as needed, and when you need to switch languages, unload the previous language table and load the new one. |
7,758 | <p>I'm getting all learned up about binding in WPF. I'm having a lot of trouble debugging the parse errors in my xaml, though. Can somebody pretty please tell me what's wrong with this little piece? :</p>
<pre><code><Border Name="TrackBackground"
Margin="0"
CornerRadius="2"
Grid.Row="1"
Grid.Column="1"
Background="BlanchedAlmond"
BorderThickness="1"
Height="{TemplateBinding Height}">
<Canvas Name="PART_Track" Background="DarkSalmon" Grid.Row="1" Grid.Column="1">
<Thumb Name="ThumbKnob" Height="{Binding ElementName=Part_Track, Path=Height, Mode=OneWay}" />
</Canvas>
</Border>
</code></pre>
<p>It's the databinding that breaks. I get an <code>InvalidAttributeValue</code> exception for ThumbKnob.Height when I try to run this. I know I must be missing something fundamental. So fill me in, stackers, and my gratitude will be boundless.</p>
<hr>
<p>Changing the ElementName didn't help. There must me something else I'm not getting.</p>
<p>I should mention that I'm testing this in Silverlight. The exact message I'm getting out of Internet Explorer is:</p>
<p><code>XamlParseException: Invalid attribute value for property Height.</code></p>
<p>This whole thing is inside a ControlTemplate. I'm making a slider control just to teach myself the concepts.</p>
| [
{
"answer_id": 7776,
"author": "Arcturus",
"author_id": 900,
"author_profile": "https://Stackoverflow.com/users/900",
"pm_score": 0,
"selected": false,
"text": "<p>First of all its a matter of casing...</p>\n\n<p>Change <pre><code>Part_Track</code></pre> to <pre><code>PART_Track</code></... | 2008/08/11 | [
"https://Stackoverflow.com/questions/7758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/93/"
] | I'm getting all learned up about binding in WPF. I'm having a lot of trouble debugging the parse errors in my xaml, though. Can somebody pretty please tell me what's wrong with this little piece? :
```
<Border Name="TrackBackground"
Margin="0"
CornerRadius="2"
Grid.Row="1"
Grid.Column="1"
Background="BlanchedAlmond"
BorderThickness="1"
Height="{TemplateBinding Height}">
<Canvas Name="PART_Track" Background="DarkSalmon" Grid.Row="1" Grid.Column="1">
<Thumb Name="ThumbKnob" Height="{Binding ElementName=Part_Track, Path=Height, Mode=OneWay}" />
</Canvas>
</Border>
```
It's the databinding that breaks. I get an `InvalidAttributeValue` exception for ThumbKnob.Height when I try to run this. I know I must be missing something fundamental. So fill me in, stackers, and my gratitude will be boundless.
---
Changing the ElementName didn't help. There must me something else I'm not getting.
I should mention that I'm testing this in Silverlight. The exact message I'm getting out of Internet Explorer is:
`XamlParseException: Invalid attribute value for property Height.`
This whole thing is inside a ControlTemplate. I'm making a slider control just to teach myself the concepts. | The ElementName property on a Binding is not supported in Silverlight.
You will notice, if you go into the code behind or inspect the Binding object in class explorer, it doesn't have a property named ElementName. |
7,773 | <p>I have a ASP.NET page with an asp:button that is not visible. I can't turn it visible with JavaScript because it is not rendered to the page.</p>
<p>What can I do to resolve this?</p>
| [
{
"answer_id": 7777,
"author": "Dave Ward",
"author_id": 60,
"author_profile": "https://Stackoverflow.com/users/60",
"pm_score": 6,
"selected": true,
"text": "<p>If you need to manipulate it on the client side, you can't use the Visible property on the server side. Instead, set its CSS ... | 2008/08/11 | [
"https://Stackoverflow.com/questions/7773",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1013/"
] | I have a ASP.NET page with an asp:button that is not visible. I can't turn it visible with JavaScript because it is not rendered to the page.
What can I do to resolve this? | If you need to manipulate it on the client side, you can't use the Visible property on the server side. Instead, set its CSS display style to "none". For example:
```
<asp:Label runat="server" id="Label1" style="display: none;" />
```
Then, you could make it visible on the client side with:
```
document.getElementById('Label1').style.display = 'inherit';
```
You could make it hidden again with:
```
document.getElementById('Label1').style.display = 'none';
```
Keep in mind that there may be issues with the ClientID being more complex than "Label1" in practice. You'll need to use the ClientID with getElementById, not the server side ID, if they differ. |
7,846 | <p>I would like to use a language that I am familiar with - Java, C#, Ruby, PHP, C/C++, although examples in any language or pseudocode are more than welcome.</p>
<p>What is the best way of splitting a large XML document into smaller sections that are still valid XML? For my purposes, I need to split them into roughly thirds or fourths, but for the sake of providing examples, splitting them into n components would be good.</p>
| [
{
"answer_id": 7853,
"author": "DannySmurf",
"author_id": 1028,
"author_profile": "https://Stackoverflow.com/users/1028",
"pm_score": 3,
"selected": true,
"text": "<p>Well of course you can always extract the top-level elements (whether this is the granularity you want is up to you). In ... | 2008/08/11 | [
"https://Stackoverflow.com/questions/7846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572/"
] | I would like to use a language that I am familiar with - Java, C#, Ruby, PHP, C/C++, although examples in any language or pseudocode are more than welcome.
What is the best way of splitting a large XML document into smaller sections that are still valid XML? For my purposes, I need to split them into roughly thirds or fourths, but for the sake of providing examples, splitting them into n components would be good. | Well of course you can always extract the top-level elements (whether this is the granularity you want is up to you). In C#, you'd use the XmlDocument class. For example, if your XML file looked something like this:
```
<Document>
<Piece>
Some text
</Piece>
<Piece>
Some other text
</Piece>
</Document>
```
then you'd use code like this to extract all of the Pieces:
```
XmlDocument doc = new XmlDocument();
doc.Load("<path to xml file>");
XmlNodeList nl = doc.GetElementsByTagName("Piece");
foreach (XmlNode n in nl)
{
// Do something with each Piece node
}
```
Once you've got the nodes, you can do something with them in your code, or you can transfer the entire text of the node to its own XML document and act on that as if it were an independent piece of XML (including saving it back to disk, etc). |
7,864 | <p>As I learn more and more about OOP, and start to implement various design patterns, I keep coming back to cases where people are hating on <a href="http://en.wikipedia.org/wiki/Active_record_pattern" rel="noreferrer">Active Record</a>.</p>
<p>Often, people say that it doesn't scale well (citing Twitter as their prime example) -- but nobody actually explains <strong><em>why</em></strong> it doesn't scale well; and / or how to achieve the pros of AR without the cons (via a similar but different pattern?)</p>
<p>Hopefully this won't turn into a holy war about design patterns -- all I want to know is ****specifically**** what's wrong with Active Record.</p>
<p>If it doesn't scale well, why not?</p>
<p>What other problems does it have?</p>
| [
{
"answer_id": 7908,
"author": "Tim Sullivan",
"author_id": 722,
"author_profile": "https://Stackoverflow.com/users/722",
"pm_score": 2,
"selected": false,
"text": "<p>The main thing that I've seen with regards to complaints about Active Record is that when you create a model around a ta... | 2008/08/11 | [
"https://Stackoverflow.com/questions/7864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/751/"
] | As I learn more and more about OOP, and start to implement various design patterns, I keep coming back to cases where people are hating on [Active Record](http://en.wikipedia.org/wiki/Active_record_pattern).
Often, people say that it doesn't scale well (citing Twitter as their prime example) -- but nobody actually explains ***why*** it doesn't scale well; and / or how to achieve the pros of AR without the cons (via a similar but different pattern?)
Hopefully this won't turn into a holy war about design patterns -- all I want to know is \*\*\*\*specifically\*\*\*\* what's wrong with Active Record.
If it doesn't scale well, why not?
What other problems does it have? | There's [ActiveRecord the Design Pattern](http://en.wikipedia.org/wiki/Active_record_pattern) and [ActiveRecord the Rails ORM Library](http://api.rubyonrails.com/classes/ActiveRecord/Base.html), and there's also a ton of knock-offs for .NET, and other languages.
These are all different things. They mostly follow that design pattern, but extend and modify it in many different ways, so before anyone says "ActiveRecord Sucks" it needs to be qualified by saying "which ActiveRecord, there's heaps?"
I'm only familiar with Rails' ActiveRecord, I'll try address all the complaints which have been raised in context of using it.
>
> @BlaM
>
>
> The problem that I see with Active Records is, that it's always just about one table
>
>
>
Code:
```
class Person
belongs_to :company
end
people = Person.find(:all, :include => :company )
```
This generates SQL with `LEFT JOIN companies on companies.id = person.company_id`, and automatically generates associated Company objects so you can do `people.first.company` and it doesn't need to hit the database because the data is already present.
>
> @pix0r
>
>
> The inherent problem with Active Record is that database queries are automatically generated and executed to populate objects and modify database records
>
>
>
Code:
```
person = Person.find_by_sql("giant complicated sql query")
```
This is discouraged as it's ugly, but for the cases where you just plain and simply need to write raw SQL, it's easily done.
>
> @Tim Sullivan
>
>
> ...and you select several instances of the model, you're basically doing a "select \* from ..."
>
>
>
Code:
```
people = Person.find(:all, :select=>'name, id')
```
This will only select the name and ID columns from the database, all the other 'attributes' in the mapped objects will just be nil, unless you manually reload that object, and so on. |
7,880 | <p>I want to open a file for reading, the C++ way. I need to be able to do it for:</p>
<ul>
<li><p>text files, which would involve some sort of read line function.</p></li>
<li><p>binary files, which would provide a way to read raw data into a <code>char*</code> buffer.</p></li>
</ul>
| [
{
"answer_id": 7886,
"author": "DannySmurf",
"author_id": 1028,
"author_profile": "https://Stackoverflow.com/users/1028",
"pm_score": 5,
"selected": true,
"text": "<p>There are three ways to do this, depending on your needs. You could use the old-school C way and call <code>fopen</code>/... | 2008/08/11 | [
"https://Stackoverflow.com/questions/7880",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/432/"
] | I want to open a file for reading, the C++ way. I need to be able to do it for:
* text files, which would involve some sort of read line function.
* binary files, which would provide a way to read raw data into a `char*` buffer. | There are three ways to do this, depending on your needs. You could use the old-school C way and call `fopen`/`fread`/`fclose`, or you could use the C++ fstream facilities (`ifstream`/`ofstream`), or if you're using MFC, use the `CFile` class, which provides functions to accomplish actual file operations.
All of these are suitable for both text and binary, though none have a specific readline functionality. What you'd most likely do instead in that case is use the fstream classes (fstream.h) and use the stream operators (<< and >>) or the read function to read/write blocks of text:
```
int nsize = 10;
std::vector<char> somedata(nsize);
ifstream myfile;
myfile.open("<path to file>");
myfile.read(somedata.data(), nsize);
myfile.close();
```
Note that, if you're using Visual Studio 2005 or higher, traditional fstream may not be available (there's a new Microsoft implementation, which is slightly different, but accomplishes the same thing). |
7,884 | <p>I've just come across this in a WHERE clause:</p>
<pre><code>AND NOT (t.id = @id)
</code></pre>
<p>How does this compare with:</p>
<pre><code>AND t.id != @id
</code></pre>
<p>Or with:</p>
<pre><code>AND t.id <> @id
</code></pre>
<p>I'd always write the latter myself, but clearly someone else thinks differently. Is one going to perform any better than the other? I know that using <code><></code> or <code>!=</code> is going to bust any hopes for using an index that I might have had, but <em>surely</em> the first approach above will suffer the same problem?</p>
| [
{
"answer_id": 7887,
"author": "Tim Sullivan",
"author_id": 722,
"author_profile": "https://Stackoverflow.com/users/722",
"pm_score": 3,
"selected": false,
"text": "<p>There will be no performance hit, both statements are perfectly equal.</p>\n\n<p>HTH</p>\n"
},
{
"answer_id": 78... | 2008/08/11 | [
"https://Stackoverflow.com/questions/7884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1030/"
] | I've just come across this in a WHERE clause:
```
AND NOT (t.id = @id)
```
How does this compare with:
```
AND t.id != @id
```
Or with:
```
AND t.id <> @id
```
I'd always write the latter myself, but clearly someone else thinks differently. Is one going to perform any better than the other? I know that using `<>` or `!=` is going to bust any hopes for using an index that I might have had, but *surely* the first approach above will suffer the same problem? | These 3 will get the same exact execution plan
```
declare @id varchar(40)
select @id = '172-32-1176'
select * from authors
where au_id <> @id
select * from authors
where au_id != @id
select * from authors
where not (au_id = @id)
```
It will also depend on the selectivity of the index itself of course. I always use au\_id <> @id myself |
7,885 | <p>Perl has OOP features, but they are somewhat rarely used. How do you create and use Perl objects with methods and properties?</p>
| [
{
"answer_id": 7960,
"author": "Bruce Alderman",
"author_id": 311,
"author_profile": "https://Stackoverflow.com/users/311",
"pm_score": 2,
"selected": false,
"text": "<p>The official tutorial on the <a href=\"http://search.cpan.org/dist/perl/pod/perltoot.pod\" rel=\"nofollow noreferrer\"... | 2008/08/11 | [
"https://Stackoverflow.com/questions/7885",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/432/"
] | Perl has OOP features, but they are somewhat rarely used. How do you create and use Perl objects with methods and properties? | You should definitely take a look at [`Moose`](http://search.cpan.org/perldoc?Moose).
```
package Point;
use Moose; # automatically turns on strict and warnings
has 'x' => (is => 'rw', isa => 'Int');
has 'y' => (is => 'rw', isa => 'Int');
sub clear {
my $self = shift;
$self->x(0);
$self->y(0);
}
```
Moose gives you (among other things) a constructor, accessor methods, and type checking for free!
So in your code you can:
```
my $p = Point->new({x=>10 , y=>20}); # Free constructor
$p->x(15); # Free setter
print $p->x(); # Free getter
$p->clear();
$p->x(15.5); # FAILS! Free type check.
```
A good starting point is [`Moose::Manual`](http://search.cpan.org/perldoc?Moose::Manual) and [`Moose::Cookbook`](http://search.cpan.org/perldoc?Moose::Cookbook)
If you just need the basic stuff you can also use [`Mouse`](http://search.cpan.org/perldoc?Mouse) which is not as complete, but without most of the compile time penalty. |
7,917 | <p>I'm importing some data from a <code>CSV</code> file, and numbers that are larger than <code>1000</code> get turned into <code>1,100</code> etc. </p>
<p>What's a good way to remove both the quotes and the comma from this so I can put it into an <code>int</code> field?</p>
<p><strong>Edit:</strong> </p>
<p>The data is actually already in a MySQL table, so I need to be able to this using SQL. Sorry for the mixup.</p>
| [
{
"answer_id": 7934,
"author": "Eldila",
"author_id": 889,
"author_profile": "https://Stackoverflow.com/users/889",
"pm_score": 0,
"selected": false,
"text": "<p>You could use this perl command.</p>\n\n<pre><code>Perl -lne 's/[,|\"]//; print' file.txt > newfile.txt\n</code></pre>\n\n<... | 2008/08/11 | [
"https://Stackoverflow.com/questions/7917",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/402/"
] | I'm importing some data from a `CSV` file, and numbers that are larger than `1000` get turned into `1,100` etc.
What's a good way to remove both the quotes and the comma from this so I can put it into an `int` field?
**Edit:**
The data is actually already in a MySQL table, so I need to be able to this using SQL. Sorry for the mixup. | Here is a good case for regular expressions. You can run a find and replace on the data either before you import (easier) or later on if the SQL import accepted those characters (not nearly as easy). But in either case, you have any number of methods to do a find and replace, be it editors, scripting languages, GUI programs, etc. Remember that you're going to want to find and replace *all* of the bad characters.
A typical regular expression to find the comma and quotes (assuming just double quotes) is: *(Blacklist)*
```
/[,"]/
```
Or, if you find something might change in the future, this regular expression, matches anything except a number or decimal point. *(Whitelist)*
```
/[^0-9\.]/
```
What has been discussed by the people above is that we don't know all of the data in your CSV file. It sounds like you want to remove the commas and quotes from all of the numbers in the CSV file. But because we don't know what else is in the CSV file we want to make sure that we don't corrupt other data. Just blindly doing a find/replace could affect other portions of the file. |
7,933 | <p>Is there some means of querying the system tables to establish which tables are using what locking schemes? I took a look at the columns in <strong>sysobjects</strong> but nothing jumped out.</p>
| [
{
"answer_id": 7935,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 0,
"selected": false,
"text": "<p>take a look at the syslockinfo and syslocks system tables\nyou can also run the sp_lock proc</p>\n"
},
{
"answer_id... | 2008/08/11 | [
"https://Stackoverflow.com/questions/7933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1030/"
] | Is there some means of querying the system tables to establish which tables are using what locking schemes? I took a look at the columns in **sysobjects** but nothing jumped out. | aargh, just being an idiot:
```
SELECT name, lockscheme(name)
FROM sysobjects
WHERE type="U"
ORDER BY name
``` |
7,937 | <p>When using IE, you cannot put an absolutely positioned div over a select input element. That's because the select element is considered an ActiveX object and is on top of every HTML element in the page.</p>
<p>I already saw people hiding selects when opening a popup div, that leads to pretty bad user experience having controls disappearing.</p>
<p>FogBugz actually had a pretty smart solution (before v6) of turning every select into text boxes when a popup was displayed. This solved the bug and tricked the user eye but the behavior was not perfect.</p>
<p>Another solution is in FogBugz 6 where they no more use the select element and recoded it everywhere.</p>
<p>Last solution I currently use is messing up the IE rendering engine and force it to render the absolutely positioned <code><div></code> as an ActiveX element too, ensuring it can live over a select element. This is achieved by placing an invisible <code><iframe></code> inside the <code><div></code> and styling it with:</p>
<pre class="lang-css prettyprint-override"><code>#MyDiv iframe
{
position: absolute;
z-index: -1;
filter: mask();
border: 0;
margin: 0;
padding: 0;
top: 0;
left: 0;
width: 9999px;
height: 9999px;
overflow: hidden;
}
</code></pre>
<p>Does anyone have an even better solution than this one?</p>
<p>EDIT: The purpose of this question is as much informative as it is a real question. I find the <code><iframe></code> trick to be a good solution, but I am still looking for improvement like removing this <em>ugly useless tag</em> that degrades accessibility.</p>
| [
{
"answer_id": 7942,
"author": "TheSmurf",
"author_id": 1975282,
"author_profile": "https://Stackoverflow.com/users/1975282",
"pm_score": 0,
"selected": false,
"text": "<p>I don't think there is. I've tried to solve this problem at my job. Hiding the select control was the best we could ... | 2008/08/11 | [
"https://Stackoverflow.com/questions/7937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/268/"
] | When using IE, you cannot put an absolutely positioned div over a select input element. That's because the select element is considered an ActiveX object and is on top of every HTML element in the page.
I already saw people hiding selects when opening a popup div, that leads to pretty bad user experience having controls disappearing.
FogBugz actually had a pretty smart solution (before v6) of turning every select into text boxes when a popup was displayed. This solved the bug and tricked the user eye but the behavior was not perfect.
Another solution is in FogBugz 6 where they no more use the select element and recoded it everywhere.
Last solution I currently use is messing up the IE rendering engine and force it to render the absolutely positioned `<div>` as an ActiveX element too, ensuring it can live over a select element. This is achieved by placing an invisible `<iframe>` inside the `<div>` and styling it with:
```css
#MyDiv iframe
{
position: absolute;
z-index: -1;
filter: mask();
border: 0;
margin: 0;
padding: 0;
top: 0;
left: 0;
width: 9999px;
height: 9999px;
overflow: hidden;
}
```
Does anyone have an even better solution than this one?
EDIT: The purpose of this question is as much informative as it is a real question. I find the `<iframe>` trick to be a good solution, but I am still looking for improvement like removing this *ugly useless tag* that degrades accessibility. | I don't know anything better than an Iframe
But it does occur to me that this could be added in JS by looking for a couple of variables
1. IE 6
2. A high Z-Index (you tend to have to set a z-index if you are floating a div over)
3. A box element
Then a script that looks for these items and just add an iframe layer would be a neat solution
Paul |
7,981 | <p>I'm working on bringing some old code from 1998 up to the 21st century. One of the first steps in the process is converting the printf statements to <a href="http://qt-project.org/doc/qt-4.8/qstring.html" rel="nofollow noreferrer">QString</a> variables. No matter how many times I look back at printf though, I always end up forgetting one thing or the other. So, for fun, let's decode it together, for ole' times sake and in the process create the first little <strong>'printf primer'</strong> for Stackoverflow.</p>
<p>In the code, I came across this little gem,</p>
<pre><code>printf("%4u\t%016.1f\t%04X\t%02X\t%1c\t%1c\t%4s", a, b, c, d, e, f, g);
</code></pre>
<p>How will the variables a, b, c, d, e, f, g be formatted?</p>
| [
{
"answer_id": 7988,
"author": "TheSmurf",
"author_id": 1975282,
"author_profile": "https://Stackoverflow.com/users/1975282",
"pm_score": 0,
"selected": false,
"text": "<p>a. decimal, four significant digits </p>\n\n<p>b. Not sure</p>\n\n<p>c. hex, minimum 4 characters </p>\n\n<p>d. Also... | 2008/08/11 | [
"https://Stackoverflow.com/questions/7981",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25/"
] | I'm working on bringing some old code from 1998 up to the 21st century. One of the first steps in the process is converting the printf statements to [QString](http://qt-project.org/doc/qt-4.8/qstring.html) variables. No matter how many times I look back at printf though, I always end up forgetting one thing or the other. So, for fun, let's decode it together, for ole' times sake and in the process create the first little **'printf primer'** for Stackoverflow.
In the code, I came across this little gem,
```
printf("%4u\t%016.1f\t%04X\t%02X\t%1c\t%1c\t%4s", a, b, c, d, e, f, g);
```
How will the variables a, b, c, d, e, f, g be formatted? | Danny is mostly right.
a. unsigned decimal, minimum 4 characters, space padded
b. floating point, minimum 16 digits before the decimal (0 padded), 1 digit after the decimal
c. hex, minimum 4 characters, 0 padded, letters are printed in upper case
d. same as above, but minimum 2 characters
e. e is assumed to be an int, converted to an unsigned char and printed
f. same as e
g. This is likely a typo, the 4 has no effect. If it were "%.4s", then a maximum of 4 characters from the string would be printed. It is interesting to note that in this case, the string does not need to be null terminated.
Edit: [jj33](https://stackoverflow.com/users/430/jj33) points out 2 errors in b and g above [here](https://stackoverflow.com/questions/7981/decoding-printf-statements-in-c-printf-primer#8051). |
7,991 | <p>I'm using the .NETCF (Windows Mobile) <code>Graphics</code> class and the <code>DrawString()</code> method to render a single character to the screen.</p>
<p>The problem is that I can't seem to get it centred properly. No matter what I set for the Y coordinate of the location of the string render, it always comes out lower than that and the larger the text size the greater the Y offset.</p>
<p>For example, at text size 12, the offset is about 4, but at 32 the offset is about 10.</p>
<p>I want the character to vertically take up most of the rectangle it's being drawn in and be centred horizontally. Here's my basic code. <code>this</code> is referencing the user control it's being drawn in.</p>
<pre><code>Graphics g = this.CreateGraphics();
float padx = ((float)this.Size.Width) * (0.05F);
float pady = ((float)this.Size.Height) * (0.05F);
float width = ((float)this.Size.Width) - 2 * padx;
float height = ((float)this.Size.Height) - 2 * pady;
float emSize = height;
g.DrawString(letter, new Font(FontFamily.GenericSansSerif, emSize, FontStyle.Regular),
new SolidBrush(Color.Black), padx, pady);
</code></pre>
<p>Yes, I know there is the label control that I could use instead and set the centring with that, but I actually do need to do this manually with the <code>Graphics</code> class.</p>
| [
{
"answer_id": 8010,
"author": "John",
"author_id": 33,
"author_profile": "https://Stackoverflow.com/users/33",
"pm_score": 2,
"selected": false,
"text": "<p>You can use an instance of the <code>StringFormat</code> object passed into the <code>DrawString</code> method to center the text.... | 2008/08/11 | [
"https://Stackoverflow.com/questions/7991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/194/"
] | I'm using the .NETCF (Windows Mobile) `Graphics` class and the `DrawString()` method to render a single character to the screen.
The problem is that I can't seem to get it centred properly. No matter what I set for the Y coordinate of the location of the string render, it always comes out lower than that and the larger the text size the greater the Y offset.
For example, at text size 12, the offset is about 4, but at 32 the offset is about 10.
I want the character to vertically take up most of the rectangle it's being drawn in and be centred horizontally. Here's my basic code. `this` is referencing the user control it's being drawn in.
```
Graphics g = this.CreateGraphics();
float padx = ((float)this.Size.Width) * (0.05F);
float pady = ((float)this.Size.Height) * (0.05F);
float width = ((float)this.Size.Width) - 2 * padx;
float height = ((float)this.Size.Height) - 2 * pady;
float emSize = height;
g.DrawString(letter, new Font(FontFamily.GenericSansSerif, emSize, FontStyle.Regular),
new SolidBrush(Color.Black), padx, pady);
```
Yes, I know there is the label control that I could use instead and set the centring with that, but I actually do need to do this manually with the `Graphics` class. | Through a combination of the suggestions I got, I came up with this:
```
private void DrawLetter()
{
Graphics g = this.CreateGraphics();
float width = ((float)this.ClientRectangle.Width);
float height = ((float)this.ClientRectangle.Width);
float emSize = height;
Font font = new Font(FontFamily.GenericSansSerif, emSize, FontStyle.Regular);
font = FindBestFitFont(g, letter.ToString(), font, this.ClientRectangle.Size);
SizeF size = g.MeasureString(letter.ToString(), font);
g.DrawString(letter, font, new SolidBrush(Color.Black), (width-size.Width)/2, 0);
}
private Font FindBestFitFont(Graphics g, String text, Font font, Size proposedSize)
{
// Compute actual size, shrink if needed
while (true)
{
SizeF size = g.MeasureString(text, font);
// It fits, back out
if (size.Height <= proposedSize.Height &&
size.Width <= proposedSize.Width) { return font; }
// Try a smaller font (90% of old size)
Font oldFont = font;
font = new Font(font.Name, (float)(font.Size * .9), font.Style);
oldFont.Dispose();
}
}
```
So far, this works flawlessly.
The only thing I would change is to move the FindBestFitFont() call to the OnResize() event so that I'm not calling it every time I draw a letter. It only needs to be called when the control size changes. I just included it in the function for completeness. |
8,004 | <p>I use <a href="http://rsync.samba.org/" rel="nofollow noreferrer">rsync</a> to synchronize files to Windows clients in a server agnostic way. What methods are available to send the progress of rsync to the parent process for display in a gui progress bar?</p>
<p>I imagine two or three choices exist. (1) Watch STDOUT (2) Watch rsync.exe log file, similar to unix <code>tail</code> (3) Watch rsync console output in memory.</p>
<p>Which one is best/preferred?</p>
| [
{
"answer_id": 8007,
"author": "Lars Mæhlum",
"author_id": 960,
"author_profile": "https://Stackoverflow.com/users/960",
"pm_score": 1,
"selected": false,
"text": "<p>.NET has a pretty straight forward way to read and watch STDOUT. <br />\nI guess this would be the cleanest way, since it... | 2008/08/11 | [
"https://Stackoverflow.com/questions/8004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1027/"
] | I use [rsync](http://rsync.samba.org/) to synchronize files to Windows clients in a server agnostic way. What methods are available to send the progress of rsync to the parent process for display in a gui progress bar?
I imagine two or three choices exist. (1) Watch STDOUT (2) Watch rsync.exe log file, similar to unix `tail` (3) Watch rsync console output in memory.
Which one is best/preferred? | For this type of tasks, I use my own [AutoIt](http://www.autoitscript.com/autoit3/) script (freeware, Windows only). The script redirects the standard output into a graphical window, displaying it with the ability to scroll back, etc (very useful in long processes like XCOPYs / PKZIPs to check if any error did happen).
I use AutoIt because it's free, very easy to use, and can compile quickly into an .EXE. I think it's an excellent alternative to a complete programming language for this type of tasks. The downside is that it's for Windows only.
```
$sCmd = "DIR E:\*.AU3 /S" ; Test command
$nAutoTimeout = 10 ; Time in seconds to close window after finish
$nDeskPct = 60 ; % of desktop size (if percent)
; $nHeight = 480 ; height/width of the main window (if fixed)
; $nWidth = 480
$sTitRun = "Executing process. Wait...." ;
$sTitDone = "Process done" ;
$sSound = @WindowsDir & "\Media\Ding.wav" ; End Sound
$sButRun = "Cancel" ; Caption of "Exec" button
$sButDone = "Close" ; Caption of "Close" button
#include <GUIConstants.au3>
#include <Constants.au3>
#Include <GuiList.au3>
Opt("GUIOnEventMode", 1)
if $nDeskPct > 0 Then
$nHeight = @DesktopHeight * ($nDeskPct / 100)
$nWidth = @DesktopWidth * ($nDeskPct / 100)
EndIf
If $CmdLine[0] > 0 Then
$sCmd = ""
For $nCmd = 1 To $CmdLine[0]
$sCmd = $sCmd & " " & $CmdLine[$nCmd]
Next
; MsgBox (1,"",$sCmd)
EndIf
; AutoItSetOption("GUIDataSeparatorChar", Chr(13)+Chr(10))
$nForm = GUICreate($sTitRun, $nWidth, $nHeight)
GUISetOnEvent($GUI_EVENT_CLOSE, "CloseForm")
$nList = GUICtrlCreateList ("", 10, 10, $nWidth - 20, $nHeight - 50, $WS_BORDER + $WS_VSCROLL)
GUICtrlSetFont (-1, 9, 0, 0, "Courier New")
$nClose = GUICtrlCreateButton ($sButRun, $nWidth - 100, $nHeight - 40, 80, 30)
GUICtrlSetOnEvent (-1, "CloseForm")
GUISetState(@SW_SHOW) ;, $nForm)
$nPID = Run(@ComSpec & " /C " & $sCmd, ".", @SW_HIDE, $STDOUT_CHILD)
; $nPID = Run(@ComSpec & " /C _RunErrl.bat " & $sCmd, ".", @SW_HIDE, $STDOUT_CHILD) ; # Con ésto devuelve el errorlevel en _ERRL.TMP
While 1
$sLine = StdoutRead($nPID)
If @error Then ExitLoop
If StringLen ($sLine) > 0 then
$sLine = StringReplace ($sLine, Chr(13), "|")
$sLine = StringReplace ($sLine, Chr(10), "")
if StringLeft($sLine, 1)="|" Then
$sLine = " " & $sLine
endif
GUICtrlSetData ($nList, $sLine)
_GUICtrlListSelectIndex ($nList, _GUICtrlListCount ($nList) - 1)
EndIf
Wend
$sLine = " ||"
GUICtrlSetData ($nList, $sLine)
_GUICtrlListSelectIndex ($nList, _GUICtrlListCount ($nList) - 1)
GUICtrlSetData ($nClose, $sButDone)
WinSetTitle ($sTitRun, "", $sTitDone)
If $sSound <> "" Then
SoundPlay ($sSound)
EndIf
$rInfo = DllStructCreate("uint;dword") ; # LASTINPUTINFO
DllStructSetData($rInfo, 1, DllStructGetSize($rInfo));
DllCall("user32.dll", "int", "GetLastInputInfo", "ptr", DllStructGetPtr($rInfo))
$nLastInput = DllStructGetData($rInfo, 2)
$nTime = TimerInit()
While 1
If $nAutoTimeout > 0 Then
DllCall("user32.dll", "int", "GetLastInputInfo", "ptr", DllStructGetPtr($rInfo))
If DllStructGetData($rInfo, 2) <> $nLastInput Then
; Tocó una tecla
$nAutoTimeout = 0
EndIf
EndIf
If $nAutoTimeout > 0 And TimerDiff ($nTime) > $nAutoTimeOut * 1000 Then
ExitLoop
EndIf
Sleep (100)
Wend
Func CloseForm()
Exit
EndFunc
``` |
8,021 | <p>I'd like to allow a user to set up an SSH tunnel to a particular machine on a particular port (say, 5000), but I want to restrict this user as much as possible. (Authentication will be with public/private keypair).</p>
<p>I know I need to edit the relevant ~/.ssh/authorized_keys file, but I'm not sure exactly what content to put in there (other than the public key).</p>
| [
{
"answer_id": 8023,
"author": "Michael Pryor",
"author_id": 245,
"author_profile": "https://Stackoverflow.com/users/245",
"pm_score": -1,
"selected": false,
"text": "<p>See <a href=\"http://www.networknewz.com/networknewz-10-20030707AuthenticatingbyPublicKeyOpenSSH.html\" rel=\"nofollow... | 2008/08/11 | [
"https://Stackoverflow.com/questions/8021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/742/"
] | I'd like to allow a user to set up an SSH tunnel to a particular machine on a particular port (say, 5000), but I want to restrict this user as much as possible. (Authentication will be with public/private keypair).
I know I need to edit the relevant ~/.ssh/authorized\_keys file, but I'm not sure exactly what content to put in there (other than the public key). | On Ubuntu 11.10, I found I could block ssh commands, sent with and without -T, and block scp copying, while allowing port forwarding to go through.
Specifically I have a redis-server on "somehost" bound to localhost:6379 that I wish to share securely via ssh tunnels to other hosts that have a keyfile and will ssh in with:
```
$ ssh -i keyfile.rsa -T -N -L 16379:localhost:6379 someuser@somehost
```
This will cause the redis-server, "localhost" port 6379 on "somehost" to appear locally on the host executing the ssh command, remapped to "localhost" port 16379.
On the remote "somehost" Here is what I used for authorized\_keys:
```
cat .ssh/authorized_keys (portions redacted)
no-pty,no-X11-forwarding,permitopen="localhost:6379",command="/bin/echo do-not-send-commands" ssh-rsa rsa-public-key-code-goes-here keyuser@keyhost
```
The no-pty trips up most ssh attempts that want to open a terminal.
The permitopen explains what ports are allowed to be forwarded, in this case port 6379 the redis-server port I wanted to forward.
The command="/bin/echo do-not-send-commands" echoes back "do-not-send-commands" if someone or something does manage to send commands to the host via ssh -T or otherwise.
From a recent Ubuntu `man sshd`, authorized\_keys / command is described as follows:
>
> command="command"
> Specifies that the command is executed whenever this key is used
> for authentication. The command supplied by the user (if any) is
> ignored.
>
>
>
Attempts to use scp secure file copying will also fail with an echo of "do-not-send-commands" I've found sftp also fails with this configuration.
I think the restricted shell suggestion, made in some previous answers, is also a good idea.
Also, I would agree that everything detailed here could be determined from reading "man sshd" and searching therein for "authorized\_keys" |
8,042 | <p>The new extensions in .Net 3.5 allow functionality to be split out from interfaces.</p>
<p>For instance in .Net 2.0</p>
<pre><code>public interface IHaveChildren {
string ParentType { get; }
int ParentId { get; }
List<IChild> GetChildren()
}
</code></pre>
<p>Can (in 3.5) become:</p>
<pre><code>public interface IHaveChildren {
string ParentType { get; }
int ParentId { get; }
}
public static class HaveChildrenExtension {
public static List<IChild> GetChildren( this IHaveChildren ) {
//logic to get children by parent type and id
//shared for all classes implementing IHaveChildren
}
}
</code></pre>
<p>This seems to me to be a better mechanism for many interfaces. They no longer need an abstract base to share this code, and functionally the code works the same. This could make the code more maintainable and easier to test.</p>
<p>The only disadvantage being that an abstract bases implementation can be virtual, but can that be worked around (would an instance method hide an extension method with the same name? would it be confusing code to do so?)</p>
<p>Any other reasons not to regularly use this pattern?</p>
<hr>
<p>Clarification:</p>
<p>Yeah, I see the tendency with extension methods is to end up with them everywhere. I'd be particularly careful having any on .Net value types without a great deal of peer review (I think the only one we have on a string is a <code>.SplitToDictionary()</code> - similar to <code>.Split()</code> but taking a key-value delimiter too)</p>
<p>I think there's a whole best practice debate there ;-)</p>
<p>(Incidentally: DannySmurf, your PM sounds scary.)</p>
<p>I'm specifically asking here about using extension methods where previously we had interface methods.</p>
<hr>
<p>I'm trying to avoid lots of levels of abstract base classes - the classes implementing these models mostly already have base classes. I think this model could be more maintainable and less overly-coupled than adding further object hierarchies.</p>
<p>Is this what MS has done to IEnumerable and IQueryable for Linq?</p>
| [
{
"answer_id": 8054,
"author": "TheSmurf",
"author_id": 1975282,
"author_profile": "https://Stackoverflow.com/users/1975282",
"pm_score": 0,
"selected": false,
"text": "<p>One problem I can see is that, in a large company, this pattern could allow the code to become difficult (if not imp... | 2008/08/11 | [
"https://Stackoverflow.com/questions/8042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/905/"
] | The new extensions in .Net 3.5 allow functionality to be split out from interfaces.
For instance in .Net 2.0
```
public interface IHaveChildren {
string ParentType { get; }
int ParentId { get; }
List<IChild> GetChildren()
}
```
Can (in 3.5) become:
```
public interface IHaveChildren {
string ParentType { get; }
int ParentId { get; }
}
public static class HaveChildrenExtension {
public static List<IChild> GetChildren( this IHaveChildren ) {
//logic to get children by parent type and id
//shared for all classes implementing IHaveChildren
}
}
```
This seems to me to be a better mechanism for many interfaces. They no longer need an abstract base to share this code, and functionally the code works the same. This could make the code more maintainable and easier to test.
The only disadvantage being that an abstract bases implementation can be virtual, but can that be worked around (would an instance method hide an extension method with the same name? would it be confusing code to do so?)
Any other reasons not to regularly use this pattern?
---
Clarification:
Yeah, I see the tendency with extension methods is to end up with them everywhere. I'd be particularly careful having any on .Net value types without a great deal of peer review (I think the only one we have on a string is a `.SplitToDictionary()` - similar to `.Split()` but taking a key-value delimiter too)
I think there's a whole best practice debate there ;-)
(Incidentally: DannySmurf, your PM sounds scary.)
I'm specifically asking here about using extension methods where previously we had interface methods.
---
I'm trying to avoid lots of levels of abstract base classes - the classes implementing these models mostly already have base classes. I think this model could be more maintainable and less overly-coupled than adding further object hierarchies.
Is this what MS has done to IEnumerable and IQueryable for Linq? | I think the judicious use of extension methods put interfaces on a more equatable position with (abstract) base classes.
**Versioning.** One advantage base classes have over interfaces is that you can easily add new virtual members in a later version, whereas adding members to an interface will break implementers built against the old version of the library. Instead, a new version of the interface with the new members needs to be created, and the library will have to work around or limit access to legacy objects only implementing the original interface.
As a concrete example, the first version of a library might define an interface like so:
```
public interface INode {
INode Root { get; }
List<INode> GetChildren( );
}
```
Once the library has released, we cannot modify the interface without breaking current users. Instead, in the next release we would need to define a new interface to add additional functionalty:
```
public interface IChildNode : INode {
INode Parent { get; }
}
```
However, only users of the new library will be able to implement the new interface. In order to work with legacy code, we need to adapt the old implementation, which an extension method can handle nicely:
```
public static class NodeExtensions {
public INode GetParent( this INode node ) {
// If the node implements the new interface, call it directly.
var childNode = node as IChildNode;
if( !object.ReferenceEquals( childNode, null ) )
return childNode.Parent;
// Otherwise, fall back on a default implementation.
return FindParent( node, node.Root );
}
}
```
Now all users of the new library can treat both legacy and modern implementations identically.
**Overloads.** Another area where extension methods can be useful is in providing overloads for interface methods. You might have a method with several parameters to control its action, of which only the first one or two are important in the 90% case. Since C# does not allow setting default values for parameters, users either have to call the fully parameterized method every time, or every implementation must implement the trivial overloads for the core method.
Instead extension methods can be used to provide the trivial overload implementations:
```
public interface ILongMethod {
public bool LongMethod( string s, double d, int i, object o, ... );
}
...
public static LongMethodExtensions {
public bool LongMethod( this ILongMethod lm, string s, double d ) {
lm.LongMethod( s, d, 0, null );
}
...
}
```
Please note that both of these cases are written in terms of the operations provided by the interfaces, and involve trivial or well-known default implementations. That said, you can only inherit from a class once, and the targeted use of extension methods can provide a valuable way to deal with some of the niceties provided by base classes that interfaces lack :)
---
**Edit:** A related post by Joe Duffy: [Extension methods as default interface method implementations](http://joeduffyblog.com/2010/02/09/extension-methods-as-default-interface-method-implementations/) |
8,128 | <p>How do I calculate the CRC32 (Cyclic Redundancy Checksum) of a string in .NET?</p>
| [
{
"answer_id": 8130,
"author": "Pete",
"author_id": 76,
"author_profile": "https://Stackoverflow.com/users/76",
"pm_score": 6,
"selected": true,
"text": "<p>This guy seems to have your answer.</p>\n\n<blockquote>\n <p><a href=\"https://damieng.com/blog/2006/08/08/calculating_crc32_in_c_... | 2008/08/11 | [
"https://Stackoverflow.com/questions/8128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17/"
] | How do I calculate the CRC32 (Cyclic Redundancy Checksum) of a string in .NET? | This guy seems to have your answer.
>
> <https://damieng.com/blog/2006/08/08/calculating_crc32_in_c_and_net>
>
>
>
And in case the blog ever goes away or breaks the url, here's the github link:
>
> <https://github.com/damieng/DamienGKit/blob/master/CSharp/DamienG.Library/Security/Cryptography/Crc32.cs>
>
>
>
---
Usage of the Crc32 class from the blog post:
```
Crc32 crc32 = new Crc32();
String hash = String.Empty;
using (FileStream fs = File.Open("c:\\myfile.txt", FileMode.Open))
foreach (byte b in crc32.ComputeHash(fs)) hash += b.ToString("x2").ToLower();
Console.WriteLine("CRC-32 is {0}", hash);
``` |
8,145 | <p>How can I find the high water mark (the historical maximum number of concurrent users) in an <strong>oracle database (9i)</strong>.</p>
| [
{
"answer_id": 8161,
"author": "ninesided",
"author_id": 1030,
"author_profile": "https://Stackoverflow.com/users/1030",
"pm_score": 4,
"selected": true,
"text": "<p>This should do the trick:</p>\n\n<pre><code>SELECT sessions_highwater FROM v$license;\n</code></pre>\n"
},
{
"answ... | 2008/08/11 | [
"https://Stackoverflow.com/questions/8145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/685/"
] | How can I find the high water mark (the historical maximum number of concurrent users) in an **oracle database (9i)**. | This should do the trick:
```
SELECT sessions_highwater FROM v$license;
``` |
8,147 | <p>Using <a href="http://www.codeplex.com/aspnet" rel="nofollow noreferrer">preview 4</a> of <a href="http://asp.net/mvc" rel="nofollow noreferrer">ASP.NET MVC</a>
Code like:</p>
<pre><code><%= Html.CheckBox( "myCheckBox", "Click Here", "True", false ) %>
</code></pre>
<p>only outputs:</p>
<pre><code><input type="checkbox" value="True" name="myCheckBox" />
</code></pre>
<p>There is a <code>name</code> there for the form post back but no <code>id</code> for javascript or labels :-(</p>
<p>I was hoping that changing it to:</p>
<pre><code>Html.CheckBox( "myCheckBox", "Click Here",
"True", false, new { id="myCheckBox" } )
</code></pre>
<p>would work - but instead I get an exception:</p>
<pre><code>System.ArgumentException: An item with the same key has already been added.
</code></pre>
<p>As if there was already an id somewhere in a collection somewhere - I'm stumped!</p>
<p>The full exception for anyone interested follows (hey - wouldn't it be nice to attach files in here):</p>
<pre>System.ArgumentException: An item with the same key has already been added.
at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
at System.Web.Routing.RouteValueDictionary.Add(String key, Object value)
at System.Web.Mvc.TagBuilder2.CreateInputTag(HtmlInputType inputType, String name, RouteValueDictionary attributes)
at System.Web.Mvc.CheckBoxBuilder.CheckBox(String htmlName, RouteValueDictionary htmlAttributes)
at System.Web.Mvc.CheckBoxBuilder.CheckBox(String htmlName, String text, String value, Boolean isChecked, RouteValueDictionary htmlAttributes)
at System.Web.Mvc.CheckBoxExtensions.CheckBox(HtmlHelper helper, String htmlName, String text, String value, Boolean isChecked, Object htmlAttributes)
at ASP.views_account_termsandconditions_ascx.__Render__control1(HtmlTextWriter __w, Control parameterContainer) in c:\dev\myProject\Views\Account\Edit.ascx:line 108</pre>
| [
{
"answer_id": 8171,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 0,
"selected": false,
"text": "<p>Apparently this is a bug. Because they are adding it to potential rendering values, they just forgot to include it. I wo... | 2008/08/11 | [
"https://Stackoverflow.com/questions/8147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/193/"
] | Using [preview 4](http://www.codeplex.com/aspnet) of [ASP.NET MVC](http://asp.net/mvc)
Code like:
```
<%= Html.CheckBox( "myCheckBox", "Click Here", "True", false ) %>
```
only outputs:
```
<input type="checkbox" value="True" name="myCheckBox" />
```
There is a `name` there for the form post back but no `id` for javascript or labels :-(
I was hoping that changing it to:
```
Html.CheckBox( "myCheckBox", "Click Here",
"True", false, new { id="myCheckBox" } )
```
would work - but instead I get an exception:
```
System.ArgumentException: An item with the same key has already been added.
```
As if there was already an id somewhere in a collection somewhere - I'm stumped!
The full exception for anyone interested follows (hey - wouldn't it be nice to attach files in here):
```
System.ArgumentException: An item with the same key has already been added.
at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
at System.Web.Routing.RouteValueDictionary.Add(String key, Object value)
at System.Web.Mvc.TagBuilder2.CreateInputTag(HtmlInputType inputType, String name, RouteValueDictionary attributes)
at System.Web.Mvc.CheckBoxBuilder.CheckBox(String htmlName, RouteValueDictionary htmlAttributes)
at System.Web.Mvc.CheckBoxBuilder.CheckBox(String htmlName, String text, String value, Boolean isChecked, RouteValueDictionary htmlAttributes)
at System.Web.Mvc.CheckBoxExtensions.CheckBox(HtmlHelper helper, String htmlName, String text, String value, Boolean isChecked, Object htmlAttributes)
at ASP.views_account_termsandconditions_ascx.__Render__control1(HtmlTextWriter __w, Control parameterContainer) in c:\dev\myProject\Views\Account\Edit.ascx:line 108
``` | Try this:
```
<%= Html.CheckBox("myCheckbox", "Click here", "True", false, new {_id ="test" })%>
```
For any keyword you can use an underscore before the name of the attribute. Instead of class you use \_class. Since class is a keyword in C#, and also the name of the attribute in HTML. Now, "id" isn't a keyword in C#, but perhaps it is in another .NET language that they want to support. From what I can tell, it's not a keyword in VB.NET, F#, or Ruby so maybe it is a mistake that they force you to use an underscore with it. |
8,154 | <p>I'm using Pylons (a python framework) to serve a simple web application, but it seems to die from time to time, with this in the error log: <code>(2006, 'MySQL server has gone away')</code></p>
<p>I did a bit of checking, and saw that this was because the connections to MySQL were not being renewed. This shouldn't be a problem though, because the <code>sqlalchemy.pool_recycle</code> in the config file should automatically keep it alive. The default was <code>3600</code>, but I dialed it back to <code>1800</code> because of this problem. It helped a bit, but <code>3600</code> <em>should</em> be fine according to the docs. The errors still happen semi-regularly. I don't want to lower it too much though and DOS my own database :).</p>
<p>Maybe something in my MySQL config is goofy? Not sure where to look exactly.</p>
<p>Other relevant details:</p>
<pre><code> Python 2.5
Pylons: 0.9.6.2 (w/ sql_alchemy)
MySQL: 5.0.51
</code></pre>
| [
{
"answer_id": 15261,
"author": "Jon Bright",
"author_id": 1813,
"author_profile": "https://Stackoverflow.com/users/1813",
"pm_score": 2,
"selected": false,
"text": "<p>You might want to check MySQL's timeout variables:</p>\n\n<pre><code>show variables like '%timeout%';\n</code></pre>\n\... | 2008/08/11 | [
"https://Stackoverflow.com/questions/8154",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/736/"
] | I'm using Pylons (a python framework) to serve a simple web application, but it seems to die from time to time, with this in the error log: `(2006, 'MySQL server has gone away')`
I did a bit of checking, and saw that this was because the connections to MySQL were not being renewed. This shouldn't be a problem though, because the `sqlalchemy.pool_recycle` in the config file should automatically keep it alive. The default was `3600`, but I dialed it back to `1800` because of this problem. It helped a bit, but `3600` *should* be fine according to the docs. The errors still happen semi-regularly. I don't want to lower it too much though and DOS my own database :).
Maybe something in my MySQL config is goofy? Not sure where to look exactly.
Other relevant details:
```
Python 2.5
Pylons: 0.9.6.2 (w/ sql_alchemy)
MySQL: 5.0.51
``` | I think I fixed it. It's turns out I had a simple config error. My ini file read:
```
sqlalchemy.default.url = [connection string here]
sqlalchemy.pool_recycle = 1800
```
The problem is that my `environment.py` file declared that the engine would only map keys with the prefix: `sqlalchemy.default` so `pool_recycle` was ignored.
The solution is to simply change the second line in the ini to:
```
sqlalchemy.default.pool_recycle = 1800
``` |
8,213 | <p>I need to import a csv file into <strong>Firebird</strong> and I've spent a couple of hours trying out some tools and none fit my needs.</p>
<p>The main problem is that all the tools I've been trying like <a href="http://www.sqlmanager.net/products/ibfb/dataimport" rel="noreferrer">EMS Data Import</a> and <a href="http://www.sqlmaestro.com/products/firebird/datawizard/help/06_01_05_csv/" rel="noreferrer">Firebird Data Wizard</a> expect that my CSV file contains all the information needed by my Table.</p>
<p>I need to write some custom SQL in the insert statement, for example, I have a CSV file with the city name, but as my database already has all the cities in another table (normalized), I need to write a subselect in the insert statement to lookup for the city and write its ID, also I have a stored procedure to cread GUIDS.</p>
<p>My insert statement would be something like this:</p>
<pre><code>INSERT INTO PERSON (ID, NAME, CITY_ID) VALUES((SELECT NEW_GUID FROM CREATE_GUID), :NAME, (SELECT CITY_ID FROM CITY WHERE NAME = :CITY_NAME)
</code></pre>
<p>How can I approach this?</p>
| [
{
"answer_id": 8216,
"author": "Vaibhav",
"author_id": 380,
"author_profile": "https://Stackoverflow.com/users/380",
"pm_score": 3,
"selected": false,
"text": "<p>Well, if it's a CSV, and it this is a one time process, open up the file in Excel, and then write formulas to populate your d... | 2008/08/11 | [
"https://Stackoverflow.com/questions/8213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/727/"
] | I need to import a csv file into **Firebird** and I've spent a couple of hours trying out some tools and none fit my needs.
The main problem is that all the tools I've been trying like [EMS Data Import](http://www.sqlmanager.net/products/ibfb/dataimport) and [Firebird Data Wizard](http://www.sqlmaestro.com/products/firebird/datawizard/help/06_01_05_csv/) expect that my CSV file contains all the information needed by my Table.
I need to write some custom SQL in the insert statement, for example, I have a CSV file with the city name, but as my database already has all the cities in another table (normalized), I need to write a subselect in the insert statement to lookup for the city and write its ID, also I have a stored procedure to cread GUIDS.
My insert statement would be something like this:
```
INSERT INTO PERSON (ID, NAME, CITY_ID) VALUES((SELECT NEW_GUID FROM CREATE_GUID), :NAME, (SELECT CITY_ID FROM CITY WHERE NAME = :CITY_NAME)
```
How can I approach this? | It's a bit crude - but for one off jobs, I sometimes use Excel.
If you import the CSV file into Excel, you can create a formula which creates an INSERT statement by using string concatenation in the formula. So - if your CSV file has 3 columns that appear in columns A, B, and C in Excel, you could write a formula like...
```
="INSERT INTO MyTable (Col1, Col2, Col3) VALUES (" & A1 & ", " & B1 & ", " & C1 & ")"
```
Then you can replicate the formula down all of your rows, and copy, and paste the answer into a text file to run against your database.
Like I say - it's crude - but it can be quite a 'quick and dirty' way of getting a job done! |
8,236 | <p>How can I figure out the size of a file, in bytes?</p>
<pre><code>#include <stdio.h>
unsigned int fsize(char* file){
//what goes here?
}
</code></pre>
| [
{
"answer_id": 8241,
"author": "Ecton",
"author_id": 457,
"author_profile": "https://Stackoverflow.com/users/457",
"pm_score": 2,
"selected": false,
"text": "<p>If you're fine with using the std c library:</p>\n\n<pre><code>#include <sys/stat.h>\noff_t fsize(char *file) {\n stru... | 2008/08/11 | [
"https://Stackoverflow.com/questions/8236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/432/"
] | How can I figure out the size of a file, in bytes?
```
#include <stdio.h>
unsigned int fsize(char* file){
//what goes here?
}
``` | On Unix-like systems, you can use POSIX system calls: [`stat` on a path](https://en.wikipedia.org/wiki/Stat_(system_call)), or `fstat` on an already-open file descriptor (POSIX [man page](https://man7.org/linux/man-pages/man3/fstat.3p.html), Linux [man page](https://man7.org/linux/man-pages/man2/lstat.2.html)).
(Get a file descriptor from `open(2)`, or `fileno(FILE*)` on a stdio stream).
Based on NilObject's code:
```
#include <sys/stat.h>
#include <sys/types.h>
off_t fsize(const char *filename) {
struct stat st;
if (stat(filename, &st) == 0)
return st.st_size;
return -1;
}
```
Changes:
* Made the filename argument a `const char`.
* Corrected the `struct stat` definition, which was missing the variable name.
* Returns `-1` on error instead of `0`, which would be ambiguous for an empty file. `off_t` is a signed type so this is possible.
If you want `fsize()` to print a message on error, you can use this:
```
#include <sys/stat.h>
#include <sys/types.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
off_t fsize(const char *filename) {
struct stat st;
if (stat(filename, &st) == 0)
return st.st_size;
fprintf(stderr, "Cannot determine size of %s: %s\n",
filename, strerror(errno));
return -1;
}
```
On 32-bit systems you should compile this with the option `-D_FILE_OFFSET_BITS=64`, otherwise `off_t` will only hold values up to 2 GB. See the "Using LFS" section of [Large File Support in Linux](http://www.suse.de/%7Eaj/linux_lfs.html) for details. |
8,348 | <p>Imagine an object you are working with has a collection of other objects associated with it, for example, the Controls collection on a WinForm. You want to check for a certain object in the collection, but the collection doesn't have a <code>Contains()</code> method. There are several ways of dealing with this.</p>
<ul>
<li>Implement your own <code>Contains()</code> method by looping through all items in the collection to see if one of them is what you are looking for. This seems to be the "best practice" approach.</li>
<li>I recently came across some code where instead of a loop, there was an attempt to access the object inside a try statement, as follows:</li>
</ul>
<blockquote>
<pre><code>try
{
Object aObject = myCollection[myObject];
}
catch(Exception e)
{
//if this is thrown, then the object doesn't exist in the collection
}
</code></pre>
</blockquote>
<p>My question is how poor of a programming practice do you consider the second option be and why? How is the performance of it compared to a loop through the collection?</p>
| [
{
"answer_id": 8350,
"author": "Ryan Fox",
"author_id": 55,
"author_profile": "https://Stackoverflow.com/users/55",
"pm_score": 0,
"selected": false,
"text": "<p>If, while writing your code, you expect this object to be in the collection, and then during runtime you find that it isn't, I... | 2008/08/11 | [
"https://Stackoverflow.com/questions/8348",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/940/"
] | Imagine an object you are working with has a collection of other objects associated with it, for example, the Controls collection on a WinForm. You want to check for a certain object in the collection, but the collection doesn't have a `Contains()` method. There are several ways of dealing with this.
* Implement your own `Contains()` method by looping through all items in the collection to see if one of them is what you are looking for. This seems to be the "best practice" approach.
* I recently came across some code where instead of a loop, there was an attempt to access the object inside a try statement, as follows:
>
>
> ```
> try
> {
> Object aObject = myCollection[myObject];
> }
> catch(Exception e)
> {
> //if this is thrown, then the object doesn't exist in the collection
> }
>
> ```
>
>
My question is how poor of a programming practice do you consider the second option be and why? How is the performance of it compared to a loop through the collection? | I would have to say that this is pretty bad practice. Whilst some people might be happy to say that looping through the collection is less efficient to throwing an exception, there is an overhead to throwing an exception. I would also question why you are using a collection to access an item by key when you would be better suited to using a dictionary or hashtable.
My main problem with this code however, is that regardless of the type of exception thrown, you are always going to be left with the same result.
For example, an exception could be thrown because the object doesn't exist in the collection, or because the collection itself is null or because you can't cast myCollect[myObject] to aObject.
All of these exceptions will get handled in the same way, which may not be your intention.
These are a couple of nice articles on when and where it is usally considered acceptable to throw exceptions:
* [Foundations of Programming](http://codebetter.com/blogs/karlseguin/archive/2008/05/29/foundations-of-programming-pt-8-back-to-basics-exceptions.aspx)
* [Throwing exceptions in c#](http://www.blackwasp.co.uk/CSharpThrowingExceptions.aspx)
I particularly like this quote from the second article:
>
> It is important that exceptions are
> thrown only when an unexpected or
> invalid activity occurs that prevents
> a method from completing its normal
> function. Exception handling
> introduces a small overhead and lowers
> performance so should not be used for
> normal program flow instead of
> conditional processing. It can also be
> difficult to maintain code that
> misuses exception handling in this
> way.
>
>
> |
8,355 | <p>What is the best way to transparently rewrite a URL over an SSL connection with Apache 2.2?</p>
<p>Apache 2 does not natively support multiple name-based virtual hosts for an SSL connection and I have heard that mod_rewrite can help with this. I would like to do something like this:</p>
<p>I have set up the server so that the sites can be accessed by</p>
<p><a href="https://secure.example.com/dbadmin" rel="nofollow noreferrer">https://secure.example.com/dbadmin</a></p>
<p>but I would like to have this as <a href="https://dbadmin.example.com" rel="nofollow noreferrer">https://dbadmin.example.com</a></p>
<p>How do I set it up so that the Rewrite rule will rewrite dbadmin.example.com to secure.example.com/dbadmin, but without displaying the rewrite on the client's address bar (i.e. the client will still just see dbadmin.example.com), all over https?</p>
| [
{
"answer_id": 8389,
"author": "UnkwnTech",
"author_id": 115,
"author_profile": "https://Stackoverflow.com/users/115",
"pm_score": 0,
"selected": false,
"text": "<p>There is apaches mod_rewrite, or you could setup apache to direct <a href=\"https://dbadmin.example.com\" rel=\"nofollow no... | 2008/08/12 | [
"https://Stackoverflow.com/questions/8355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/277/"
] | What is the best way to transparently rewrite a URL over an SSL connection with Apache 2.2?
Apache 2 does not natively support multiple name-based virtual hosts for an SSL connection and I have heard that mod\_rewrite can help with this. I would like to do something like this:
I have set up the server so that the sites can be accessed by
<https://secure.example.com/dbadmin>
but I would like to have this as <https://dbadmin.example.com>
How do I set it up so that the Rewrite rule will rewrite dbadmin.example.com to secure.example.com/dbadmin, but without displaying the rewrite on the client's address bar (i.e. the client will still just see dbadmin.example.com), all over https? | Configure a single VirtualHost to serve both secure.example.com and dbadmin.example.com (making it the only \*:443 VirtualHost achieves this). You can then use [mod\_rewrite](http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html) to adjust the URI for requests to dbadmin.example.com:
```
<VirtualHost *:443>
ServerName secure.example.com
ServerAlias dbadmin.example.com
RewriteEngine on
RewriteCond %{SERVER_NAME} dbadmin.example.com
RewriteRule !/dbadmin(.*)$ /dbadmin$1
</VirtualHost>
```
Your SSL certificate will need to be valid for both secure.example.com and dbadmin.example.com. It can be a wildcard certificate as mentioned by Terry Lorber, or you can use the [subjectAltName](http://wiki.cacert.org/wiki/VhostTaskForce#A1.Way.3ASubjectAltNameOnly) field to add additional host names.
If you're having trouble, first set it up on `<VirtualHost *>` and check that it works without SSL. The SSL connection and certificate is a separate layer of complexity that you can set up after the URI rewriting is working. |
8,371 | <p>How do you redirect HTTPS to HTTP?. That is, the opposite of what (seemingly) everyone teaches.</p>
<p>I have a server on HTTPS for which I paid an SSL certification for and a mirror for which I haven't and keep around for just for emergencies so it doesn't merit getting a certification for.</p>
<p>On my client's desktops I have SOME shortcuts which point to <code>http://production_server</code> and <code>https://production_server</code> (both work). However, I know that if my production server goes down, then DNS forwarding kicks in and those clients which have "https" on their shortcut will be staring at <code>https://mirror_server</code> (which doesn't work) and a big fat Internet Explorer 7 red screen of uneasyness for my company. </p>
<p>Unfortunately, I can't just switch this around at the client level. These users are very computer illiterate: and are very likely to freak out from seeing HTTPS "insecurity" errors (especially the way Firefox 3 and Internet Explorer 7 handle it nowadays: FULL STOP, kind of thankfully, but not helping me here LOL).</p>
<p>It's <a href="http://www.cyberciti.biz/tips/howto-apache-force-https-secure-connections.html" rel="noreferrer">very easy</a> <a href="http://bytes.com/forum/thread54801.html" rel="noreferrer">to find</a> <a href="http://support.jodohost.com/showthread.php?t=6678" rel="noreferrer">Apache solutions</a> for <a href="http://www.google.com/search?q=https+redirection&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a" rel="noreferrer">http->https redirection</a>, but for the life of me I can't do the opposite.</p>
<p>Ideas?</p>
| [
{
"answer_id": 8380,
"author": "ejunker",
"author_id": 796,
"author_profile": "https://Stackoverflow.com/users/796",
"pm_score": 8,
"selected": true,
"text": "<p>This has not been tested but I think this should work using mod_rewrite</p>\n\n<pre><code>RewriteEngine On\nRewriteCond %{HTTP... | 2008/08/12 | [
"https://Stackoverflow.com/questions/8371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/547/"
] | How do you redirect HTTPS to HTTP?. That is, the opposite of what (seemingly) everyone teaches.
I have a server on HTTPS for which I paid an SSL certification for and a mirror for which I haven't and keep around for just for emergencies so it doesn't merit getting a certification for.
On my client's desktops I have SOME shortcuts which point to `http://production_server` and `https://production_server` (both work). However, I know that if my production server goes down, then DNS forwarding kicks in and those clients which have "https" on their shortcut will be staring at `https://mirror_server` (which doesn't work) and a big fat Internet Explorer 7 red screen of uneasyness for my company.
Unfortunately, I can't just switch this around at the client level. These users are very computer illiterate: and are very likely to freak out from seeing HTTPS "insecurity" errors (especially the way Firefox 3 and Internet Explorer 7 handle it nowadays: FULL STOP, kind of thankfully, but not helping me here LOL).
It's [very easy](http://www.cyberciti.biz/tips/howto-apache-force-https-secure-connections.html) [to find](http://bytes.com/forum/thread54801.html) [Apache solutions](http://support.jodohost.com/showthread.php?t=6678) for [http->https redirection](http://www.google.com/search?q=https+redirection&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a), but for the life of me I can't do the opposite.
Ideas? | This has not been tested but I think this should work using mod\_rewrite
```
RewriteEngine On
RewriteCond %{HTTPS} on
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI}
``` |
8,441 | <p>I'm using <code>.htaccess</code> and <code>mod_rewrite</code> to point to files that reside behind the DocumentRoot. My folder structure looks like this:</p>
<pre><code>home/
webroot/
other_files/
</code></pre>
<p>I have a <code>.htaccess</code> file in webroot with the following content:</p>
<pre>
RewriteEngine on
RewriteRule ^(.*)$ /home/other_files/$1
</pre>
<p>If I try to access <a href="http://example.com/file.html" rel="noreferrer">http://example.com/file.html</a> I receive the following error: </p>
<blockquote>
<p>The requested URL /home/other_files/file.html was not found on this server. </p>
</blockquote>
<p>Is it even possible to load files that are behind the DocumentRoot? If so, can someone point me in the right direction?</p>
| [
{
"answer_id": 8454,
"author": "Ryan Ahearn",
"author_id": 75,
"author_profile": "https://Stackoverflow.com/users/75",
"pm_score": 5,
"selected": true,
"text": "<p>I believe you need to add a section with </p>\n\n<pre><code><Directory \"/home/other_files\">\n (options)\n</Direc... | 2008/08/12 | [
"https://Stackoverflow.com/questions/8441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/57/"
] | I'm using `.htaccess` and `mod_rewrite` to point to files that reside behind the DocumentRoot. My folder structure looks like this:
```
home/
webroot/
other_files/
```
I have a `.htaccess` file in webroot with the following content:
```
RewriteEngine on
RewriteRule ^(.*)$ /home/other_files/$1
```
If I try to access <http://example.com/file.html> I receive the following error:
>
> The requested URL /home/other\_files/file.html was not found on this server.
>
>
>
Is it even possible to load files that are behind the DocumentRoot? If so, can someone point me in the right direction? | I believe you need to add a section with
```
<Directory "/home/other_files">
(options)
</Directory>
```
to your server configuration before apache will be able to serve anything from it. For an example, my DocumentRoot is /var/www but there is this section in the default available site:
```
Alias /doc/ "/usr/share/doc/"
<Directory "/usr/share/doc/">
Options Indexes MultiViews FollowSymLinks
AllowOverride None
Order deny,allow
Deny from all
Allow from 127.0.0.0/255.0.0.0 ::1/128
</Directory>
```
You could then rewrite a URL to go to /doc/ and the server would know where to get the files from. |
8,447 | <p>From time to time I see an enum like the following:</p>
<pre><code>[Flags]
public enum Options
{
None = 0,
Option1 = 1,
Option2 = 2,
Option3 = 4,
Option4 = 8
}
</code></pre>
<p>I don't understand what exactly the <code>[Flags]</code> attribute does.</p>
<p>Anyone have a good explanation or example they could post?</p>
| [
{
"answer_id": 8455,
"author": "Jay Mooney",
"author_id": 733,
"author_profile": "https://Stackoverflow.com/users/733",
"pm_score": 4,
"selected": false,
"text": "<p>Flags allow you to use bitmasking inside your enumeration. This allows you to combine enumeration values, while retaining... | 2008/08/12 | [
"https://Stackoverflow.com/questions/8447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/580/"
] | From time to time I see an enum like the following:
```
[Flags]
public enum Options
{
None = 0,
Option1 = 1,
Option2 = 2,
Option3 = 4,
Option4 = 8
}
```
I don't understand what exactly the `[Flags]` attribute does.
Anyone have a good explanation or example they could post? | The `[Flags]` attribute should be used whenever the enumerable represents a collection of possible values, rather than a single value. Such collections are often used with bitwise operators, for example:
```
var allowedColors = MyColor.Red | MyColor.Green | MyColor.Blue;
```
Note that the `[Flags]` attribute **doesn't** enable this by itself - all it does is allow a nice representation by the `.ToString()` method:
```
enum Suits { Spades = 1, Clubs = 2, Diamonds = 4, Hearts = 8 }
[Flags] enum SuitsFlags { Spades = 1, Clubs = 2, Diamonds = 4, Hearts = 8 }
...
var str1 = (Suits.Spades | Suits.Diamonds).ToString();
// "5"
var str2 = (SuitsFlags.Spades | SuitsFlags.Diamonds).ToString();
// "Spades, Diamonds"
```
It is also important to note that `[Flags]` **does not** automatically make the enum values powers of two. If you omit the numeric values, the enum will not work as one might expect in bitwise operations, because by default the values start with 0 and increment.
Incorrect declaration:
```
[Flags]
public enum MyColors
{
Yellow, // 0
Green, // 1
Red, // 2
Blue // 3
}
```
The values, if declared this way, will be Yellow = 0, Green = 1, Red = 2, Blue = 3. This will render it useless as flags.
Here's an example of a correct declaration:
```
[Flags]
public enum MyColors
{
Yellow = 1,
Green = 2,
Red = 4,
Blue = 8
}
```
To retrieve the distinct values in your property, one can do this:
```
if (myProperties.AllowedColors.HasFlag(MyColor.Yellow))
{
// Yellow is allowed...
}
```
or prior to .NET 4:
```
if((myProperties.AllowedColors & MyColor.Yellow) == MyColor.Yellow)
{
// Yellow is allowed...
}
if((myProperties.AllowedColors & MyColor.Green) == MyColor.Green)
{
// Green is allowed...
}
```
**Under the covers**
This works because you used powers of two in your enumeration. Under the covers, your enumeration values look like this in binary ones and zeros:
```
Yellow: 00000001
Green: 00000010
Red: 00000100
Blue: 00001000
```
Similarly, after you've set your property *AllowedColors* to Red, Green and Blue using the binary bitwise OR `|` operator, *AllowedColors* looks like this:
```
myProperties.AllowedColors: 00001110
```
So when you retrieve the value you are actually performing bitwise AND `&` on the values:
```
myProperties.AllowedColors: 00001110
MyColor.Green: 00000010
-----------------------
00000010 // Hey, this is the same as MyColor.Green!
```
**The None = 0 value**
And regarding the use of `0` in your enumeration, quoting from MSDN:
```
[Flags]
public enum MyColors
{
None = 0,
....
}
```
>
> Use None as the name of the flag enumerated constant whose value is zero. **You cannot use the None enumerated constant in a bitwise AND operation to test for a flag because the result is always zero.** However, you can perform a logical, not a bitwise, comparison between the numeric value and the None enumerated constant to determine whether any bits in the numeric value are set.
>
>
>
You can find more info about the flags attribute and its usage at [msdn](http://msdn.microsoft.com/en-us/library/system.flagsattribute.aspx) and [designing flags at msdn](http://msdn.microsoft.com/en-us/library/ms229062.aspx) |
8,448 | <p>Anyone have a decent example, preferably practical/useful, they could post demonstrating the concept?</p>
| [
{
"answer_id": 8457,
"author": "Patrick",
"author_id": 429,
"author_profile": "https://Stackoverflow.com/users/429",
"pm_score": 2,
"selected": false,
"text": "<p>It's a fairly simple process. Take a function, bind one of its arguments and return a new function. For example:</p>\n\n<pre>... | 2008/08/12 | [
"https://Stackoverflow.com/questions/8448",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/580/"
] | Anyone have a decent example, preferably practical/useful, they could post demonstrating the concept? | >
> (Edit: a small [Ocaml FP Koan](http://web.archive.org/web/20041012103936/http%3A//www.bagley.org/~doug/ocaml/Notes/okoans.shtml) to start things off)
>
>
>
> >
> > **The Koan of Currying (A koan about food, that is not about food)**
> >
> >
> >
> > >
> > > A student came to Jacques Garrigue and said, "I do not understand what currying is good for." Jacques replied, "Tell me your favorite meal and your favorite dessert". The puzzled student replied that he liked okonomiyaki and kanten, but while his favorite restaurant served great okonomiyaki, their kanten always gave him a stomach ache the following morning. So Jacques took the student to eat at a restaurant that served okonomiyaki every bit as good as the student's favorite, then took him across town to a shop that made excellent kanten where the student happily applied the remainder of his appetite. The student was sated, but he was not enlightened ... until the next morning when he woke up and his stomach felt fine.
> > >
> > >
> > >
> >
> >
> >
>
>
>
My examples will cover using it for the reuse and encapsulation of code. This is fairly obvious once you look at these and should give you a concrete, simple example that you can think of applying in numerous situations.
We want to do a map over a tree. This function could be curried and applied to each node if it needs more then one argument -- since we'd be applying the one at the node as it's final argument. It doesn't have to be curried, but writing *another* function (assuming this function is being used in other instances with other variables) would be a waste.
```
type 'a tree = E of 'a | N of 'a * 'a tree * 'a tree
let rec tree_map f tree = match tree with
| N(x,left,right) -> N(f x, tree_map f left, tree_map f right)
| E(x) -> E(f x)
let sample_tree = N(1,E(3),E(4)
let multiply x y = x * y
let sample_tree2 = tree_map (multiply 3) sample_tree
```
but this is the same as:
```
let sample_tree2 = tree_map (fun x -> x * 3) sample_tree
```
So this simple case isn't convincing. It really is though, and powerful once you use the language more and naturally come across these situations. The other example with some code reuse as currying. A [recurrence relation to create prime numbers](https://stackoverflow.com/questions/7272/of-ways-to-count-the-limitless-primes#7487). Awful lot of similarity in there:
```
let rec f_recurrence f a seed n =
match n with
| a -> seed
| _ -> let prev = f_recurrence f a seed (n-1) in
prev + (f n prev)
let rowland = f_recurrence gcd 1 7
let cloitre = f_recurrence lcm 1 1
let rowland_prime n = (rowland (n+1)) - (rowland n)
let cloitre_prime n = ((cloitre (n+1))/(cloitre n)) - 1
```
Ok, now rowland and cloitre are curried functions, since they have free variables, and we can get any index of it's sequence without knowing or worrying about f\_recurrence. |
8,451 | <p>I want to create an allocator which provides memory with the following attributes:</p>
<ul>
<li>cannot be paged to disk. </li>
<li>is incredibly hard to access through an attached debugger</li>
</ul>
<p>The idea is that this will contain sensitive information (like licence information) which should be inaccessible to the user. I have done the usual research online and asked a few other people about this, but I cannot find a good place start on this problem.</p>
<p><strong>Updates</strong></p>
<p><a href="https://stackoverflow.com/questions/8451/secure-memory-allocator-in-c#27194">Josh</a> mentions using <code>VirtualAlloc</code> to set protection on the memory space. I have created a custom allocator ( shown below ) I have found the using the <code>VirtualLock</code> function it limits the amount of memory I can allocate. This seems to be by design though. Since I am using it for small objects this is not a problem.</p>
<pre><code>//
template<class _Ty>
class LockedVirtualMemAllocator : public std::allocator<_Ty>
{
public:
template<class _Other>
LockedVirtualMemAllocator<_Ty>& operator=(const LockedVirtualMemAllocator<_Other>&)
{ // assign from a related LockedVirtualMemAllocator (do nothing)
return (*this);
}
template<class Other>
struct rebind {
typedef LockedVirtualMemAllocator<Other> other;
};
pointer allocate( size_type _n )
{
SIZE_T allocLen = (_n * sizeof(_Ty));
DWORD allocType = MEM_COMMIT;
DWORD allocProtect = PAGE_READWRITE;
LPVOID pMem = ::VirtualAlloc( NULL, allocLen, allocType, allocProtect );
if ( pMem != NULL ) {
::VirtualLock( pMem, allocLen );
}
return reinterpret_cast<pointer>( pMem );
}
pointer allocate( size_type _n, const void* )
{
return allocate( _n );
}
void deallocate(void* _pPtr, size_type _n )
{
if ( _pPtr != NULL ) {
SIZE_T allocLen = (_n * sizeof(_Ty));
::SecureZeroMemory( _pPtr, allocLen );
::VirtualUnlock( _pPtr, allocLen );
::VirtualFree( _pPtr, 0, MEM_RELEASE );
}
}
};
</code></pre>
<p>and is used</p>
<pre><code> //a memory safe std::string
typedef std::basic_string<char, std::char_traits<char>,
LockedVirtualMemAllocato<char> > modulestring_t;
</code></pre>
<p><a href="https://stackoverflow.com/questions/8451/secure-memory-allocator-in-c#38708">Ted Percival</a> mentions mlock, but I have no implementation of that yet.</p>
<p>I found <a href="http://www.schneier.com/book-practical.html" rel="noreferrer">Practical Cryptography by Neil Furguson and Bruce Schneier</a> quite helpful as well.</p>
| [
{
"answer_id": 8476,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 2,
"selected": false,
"text": "<p>What you are asking for is handled at the OS level. Once the data is in your program, it is liable to be paged out.</p... | 2008/08/12 | [
"https://Stackoverflow.com/questions/8451",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/716/"
] | I want to create an allocator which provides memory with the following attributes:
* cannot be paged to disk.
* is incredibly hard to access through an attached debugger
The idea is that this will contain sensitive information (like licence information) which should be inaccessible to the user. I have done the usual research online and asked a few other people about this, but I cannot find a good place start on this problem.
**Updates**
[Josh](https://stackoverflow.com/questions/8451/secure-memory-allocator-in-c#27194) mentions using `VirtualAlloc` to set protection on the memory space. I have created a custom allocator ( shown below ) I have found the using the `VirtualLock` function it limits the amount of memory I can allocate. This seems to be by design though. Since I am using it for small objects this is not a problem.
```
//
template<class _Ty>
class LockedVirtualMemAllocator : public std::allocator<_Ty>
{
public:
template<class _Other>
LockedVirtualMemAllocator<_Ty>& operator=(const LockedVirtualMemAllocator<_Other>&)
{ // assign from a related LockedVirtualMemAllocator (do nothing)
return (*this);
}
template<class Other>
struct rebind {
typedef LockedVirtualMemAllocator<Other> other;
};
pointer allocate( size_type _n )
{
SIZE_T allocLen = (_n * sizeof(_Ty));
DWORD allocType = MEM_COMMIT;
DWORD allocProtect = PAGE_READWRITE;
LPVOID pMem = ::VirtualAlloc( NULL, allocLen, allocType, allocProtect );
if ( pMem != NULL ) {
::VirtualLock( pMem, allocLen );
}
return reinterpret_cast<pointer>( pMem );
}
pointer allocate( size_type _n, const void* )
{
return allocate( _n );
}
void deallocate(void* _pPtr, size_type _n )
{
if ( _pPtr != NULL ) {
SIZE_T allocLen = (_n * sizeof(_Ty));
::SecureZeroMemory( _pPtr, allocLen );
::VirtualUnlock( _pPtr, allocLen );
::VirtualFree( _pPtr, 0, MEM_RELEASE );
}
}
};
```
and is used
```
//a memory safe std::string
typedef std::basic_string<char, std::char_traits<char>,
LockedVirtualMemAllocato<char> > modulestring_t;
```
[Ted Percival](https://stackoverflow.com/questions/8451/secure-memory-allocator-in-c#38708) mentions mlock, but I have no implementation of that yet.
I found [Practical Cryptography by Neil Furguson and Bruce Schneier](http://www.schneier.com/book-practical.html) quite helpful as well. | You can't really protect against memory access. You can probably prevent paging if you are running as an admin or as the system, but you cannot prevent the admin or system from reading your memory. Even if you could somehow completely block other processes from reading your memory (which you can't), another process could still actually inject a new thread into your process and read the memory that way.
Even if you could somehow completely lock down your process and guarantee that the OS would *never* allow anyone else to access your process, you still don't have full protection. The entire OS could be running in a virtual machine, which could be paused and inspected at any time.
You *cannot* protect memory contents from the owner of the system. Hollywood and the music industry have been aching for this for years. If it were possible, they'd already be doing it. |
8,452 | <p>I've done some WPF programing and one thing I never got was the command pattern. Every example seems to be for built in ones, edit, cut, paste. Anyone have an example or suggestion of best practice for custom commands?</p>
| [
{
"answer_id": 8471,
"author": "Nidonocu",
"author_id": 483,
"author_profile": "https://Stackoverflow.com/users/483",
"pm_score": 6,
"selected": true,
"text": "<p>Ah ha! A question I can answer! Firstly, I should mention that I have personally found it easier to define and hook up comman... | 2008/08/12 | [
"https://Stackoverflow.com/questions/8452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/580/"
] | I've done some WPF programing and one thing I never got was the command pattern. Every example seems to be for built in ones, edit, cut, paste. Anyone have an example or suggestion of best practice for custom commands? | Ah ha! A question I can answer! Firstly, I should mention that I have personally found it easier to define and hook up commands in code rather than in XAML. It allows me to hook up the handlers for the commands a little more flexibly than an all XAML approach does.
You should work out what commands you want to have and what they relate to. In my application, I currently have a class for defining important application commands like so:
```
public static class CommandBank
{
/// Command definition for Closing a window
public static RoutedUICommand CloseWindow { get; private set; }
/// Static private constructor, sets up all application wide commands.
static CommandBank()
{
CloseWindow = new RoutedUICommand();
CloseWindow.InputGestures.Add(new KeyGesture(Key.F4, ModifierKeys.Alt));
// ...
}
```
Now, because I wanted to keep the code all together, using a code only approach to Commands lets me put the following methods in the class above:
```
/// Closes the window provided as a parameter
public static void CloseWindowExecute(object sender, ExecutedRoutedEventArgs e)
{
((Window)e.Parameter).Close();
}
/// Allows a Command to execute if the CommandParameter is not a null value
public static void CanExecuteIfParameterIsNotNull(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = e.Parameter != null;
e.Handled = true;
}
```
The second method there can even be shared with other Commands without me having to repeat it all over the place.
Once you have defined the commands like this, you can add them to any piece of UI. In the following, once the Window has Loaded, I add command bindings to both the Window and MenuItem and then add an input binding to the Window using a loop to do this for all command bindings. The parameter that is passed is the Window its self so the code above knows what Window to try and close.
```
public partial class SimpleWindow : Window
{
private void WindowLoaded(object sender, RoutedEventArgs e)
{
// ...
this.CommandBindings.Add(
new CommandBinding(
CommandBank.CloseWindow,
CommandBank.CloseWindowExecute,
CommandBank.CanExecuteIfParameterIsNotNull));
foreach (CommandBinding binding in this.CommandBindings)
{
RoutedCommand command = (RoutedCommand)binding.Command;
if (command.InputGestures.Count > 0)
{
foreach (InputGesture gesture in command.InputGestures)
{
var iBind = new InputBinding(command, gesture);
iBind.CommandParameter = this;
this.InputBindings.Add(iBind);
}
}
}
// menuItemExit is defined in XAML
menuItemExit.Command = CommandBank.CloseWindow;
menuItemExit.CommandParameter = this;
// ...
}
// ....
}
```
I then also later have event handlers for the WindowClosing and WindowClosed events, I do recommend you make the actual implementation of commands as small and generic as possible. As in this case, I didn't try to put code that tries to stop the Window closing if there is unsaved data, I kept that code firmly inside the WindowClosing event.
Let me know if you have any follow up questions. :) |
8,472 | <p>It looks like we'll be adding <a href="http://en.wikipedia.org/wiki/Captcha" rel="noreferrer">CAPTCHA</a> support to Stack Overflow. This is necessary to prevent bots, spammers, and other malicious scripted activity. We only want human beings to post or edit things here!</p>
<p>We'll be using a JavaScript (jQuery) CAPTCHA as a first line of defense:</p>
<p><a href="http://docs.jquery.com/Tutorials:Safer_Contact_Forms_Without_CAPTCHAs" rel="noreferrer">http://docs.jquery.com/Tutorials:Safer_Contact_Forms_Without_CAPTCHAs</a></p>
<p>The advantage of this approach is that, <strong>for most people, the CAPTCHA won't ever be visible!</strong></p>
<p>However, for people with JavaScript disabled, we still need a fallback and this is where it gets tricky.</p>
<p>I have written a <a href="http://www.codeproject.com/KB/custom-controls/CaptchaControl.aspx" rel="noreferrer">traditional CAPTCHA control for ASP.NET</a> which we can re-use.</p>
<p><img src="https://i.stack.imgur.com/Puvbf.jpg" alt="CaptchaImage"></p>
<p>However, I'd prefer to go with something textual to avoid the overhead of creating all these images on the server with each request.</p>
<p>I've seen things like..</p>
<ul>
<li>ASCII text captcha: <code>\/\/(_)\/\/</code></li>
<li>math puzzles: what is 7 minus 3 times 2?</li>
<li>trivia questions: what tastes better, a toad or a popsicle?</li>
</ul>
<p>Maybe I'm just tilting at windmills here, but I'd like to have a less resource intensive, non-image based <code><noscript></code> compatible CAPTCHA if possible.</p>
<p>Ideas?</p>
| [
{
"answer_id": 8474,
"author": "Jeff Atwood",
"author_id": 1,
"author_profile": "https://Stackoverflow.com/users/1",
"pm_score": 2,
"selected": false,
"text": "<p>Someone also suggest the Raphael JavaScript library, which apparently let you draw on the client in all popular browsers:</p>... | 2008/08/12 | [
"https://Stackoverflow.com/questions/8472",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1/"
] | It looks like we'll be adding [CAPTCHA](http://en.wikipedia.org/wiki/Captcha) support to Stack Overflow. This is necessary to prevent bots, spammers, and other malicious scripted activity. We only want human beings to post or edit things here!
We'll be using a JavaScript (jQuery) CAPTCHA as a first line of defense:
<http://docs.jquery.com/Tutorials:Safer_Contact_Forms_Without_CAPTCHAs>
The advantage of this approach is that, **for most people, the CAPTCHA won't ever be visible!**
However, for people with JavaScript disabled, we still need a fallback and this is where it gets tricky.
I have written a [traditional CAPTCHA control for ASP.NET](http://www.codeproject.com/KB/custom-controls/CaptchaControl.aspx) which we can re-use.

However, I'd prefer to go with something textual to avoid the overhead of creating all these images on the server with each request.
I've seen things like..
* ASCII text captcha: `\/\/(_)\/\/`
* math puzzles: what is 7 minus 3 times 2?
* trivia questions: what tastes better, a toad or a popsicle?
Maybe I'm just tilting at windmills here, but I'd like to have a less resource intensive, non-image based `<noscript>` compatible CAPTCHA if possible.
Ideas? | [A method that I have developed](http://gatekiller.co.uk/Post/JavaScript_Captcha) and which seems to work perfectly (although I probably don't get as much comment spam as you), is to have a hidden field and fill it with a bogus value e.g.:
```html
<input type="hidden" name="antispam" value="lalalala" />
```
I then have a piece of JavaScript which updates the value every second with the number of seconds the page has been loaded for:
```js
var antiSpam = function() {
if (document.getElementById("antiSpam")) {
a = document.getElementById("antiSpam");
if (isNaN(a.value) == true) {
a.value = 0;
} else {
a.value = parseInt(a.value) + 1;
}
}
setTimeout("antiSpam()", 1000);
}
antiSpam();
```
Then when the form is submitted, If the antispam value is still "lalalala", then I mark it as spam. If the antispam value is an integer, I check to see if it is above something like 10 (seconds). If it's below 10, I mark it as spam, if it's 10 or more, I let it through.
```asp
If AntiSpam = A Integer
If AntiSpam >= 10
Comment = Approved
Else
Comment = Spam
Else
Comment = Spam
```
The theory being that:
* A spam bot will not support JavaScript and will submit what it sees
* If the bot does support JavaScript it will submit the form instantly
* The commenter has at least read some of the page before posting
The downside to this method is that it requires JavaScript, and if you don't have JavaScript enabled, your comment will be marked as spam, however, I do review comments marked as spam, so this is not a problem.
**Response to comments**
@MrAnalogy: The server side approach sounds quite a good idea and is exactly the same as doing it in JavaScript. Good Call.
@AviD: I'm aware that this method is prone to direct attacks as I've mentioned on [my blog](http://gatekiller.co.uk/Post/JavaScript_Captcha). However, it will defend against your average spam bot which blindly submits rubbish to any form it can find. |
8,485 | <p>I'm using ASP.NET MVC Preview 4 and would like to know how to use the routing engine for form submissions.</p>
<p>For example, I have a route like this:</p>
<pre><code>routes.MapRoute(
"TestController-TestAction",
"TestController.mvc/TestAction/{paramName}",
new { controller = "TestController", action = "TestAction", id = "TestTopic" }
);
</code></pre>
<p>And a form declaration that looks like this:</p>
<pre><code><% using (Html.Form("TestController", "TestAction", FormMethod.Get))
{ %>
<input type="text" name="paramName" />
<input type="submit" />
<% } %>
</code></pre>
<p>which renders to:</p>
<pre><code><form method="get" action="/TestController.mvc/TestAction">
<input type="text" name="paramName" />
<input type="submit" />
</form>
</code></pre>
<p>The resulting URL of a form submission is:</p>
<pre><code>localhost/TestController.mvc/TestAction?paramName=value
</code></pre>
<p>Is there any way to have this form submission route to the desired URL of:</p>
<pre><code>localhost/TestController.mvc/TestAction/value
</code></pre>
<p>The only solutions I can think of are to create a separate action that just checks the request parameters, or to use Javascript.</p>
| [
{
"answer_id": 8495,
"author": "Haacked",
"author_id": 598,
"author_profile": "https://Stackoverflow.com/users/598",
"pm_score": 2,
"selected": false,
"text": "<p>In your route, get rid of the {paramName} part of the URL. It should be:</p>\n\n<p>TestController.mvc/TestAction</p>\n\n<p>As... | 2008/08/12 | [
"https://Stackoverflow.com/questions/8485",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/364/"
] | I'm using ASP.NET MVC Preview 4 and would like to know how to use the routing engine for form submissions.
For example, I have a route like this:
```
routes.MapRoute(
"TestController-TestAction",
"TestController.mvc/TestAction/{paramName}",
new { controller = "TestController", action = "TestAction", id = "TestTopic" }
);
```
And a form declaration that looks like this:
```
<% using (Html.Form("TestController", "TestAction", FormMethod.Get))
{ %>
<input type="text" name="paramName" />
<input type="submit" />
<% } %>
```
which renders to:
```
<form method="get" action="/TestController.mvc/TestAction">
<input type="text" name="paramName" />
<input type="submit" />
</form>
```
The resulting URL of a form submission is:
```
localhost/TestController.mvc/TestAction?paramName=value
```
Is there any way to have this form submission route to the desired URL of:
```
localhost/TestController.mvc/TestAction/value
```
The only solutions I can think of are to create a separate action that just checks the request parameters, or to use Javascript. | Solution:
```
public ActionResult TestAction(string paramName)
{
if (!String.IsNullOrEmpty(Request["paramName"]))
{
return RedirectToAction("TestAction", new { paramName = Request["paramName"]});
}
/* ... */
}
``` |
8,493 | <p>Are there any handy general items you put in your .procmailrc file?</p>
| [
{
"answer_id": 8629,
"author": "Marie Fischer",
"author_id": 719,
"author_profile": "https://Stackoverflow.com/users/719",
"pm_score": 3,
"selected": false,
"text": "<p>Just simple things - move messages to appropriate folders, forward some stuff to an email2sms address, move spam to spa... | 2008/08/12 | [
"https://Stackoverflow.com/questions/8493",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/459/"
] | Are there any handy general items you put in your .procmailrc file? | Many mailers prefix a mail's subject with "Re: " when replying, if that prefix isn't already there. German Outlook instead prefixes with "AW: " (for "AntWort") if that prefix isn't already there. Unfortunately, these two behaviours clash, resulting in mail subjects like "Re: AW: Re: AW: Re: AW: Re: AW: Lunch". So I now have:
```
:0f
* ^Subject: (Antwort|AW):
|sed -r -e '1,/^$/s/^(Subject: )(((Antwort: )|(Re: )|(AW: ))+)(.*)/\1Re: \7\nX-Orig-Subject: \2\7/'
```
Which curtails these (and an "Antwort: " prefix that I've evidently also been bothered by at some point) down to a single "Re: ". |
8,532 | <p>I've had an app doing prefix searches for a while. Recently the index size was increased and it turned out that some prefixes were too darned numerous for lucene to handle. It kept throwing me a <a href="http://web.archive.org/web/20080901205009/http://lucene.apache.org:80/java/2_3_2/api/core/org/apache/lucene/search/BooleanQuery.TooManyClauses.html" rel="nofollow noreferrer">Too Many Clauses</a> error, which was very frustrating as I kept looking at my JARs and confirming that none of the included code actually used a boolean query.</p>
<p>Why doesn't it throw something like a Too Many Hits exception? And why does increasing the boolean query's static max clauses integer actually make this error go away, when I'm definitely only using a prefix query? Is there something fundamental to how queries are run that I'm not understanding; is it that they secretly become Boolean queries?</p>
| [
{
"answer_id": 9085,
"author": "Ryan Ahearn",
"author_id": 75,
"author_profile": "https://Stackoverflow.com/users/75",
"pm_score": 4,
"selected": true,
"text": "<p>I've hit this before. It has to do with the fact that lucene, under the covers, turns many (all?) things into boolean queri... | 2008/08/12 | [
"https://Stackoverflow.com/questions/8532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/459/"
] | I've had an app doing prefix searches for a while. Recently the index size was increased and it turned out that some prefixes were too darned numerous for lucene to handle. It kept throwing me a [Too Many Clauses](http://web.archive.org/web/20080901205009/http://lucene.apache.org:80/java/2_3_2/api/core/org/apache/lucene/search/BooleanQuery.TooManyClauses.html) error, which was very frustrating as I kept looking at my JARs and confirming that none of the included code actually used a boolean query.
Why doesn't it throw something like a Too Many Hits exception? And why does increasing the boolean query's static max clauses integer actually make this error go away, when I'm definitely only using a prefix query? Is there something fundamental to how queries are run that I'm not understanding; is it that they secretly become Boolean queries? | I've hit this before. It has to do with the fact that lucene, under the covers, turns many (all?) things into boolean queries when you call Query.rewrite()
From: <http://web.archive.org/web/20110915061619/http://lucene.apache.org:80/java/2_2_0/api/org/apache/lucene/search/Query.html>
```
public Query rewrite(IndexReader reader)
throws IOException
Expert: called to re-write queries into primitive queries.
For example, a PrefixQuery will be rewritten into a
BooleanQuery that consists of TermQuerys.
Throws:
IOException
``` |
8,549 | <p>Is there any Visual Studio Add-In that can do the remove method refactoring?<br>
Suppose you have the following method: </p>
<pre><code>Result DoSomething(parameters)
{
return ComputeResult(parameters);
}
</code></pre>
<p>Or the variant where Result is void.</p>
<p>The purpose of the refactoring is to replace all the calls to DoSomething with calls to ComputeResult or the expression that uses the parameters if ComputeResult is not a method call.</p>
| [
{
"answer_id": 8551,
"author": "Lars Mæhlum",
"author_id": 960,
"author_profile": "https://Stackoverflow.com/users/960",
"pm_score": 1,
"selected": false,
"text": "<p>When it comes to refactoring like that, try out <a href=\"http://www.jetbrains.com/resharper/index.html\" rel=\"nofollow ... | 2008/08/12 | [
"https://Stackoverflow.com/questions/8549",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1065/"
] | Is there any Visual Studio Add-In that can do the remove method refactoring?
Suppose you have the following method:
```
Result DoSomething(parameters)
{
return ComputeResult(parameters);
}
```
Or the variant where Result is void.
The purpose of the refactoring is to replace all the calls to DoSomething with calls to ComputeResult or the expression that uses the parameters if ComputeResult is not a method call. | If I understand the question, then Resharper calls this 'inline method' - `Ctrl` - `R` + `I` |
8,566 | <p>First off, this is a question about a desktop application using Windows Forms, not an <a href="http://en.wikipedia.org/wiki/ASP.NET" rel="nofollow noreferrer">ASP.NET</a> question.</p>
<p>I need to interact with controls on other forms. I am trying to access the controls by using, for example, the following...</p>
<pre><code>otherForm.Controls["nameOfControl"].Visible = false;
</code></pre>
<p>It doesn't work the way I would expect. I end up with an exception thrown from <code>Main</code>. However, if I make the controls <code>public</code> instead of <code>private</code>, I can then access them directly, as so...</p>
<pre><code>otherForm.nameOfControl.Visible = false;
</code></pre>
<p>But is that the best way to do it? Is making the controls <code>public</code> on the other form considered "best practice"? Is there a "better" way to access controls on another form?</p>
<p><strong>Further Explanation:</strong></p>
<p>This is actually a sort of follow-up to another question I asked, <em><a href="https://stackoverflow.com/questions/3725/best-method-for-creating-a-tree-view-preferences-dialog-type-of-interface-in-c">Best method for creating a “tree-view preferences dialog” type of interface in C#?</a></em>. The answer I got was great and solved many, many organizational problems I was having in terms of keeping the UI straight and easy to work with both in run-time and design-time. However, it did bring up this one niggling issue of easily controlling other aspects of the interface.</p>
<p>Basically, I have a root form that instantiates a lot of other forms that sit in a panel on the root form. So, for instance, a radio button on one of those sub-forms might need to alter the state of a status strip icon on the main, root form. In that case, I need the sub-form to talk to the control in the status strip of the parent (root) form. (I hope that makes sense, not in a "who's on first" kind of way.)</p>
| [
{
"answer_id": 8567,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 4,
"selected": false,
"text": "<p>I personally would recommend <em>NOT</em> doing it... If it's responding to some sort of action and it needs to change its... | 2008/08/12 | [
"https://Stackoverflow.com/questions/8566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/551/"
] | First off, this is a question about a desktop application using Windows Forms, not an [ASP.NET](http://en.wikipedia.org/wiki/ASP.NET) question.
I need to interact with controls on other forms. I am trying to access the controls by using, for example, the following...
```
otherForm.Controls["nameOfControl"].Visible = false;
```
It doesn't work the way I would expect. I end up with an exception thrown from `Main`. However, if I make the controls `public` instead of `private`, I can then access them directly, as so...
```
otherForm.nameOfControl.Visible = false;
```
But is that the best way to do it? Is making the controls `public` on the other form considered "best practice"? Is there a "better" way to access controls on another form?
**Further Explanation:**
This is actually a sort of follow-up to another question I asked, *[Best method for creating a “tree-view preferences dialog” type of interface in C#?](https://stackoverflow.com/questions/3725/best-method-for-creating-a-tree-view-preferences-dialog-type-of-interface-in-c)*. The answer I got was great and solved many, many organizational problems I was having in terms of keeping the UI straight and easy to work with both in run-time and design-time. However, it did bring up this one niggling issue of easily controlling other aspects of the interface.
Basically, I have a root form that instantiates a lot of other forms that sit in a panel on the root form. So, for instance, a radio button on one of those sub-forms might need to alter the state of a status strip icon on the main, root form. In that case, I need the sub-form to talk to the control in the status strip of the parent (root) form. (I hope that makes sense, not in a "who's on first" kind of way.) | Instead of making the control public, you can create a property that controls its visibility:
```
public bool ControlIsVisible
{
get { return control.Visible; }
set { control.Visible = value; }
}
```
This creates a proper accessor to that control that won't expose the control's whole set of properties. |
8,569 | <p>I'm currently trying to get into the Java EE development with the Spring framework. As I'm new to Spring, it is hard to imaging how a good running project should start off.</p>
<p>Do you have any <em>best practices</em>, tipps or major <em>DO NOTs</em> for a starter? How did you start with Spring - big project or small tutorial-like applications? Which technology did you use right away: AOP, complex Hibernate...</p>
| [
{
"answer_id": 8571,
"author": "Michael Neale",
"author_id": 699,
"author_profile": "https://Stackoverflow.com/users/699",
"pm_score": 2,
"selected": false,
"text": "<p>Whilst its been years since I have used spring, and I can't say I am a fan of it, I know that the App Fuse tool (<a hre... | 2008/08/12 | [
"https://Stackoverflow.com/questions/8569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/834/"
] | I'm currently trying to get into the Java EE development with the Spring framework. As I'm new to Spring, it is hard to imaging how a good running project should start off.
Do you have any *best practices*, tipps or major *DO NOTs* for a starter? How did you start with Spring - big project or small tutorial-like applications? Which technology did you use right away: AOP, complex Hibernate... | Small tip - I've found it helpful to modularize and clearly label my Spring xml context files based on application concern. Here's an example for a web app I worked on:
* `MyProject / src / main / resources / spring /`
+ ***datasource.xml*** - My single data source bean.
+ ***persistence.xml*** - My DAOs/Repositories. Depends on `datasource.xml` beans.
+ ***services.xml*** - Service layer implementations. These are usually the beans to which I apply transactionality using AOP. Depends on `persistence.xml` beans.
+ ***controllers.xml*** - My Spring MVC controllers. Depends on `services.xml` beans.
+ ***views.xml*** - My view implementations.
This list is neither perfect nor exhaustive, but I hope it illustrates the point. Choose whatever naming strategy and granularity works best for you.
In my (limited) experience, I've seen this approach yeild the following benefits:
**Clearer architecture**
Clearly named context files gives those unfamiliar with your project structure a reasonable
place to start looking for bean definitions. Can make detecting circular/unwanted dependencies a little easier.
**Helps domain design**
If you want to add a bean definition, but it doesn't fit well in any of your context files, perhaps there's a new concept or concern emerging? Examples:
* Suppose you want to make your Service layer transactional with AOP. Do you add those bean definitions to `services.xml`, or put them in their own `transactionPolicy.xml`? Talk it over with your team. Should your transaction policy be pluggable?
* Add Acegi/Spring Security beans to your `controllers.xml` file, or create a `security.xml` context file? Do you have different security requirements for different deployments/environments?
**Integration testing**
You can wire up a subset of your application for integration testing (ex: given the above files, to test the database you need to create only `datasource.xml` and `persistence.xml` beans).
Specifically, you can annotate an integration test class as such:
```
@ContextConfiguration(locations = { "/spring/datasource.xml" , "/spring/persistence.xml" })
```
**Works well with Spring IDE's Beans Graph**
Having lots of focused and well-named context files makes it easy to create custom BeansConfigSets to visualize the layers of your app using Spring IDE's [Beans Graph](http://springide.org/project/wiki/BeansGraph). I've used this before to give new team members a high-level overview of our application's organization. |
8,625 | <p>I have a class that I want to use to store "properties" for another class. These properties simply have a name and a value. Ideally, what I would like is to be able to add <em>typed</em> properties, so that the "value" returned is always of the type that I want it to be.</p>
<p>The type should always be a primitive. This class subclasses an abstract class which basically stores the name and value as string. The idea being that this subclass will add some type-safety to the base class (as well as saving me on some conversion).</p>
<p>So, I have created a class which is (roughly) this:</p>
<pre><code>public class TypedProperty<DataType> : Property
{
public DataType TypedValue
{
get { // Having problems here! }
set { base.Value = value.ToString();}
}
}
</code></pre>
<p>So the question is:</p>
<p><strong>Is there a "generic" way to convert from string back to a primitive?</strong></p>
<p>I can't seem to find any generic interface that links the conversion across the board (something like <em>ITryParsable</em> would have been ideal!).</p>
| [
{
"answer_id": 8632,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 2,
"selected": false,
"text": "<p>You could possibly use a construct such as a <a href=\"http://www.boost.org/community/generic_programming.html#traits\" ... | 2008/08/12 | [
"https://Stackoverflow.com/questions/8625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/832/"
] | I have a class that I want to use to store "properties" for another class. These properties simply have a name and a value. Ideally, what I would like is to be able to add *typed* properties, so that the "value" returned is always of the type that I want it to be.
The type should always be a primitive. This class subclasses an abstract class which basically stores the name and value as string. The idea being that this subclass will add some type-safety to the base class (as well as saving me on some conversion).
So, I have created a class which is (roughly) this:
```
public class TypedProperty<DataType> : Property
{
public DataType TypedValue
{
get { // Having problems here! }
set { base.Value = value.ToString();}
}
}
```
So the question is:
**Is there a "generic" way to convert from string back to a primitive?**
I can't seem to find any generic interface that links the conversion across the board (something like *ITryParsable* would have been ideal!). | I am not sure whether I understood your intentions correctly, but let's see if this one helps.
```
public class TypedProperty<T> : Property where T : IConvertible
{
public T TypedValue
{
get { return (T)Convert.ChangeType(base.Value, typeof(T)); }
set { base.Value = value.ToString();}
}
}
``` |
8,626 | <p>Is there anyplace where one can download a virtual machine containing a working install of some Linux distro with Globus Toolkit and some development tools (Java) for testing purposes? A real deployment of a grid is more complicated but I just need something portable, for development.</p>
| [
{
"answer_id": 8632,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 2,
"selected": false,
"text": "<p>You could possibly use a construct such as a <a href=\"http://www.boost.org/community/generic_programming.html#traits\" ... | 2008/08/12 | [
"https://Stackoverflow.com/questions/8626",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1065/"
] | Is there anyplace where one can download a virtual machine containing a working install of some Linux distro with Globus Toolkit and some development tools (Java) for testing purposes? A real deployment of a grid is more complicated but I just need something portable, for development. | I am not sure whether I understood your intentions correctly, but let's see if this one helps.
```
public class TypedProperty<T> : Property where T : IConvertible
{
public T TypedValue
{
get { return (T)Convert.ChangeType(base.Value, typeof(T)); }
set { base.Value = value.ToString();}
}
}
``` |
8,651 | <p>I am trying to load Linq on my .Net 3.5 enabled web server by adding the following to my .aspx page:</p>
<pre><code><%@ Import Namespace="System.Query" %>
</code></pre>
<p>However, this fails and tells me it cannot find the namespace.</p>
<blockquote>
<p>The type or namespace name 'Query' does not exist in the namespace 'System' </p>
</blockquote>
<p>I have also tried with no luck:</p>
<ul>
<li><code>System.Data.Linq</code></li>
<li><code>System.Linq</code></li>
<li><code>System.Xml.Linq</code></li>
</ul>
<p>I believe that .Net 3.5 is working because <code>var hello = "Hello World"</code> seems to work.</p>
<p>Can anyone help please?</p>
<p>PS: I just want to clarify that I don't use Visual Studio, I simply have a <a href="http://www.ultraedit.com/" rel="nofollow noreferrer">Text Editor</a> and write my code directly into .aspx files.</p>
| [
{
"answer_id": 8657,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 0,
"selected": false,
"text": "<p>The <code>var hello</code> stuff is compiler magic and will work without Linq.</p>\n\n<p>Try adding a reference to <code>System... | 2008/08/12 | [
"https://Stackoverflow.com/questions/8651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383/"
] | I am trying to load Linq on my .Net 3.5 enabled web server by adding the following to my .aspx page:
```
<%@ Import Namespace="System.Query" %>
```
However, this fails and tells me it cannot find the namespace.
>
> The type or namespace name 'Query' does not exist in the namespace 'System'
>
>
>
I have also tried with no luck:
* `System.Data.Linq`
* `System.Linq`
* `System.Xml.Linq`
I believe that .Net 3.5 is working because `var hello = "Hello World"` seems to work.
Can anyone help please?
PS: I just want to clarify that I don't use Visual Studio, I simply have a [Text Editor](http://www.ultraedit.com/) and write my code directly into .aspx files. | >
> I have version 2 selected in IIS and I
>
>
>
Well, surely that's your problem? Select 3.5.
Actually, here's the real info:
<http://www.hanselman.com/blog/HowToSetAnIISApplicationOrAppPoolToUseASPNET35RatherThan20.aspx> |
8,669 | <p>I'm trying to write a Crystal Report which has totals grouped in a different way to the main report. The only way I've been able to do this so far is to use a subreport for the totals, but it means having to hit the data source again to retrieve the same data, which seems like nonsense. Here's a simplified example:</p>
<pre><code> date name earnings source location
-----------------------------------------------------------
12-AUG-2008 Tom $50.00 washing cars uptown
12-AUG-2008 Dick $100.00 washing cars downtown { main report }
12-AUG-2008 Harry $75.00 mowing lawns around town
total earnings for washing cars: $150.00 { subreport }
total earnings for mowing lawns: $75.00
date name earnings source location
-----------------------------------------------------------
13-AUG-2008 John $95.00 dog walking downtown
13-AUG-2008 Jane $105.00 washing cars around town { main report }
13-AUG-2008 Dave $65.00 mowing lawns around town
total earnings for dog walking: $95.00
total earnings for washing cars: $105.00 { subreport }
total earnings for mowing lawns: $65.00
</code></pre>
<p>In this example, the main report is grouped by 'date', but the totals are grouped additionally by 'source'. I've looked up examples of using running totals, but they don't really do what I need. Isn't there some way of storing the result set and having both the main report and the subreport reference the same data?</p>
| [
{
"answer_id": 8751,
"author": "N8g",
"author_id": 1104,
"author_profile": "https://Stackoverflow.com/users/1104",
"pm_score": 1,
"selected": false,
"text": "<p>The only way I can think of doing this without a second run through the data would be by creating some formulas to do running t... | 2008/08/12 | [
"https://Stackoverflow.com/questions/8669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1030/"
] | I'm trying to write a Crystal Report which has totals grouped in a different way to the main report. The only way I've been able to do this so far is to use a subreport for the totals, but it means having to hit the data source again to retrieve the same data, which seems like nonsense. Here's a simplified example:
```
date name earnings source location
-----------------------------------------------------------
12-AUG-2008 Tom $50.00 washing cars uptown
12-AUG-2008 Dick $100.00 washing cars downtown { main report }
12-AUG-2008 Harry $75.00 mowing lawns around town
total earnings for washing cars: $150.00 { subreport }
total earnings for mowing lawns: $75.00
date name earnings source location
-----------------------------------------------------------
13-AUG-2008 John $95.00 dog walking downtown
13-AUG-2008 Jane $105.00 washing cars around town { main report }
13-AUG-2008 Dave $65.00 mowing lawns around town
total earnings for dog walking: $95.00
total earnings for washing cars: $105.00 { subreport }
total earnings for mowing lawns: $65.00
```
In this example, the main report is grouped by 'date', but the totals are grouped additionally by 'source'. I've looked up examples of using running totals, but they don't really do what I need. Isn't there some way of storing the result set and having both the main report and the subreport reference the same data? | Hmm... as nice as it is to call the stored proc from the report and have it all contained in one location, however we found (like you) that you eventually hit a point where you can't get crystal to do what you want even tho the data is right there.
We ended up introducing a business layer which sits under the report and rather than "pulling" data from the report we "push" the datasets to it and bind the data to the report. The advantage is that you can manipulate the data in code in datasets or objects before it reaches the report and then simply bind the data to the report.
[This article](http://www.codeguru.com/csharp/.net/net_general/toolsand3rdparty/article.php/c13253) has a nice intro on how to setup pushing data to the reports. I understand that your time/business constraints may not allow you to do this, but if it's at all possible, I'd highly recommend it as it's meant we can remove all "coding" out of our reports and into managed code which is always a good thing. |
8,681 | <p>If you're using Opera 9.5x you may notice that our client-side <a href="http://docs.jquery.com/Plugins/Validation" rel="noreferrer">JQuery.Validate</a> code is disabled here at Stack Overflow.</p>
<pre><code>function initValidation() {
if (navigator.userAgent.indexOf("Opera") != -1) return;
$("#post-text").rules("add", { required: true, minlength: 5 });
}
</code></pre>
<p>That's because it generates an exception in Opera! Of course it works in every other browser we've tried. I'm starting to seriously, seriously hate Opera.</p>
<p>This is kind of a bummer because without proper client-side validation some of our requests will fail. We haven't had time to put in complete server-side messaging when data is incomplete, so <strong>you may see the YSOD on Opera much more than other browsers</strong>, if you forget to fill out all the fields on the form.</p>
<p>Any Opera-ites want to uncomment those lines (they're on core Ask & Answer pages like this one -- just View Source and search for <code>"Opera"</code>) and give it a go?</p>
| [
{
"answer_id": 8712,
"author": "Neall",
"author_id": 619,
"author_profile": "https://Stackoverflow.com/users/619",
"pm_score": 0,
"selected": false,
"text": "<p>I can't seem to reproduce this bug. Can you give more details?</p>\n\n<p>I have my copy of Opera masquerading as Firefox so the... | 2008/08/12 | [
"https://Stackoverflow.com/questions/8681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1/"
] | If you're using Opera 9.5x you may notice that our client-side [JQuery.Validate](http://docs.jquery.com/Plugins/Validation) code is disabled here at Stack Overflow.
```
function initValidation() {
if (navigator.userAgent.indexOf("Opera") != -1) return;
$("#post-text").rules("add", { required: true, minlength: 5 });
}
```
That's because it generates an exception in Opera! Of course it works in every other browser we've tried. I'm starting to seriously, seriously hate Opera.
This is kind of a bummer because without proper client-side validation some of our requests will fail. We haven't had time to put in complete server-side messaging when data is incomplete, so **you may see the YSOD on Opera much more than other browsers**, if you forget to fill out all the fields on the form.
Any Opera-ites want to uncomment those lines (they're on core Ask & Answer pages like this one -- just View Source and search for `"Opera"`) and give it a go? | turns out the problem was in the
```
{ debug : true }
```
option for the JQuery.Validate initializer. **With this removed, things work fine in Opera.** Thanks to Jörn Zaefferer for helping us figure this out!
Oh, and the $50 will be donated to the JQuery project. :) |
8,685 | <p>I'm trying to use <code>strtotime()</code> to respond to a button click to advance -1 and +1 days (two buttons) relative to the day advanced to on the previous click. </p>
<p><strong>Example:</strong> </p>
<ul>
<li>It's the 10th of the month, I click "-1 day" button, and now the date reads as the 9th. </li>
<li>I click the "-1 day" button again and now the readout states the 8th day. </li>
<li>I click the "+1 day" button and now the readout states it's the 9th. </li>
</ul>
<p>I understand the buttons and the displaying the date and using <code>$_GET</code> and PHP to pass info, but how do I get <code>strtotime()</code> to work on the relative date from the last time the time travel script was called?</p>
<p>My work so far has let me show yesterday and today relative to <em>now</em> but not relative to, for example, the <em>day before yesterday</em>, or the <em>day after tomorrow</em>. Or if I use my <strong>"last monday"</strong> button, the day before or after whatever that day is.</p>
| [
{
"answer_id": 8689,
"author": "Philip Reynolds",
"author_id": 1087,
"author_profile": "https://Stackoverflow.com/users/1087",
"pm_score": 1,
"selected": false,
"text": "<p>Kevin, you work off a solid absolute base (i.e. a date / time), not a relative time period. You then convert to the... | 2008/08/12 | [
"https://Stackoverflow.com/questions/8685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1149/"
] | I'm trying to use `strtotime()` to respond to a button click to advance -1 and +1 days (two buttons) relative to the day advanced to on the previous click.
**Example:**
* It's the 10th of the month, I click "-1 day" button, and now the date reads as the 9th.
* I click the "-1 day" button again and now the readout states the 8th day.
* I click the "+1 day" button and now the readout states it's the 9th.
I understand the buttons and the displaying the date and using `$_GET` and PHP to pass info, but how do I get `strtotime()` to work on the relative date from the last time the time travel script was called?
My work so far has let me show yesterday and today relative to *now* but not relative to, for example, the *day before yesterday*, or the *day after tomorrow*. Or if I use my **"last monday"** button, the day before or after whatever that day is. | Working from previous calls to the same script isn't really a good idea for this type of thing.
What you want to do is always pass two values to your script, the date, and the movement. (the below example is simplified so that you only pass the date, and it will always add one day to it)
Example
<http://www.site.com/addOneDay.php?date=1999-12-31>
```
<?php
echo Date("Y-m-d",(strtoTime($_GET[date])+86400));
?>
```
Please note that you should check to make sure that isset($\_GET[date]) before as well
If you really want to work from previous calls to the same script, you're going to have to do it with sessions, so please specify if that is the case. |
8,691 | <p>For a C# UserControl on Windows Mobile (though please answer if you know it for full Windows...it might work) how do you change what shows up in the Designer Properties window for one of the Control's public Properties. For example:</p>
<pre><code>private Color blah = Color.Black;
public Color Blah
{
get { return this.blah; }
set { this.blah = value; }
}
</code></pre>
<p>This shows up for the control, but it's in the "Misc" category and has no description or default value. I've tried using the settings in System.ComponentModel like "DesignerCategory", such as:</p>
<pre><code>[DesignerCategory("Custom")]
</code></pre>
<p>But says this is only valid for class declarations... could've sworn it was the System.ComponentModel items I used before...</p>
<h3>Update:</h3>
<p>@John said:</p>
<blockquote>
<p>DesignerCatogy is used to say if the
class is a form, component etc.</p>
<p>Try this:</p>
<p>[Category("Custom")]</p>
</blockquote>
<p>Is there a particular namespace I need to use in order to get those?
I've tried those exactly and the compiler doesn't recognize them.</p>
<p>In .NETCF all I seem to have available from System.ComponentModel is:</p>
<pre><code>DataObject,
DataObjectMethod,
DefaultValue,
DesignerCategory,
DesignTimeVisible,
EditorBrowsable
</code></pre>
<p>The only one it doesn't scream at is EditorBrowsable</p>
| [
{
"answer_id": 8693,
"author": "John",
"author_id": 33,
"author_profile": "https://Stackoverflow.com/users/33",
"pm_score": 3,
"selected": false,
"text": "<p><code>DesignerCategory</code> is used to say if the class is a form, component etc.</p>\n\n<p>For full windows the attribute you w... | 2008/08/12 | [
"https://Stackoverflow.com/questions/8691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/194/"
] | For a C# UserControl on Windows Mobile (though please answer if you know it for full Windows...it might work) how do you change what shows up in the Designer Properties window for one of the Control's public Properties. For example:
```
private Color blah = Color.Black;
public Color Blah
{
get { return this.blah; }
set { this.blah = value; }
}
```
This shows up for the control, but it's in the "Misc" category and has no description or default value. I've tried using the settings in System.ComponentModel like "DesignerCategory", such as:
```
[DesignerCategory("Custom")]
```
But says this is only valid for class declarations... could've sworn it was the System.ComponentModel items I used before...
### Update:
@John said:
>
> DesignerCatogy is used to say if the
> class is a form, component etc.
>
>
> Try this:
>
>
> [Category("Custom")]
>
>
>
Is there a particular namespace I need to use in order to get those?
I've tried those exactly and the compiler doesn't recognize them.
In .NETCF all I seem to have available from System.ComponentModel is:
```
DataObject,
DataObjectMethod,
DefaultValue,
DesignerCategory,
DesignTimeVisible,
EditorBrowsable
```
The only one it doesn't scream at is EditorBrowsable | Is this of use to you? I am not into CF development, but it looks like you need to add some XML metadata to enable it:
<http://blogs.msdn.com/bluecollar/archive/2007/02/08/adding-compact-framework-design-time-attributes-or-more-fun-with-textboxes.aspx>
Interesting read.. Looks like a lot of design time support was stripped out of CF because you dont design them on the devices.. Which seems kinda weird to me.. Cant imagine using a handheld as a development rig!
Scroll down about half way for the good stuff ;) |
8,692 | <p>What are the libraries that support XPath? Is there a full implementation? How is the library used? Where is its website?</p>
| [
{
"answer_id": 8699,
"author": "James Sulak",
"author_id": 207,
"author_profile": "https://Stackoverflow.com/users/207",
"pm_score": 6,
"selected": false,
"text": "<p>The <a href=\"http://lxml.de/\" rel=\"noreferrer\">lxml package</a> supports xpath. It seems to work pretty well, althou... | 2008/08/12 | [
"https://Stackoverflow.com/questions/8692",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | What are the libraries that support XPath? Is there a full implementation? How is the library used? Where is its website? | [libxml2](http://xmlsoft.org/python.html) has a number of advantages:
1. Compliance to the [spec](http://www.w3.org/TR/xpath)
2. Active development and a community participation
3. Speed. This is really a python wrapper around a C implementation.
4. Ubiquity. The libxml2 library is pervasive and thus well tested.
Downsides include:
1. Compliance to the [spec](http://www.w3.org/TR/xpath). It's strict. Things like default namespace handling are easier in other libraries.
2. Use of native code. This can be a pain depending on your how your application is distributed / deployed. RPMs are available that ease some of this pain.
3. Manual resource handling. Note in the sample below the calls to freeDoc() and xpathFreeContext(). This is not very Pythonic.
If you are doing simple path selection, stick with [ElementTree](http://effbot.org/zone/element-xpath.htm) ( which is included in Python 2.5 ). If you need full spec compliance or raw speed and can cope with the distribution of native code, go with libxml2.
**Sample of libxml2 XPath Use**
---
```
import libxml2
doc = libxml2.parseFile("tst.xml")
ctxt = doc.xpathNewContext()
res = ctxt.xpathEval("//*")
if len(res) != 2:
print "xpath query: wrong node set size"
sys.exit(1)
if res[0].name != "doc" or res[1].name != "foo":
print "xpath query: wrong node set value"
sys.exit(1)
doc.freeDoc()
ctxt.xpathFreeContext()
```
**Sample of ElementTree XPath Use**
---
```
from elementtree.ElementTree import ElementTree
mydoc = ElementTree(file='tst.xml')
for e in mydoc.findall('/foo/bar'):
print e.get('title').text
```
--- |
8,728 | <p>I've got an MDI application written in Delphi 2006 which runs XP with the default theme. </p>
<p>Is there a way of controlling the appearance of the MDI Children to avoid the large XP-style title bar on each window? </p>
<p>I've tried setting the <code>BorderStyle</code> of the <code>MDIChildren</code> to <code>bsSizeToolWin</code> but they are still rendered as normal Forms.</p>
| [
{
"answer_id": 8792,
"author": "onnodb",
"author_id": 1037,
"author_profile": "https://Stackoverflow.com/users/1037",
"pm_score": 0,
"selected": false,
"text": "<p>I don't think there is; in my experience, MDI in Delphi is very strictly limited and controlled by its implementation in the... | 2008/08/12 | [
"https://Stackoverflow.com/questions/8728",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1008/"
] | I've got an MDI application written in Delphi 2006 which runs XP with the default theme.
Is there a way of controlling the appearance of the MDI Children to avoid the large XP-style title bar on each window?
I've tried setting the `BorderStyle` of the `MDIChildren` to `bsSizeToolWin` but they are still rendered as normal Forms. | All your need - overload procedure CreateWindowHandle, like this:
```
unit CHILDWIN;
interface
uses Windows, Classes, Graphics, Forms, Controls, StdCtrls;
type
TMDIChild = class(TForm)
private
{ Private declarations }
public
{ Public declarations }
procedure CreateWindowHandle(const Params: TCreateParams); override;
end;
implementation
{$R *.dfm}
procedure TMDIChild.CreateWindowHandle(const Params: TCreateParams);
begin
inherited CreateWindowHandle(Params);
SetWindowLong(Handle, GWL_EXSTYLE, WS_EX_TOOLWINDOW);
end;
end.
``` |
8,763 | <p>I'm trying to rebuild an old metronome application that was originally written using <code>MFC</code> in C++ to be written in <code>.NET</code> using <code>C#</code>. One of the issues I'm running into is playing the midi files that are used to represent the metronome "clicks".</p>
<p>I've found a few articles online about playing <code>MIDI</code> in .NET, but most of them seem to rely on custom libraries that someone has cobbled together and made available. I'm not averse to using these, but I'd rather understand for myself how this is being done, since it seems like it <em>should</em> be a mostly trivial exercise.</p>
<p>So, am I missing something? Or is it just difficult to use MIDI inside of a .NET application?</p>
| [
{
"answer_id": 8773,
"author": "Whisk",
"author_id": 908,
"author_profile": "https://Stackoverflow.com/users/908",
"pm_score": 1,
"selected": false,
"text": "<p>I can't claim to know much about it, but I don't think it's that straightforward - Carl Franklin of <a href=\"http://www.dotnet... | 2008/08/12 | [
"https://Stackoverflow.com/questions/8763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1108/"
] | I'm trying to rebuild an old metronome application that was originally written using `MFC` in C++ to be written in `.NET` using `C#`. One of the issues I'm running into is playing the midi files that are used to represent the metronome "clicks".
I've found a few articles online about playing `MIDI` in .NET, but most of them seem to rely on custom libraries that someone has cobbled together and made available. I'm not averse to using these, but I'd rather understand for myself how this is being done, since it seems like it *should* be a mostly trivial exercise.
So, am I missing something? Or is it just difficult to use MIDI inside of a .NET application? | I think you'll need to p/invoke out to the windows api to be able to play midi files from .net.
This codeproject article does a good job on explaining how to do this:
[vb.net article to play midi files](http://www.codeproject.com/KB/audio-video/vbnetSoundClass.aspx)
To rewrite this is c# you'd need the following import statement for mciSendString:
```
[DllImport("winmm.dll")]
static extern Int32 mciSendString(String command, StringBuilder buffer,
Int32 bufferSize, IntPtr hwndCallback);
```
Hope this helps - good luck! |
8,790 | <p>I have a build script and as part of that script it copies a jar file to a directory, for ease lets call it the utils jar. the utils jar is built by another build script sitting in another directory. What im trying to do have my build script run the utils build script so that I can ensure the utils jar is up to date.</p>
<p>So I know I need to import the utils build file.</p>
<pre><code><import file="../utils/build/build.xml" />
</code></pre>
<p>Which doesn't work because the import task, unlike almost every other ant taks, doesn't run from basedir, it runs from the pwd. So to get around that I have this little ditty, which does successfully import the build file</p>
<pre><code> <property name="baseDirUpOne" location=".." />
<import file="${baseDirUpOne}/utils/build/build.xml" />
</code></pre>
<p>So now that ive solved my import problem I need to call the task, well that should be easy right:</p>
<pre><code><antcall target="utils.package" />
</code></pre>
<p><em>note that in the above, utils is the project name of ../utils/build/build.xml</em></p>
<p>the problem I'm now running into is that ant call doesn't execute in ../utils/build so what I need, and cant find, is a runat property or something similar, essentially:</p>
<pre><code><antcall target="utils.package" runat="../utils/build" />
</code></pre>
<p>The reason I need this is that in my utils build file the step to select which code to copy to the jar is based on relative paths so as to avoid hardcoding paths in my ant file. Any ideas? </p>
| [
{
"answer_id": 8805,
"author": "Theo",
"author_id": 1109,
"author_profile": "https://Stackoverflow.com/users/1109",
"pm_score": 6,
"selected": true,
"text": "<p>I've got something similar set up: I have a main Ant build.xml which calls a separate build.xml that takes care of building my ... | 2008/08/12 | [
"https://Stackoverflow.com/questions/8790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/292/"
] | I have a build script and as part of that script it copies a jar file to a directory, for ease lets call it the utils jar. the utils jar is built by another build script sitting in another directory. What im trying to do have my build script run the utils build script so that I can ensure the utils jar is up to date.
So I know I need to import the utils build file.
```
<import file="../utils/build/build.xml" />
```
Which doesn't work because the import task, unlike almost every other ant taks, doesn't run from basedir, it runs from the pwd. So to get around that I have this little ditty, which does successfully import the build file
```
<property name="baseDirUpOne" location=".." />
<import file="${baseDirUpOne}/utils/build/build.xml" />
```
So now that ive solved my import problem I need to call the task, well that should be easy right:
```
<antcall target="utils.package" />
```
*note that in the above, utils is the project name of ../utils/build/build.xml*
the problem I'm now running into is that ant call doesn't execute in ../utils/build so what I need, and cant find, is a runat property or something similar, essentially:
```
<antcall target="utils.package" runat="../utils/build" />
```
The reason I need this is that in my utils build file the step to select which code to copy to the jar is based on relative paths so as to avoid hardcoding paths in my ant file. Any ideas? | I've got something similar set up: I have a main Ant build.xml which calls a separate build.xml that takes care of building my tests. This is how I do it:
```
<target name="build-tests">
<subant target="build">
<fileset dir="${test.home}" includes="build.xml"/>
</subant>
</target>
```
The trick is to use [`subant`](http://ant.apache.org/manual/Tasks/subant.html) instead of `antcall`. You don't have to import the other build file. |