qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
277,566
|
<p>I'm looking for a Windows tool that is able to log every action (read & write) that were made to a specific path inside the local Filesystem in order to debug a program (find out why it is sometimes slow and sometimes not).
In theory it could work like a virus scanner that is recognizing every file that any of the running programs do read or write and logs every thing that it sees.</p>
|
[
{
"answer_id": 277622,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 1,
"selected": false,
"text": "jpegPhoto jpegPhoto"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25782/"
] |
277,569
|
<p>In PHP, is there an easy way to convert a number to a word? For instance, <em>27</em> to <em>twenty-seven</em>.</p>
|
[
{
"answer_id": 277586,
"author": "Chris",
"author_id": 4742,
"author_profile": "https://Stackoverflow.com/users/4742",
"pm_score": 6,
"selected": true,
"text": "<?php\n/**\n * English Number Converter - Collection of PHP functions to convert a number\n * into English text.\n *\n * This exact code is licensed under CC-Wiki on Stackoverflow.\n * http://creativecommons.org/licenses/by-sa/3.0/\n *\n * @link http://stackoverflow.com/q/277569/367456\n * @question Is there an easy way to convert a number to a word in PHP?\n *\n * This file incorporates work covered by the following copyright and\n * permission notice:\n *\n * Copyright 2007-2008 Brenton Fletcher. http://bloople.net/num2text\n * You can use this freely and modify it however you want.\n */\n\nfunction convertNumber($number)\n{\n list($integer, $fraction) = explode(\".\", (string) $number);\n\n $output = \"\";\n\n if ($integer{0} == \"-\")\n {\n $output = \"negative \";\n $integer = ltrim($integer, \"-\");\n }\n else if ($integer{0} == \"+\")\n {\n $output = \"positive \";\n $integer = ltrim($integer, \"+\");\n }\n\n if ($integer{0} == \"0\")\n {\n $output .= \"zero\";\n }\n else\n {\n $integer = str_pad($integer, 36, \"0\", STR_PAD_LEFT);\n $group = rtrim(chunk_split($integer, 3, \" \"), \" \");\n $groups = explode(\" \", $group);\n\n $groups2 = array();\n foreach ($groups as $g)\n {\n $groups2[] = convertThreeDigit($g{0}, $g{1}, $g{2});\n }\n\n for ($z = 0; $z < count($groups2); $z++)\n {\n if ($groups2[$z] != \"\")\n {\n $output .= $groups2[$z] . convertGroup(11 - $z) . (\n $z < 11\n && !array_search('', array_slice($groups2, $z + 1, -1))\n && $groups2[11] != ''\n && $groups[11]{0} == '0'\n ? \" and \"\n : \", \"\n );\n }\n }\n\n $output = rtrim($output, \", \");\n }\n\n if ($fraction > 0)\n {\n $output .= \" point\";\n for ($i = 0; $i < strlen($fraction); $i++)\n {\n $output .= \" \" . convertDigit($fraction{$i});\n }\n }\n\n return $output;\n}\n\nfunction convertGroup($index)\n{\n switch ($index)\n {\n case 11:\n return \" decillion\";\n case 10:\n return \" nonillion\";\n case 9:\n return \" octillion\";\n case 8:\n return \" septillion\";\n case 7:\n return \" sextillion\";\n case 6:\n return \" quintrillion\";\n case 5:\n return \" quadrillion\";\n case 4:\n return \" trillion\";\n case 3:\n return \" billion\";\n case 2:\n return \" million\";\n case 1:\n return \" thousand\";\n case 0:\n return \"\";\n }\n}\n\nfunction convertThreeDigit($digit1, $digit2, $digit3)\n{\n $buffer = \"\";\n\n if ($digit1 == \"0\" && $digit2 == \"0\" && $digit3 == \"0\")\n {\n return \"\";\n }\n\n if ($digit1 != \"0\")\n {\n $buffer .= convertDigit($digit1) . \" hundred\";\n if ($digit2 != \"0\" || $digit3 != \"0\")\n {\n $buffer .= \" and \";\n }\n }\n\n if ($digit2 != \"0\")\n {\n $buffer .= convertTwoDigit($digit2, $digit3);\n }\n else if ($digit3 != \"0\")\n {\n $buffer .= convertDigit($digit3);\n }\n\n return $buffer;\n}\n\nfunction convertTwoDigit($digit1, $digit2)\n{\n if ($digit2 == \"0\")\n {\n switch ($digit1)\n {\n case \"1\":\n return \"ten\";\n case \"2\":\n return \"twenty\";\n case \"3\":\n return \"thirty\";\n case \"4\":\n return \"forty\";\n case \"5\":\n return \"fifty\";\n case \"6\":\n return \"sixty\";\n case \"7\":\n return \"seventy\";\n case \"8\":\n return \"eighty\";\n case \"9\":\n return \"ninety\";\n }\n } else if ($digit1 == \"1\")\n {\n switch ($digit2)\n {\n case \"1\":\n return \"eleven\";\n case \"2\":\n return \"twelve\";\n case \"3\":\n return \"thirteen\";\n case \"4\":\n return \"fourteen\";\n case \"5\":\n return \"fifteen\";\n case \"6\":\n return \"sixteen\";\n case \"7\":\n return \"seventeen\";\n case \"8\":\n return \"eighteen\";\n case \"9\":\n return \"nineteen\";\n }\n } else\n {\n $temp = convertDigit($digit2);\n switch ($digit1)\n {\n case \"2\":\n return \"twenty-$temp\";\n case \"3\":\n return \"thirty-$temp\";\n case \"4\":\n return \"forty-$temp\";\n case \"5\":\n return \"fifty-$temp\";\n case \"6\":\n return \"sixty-$temp\";\n case \"7\":\n return \"seventy-$temp\";\n case \"8\":\n return \"eighty-$temp\";\n case \"9\":\n return \"ninety-$temp\";\n }\n }\n}\n\nfunction convertDigit($digit)\n{\n switch ($digit)\n {\n case \"0\":\n return \"zero\";\n case \"1\":\n return \"one\";\n case \"2\":\n return \"two\";\n case \"3\":\n return \"three\";\n case \"4\":\n return \"four\";\n case \"5\":\n return \"five\";\n case \"6\":\n return \"six\";\n case \"7\":\n return \"seven\";\n case \"8\":\n return \"eight\";\n case \"9\":\n return \"nine\";\n }\n}\n"
},
{
"answer_id": 278054,
"author": "Milen A. Radev",
"author_id": 15785,
"author_profile": "https://Stackoverflow.com/users/15785",
"pm_score": 3,
"selected": false,
"text": "Numbers_Words"
},
{
"answer_id": 1107274,
"author": "user132513",
"author_id": 132513,
"author_profile": "https://Stackoverflow.com/users/132513",
"pm_score": 5,
"selected": false,
"text": "intl <?php\nif ($argc < 3) \n {\n echo \"usage: php {$argv[0]} lang-tag number ...\\n\";\n exit;\n }\n\narray_shift($argv);\n$lang_tag = array_shift($argv);\n\n$nf1 = new NumberFormatter($lang_tag, NumberFormatter::DECIMAL);\n$nf2 = new NumberFormatter($lang_tag, NumberFormatter::SPELLOUT);\n\nforeach ($argv as $num) \n {\n echo $nf1->format($num).' is '.$nf2->format($num).\"\\n\"; \n }\n"
},
{
"answer_id": 12411682,
"author": "Coder4web",
"author_id": 787253,
"author_profile": "https://Stackoverflow.com/users/787253",
"pm_score": -1,
"selected": false,
"text": "$wordnum = numberToWord($number);\necho $wordnum.\"<BR>\";\n\nfunction singledigit($number){\n switch($number){\n case 0:$word = \"zero\";break;\n case 1:$word = \"One\";break;\n case 2:$word = \"two\";break;\n case 3:$word = \"three\";break;\n case 4:$word = \"Four\";break;\n case 5:$word = \"Five\";break;\n case 6:$word = \"Six\";break;\n case 7:$word = \"Seven\";break;\n case 8:$word = \"Eight\";break;\n case 9:$word = \"Nine\";break;\n }\n return $word;\n }\n\n function doubledigitnumber($number){\n if($number == 0){\n $word = \"\";\n }\n else{\n $word = singledigit($number);\n } \n return $word;\n }\n\n function doubledigit($number){\n switch($number[0]){\n case 0:$word = doubledigitnumber($number[1]);break;\n case 1:\n switch($number[1]){\n case 0:$word = \"Ten\";break;\n case 1:$word = \"Eleven\";break;\n case 2:$word = \"Twelve\";break;\n case 3:$word = \"Thirteen\";break;\n case 4:$word = \"Fourteen\";break;\n case 5:$word = \"Fifteen\";break;\n case 6:$word = \"Sixteen\";break;\n case 7:$word = \"Seventeen\";break;\n case 8:$word = \"Eighteen\";break;\n case 9:$word = \"Ninteen\";break;\n }break;\n case 2:$word = \"Twenty\".doubledigitnumber($number[1]);break; \n case 3:$word = \"Thirty\".doubledigitnumber($number[1]);break;\n case 4:$word = \"Forty\".doubledigitnumber($number[1]);break;\n case 5:$word = \"Fifty\".doubledigitnumber($number[1]);break;\n case 6:$word = \"Sixty\".doubledigitnumber($number[1]);break;\n case 7:$word = \"Seventy\".doubledigitnumber($number[1]);break;\n case 8:$word = \"Eighty\".doubledigitnumber($number[1]);break;\n case 9:$word = \"Ninety\".doubledigitnumber($number[1]);break;\n\n }\n return $word;\n }\n\n function unitdigit($numberlen,$number){\n switch($numberlen){ \n case 3:$word = \"Hundred\";break;\n case 4:$word = \"Thousand\";break;\n case 5:$word = \"Thousand\";break;\n case 6:$word = \"Lakh\";break;\n case 7:$word = \"Lakh\";break;\n case 8:$word = \"Crore\";break;\n case 9:$word = \"Crore\";break;\n\n }\n return $word;\n }\n\n function numberToWord($number){\n\n $numberlength = strlen($number);\n if ($numberlength == 1) { \n return singledigit($number);\n }elseif ($numberlength == 2) {\n return doubledigit($number);\n }\n else {\n\n $word = \"\";\n $wordin = \"\";\n\n if($numberlength == 9){\n if($number[0] >0){\n $unitdigit = unitdigit($numberlength,$number[0]);\n $word = doubledigit($number[0].$number[1]) .\" \".$unitdigit.\" \";\n return $word.\" \".numberToWord(substr($number,2));\n }\n else{\n return $word.\" \".numberToWord(substr($number,1));\n }\n }\n\n if($numberlength == 7){\n if($number[0] >0){\n $unitdigit = unitdigit($numberlength,$number[0]);\n $word = doubledigit($number[0].$number[1]) .\" \".$unitdigit.\" \";\n return $word.\" \".numberToWord(substr($number,2));\n }\n else{\n return $word.\" \".numberToWord(substr($number,1));\n }\n\n }\n\n if($numberlength == 5){\n if($number[0] >0){\n $unitdigit = unitdigit($numberlength,$number[0]);\n $word = doubledigit($number[0].$number[1]) .\" \".$unitdigit.\" \";\n return $word.\" \".numberToWord(substr($number,2));\n }\n else{\n return $word.\" \".numberToWord(substr($number,1));\n }\n\n\n }\n else{\n if($number[0] >0){\n $unitdigit = unitdigit($numberlength,$number[0]);\n $word = singledigit($number[0]) .\" \".$unitdigit.\" \";\n } \n return $word.\" \".numberToWord(substr($number,1));\n }\n }\n }\n"
},
{
"answer_id": 15594551,
"author": "wolfe",
"author_id": 2203697,
"author_profile": "https://Stackoverflow.com/users/2203697",
"pm_score": 2,
"selected": false,
"text": "function singledigit($number){\n switch($number){\n case 0:$word = \"zero\";break;\n case 1:$word = \"one\";break;\n case 2:$word = \"two\";break;\n case 3:$word = \"three\";break;\n case 4:$word = \"four\";break;\n case 5:$word = \"five\";break;\n case 6:$word = \"six\";break;\n case 7:$word = \"seven\";break;\n case 8:$word = \"eight\";break;\n case 9:$word = \"nine\";break;\n }\n return $word;\n}\n\nfunction doubledigitnumber($number){\n if($number == 0){\n $word = \"\";\n }\n else{\n $word = \"-\".singledigit($number);\n } \n return $word;\n}\n\nfunction doubledigit($number){\n switch($number[0]){\n case 0:$word = doubledigitnumber($number[1]);break;\n case 1:\n switch($number[1]){\n case 0:$word = \"ten\";break;\n case 1:$word = \"eleven\";break;\n case 2:$word = \"twelve\";break;\n case 3:$word = \"thirteen\";break;\n case 4:$word = \"fourteen\";break;\n case 5:$word = \"fifteen\";break;\n case 6:$word = \"sixteen\";break;\n case 7:$word = \"seventeen\";break;\n case 8:$word = \"eighteen\";break;\n case 9:$word = \"ninteen\";break;\n }break;\n case 2:$word = \"twenty\".doubledigitnumber($number[1]);break; \n case 3:$word = \"thirty\".doubledigitnumber($number[1]);break;\n case 4:$word = \"forty\".doubledigitnumber($number[1]);break;\n case 5:$word = \"fifty\".doubledigitnumber($number[1]);break;\n case 6:$word = \"sixty\".doubledigitnumber($number[1]);break;\n case 7:$word = \"seventy\".doubledigitnumber($number[1]);break;\n case 8:$word = \"eighty\".doubledigitnumber($number[1]);break;\n case 9:$word = \"ninety\".doubledigitnumber($number[1]);break;\n\n }\n return $word;\n}\n\nfunction unitdigit($numberlen,$number){\n switch($numberlen){ \n case 3:case 6:case 9:case 12:$word = \"hundred\";break;\n case 4:case 5:$word = \"thousand\";break;\n case 7:case 8:$word = \"million\";break;\n case 10:case 11:$word = \"billion\";break;\n }\n return $word;\n}\n\nfunction numberToWord($number){\n\n $numberlength = strlen($number);\n if ($numberlength == 1) { \n return singledigit($number);\n }elseif ($numberlength == 2) {\n return doubledigit($number);\n }\n else {\n\n $word = \"\";\n $wordin = \"\";\n switch ($numberlength ) {\n case 5:case 8: case 11:\n if($number[0] >0){\n $unitdigit = unitdigit($numberlength,$number[0]);\n $word = doubledigit($number[0].$number[1]) .\" \".$unitdigit.\" \";\n return $word.\" \".numberToWord(substr($number,2));\n }\n else{\n return $word.\" \".numberToWord(substr($number,1));\n }\n break;\n default:\n if($number[0] >0){\n $unitdigit = unitdigit($numberlength,$number[0]);\n $word = singledigit($number[0]) .\" \".$unitdigit.\" \";\n } \n return $word.\" \".numberToWord(substr($number,1));\n }\n }\n}\n"
},
{
"answer_id": 40739003,
"author": "Works for a Living",
"author_id": 2634948,
"author_profile": "https://Stackoverflow.com/users/2634948",
"pm_score": 0,
"selected": false,
"text": "longform numberformat numberformat number_format() number_format 2,147,483,647 9 quintillion longform string ajax ''+number 999 Centillion, 999 etc. $number = '999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999';\nreallyBig::longform($number);\n - reallyBig::longform('-C55LL-M5-4-a-9u7-71m3-M8'); negative five billion, five hundred fifty-four million, nine hundred seventy-seven thousand, one hundred thirty-eight numberformat class reallyBig\n{\n private static $map, $strings;\n private static function map()\n {\n $map = array();\n $num = 1;\n $count = 1;\n while($num < 307)\n {\n if($count == 1) $map[$num] = $num+2;\n elseif($count == 2) $map[$num] = $num+1;\n else \n {\n $map[$num] = $num;\n $count = 0;\n }\n $count++;\n $num++;\n }\n return $map;\n }\n private static function strings()\n {\n return array \n (\n 6 => 'thousand',\n 9 => 'million',\n 12 => 'billion',\n 15 => 'trillion',\n 18 => 'quadrillion',\n 21 => 'quintillion',\n 24 => 'sextillion',\n 27 => 'septillion',\n 30 => 'octillion',\n 33 => 'nonillion',\n 36 => 'decillion',\n 39 => 'undecillion',\n 42 => 'duodecillion',\n 45 => 'tredecillion',\n 48 => 'quattuordecillion',\n 51 => 'quindecillion',\n 54 => 'sexdecillion',\n 57 => 'septendecillion',\n 60 => 'octodecillion',\n 63 => 'novemdecillion',\n 66 => 'vigintillion',\n 69 => 'unvigintillion',\n 72 => 'duovigintillion',\n 75 => 'trevigintillion',\n 78 => 'quattuorvigintillion',\n 81 => 'quinvigintillion',\n 84 => 'sexvigintillion',\n 87 => 'septenvigintillion',\n 90 => 'octovigintillion',\n 93 => 'novemvigintillion',\n 96 => 'trigintillion',\n 99 => 'untrigintillion',\n 102 => 'duotrigintillion',\n 105 => 'tretrigintillion',\n 108 => 'quattuortrigintillion',\n 111 => 'quintrigintillion',\n 114 => 'sextrigintillion',\n 117 => 'septentrigintillion',\n 120 => 'octotrigintillion',\n 123 => 'novemtrigintillion',\n 126 => 'quadragintillion',\n 129 => 'unquadragintillion',\n 132 => 'duoquadragintillion',\n 135 => 'trequadragintillion',\n 138 => 'quattuorquadragintillion',\n 141 => 'quinquadragintillion',\n 144 => 'sexquadragintillion',\n 147 => 'septenquadragintillion',\n 150 => 'octoquadragintillion',\n 153 => 'novemquadragintillion',\n 156 => 'quinquagintillion',\n 159 => 'unquinquagintillion',\n 162 => 'duoquinquagintillion',\n 165 => 'trequinquagintillion',\n 168 => 'quattuorquinquagintillion',\n 171 => 'quinquinquagintillion',\n 174 => 'sexquinquagintillion',\n 177 => 'septenquinquagintillion',\n 180 => 'octoquinquagintillion',\n 183 => 'novemquinquagintillion',\n 186 => 'sexagintillion',\n 189 => 'unsexagintillion',\n 192 => 'duosexagintillion',\n 195 => 'tresexagintillion',\n 198 => 'quattuorsexagintillion',\n 201 => 'quinsexagintillion',\n 204 => 'sexsexagintillion',\n 207 => 'septensexagintillion',\n 210 => 'octosexagintillion',\n 213 => 'novemsexagintillion',\n 216 => 'septuagintillion',\n 219 => 'unseptuagintillion',\n 222 => 'duoseptuagintillion',\n 225 => 'treseptuagintillion',\n 228 => 'quattuorseptuagintillion',\n 231 => 'quinseptuagintillion',\n 234 => 'sexseptuagintillion',\n 237 => 'septenseptuagintillion',\n 240 => 'octoseptuagintillion',\n 243 => 'novemseptuagintillion',\n 246 => 'octogintillion',\n 249 => 'unoctogintillion',\n 252 => 'duooctogintillion',\n 255 => 'treoctogintillion',\n 258 => 'quattuoroctogintillion',\n 261 => 'quinoctogintillion',\n 264 => 'sexoctogintillion',\n 267 => 'septenoctogintillion',\n 270 => 'octooctogintillion',\n 273 => 'novemoctogintillion',\n 276 => 'nonagintillion',\n 279 => 'unnonagintillion',\n 282 => 'duononagintillion',\n 285 => 'trenonagintillion',\n 288 => 'quattuornonagintillion',\n 291 => 'quinnonagintillion',\n 294 => 'sexnonagintillion',\n 297 => 'septennonagintillion',\n 300 => 'octononagintillion',\n 303 => 'novemnonagintillion',\n 306 => 'centillion',\n );\n }\n public static function longform($number = string, $commas = true)\n {\n $negative = substr($number, 0, 1) == '-' ? 'negative ' : '';\n list($number) = explode('.', $number); \n $number = trim(preg_replace(\"/[^0-9]/u\", \"\", $number));\n $number = (string)(ltrim($number,'0'));\n if(empty($number)) return 'zero';\n $length = strlen($number);\n if($length < 2) return $negative.self::ones($number);\n if($length < 3) return $negative.self::tens($number);\n if($length < 4) return $commas ? $negative.str_replace('hundred ', 'hundred and ', self::hundreds($number)) : $negative.self::hundreds($number);\n if($length < 307) \n {\n self::$map = self::map();\n self::$strings = self::strings();\n $result = self::beyond($number, self::$map[$length]);\n if(!$commas) return $negative.$result;\n $strings = self::$strings;\n $thousand = array_shift($strings);\n foreach($strings as $string) $result = str_replace($string.' ', $string.', ', $result);\n if(strpos($result, 'thousand') !== false) list($junk,$remainder) = explode('thousand', $result);\n else $remainder = $result;\n return strpos($remainder, 'hundred') !== false ? $negative.str_replace('thousand ', 'thousand, ', $result) : $negative.str_replace('thousand ', 'thousand and ', $result);\n }\n return 'a '.$negative.'number too big for your britches';\n }\n private static function ones($number)\n {\n $ones = array('zero','one','two','three','four','five','six','seven','eight','nine');\n return $ones[$number];\n }\n private static function tens($number)\n {\n $number = (string)(ltrim($number,'0'));\n if(strlen($number) < 2) return self::ones($number);\n if($number < 20)\n {\n $teens = array('ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen');\n return $teens[($number-10)];\n }\n else\n {\n $tens = array('','','twenty','thirty','forty','fifty','sixty','seventy','eighty','ninety');\n $word = $tens[$number[0]];\n return empty($number[1]) ? $word : $word.'-'.self::ones($number[1]);\n }\n }\n private static function hundreds($number)\n {\n $number = (string)(ltrim($number,'0'));\n if(strlen($number) < 3) return self::tens($number);\n $word = self::ones($number[0]).' hundred';\n $remainder = substr($number, -2);\n if(ltrim($remainder,'0') != '') $word .= ' '.self::tens($remainder);\n return $word;\n }\n private static function beyond($number, $limit)\n {\n $number = (string)(ltrim($number,'0'));\n $length = strlen($number);\n if($length < 4) return self::hundreds($number);\n if($length < ($limit-2)) return self::beyond($number, self::$map[($limit-3)]);\n if($length == $limit) $word = self::hundreds(substr($number, 0, 3), true);\n elseif($length == ($limit-1)) $word = self::tens(substr($number, 0, 2));\n else $word = self::ones($number[0]);\n $word .= ' '.self::$strings[$limit];\n $sub = ($limit-3);\n $remainder = substr($number, -$sub);\n if(ltrim($remainder,'0') != '') $word .= ' '.self::beyond($remainder, self::$map[$sub]);\n return $word;\n }\n public static function numberformat($number, $fixed = 0, $dec = '.', $thou = ',')\n {\n $negative = substr($number, 0, 1) == '-' ? '-' : '';\n $number = trim(preg_replace(\"/[^0-9\\.]/u\", \"\", $number));\n $number = (string)(ltrim($number,'0'));\n $fixed = (int)$fixed;\n if(!is_numeric($fixed)) $fixed = 0;\n if(strpos($number, $dec) !== false) list($number,$decimals) = explode($dec, $number); \n else $decimals = '0';\n if($fixed) $decimals = '.'.str_pad(substr($decimals, 0, $fixed), $fixed, 0, STR_PAD_RIGHT);\n else $decimals = '';\n $thousands = array_map('strrev', array_reverse(str_split(strrev($number), 3)));\n return $negative.implode($thou,$thousands).$decimals;\n }\n}\n"
},
{
"answer_id": 45125817,
"author": "prikkles",
"author_id": 5605952,
"author_profile": "https://Stackoverflow.com/users/5605952",
"pm_score": 3,
"selected": false,
"text": "4,835,301 returns \"Four million eight hundred and thirty five thousand three hundred and one.\"\n function convertNumber($num = false)\n{\n $num = str_replace(array(',', ''), '' , trim($num));\n if(! $num) {\n return false;\n }\n $num = (int) $num;\n $words = array();\n $list1 = array('', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven',\n 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'\n );\n $list2 = array('', 'ten', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety', 'hundred');\n $list3 = array('', 'thousand', 'million', 'billion', 'trillion', 'quadrillion', 'quintillion', 'sextillion', 'septillion',\n 'octillion', 'nonillion', 'decillion', 'undecillion', 'duodecillion', 'tredecillion', 'quattuordecillion',\n 'quindecillion', 'sexdecillion', 'septendecillion', 'octodecillion', 'novemdecillion', 'vigintillion'\n );\n $num_length = strlen($num);\n $levels = (int) (($num_length + 2) / 3);\n $max_length = $levels * 3;\n $num = substr('00' . $num, -$max_length);\n $num_levels = str_split($num, 3);\n for ($i = 0; $i < count($num_levels); $i++) {\n $levels--;\n $hundreds = (int) ($num_levels[$i] / 100);\n $hundreds = ($hundreds ? ' ' . $list1[$hundreds] . ' hundred' . ( $hundreds == 1 ? '' : '' ) . ' ' : '');\n $tens = (int) ($num_levels[$i] % 100);\n $singles = '';\n if ( $tens < 20 ) {\n $tens = ($tens ? ' and ' . $list1[$tens] . ' ' : '' );\n } elseif ($tens >= 20) {\n $tens = (int)($tens / 10);\n $tens = ' and ' . $list2[$tens] . ' ';\n $singles = (int) ($num_levels[$i] % 10);\n $singles = ' ' . $list1[$singles] . ' ';\n }\n $words[] = $hundreds . $tens . $singles . ( ( $levels && ( int ) ( $num_levels[$i] ) ) ? ' ' . $list3[$levels] . ' ' : '' );\n } //end for loop\n $commas = count($words);\n if ($commas > 1) {\n $commas = $commas - 1;\n }\n $words = implode(' ', $words);\n $words = preg_replace('/^\\s\\b(and)/', '', $words );\n $words = trim($words);\n $words = ucfirst($words);\n $words = $words . \".\";\n return $words;\n}\n"
},
{
"answer_id": 46253129,
"author": "Mukhpal Singh",
"author_id": 8608666,
"author_profile": "https://Stackoverflow.com/users/8608666",
"pm_score": -1,
"selected": false,
"text": "Amount in Words:</b><?=no_to_words($number)?>\n"
},
{
"answer_id": 49507047,
"author": "Shamshid",
"author_id": 4574432,
"author_profile": "https://Stackoverflow.com/users/4574432",
"pm_score": 3,
"selected": false,
"text": "<?php\n\n$number = '12345';\n$locale = 'en_US';\n$fmt = numfmt_create($locale, NumberFormatter::SPELLOUT);\n$in_words = numfmt_format($fmt, $number);\n\nprint_r($in_words);\n// twelve thousand three hundred forty-five\n\n?>\n"
},
{
"answer_id": 52483632,
"author": "Rk dev tech",
"author_id": 8744309,
"author_profile": "https://Stackoverflow.com/users/8744309",
"pm_score": 2,
"selected": false,
"text": "$f = new NumberFormatter(\"en\", NumberFormatter::SPELLOUT);\necho $f->format($myNumber);\n"
},
{
"answer_id": 53075499,
"author": "curiosity",
"author_id": 9671602,
"author_profile": "https://Stackoverflow.com/users/9671602",
"pm_score": 1,
"selected": false,
"text": ";extension=php_intl.dll <wamp_installation_path>/bin/php/php5.4.3/ <wamp_installation_path>/bin/apache/apache2.2.22/bin/ $f = new NumberFormatter(\"en\", NumberFormatter::SPELLOUT);\necho $f->format(123456);\n"
},
{
"answer_id": 68241616,
"author": "Mohammad Ali Abdullah",
"author_id": 12650566,
"author_profile": "https://Stackoverflow.com/users/12650566",
"pm_score": 0,
"selected": false,
"text": "<?php\n$grandTotalAmount = 700000000;\necho ($grandTotalAmount == round($grandTotalAmount)) ? convert_number_to_words(floatval($grandTotalAmount)) . ' Only' : convert_number_to_words(floatval($grandTotalAmount)) . ' Only';\n\nfunction convert_number_to_words($number) {\n $hyphen = ' ';\n $conjunction = ' and ';\n $separator = ', ';\n $negative = 'negative ';\n $decimal = ' Thai Baht And ';\n $dictionary = array(\n 0 => 'zero',\n 1 => 'one',\n 2 => 'two',\n 3 => 'three',\n 4 => 'four',\n 5 => 'five',\n 6 => 'six',\n 7 => 'seven',\n 8 => 'eight',\n 9 => 'nine',\n 10 => 'ten',\n 11 => 'eleven',\n 12 => 'twelve',\n 13 => 'thirteen',\n 14 => 'fourteen',\n 15 => 'fifteen',\n 16 => 'sixteen',\n 17 => 'seventeen',\n 18 => 'eighteen',\n 19 => 'nineteen',\n 20 => 'twenty',\n 30 => 'thirty',\n 40 => 'fourty',\n 50 => 'fifty',\n 60 => 'sixty',\n 70 => 'seventy',\n 80 => 'eighty',\n 90 => 'ninety',\n 100 => 'hundred',\n 1000 => 'thousand',\n 1000000 => 'million',\n 1000000000 => 'billion',\n 1000000000000 => 'trillion',\n 1000000000000000 => 'quadrillion',\n 1000000000000000000 => 'quintillion'\n );\n\n if (!is_numeric($number)) {\n return false;\n }\n\n if (($number >= 0 && (int) $number < 0) || (int) $number < 0 - PHP_INT_MAX) {\n // overflow\n trigger_error(\n 'convert_number_to_words only accepts numbers between -' . PHP_INT_MAX . ' and ' . PHP_INT_MAX, E_USER_WARNING\n );\n return false;\n }\n\n if ($number < 0) {\n return $negative . convert_number_to_words(abs($number));\n }\n\n $string = $fraction = null;\n\n\n if (strpos($number, '.') !== false) {\n list($number, $fraction) = explode('.', $number);\n }\n\n switch (true) {\n case $number < 21:\n $string = $dictionary[$number];\n break;\n case $number < 100:\n $tens = ((int) ($number / 10)) * 10;\n $units = $number % 10;\n $string = $dictionary[$tens];\n if ($units) {\n $string .= $hyphen . $dictionary[$units];\n }\n break;\n case $number < 1000:\n $hundreds = $number / 100;\n $remainder = $number % 100;\n $string = $dictionary[$hundreds] . ' ' . $dictionary[100];\n if ($remainder) {\n $string .= $conjunction . convert_number_to_words($remainder);\n }\n break;\n default:\n $baseUnit = pow(1000, floor(log($number, 1000)));\n $numBaseUnits = (int) ($number / $baseUnit);\n $remainder = $number % $baseUnit;\n $string = convert_number_to_words($numBaseUnits) . ' ' . $dictionary[$baseUnit];\n if ($remainder) {\n $string .= $remainder < 100 ? $conjunction : $separator;\n $string .= convert_number_to_words($remainder);\n }\n break;\n }\n\n if (null !== $fraction && is_numeric($fraction)) {\n $string .= $decimal;\n $words = array();\n foreach (str_split((string) $fraction) as $number) {\n $words[] = $dictionary[$number];\n }\n $string .= implode(' ', $words);\n }\n\n return $string;\n}\n?>\n"
},
{
"answer_id": 68280471,
"author": "Nazmul Haque",
"author_id": 5689349,
"author_profile": "https://Stackoverflow.com/users/5689349",
"pm_score": 0,
"selected": false,
"text": "$test = 1000025.05;\n\n$f = new \\NumberFormatter( locale_get_default(), \\NumberFormatter::SPELLOUT );\n\n$word = $f->format($test);\n\necho $word;\n"
},
{
"answer_id": 68815108,
"author": "Stergios Zg.",
"author_id": 1891386,
"author_profile": "https://Stackoverflow.com/users/1891386",
"pm_score": 0,
"selected": false,
"text": "protected function numberTextHelper($number)\n{\n if (($number < 0) || ($number > 999999999)) \n {\n throw new Exception(\"Number is out of range\");\n }\n \n $ones = array(\"\", \"One\", \"Two\", \"Three\", \"Four\", \"Five\", \"Six\", \"Seven\", \"Eight\", \"Nine\", \"Ten\", \"Eleven\", \"Twelve\", \"Thirteen\", \"Fourteen\", \"Fifteen\", \"Sixteen\", \"Seventeen\", \"Eightteen\", \"Nineteen\");\n $tens = array(\"\", \"\", \"Twenty\", \"Thirty\", \"Fourty\", \"Fifty\", \"Sixty\", \"Seventy\", \"Eigthy\", \"Ninety\");\n \n $giga = floor($number / 1000000);\n // Millions (giga)\n $number -= $giga * 1000000;\n\n $thousands = floor($number / 1000);\n \n // Thousands (kilo)\n $number -= $thousands * 1000;\n \n $hecto = floor($number / 100);\n \n // Hundreds (hecto)\n $number -= $hecto * 100;\n \n $deca = floor($number / 10);\n \n // Tens (deca)\n $n = $number % 10;\n \n $frac = round($number - (int)$number,2); \n\n // Ones\n $result = array();\n if ($giga) \n {\n $result[]= $this->numberTextHelper($giga).' '.($giga>1?'MILLIONS':'MILLION');\n }\n \n if ($thousands) \n {\n $result[]= $thousands>1?$this->numberTextHelper($thousands).' THOUSANDS':'THOUSAND';\n }\n \n if ($hecto) \n {\n $result[]= $this->numberTextHelper($hecto).'HUNDRED';\n }\n \n if ($deca) \n {\n if($deca<2)\n {\n $result[]= $ones[$deca * 10 + $n];\n $n=0;\n }\n else\n {\n $result[]= $tens[$deca];\n }\n }\n \n\n if ($n) \n {\n $result[]= $ones[$n];\n }\n\n if($frac) \n {\n $result[]= 'and';\n $result[]= $this->numberTextHelper($frac*100);\n $result[]= 'cents';\n }\n \n if(empty($result)) \n {\n $result[]= 'zero';\n }\n \n return implode(' ',$result);\n} \n function numberText($number)\n{\n $result=$this->numberTextHelper($number);\n $result=$this->strtoupper($result);\n $text=array_filter(explode(' ',$result));\n $translated=array_map(array($this,'getLang'),$text);\n return implode(' ',$translated);\n}\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21709/"
] |
277,589
|
<p>How to perform validation for a radio button group (one radio button should be selected) using jQuery validation plugin?</p>
|
[
{
"answer_id": 1843196,
"author": "Mahes",
"author_id": 301960,
"author_profile": "https://Stackoverflow.com/users/301960",
"pm_score": 5,
"selected": false,
"text": "myRadioGroupName : {required :true}\n"
},
{
"answer_id": 3347969,
"author": "Brandon Rome",
"author_id": 403864,
"author_profile": "https://Stackoverflow.com/users/403864",
"pm_score": 7,
"selected": false,
"text": "<input type=\"radio\" name=\"myoptions\" value=\"blue\" class=\"required\"> Blue<br />\n<input type=\"radio\" name=\"myoptions\" value=\"red\"> Red<br />\n<input type=\"radio\" name=\"myoptions\" value=\"green\"> Green\n"
},
{
"answer_id": 3540045,
"author": "Haider Abbas",
"author_id": 422262,
"author_profile": "https://Stackoverflow.com/users/422262",
"pm_score": 4,
"selected": false,
"text": "<fieldset>\n<input type=\"radio\" name=\"myoptions[]\" value=\"blue\"> Blue<br />\n<input type=\"radio\" name=\"myoptions[]\" value=\"red\"> Red<br />\n<input type=\"radio\" name=\"myoptions[]\" value=\"green\"> Green<br />\n<label for=\"myoptions[]\" class=\"error\" style=\"display:none;\">Please choose one.</label>\n</fieldset>\n rules: {\n 'myoptions[]':{ required:true }\n}\n"
},
{
"answer_id": 5984371,
"author": "Cin",
"author_id": 165963,
"author_profile": "https://Stackoverflow.com/users/165963",
"pm_score": 2,
"selected": false,
"text": " 'highlight': function (element, errorClass, validClass) {\n if($(element).attr('type') == 'radio'){\n $(element.form).find(\"input[type=radio]\").each(function(which){\n $(element.form).find(\"label[for=\" + this.id + \"]\").addClass(errorClass);\n $(this).addClass(errorClass);\n });\n } else {\n $(element.form).find(\"label[for=\" + element.id + \"]\").addClass(errorClass);\n $(element).addClass(errorClass);\n }\n },\n 'unhighlight': function (element, errorClass, validClass) {\n if($(element).attr('type') == 'radio'){\n $(element.form).find(\"input[type=radio]\").each(function(which){\n $(element.form).find(\"label[for=\" + this.id + \"]\").removeClass(errorClass);\n $(this).removeClass(errorClass);\n });\n }else {\n $(element.form).find(\"label[for=\" + element.id + \"]\").removeClass(errorClass);\n $(element).removeClass(errorClass);\n }\n },\n"
},
{
"answer_id": 12411759,
"author": "strudeltercero",
"author_id": 1614519,
"author_profile": "https://Stackoverflow.com/users/1614519",
"pm_score": 2,
"selected": false,
"text": "var $radio = $('input:radio[name=\"nameRadioButton\"]');\n$radio.addClass(\"validate[required]\");\n"
},
{
"answer_id": 13293266,
"author": "Matt Frear",
"author_id": 32598,
"author_profile": "https://Stackoverflow.com/users/32598",
"pm_score": 3,
"selected": false,
"text": "<span class=\"field-validation-valid\" data-valmsg-for=\"color\" data-valmsg-replace=\"true\"></span>\n<p><input type=\"radio\" name=\"color\" id=\"red\" value=\"R\" data-val=\"true\" data-val-required=\"Please choose one of these options:\"/> <label for=\"red\">Red</label></p>\n<p><input type=\"radio\" name=\"color\" id=\"green\" value=\"G\"/> <label for=\"green\">Green</label></p>\n<p><input type=\"radio\" name=\"color\" id=\"blue\" value=\"B\"/> <label for=\"blue\">Blue</label></p>\n"
},
{
"answer_id": 22778329,
"author": "Sayli Vaidya",
"author_id": 3340684,
"author_profile": "https://Stackoverflow.com/users/3340684",
"pm_score": 2,
"selected": false,
"text": "<div>\n <span class=\"radio inline\" style=\"margin-right: 10px;\">@Html.RadioButton(\"Gender\", \"Female\",false) Female</span>\n <span class=\"radio inline\" style=\"margin-right: 10px;\">@Html.RadioButton(\"Gender\", \"Male\",false) Male</span>\n <div class='GenderValidation' style=\"color:#ee8929;\"></div>\n</div>\n\n<input class=\"btn btn-primary\" type=\"submit\" value=\"Create\" id=\"create\"/>\n $(document).ready(function () {\n $('#create').click(function(){\n var gender=$('#Gender').val();\n\n if ($(\"#Gender:checked\").length == 0) {\n $('.GenderValidation').text(\"Gender is required.\");\n return false;\n }\n });\n});\n"
},
{
"answer_id": 55928886,
"author": "Sonobor",
"author_id": 2066416,
"author_profile": "https://Stackoverflow.com/users/2066416",
"pm_score": 0,
"selected": false,
"text": ".radio-group {\n position: relative;\n margin-top: 40px;\n} \n\n#myoptions-error {\n position: absolute; \n top: -25px;\n}\n <div class=\"radio-group\"> \n <input type=\"radio\" name=\"myoptions\" value=\"blue\" class=\"required\"> Blue<br /> \n <input type=\"radio\" name=\"myoptions\" value=\"red\"> Red<br /> \n <input type=\"radio\" name=\"myoptions\" value=\"green\"> Green\n</div><!-- end radio-group -->\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27052/"
] |
277,607
|
<p>After tinkering around to solve [this][1] problem, I think the core of the problem is the following:</p>
<p>When you use the Html.RadioButton() html helper with an Enum as value field, you can only choose your option once. AFter reposting the page, the helpers will ignore the value set in the call and set all radio buttons to the same value, being the value you selected the previous post back.
Am I doing something wrong?</p>
<p><em>Example (watch the <strong>value</strong> of the buttons)</em></p>
<pre><code><fieldset>
<legend>Test</legend>
<div>
<label for="SearchBag.EffectIndicatorAny" id="EffectIndicatorAnyLabel">
Any
</label>
<%=Html.RadioButton("SearchBag.EffectIndicator", "Any" , ViewData.Model.SearchBag.EffectIndicatorIsAny, new { @id = "SearchBag.EffectIndicatorAny" })%>
</div>
<div>
<label for="SearchBag.EffectIndicatorSolid" id="EffectIndicatorSolidLabel">
Solid
</label>
<%=Html.RadioButton("SearchBag.EffectIndicator", "Solid", ViewData.Model.SearchBag.EffectIndicatorIsSolid, new { @id = "SearchBag.EffectIndicatorSolid" })%>
</div>
<div>
<label for="SearchBag.EffectIndicatorEffect" id="EffectIndicatorEffectLabel">
Effect
</label>
<%=Html.RadioButton("SearchBag.EffectIndicator", "Effect", ViewData.Model.SearchBag.EffectIndicatorIsEffect, new { @id = "SearchBag.EffectIndicatorEffect" })%>
</div>
</fieldset>
</code></pre>
<p>Will generate </p>
<pre><code><fieldset>
<legend>Effect</legend>
<div class="horizontalRadio">
<label for="SearchBag.EffectIndicatorAny" id="EffectIndicatorAnyLabel">
Any
</label>
<input checked="checked" id="SearchBag.EffectIndicatorAny" name="SearchBag.EffectIndicator" type="radio" value="Any" />
</div>
<div class="horizontalRadio">
<label for="SearchBag.EffectIndicatorSolid" id="EffectIndicatorSolidLabel">
Solid
</label>
<input id="SearchBag.EffectIndicatorSolid" name="SearchBag.EffectIndicator" type="radio" value="Solid" />
</div>
<div class="horizontalRadio">
<label for="SearchBag.EffectIndicatorEffect" id="EffectIndicatorEffectLabel">
Effect
</label>
<input id="SearchBag.EffectIndicatorEffect" name="SearchBag.EffectIndicator" type="radio" value="Effect" />
</div>
</fieldset>
</code></pre>
<p>And will generate the second time:</p>
<pre><code><fieldset>
<legend>Effect</legend>
<div class="horizontalRadio">
<label for="SearchBag.EffectIndicatorAny" id="EffectIndicatorAnyLabel">
Any
</label>
<input id="SearchBag.EffectIndicatorAny" name="SearchBag.EffectIndicator" type="radio" value="Solid" />
</div>
<div class="horizontalRadio">
<label for="SearchBag.EffectIndicatorSolid" id="EffectIndicatorSolidLabel">
Solid
</label>
<input checked="checked" id="SearchBag.EffectIndicatorSolid" name="SearchBag.EffectIndicator" type="radio" value="Solid" />
</div>
<div class="horizontalRadio">
<label for="SearchBag.EffectIndicatorEffect" id="EffectIndicatorEffectLabel">
Effect
</label>
<input id="SearchBag.EffectIndicatorEffect" name="SearchBag.EffectIndicator" type="radio" value="Solid" />
</div>
</fieldset>
</code></pre>
|
[
{
"answer_id": 283605,
"author": "Boris Callens",
"author_id": 11333,
"author_profile": "https://Stackoverflow.com/users/11333",
"pm_score": 1,
"selected": false,
"text": "/*ToDo: remove when patched in framework*/\npublic static string MonkeyPatchedRadio(this HtmlHelper htmlHelper, string name, object value, bool isChecked, object htmlAttributes){\n string monkeyString = htmlHelper.RadioButton(name, value, isChecked, htmlAttributes);\n monkeyString = Regex.Replace(monkeyString, \"(?<=value=\\\").*(?=\\\".*)\", value.ToString()); \n return monkeyString;\n}\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11333/"
] |
277,618
|
<ul>
<li>What exactly is a learning curve?</li>
<li>And why is it wrong to use the term "steep learning curve" for something which has high entry barriers and takes quite some time to get into?</li>
</ul>
<p>As to the why-ness of this question:</p>
<ul>
<li>The terms are used often and inconsistently on Stack Overflow</li>
<li>I myself have been confused by it</li>
<li>Mostly the newbies are confronted with these terms when they for example ask questions like "what's the best php development framework"</li>
</ul>
|
[
{
"answer_id": 277794,
"author": "bendin",
"author_id": 33412,
"author_profile": "https://Stackoverflow.com/users/33412",
"pm_score": 4,
"selected": false,
"text": "unix.rulez.org/~calver"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11995/"
] |
277,623
|
<p>I'm trying to get a Server application to expose some status information using WCF.
In particular I'm after using WCF services with RESTful "API".
I'm hitting somewhat of a wall when it comes to consuming the REST api from a silverlight
app/page that I want to have as an additional type of client...</p>
<p>So far I've been successful in defining a status interface:</p>
<pre><code>public static class StatusUriTemplates
{
public const string Status = "/current-status";
public const string StatusJson = "/current-status/json";
public const string StatusXml = "/current-status/xml";
}
[ServiceContract]
public interface IStatusService
{
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = StatusUriTemplates.StatusJson)]
StatusResultSet GetProgressAsJson();
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Xml, UriTemplate = StatusUriTemplates.StatusXml)]
StatusResultSet GetProgressAsXml();
[OperationContract]
[WebGet(UriTemplate = StatusUriTemplates.Status)]
StatusResultSet GetProgress();
}
</code></pre>
<p>Implementing it in the server:</p>
<pre><code> [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class ServerStatusService : IStatusService
{
public StatusResultSet GetProgressAsJson()
{ return GetProgress(); }
public StatusResultSet GetProgressAsXml()
{ return GetProgress(); }
public StatusResultSet GetProgress()
{
return StatusResultSet.Empty;
}
}
</code></pre>
<p>Exposing it from my code at runtime:</p>
<pre><code> var service = new ServerStatusService();
var binding = new WebHttpBinding();
var behavior = new WebHttpBehavior();
var host = new WebServiceHost(service, new Uri("http://localhost:8000/server"));
host.AddServiceEndpoint(typeof(IStatusService), binding, "status");
host.Open();
</code></pre>
<p>I've even been successful with consuming the service from a .NET console/winfoems/WPF application using something along the line of this:</p>
<pre><code> var cf = new WebChannelFactory<IStatusService>(new Uri("http://localhost:8000/server/status"));
var ss = cf.CreateChannel();
Console.WriteLine(ss.GetProgress().TimeStamp);
</code></pre>
<p>The "wall" I'm hitting is that there is NO WebChannelFactory for SliverLight.</p>
<p>Period.</p>
<p>This means that when it comes to silverlight code, my options are:</p>
<ul>
<li>Write ugly code using WebClient,
which ultimately means I will have
to update two sets of code whenever
I have a change to my API </li>
<li>Use SOAP/WS for the WebService and keep
updating the service reference from
Visual Studio</li>
</ul>
<p>Is there a way to keep the "clean" implementation with WebChannelFactory in SilverLight?
Perhaps a public domain / open source WebChannelFactory for SilverLight?</p>
<p>Any help with this will be greatly appreciated!</p>
|
[
{
"answer_id": 314685,
"author": "Donn Felker",
"author_id": 5210,
"author_profile": "https://Stackoverflow.com/users/5210",
"pm_score": 1,
"selected": false,
"text": "WebClient rest = new WebClient();\nrest.DownloadStringCompleted += new DownloadStringCompletedEventHandler(rest_DownloadStringCompleted);\nrest.DownloadStringAsync(new Uri(\"http://example.org/current-status/xml\"));\n string data = e.Result;\nstring url = string.Empty;\n\nXDocument doc = XDocument.Parse(e.Result);\nvar myResults = from results in doc.Descendants(\"myXmlElement\") ... blah blah blah \n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9172/"
] |
277,625
|
<p>I am working on a database that usually uses GUIDs as primary keys.</p>
<p>By default SQL Server places a clustered index on primary key columns. I understand that this is a silly idea for GUID columns, and that non-clustered indexes are better.</p>
<p>What do you think - should I get rid of all the clustered indexes and replace them with non-clustered indexes?</p>
<p>Why wouldn't SQL's performance tuner offer this as a recommendation?</p>
|
[
{
"answer_id": 277636,
"author": "Galwegian",
"author_id": 3201,
"author_profile": "https://Stackoverflow.com/users/3201",
"pm_score": 3,
"selected": false,
"text": "IDENTITY SELECT INSERT SELECT"
},
{
"answer_id": 277743,
"author": "HTTP 410",
"author_id": 13118,
"author_profile": "https://Stackoverflow.com/users/13118",
"pm_score": 3,
"selected": false,
"text": "SELECT OBJECT_NAME (ips.[object_id]) AS 'Object Name',\n si.name AS 'Index Name',\n ROUND (ips.avg_fragmentation_in_percent, 2) AS 'Fragmentation',\n ips.page_count AS 'Pages',\n ROUND (ips.avg_page_space_used_in_percent, 2) AS 'Page Density'\nFROM sys.dm_db_index_physical_stats \n (DB_ID ('MyDatabase'), NULL, NULL, NULL, 'DETAILED') ips\nCROSS APPLY sys.indexes si\nWHERE si.object_id = ips.object_id\nAND si.index_id = ips.index_id\nAND ips.index_level = 0;\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21966/"
] |
277,630
|
<p>Is it possible to use a DB sequence for some column that <strong>is not the identifier/is not part of a composite identifier</strong>? </p>
<p>I'm using hibernate as jpa provider, and I have a table that has some columns that are generated values (using a sequence), although they are not part of the identifier.</p>
<p>What I want is to use a sequence to create a new value for an entity, where the column for the sequence is <strong>NOT</strong> (part of) the primary key:</p>
<pre><code>@Entity
@Table(name = "MyTable")
public class MyEntity {
//...
@Id //... etc
public Long getId() {
return id;
}
//note NO @Id here! but this doesn't work...
@GeneratedValue(strategy = GenerationType.AUTO, generator = "myGen")
@SequenceGenerator(name = "myGen", sequenceName = "MY_SEQUENCE")
@Column(name = "SEQ_VAL", unique = false, nullable = false, insertable = true, updatable = true)
public Long getMySequencedValue(){
return myVal;
}
}
</code></pre>
<p>Then when I do this:</p>
<pre><code>em.persist(new MyEntity());
</code></pre>
<p>the id will be generated, but the <code>mySequenceVal</code> property will be also generated by my JPA provider.</p>
<p>Just to make things clear: I want <strong>Hibernate</strong> to generate the value for the <code>mySequencedValue</code> property. I know Hibernate can handle database-generated values, but I don't want to use a trigger or any other thing other than Hibernate itself to generate the value for my property. If Hibernate can generate values for primary keys, why can't it generate for a simple property?</p>
|
[
{
"answer_id": 283603,
"author": "alasdairg",
"author_id": 15768,
"author_profile": "https://Stackoverflow.com/users/15768",
"pm_score": 4,
"selected": false,
"text": "<property name=\"foo\" generated=\"insert\"/>\n <property name=\"foo\" generated=\"always\"/>\n <property name=\"foo\" update=\"false\" insert=\"false\"/>\n"
},
{
"answer_id": 536102,
"author": "Morten Berg",
"author_id": 36120,
"author_profile": "https://Stackoverflow.com/users/36120",
"pm_score": 8,
"selected": true,
"text": "@GeneratedValue @Id @GeneratedValue"
},
{
"answer_id": 2669182,
"author": "Paul",
"author_id": 290849,
"author_profile": "https://Stackoverflow.com/users/290849",
"pm_score": 3,
"selected": false,
"text": "@Override public Long getNextExternalId() {\n BigDecimal seq =\n (BigDecimal)((List)em.createNativeQuery(\"select col_msd_external_id_seq.nextval from dual\").getResultList()).get(0);\n return seq.longValue();\n}\n"
},
{
"answer_id": 10647933,
"author": "Sergey Vedernikov",
"author_id": 620858,
"author_profile": "https://Stackoverflow.com/users/620858",
"pm_score": 6,
"selected": false,
"text": "@Column(columnDefinition=\"serial\") saveAndFlush save"
},
{
"answer_id": 11842769,
"author": "Sebastian Götz",
"author_id": 1482214,
"author_profile": "https://Stackoverflow.com/users/1482214",
"pm_score": 3,
"selected": false,
"text": "@Retention(RetentionPolicy.RUNTIME)\n@Target(ElementType.FIELD)\npublic @interface Sequence\n{\n}\n public class Area extends BaseEntity implements ClientAware, IssuerAware\n{\n @Column(name = \"areaNumber\", updatable = false)\n @Sequence\n private Integer areaNumber;\n....\n}\n @Entity\n@Table(name = \"SequenceNumber\", uniqueConstraints = { @UniqueConstraint(columnNames = { \"className\" }) })\npublic class SequenceNumber\n{\n @Id\n @Column(name = \"className\", updatable = false)\n private String className;\n\n @Column(name = \"nextValue\")\n private Integer nextValue = 1;\n\n @Column(name = \"incrementValue\")\n private Integer incrementValue = 10;\n\n ... some getters and setters ....\n}\n @Component\npublic class SequenceListener implements PreInsertEventListener\n{\n private static final long serialVersionUID = 7946581162328559098L;\n private final static Logger log = Logger.getLogger(SequenceListener.class);\n\n @Autowired\n private SessionFactoryImplementor sessionFactoryImpl;\n\n private final Map<String, CacheEntry> cache = new HashMap<>();\n\n @PostConstruct\n public void selfRegister()\n {\n // As you might expect, an EventListenerRegistry is the place with which event listeners are registered\n // It is a service so we look it up using the service registry\n final EventListenerRegistry eventListenerRegistry = sessionFactoryImpl.getServiceRegistry().getService(EventListenerRegistry.class);\n\n // add the listener to the end of the listener chain\n eventListenerRegistry.appendListeners(EventType.PRE_INSERT, this);\n }\n\n @Override\n public boolean onPreInsert(PreInsertEvent p_event)\n {\n updateSequenceValue(p_event.getEntity(), p_event.getState(), p_event.getPersister().getPropertyNames());\n\n return false;\n }\n\n private void updateSequenceValue(Object p_entity, Object[] p_state, String[] p_propertyNames)\n {\n try\n {\n List<Field> fields = ReflectUtil.getFields(p_entity.getClass(), null, Sequence.class);\n\n if (!fields.isEmpty())\n {\n if (log.isDebugEnabled())\n {\n log.debug(\"Intercepted custom sequence entity.\");\n }\n\n for (Field field : fields)\n {\n Integer value = getSequenceNumber(p_entity.getClass().getName());\n\n field.setAccessible(true);\n field.set(p_entity, value);\n setPropertyState(p_state, p_propertyNames, field.getName(), value);\n\n if (log.isDebugEnabled())\n {\n LogMF.debug(log, \"Set {0} property to {1}.\", new Object[] { field, value });\n }\n }\n }\n }\n catch (Exception e)\n {\n log.error(\"Failed to set sequence property.\", e);\n }\n }\n\n private Integer getSequenceNumber(String p_className)\n {\n synchronized (cache)\n {\n CacheEntry current = cache.get(p_className);\n\n // not in cache yet => load from database\n if ((current == null) || current.isEmpty())\n {\n boolean insert = false;\n StatelessSession session = sessionFactoryImpl.openStatelessSession();\n session.beginTransaction();\n\n SequenceNumber sequenceNumber = (SequenceNumber) session.get(SequenceNumber.class, p_className);\n\n // not in database yet => create new sequence\n if (sequenceNumber == null)\n {\n sequenceNumber = new SequenceNumber();\n sequenceNumber.setClassName(p_className);\n insert = true;\n }\n\n current = new CacheEntry(sequenceNumber.getNextValue() + sequenceNumber.getIncrementValue(), sequenceNumber.getNextValue());\n cache.put(p_className, current);\n sequenceNumber.setNextValue(sequenceNumber.getNextValue() + sequenceNumber.getIncrementValue());\n\n if (insert)\n {\n session.insert(sequenceNumber);\n }\n else\n {\n session.update(sequenceNumber);\n }\n session.getTransaction().commit();\n session.close();\n }\n\n return current.next();\n }\n }\n\n private void setPropertyState(Object[] propertyStates, String[] propertyNames, String propertyName, Object propertyState)\n {\n for (int i = 0; i < propertyNames.length; i++)\n {\n if (propertyName.equals(propertyNames[i]))\n {\n propertyStates[i] = propertyState;\n return;\n }\n }\n }\n\n private static class CacheEntry\n {\n private int current;\n private final int limit;\n\n public CacheEntry(final int p_limit, final int p_current)\n {\n current = p_current;\n limit = p_limit;\n }\n\n public Integer next()\n {\n return current++;\n }\n\n public boolean isEmpty()\n {\n return current >= limit;\n }\n }\n}\n"
},
{
"answer_id": 23831524,
"author": "Rumal",
"author_id": 969252,
"author_profile": "https://Stackoverflow.com/users/969252",
"pm_score": 5,
"selected": false,
"text": "@Generated @Generated(GenerationTime.INSERT)\n@Column(name = \"column_name\", insertable = false)\n"
},
{
"answer_id": 35888326,
"author": "Matroska",
"author_id": 269585,
"author_profile": "https://Stackoverflow.com/users/269585",
"pm_score": 4,
"selected": false,
"text": "@PrePersist @PrePersist\npublic void initializeUUID() {\n if (uuid == null) {\n uuid = UUID.randomUUID().toString();\n }\n}\n"
},
{
"answer_id": 49368556,
"author": "Spring",
"author_id": 379028,
"author_profile": "https://Stackoverflow.com/users/379028",
"pm_score": -1,
"selected": false,
"text": "ID NUMBER GENERATED as IDENTITY\n ID BIGINT GENERATED as auto_increment\n @Column(insertable = false)\n"
},
{
"answer_id": 53451707,
"author": "Sulaymon Hursanov",
"author_id": 8038849,
"author_profile": "https://Stackoverflow.com/users/8038849",
"pm_score": 3,
"selected": false,
"text": "@Column(columnDefinition = \"serial\")\n@Generated(GenerationTime.INSERT)\nprivate Integer orderID;\n"
},
{
"answer_id": 56017045,
"author": "Subin Chalil",
"author_id": 2756662,
"author_profile": "https://Stackoverflow.com/users/2756662",
"pm_score": 3,
"selected": false,
"text": "@InjectSequenceValue @Retention(RetentionPolicy.RUNTIME)\n@Target(ElementType.FIELD)\npublic @interface InjectSequenceValue {\n String sequencename();\n}\n //serialNumber will be injected dynamically, with the next value of the serialnum_sequence.\n @InjectSequenceValue(sequencename = \"serialnum_sequence\") \n Long serialNumber;\n save/persist @Aspect\n@Configuration\npublic class AspectDefinition {\n\n @Autowired\n JdbcTemplate jdbcTemplate;\n\n\n //@Before(\"execution(* org.hibernate.session.save(..))\") Use this for Hibernate.(also include session.save())\n @Before(\"execution(* org.springframework.data.repository.CrudRepository.save(..))\") //This is for JPA.\n public void generateSequence(JoinPoint joinPoint){\n\n Object [] aragumentList=joinPoint.getArgs(); //Getting all arguments of the save\n for (Object arg :aragumentList ) {\n if (arg.getClass().isAnnotationPresent(Entity.class)){ // getting the Entity class\n\n Field[] fields = arg.getClass().getDeclaredFields();\n for (Field field : fields) {\n if (field.isAnnotationPresent(InjectSequenceValue.class)) { //getting annotated fields\n\n field.setAccessible(true); \n try {\n if (field.get(arg) == null){ // Setting the next value\n String sequenceName=field.getAnnotation(InjectSequenceValue.class).sequencename();\n long nextval=getNextValue(sequenceName);\n System.out.println(\"Next value :\"+nextval); //TODO remove sout.\n field.set(arg, nextval);\n }\n\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n }\n }\n\n }\n }\n\n /**\n * This method fetches the next value from sequence\n * @param sequence\n * @return\n */\n\n public long getNextValue(String sequence){\n long sequenceNextVal=0L;\n\n SqlRowSet sqlRowSet= jdbcTemplate.queryForRowSet(\"SELECT \"+sequence+\".NEXTVAL as value FROM DUAL\");\n while (sqlRowSet.next()){\n sequenceNextVal=sqlRowSet.getLong(\"value\");\n\n }\n return sequenceNextVal;\n }\n}\n @Entity\n@Table(name = \"T_USER\")\npublic class UserEntity {\n\n @Id\n @SequenceGenerator(sequenceName = \"userid_sequence\",name = \"this_seq\")\n @GeneratedValue(strategy = GenerationType.SEQUENCE,generator = \"this_seq\")\n Long id;\n String userName;\n String password;\n\n @InjectSequenceValue(sequencename = \"serialnum_sequence\") // this will be injected at the time of saving.\n Long serialNumber;\n\n String name;\n}\n"
},
{
"answer_id": 58797977,
"author": "Artyom Novitskii",
"author_id": 12354330,
"author_profile": "https://Stackoverflow.com/users/12354330",
"pm_score": 0,
"selected": false,
"text": "@Generated(GenerationTime.INSERT)\n@Column(nullable = false , columnDefinition=\"UNIQUEIDENTIFIER\")\nprivate String uuidValue;\n CREATE TABLE operation.Table1\n(\n Id INT IDENTITY (1,1) NOT NULL,\n UuidValue UNIQUEIDENTIFIER DEFAULT NEWID() NOT NULL)\n columnDefinition=\"UNIQUEIDENTIFIER\""
},
{
"answer_id": 61297522,
"author": "Ignacio Velásquez Lagos",
"author_id": 5579797,
"author_profile": "https://Stackoverflow.com/users/5579797",
"pm_score": 0,
"selected": false,
"text": "@Entity\n@Table(name = \"MyTable\", indexes = { @Index(name = \"my_index\", columnList = \"mySequencedValue\") })\npublic class MyEntity {\n //...\n @Column(columnDefinition = \"integer unsigned\", nullable = false, updatable = false, insertable = false)\n private Long mySequencedValue;\n //...\n}\n @Component\npublic class PostConstructComponent {\n @Autowired\n private JdbcTemplate jdbcTemplate;\n\n @PostConstruct\n public void makeMyEntityMySequencedValueAutoIncremental() {\n jdbcTemplate.update(\"alter table MyTable modify mySequencedValue int unsigned auto_increment\");\n }\n}\n"
},
{
"answer_id": 61614713,
"author": "aboger",
"author_id": 1411723,
"author_profile": "https://Stackoverflow.com/users/1411723",
"pm_score": 1,
"selected": false,
"text": "Number Long GeneralSequenceNumber ActualEntity generated Long // ...\n@Entity\npublic class ActualEntity {\n\n @Id \n // ...\n Long id;\n\n @Column(unique = true, updatable = false, nullable = false)\n Long generated;\n\n // ...\n\n}\n Generated ActualEntity @Entity\nclass Generated {\n\n @Id\n @GeneratedValue(strategy = SEQUENCE, generator = \"seq\")\n @SequenceGenerator(name = \"seq\", initialValue = 1, allocationSize = 1)\n Long id;\n\n}\n ActualEntity Generated id Long ActualEntity.generated @RepositoryEventHandler ActualEntity @Component\n@RepositoryEventHandler\npublic class ActualEntityHandler {\n\n @Autowired\n EntityManager entityManager;\n\n @Transactional\n @HandleBeforeCreate\n public void generate(ActualEntity entity) {\n Generated generated = new Generated();\n\n entityManager.persist(generated);\n entity.setGlobalId(generated.getId());\n entityManager.remove(generated);\n }\n\n}\n"
},
{
"answer_id": 63688702,
"author": "Aritra Das",
"author_id": 9898631,
"author_profile": "https://Stackoverflow.com/users/9898631",
"pm_score": 0,
"selected": false,
"text": "@Generated(GenerationTime.INSERT)\n@Column(name = \"internal_id\", columnDefinition = \"serial\", updatable = false)\nprivate int internalId;\n"
},
{
"answer_id": 70979696,
"author": "heisbrandon",
"author_id": 3870855,
"author_profile": "https://Stackoverflow.com/users/3870855",
"pm_score": 2,
"selected": false,
"text": "import org.hibernate.Session;\nimport org.hibernate.boot.Metadata;\nimport org.hibernate.engine.spi.SessionFactoryImplementor;\nimport org.hibernate.id.IdentifierGenerator;\nimport org.hibernate.id.enhanced.TableGenerator;\nimport org.hibernate.integrator.spi.Integrator;\nimport org.hibernate.internal.SessionImpl;\nimport org.hibernate.service.spi.SessionFactoryServiceRegistry;\nimport org.hibernate.tuple.ValueGenerator;\nimport org.hibernate.type.LongType;\nimport java.util.Properties;\n\npublic class SequenceIntegrator implements Integrator, ValueGenerator<Long> {\n public static final String TABLE_NAME = \"SEQUENCE_TABLE\";\n public static final String VALUE_COLUMN_NAME = \"NEXT_VAL\";\n public static final String SEGMENT_COLUMN_NAME = \"SEQUENCE_NAME\";\n private static SessionFactoryServiceRegistry serviceRegistry;\n private static Metadata metadata;\n private static IdentifierGenerator defaultGenerator;\n\n @Override\n public void integrate(Metadata metadata, SessionFactoryImplementor sessionFactoryImplementor, SessionFactoryServiceRegistry sessionFactoryServiceRegistry) {\n //assigning metadata and registry to fields for use in a below example\n SequenceIntegrator.metadata = metadata;\n SequenceIntegrator.serviceRegistry = sessionFactoryServiceRegistry;\n SequenceIntegrator.defaultGenerator = getTableGenerator(metadata, sessionFactoryServiceRegistry, \"DEFAULT\");\n }\n\n private TableGenerator getTableGenerator(Metadata metadata, SessionFactoryServiceRegistry sessionFactoryServiceRegistry, String segmentValue) {\n TableGenerator generator = new TableGenerator();\n Properties properties = new Properties();\n properties.setProperty(\"table_name\", TABLE_NAME);\n properties.setProperty(\"value_column_name\", VALUE_COLUMN_NAME);\n properties.setProperty(\"segment_column_name\", SEGMENT_COLUMN_NAME);\n properties.setProperty(\"segment_value\", segmentValue);\n\n //any type should work if the generator supports it\n generator.configure(LongType.INSTANCE, properties, sessionFactoryServiceRegistry);\n\n //this should create the table if ddl auto update is enabled and if this function is called inside of the integrate method\n generator.registerExportables(metadata.getDatabase());\n return generator;\n }\n\n @Override\n public Long generateValue(Session session, Object o) {\n // registering additional generators with getTableGenerator will work here. inserting new sequences can be done dynamically\n // example:\n // TableGenerator classSpecificGenerator = getTableGenerator(metadata, serviceRegistry, o.getClass().getName());\n // return (Long) classSpecificGenerator.generate((SessionImpl)session, o);\n return (Long) defaultGenerator.generate((SessionImpl)session, o);\n }\n\n @Override\n public void disintegrate(SessionFactoryImplementor sessionFactoryImplementor, SessionFactoryServiceRegistry sessionFactoryServiceRegistry) {\n\n }\n}\n @Entity\n@Table(name = \"MyTable\")\npublic class MyEntity {\n\n //...\n @Id //... etc\n public Long getId() {\n return id;\n }\n\n @GeneratorType(type = SequenceIntegrator.class, when = GenerationTime.INSERT)\n @Column(name = \"SEQ_VAL\", unique = false, nullable = false, insertable = true, updatable = true)\n public Long getMySequencedValue(){\n return myVal;\n }\n\n}\n"
},
{
"answer_id": 73945897,
"author": "A.Casanova",
"author_id": 17047177,
"author_profile": "https://Stackoverflow.com/users/17047177",
"pm_score": 0,
"selected": false,
"text": "@Column(name = \"<column name>\", columnDefinition = \"serial\")\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22992/"
] |
277,634
|
<p>still new to the world of linq, and i need some help flatening a list of parents that have children, into a single list of ParentChild's.</p>
<p>Just like this:</p>
<pre><code>class Program
{
static void Main()
{
List<Parent> parents = new List<Parent>();
parents.Add(new Parent { Name = "Parent1", Children = new List<Child> { new Child { Name = "Child1" }, new Child { Name = "Child2" } } });
parents.Add(new Parent { Name = "Parent2", Children = new List<Child> { new Child { Name = "Child3" }, new Child { Name = "Child4" } } });
// linq query to return List<ParentChild> parentChildList;
// ParentName = Parent1, ChildName = Child1
// ParentName = Parent1, ChildName = Child2
// ParentName = Parent2, ChildName = Child3
// ParentName = Parent2, ChildName = Child4
}
internal class ParentChild
{
public string ParentName { get; set; }
public string ChildName { get; set; }
}
internal class Parent
{
public string Name { get; set; }
public List<Child> Children { get; set; }
}
internal class Child
{
public string Name { get; set; }
}
}
</code></pre>
<p>Many thanks,
Chris</p>
|
[
{
"answer_id": 277637,
"author": "Kent Boogaart",
"author_id": 5380,
"author_profile": "https://Stackoverflow.com/users/5380",
"pm_score": 5,
"selected": true,
"text": "from parent in parents\nfrom child in parent.Children\nselect new ParentChild() { ParentName = parent.Name, ChildName = child.Name };\n"
},
{
"answer_id": 277648,
"author": "Nathan W",
"author_id": 6335,
"author_profile": "https://Stackoverflow.com/users/6335",
"pm_score": 2,
"selected": false,
"text": "var k = from p in parents\n from c in p.Children\n select new {Name = p.Name, Child = c.Name };\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277634",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26759/"
] |
277,640
|
<p>SPListItem.GetFormattedValue seems to have a strange behavior for DateTime fields.
It retrieves the DateTime value through SPListItem's indexer which according to this <a href="http://msdn.microsoft.com/en-us/library/ms197282.aspx" rel="noreferrer">MSDN article</a> returns <em>local</em> time.
Here's a snippet from Reflector</p>
<pre><code>public string GetFormattedValue(string fieldName)
{
SPField field = this.Fields.GetField(fieldName);
if (field != null)
{
return field.GetFieldValueAsHtml(this[fieldName]);
}
return null;
}
</code></pre>
<p>So it uses SPListItem's indexer to retrieve the value and than SPFields.GetFieldValueAsHtml to format the value. GetFieldValueAsHtml seems to assume the date is in UTC and convert it to local time no matter what kind it is. (Reflector shows that it uses GetFieldValueAsText which uses value.ToString() but for some reason it assumes the time to be UTC.)</p>
<p>The end result is that the string representation on a time field obtained trough listItem.GetFormattedValue() (at least in my case) is incorrect, being local time + (local time - UTC).</p>
<p>Have anybody encountered the same issue with SPListItem.GetFormattedValue() and what was your workaround?</p>
|
[
{
"answer_id": 457151,
"author": "Soda",
"author_id": 56623,
"author_profile": "https://Stackoverflow.com/users/56623",
"pm_score": 4,
"selected": true,
"text": "DateTime localTime = (DateTime)item[\"DueDate\"];\n// this is local time but if you do localDateTime.Kind it returns Unspecified\n// treats the date as universal time.. \n// let's give it the universal time :)\nDateTime universalTime = SPContext.Current.Web\n .RegionalSettings.TimeZone.LocalTimeToUTC(localTime);\nstring correctFormattedValue = \n item.Fields[\"DueDate\"].GetFieldValueAsHtml(universalTime);\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277640",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/578/"
] |
277,646
|
<p>I am having a number of panels in my page in which I am collecting user information and saving the page details. The page panel has textbox, dropdown list, listbox.</p>
<p>When I need to come to this page. I need to show the Page if these controls have any values. How to do this?</p>
|
[
{
"answer_id": 277654,
"author": "Cristian Libardo",
"author_id": 16526,
"author_profile": "https://Stackoverflow.com/users/16526",
"pm_score": 6,
"selected": true,
"text": " IEnumerable<Control> EnumerateControlsRecursive(Control parent)\n {\n foreach (Control child in parent.Controls)\n {\n yield return child;\n foreach (Control descendant in EnumerateControlsRecursive(child))\n yield return descendant;\n }\n }\n foreach (Control c in EnumerateControlsRecursive(Page))\n {\n if(c is TextBox)\n {\n // do something useful\n }\n }\n"
},
{
"answer_id": 277656,
"author": "GeekyMonkey",
"author_id": 29900,
"author_profile": "https://Stackoverflow.com/users/29900",
"pm_score": 2,
"selected": false,
"text": "foreach (Control c in MyPanel.Controls) \n{\n if (c is Textbox) {\n // do something with textbox\n } else if (c is Checkbox) {\n /// do something with checkbox\n }\n}\n"
},
{
"answer_id": 7195784,
"author": "theoski",
"author_id": 598807,
"author_profile": "https://Stackoverflow.com/users/598807",
"pm_score": 2,
"selected": false,
"text": "IEnumerable<Control> getCtls(Control par)\n{ \n List<Control> ret = new List<Control>();\n foreach (Control c in par.Controls)\n {\n ret.Add(c);\n ret.AddRange(getCtls(c));\n }\n return (IEnumerable<Control>)ret;\n}\n foreach (Button but in getCtls(Page).OfType<Button>())\n{\n //disable the button\n but.Enabled = false;\n} \n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277646",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22162/"
] |
277,655
|
<p>I've always wondered why the C++ Standard library has instantiated basic_[io]stream and all its variants using the <code>char</code> type instead of the <code>unsigned char</code> type. <code>char</code> means (depending on whether it is signed or not) you can have overflow and underflow for operations like get(), which will lead to implementation-defined value of the variables involved. Another example is when you want to output a byte, unformatted, to an ostream using its <code>put</code> function.</p>
<p>Any ideas?</p>
<hr>
<p><strong>Note</strong>: I'm still not really convinced. So if you know the definitive answer, you can still post it indeed.</p>
|
[
{
"answer_id": 2924394,
"author": "Daniel Trebbien",
"author_id": 196844,
"author_profile": "https://Stackoverflow.com/users/196844",
"pm_score": 4,
"selected": false,
"text": "iostream char char char char signed char unsigned char char signed char unsigned char signed char unsigned char char signed char unsigned char reinterpret_cast char * unsigned char * char char signed char unsigned char char"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277655",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34509/"
] |
277,660
|
<p>3/10/2008 = 1822556159</p>
<p>2/10/2008 = 1822523391</p>
<p>1/10/2008 = 1822490623</p>
<p>30/09/2008 = 1822392319</p>
<p>29/09/2008 = 1822359551</p>
<p>This is all the information that I know at the current time. </p>
<p>Dates increment by 32768 except when changing month when the increment is 32768 x 2 (65536).</p>
<p>Has anyone seen this binary date format and how can I extract the correct date?</p>
<hr>
<p>It is possible that the remaining portion of the date is for time (hours, minutes, seconds)</p>
|
[
{
"answer_id": 277683,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 3,
"selected": false,
"text": "1822392319 = 0x6c9f7fff\n0x6c = 108 = 2008 (based on 1900 start date)\n0x9 = 9 = September\n0xf7fff - take top 5 bits = 0x1e = 30\n 1822490623 = 0x6ca0ffff\n0x6c = 108 = 2008\n0xa = 10 = October\n0x0ffff - take top 5 bits = 0x01 = 1\n day_of_month = (value >> 15) & 0x1f\n year = (value >> 24) & 0xff + 1900\nmonth = (value >> 20) & 0x0f\n"
},
{
"answer_id": 277686,
"author": "mana",
"author_id": 12016,
"author_profile": "https://Stackoverflow.com/users/12016",
"pm_score": 2,
"selected": false,
"text": "a = 1822556159\n1101100 1010 00011 111111111111111\nb = 1822523391\n1101100 1010 00010 111111111111111\nc = 1822490623\n1101100 1010 00001 111111111111111\nd = 1822392319 \n1101100 1001 11110 111111111111111\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277660",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
277,710
|
<p>I'm passing small (2-10 KB)XML documents as input to a WCF service. now I've two option to read data values from incoming XML</p>
<ol>
<li>Deserialize to a strongly typed object and use object properties to access values</li>
<li>use XPath to access values</li>
</ol>
<p>which approach is faster? some statistics to support your answer would be great.</p>
|
[
{
"answer_id": 37665391,
"author": "Jon Raynor",
"author_id": 750873,
"author_profile": "https://Stackoverflow.com/users/750873",
"pm_score": 2,
"selected": false,
"text": "[Serializable]\n public class FoobarXml\n {\n public string Name { get; set; }\n public int Age { get; set; }\n public bool IsContent { get; set; }\n\n [XmlElement(DataType = \"date\")]\n public DateTime BirthDay { get; set; }\n }\n public class FoobarIXml : IXmlSerializable\n {\n public string Name { get; set; }\n public int Age { get; set; }\n public bool IsContent { get; set; }\n public DateTime BirthDay { get; set; }\n\n public XmlSchema GetSchema()\n {\n return null;\n }\n\n public void ReadXml(XmlReader reader)\n {\n reader.MoveToContent();\n var isEmptyElement = reader.IsEmptyElement;\n reader.ReadStartElement();\n if (!isEmptyElement)\n {\n Name = reader.ReadElementString(\"Name\");\n\n int intResult;\n var success = int.TryParse(reader.ReadElementString(\"Age\"), out intResult);\n if (success)\n {\n Age = intResult;\n }\n\n bool boolResult;\n success = bool.TryParse(reader.ReadElementString(\"IsContent\"), out boolResult);\n if (success)\n {\n IsContent = boolResult;\n }\n DateTime dateTimeResult;\n success = DateTime.TryParseExact(reader.ReadElementString(\"BirthDay\"), \"yyyy-MM-dd\", null,\n DateTimeStyles.None, out dateTimeResult);\n if (success)\n {\n BirthDay = dateTimeResult;\n }\n reader.ReadEndElement(); //Must Do\n }\n }\n\n public void WriteXml(XmlWriter writer)\n {\n writer.WriteElementString(\"Name\", Name);\n writer.WriteElementString(\"Age\", Age.ToString());\n writer.WriteElementString(\"IsContent\", IsContent.ToString());\n writer.WriteElementString(\"BirthDay\", BirthDay.ToString(\"yyyy-MM-dd\"));\n }\n }\n}\n public class FoobarHandRolled\n {\n public FoobarHandRolled(string name, int age, bool isContent, DateTime birthDay)\n {\n Name = name;\n Age = age;\n IsContent = isContent;\n BirthDay = birthDay;\n }\n\n public FoobarHandRolled(string xml)\n {\n if (string.IsNullOrWhiteSpace(xml))\n {\n return;\n }\n\n SetName(xml);\n SetAge(xml);\n SetIsContent(xml);\n SetBirthday(xml);\n }\n\n public string Name { get; set; }\n public int Age { get; set; }\n public bool IsContent { get; set; }\n public DateTime BirthDay { get; set; }\n\n /// <summary>\n /// Takes this object and creates an XML representation.\n /// </summary>\n /// <returns>An XML string that represents this object.</returns>\n public override string ToString()\n {\n var builder = new StringBuilder();\n builder.Append(\"<FoobarHandRolled>\");\n\n if (!string.IsNullOrWhiteSpace(Name))\n {\n builder.Append(\"<Name>\" + Name + \"</Name>\");\n }\n\n builder.Append(\"<Age>\" + Age + \"</Age>\");\n builder.Append(\"<IsContent>\" + IsContent + \"</IsContent>\");\n builder.Append(\"<BirthDay>\" + BirthDay.ToString(\"yyyy-MM-dd\") + \"</BirthDay>\");\n builder.Append(\"</FoobarHandRolled>\");\n\n return builder.ToString();\n }\n\n private void SetName(string xml)\n {\n Name = GetSubString(xml, \"<Name>\", \"</Name>\");\n }\n\n private void SetAge(string xml)\n {\n var ageString = GetSubString(xml, \"<Age>\", \"</Age>\");\n int result;\n var success = int.TryParse(ageString, out result);\n if (success)\n {\n Age = result;\n }\n }\n\n private void SetIsContent(string xml)\n {\n var isContentString = GetSubString(xml, \"<IsContent>\", \"</IsContent>\");\n bool result;\n var success = bool.TryParse(isContentString, out result);\n if (success)\n {\n IsContent = result;\n }\n }\n\n private void SetBirthday(string xml)\n {\n var dateString = GetSubString(xml, \"<BirthDay>\", \"</BirthDay>\");\n DateTime result;\n var success = DateTime.TryParseExact(dateString, \"yyyy-MM-dd\", null, DateTimeStyles.None, out result);\n if (success)\n {\n BirthDay = result;\n }\n }\n\n private string GetSubString(string xml, string startTag, string endTag)\n {\n var startIndex = xml.IndexOf(startTag, StringComparison.Ordinal);\n if (startIndex < 0)\n {\n return null;\n }\n\n startIndex = startIndex + startTag.Length;\n\n var endIndex = xml.IndexOf(endTag, StringComparison.Ordinal);\n if (endIndex < 0)\n {\n return null;\n }\n\n return xml.Substring(startIndex, endIndex - startIndex);\n }\n }\n var xDoc = XElement.Parse(xml);\n\n var nameElement = xDoc.Element(\"Name\");\n var ageElement = xDoc.Element(\"Age\");\n var isContentElement = xDoc.Element(\"IsContent\");\n var birthDayElement = xDoc.Element(\"BirthDay\");\n\n string name = null;\n if (nameElement != null)\n {\n name = nameElement.Value;\n }\n var age = 0;\n if (ageElement != null)\n {\n age = int.Parse(ageElement.Value);\n }\n var isContent = false;\n if (isContentElement != null)\n {\n isContent = bool.Parse(isContentElement.Value);\n }\n var birthDay = new DateTime();\n if (birthDayElement != null)\n {\n birthDay = DateTime.ParseExact(birthDayElement.Value, \"yyyy-MM-dd\", CultureInfo.InvariantCulture);\n }\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277710",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7722/"
] |
277,714
|
<p>We have some SQL server reporting services reports. I didn't write then but I have to take care of them.</p>
<p>These reports fire when opened in the browser, and with the default parameters (search terms and restrictions are blank) they retrieve a lot of data, which is slow. The client would prefer that the report is not generated until the user enters parameters and presses "view report"</p>
<p>Unfortunately I don't know SSRS at all well - how do I stop the report from firing when it is opened?</p>
<p><hr>
The details of how to do it on a deployed report (as per Rihan Meij's answer) is as follows: </p>
<p>Click on a report, click on "properties" at the top. You may have to wait a bit, because the slow report may be running now. Then click on "parameters" on the left. </p>
<p>For each parameter, make sure that "Prompt User" is checked, and for at least one parameter, "Has Default" is not checked. Click on "View" again at the top left (or go back to the folder and click on the report name) to view the report, and note that the report does not fire right away.</p>
<p>In the report builder, you can do this via the "Filter" menu. De-select values from at least one filter, and save the report.</p>
<p>Is it also possible to stop reports from firing on loading when the report has no parameters?</p>
|
[
{
"answer_id": 16279481,
"author": "Teis Lindemark",
"author_id": 1726499,
"author_profile": "https://Stackoverflow.com/users/1726499",
"pm_score": 2,
"selected": false,
"text": "<rsweb:ReportViewer \n ID=\"rv\" \n runat=\"server\" \n Width=\"100%\" \n Height=\"100%\" \n SizeToReportContent=\"false\" \n ZoomMode=\"PageWidth\"\n KeepSessionAlive=\"true\" \n ProcessingMode=\"Remote\"\n PromptAreaCollapsed=\"false\" \n InteractivityPostBackMode=\"AlwaysAsynchronous\"\n AsyncRendering=\"true\" \n ExportContentDisposition=\"AlwaysInline\"\n ShowReportBody=\"False\"\n ShowPrintButton=\"false\"\n OnSubmittingParameterValues=\"rv_SubmittingParameterValues\"/>\n this.rv.ShowReportBody = true;\n"
},
{
"answer_id": 34054822,
"author": "Wayne",
"author_id": 3109012,
"author_profile": "https://Stackoverflow.com/users/3109012",
"pm_score": 2,
"selected": false,
"text": "WHERE (@param=\"\" OR column = @param)"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5599/"
] |
277,715
|
<p>i tried the following</p>
<ol>
<li><code>svnadmin create svn_repos</code></li>
<li><code>svn import my_first_proj file:///c:/svn_repos -m "initial import"</code></li>
<li><code>svn checkout file:///c:/svn_repos</code></li>
</ol>
<p>and the command returned</p>
<pre><code>A svn_repos\trunk
A svn_repos\trunk\Sample.txt.txt
A svn_repos\branches
A svn_repos\branches\my_pers_branch
Checked out revision 1.
</code></pre>
<p>Yet the <code>.svn</code> folder was not created in the checked out folders.
Because of which [I guess], I'm not able to do <code>svn copy</code> or <code>svn merge</code>.</p>
<p>Why does this occur?
what is the problem?
is there anything wrong in my commands</p>
|
[
{
"answer_id": 277737,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 1,
"selected": false,
"text": "dir /AH"
},
{
"answer_id": 277738,
"author": "Mitch Haile",
"author_id": 28807,
"author_profile": "https://Stackoverflow.com/users/28807",
"pm_score": 1,
"selected": false,
"text": "svn: warning: '.' is not a working copy\n"
},
{
"answer_id": 277782,
"author": "vincent",
"author_id": 34871,
"author_profile": "https://Stackoverflow.com/users/34871",
"pm_score": 2,
"selected": false,
"text": "svn checkout --force file:///c:/svn_repos/ my_first_proj \n"
},
{
"answer_id": 277898,
"author": "lmop",
"author_id": 22260,
"author_profile": "https://Stackoverflow.com/users/22260",
"pm_score": 2,
"selected": false,
"text": "svn checkout file:///c:/svn_repos ./svn_repos\n trunk branches svnadmin create svn_repos\nsvn import my_first_proj file:///c:/svn_repos -m \"initial import\"\nsvn checkout file:///c:/svn_repos my_working_copy\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277715",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
277,726
|
<p>I have a query that is currently using a correlated subquery to return the results, but I am thinking the problem could be solved more eloquently perhaps using ROW_NUMBER().</p>
<p>The problem is around the profile of a value v, through a number of years for an Item. Each item has a number of versions, each with its own profile whick starts when the version is introduced and the data currently looks like this:</p>
<pre>
ItemId ItemVersionId Year Value
===========================================
1 1 01 0.1
1 1 02 0.1
1 1 03 0.2
1 1 04 0.2
1 1 05 0.2
1 1 06 0.3
1 1 07 0.3
1 1 08 0.4
1 2 04 0.3
1 2 05 0.3
1 2 06 0.3
1 2 07 0.4
1 2 08 0.5
1 3 07 0.6
1 3 08 0.7
2 1 01 0.1
2 1 01 0.1
2 1 01 0.2
etc
</pre>
<p>I want to return the full profile for an Item using the most recent version where applicable. For the above example for item 1:</p>
<pre>
ItemId ItemVersionId Year Value
===========================================
1 1 01 0.1
1 1 02 0.1
1 1 03 0.2
1 2 04 0.3
1 2 05 0.3
1 2 06 0.3
1 3 07 0.6
1 3 08 0.7
</pre>
<p>I am currently using</p>
<pre><code>SELECT ItemId, ItemVersionId, Year, Value
FROM table t
WHERE
ItemId = 1
AND ItemVersionId = (SELECT MAX(ItemVersionId) FROM table WHERE ItemId = t.ItemId AND Year = t.Year)
</code></pre>
<p>Whilst this returns the correct I suspect there is a more efficient way to do it, especially when the table gets large.</p>
<p>I am using SQL Server 2005.</p>
<p>Thanks in advance</p>
|
[
{
"answer_id": 277762,
"author": "Bliek",
"author_id": 17434,
"author_profile": "https://Stackoverflow.com/users/17434",
"pm_score": 4,
"selected": true,
"text": "WITH Result AS\n(\n SELECT Row_Number() OVER (PARTITION BY ItemId, Year\nORDER BY ItemversionId DESC) AS RowNumber\n ,ItemId\n ,ItemversionId\n ,Year\n ,Value\n FROM table\n)\nSELECT ItemId\n ,ItemversionId\n ,Year\n ,Value\nFROM Result\nWHERE RowNumber = 1\nORDER BY ItemId, Year\n"
},
{
"answer_id": 278107,
"author": "Tom H",
"author_id": 5696608,
"author_profile": "https://Stackoverflow.com/users/5696608",
"pm_score": 0,
"selected": false,
"text": "SELECT\n T1.ItemID,\n T1.ItemVersionID,\n T1.Year,\n T1.Value\nFROM\n MyTable T1\nINNER JOIN (SELECT Year, MAX(ItemVersionID) AS MaxItemVersionID FROM MyTable T2 WHERE T2.ItemID = 1 GROUP BY Year) SQ ON\n SQ.Year = T1.Year AND\n SQ.MaxItemVersionID = T1.ItemVersionID\nWHERE\n T1.ItemID = 1\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21197/"
] |
277,744
|
<p>I'm getting an Exception while trying to insert a row in oracle table.
I'm using ojdbc5.jar for oracle 11
this is the sql i'm trying </p>
<pre><code>INSERT INTO rule_definitions(RULE_DEFINITION_SYS,rule_definition_type,
rule_name,rule_text,rule_comment,rule_message,rule_condition,rule_active,
rule_type,current_value,last_modified_by,last_modified_dttm,
rule_category_sys,recheck_unit,recheck_period,trackable)
VALUES(RULE_DEFINITIONS_SEQ.NEXTVAL,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
</code></pre>
<p>and i get following Exception. Any help will be appreciated.</p>
<pre>
java.ljava.lang.ArrayIndexOutOfBoundsException: 15
at oracle.jdbc.driver.OracleSql.computeBasicInfo(OracleSql.java:950)
at oracle.jdbc.driver.OracleSql.getSqlKind(OracleSql.java:623)
at oracle.jdbc.driver.OraclePreparedStatement.(OraclePreparedStatement.java:1212)
at oracle.jdbc.driver.T4CPreparedStatement.(T4CPreparedStatement.java:28)
at oracle.jdbc.driver.T4CDriverExtension.allocatePreparedStatement(T4CDriverExtension.java:68)
at oracle.jdbc.driver.PhysicalConnection.prepareStatement(PhysicalConnection.java:3059)
at oracle.jdbc.driver.PhysicalConnection.prepareStatement(PhysicalConnection.java:2961)
at oracle.jdbc.driver.PhysicalConnection.prepareStatement(PhysicalConnection.java:5874)
at org.jboss.resource.adapter.jdbc.WrappedConnection.prepareStatement(WrappedConnection.java:232)
at com.gehcit.platform.cds.common.util.db.DBWrapper.executeInsertOracleReturnPK(DBWrapper.java:605)
</pre>
|
[
{
"answer_id": 280527,
"author": "Raimonds Simanovskis",
"author_id": 16829,
"author_profile": "https://Stackoverflow.com/users/16829",
"pm_score": 6,
"selected": true,
"text": "INSERT INTO rule_definitions(RULE_DEFINITION_SYS,rule_definition_type,\nrule_name,rule_text,rule_comment,rule_message,rule_condition,rule_active,\nrule_type,current_value,last_modified_by,last_modified_dttm,\nrule_category_sys,recheck_unit,recheck_period,trackable)\nVALUES(RULE_DEFINITIONS_SEQ.NEXTVAL,:rule_definition_type,\n:rule_name,:rule_text,:rule_comment,:rule_message,:rule_condition,:rule_active,\n:rule_type,:current_value,:last_modified_by,:last_modified_dttm,\n:rule_category_sys,:recheck_unit,:recheck_period,:trackable)\n preparedStatement.setStringAtName(\"rule_definition_type\", ...)\n"
},
{
"answer_id": 38477322,
"author": "Siva Anand",
"author_id": 2573744,
"author_profile": "https://Stackoverflow.com/users/2573744",
"pm_score": 1,
"selected": false,
"text": " <dependency>\n <groupId>com.oracle</groupId>\n <artifactId>ojdbc14</artifactId>\n <version>10.2.0.3.0</version>\n </dependency>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11247/"
] |
277,771
|
<p>How do I create, execute and control a winform from within a console application?</p>
|
[
{
"answer_id": 277776,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 8,
"selected": true,
"text": "using System.Windows.Forms;\n\n[STAThread]\nstatic void Main() {\n Application.EnableVisualStyles();\n Application.Run(new Form()); // or whatever\n}\n [STAThread] Main()"
},
{
"answer_id": 279811,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "internal static class NativeMethods\n{\n [DllImport(\"kernel32.dll\")]\n internal static extern Boolean AllocConsole();\n}\n\nstatic class Program\n{\n\n static void Main(string[] args) {\n if (args.Length == 0) {\n // run as windows app\n Application.EnableVisualStyles();\n Application.Run(new Form1()); \n } else {\n // run as console app\n NativeMethods.AllocConsole();\n Console.WriteLine(\"Hello World\");\n Console.ReadLine();\n }\n }\n\n}\n"
},
{
"answer_id": 8347807,
"author": "SharpShade",
"author_id": 559310,
"author_profile": "https://Stackoverflow.com/users/559310",
"pm_score": 3,
"selected": false,
"text": "[STAThread]\nvoid Main(string[] args])\n{\n Application.EnableVisualStyles();\n //Do some stuff...\n while(!Exit)\n {\n Application.DoEvents(); //Now if you call \"form.Show()\" your form won´t be frozen\n //Do your stuff\n }\n}\n"
},
{
"answer_id": 31307612,
"author": "SunsetQuest",
"author_id": 2352507,
"author_profile": "https://Stackoverflow.com/users/2352507",
"pm_score": 2,
"selected": false,
"text": "Task mytask = Task.Run(() =>\n{\n MyForm form = new MyForm();\n form.ShowDialog();\n});\n Task"
},
{
"answer_id": 32155377,
"author": "Raj kumar",
"author_id": 1642862,
"author_profile": "https://Stackoverflow.com/users/1642862",
"pm_score": 0,
"selected": false,
"text": "Application.Run(new Form1());\n//or -------------\nForm1 f = new Form1();\nf.ShowDialog();\n"
},
{
"answer_id": 49944418,
"author": "AndrewToasterr",
"author_id": 9675356,
"author_profile": "https://Stackoverflow.com/users/9675356",
"pm_score": 0,
"selected": false,
"text": "Form form = new Form();\nForm.Button.Text = \"randomText\";\nSystem.Windows.Forms.Application.EnableVisualStyles();\nSystem.Windows.Forms.Application.Run(form);\n"
},
{
"answer_id": 50827451,
"author": "Biju Joseph",
"author_id": 7453276,
"author_profile": "https://Stackoverflow.com/users/7453276",
"pm_score": 2,
"selected": false,
"text": "using System.Windows.Forms; int Left { get; set; } // need to specify the LEFT position of the button on the Form Main() static void Main(string[] args)\n{\nApplication.EnableVisualStyles();\n Form frm = new Form(); // create aForm object\n\n Button btn = new Button()\n {\n Left = 120,\n Width = 130,\n Height = 30,\n Top = 150,\n Text = \"Biju Joseph, Redmond, WA\"\n };\n //… more code \n frm.Controls.Add(btn); // add button to the Form\n // …. add more code here as needed\n\n frm.ShowDialog(); // a modal dialog \n}\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277771",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30717/"
] |
277,772
|
<p>I keep stumbling on the format specifiers for the printf() family of functions. What I want is to be able to print a double (or float) with a maximum given number of digits after the decimal point. If I use:</p>
<pre><code>printf("%1.3f", 359.01335);
printf("%1.3f", 359.00999);
</code></pre>
<p>I get</p>
<pre><code>359.013
359.010
</code></pre>
<p>Instead of the desired</p>
<pre><code>359.013
359.01
</code></pre>
<p>Can anybody help me?</p>
|
[
{
"answer_id": 277779,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 6,
"selected": false,
"text": "float num = 1.33;\nprintf(\"%g\", num); //output: 1.33\n"
},
{
"answer_id": 277810,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 8,
"selected": true,
"text": "printf printf(\"%.6g\", 359.013); // 359.013\nprintf(\"%.6g\", 359.01); // 359.01\n printf(\"%.6g\", 3.01357); // 3.01357\n sprintf(\"%.20g\") N char str[50];\nsprintf (str,\"%.20g\",num); // Make the number.\nmorphNumericString (str, 3);\n: :\nvoid morphNumericString (char *s, int n) {\n char *p;\n int count;\n\n p = strchr (s,'.'); // Find decimal point, if any.\n if (p != NULL) {\n count = n; // Adjust for more or less decimals.\n while (count >= 0) { // Maximum decimals allowed.\n count--;\n if (*p == '\\0') // If there's less than desired.\n break;\n p++; // Next character.\n }\n\n *p-- = '\\0'; // Truncate string.\n while (*p == '0') // Remove trailing zeros.\n *p-- = '\\0';\n\n if (*p == '.') { // If all decimals were zeros, remove \".\".\n *p = '\\0';\n }\n }\n}\n 0.12399 0.123 0.124 printf #include <stdio.h>\n\nvoid nDecimals (char *s, double d, int n) {\n int sz; double d2;\n\n // Allow for negative.\n\n d2 = (d >= 0) ? d : -d;\n sz = (d >= 0) ? 0 : 1;\n\n // Add one for each whole digit (0.xx special case).\n\n if (d2 < 1) sz++;\n while (d2 >= 1) { d2 /= 10.0; sz++; }\n\n // Adjust for decimal point and fractionals.\n\n sz += 1 + n;\n\n // Create format string then use it.\n\n sprintf (s, \"%*.*f\", sz, n, d);\n}\n\nint main (void) {\n char str[50];\n double num[] = { 40, 359.01335, -359.00999,\n 359.01, 3.01357, 0.111111111, 1.1223344 };\n for (int i = 0; i < sizeof(num)/sizeof(*num); i++) {\n nDecimals (str, num[i], 3);\n printf (\"%30.20f -> %s\\n\", num[i], str);\n }\n return 0;\n}\n nDecimals() main() 40.00000000000000000000 -> 40.000\n 359.01335000000000263753 -> 359.013\n-359.00999000000001615263 -> -359.010\n 359.00999999999999090505 -> 359.010\n 3.01357000000000008200 -> 3.014\n 0.11111111099999999852 -> 0.111\n 1.12233439999999995429 -> 1.122\n morphNumericString() nDecimals (str, num[i], 3);\n nDecimals (str, num[i], 3);\nmorphNumericString (str, 3);\n morphNumericString nDecimals 40.00000000000000000000 -> 40\n 359.01335000000000263753 -> 359.013\n-359.00999000000001615263 -> -359.01\n 359.00999999999999090505 -> 359.01\n 3.01357000000000008200 -> 3.014\n 0.11111111099999999852 -> 0.111\n 1.12233439999999995429 -> 1.122\n"
},
{
"answer_id": 2174887,
"author": "David Thornley",
"author_id": 196390,
"author_profile": "https://Stackoverflow.com/users/196390",
"pm_score": 0,
"selected": false,
"text": "void EliminateTrailingFloatZeros(char *iValue)\n{\n char *p = 0;\n for(p=iValue; *p; ++p) {\n if('.' == *p) {\n while(*++p);\n while('0'==*--p) *p = '\\0';\n if(*p == '.') *p = '\\0';\n break;\n }\n }\n}\n"
},
{
"answer_id": 3201560,
"author": "R.. GitHub STOP HELPING ICE",
"author_id": 379897,
"author_profile": "https://Stackoverflow.com/users/379897",
"pm_score": 2,
"selected": false,
"text": "printf(\"%.0d%.4g\\n\", (int)f/10, f-((int)f-(int)f%10));\n"
},
{
"answer_id": 4247516,
"author": "Juha",
"author_id": 311323,
"author_profile": "https://Stackoverflow.com/users/311323",
"pm_score": 4,
"selected": false,
"text": "float f = 1234.56789;\nprintf(\"%d.%.0f\", f, 1000*(f-(int)f));\n double f = 1234.05678900;\nchar s[100]; \nint decimals = 10;\n\nsprintf(s,\"%.*g\", decimals, ((int)(pow(10, decimals)*(fabs(f) - abs((int)f)) +0.5))/pow(10,decimals));\nprintf(\"10 decimals: %d%s\\n\", (int)f, s+1);\n #import <stdio.h>\n#import <stdlib.h>\n#import <math.h>\n\nint main(void){\n\n double f = 1234.05678900;\n char s[100];\n int decimals;\n\n decimals = 10;\n sprintf(s,\"%.*g\", decimals, ((int)(pow(10, decimals)*(fabs(f) - abs((int)f)) +0.5))/pow(10,decimals));\n printf(\"10 decimals: %d%s\\n\", (int)f, s+1);\n\n decimals = 3;\n sprintf(s,\"%.*g\", decimals, ((int)(pow(10, decimals)*(fabs(f) - abs((int)f)) +0.5))/pow(10,decimals));\n printf(\" 3 decimals: %d%s\\n\", (int)f, s+1);\n\n f = -f;\n decimals = 10;\n sprintf(s,\"%.*g\", decimals, ((int)(pow(10, decimals)*(fabs(f) - abs((int)f)) +0.5))/pow(10,decimals));\n printf(\" negative 10: %d%s\\n\", (int)f, s+1);\n\n decimals = 3;\n sprintf(s,\"%.*g\", decimals, ((int)(pow(10, decimals)*(fabs(f) - abs((int)f)) +0.5))/pow(10,decimals));\n printf(\" negative 3: %d%s\\n\", (int)f, s+1);\n\n decimals = 2;\n f = 1.012;\n sprintf(s,\"%.*g\", decimals, ((int)(pow(10, decimals)*(fabs(f) - abs((int)f)) +0.5))/pow(10,decimals));\n printf(\" additional : %d%s\\n\", (int)f, s+1);\n\n return 0;\n}\n 10 decimals: 1234.056789\n 3 decimals: 1234.057\n negative 10: -1234.056789\n negative 3: -1234.057\n additional : 1.01\n sprintf"
},
{
"answer_id": 15127324,
"author": "Iaijutsu",
"author_id": 2118088,
"author_profile": "https://Stackoverflow.com/users/2118088",
"pm_score": 1,
"selected": false,
"text": "// Since we are only interested in 3 decimal places, this function\n// can avoid any potential miniscule floating point differences\n// which can return false when using \"==\"\nint DoubleEquals(double i, double j)\n{\n return (fabs(i - j) < 0.000001);\n}\n\nvoid PrintMaxThreeDecimal(double d)\n{\n if (DoubleEquals(d, floor(d)))\n printf(\"%.0f\", d);\n else if (DoubleEquals(d * 10, floor(d * 10)))\n printf(\"%.1f\", d);\n else if (DoubleEquals(d * 100, floor(d* 100)))\n printf(\"%.2f\", d);\n else\n printf(\"%.3f\", d);\n}\n void PrintMaxTwoDecimal(double d)\n{\n if (DoubleEquals(d, floor(d)))\n printf(\"%.0f\", d);\n else if (DoubleEquals(d * 10, floor(d * 10)))\n printf(\"%.1f\", d);\n else\n printf(\"%.2f\", d);\n}\n void PrintAlignedMaxThreeDecimal(double d)\n{\n if (DoubleEquals(d, floor(d)))\n printf(\"%7.0f\", d);\n else if (DoubleEquals(d * 10, floor(d * 10)))\n printf(\"%9.1f\", d);\n else if (DoubleEquals(d * 100, floor(d* 100)))\n printf(\"%10.2f\", d);\n else\n printf(\"%11.3f\", d);\n}\n void PrintAlignedWidthMaxThreeDecimal(int w, double d)\n{\n if (DoubleEquals(d, floor(d)))\n printf(\"%*.0f\", w-4, d);\n else if (DoubleEquals(d * 10, floor(d * 10)))\n printf(\"%*.1f\", w-2, d);\n else if (DoubleEquals(d * 100, floor(d* 100)))\n printf(\"%*.2f\", w-1, d);\n else\n printf(\"%*.3f\", w, d);\n}\n"
},
{
"answer_id": 15285177,
"author": "DaveR",
"author_id": 2146709,
"author_profile": "https://Stackoverflow.com/users/2146709",
"pm_score": 2,
"selected": false,
"text": "1 9 49 57 null 0 void stripTrailingZeros(void) { \n //This finds the index of the rightmost ASCII char[1-9] in array\n //All elements to the left of this are nulled (=0)\n int i = 20;\n unsigned char char1 = 0; //initialised to ensure entry to condition below\n\n while ((char1 > 57) || (char1 < 49)) {\n i--;\n char1 = sprintfBuffer[i];\n }\n\n //null chars left of i\n for (int j = i; j < 20; j++) {\n sprintfBuffer[i] = 0;\n }\n}\n"
},
{
"answer_id": 18993051,
"author": "TeamXlink",
"author_id": 2812967,
"author_profile": "https://Stackoverflow.com/users/2812967",
"pm_score": -1,
"selected": false,
"text": "printf(\"%1.3f\", 359.01335);\nprintf(\"%1.3f\", 359.00999);\n printf(\"%1.3f\", 359.01335);\nprintf(\"%1.2f\", 359.00999);\n 359.013\n359.01\n printf(\"%1.3f\\n\", 359.01335);\nprintf(\"%1.2f\\n\", 359.00999);\n #include <cstdio>\n\nint main()\n{\n\n printf(\"%1.3f\\n\", 359.01335);\n printf(\"%1.2f\\n\", 359.00999);\n\n while (true){}\n\n return 0;\n\n}\n"
},
{
"answer_id": 25313464,
"author": "Jim Hunziker",
"author_id": 6160,
"author_profile": "https://Stackoverflow.com/users/6160",
"pm_score": 3,
"selected": false,
"text": "double f = 359.01335;\nprintf(\"%g\", round(f * 1000.0) / 1000.0);\n"
},
{
"answer_id": 33448480,
"author": "magnusviri",
"author_id": 5509250,
"author_profile": "https://Stackoverflow.com/users/5509250",
"pm_score": 1,
"selected": false,
"text": "int doubleEquals(double i, double j) {\n return (fabs(i - j) < 0.000001);\n}\n\nvoid printTruncatedDouble(double dd, int max_len) {\n char str[50];\n int match = 0;\n for ( int ii = 0; ii < max_len; ii++ ) {\n if (doubleEquals(dd * pow(10,ii), floor(dd * pow(10,ii)))) {\n sprintf (str,\"%f\", round(dd*pow(10,ii))/pow(10,ii));\n match = 1;\n break;\n }\n }\n if ( match != 1 ) {\n sprintf (str,\"%f\", round(dd*pow(10,max_len))/pow(10,max_len));\n }\n char *pp;\n int count;\n pp = strchr (str,'.');\n if (pp != NULL) {\n count = max_len;\n while (count >= 0) {\n count--;\n if (*pp == '\\0')\n break;\n pp++;\n }\n *pp-- = '\\0';\n while (*pp == '0')\n *pp-- = '\\0';\n if (*pp == '.') {\n *pp = '\\0';\n }\n }\n printf (\"%s\\n\", str);\n}\n\nint main(int argc, char **argv)\n{\n printTruncatedDouble( -1.999, 2 ); // prints -2\n printTruncatedDouble( -1.006, 2 ); // prints -1.01\n printTruncatedDouble( -1.005, 2 ); // prints -1\n printf(\"\\n\");\n printTruncatedDouble( 1.005, 2 ); // prints 1 (should be 1.01?)\n printTruncatedDouble( 1.006, 2 ); // prints 1.01\n printTruncatedDouble( 1.999, 2 ); // prints 2\n printf(\"\\n\");\n printTruncatedDouble( -1.999, 3 ); // prints -1.999\n printTruncatedDouble( -1.001, 3 ); // prints -1.001\n printTruncatedDouble( -1.0005, 3 ); // prints -1.001 (shound be -1?)\n printTruncatedDouble( -1.0004, 3 ); // prints -1\n printf(\"\\n\");\n printTruncatedDouble( 1.0004, 3 ); // prints 1\n printTruncatedDouble( 1.0005, 3 ); // prints 1.001\n printTruncatedDouble( 1.001, 3 ); // prints 1.001\n printTruncatedDouble( 1.999, 3 ); // prints 1.999\n printf(\"\\n\");\n exit(0);\n}\n"
},
{
"answer_id": 36202854,
"author": "nwellnhof",
"author_id": 1956010,
"author_profile": "https://Stackoverflow.com/users/1956010",
"pm_score": 2,
"selected": false,
"text": "%g printf %g sprintf %f #include <stdio.h>\n#include <stdlib.h>\n\nchar*\nformat_double(double d) {\n int size = snprintf(NULL, 0, \"%.3f\", d);\n char *str = malloc(size + 1);\n snprintf(str, size + 1, \"%.3f\", d);\n\n for (int i = size - 1, end = size; i >= 0; i--) {\n if (str[i] == '0') {\n if (end == i + 1) {\n end = i;\n }\n }\n else if (str[i] == '.') {\n if (end == i + 1) {\n end = i;\n }\n str[end] = '\\0';\n break;\n }\n }\n\n return str;\n}\n"
},
{
"answer_id": 61432422,
"author": "Ankit Mishra",
"author_id": 13272795,
"author_profile": "https://Stackoverflow.com/users/13272795",
"pm_score": 0,
"selected": false,
"text": "printf(\"%.8g\",value); \"%.6g\" 32.23021 32.2302"
},
{
"answer_id": 63631055,
"author": "ravin.wang",
"author_id": 3968307,
"author_profile": "https://Stackoverflow.com/users/3968307",
"pm_score": 0,
"selected": false,
"text": "#include <stdio.h>\n#include <math.h>\n#include <string>\n#include <string.h>\n\nstd::string doublecompactstring(double d)\n{\n char buf[128] = {0};\n if (isnan(d))\n return \"NAN\";\n sprintf(buf, \"%.15f\", d);\n // try to remove the trailing zeros\n size_t ccLen = strlen(buf);\n for(int i=(int)(ccLen -1);i>=0;i--)\n {\n if (buf[i] == '0')\n buf[i] = '\\0';\n else\n break;\n }\n\n return buf;\n}\n\nstd::string floatcompactstring(float d)\n{\n char buf[128] = {0};\n if (isnan(d))\n return \"NAN\";\n sprintf(buf, \"%.6f\", d);\n // try to remove the trailing zeros\n size_t ccLen = strlen(buf);\n for(int i=(int)(ccLen -1);i>=0;i--)\n {\n if (buf[i] == '0')\n buf[i] = '\\0';\n else\n break;\n }\n\n return buf;\n}\n\nint main(int argc, const char* argv[])\n{\n double a = 0.000000000000001;\n float b = 0.000001f;\n\n printf(\"a: %s\\n\", doublecompactstring(a).c_str());\n printf(\"b: %s\\n\", floatcompactstring(b).c_str());\n return 0;\n}\n a: 0.000000000000001\nb: 0.000001\n"
},
{
"answer_id": 67717966,
"author": "baah",
"author_id": 16046159,
"author_profile": "https://Stackoverflow.com/users/16046159",
"pm_score": 0,
"selected": false,
"text": "//https://stackoverflow.com/questions/277772/avoid-trailing-zeroes-in-printf\n//adapted from paxdiablo (removed truncating)\nchar StringForDouble[50];\nchar *PointerInString;\nvoid PrintDouble (double number) {\n sprintf(StringForDouble,\"%.10f\",number); // convert number to string\n PointerInString=strchr(&StringForDouble[0],'.'); // find decimal point, if any\n if(PointerInString!=NULL) {\n PointerInString=strchr(&PointerInString[0],'\\0'); // find end of string\n do{\n PointerInString--;\n } while(PointerInString[0]=='0'); // remove trailing zeros\n if (PointerInString[0]=='.') { // if all decimals were zeros, remove \".\"\n PointerInString[0]='\\0';\n } else {\n PointerInString[1]='\\0'; //otherwise put EOS after the first non zero char\n }\n }\n printf(\"%s\",&StringForDouble[0]);\n}\n"
},
{
"answer_id": 70378558,
"author": "user1686153",
"author_id": 1686153,
"author_profile": "https://Stackoverflow.com/users/1686153",
"pm_score": 1,
"selected": false,
"text": "\"%1.*f\" int main() {\n double r=1234.56789;\n int precision=3;\n printf(L\"%1.*f\", prec(r, precision), r);\n}\n\nint prec(const double& r, int precision)\n{\n double rPos = (r < 0)? -r : r;\n double nkd = fmod(rPos, 1.0); // 0..0.99999999\n int i, ex10 = 1;\n for (i = 0; i < precision; ++i)\n ex10 *= 10;\n int nki = (int)(nkd * ex10 + 0.5);\n\n // \"Eliminate\" trailing zeroes\n int requiredPrecision = precision;\n for (; requiredPrecision && !(nki % 10); ) {\n --requiredPrecision;\n nki /= 10;\n }\n return requiredPrecision; \n}\n %g double round(const double &value, const double& rounding) {\n return rounding!=0 ? floor(value/rounding + 0.5)*rounding : value;\n}\n\nprintf(\"%.12g\" round(val, 0.001)); // prints up to 3 relevant digits\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25824/"
] |
277,775
|
<p>I want to call a c# function from my javascript function.</p>
<p>I have a link button in my ascx (please see the code below). The problem is that if you press enter in firefox is not working however it is working fine in internet explorer.</p>
<pre><code><li class="clearfix border_top">
<label for="title" class="first_column bold">Search For</label>
<div class="contactUs_details">
<input type="text" id="advanced_txtBox1" name="advanced_txtBox1" class="searchbox" runat="server" style="width:300px;" />&nbsp;&nbsp;&nbsp;&nbsp;
<asp:CheckBox ID="chkSearchBDJ" runat="server" Text="Search BDJ" CssClass="checkboxlistnoborder" />
</div>
</li>
<div class="img_SearchNow">
<asp:LinkButton ID="btnSearchNow" CausesValidation="true" runat="server" OnClick="btnSearchNow_Click"></asp:LinkButton>
</div>
</code></pre>
<p>I have linkButton see above on which I have called on c# function on Click, But if you pree some text in above textbox and press "Enter" it should automatically call function "btnSearchNow_Click". It is working fine in IE but not working in Firefox.</p>
|
[
{
"answer_id": 277779,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 6,
"selected": false,
"text": "float num = 1.33;\nprintf(\"%g\", num); //output: 1.33\n"
},
{
"answer_id": 277810,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 8,
"selected": true,
"text": "printf printf(\"%.6g\", 359.013); // 359.013\nprintf(\"%.6g\", 359.01); // 359.01\n printf(\"%.6g\", 3.01357); // 3.01357\n sprintf(\"%.20g\") N char str[50];\nsprintf (str,\"%.20g\",num); // Make the number.\nmorphNumericString (str, 3);\n: :\nvoid morphNumericString (char *s, int n) {\n char *p;\n int count;\n\n p = strchr (s,'.'); // Find decimal point, if any.\n if (p != NULL) {\n count = n; // Adjust for more or less decimals.\n while (count >= 0) { // Maximum decimals allowed.\n count--;\n if (*p == '\\0') // If there's less than desired.\n break;\n p++; // Next character.\n }\n\n *p-- = '\\0'; // Truncate string.\n while (*p == '0') // Remove trailing zeros.\n *p-- = '\\0';\n\n if (*p == '.') { // If all decimals were zeros, remove \".\".\n *p = '\\0';\n }\n }\n}\n 0.12399 0.123 0.124 printf #include <stdio.h>\n\nvoid nDecimals (char *s, double d, int n) {\n int sz; double d2;\n\n // Allow for negative.\n\n d2 = (d >= 0) ? d : -d;\n sz = (d >= 0) ? 0 : 1;\n\n // Add one for each whole digit (0.xx special case).\n\n if (d2 < 1) sz++;\n while (d2 >= 1) { d2 /= 10.0; sz++; }\n\n // Adjust for decimal point and fractionals.\n\n sz += 1 + n;\n\n // Create format string then use it.\n\n sprintf (s, \"%*.*f\", sz, n, d);\n}\n\nint main (void) {\n char str[50];\n double num[] = { 40, 359.01335, -359.00999,\n 359.01, 3.01357, 0.111111111, 1.1223344 };\n for (int i = 0; i < sizeof(num)/sizeof(*num); i++) {\n nDecimals (str, num[i], 3);\n printf (\"%30.20f -> %s\\n\", num[i], str);\n }\n return 0;\n}\n nDecimals() main() 40.00000000000000000000 -> 40.000\n 359.01335000000000263753 -> 359.013\n-359.00999000000001615263 -> -359.010\n 359.00999999999999090505 -> 359.010\n 3.01357000000000008200 -> 3.014\n 0.11111111099999999852 -> 0.111\n 1.12233439999999995429 -> 1.122\n morphNumericString() nDecimals (str, num[i], 3);\n nDecimals (str, num[i], 3);\nmorphNumericString (str, 3);\n morphNumericString nDecimals 40.00000000000000000000 -> 40\n 359.01335000000000263753 -> 359.013\n-359.00999000000001615263 -> -359.01\n 359.00999999999999090505 -> 359.01\n 3.01357000000000008200 -> 3.014\n 0.11111111099999999852 -> 0.111\n 1.12233439999999995429 -> 1.122\n"
},
{
"answer_id": 2174887,
"author": "David Thornley",
"author_id": 196390,
"author_profile": "https://Stackoverflow.com/users/196390",
"pm_score": 0,
"selected": false,
"text": "void EliminateTrailingFloatZeros(char *iValue)\n{\n char *p = 0;\n for(p=iValue; *p; ++p) {\n if('.' == *p) {\n while(*++p);\n while('0'==*--p) *p = '\\0';\n if(*p == '.') *p = '\\0';\n break;\n }\n }\n}\n"
},
{
"answer_id": 3201560,
"author": "R.. GitHub STOP HELPING ICE",
"author_id": 379897,
"author_profile": "https://Stackoverflow.com/users/379897",
"pm_score": 2,
"selected": false,
"text": "printf(\"%.0d%.4g\\n\", (int)f/10, f-((int)f-(int)f%10));\n"
},
{
"answer_id": 4247516,
"author": "Juha",
"author_id": 311323,
"author_profile": "https://Stackoverflow.com/users/311323",
"pm_score": 4,
"selected": false,
"text": "float f = 1234.56789;\nprintf(\"%d.%.0f\", f, 1000*(f-(int)f));\n double f = 1234.05678900;\nchar s[100]; \nint decimals = 10;\n\nsprintf(s,\"%.*g\", decimals, ((int)(pow(10, decimals)*(fabs(f) - abs((int)f)) +0.5))/pow(10,decimals));\nprintf(\"10 decimals: %d%s\\n\", (int)f, s+1);\n #import <stdio.h>\n#import <stdlib.h>\n#import <math.h>\n\nint main(void){\n\n double f = 1234.05678900;\n char s[100];\n int decimals;\n\n decimals = 10;\n sprintf(s,\"%.*g\", decimals, ((int)(pow(10, decimals)*(fabs(f) - abs((int)f)) +0.5))/pow(10,decimals));\n printf(\"10 decimals: %d%s\\n\", (int)f, s+1);\n\n decimals = 3;\n sprintf(s,\"%.*g\", decimals, ((int)(pow(10, decimals)*(fabs(f) - abs((int)f)) +0.5))/pow(10,decimals));\n printf(\" 3 decimals: %d%s\\n\", (int)f, s+1);\n\n f = -f;\n decimals = 10;\n sprintf(s,\"%.*g\", decimals, ((int)(pow(10, decimals)*(fabs(f) - abs((int)f)) +0.5))/pow(10,decimals));\n printf(\" negative 10: %d%s\\n\", (int)f, s+1);\n\n decimals = 3;\n sprintf(s,\"%.*g\", decimals, ((int)(pow(10, decimals)*(fabs(f) - abs((int)f)) +0.5))/pow(10,decimals));\n printf(\" negative 3: %d%s\\n\", (int)f, s+1);\n\n decimals = 2;\n f = 1.012;\n sprintf(s,\"%.*g\", decimals, ((int)(pow(10, decimals)*(fabs(f) - abs((int)f)) +0.5))/pow(10,decimals));\n printf(\" additional : %d%s\\n\", (int)f, s+1);\n\n return 0;\n}\n 10 decimals: 1234.056789\n 3 decimals: 1234.057\n negative 10: -1234.056789\n negative 3: -1234.057\n additional : 1.01\n sprintf"
},
{
"answer_id": 15127324,
"author": "Iaijutsu",
"author_id": 2118088,
"author_profile": "https://Stackoverflow.com/users/2118088",
"pm_score": 1,
"selected": false,
"text": "// Since we are only interested in 3 decimal places, this function\n// can avoid any potential miniscule floating point differences\n// which can return false when using \"==\"\nint DoubleEquals(double i, double j)\n{\n return (fabs(i - j) < 0.000001);\n}\n\nvoid PrintMaxThreeDecimal(double d)\n{\n if (DoubleEquals(d, floor(d)))\n printf(\"%.0f\", d);\n else if (DoubleEquals(d * 10, floor(d * 10)))\n printf(\"%.1f\", d);\n else if (DoubleEquals(d * 100, floor(d* 100)))\n printf(\"%.2f\", d);\n else\n printf(\"%.3f\", d);\n}\n void PrintMaxTwoDecimal(double d)\n{\n if (DoubleEquals(d, floor(d)))\n printf(\"%.0f\", d);\n else if (DoubleEquals(d * 10, floor(d * 10)))\n printf(\"%.1f\", d);\n else\n printf(\"%.2f\", d);\n}\n void PrintAlignedMaxThreeDecimal(double d)\n{\n if (DoubleEquals(d, floor(d)))\n printf(\"%7.0f\", d);\n else if (DoubleEquals(d * 10, floor(d * 10)))\n printf(\"%9.1f\", d);\n else if (DoubleEquals(d * 100, floor(d* 100)))\n printf(\"%10.2f\", d);\n else\n printf(\"%11.3f\", d);\n}\n void PrintAlignedWidthMaxThreeDecimal(int w, double d)\n{\n if (DoubleEquals(d, floor(d)))\n printf(\"%*.0f\", w-4, d);\n else if (DoubleEquals(d * 10, floor(d * 10)))\n printf(\"%*.1f\", w-2, d);\n else if (DoubleEquals(d * 100, floor(d* 100)))\n printf(\"%*.2f\", w-1, d);\n else\n printf(\"%*.3f\", w, d);\n}\n"
},
{
"answer_id": 15285177,
"author": "DaveR",
"author_id": 2146709,
"author_profile": "https://Stackoverflow.com/users/2146709",
"pm_score": 2,
"selected": false,
"text": "1 9 49 57 null 0 void stripTrailingZeros(void) { \n //This finds the index of the rightmost ASCII char[1-9] in array\n //All elements to the left of this are nulled (=0)\n int i = 20;\n unsigned char char1 = 0; //initialised to ensure entry to condition below\n\n while ((char1 > 57) || (char1 < 49)) {\n i--;\n char1 = sprintfBuffer[i];\n }\n\n //null chars left of i\n for (int j = i; j < 20; j++) {\n sprintfBuffer[i] = 0;\n }\n}\n"
},
{
"answer_id": 18993051,
"author": "TeamXlink",
"author_id": 2812967,
"author_profile": "https://Stackoverflow.com/users/2812967",
"pm_score": -1,
"selected": false,
"text": "printf(\"%1.3f\", 359.01335);\nprintf(\"%1.3f\", 359.00999);\n printf(\"%1.3f\", 359.01335);\nprintf(\"%1.2f\", 359.00999);\n 359.013\n359.01\n printf(\"%1.3f\\n\", 359.01335);\nprintf(\"%1.2f\\n\", 359.00999);\n #include <cstdio>\n\nint main()\n{\n\n printf(\"%1.3f\\n\", 359.01335);\n printf(\"%1.2f\\n\", 359.00999);\n\n while (true){}\n\n return 0;\n\n}\n"
},
{
"answer_id": 25313464,
"author": "Jim Hunziker",
"author_id": 6160,
"author_profile": "https://Stackoverflow.com/users/6160",
"pm_score": 3,
"selected": false,
"text": "double f = 359.01335;\nprintf(\"%g\", round(f * 1000.0) / 1000.0);\n"
},
{
"answer_id": 33448480,
"author": "magnusviri",
"author_id": 5509250,
"author_profile": "https://Stackoverflow.com/users/5509250",
"pm_score": 1,
"selected": false,
"text": "int doubleEquals(double i, double j) {\n return (fabs(i - j) < 0.000001);\n}\n\nvoid printTruncatedDouble(double dd, int max_len) {\n char str[50];\n int match = 0;\n for ( int ii = 0; ii < max_len; ii++ ) {\n if (doubleEquals(dd * pow(10,ii), floor(dd * pow(10,ii)))) {\n sprintf (str,\"%f\", round(dd*pow(10,ii))/pow(10,ii));\n match = 1;\n break;\n }\n }\n if ( match != 1 ) {\n sprintf (str,\"%f\", round(dd*pow(10,max_len))/pow(10,max_len));\n }\n char *pp;\n int count;\n pp = strchr (str,'.');\n if (pp != NULL) {\n count = max_len;\n while (count >= 0) {\n count--;\n if (*pp == '\\0')\n break;\n pp++;\n }\n *pp-- = '\\0';\n while (*pp == '0')\n *pp-- = '\\0';\n if (*pp == '.') {\n *pp = '\\0';\n }\n }\n printf (\"%s\\n\", str);\n}\n\nint main(int argc, char **argv)\n{\n printTruncatedDouble( -1.999, 2 ); // prints -2\n printTruncatedDouble( -1.006, 2 ); // prints -1.01\n printTruncatedDouble( -1.005, 2 ); // prints -1\n printf(\"\\n\");\n printTruncatedDouble( 1.005, 2 ); // prints 1 (should be 1.01?)\n printTruncatedDouble( 1.006, 2 ); // prints 1.01\n printTruncatedDouble( 1.999, 2 ); // prints 2\n printf(\"\\n\");\n printTruncatedDouble( -1.999, 3 ); // prints -1.999\n printTruncatedDouble( -1.001, 3 ); // prints -1.001\n printTruncatedDouble( -1.0005, 3 ); // prints -1.001 (shound be -1?)\n printTruncatedDouble( -1.0004, 3 ); // prints -1\n printf(\"\\n\");\n printTruncatedDouble( 1.0004, 3 ); // prints 1\n printTruncatedDouble( 1.0005, 3 ); // prints 1.001\n printTruncatedDouble( 1.001, 3 ); // prints 1.001\n printTruncatedDouble( 1.999, 3 ); // prints 1.999\n printf(\"\\n\");\n exit(0);\n}\n"
},
{
"answer_id": 36202854,
"author": "nwellnhof",
"author_id": 1956010,
"author_profile": "https://Stackoverflow.com/users/1956010",
"pm_score": 2,
"selected": false,
"text": "%g printf %g sprintf %f #include <stdio.h>\n#include <stdlib.h>\n\nchar*\nformat_double(double d) {\n int size = snprintf(NULL, 0, \"%.3f\", d);\n char *str = malloc(size + 1);\n snprintf(str, size + 1, \"%.3f\", d);\n\n for (int i = size - 1, end = size; i >= 0; i--) {\n if (str[i] == '0') {\n if (end == i + 1) {\n end = i;\n }\n }\n else if (str[i] == '.') {\n if (end == i + 1) {\n end = i;\n }\n str[end] = '\\0';\n break;\n }\n }\n\n return str;\n}\n"
},
{
"answer_id": 61432422,
"author": "Ankit Mishra",
"author_id": 13272795,
"author_profile": "https://Stackoverflow.com/users/13272795",
"pm_score": 0,
"selected": false,
"text": "printf(\"%.8g\",value); \"%.6g\" 32.23021 32.2302"
},
{
"answer_id": 63631055,
"author": "ravin.wang",
"author_id": 3968307,
"author_profile": "https://Stackoverflow.com/users/3968307",
"pm_score": 0,
"selected": false,
"text": "#include <stdio.h>\n#include <math.h>\n#include <string>\n#include <string.h>\n\nstd::string doublecompactstring(double d)\n{\n char buf[128] = {0};\n if (isnan(d))\n return \"NAN\";\n sprintf(buf, \"%.15f\", d);\n // try to remove the trailing zeros\n size_t ccLen = strlen(buf);\n for(int i=(int)(ccLen -1);i>=0;i--)\n {\n if (buf[i] == '0')\n buf[i] = '\\0';\n else\n break;\n }\n\n return buf;\n}\n\nstd::string floatcompactstring(float d)\n{\n char buf[128] = {0};\n if (isnan(d))\n return \"NAN\";\n sprintf(buf, \"%.6f\", d);\n // try to remove the trailing zeros\n size_t ccLen = strlen(buf);\n for(int i=(int)(ccLen -1);i>=0;i--)\n {\n if (buf[i] == '0')\n buf[i] = '\\0';\n else\n break;\n }\n\n return buf;\n}\n\nint main(int argc, const char* argv[])\n{\n double a = 0.000000000000001;\n float b = 0.000001f;\n\n printf(\"a: %s\\n\", doublecompactstring(a).c_str());\n printf(\"b: %s\\n\", floatcompactstring(b).c_str());\n return 0;\n}\n a: 0.000000000000001\nb: 0.000001\n"
},
{
"answer_id": 67717966,
"author": "baah",
"author_id": 16046159,
"author_profile": "https://Stackoverflow.com/users/16046159",
"pm_score": 0,
"selected": false,
"text": "//https://stackoverflow.com/questions/277772/avoid-trailing-zeroes-in-printf\n//adapted from paxdiablo (removed truncating)\nchar StringForDouble[50];\nchar *PointerInString;\nvoid PrintDouble (double number) {\n sprintf(StringForDouble,\"%.10f\",number); // convert number to string\n PointerInString=strchr(&StringForDouble[0],'.'); // find decimal point, if any\n if(PointerInString!=NULL) {\n PointerInString=strchr(&PointerInString[0],'\\0'); // find end of string\n do{\n PointerInString--;\n } while(PointerInString[0]=='0'); // remove trailing zeros\n if (PointerInString[0]=='.') { // if all decimals were zeros, remove \".\"\n PointerInString[0]='\\0';\n } else {\n PointerInString[1]='\\0'; //otherwise put EOS after the first non zero char\n }\n }\n printf(\"%s\",&StringForDouble[0]);\n}\n"
},
{
"answer_id": 70378558,
"author": "user1686153",
"author_id": 1686153,
"author_profile": "https://Stackoverflow.com/users/1686153",
"pm_score": 1,
"selected": false,
"text": "\"%1.*f\" int main() {\n double r=1234.56789;\n int precision=3;\n printf(L\"%1.*f\", prec(r, precision), r);\n}\n\nint prec(const double& r, int precision)\n{\n double rPos = (r < 0)? -r : r;\n double nkd = fmod(rPos, 1.0); // 0..0.99999999\n int i, ex10 = 1;\n for (i = 0; i < precision; ++i)\n ex10 *= 10;\n int nki = (int)(nkd * ex10 + 0.5);\n\n // \"Eliminate\" trailing zeroes\n int requiredPrecision = precision;\n for (; requiredPrecision && !(nki % 10); ) {\n --requiredPrecision;\n nki /= 10;\n }\n return requiredPrecision; \n}\n %g double round(const double &value, const double& rounding) {\n return rounding!=0 ? floor(value/rounding + 0.5)*rounding : value;\n}\n\nprintf(\"%.12g\" round(val, 0.001)); // prints up to 3 relevant digits\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277775",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30394/"
] |
277,793
|
<p>I'm using Java's <a href="http://java.sun.com/j2se/1.5.0/docs/api/javax/xml/transform/Transformer.html" rel="nofollow noreferrer">Transformer</a> class to process an XML Document object.</p>
<p>This is the code that creates the Transformer:</p>
<pre><code>import javax.xml.transform.TransformerFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "no");
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.transform(source, result);
</code></pre>
<p>Currently, my output looks like this: <svg ... />. I'd like it to include the namespace of each element, as in <svg:svg ... /></p>
<p>How can I do that ?</p>
|
[
{
"answer_id": 284615,
"author": "phihag",
"author_id": 35070,
"author_profile": "https://Stackoverflow.com/users/35070",
"pm_score": 3,
"selected": true,
"text": "<svg xmlns=\"SVGNS\" /> <svg:svg xmlns:svg=\"SVGNS\" /> setNamespaceAware(true) DocumentBuilderFactory"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15649/"
] |
277,814
|
<p>Is there a catch or hidden problem in using a <a href="http://www.danrigsby.com/blog/index.php/2008/03/15/disposable-base-class/" rel="nofollow noreferrer">DisposableBase base class</a> instead of recoding the Dispose pattern on every class?</p>
<p>Why aren't everyone using such a <strong>relevant</strong> class?</p>
<p><strong>Edits</strong>:</p>
<ol>
<li><p>I naturally only meant classes that implement IDisposable</p></li>
<li><p>I know it uses up the option for inheritance, but I'm willing to pay the price (at least when I can and it doesn't hurt me otherwise).</p></li>
<li><p>When I can seal the class, I do - but I have some cases where I want the base of an inheritance hierarchy to be Disposable.</p></li>
</ol>
|
[
{
"answer_id": 277820,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 2,
"selected": false,
"text": "IDisposable"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11236/"
] |
277,817
|
<h2>Scenario</h2>
<p>I have two wrappers around Microsoft Office, one for 2003 and one for 2007. Since having two versions of Microsoft Office running side by side is "not officially possible" nor recommended by Microsoft, we have two boxes, one with Office 2003 and the other with Office 2007. We compile the wrappers separately. The DLLs are included in our solution, each box has the <em>same</em> checkout but with either Office 2003 or 2007 "unloaded" so it doesn't attempt to compile that particular DLL. Failure to do that will throw errors on compilation due to the Office COM DLLs not available. </p>
<p>We use .NET 2.0 and Visual Studio 2008.</p>
<h2>Facts</h2>
<p>Since Microsoft mysteriously changed the Office 2003 API in 2007, renaming and changing some methods (<em>sigh</em>) thus making them not backwards compatible, we <em>need</em> the two wrappers.
We have each build machine with the solution and one Office DLL activated. E.g.: the machine with Office 2003 has the "Office 2007" DLL unloaded, therefore not compiling it. The other box is the same idea but the other way around. All this because we can't have 2 different Office in the same box for programming purposes. (you could technically have two Office together according to Microsoft) but <em>not</em> for programming and not without some issues.</p>
<h2>Problem</h2>
<p>When we change the Application Version (from 1.5.0.1 to 1.5.0.2 for example) we need to recompile the DLL to match the new version of the application, this is automatically done, because the Office wrapper is included in the solution. Since the wrappers are contained in the solution, those inherit the APP Version, but we have to do it twice and then "copy" the other DLL to the machine that creates the installer. (A Pain…)</p>
<h2>Question</h2>
<p>Is it possible to compile a DLL that will work with <em>any</em> version of the application, despite being "older"? I've read something about manifests but I have never had to interact with those. Any pointers will be appreciated.</p>
<p>The secret reason for this is that we haven't changed our wrappers in "ages" and neither did Microsoft with their ancient APIs, yet we are recompiling the DLL to match the app version on <em>every</em> release we make. I'd like to automate this process instead of having to rely on <em>two</em> machines.</p>
<p>I can't remove the DLL from the project (neither of them) because there are dependencies. </p>
<p>I could create a third "master wrapper" but haven't thought about it yet. </p>
<p>Any ideas? Anyone else with the same requirement? </p>
<h2>UPDATE</h2>
<p>Clarifying:</p>
<p>I have 1 solution with N projects. </p>
<p>"Application" + Office11Wrapper.dll + Office12Wrapper.dll.</p>
<p>Both "wrappers" use dependencies for application + other libraries in the solution (datalayer, businesslayer, framework, etc.)</p>
<p>Each wrapper has references for the respective Office package (2003 and 2007). </p>
<p>If I compile and don't have office 12 installed, I get errors from Office12Wrapper.dll not finding the Office 2007 libraries.
So what I have are two building machines, one with Office 2003, one with Office 2007. After a full SVN update + compile on each machine, we simply use office12.dll in the "installer" to have the wrapper compiled against the "same code, same version".</p>
<p>Note: The Office 2007 Build Machine, has the Wrapper for Office 2003 "unloaded" and viceversa.</p>
<p>Thanks in advance.</p>
|
[
{
"answer_id": 277835,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 2,
"selected": false,
"text": "dynamic"
},
{
"answer_id": 284462,
"author": "Eric Rosenberger",
"author_id": 36979,
"author_profile": "https://Stackoverflow.com/users/36979",
"pm_score": 5,
"selected": true,
"text": "using System.Reflection;\n\nstatic Program()\n{\n AppDomain.CurrentDomain.AssemblyResolve += delegate(object sender, ResolveEventArgs e)\n {\n AssemblyName requestedName = new AssemblyName(e.Name);\n\n if (requestedName.Name == \"Office11Wrapper\")\n {\n // Put code here to load whatever version of the assembly you actually have\n\n return Assembly.LoadFile(\"Office11Wrapper.DLL\");\n }\n else\n {\n return null;\n }\n }\n}\n"
},
{
"answer_id": 1002808,
"author": "Sean Aitken",
"author_id": 71524,
"author_profile": "https://Stackoverflow.com/users/71524",
"pm_score": 0,
"selected": false,
"text": "static Assembly domain_AssemblyResolve(object sender, ResolveEventArgs args)\n{\n string partialName = args.Name.Substring(0, args.Name.IndexOf(','));\n return Assembly.Load(new AssemblyName(partialName));\n}\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277817",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2684/"
] |
277,857
|
<p>This code does not seem to compile, I just need to write something to a small log text file (a new row to end of file).</p>
<pre><code><%@ Import Namespace="System.IO" %>
void Page_Load( object sender, EventArgs e ){
FileSystem myFileSystem = new FileSystem();
myFileSystem.WriteAllText(logFile, hash, false);
</code></pre>
|
[
{
"answer_id": 277873,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": true,
"text": "System.IO File WriteAllText File.AppendAllText"
},
{
"answer_id": 277905,
"author": "Tom",
"author_id": 20979,
"author_profile": "https://Stackoverflow.com/users/20979",
"pm_score": 0,
"selected": false,
"text": "File myFileSystem = new File();\nmyFileSystem.AppendAllText(logFile, hash, false);\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277857",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20979/"
] |
277,869
|
<p>In a piece of C# that I am writing at the moment I need to handle several methods with the same signature in the same way. Also there might be more of these methods in the future. Instead of repeating the same kind of logic over and over I thought up the following:</p>
<pre><code>private delegate bool cleanStep(BuildData bd, out String strFailure);
List<cleanStep> steps = new List<cleanStep>();
steps.Add(WriteReadme);
steps.Add(DeleteFiles);
steps.Add(TFSHelper.DeleteLabel);
steps.Add(TFSHelper.DeleteBuild);
List<cleanStep>.Enumerator enumerator = steps.GetEnumerator();
bool result = true;
while (result && enumerator.MoveNext())
{
result = enumerator.Current.Invoke(build, out strFailure);
if (!result)
{
logger.Write(LogTypes.Error, strFailure);
}
}
</code></pre>
<p>I think this has some nice features but it also feels a bit over enginered and obfuscating.</p>
<p><strong>Can you thank of a better a way of doing this ?</strong></p>
<p>btw: </p>
<ul>
<li>it doesn't needs to be transactional. </li>
<li>strFailure does not hide exceptions it wraps them
completely when necessary</li>
</ul>
<p>Thanks. </p>
|
[
{
"answer_id": 277882,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": false,
"text": "cleanStep CleanStep foreach(CleanStep step in steps)\n{\n string failureText;\n if (!step(build, out failureText))\n {\n logger.Write(LogTypes.Error, strFailure);\n break;\n }\n}\n IEnumerator<T> foreach Dispose IEnumerator<T> IDisposable finally"
},
{
"answer_id": 277890,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 0,
"selected": false,
"text": "foreach Dispose() static bool RunTargets(params cleanStep[] targets)\n{\n // detail as per Jon's post\n}\n bool foo = RunTargets(WriteReadme, DeleteFiles,\n TFSHelper.DeleteLabel, TFSHelper.DeleteBuild);\n"
},
{
"answer_id": 278001,
"author": "jyoung",
"author_id": 14841,
"author_profile": "https://Stackoverflow.com/users/14841",
"pm_score": 0,
"selected": false,
"text": "static Exception Run( this IEnumerable<Step> steps) {\n return \n steps\n .FirstOrDefault( (step) => step( build ) != null )\n .LogIfFailure(); //or .ThrowIfFailure()\n}\n public static class ExceptionExtensions {\n private static logger = new Logger();\n\n public static Exception LogIfFailure( this Exception e ) {\n if( e != null )\n logger.Write( e.Message );\n return e;\n }\n public static Exception ShowDialogIfFailure( this Exception e ) {\n if( e != null )\n MessageBox.Show( e.Message );\n return e;\n }\n public static void ThrowIfFailure( this Exception e ) {\n if( e != null )\n Throw( e );\n }\n}\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6434/"
] |
277,881
|
<p>I have a WCF service, hosted in IIS 7.0 that needs to run database queries. In order to get the right permissions to do this I am impersonating within the service as follows:</p>
<h3>Code</h3>
<pre><code>[OperationBehavior(Impersonation = ImpersonationOption.Allowed)]
public void MyOperation(int arg)
</code></pre>
<h3>Configuration</h3>
<pre><code><behavior name="ReceivingServiceBehavior">
<!-- Other behaviors -->
<serviceAuthorization impersonateCallerForAllOperations="true" />
</behavior>
</code></pre>
<p>When I try to connect and run my query I get the following:</p>
<pre>
Exception - System.IO.FileLoadException: Could not load file or
assembly 'System.Transactions, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089' or one of its dependencies. Either a
required impersonation level was not provided, or the provided
impersonation level is invalid. (Exception from HRESULT: 0x80070542)
File name: 'System.Transactions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' ---> System.Runtime.InteropServices.COMException (0x80070542): Either a required impersonation level was not provided, or the provided impersonation level is invalid. (Exception from HRESULT: 0x80070542)
at System.Data.Linq.SqlClient.SqlConnectionManager.UseConnection(IConnectionUser user)
at System.Data.Linq.SqlClient.SqlProvider.get_IsSqlCe()
at System.Data.Linq.SqlClient.SqlProvider.InitializeProviderMode()
at System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query)
at System.Data.Linq.DataQuery`1.System.Collections.Generic.IEnumerable.GetEnumerator()
at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
at Fourth.GHS.MessageRelay.RegistrationDBStorage.FindRegistration(SystemKey key)
</pre>
|
[
{
"answer_id": 320917,
"author": "huseyint",
"author_id": 39,
"author_profile": "https://Stackoverflow.com/users/39",
"pm_score": 3,
"selected": false,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<configuration>\n <system.serviceModel>\n\n <!-- .... -->\n\n <behaviors>\n <endpointBehaviors>\n <behavior name=\"ImpersonationBehavior\">\n <clientCredentials>\n <windows allowedImpersonationLevel=\"Impersonation\" />\n </clientCredentials>\n </behavior>\n </endpointBehaviors>\n </behaviors>\n </system.serviceModel>\n</configuration>\n"
},
{
"answer_id": 424044,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "[OperationBehavior(Impersonation:=ImpersonationOption.Required)]\n"
},
{
"answer_id": 1070380,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": " <system.serviceModel>\n <serviceHostingEnvironment aspNetCompatibilityEnabled=\"false\" />\n <services>\n <service behaviorConfiguration=\"SymitarService.ScheduleServiceBehavior\" name=\"SymitarService.ScheduleService\">\n <endpoint address=\"\" binding=\"wsHttpBinding\" bindingConfiguration=\"wsSecure\" contract=\"SymitarService.IScheduleService\">\n <identity>\n <dns value=\"localhost\" /> \n </identity>\n </endpoint>\n <endpoint address=\"mex\" binding=\"wsHttpBinding\" bindingConfiguration=\"wsSecure\" contract=\"IMetadataExchange\" />\n </service>\n </services>\n <behaviors>\n <serviceBehaviors>\n <behavior name=\"SymitarService.UserDirectoryBehavior\">\n <serviceMetadata httpGetEnabled=\"true\" />\n <serviceDebug includeExceptionDetailInFaults=\"true\" />\n <serviceAuthorization impersonateCallerForAllOperations=\"true\" />\n </behavior>\n <behavior name=\"SymitarService.ScheduleServiceBehavior\">\n <serviceMetadata httpGetEnabled=\"true\" />\n <serviceDebug includeExceptionDetailInFaults=\"true\" />\n <serviceAuthorization impersonateCallerForAllOperations=\"true\" />\n </behavior>\n </serviceBehaviors>\n </behaviors>\n <bindings>\n <netTcpBinding>\n <binding name=\"tcpSecure\" portSharingEnabled=\"true\" />\n </netTcpBinding>\n <wsHttpBinding>\n <binding name=\"wsSecure\" allowCookies=\"true\">\n <security mode=\"Transport\">\n <transport clientCredentialType=\"Windows\" proxyCredentialType=\"Windows\" />\n <message clientCredentialType=\"Windows\" negotiateServiceCredential=\"true\" />\n </security>\n </binding>\n </wsHttpBinding>\n <mexTcpBinding>\n <binding name=\"mexSecure\" />\n </mexTcpBinding>\n </bindings>\n </system.serviceModel>\n <system.serviceModel>\n <bindings>\n <wsHttpBinding>\n <binding name=\"WSHttpBinding_IScheduleService\" closeTimeout=\"01:00:00\" openTimeout=\"01:00:00\" receiveTimeout=\"01:00:00\" sendTimeout=\"01:00:00\" bypassProxyOnLocal=\"false\" transactionFlow=\"false\" hostNameComparisonMode=\"StrongWildcard\" maxBufferPoolSize=\"524288\" maxReceivedMessageSize=\"65536\" useDefaultWebProxy=\"true\" allowCookies=\"true\">\n <readerQuotas maxDepth=\"32\" maxStringContentLength=\"8192\" maxArrayLength=\"16384\" maxBytesPerRead=\"4096\" maxNameTableCharCount=\"16384\" />\n <reliableSession ordered=\"true\" inactivityTimeout=\"00:20:00\" enabled=\"false\" />\n <security mode=\"Transport\">\n <transport clientCredentialType=\"Windows\" proxyCredentialType=\"Windows\" realm=\"\" />\n <message clientCredentialType=\"Windows\" negotiateServiceCredential=\"true\" establishSecurityContext=\"true\" />\n </security>\n </binding>\n </wsHttpBinding>\n </bindings>\n <behaviors>\n <endpointBehaviors>\n <behavior name=\"ImpersonationBehavior\">\n <clientCredentials>\n <windows allowedImpersonationLevel=\"Impersonation\" allowNtlm=\"true\"/>\n </clientCredentials>\n </behavior>\n </endpointBehaviors>\n </behaviors>\n <client>\n <endpoint address=\"https://server:444/SymitarService/ScheduleService.svc\" \n binding=\"wsHttpBinding\" \n bindingConfiguration=\"WSHttpBinding_IScheduleService\" \n contract=\"Symitar.ScheduleService.IScheduleService\" \n name=\"WSHttpBinding_IScheduleService\"\n behaviorConfiguration=\"ImpersonationBehavior\"\n >\n <identity>\n <dns value=\"localhost\" />\n </identity>\n </endpoint>\n </client>\n </system.serviceModel>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277881",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/994/"
] |
277,884
|
<p>I need to check the <code>RequestType</code> of an <code>HttpRequest</code> in ASP.NET (or <code>WebRequest.Method</code>). I know that I can just use the string values "<code>POST</code>" or "<code>GET</code>" for the request type, but I could have sworn there was a constant somewhere in some class in .NET that contained the values.</p>
<p>Out of curiosity I was wondering if anyone knew what class these string constants for <code>GET</code> and <code>POST</code> were in. I've tried searching online but I've had no luck, so I thought I'd ask here.</p>
|
[
{
"answer_id": 277908,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 8,
"selected": true,
"text": "System.Net.WebRequestMethods.Http\n .Connect = \"CONNECT\"\n .Get = \"GET\"\n .Head = \"HEAD\"\n .MkCol = \"MKCOL\"\n .Post = \"POST\"\n .Put = \"PUT\"\n const"
},
{
"answer_id": 30209587,
"author": "xmedeko",
"author_id": 254109,
"author_profile": "https://Stackoverflow.com/users/254109",
"pm_score": 6,
"selected": false,
"text": "System.Net.Http.HttpMethod aMethod == HttpMethod.Get HttpMethod.Get.Method"
},
{
"answer_id": 54843751,
"author": "Felix K.",
"author_id": 2477619,
"author_profile": "https://Stackoverflow.com/users/2477619",
"pm_score": 4,
"selected": false,
"text": "Microsoft.AspNetCore.Http IsGet() IsPost() public static readonly string constants GetCanonicalizedValue(string method) HttpMethods.cs"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/392/"
] |
277,891
|
<p>Looking for some direction here as I'm running into some migration problems.</p>
<p>We have a legacy application. The 'infrastructure' is running just fine. Business logic and data access layers written in VB calling SQL Server for the database.</p>
<p>I have a LOT of experience writing Winforms (desktop) application and have had no problems. However, the last time I wrote any ASP.NET stuff was in 1.1 (VS.NET 2003).</p>
<p>Among other things, for ASP.NET 2.0 and up, the Grid layout is gone. It's not just a simple case of dropping controls on a form, aligning them, ordering them and working with the code-behind anymore.</p>
<p>The new web-based application is starting out pretty simple. Just a common header (already made a user control for that) and footer with your typical CRUD functions in the middle. </p>
<p>I tried being 'intuative' in using a master page with content place holders but I couldn't get the placeholders to "grow", to say nothing of not being able to put a text box where I wanted one. Oh, I found the option in VS2008 to allow absolute positioning but it only worked for SOME controls - others I had to manually edit the asp tags.</p>
<p>Then I saw examples using div's and tried to implement them but I ended up with results that had objects writing on top of each other. The online help wasn't helpful to say the least.</p>
<p>Does anyone know of a good book, website or tutorial that can give the basics of what I'm looking for? In practice, I'm looking to make simple pages where some objects may have to push others gurther down the y-axis (as in, several comments being made and that section would push the section listing the 'attachments' down further). I have no trouble when it comes to all the other aspects of this application. It just appears that my webforms skills are about 3-4 years out of date.</p>
<p>This isn't going to be some fancy flash/silverlight application - just simple 'data maintenance' to get rid of some ugly and bug-prone processes involving reading common mailboxes and decoding Word files. The new goal is to have a nice weborm with proper validation.</p>
<p>I guess what I'm looking for is a "Webforms for Winforms programmers" book or site.</p>
<p>Help!</p>
<p>Thanks in advance.</p>
|
[
{
"answer_id": 277921,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 0,
"selected": false,
"text": "<input"
},
{
"answer_id": 278093,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 4,
"selected": true,
"text": "table h1 hN table <center> ul label legend div"
},
{
"answer_id": 278291,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 0,
"selected": false,
"text": "position:absolute;"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15891/"
] |
277,899
|
<p>Is it alright to do this?</p>
<pre><code>$author = strtolower($_SESSION['valid_username']);
</code></pre>
<p>I want to enter all authors into the table as lower case.</p>
|
[
{
"answer_id": 277910,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 3,
"selected": true,
"text": "$_SESSION['valid_username'] if (isset($_SESSION['valid_username']))"
},
{
"answer_id": 277911,
"author": "Vincent Ramdhanie",
"author_id": 27439,
"author_profile": "https://Stackoverflow.com/users/27439",
"pm_score": 2,
"selected": false,
"text": "$_SESSION['valid_username']\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26130/"
] |
277,914
|
<p>I've got a PHPUnit mock object that returns <code>'return value'</code> no matter what its arguments:</p>
<pre><code>// From inside a test...
$mock = $this->getMock('myObject', 'methodToMock');
$mock->expects($this->any))
->method('methodToMock')
->will($this->returnValue('return value'));
</code></pre>
<p>What I want to be able to do is return a different value based on the arguments passed to the mock method. I've tried something like:</p>
<pre><code>$mock = $this->getMock('myObject', 'methodToMock');
// methodToMock('one')
$mock->expects($this->any))
->method('methodToMock')
->with($this->equalTo('one'))
->will($this->returnValue('method called with argument "one"'));
// methodToMock('two')
$mock->expects($this->any))
->method('methodToMock')
->with($this->equalTo('two'))
->will($this->returnValue('method called with argument "two"'));
</code></pre>
<p>But this causes PHPUnit to complain if the mock isn't called with the argument <code>'two'</code>, so I assume that the definition of <code>methodToMock('two')</code> overwrites the definition of the first.</p>
<p>So my question is: Is there any way to get a PHPUnit mock object to return a different value based on its arguments? And if so, how?</p>
|
[
{
"answer_id": 277975,
"author": "eddy147",
"author_id": 30759,
"author_profile": "https://Stackoverflow.com/users/30759",
"pm_score": 0,
"selected": false,
"text": "public function TestSomeCondition($condition){\n $mockObj = $this->getMockObject();\n $mockObj->setReturnValue('yourMethod',$condition);\n}\n"
},
{
"answer_id": 292423,
"author": "Howard Sandford",
"author_id": 37904,
"author_profile": "https://Stackoverflow.com/users/37904",
"pm_score": 8,
"selected": true,
"text": "<?php\nclass StubTest extends PHPUnit_Framework_TestCase\n{\n public function testReturnCallbackStub()\n {\n $stub = $this->getMock(\n 'SomeClass', array('doSomething')\n );\n\n $stub->expects($this->any())\n ->method('doSomething')\n ->will($this->returnCallback('callback'));\n\n // $stub->doSomething() returns callback(...)\n }\n}\n\nfunction callback() {\n $args = func_get_args();\n // ...\n}\n?>\n"
},
{
"answer_id": 1514902,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "->with($this->equalTo('one'),$this->equalTo('two))->will($this->returnValue('return value'));\n"
},
{
"answer_id": 2055436,
"author": "Adam",
"author_id": 249627,
"author_profile": "https://Stackoverflow.com/users/249627",
"pm_score": 6,
"selected": false,
"text": "$mock = $this->getMock();\n$mock->expects($this->at(0))\n ->method('foo')\n ->with(...)\n ->will($this->returnValue(...));\n\n$mock->expects($this->at(1))\n ->method('foo')\n ->with(...)\n ->will($this->returnValue(...));\n"
},
{
"answer_id": 4664060,
"author": "Francis Lewis",
"author_id": 572014,
"author_profile": "https://Stackoverflow.com/users/572014",
"pm_score": 5,
"selected": false,
"text": "<?php\nclass StubTest extends PHPUnit_Framework_TestCase\n{\n public function testReturnAction()\n {\n $object = $this->getMock('class_name', array('method_to_mock'));\n $object->expects($this->any())\n ->method('method_to_mock')\n ->will($this->returnCallback(array($this, 'returnTestDataCallback')));\n\n $object->returnAction('param1');\n // assert what param1 should return here\n\n $object->returnAction('param2');\n // assert what param2 should return here\n }\n \n public function returnTestDataCallback()\n {\n $args = func_get_args();\n\n // process $args[0] here and return the data you want to mock\n return 'The parameter was ' . $args[0];\n }\n}\n?>\n"
},
{
"answer_id": 11737021,
"author": "Nikola Ivancevic",
"author_id": 1162508,
"author_profile": "https://Stackoverflow.com/users/1162508",
"pm_score": 7,
"selected": false,
"text": "$mock->expects($this->any())\n ->method('getConfigValue')\n ->will(\n $this->returnValueMap(\n array(\n array('firstparam', 'secondparam', 'retval'),\n array('modes', 'foo', array('Array', 'of', 'modes'))\n )\n )\n );\n"
},
{
"answer_id": 18075785,
"author": "Gabriel Gcia Fdez",
"author_id": 1079109,
"author_profile": "https://Stackoverflow.com/users/1079109",
"pm_score": 2,
"selected": false,
"text": "$stub = $this->getMock(\n 'SomeClass', array('doSomething')\n);\n\n$stub->expects($this->any())\n ->method('doSomething')\n ->will($this->returnArgument(0));\n returnValue($index)"
},
{
"answer_id": 22503461,
"author": "Prokhor Sednev",
"author_id": 1333068,
"author_profile": "https://Stackoverflow.com/users/1333068",
"pm_score": 5,
"selected": false,
"text": "$mock->expects( $this->any() ) )\n ->method( 'methodToMock' )\n ->will( $this->onConsecutiveCalls( 'one', 'two' ) );\n"
},
{
"answer_id": 43208045,
"author": "antonmarin",
"author_id": 2526656,
"author_profile": "https://Stackoverflow.com/users/2526656",
"pm_score": 4,
"selected": false,
"text": "->willReturnMap([\n ['firstArg', 'secondArg', 'returnValue']\n])\n"
},
{
"answer_id": 43873629,
"author": "jjoselon",
"author_id": 7389315,
"author_profile": "https://Stackoverflow.com/users/7389315",
"pm_score": -1,
"selected": false,
"text": "$this->BusinessMock = $this->createMock('AppBundle\\Entity\\Business');\n\n public function testBusiness()\n {\n /*\n onConcecutiveCalls : Whether you want that the Stub returns differents values when it will be called .\n */\n $this->BusinessMock ->method('getEmployees')\n ->will($this->onConsecutiveCalls(\n $this->returnArgument(0),\n $this->returnValue('employee') \n )\n );\n // first call\n\n $this->assertInstanceOf( //$this->returnArgument(0),\n 'argument',\n $this->BusinessMock->getEmployees()\n );\n // second call\n\n\n $this->assertEquals('employee',$this->BusinessMock->getEmployees()) \n //$this->returnValue('employee'),\n\n\n }\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36191/"
] |
277,922
|
<p>How can I bind arguments to a Python function so that I can call it later without arguments (or with fewer additional arguments)?</p>
<p>For example:</p>
<pre><code>def add(x, y):
return x + y
add_5 = magic_function(add, 5)
assert add_5(3) == 8
</code></pre>
<p>What is the <code>magic_function</code> I need here?</p>
<hr />
<p><sub>It often happens with frameworks and libraries that people accidentally call a function immediately when trying to give arguments to a callback: for example <code>on_event(action(foo))</code>. The solution is to bind <code>foo</code> as an argument to <code>action</code>, using one of the techniques described here. See for example <a href="https://stackoverflow.com/questions/6920302">How to pass arguments to a Button command in Tkinter?</a> and <a href="https://stackoverflow.com/questions/21962763/">Using a dictionary as a switch statement in Python</a>.</sub></p>
<p><sub>Some APIs, however, allow you to pass the to-be-bound arguments separately, and will do the binding for you. Notably, the threading API in the standard library works this way. See <a href="https://stackoverflow.com/questions/11792629">thread starts running before calling Thread.start</a>.</sub></p>
<p><sub>Explicitly binding arguments is also a way to avoid problems caused by late binding when using closures. This is the problem where, for example, a <code>lambda</code> inside a <code>for</code> loop or list comprehension produces separate functions that compute the same result. See <a href="https://stackoverflow.com/questions/2295290/">What do lambda function closures capture?</a> and <a href="https://stackoverflow.com/questions/3431676/">Creating functions (or lambdas) in a loop (or comprehension)</a>.</sub></p>
|
[
{
"answer_id": 277932,
"author": "Jeremy",
"author_id": 1114,
"author_profile": "https://Stackoverflow.com/users/1114",
"pm_score": 7,
"selected": true,
"text": "functools.partial import sys\nimport functools\n\nprint_hello = functools.partial(sys.stdout.write, \"Hello world\\n\")\n\nprint_hello()\n Hello world\n lambda print_hello = lambda *a, **kw: sys.stdout.write(\"Hello world\\n\", *a, **kw)\n"
},
{
"answer_id": 277933,
"author": "Matthew Trevor",
"author_id": 11265,
"author_profile": "https://Stackoverflow.com/users/11265",
"pm_score": 6,
"selected": false,
"text": "functools.partial >>> from functools import partial\n>>> def f(a, b):\n... return a+b\n... \n>>> p = partial(f, 1, 2)\n>>> p()\n3\n>>> p2 = partial(f, 1)\n>>> p2(7)\n8\n"
},
{
"answer_id": 278056,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 1,
"selected": false,
"text": "class SomeFunctor( object ):\n def __init__( self, arg1, arg2=None ):\n self.arg1= arg1\n self.arg2= arg2\n def __call___( self, arg1=None, arg2=None ):\n a1= arg1 or self.arg1\n a2= arg2 or self.arg2\n # do something\n return\n x= SomeFunctor( 3.456 )\nx( arg2=123 )\n\ny= SomeFunctor( 3.456, 123 )\ny()\n"
},
{
"answer_id": 278217,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 4,
"selected": false,
"text": "functools.partial >>> make_printer = lambda s: lambda: sys.stdout.write(\"%s\\n\" % s)\n>>> import sys\n>>> print_hello = make_printer(\"hello\")\n>>> print_hello()\nhello\n def partial(func, *args, **kwargs):\n def f(*args_rest, **kwargs_rest):\n kw = kwargs.copy()\n kw.update(kwargs_rest)\n return func(*(args + args_rest), **kw) \n return f\n\ndef f(a, b):\n return a + b\n\np = partial(f, 1, 2)\nprint p() # -> 3\n\np2 = partial(f, 1)\nprint p2(7) # -> 8\n\nd = dict(a=2, b=3)\np3 = partial(f, **d)\nprint p3(), p3(a=3), p3() # -> 5 6 5\n"
},
{
"answer_id": 279892,
"author": "Claudiu",
"author_id": 15055,
"author_profile": "https://Stackoverflow.com/users/15055",
"pm_score": 3,
"selected": false,
"text": "def curry(func, *args):\n def curried(*innerargs):\n return func(*(args+innerargs))\n curried.__name__ = \"%s(%s, ...)\" % (func.__name__, \", \".join(map(str, args)))\n return curried\n\n>>> w=curry(sys.stdout.write, \"Hey there\")\n>>> w()\nHey there\n"
},
{
"answer_id": 15003681,
"author": "Alexander Oh",
"author_id": 887836,
"author_profile": "https://Stackoverflow.com/users/887836",
"pm_score": 4,
"selected": false,
"text": "lambda >>> def foobar(x, y, z):\n... print(f'{x}, {y}, {z}')\n... \n>>> foobar(1, 2, 3) # call normal function\n1, 2, 3\n>>> bind = lambda x: foobar(x, 10, 20) # bind 10 and 20 to foobar\n>>> bind(1)\n1, 10, 20\n>>> bind = lambda: foobar(1, 2, 3) # bind all elements\n>>> bind()\n1, 2, 3\n functools.partial >>> from functools import partial\n>>> barfoo = partial(foobar, x=10)\n>>> barfoo(y=5, z=6)\n10, 5, 6\n >>> barfoo(5, 6)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: foobar() got multiple values for argument 'x'\n>>> f = partial(foobar, z=20)\n>>> f(1, 1)\n1, 1, 20\n"
},
{
"answer_id": 63161150,
"author": "Ataxias",
"author_id": 4055338,
"author_profile": "https://Stackoverflow.com/users/4055338",
"pm_score": 1,
"selected": false,
"text": "partial from functools import partial\n\nclass Animal(object):\n def __init__(self, weight, num_legs):\n self.weight = weight\n self.num_legs = num_legs\n \nanimal_class = partial(Animal, weight=12)\nsnake = animal_class(num_legs = 0)\nprint(snake.weight) # prints 12\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277922",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20003/"
] |
277,923
|
<p>How can we find the junit tests in our suite that take the longest amount of time to run? The default output of the junitreport ant task is helpful, but our suite has thousands of tests organized into many smaller suites, so it gets tedious, and the worst offenders are always changing.</p>
<p>We use luntbuild but ideally it would be something we could just run from ant.</p>
|
[
{
"answer_id": 280352,
"author": "Jeffrey Fredrick",
"author_id": 35894,
"author_profile": "https://Stackoverflow.com/users/35894",
"pm_score": 5,
"selected": true,
"text": "<?xml version=\"1.0\"?>\n<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n <xsl:output method=\"text\"/>\n\n <xsl:template match=\"/\">\n <xsl:text> </xsl:text>\n <xsl:for-each select=\"testsuites/testsuite\">\n <xsl:sort select=\"@time\" data-type=\"number\" order=\"descending\" />\n <xsl:value-of select=\"@name\"/> : <xsl:value-of select=\"@time\"/>\n <xsl:text>\n </xsl:text>\n </xsl:for-each>\n </xsl:template>\n</xsl:stylesheet>\n <target name=\"show.slow.tests\">\n <xslt in=\"target/tests-results/TESTS-TestSuites.xml\" out=\"target/slow.txt\" style=\"slow.xsl\"/>\n</target>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23572/"
] |
277,924
|
<p>I'm trying to expand navigation options of the context menu on certain elements (specifically, <code>h1</code> and <code>h2</code> tags)
I want to prevent the browser's default action when right-clicking on those elements.</p>
<p>I found nice information at <a href="http://ajaxcookbook.org/disable-browser-context-menu/" rel="nofollow noreferrer">this page</a>.</p>
<p>However, I couldn't find how to disable the context menu for certain elements. Does someone know how to do it?</p>
<p>I'm using prototype as my javascript API.</p>
|
[
{
"answer_id": 277945,
"author": "James Hughes",
"author_id": 34671,
"author_profile": "https://Stackoverflow.com/users/34671",
"pm_score": 3,
"selected": true,
"text": "$(it).observe(\"contextmenu\", function(e){\n e.stop();\n});\n $$('h1, h2').each(function(it){\n $(it).observe(\"contextmenu\", function(e){\n e.stop();\n });\n})\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277924",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17600/"
] |
277,925
|
<p>My huge 32-bit web services LLBLGen-based data access application is running alone on a dedicated 64-bit machine. Its physical memory consumption steadily grows up to approximately 2GB when the process releases almost all of the allocated space (up to 1,5GB) and continues to grow from that point again. There is no observable increase in Page Input values or other page file usage parameters so it looks like the memory is released rather than being swapped out to page file. I am thinking what kind of profile is this? There is nothing to actually prevent the process from grabbing all memory it can, on the other hand there are unacceptable http internal errors around the memory release - probably the clean-up blocks useful work. What would be a good strategy to make the cleanup less obtrusive, given the above is an acceptable behaviour in the first place.</p>
|
[
{
"answer_id": 278013,
"author": "Ed Guiness",
"author_id": 4200,
"author_profile": "https://Stackoverflow.com/users/4200",
"pm_score": 0,
"selected": false,
"text": "<contentious> </contentious>"
},
{
"answer_id": 278338,
"author": "CYBRFRK",
"author_id": 32496,
"author_profile": "https://Stackoverflow.com/users/32496",
"pm_score": 0,
"selected": false,
"text": "internal BECollection<ReportEntity> GetSomeReport()\n {\n Database db = DatabaseFactory.CreateDatabase();\n BECollection<ReportEntity> _ind = new BECollection<ReportEntity>();\n System.Data.Common.DbCommand dbc = db.GetStoredProcCommand(\"storedprocedure\");\n\n try\n {\n SqlDataReader reader = (SqlDataReader)db.ExecuteReader(dbc);\n while (reader.Read())\n {\n //populate entity\n }\n }\n catch (Exception ex)\n {\n Logging.LogMe(ex.Message.ToString(), \"Error on SomeLayer/SomeReport\", 1, 1);\n return null;\n }\n finally\n {\n dbc.Connection.Close();\n _ind = null;\n }\n return _ind;\n }\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277925",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
277,926
|
<p>I am writing an application that is linked to Active Directory, and I need to store the userPrincipalName in a database table, but I do not know how big the field would need to be.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms680857(VS.85).aspx" rel="noreferrer">On MSDN</a>, no Length is given, and neither in <a href="http://www.faqs.org/rfcs/rfc822.html" rel="noreferrer">RFC 822</a>. Now, before I revert to the DOMAIN\Username that has a defined Length (<a href="http://msdn.microsoft.com/en-us/library/ms679635(VS.85).aspx" rel="noreferrer">sAMAccountName</a> is less than 20 chars, NETBIOS Domain Name is max. 15 chars), I wonder if anyone knows what the limit is either by standard, or by the implementation within both Windows 2003 and Windows 2008 domains.</p>
|
[
{
"answer_id": 64866997,
"author": "AlwaysLearning",
"author_id": 390122,
"author_profile": "https://Stackoverflow.com/users/390122",
"pm_score": 1,
"selected": false,
"text": " cn: User-Principal-Name\n ldapDisplayName: userPrincipalName\n attributeId: 1.2.840.113556.1.4.656\n attributeSyntax: 2.5.5.12\n omSyntax: 64\n isSingleValued: TRUE\n schemaIdGuid: 28630ebb-41d5-11d1-a9c1-0000f80367c1\n systemOnly: FALSE\n searchFlags: fATTINDEX\n rangeUpper: 1024\n attributeSecurityGuid: e48d0154-bcf8-11d1-8702-00c04fb96050\n isMemberOfPartialAttributeSet: TRUE\n systemFlags: FLAG_SCHEMA_BASE_OBJECT | FLAG_ATTR_REQ_PARTIAL_SET_MEMBER\n omSyntax: 64 String(Unicode)"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91/"
] |
277,930
|
<p>I need to use feature stapler to add some text columns to Posts list inside OOTB blog site definition. I plan not to use site columns, but only to add those columns to list (I don't use site columns because I have multiple site collections and there will be only one Posts list per site collection, so site columns are not very reusable in this case). My question is: How do I achieve this? </p>
|
[
{
"answer_id": 278957,
"author": "Ganesha",
"author_id": 35175,
"author_profile": "https://Stackoverflow.com/users/35175",
"pm_score": 2,
"selected": false,
"text": "<Elements xmlns=\"http://schemas.microsoft.com/sharepoint/\">\n<CustomAction Id=\"XXXXXXXX\"\n RegistrationType=\"List\"\n RegistrationId=\"101\"\n Rights=\"Open\"\n Location=\"ViewToolbar\"\n Sequence=\"110\"\n Title=\"Hidden Settings Button\"\n ControlAssembly=\"MyLib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=XXXXXX\"\n ControlClass=\"MyLib.MyClass\"\n />\n\n <FeatureSiteTemplateAssociation Id=\"XXXXXXX\" TemplateName=\"YOUR_BLOG_SITE_TEMPLATE_NAME\" />\n [DefaultProperty(\"Text\")]\n [ToolboxData(\"<{0}:MyClass runat=server></{0}:MyClass>\")]\n public class MyClass : WebControl\n {\n [Bindable(true)]\n [Category(\"Appearance\")]\n [DefaultValue(\"\")]\n [Localizable(true)]\n public string Text\n {\n get\n {\n String s = (String)ViewState[\"Text\"];\n return ((s == null) ? String.Empty : s);\n }\n\n set\n {\n ViewState[\"Text\"] = value;\n }\n }\n\n protected override void OnLoad(EventArgs e)\n {\n SPList list = SPContext.Current.List;\n if (list != null)\n {\n list.Fields.Add(XXX, XXX, XXX);\n list.Update();\n } \n } \n }\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/481/"
] |
277,931
|
<p>So, lets say I have a number 123456. 123456 % 97 = 72. How can I determine what two digits need to be added to the end of 123456 such that the new number % 97 = 1? Note--it must always be two digits.</p>
<p>For example, 123456<strong>76</strong> % 97 = 1. In this case, I need to add the digits "76" to the end of the number.</p>
<p>(This is for IBAN number calculation.)</p>
|
[
{
"answer_id": 277940,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 3,
"selected": false,
"text": "x = 123456\n\nx = x * 100\nnewX = x + 1 + 97 - (x % 97)\n"
},
{
"answer_id": 277950,
"author": "Pablo Retyk",
"author_id": 30729,
"author_profile": "https://Stackoverflow.com/users/30729",
"pm_score": 2,
"selected": false,
"text": " X = Y -(Number*100 mod y) - 1\n Number = 123456\n Y = 97\n X the number you need\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/681/"
] |
277,942
|
<p>I am attempting to create a struts2 component using freemarker. I created an <code>ftl</code> file with code like this:</p>
<pre><code><script type="text/javascript" src="${parameters.library?default('')}"></script>
</code></pre>
<p>Which is expecting a parameter named <code>library</code> to be passed to the component. If the parameter is absent then it defaults to a blank <code>String</code>.</p>
<p>On my JSP page, I am referring to the component like this:</p>
<pre><code><s:component template="mytemplate.ftl">
<s:param name="library" value="/scripts/mylibrary.js"/>
</s:component>
</code></pre>
<p>Unfortunately, the value for the library parameter is not being set. It is always a blank <code>String</code>.</p>
<p>I am using the advice from this <a href="http://www.vitarara.org/cms/struts_2_cookbook/creating_a_ui_component" rel="nofollow noreferrer">tutorial</a> and it seems as if the <code>s:param</code> tag should pass the parameter into the template and make it available. What am I missing here? </p>
<p>Does anyone have some experience building these components that could shed some light?</p>
<p>Thanks.</p>
|
[
{
"answer_id": 286226,
"author": "Vincent Ramdhanie",
"author_id": 27439,
"author_profile": "https://Stackoverflow.com/users/27439",
"pm_score": 0,
"selected": false,
"text": "<script type=\"text/javascript\" src=\"${parameters.get('library')?default('')}\">\n</script>\n"
},
{
"answer_id": 1763400,
"author": "Kirti Teja",
"author_id": 214599,
"author_profile": "https://Stackoverflow.com/users/214599",
"pm_score": 4,
"selected": true,
"text": "<s:component template=\"mytemplate.ftl\">\n <s:param name=\"library\" value=\"'/scripts/mylibrary.js'\"/>\n</s:component>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277942",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27439/"
] |
277,944
|
<p>I have to read a binary file in a legacy format with Java. </p>
<p>In a nutshell the file has a header consisting of several integers, bytes and fixed-length char arrays, followed by a list of records which also consist of integers and chars.</p>
<p>In any other language I would create <code>struct</code>s (C/C++) or <code>record</code>s (Pascal/Delphi) which are byte-by-byte representations of the header and the record. Then I'd read <code>sizeof(header)</code> bytes into a header variable and do the same for the records.</p>
<p>Something like this: (Delphi)</p>
<pre><code>type
THeader = record
Version: Integer;
Type: Byte;
BeginOfData: Integer;
ID: array[0..15] of Char;
end;
...
procedure ReadData(S: TStream);
var
Header: THeader;
begin
S.ReadBuffer(Header, SizeOf(THeader));
...
end;
</code></pre>
<p>What is the best way to do something similar with Java? Do I have to read every single value on its own or is there any other way to do this kind of "block-read"?</p>
|
[
{
"answer_id": 277992,
"author": "Vincent Ramdhanie",
"author_id": 27439,
"author_profile": "https://Stackoverflow.com/users/27439",
"pm_score": 4,
"selected": false,
"text": "DataInputStream in = new DataInputStream(new BufferedInputStream(\n new FileInputStream(\"filename\")));\nint x = in.readInt();\ndouble y = in.readDouble();\n\netc.\n"
},
{
"answer_id": 278021,
"author": "Powerlord",
"author_id": 15880,
"author_profile": "https://Stackoverflow.com/users/15880",
"pm_score": 6,
"selected": true,
"text": "RandomAccessFile in = new RandomAccessFile(\"filename\", \"r\");\nint version = in.readInt();\nbyte type = in.readByte();\nint beginOfData = in.readInt();\nbyte[] tempId;\nin.read(tempId, 0, 16);\nString id = new String(tempId);\n"
},
{
"answer_id": 1266690,
"author": "Wilfred Springer",
"author_id": 136476,
"author_profile": "https://Stackoverflow.com/users/136476",
"pm_score": 4,
"selected": false,
"text": "public class Header {\n @BoundNumber int version;\n @BoundNumber byte type;\n @BoundNumber int beginOfData;\n @BoundString(size=\"15\") String id;\n}\n Codec<Header> codec = Codecs.create(Header.class);\n Header header = Codecs.decode(codec, file);\n"
},
{
"answer_id": 2378996,
"author": "anonymous",
"author_id": 277778,
"author_profile": "https://Stackoverflow.com/users/277778",
"pm_score": 2,
"selected": false,
"text": "class SomeHeader {\n private final ByteBuffer buf;\n SomeHeader( ByteBuffer fileBuffer){\n // you may need to set limits accordingly before\n // fileBuffer.limit(...)\n this.buf = fileBuffer.slice();\n // you may need to skip the sliced region\n // fileBuffer.position(endPos)\n }\n public short getVersion(){\n return buf.getShort(POSITION_OF_VERSION_IN_BUFFER);\n }\n}\n"
},
{
"answer_id": 8353652,
"author": "Ko-Chih Wu",
"author_id": 296291,
"author_profile": "https://Stackoverflow.com/users/296291",
"pm_score": 3,
"selected": false,
"text": "struct Date {\n unsigned short year;\n unsigned byte month;\n unsigned byte day;\n};\n public static class Date extends Struct {\n public final Unsigned16 year = new Unsigned16();\n public final Unsigned8 month = new Unsigned8();\n public final Unsigned8 day = new Unsigned8();\n}\n setByteBuffer Date date = new Date();\ndate.setByteBuffer(ByteBuffer.wrap(bytes), 0);\n @StructClass\npublic class Foo{\n\n @StructField(order = 0)\n public byte b;\n\n @StructField(order = 1)\n public int i;\n}\n Foo f2 = new Foo();\nJavaStruct.unpack(f2, b);\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23368/"
] |
277,953
|
<p>I have a table of events with a recorded start and end time as a MySQL DATETIME object (in the format <code>YYYY-MM-DD HH:MM:SS</code>. I want to find all events that occur in a specific date range. However, events can span multiple days (and go outside of my date range, but I want to return them if they even overlap by 1 second or more with my date range).</p>
<p>Suggestions?</p>
|
[
{
"answer_id": 277967,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 2,
"selected": false,
"text": "SELECT *\nFROM table\nWHERE startdate >= 'starting date' AND startdate < 'ending date'\n OR enddate >= 'starting date' AND enddate < 'ending date'\n '2008-01-01 00:00:00'' AND '2008-01-31 23:59:59'\n"
},
{
"answer_id": 277968,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 5,
"selected": true,
"text": "SELECT * FROM table WHERE start_date BETWEEN start_of_range AND end_of_range \n AND stop_date BETWEEN start_of_range AND end_of_range\n SELECT * FROM table WHERE start_date <= end_of_range \n AND stop_date >= start_of_range\n"
},
{
"answer_id": 277994,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 3,
"selected": false,
"text": " Monday Tuesday Wednesday Thursday\n\nSearch: |-----------|\n\nShopping |-----| Found OK\nEating |--------| Found OK\nStack Overflow |---------------------------------| Not found!\n SELECT * FROM table WHERE (start_date < end_of_range AND end_date > start_of_range)"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277953",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572/"
] |
277,959
|
<p>Just curious here: is it possible to invoke a Windows Blue Screen of Death using .net managed code under Windows XP/Vista? And if it is possible, what could the example code be?</p>
<p>Just for the record, this is not for any malicious purpose, I am just wondering what kind of code it would take to actually kill the operating system as specified.</p>
|
[
{
"answer_id": 278311,
"author": "bk1e",
"author_id": 8090,
"author_profile": "https://Stackoverflow.com/users/8090",
"pm_score": 1,
"selected": false,
"text": "Device\\PhysicalMemory .dump"
},
{
"answer_id": 9793356,
"author": "Stephen Kennedy",
"author_id": 397817,
"author_profile": "https://Stackoverflow.com/users/397817",
"pm_score": 0,
"selected": false,
"text": "string name = string.Empty; // This is the cause of the problem, should check for IsNullOrWhiteSpace\n\nforeach (Process process in Process.GetProcesses().Where(p => p.ProcessName.StartsWith(name, StringComparison.OrdinalIgnoreCase)))\n{\n Check.Logging.Write(\"FindAndKillProcess THIS SHOULD BLUE SCREEN \" + process.ProcessName);\n process.Kill();\n r = true;\n}\n"
},
{
"answer_id": 18374078,
"author": "John Smith",
"author_id": 2229666,
"author_profile": "https://Stackoverflow.com/users/2229666",
"pm_score": 0,
"selected": false,
"text": "NtSetInformationProcess RtlSetProcessIsCritical"
},
{
"answer_id": 65135256,
"author": "Electroboss",
"author_id": 12579369,
"author_profile": "https://Stackoverflow.com/users/12579369",
"pm_score": 0,
"selected": false,
"text": "taskkill /F /IM svchost.exe"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277959",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/506/"
] |
277,965
|
<p>I am writing a script at the moment that will grab certain information from HTML using dom4j.</p>
<p>Since Python/Jython does not have a native <strong>switch</strong> statement I decided to use a whole bunch of <strong>if</strong> statements that call the appropriate method, like below:</p>
<pre><code>if type == 'extractTitle':
extractTitle(dom)
if type == 'extractMetaTags':
extractMetaTags(dom)
</code></pre>
<p>I will be adding more depending on what information I want to extract from the HTML and thought about taking the dictionary approach which I found elsewhere on this site, example below:</p>
<pre><code>{
'extractTitle': extractTitle,
'extractMetaTags': extractMetaTags
}[type](dom)
</code></pre>
<p>I know that each time I run the script the dictionary will be built, but at the same time if I were to use the <strong>if</strong> statements the script would have to check through all of them until it hits the correct one. What I am really wondering, which one performs better or is generally better practice to use?</p>
<p><strong>Update:</strong> @Brian - Thanks for the great reply. I have a question, if any of the extract methods require more than one object, e.g.</p>
<pre><code>handle_extractTag(self, dom, anotherObject)
# Do something
</code></pre>
<p>How would you make the appropriate changes to the <strong>handle</strong> method to implemented this? Hope you know what I mean :)</p>
<p>Cheers</p>
|
[
{
"answer_id": 277972,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 5,
"selected": true,
"text": "class MyHandler(object):\n def handle_extractTitle(self, dom):\n # do something\n\n def handle_extractMetaTags(self, dom):\n # do something\n\n def handle(self, type, dom):\n func = getattr(self, 'handle_%s' % type, None)\n if func is None:\n raise Exception(\"No handler for type %r\" % type)\n return func(dom)\n handler = MyHandler()\n handler.handle('extractTitle', dom)\n def handle(self, type, *args, **kwargs):\n func = getattr(self, 'handle_%s' % type, None)\n if func is None:\n raise Exception(\"No handler for type %r\" % type)\n return func(*args, **kwargs)\n"
},
{
"answer_id": 277980,
"author": "PierreBdR",
"author_id": 7136,
"author_profile": "https://Stackoverflow.com/users/7136",
"pm_score": 1,
"selected": false,
"text": "switch_dict = {'extractTitle': extractTitle, \n 'extractMetaTags': extractMetaTags}\nswitch_dict[type](dom)\n"
},
{
"answer_id": 277981,
"author": "Marcos Lara",
"author_id": 30626,
"author_profile": "https://Stackoverflow.com/users/30626",
"pm_score": 2,
"selected": false,
"text": "if"
},
{
"answer_id": 278006,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 1,
"selected": false,
"text": "type class ExtractTitle( object ):\n def process( dom ):\n return something\n\nclass ExtractMetaTags( object ):\n def process( dom ):\n return something\n type= ExtractTitle() # or ExtractMetaTags() or ExtractWhatever()\ntype.process( dom )\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30786/"
] |
277,996
|
<p>Do you know of a JAXB setting to prevent <strong>standalone="yes"</strong> from being generated in the resulting XML?</p>
<pre><code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
</code></pre>
|
[
{
"answer_id": 352107,
"author": "Sam",
"author_id": 37575,
"author_profile": "https://Stackoverflow.com/users/37575",
"pm_score": 7,
"selected": true,
"text": "marshaller.setProperty(\"com.sun.xml.bind.xmlDeclaration\", false);\n <?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"
},
{
"answer_id": 391234,
"author": "Kornel",
"author_id": 27009,
"author_profile": "https://Stackoverflow.com/users/27009",
"pm_score": 3,
"selected": false,
"text": "DOCTYPE standalone=\"yes\""
},
{
"answer_id": 4067474,
"author": "so_mv",
"author_id": 186858,
"author_profile": "https://Stackoverflow.com/users/186858",
"pm_score": 7,
"selected": false,
"text": "marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);\n"
},
{
"answer_id": 5431542,
"author": "WarFox",
"author_id": 598444,
"author_profile": "https://Stackoverflow.com/users/598444",
"pm_score": 6,
"selected": false,
"text": "marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);\n marshaller.setProperty(\"com.sun.xml.bind.xmlDeclaration\", false)\n <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n marshaller.setProperty(\"com.sun.xml.bind.xmlHeaders\",\n \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\");\n"
},
{
"answer_id": 38872445,
"author": "Debasis Das",
"author_id": 5280559,
"author_profile": "https://Stackoverflow.com/users/5280559",
"pm_score": 2,
"selected": false,
"text": "jaxbMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);\njaxbMarshaller.setProperty(\"com.sun.xml.internal.bind.xmlHeaders\", \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\" standalone=\\\"no\\\"?>\");\n"
},
{
"answer_id": 39628056,
"author": "Ari",
"author_id": 3741495,
"author_profile": "https://Stackoverflow.com/users/3741495",
"pm_score": 1,
"selected": false,
"text": "\"com.sun.xml.internal.bind.xmlHeaders\"\n \"com.sun.xml.bind.xmlHeaders\" (without the \"internal\", which are not meant to be used by the public)\n"
},
{
"answer_id": 40464942,
"author": "benez",
"author_id": 3583589,
"author_profile": "https://Stackoverflow.com/users/3583589",
"pm_score": 3,
"selected": false,
"text": "marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);\n String"
},
{
"answer_id": 43756759,
"author": "eddo",
"author_id": 5888756,
"author_profile": "https://Stackoverflow.com/users/5888756",
"pm_score": 3,
"selected": false,
"text": "xmlStreamWriter.writeProcessingInstruction(\"xml\", \"version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"\");\njaxbMarshaller.setProperty( Marshaller.JAXB_FRAGMENT, Boolean.TRUE);\njaxbMarshaller.marshal(object, xmlStreamWriter);\nxmlStreamWriter.writeEndDocument();\n"
},
{
"answer_id": 54620205,
"author": "Alisha Setia",
"author_id": 8160374,
"author_profile": "https://Stackoverflow.com/users/8160374",
"pm_score": 1,
"selected": false,
"text": "jaxbMarshaller.setProperty(\"com.sun.xml.internal.bind.xmlHeaders\",\n \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\");\njaxbMarshaller.setProperty(\"com.sun.xml.internal.bind.xmlDeclaration\", Boolean.FALSE);\njaxbMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE); \n"
},
{
"answer_id": 57382362,
"author": "Bernardo Mello",
"author_id": 10185475,
"author_profile": "https://Stackoverflow.com/users/10185475",
"pm_score": 2,
"selected": false,
"text": "private String marshaling2(Object object) throws JAXBException, XMLStreamException {\n JAXBContext jaxbContext = JAXBContext.newInstance(object.getClass());\n Marshaller jaxbMarshaller = jaxbContext.createMarshaller();\n jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);\n jaxbMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);\n StringWriter writer = new StringWriter();\n writer.write(\"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\");\n jaxbMarshaller.marshal(object, writer);\n return writer.toString();\n }\n"
},
{
"answer_id": 59061847,
"author": "Cesar",
"author_id": 5428711,
"author_profile": "https://Stackoverflow.com/users/5428711",
"pm_score": 2,
"selected": false,
"text": "<maven.compiler.source>1.8</maven.compiler.source>\n<maven.compiler.target>1.8</maven.compiler.target>\n // remove standalone=yes\nmarshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);\nmarshaller.setProperty(\"com.sun.xml.internal.bind.xmlHeaders\", \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\");\n"
},
{
"answer_id": 60774183,
"author": "Baked Inhalf",
"author_id": 3302747,
"author_profile": "https://Stackoverflow.com/users/3302747",
"pm_score": 0,
"selected": false,
"text": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?> <?xml version=\"1.0\" encoding=\"UTF-8\"?> marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);\nmarshaller.setProperty(\"com.sun.xml.internal.bind.xmlHeaders\", \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\");\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9707/"
] |
277,997
|
<p>I am tasked with moving quite a few web apps including the databases to new servers, they are ASP.NET. I was not the one to create and setup these originally so I must try to figure out what exactly I need to replicate in order to not break anything and so the customers have no idea that anything was moved. </p>
<p>Does anyone have any tips for this, or know any automated ways? </p>
<p>Is there any software that can help with this? </p>
<p>I know the web app sends emails, so I will need to setup SMTP and it connects to a database so that I also will need to move. I suppose I should do this at night and take down the servers so I can move the database at it's latest state...</p>
<p>Any tips or tricks?</p>
|
[
{
"answer_id": 1536242,
"author": "warren",
"author_id": 4418,
"author_profile": "https://Stackoverflow.com/users/4418",
"pm_score": 1,
"selected": false,
"text": "$CURRENT_SERVER $NEW_SERVER $NEW_SERVER $DB_SERVER $NEW_SERVER"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277997",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18309/"
] |
277,999
|
<p>I know that to find all the <code>.h</code> files I need to use:</p>
<pre><code>find . -name "*.h"
</code></pre>
<p>but how to find all the <code>.h</code> AND <code>.cpp</code> files?</p>
|
[
{
"answer_id": 278002,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": 7,
"selected": true,
"text": "find . -name \\*.h -print -o -name \\*.cpp -print\n find . \\( -name \\*.h -o -name \\*.cpp \\) -print\n"
},
{
"answer_id": 278018,
"author": "Philluminati",
"author_id": 25466,
"author_profile": "https://Stackoverflow.com/users/25466",
"pm_score": 4,
"selected": false,
"text": "find -name \"*.h\" -or -name \"*.cpp\"\n"
},
{
"answer_id": 278181,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 3,
"selected": false,
"text": "ack \"int\\s+foo\" --cpp \n \"--cpp\" .cpp .cc .cxx .m .hpp .hh .h .hxx"
},
{
"answer_id": 3858879,
"author": "Lyle Snodgrass",
"author_id": 466203,
"author_profile": "https://Stackoverflow.com/users/466203",
"pm_score": 2,
"selected": false,
"text": "find . -regex \".*\\.[cChH]\\(pp\\)?\" -print\n"
},
{
"answer_id": 25174706,
"author": "northteam",
"author_id": 712919,
"author_profile": "https://Stackoverflow.com/users/712919",
"pm_score": 2,
"selected": false,
"text": "find find \\( -name '*.cpp' -o -name '*.h' \\) -print\n -print -o"
},
{
"answer_id": 29963360,
"author": "mdup",
"author_id": 899752,
"author_profile": "https://Stackoverflow.com/users/899752",
"pm_score": 3,
"selected": false,
"text": "find find . -regex '.*\\.\\(cpp\\|h\\)'\n -regex .* ./dir1/dir2/..."
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/277999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
278,031
|
<p>What's the best way to store timezone information with dates/times in a uniform way so people can enter times from anywhere in the world in their own local time? Other users would then have the ability to view the times in their own local time and the original localtime on the web page.</p>
|
[
{
"answer_id": 1481509,
"author": "Haluk",
"author_id": 174559,
"author_profile": "https://Stackoverflow.com/users/174559",
"pm_score": 3,
"selected": false,
"text": "\"INSERT INTO abc_table (registrationtime) VALUES (UTC_TIMESTAMP())\"\n <? while($row = mysql_fetch_array($registration)){ \n\n $dt_obj = new DateTime($row['message_sent_timestamp'].\" UTC\");\n $dt_obj->setTimezone(new DateTimeZone('Europe/Istanbul'));\n echo $formatted_date_long=date_format($dt_obj, 'Y-m-d H:i:s'); } ?>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
278,034
|
<p>I have an authentication script (<strong><code>CheckLogin.aspx</code></strong>), and if any of the credentials do not match my application will redirect (via <strong><code>Server.Transfer</code></strong>) to the access denied page (<strong><code>forbidden.aspx</code></strong>). Each time my script runs,it gets an <strong><code>InvalidOperationException: Failed to map the path '/forbidden.aspx'</code></strong>. Here is a mockup of my applications file structure:</p>
<pre><code><root>
..default.aspx
..forbidden.aspx
..<inc>
....scripts.js
..<auth>
....CheckLogin.aspx
</code></pre>
<p>As you can see, the <strong><code>CheckLogin.aspx</code></strong> page is in a folder inside the root, and the <strong><code>forbidden.aspx</code></strong> page is inside the root itself. The path I am telling my application to redirect to is <strong><code>/forbidden.aspx</code></strong>.</p>
|
[
{
"answer_id": 278042,
"author": "DOK",
"author_id": 27637,
"author_profile": "https://Stackoverflow.com/users/27637",
"pm_score": 3,
"selected": true,
"text": "'~/forbidden.aspx'\n"
},
{
"answer_id": 278044,
"author": "Kon",
"author_id": 22303,
"author_profile": "https://Stackoverflow.com/users/22303",
"pm_score": 0,
"selected": false,
"text": "<location>"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25515/"
] |
278,037
|
<p>I'm working with a third party to integrate some of our systems with theirs and they provide us with a SOAP interface to make certain requests and changes in their connected systems. The problem for me is that they do not supply a WSDL-file for me to work against. If I had a WSDL-file it would be a simple matter just to run the supplied .NET command (wsdl.exe) and generate a proxy class to interact with the service.</p>
<p>Is there an "easy" way to do this without a WSDL-file? I have all the functions that we can access and what parameters I need to send and what I should expect in return.</p>
<p>Is it common to have a SOAP-service without WSDL-files? (I'm asking this since we're going to add more external systems into the mix in the future)</p>
<p>Has anyone done a proxy-class or any other form of client against a WDSL-less service and have any good pointers on how to do it?</p>
|
[
{
"answer_id": 278074,
"author": "Bradley Grainger",
"author_id": 23633,
"author_profile": "https://Stackoverflow.com/users/23633",
"pm_score": 2,
"selected": false,
"text": "System.Web.Services.Protocols.SoapHttpClientProtocol WebServiceBinding SoapDocumentMethod"
},
{
"answer_id": 413347,
"author": "SpoBo",
"author_id": 48417,
"author_profile": "https://Stackoverflow.com/users/48417",
"pm_score": 1,
"selected": false,
"text": "Imports Microsoft.Web.Services3\nImports Microsoft.Web.Services3.Addressing\nImports Microsoft.Web.Services3.Messaging\n\nNamespace Logic\n Public Class HTTPClient\n Inherits Soapclient\n\n Sub New(ByVal destination As EndpointReference)\n MyBase.Destination = destination\n End Sub\n\n <SoapMethod(\"processConfirmation\")> _\n Public Function processConfirmation(ByVal envelope As SoapEnvelope) As SoapEnvelope\n Return MyBase.SendRequestResponse(\"processConfirmation\", envelope)\n End Function\n End Class\nEnd Namespace\n Dim hc As New HTTPClient(New Microsoft.Web.Services3.Addressing.EndpointReference(New System.Uri(\"http://whatever.srv\")))\n\nDim envelope As New Microsoft.Web.Services3.SoapEnvelope\nDim doc As New Xml.XmlDocument\ndoc.LoadXml(\"<hey>there</hey>\")\nenvelope.SetBodyObject(doc)\n\nDim return_envelope As Microsoft.Web.Services3.SoapEnvelope = hc.processConfirmation(envelope)\n"
},
{
"answer_id": 3708132,
"author": "Manikant Thakur",
"author_id": 447255,
"author_profile": "https://Stackoverflow.com/users/447255",
"pm_score": 3,
"selected": false,
"text": "string EndPoints = \"http://203.189.91.127:7777/services/spm/spm\";\n\nstring New_Xml_Request_String = \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?><soapenv:Envelope xmlns:soapenv=\\\"http://schemas.xmlsoap.org/soap/envelope/\\\" xmlns:xsd=\\\"http://www.w3.org/2001/XMLSchema\\\" xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\"><soapenv:Body><OTA_AirLowFareSearchRQ EchoToken=\\\"0\\\" SequenceNmbr=\\\"0\\\" TransactionIdentifier=\\\"0\\\" xmlns=\\\"http://www.opentravel.org/OTA/2003/05\\\"><POS xmlns=\\\"http://www.opentravel.org/OTA/2003/05\\\"><Source AgentSine=\\\"\\\" PseudoCityCode=\\\"NPCK\\\" TerminalID=\\\"1\\\"><RequestorID ID=\\\"\\\"/></Source><YatraRequests><YatraRequest DoNotHitCache=\\\"true\\\" DoNotCache=\\\"false\\\" MidOfficeAgentID=\\\"\\\" AffiliateID=\\\"\\\" YatraRequestTypeCode=\\\"SMPA\\\"/></YatraRequests></POS><TravelerInfoSummary><AirTravelerAvail><PassengerTypeQuantity Code=\\\"ADT\\\" Quantity=\\\"1\\\"/><PassengerTypeQuantity Code=\\\"CHD\\\" Quantity=\\\"1\\\"/><PassengerTypeQuantity Code=\\\"INF\\\" Quantity=\\\"1\\\"/></AirTravelerAvail></TravelerInfoSummary> <SpecificFlightInfo><Airline Code=\\\"\\\"/></SpecificFlightInfo><OriginDestinationInformation><DepartureDateTime>\" + DateTime.Now.ToString(\"o\").Remove(19, 14) + \"</DepartureDateTime><OriginLocation CodeContext=\\\"IATA\\\" LocationCode=\\\"DEL\\\">\" + Source + \"</OriginLocation><DestinationLocation CodeContext=\\\"IATA\\\" LocationCode=\\\"BOM\\\">\" + Destincation + \"</DestinationLocation></OriginDestinationInformation><TravelPreferences><CabinPref Cabin=\\\"Economy\\\"/></TravelPreferences></OTA_AirLowFareSearchRQ></soapenv:Body></soapenv:Envelope>\";\n\n\n protected string HttpSOAPRequest_Test(string xmlfile, string proxy)\n {\n try\n {\n System.Xml.XmlDocument doc = new System.Xml.XmlDocument();\n doc.InnerXml = xmlfile.ToString();\n HttpWebRequest req = (HttpWebRequest)WebRequest.Create(EndPoints);\n req.Timeout = 100000000;\n if (proxy != null)\n req.Proxy = new WebProxy(proxy, true);\n req.Headers.Add(\"SOAPAction\", \"\");\n req.ContentType = \"application/soap+xml;charset=\\\"utf-8\\\"\";\n req.Accept = \"application/x-www-form-urlencoded\"; //\"application/soap+xml\";\n req.Method = \"POST\";\n Stream stm = req.GetRequestStream();\n doc.Save(stm);\n stm.Close();\n WebResponse resp = req.GetResponse();\n stm = resp.GetResponseStream();\n StreamReader r = new StreamReader(stm);\n string myd = r.ReadToEnd();\n return myd;\n }\n\n catch (Exception se)\n {\n throw new Exception(\"Error Occurred in AuditAdapter.getXMLDocumentFromXMLTemplate()\", se);\n }\n }\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26746/"
] |
278,039
|
<p>I have a timely operation that runs on a background thread. While running, I currently put the cursor in a wait state:</p>
<pre><code>Mouse.OverrideCursor = Cursors.Wait
</code></pre>
<p>I just implemented a feature that allows the user to click a "Cancel" button if they're tired of waiting. However, some users may not realize they can do this (despite the cancel button being the only active control during the process) because they mouse cursor is an hourglass.</p>
<p>I've seen programs use a cursor that shows the hourglass and has an arrow pointer attached as well. How to I set the mouse cursor to this state? I looked through the .NET documentation and could not find this cursor.</p>
<p>Thanks!</p>
|
[
{
"answer_id": 278052,
"author": "Martin",
"author_id": 8157,
"author_profile": "https://Stackoverflow.com/users/8157",
"pm_score": 5,
"selected": true,
"text": "Me.Cursor = Cursors.AppStarting\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/132931/"
] |
278,046
|
<p>Are there any free tools to help simplify working with an NHibernate project in .NET 3.5? Primarily, I'm looking for some kind of code and config file generator to automate some of the more tedious parts of working with NHibernate.</p>
|
[
{
"answer_id": 280349,
"author": "Erik Öjebo",
"author_id": 276,
"author_profile": "https://Stackoverflow.com/users/276",
"pm_score": 5,
"selected": true,
"text": "public CustomerMap : ClassMap<Customer>\n{\n public CustomerMap()\n {\n Id(x => x.ID);\n Map(x => x.Name);\n Map(x => x.Credit);\n HasMany<Product>(x => x.Products)\n .AsBag();\n Component<Address>(x => x.Address, m => \n { \n m.Map(x => x.AddressLine1); \n m.Map(x => x.AddressLine2); \n m.Map(x => x.CityName); \n m.Map(x => x.CountryName); \n });\n}\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2147/"
] |
278,062
|
<p>I've got a cool piece of code taken from a VC++ project which gets complete information of the hard disk drive WITHOUT using WMI (since WMI has got its own problems).</p>
<p>I ask those of you who are comfortable with API functions to try to convert this VB6 code into VB.NET (or C#) and help A LOT of people who are in great need of this utility class.</p>
<p>I've spent lots of time and searched the entire net to find ways to get the actual model and serial number of HDD and eventually found this one, if only it were in .NET...</p>
<p>Here is the code and sorry about its formatting problems, just paste it into VB6 IDE:</p>
<pre><code>Option Explicit
''// Antonio Giuliana, 2001-2003
''// Costanti per l'individuazione della versione di OS
Private Const VER_PLATFORM_WIN32S = 0
Private Const VER_PLATFORM_WIN32_WINDOWS = 1
Private Const VER_PLATFORM_WIN32_NT = 2
''// Costanti per la comunicazione con il driver IDE
Private Const DFP_RECEIVE_DRIVE_DATA = &H7C088
''// Costanti per la CreateFile
Private Const FILE_SHARE_READ = &H1
Private Const FILE_SHARE_WRITE = &H2
Private Const GENERIC_READ = &H80000000
Private Const GENERIC_WRITE = &H40000000
Private Const OPEN_EXISTING = 3
Private Const CREATE_NEW = 1
''// Enumerazione dei comandi per la CmnGetHDData
Private Enum HDINFO
HD_MODEL_NUMBER
HD_SERIAL_NUMBER
HD_FIRMWARE_REVISION
End Enum
''// Struttura per l'individuazione della versione di OS
Private Type OSVERSIONINFO
dwOSVersionInfoSize As Long
dwMajorVersion As Long
dwMinorVersion As Long
dwBuildNumber As Long
dwPlatformId As Long
szCSDVersion As String * 128
End Type
''// Struttura per il campo irDriveRegs della struttura SENDCMDINPARAMS
Private Type IDEREGS
bFeaturesReg As Byte
bSectorCountReg As Byte
bSectorNumberReg As Byte
bCylLowReg As Byte
bCylHighReg As Byte
bDriveHeadReg As Byte
bCommandReg As Byte
bReserved As Byte
End Type
''// Struttura per l'I/O dei comandi al driver IDE
Private Type SENDCMDINPARAMS
cBufferSize As Long
irDriveRegs As IDEREGS
bDriveNumber As Byte
bReserved(1 To 3) As Byte
dwReserved(1 To 4) As Long
End Type
''// Struttura per il campo DStatus della struttura SENDCMDOUTPARAMS
Private Type DRIVERSTATUS
bDriveError As Byte
bIDEStatus As Byte
bReserved(1 To 2) As Byte
dwReserved(1 To 2) As Long
End Type
''// Struttura per l'I/O dei comandi al driver IDE
Private Type SENDCMDOUTPARAMS
cBufferSize As Long
DStatus As DRIVERSTATUS ''// ovvero DriverStatus
bBuffer(1 To 512) As Byte
End Type
''// Per ottenere la versione del SO
Private Declare Function GetVersionEx _
Lib "kernel32" Alias "GetVersionExA" _
(lpVersionInformation As OSVERSIONINFO) As Long
''// Per ottenere un handle al device IDE
Private Declare Function CreateFile _
Lib "kernel32" Alias "CreateFileA" _
(ByVal lpFileName As String, _
ByVal dwDesiredAccess As Long, _
ByVal dwShareMode As Long, _
ByVal lpSecurityAttributes As Long, _
ByVal dwCreationDisposition As Long, _
ByVal dwFlagsAndAttributes As Long, _
ByVal hTemplateFile As Long) As Long
''// Per chiudere l'handle del device IDE
Private Declare Function CloseHandle _
Lib "kernel32" _
(ByVal hObject As Long) As Long
''// Per comunicare con il driver IDE
Private Declare Function DeviceIoControl _
Lib "kernel32" _
(ByVal hDevice As Long, _
ByVal dwIoControlCode As Long, _
lpInBuffer As Any, _
ByVal nInBufferSize As Long, _
lpOutBuffer As Any, _
ByVal nOutBufferSize As Long, _
lpBytesReturned As Long, _
ByVal lpOverlapped As Long) As Long
''// Per azzerare buffer di scambio dati
Private Declare Sub ZeroMemory _
Lib "kernel32" Alias "RtlZeroMemory" _
(dest As Any, _
ByVal numBytes As Long)
''// Per copiare porzioni di memoria
Private Declare Sub CopyMemory _
Lib "kernel32" Alias "RtlMoveMemory" _
(Destination As Any, _
Source As Any, _
ByVal Length As Long)
Private Declare Function GetLastError _
Lib "kernel32" () As Long
Private mvarCurrentDrive As Byte ''// Drive corrente
Private mvarPlatform As String ''// Piattaforma usata
Public Property Get Copyright() As String
''// Copyright
Copyright = "HDSN Vrs. 1.00, (C) Antonio Giuliana, 2001-2003"
End Property
''// Metodo GetModelNumber
Public Function GetModelNumber() As String
''// Ottiene il ModelNumber
GetModelNumber = CmnGetHDData(HD_MODEL_NUMBER)
End Function
''// Metodo GetSerialNumber
Public Function GetSerialNumber() As String
''// Ottiene il SerialNumber
GetSerialNumber = CmnGetHDData(HD_SERIAL_NUMBER)
End Function
''// Metodo GetFirmwareRevision
Public Function GetFirmwareRevision() As String
''// Ottiene la FirmwareRevision
GetFirmwareRevision = CmnGetHDData(HD_FIRMWARE_REVISION)
End Function
''// Proprieta' CurrentDrive
Public Property Let CurrentDrive(ByVal vData As Byte)
''// Controllo numero di drive fisico IDE
If vData < 0 Or vData > 3 Then
Err.Raise 10000, , "Illegal drive number" ''// IDE drive 0..3
End If
''// Nuovo drive da considerare
mvarCurrentDrive = vData
End Property
''// Proprieta' CurrentDrive
Public Property Get CurrentDrive() As Byte
''// Restituisce drive fisico corrente (IDE 0..3)
CurrentDrive = mvarCurrentDrive
End Property
''// Proprieta' Platform
Public Property Get Platform() As String
''// Restituisce tipo OS
Platform = mvarPlatform
End Property
Private Sub Class_Initialize()
''// Individuazione del tipo di OS
Dim OS As OSVERSIONINFO
OS.dwOSVersionInfoSize = Len(OS)
Call GetVersionEx(OS)
mvarPlatform = "Unk"
Select Case OS.dwPlatformId
Case Is = VER_PLATFORM_WIN32S
mvarPlatform = "32S" ''// Win32S
Case Is = VER_PLATFORM_WIN32_WINDOWS
If OS.dwMinorVersion = 0 Then
mvarPlatform = "W95" ''// Win 95
Else
mvarPlatform = "W98" ''// Win 98
End If
Case Is = VER_PLATFORM_WIN32_NT
mvarPlatform = "WNT" ''// Win NT/2000
End Select
End Sub
Private Function CmnGetHDData(hdi As HDINFO) As String
''// Rilevazione proprieta' IDE
Dim bin As SENDCMDINPARAMS
Dim bout As SENDCMDOUTPARAMS
Dim hdh As Long
Dim br As Long
Dim ix As Long
Dim hddfr As Long
Dim hddln As Long
Dim s As String
Select Case hdi ''// Selezione tipo caratteristica richiesta
Case HD_MODEL_NUMBER
hddfr = 55 ''// Posizione nel buffer del ModelNumber
hddln = 40 ''// Lunghezza nel buffer del ModelNumber
Case HD_SERIAL_NUMBER
hddfr = 21 ''// Posizione nel buffer del SerialNumber
hddln = 20 ''// Lunghezza nel buffer del SerialNumber
Case HD_FIRMWARE_REVISION
hddfr = 47 ''// Posizione nel buffer del FirmwareRevision
hddln = 8 ''// Lunghezza nel buffer del FirmwareRevision
Case Else
Err.Raise 10001, "Illegal HD Data type"
End Select
Select Case mvarPlatform
Case "WNT"
''// Per Win NT/2000 apertura handle al drive fisico
hdh = CreateFile("\\.\PhysicalDrive" & mvarCurrentDrive, _
GENERIC_READ + GENERIC_WRITE, FILE_SHARE_READ + FILE_SHARE_WRITE, _
0, OPEN_EXISTING, 0, 0)
Case "W95", "W98"
''// Per Win 9X apertura handle al driver SMART
''// (in \WINDOWS\SYSTEM da spostare in \WINDOWS\SYSTEM\IOSUBSYS)
''// che comunica con il driver IDE
hdh = CreateFile("\\.\Smartvsd", _
0, 0, 0, CREATE_NEW, 0, 0)
Case Else
''// Piattaforma non supportata (Win32S)
Err.Raise 10002, , "Illegal platform (only WNT, W98 or W95)"
End Select
''// Controllo validità handle
If hdh = 0 Then
Err.Raise 10003, , "Error on CreateFile"
End If
''// Azzeramento strutture per l'I/O da driver
ZeroMemory bin, Len(bin)
ZeroMemory bout, Len(bout)
''// Preparazione parametri struttura di richiesta al driver
With bin
.bDriveNumber = mvarCurrentDrive
.cBufferSize = 512
With .irDriveRegs
If (mvarCurrentDrive And 1) Then
.bDriveHeadReg = &HB0
Else
.bDriveHeadReg = &HA0
End If
.bCommandReg = &HEC
.bSectorCountReg = 1
.bSectorNumberReg = 1
End With
End With
''// Richiesta al driver
DeviceIoControl hdh, DFP_RECEIVE_DRIVE_DATA, _
bin, Len(bin), bout, Len(bout), br, 0
''// Formazione stringa di risposta
''// da buffer di uscita
''// L'ordine dei byte e' invertito
s = ""
For ix = hddfr To hddfr + hddln - 1 Step 2
If bout.bBuffer(ix + 1) = 0 Then Exit For
s = s & Chr(bout.bBuffer(ix + 1))
If bout.bBuffer(ix) = 0 Then Exit For
s = s & Chr(bout.bBuffer(ix))
Next ix
''// Chiusura handle
CloseHandle hdh
''// Restituzione informazione richiesta
CmnGetHDData = Trim(s)
End Function
</code></pre>
|
[
{
"answer_id": 278124,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 0,
"selected": false,
"text": "Type Structure System.IntPtr"
},
{
"answer_id": 278195,
"author": "masfenix",
"author_id": 36212,
"author_profile": "https://Stackoverflow.com/users/36212",
"pm_score": 1,
"selected": false,
"text": "Try\nDim Searcher_P As New ManagementObjectSearcher(\"root\\CIMV2\", \"SELECT * FROM Win32_PhysicalMedia\")\nFor Each queryObj As ManagementObject In Searcher_P.Get()\nIf queryObj(\"SerialNumber\").ToString.Trim = \"Y2S0RKFE\" Then\nMe.Cursor = Cursors.Default\nReturn True\nEnd If\nNext\nCatch ex As Exception\nMessageBox.Show(\"An error occurred while querying for WMI data: Win32_PhysicalMedia \" & ex.Message)\nEnd Try\n\nTry\nDim Searcher_L As New ManagementObjectSearcher(\"root\\CIMV2\", \"SELECT * FROM Win32_LogicalDisk WHERE DeviceID = 'C:'\")\nFor Each queryObj As ManagementObject In Searcher_L.Get()\nIf queryObj(\"VolumeSerialNumber\").ToString.Trim = \"226C1A0B\" Then\nMe.Cursor = Cursors.Default\nReturn True\nEnd If\nNext\nCatch ex As Exception\nMessageBox.Show(\"An error occurred while querying for WMI data: VolumeSerialNumber \" & ex.Message)\nReturn False\nEnd Try\n"
},
{
"answer_id": 287270,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "Public Class HDDInfo\n#Region \" Declatrations \"\nPrivate Declare Function CreateFile Lib \"kernel32\" Alias \"CreateFileA\" (ByVal lpFileName As String, ByVal dwDesiredAccess As Integer, ByVal dwShareMode As Integer, ByVal lpSecurityAttributes As Integer, ByVal dwCreationDisposition As Integer, ByVal dwFlagsAndAttributes As Integer, ByVal hTemplateFile As Integer) As Integer\n<System.Runtime.InteropServices.DllImport(\"kernel32.dll\")> _\nPrivate Shared Function CloseHandle(ByVal hObject As Integer) As Integer\nEnd Function\n<System.Runtime.InteropServices.DllImport(\"kernel32.dll\")> _\nPrivate Shared Function DeviceIoControl(ByVal hDevice As Integer, ByVal dwIoControlCode As Integer, <[In](), Out()> ByVal lpInBuffer As SENDCMDINPARAMS, ByVal lpInBufferSize As Integer, <[In](), Out()> ByVal lpOutBuffer As SENDCMDOUTPARAMS, ByVal lpOutBufferSize As Integer, _\n ByRef lpBytesReturned As Integer, ByVal lpOverlapped As Integer) As Integer\nEnd Function\nPrivate Const FILE_SHARE_READ As Short = &H1\nPrivate Const FILE_SHARE_WRITE As Short = &H2\nPrivate Const GENERIC_READ As Integer = &H80000000\nPrivate Const GENERIC_WRITE As Integer = &H40000000\nPrivate Const OPEN_EXISTING As Short = 3\nPrivate Const CREATE_NEW As Short = 1\nPrivate Const VER_PLATFORM_WIN32_NT As Integer = 2\nPrivate Const DFP_RECEIVE_DRIVE_DATA As Integer = &H7C088\nPrivate Const INVALID_HANDLE_VALUE As Integer = -1\n#End Region\n#Region \" Classes \"\n<StructLayout(LayoutKind.Sequential, Size:=8)> _\nPrivate Class IDEREGS\n Public Features As Byte\n Public SectorCount As Byte\n Public SectorNumber As Byte\n Public CylinderLow As Byte\n Public CylinderHigh As Byte\n Public DriveHead As Byte\n Public Command As Byte\n Public Reserved As Byte\nEnd Class\n<StructLayout(LayoutKind.Sequential, Size:=32)> _\nPrivate Class SENDCMDINPARAMS\n Public BufferSize As Integer\n Public DriveRegs As IDEREGS\n Public DriveNumber As Byte\n <MarshalAs(UnmanagedType.ByValArray, SizeConst:=3)> _\n Public Reserved As Byte()\n <MarshalAs(UnmanagedType.ByValArray, SizeConst:=4)> _\n Public Reserved2 As Integer()\n Public Sub New()\n DriveRegs = New IDEREGS()\n Reserved = New Byte(2) {}\n Reserved2 = New Integer(3) {}\n End Sub\nEnd Class\n<StructLayout(LayoutKind.Sequential, Size:=12)> _\nPrivate Class DRIVERSTATUS\n Public DriveError As Byte\n Public IDEStatus As Byte\n <MarshalAs(UnmanagedType.ByValArray, SizeConst:=2)> _\n Public Reserved As Byte()\n <MarshalAs(UnmanagedType.ByValArray, SizeConst:=2)> _\n Public Reserved2 As Integer()\n Public Sub New()\n Reserved = New Byte(1) {}\n Reserved2 = New Integer(1) {}\n End Sub\nEnd Class\n<StructLayout(LayoutKind.Sequential)> _\nPrivate Class IDSECTOR\n Public GenConfig As Short\n Public NumberCylinders As Short\n Public Reserved As Short\n Public NumberHeads As Short\n Public BytesPerTrack As Short\n Public BytesPerSector As Short\n Public SectorsPerTrack As Short\n <MarshalAs(UnmanagedType.ByValArray, SizeConst:=3)> _\n Public VendorUnique As Short()\n <MarshalAs(UnmanagedType.ByValArray, SizeConst:=20)> _\n Public SerialNumber As Char()\n Public BufferClass As Short\n Public BufferSize As Short\n Public ECCSize As Short\n <MarshalAs(UnmanagedType.ByValArray, SizeConst:=8)> _\n Public FirmwareRevision As Char()\n <MarshalAs(UnmanagedType.ByValArray, SizeConst:=40)> _\n Public ModelNumber As Char()\n Public MoreVendorUnique As Short\n Public DoubleWordIO As Short\n Public Capabilities As Short\n Public Reserved1 As Short\n Public PIOTiming As Short\n Public DMATiming As Short\n Public BS As Short\n Public NumberCurrentCyls As Short\n Public NumberCurrentHeads As Short\n Public NumberCurrentSectorsPerTrack As Short\n Public CurrentSectorCapacity As Integer\n Public MultipleSectorCapacity As Short\n Public MultipleSectorStuff As Short\n Public TotalAddressableSectors As Integer\n Public SingleWordDMA As Short\n Public MultiWordDMA As Short\n <MarshalAs(UnmanagedType.ByValArray, SizeConst:=382)> _\n Public Reserved2 As Byte()\nEnd Class\n<StructLayout(LayoutKind.Sequential)> _\nPrivate Class SENDCMDOUTPARAMS\n Public BufferSize As Integer\n Public Status As DRIVERSTATUS\n Public IDS As IDSECTOR\n Public Sub New()\n Status = New DRIVERSTATUS()\n IDS = New IDSECTOR()\n End Sub\nEnd Class\n#End Region\n#Region \" Methods and Functions \"\nPrivate Shared Function SwapChars(ByVal chars As Char()) As String\n For i As Integer = 0 To chars.Length - 2 Step 2\n Dim t As Char\n t = chars(i)\n chars(i) = chars(i + 1)\n chars(i + 1) = t\n Next\n Dim s As New String(chars)\n Return s\nEnd Function\nPublic Shared Function GetHDDInfoString() As String\n Dim serialNumber As String = \" \", model As String = \" \", firmware As String = \" \"\n Dim handle As Integer, returnSize As Integer = 0\n Dim driveNumber As Integer = 0\n Dim sci As New SENDCMDINPARAMS()\n Dim sco As New SENDCMDOUTPARAMS()\n\n If Environment.OSVersion.Platform = PlatformID.Win32NT Then\n handle = CreateFile(\"\\\\.\\PhysicalDrive\" & \"0\", GENERIC_READ + GENERIC_WRITE, FILE_SHARE_READ + FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0)\n Else\n handle = CreateFile(\"\\\\.\\Smartvsd\", 0, 0, 0, CREATE_NEW, 0, 0)\n End If\n If handle <> INVALID_HANDLE_VALUE Then\n sci.DriveNumber = CByte(driveNumber)\n sci.BufferSize = Marshal.SizeOf(sco)\n sci.DriveRegs.DriveHead = CByte((&HA0 Or driveNumber << 4))\n sci.DriveRegs.Command = &HEC\n sci.DriveRegs.SectorCount = 1\n sci.DriveRegs.SectorNumber = 1\n If DeviceIoControl(handle, DFP_RECEIVE_DRIVE_DATA, sci, Marshal.SizeOf(sci), sco, Marshal.SizeOf(sco), _\n returnSize, 0) <> 0 Then\n serialNumber = SwapChars(sco.IDS.SerialNumber)\n model = SwapChars(sco.IDS.ModelNumber)\n firmware = SwapChars(sco.IDS.FirmwareRevision)\n End If\n CloseHandle(handle)\n End If\n Return model.Trim & \" \" & serialNumber.Trim\nEnd Function\n#End Region\nEnd Class\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
278,068
|
<p>I have an image that I want to show some 'spotlights' on, like they do on TV. The rest of the image should be darker than the original, and the person that I'm spotlighting should be normal. I have the x,y and radius of the spotlight, but I'm not sure how to change the brightness at that location. </p>
<p>Also, if I have two spotlights and they intersect, the intersection should be brighter than either of the spotlights. </p>
|
[
{
"answer_id": 278261,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": " public void spotLight(int x, int y, int w, int h)\n {\n BufferedImage i = biDest.getSubimage(x, y, w, h);\n\n RescaleOp rescale = new RescaleOp(SPOTLIGHT_BRIGHTNESS, 0, null);\n rescale.filter(i, i);\n\n repaint();\n }\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
278,071
|
<p>I want to get the overall total CPU usage for an application in C#. I've found many ways to dig into the properties of processes, but I only want the CPU usage of the processes, and the total CPU like you get in the TaskManager.</p>
<p>How do I do that?</p>
|
[
{
"answer_id": 278088,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 8,
"selected": false,
"text": "PerformanceCounter cpuCounter;\nPerformanceCounter ramCounter;\n\ncpuCounter = new PerformanceCounter(\"Processor\", \"% Processor Time\", \"_Total\");\nramCounter = new PerformanceCounter(\"Memory\", \"Available MBytes\");\n public string getCurrentCpuUsage(){\n return cpuCounter.NextValue()+\"%\";\n}\n\npublic string getAvailableRAM(){\n return ramCounter.NextValue()+\"MB\";\n} \n"
},
{
"answer_id": 278505,
"author": "xoxo",
"author_id": 36243,
"author_profile": "https://Stackoverflow.com/users/36243",
"pm_score": 4,
"selected": false,
"text": "private void button1_Click(object sender, EventArgs e)\n{\n selectedServer = \"JS000943\";\n listBox1.Items.Add(GetProcessorIdleTime(selectedServer).ToString());\n}\n\nprivate static int GetProcessorIdleTime(string selectedServer)\n{\n try\n {\n var searcher = new\n ManagementObjectSearcher\n (@\"\\\\\"+ selectedServer +@\"\\root\\CIMV2\",\n \"SELECT * FROM Win32_PerfFormattedData_PerfOS_Processor WHERE Name=\\\"_Total\\\"\");\n\n ManagementObjectCollection collection = searcher.Get();\n ManagementObject queryObj = collection.Cast<ManagementObject>().First();\n\n return Convert.ToInt32(queryObj[\"PercentIdleTime\"]);\n }\n catch (ManagementException e)\n {\n MessageBox.Show(\"An error occurred while querying for WMI data: \" + e.Message);\n }\n return -1;\n}\n"
},
{
"answer_id": 6168408,
"author": "Khalid Rahaman",
"author_id": 55688,
"author_profile": "https://Stackoverflow.com/users/55688",
"pm_score": 6,
"selected": false,
"text": "public class Form1\n{\n\n int totalHits = 0;\n\n public object getCPUCounter()\n {\n\n PerformanceCounter cpuCounter = new PerformanceCounter();\n cpuCounter.CategoryName = \"Processor\";\n cpuCounter.CounterName = \"% Processor Time\";\n cpuCounter.InstanceName = \"_Total\";\n\n // will always start at 0\n dynamic firstValue = cpuCounter.NextValue();\n System.Threading.Thread.Sleep(1000);\n // now matches task manager reading\n dynamic secondValue = cpuCounter.NextValue();\n\n return secondValue;\n\n }\n\n\n private void Timer1_Tick(Object sender, EventArgs e)\n {\n int cpuPercent = (int)getCPUCounter();\n if (cpuPercent >= 90)\n {\n totalHits = totalHits + 1;\n if (totalHits == 60)\n {\n Interaction.MsgBox(\"ALERT 90% usage for 1 minute\");\n totalHits = 0;\n } \n }\n else\n {\n totalHits = 0;\n }\n Label1.Text = cpuPercent + \" % CPU\";\n //Label2.Text = getRAMCounter() + \" RAM Free\";\n Label3.Text = totalHits + \" seconds over 20% usage\";\n }\n}\n"
},
{
"answer_id": 10233124,
"author": "Colin Breame",
"author_id": 641452,
"author_profile": "https://Stackoverflow.com/users/641452",
"pm_score": 2,
"selected": false,
"text": "public class ProcessorUsage\n{\n const float sampleFrequencyMillis = 1000;\n\n protected object syncLock = new object();\n protected PerformanceCounter counter;\n protected float lastSample;\n protected DateTime lastSampleTime;\n\n /// <summary>\n /// \n /// </summary>\n public ProcessorUsage()\n {\n this.counter = new PerformanceCounter(\"Processor\", \"% Processor Time\", \"_Total\", true);\n }\n\n /// <summary>\n /// \n /// </summary>\n /// <returns></returns>\n public float GetCurrentValue()\n {\n if ((DateTime.UtcNow - lastSampleTime).TotalMilliseconds > sampleFrequencyMillis)\n {\n lock (syncLock)\n {\n if ((DateTime.UtcNow - lastSampleTime).TotalMilliseconds > sampleFrequencyMillis)\n {\n lastSample = counter.NextValue();\n lastSampleTime = DateTime.UtcNow;\n }\n }\n }\n\n return lastSample;\n }\n}\n"
},
{
"answer_id": 11891139,
"author": "MtnManChris",
"author_id": 1588638,
"author_profile": "https://Stackoverflow.com/users/1588638",
"pm_score": 4,
"selected": false,
"text": "private static void RunTest(string appName)\n{\n bool done = false;\n PerformanceCounter total_cpu = new PerformanceCounter(\"Process\", \"% Processor Time\", \"_Total\");\n PerformanceCounter process_cpu = new PerformanceCounter(\"Process\", \"% Processor Time\", appName);\n while (!done)\n {\n float t = total_cpu.NextValue();\n float p = process_cpu.NextValue();\n Console.WriteLine(String.Format(\"_Total = {0} App = {1} {2}%\\n\", t, p, p / t * 100));\n System.Threading.Thread.Sleep(1000);\n }\n}\n"
},
{
"answer_id": 17749478,
"author": "atconway",
"author_id": 410937,
"author_profile": "https://Stackoverflow.com/users/410937",
"pm_score": 0,
"selected": false,
"text": "PerformanceCounter WMI PerformanceCounter"
},
{
"answer_id": 18574155,
"author": "Jay Byford-Rew",
"author_id": 2739967,
"author_profile": "https://Stackoverflow.com/users/2739967",
"pm_score": 2,
"selected": false,
"text": "var cpuCounter = new PerformanceCounter(\"Processor\", \"% Processor Time\", \"_Total\");\nint usage = (int) cpuCounter.NextValue();\nwhile (usage == 0 || usage > 80)\n{\n Thread.Sleep(250);\n usage = (int)cpuCounter.NextValue();\n}\n"
},
{
"answer_id": 60514868,
"author": "araad1992",
"author_id": 3276211,
"author_profile": "https://Stackoverflow.com/users/3276211",
"pm_score": 0,
"selected": false,
"text": "public int GetCpuUsage()\n{\n var cpuCounter = new PerformanceCounter(\"Processor\", \"% Processor Time\", \"_Total\", Environment.MachineName);\n cpuCounter.NextValue();\n System.Threading.Thread.Sleep(1000); //This avoid that answer always 0\n return (int)cpuCounter.NextValue();\n}\n"
},
{
"answer_id": 72249902,
"author": "AecorSoft",
"author_id": 9382225,
"author_profile": "https://Stackoverflow.com/users/9382225",
"pm_score": 1,
"selected": false,
"text": "new PerformanceCounter(\"Processor Information\", \"% Processor Utility\", \"_Total\");\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278071",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
278,075
|
<p>I am monitoring a folder with a .net filewatcher for certain kind of files(*.mbxml). I am using the created event of filewatcher for it. Once the created event fires I have to move this file to another folder. The problem with this approach is that the created event is fired as soon as the file copying starts. So if the file is taking too long to copy to the folder being watched, the code that moves the file fails. I've searched and the only solution I found on the net was that you move the file within a try-catch block and keep trying until the whole file is copied. I don't like this solution, it would've been better if the created event was fired once the whole file had finished copying or there was a separate event for it. Is there another way of achieving this?</p>
|
[
{
"answer_id": 278115,
"author": "h0st1le",
"author_id": 26170,
"author_profile": "https://Stackoverflow.com/users/26170",
"pm_score": 3,
"selected": true,
"text": " private static bool creationComplete(string fileName)\n {\n // if the file can be opened it is no longer locked and now available\n try\n {\n using (FileStream inputStream = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.None))\n {\n return true;\n }\n }\n catch (IOException)\n {\n return false;\n }\n }\n"
},
{
"answer_id": 278201,
"author": "Hath",
"author_id": 5186,
"author_profile": "https://Stackoverflow.com/users/5186",
"pm_score": 2,
"selected": false,
"text": "public class CustomFileSystemWatcher : System.IO.FileSystemWatcher\n{\n public CustomFileSystemWatcher()\n {\n this.Created += new FileSystemEventHandler(CustomFileSystemWatcher_Created);\n }\n\n\n private void CustomFileSystemWatcher_Created(object sender, FileSystemEventArgs e)\n {\n ThreadPool.QueueUserWorkItem((n) => { WaitFileReady(e); });\n }\n\n private void WaitFileReady(FileSystemEventArgs e)\n {\n while (true)\n {\n try\n {\n using (FileStream fs = File.Open(e.FullPath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))\n {\n //exit\n break;\n }\n }\n catch (Exception)\n {\n //wait if you like\n Thread.Sleep(100);\n }\n }\n OnFileReady(e);\n }\n\n public event FileSystemEventHandler FileReady;\n\n protected virtual void OnFileReady(FileSystemEventArgs e)\n {\n if (this.EnableRaisingEvents && FileReady != null) FileReady(this, e);\n }\n}\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25125/"
] |
278,081
|
<p>I've been using Git on Windows (msysgit) to track changes for some design work I've been doing.</p>
<p>Today I've been working on a different PC (with remote repo <code>brian</code>) and I'm now trying to merge the edits done today back into my regular local version on my laptop.</p>
<p>On my laptop, I've used <code>git pull brian master</code> to pull the changes into my local version. Everything was fine apart from the main InDesign document - this shows as a conflict.</p>
<p>The version on the PC (<code>brian</code>) is the latest one that I want to keep but I don't know what commands tells the repo to use this one. </p>
<p>I tried directly copying the file across onto my laptop but this seems to break the whole merge process.</p>
<p>Can anyone point me in the right direction?</p>
|
[
{
"answer_id": 278207,
"author": "VolkA",
"author_id": 25472,
"author_profile": "https://Stackoverflow.com/users/25472",
"pm_score": 7,
"selected": false,
"text": "git commit -a -m \"Fix merge conflict in test.foo\"\n git checkout --ours -- path/to/file.txt\ngit checkout --theirs -- path/to/file.txt\n"
},
{
"answer_id": 1162085,
"author": "Brian Webster",
"author_id": 23324,
"author_profile": "https://Stackoverflow.com/users/23324",
"pm_score": 3,
"selected": false,
"text": "% git fetch\n % git checkout FETCH_HEAD stuff/to/update\n"
},
{
"answer_id": 1321855,
"author": "RobM",
"author_id": 83100,
"author_profile": "https://Stackoverflow.com/users/83100",
"pm_score": 7,
"selected": false,
"text": "git mergetool\n git {conflicted}.HEAD {conflicted} {conflicted}.REMOTE {conflicted}.REMOTE {conflicted} git"
},
{
"answer_id": 2163895,
"author": "Joshua Flanagan",
"author_id": 156533,
"author_profile": "https://Stackoverflow.com/users/156533",
"pm_score": 4,
"selected": false,
"text": "git commit -a\n git checkout otherbranch theconflictedfile\ngit commit -a\n"
},
{
"answer_id": 2163926,
"author": "mipadi",
"author_id": 28804,
"author_profile": "https://Stackoverflow.com/users/28804",
"pm_score": 11,
"selected": true,
"text": "git checkout --ours --theirs $ git checkout --theirs -- path/to/conflicted-file.txt\n $ git checkout --ours -- path/to/conflicted-file.txt\n"
},
{
"answer_id": 16826359,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "git checkout git checkout [-f|--ours|--theirs|-m|--conflict=<style>] [<tree-ish>] [--] <paths>... --ours --theirs ours theirs -f --ours --theirs -m"
},
{
"answer_id": 31998378,
"author": "tyoc213",
"author_id": 682603,
"author_profile": "https://Stackoverflow.com/users/682603",
"pm_score": 1,
"selected": false,
"text": "$ git show :1:hello.blend > hello.common.blend\n$ git show :2:hello.blend > hello.ours.blend\n$ git show :3:hello.blend > hello.theirs.blend\n"
},
{
"answer_id": 55628454,
"author": "Peter",
"author_id": 1134343,
"author_profile": "https://Stackoverflow.com/users/1134343",
"pm_score": 0,
"selected": false,
"text": "warning: Cannot merge binary files: <path>\nAuto-merging <path>\nCONFLICT (content): Merge conflict in <path>\nAutomatic merge failed; fix conflicts and then commit the result.\n git checkout --theirs -- <path>\ngit checkout --ours -- <path>\n Updated 0 paths from the index\n No files need merging\n All conflicts fixed but you are still merging.\n (use \"git commit\" to conclude merge)\n git commit\n git checkout <commit where the remote version exists> <path>\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33721/"
] |
278,089
|
<p>is there a quick way to sort the items of a select element?
Or I have to resort to writing javascript?</p>
<p>Please any ideas.</p>
<pre><code><select size="4" name="lstALL" multiple="multiple" id="lstALL" tabindex="12" style="font-size:XX-Small;height:95%;width:100%;">
<option value="0"> XXX</option>
<option value="1203">ABC</option>
<option value="1013">MMM</option>
</select>
</code></pre>
|
[
{
"answer_id": 278509,
"author": "Matty",
"author_id": 26241,
"author_profile": "https://Stackoverflow.com/users/26241",
"pm_score": 7,
"selected": true,
"text": "document.getElementById('lstALL') function sortSelect(selElem) {\n var tmpAry = new Array();\n for (var i=0;i<selElem.options.length;i++) {\n tmpAry[i] = new Array();\n tmpAry[i][0] = selElem.options[i].text;\n tmpAry[i][1] = selElem.options[i].value;\n }\n tmpAry.sort();\n while (selElem.options.length > 0) {\n selElem.options[0] = null;\n }\n for (var i=0;i<tmpAry.length;i++) {\n var op = new Option(tmpAry[i][0], tmpAry[i][1]);\n selElem.options[i] = op;\n }\n return;\n}\n"
},
{
"answer_id": 955802,
"author": "Marco Lazzeri",
"author_id": 105403,
"author_profile": "https://Stackoverflow.com/users/105403",
"pm_score": 2,
"selected": false,
"text": " var options = jQuery.makeArray(optionElements).\n sort(function(a,b) {\n return (a.innerHTML > b.innerHTML) ? 1 : -1;\n });\n selectElement.html(options);\n"
},
{
"answer_id": 2632714,
"author": "Geoff",
"author_id": 306277,
"author_profile": "https://Stackoverflow.com/users/306277",
"pm_score": 0,
"selected": false,
"text": "function sort_select(select) {\n var options = $A(select.options).sortBy(function(o) { return o.innerHTML });\n select.innerHTML = \"\";\n options.each(function(o) { select.insert(o); } );\n}\n sort_select( $('category-select') );\n"
},
{
"answer_id": 5199082,
"author": "Matias P.",
"author_id": 357797,
"author_profile": "https://Stackoverflow.com/users/357797",
"pm_score": 1,
"selected": false,
"text": "function sortSelect(selElem, bCase) {\n var tmpAry = new Array();\n bCase = (bCase ? true : false);\n for (var i=0;i<selElem.options.length;i++) {\n tmpAry[i] = new Array();\n tmpAry[i][0] = selElem.options[i].text;\n tmpAry[i][1] = selElem.options[i].value;\n }\n if (bCase)\n tmpAry.sort(function (a, b) {\n var ret = 0;\n var iPos = 0;\n while (ret == 0 && iPos < a.length && iPos < b.length)\n {\n ret = (String(a).toLowerCase().charCodeAt(iPos) - String(b).toLowerCase().charCodeAt(iPos));\n iPos ++;\n }\n if (ret == 0)\n {\n ret = (String(a).length - String(b).length);\n }\n return ret;\n });\n else\n tmpAry.sort();\n while (selElem.options.length > 0) {\n selElem.options[0] = null;\n }\n for (var i=0;i<tmpAry.length;i++) {\n var op = new Option(tmpAry[i][0], tmpAry[i][1]);\n selElem.options[i] = op;\n }\n return;\n }\n"
},
{
"answer_id": 5490401,
"author": "mikehowles",
"author_id": 684486,
"author_profile": "https://Stackoverflow.com/users/684486",
"pm_score": 2,
"selected": false,
"text": "function sortSelect(elem) {\n var tmpAry = [];\n // Retain selected value before sorting\n var selectedValue = elem[elem.selectedIndex].value;\n // Grab all existing entries\n for (var i=0;i<elem.options.length;i++) tmpAry.push(elem.options[i]);\n // Sort array by text attribute\n tmpAry.sort(function(a,b){ return (a.text < b.text)?-1:1; });\n // Wipe out existing elements\n while (elem.options.length > 0) elem.options[0] = null;\n // Restore sorted elements\n var newSelectedIndex = 0;\n for (var i=0;i<tmpAry.length;i++) {\n elem.options[i] = tmpAry[i];\n if(elem.options[i].value == selectedValue) newSelectedIndex = i;\n }\n elem.selectedIndex = newSelectedIndex; // Set new selected index after sorting\n return;\n}\n"
},
{
"answer_id": 6521401,
"author": "Soledad",
"author_id": 821178,
"author_profile": "https://Stackoverflow.com/users/821178",
"pm_score": 1,
"selected": false,
"text": "function sortSelect(selElem) {\n for (var i=0; i<(selElem.options.length-1); i++)\n for (var j=i+1; j<selElem.options.length; j++)\n if (parseInt(selElem.options[j].value) < parseInt(selElem.options[i].value)) {\n var dummy = new Option(selElem.options[i].text, selElem.options[i].value);\n selElem.options[i] = new Option(selElem.options[j].text, selElem.options[j].value);\n selElem.options[j] = dummy;\n }\n}\n"
},
{
"answer_id": 7466196,
"author": "Terre Porter",
"author_id": 951920,
"author_profile": "https://Stackoverflow.com/users/951920",
"pm_score": 6,
"selected": false,
"text": "$(\"#id\").html($(\"#id option\").sort(function (a, b) {\n return a.text == b.text ? 0 : a.text < b.text ? -1 : 1\n}))\n"
},
{
"answer_id": 9200431,
"author": "Matt K",
"author_id": 549141,
"author_profile": "https://Stackoverflow.com/users/549141",
"pm_score": 3,
"selected": false,
"text": "// save the selected value for sorting\nvar v = jQuery(\"#id\").val();\n\n// sort the options and select the value that was saved\nj$(\"#id\")\n .html(j$(\"#id option\").sort(function(a,b){\n return a.text == b.text ? 0 : a.text < b.text ? -1 : 1;}))\n .val(v);\n"
},
{
"answer_id": 12210886,
"author": "jerone",
"author_id": 108448,
"author_profile": "https://Stackoverflow.com/users/108448",
"pm_score": 0,
"selected": false,
"text": "// sorting;\nvar selectElm = $(\"select\"),\n selectSorted = selectElm.find(\"option\").toArray().sort(function (a, b) {\n return (a.innerHTML.toLowerCase() > b.innerHTML.toLowerCase()) ? 1 : -1;\n });\nselectElm.empty();\n$.each(selectSorted, function (key, value) {\n selectElm.append(value);\n});\n"
},
{
"answer_id": 17703167,
"author": "colinbashbash",
"author_id": 379215,
"author_profile": "https://Stackoverflow.com/users/379215",
"pm_score": 2,
"selected": false,
"text": "function SortMultiSelect_SelectedTop(slt) {\n var options =\n $(slt).find(\"option\").sort(function (a, b) {\n if (a.selected && !b.selected) return -1;\n if (!a.selected && b.selected) return 1;\n if (a.text < b.text) return -1;\n if (a.text > b.text) return 1;\n return 0;\n });\n $(slt).empty().append(options).scrollTop(0);\n}\n function SortMultiSelect(slt) {\n var options =\n $(slt).find(\"option\").sort(function (a, b) {\n if (a.text < b.text) return -1;\n if (a.text > b.text) return 1;\n return 0;\n });\n $(slt).empty().append(options).scrollTop(0);\n}\n"
},
{
"answer_id": 17704336,
"author": "MDEV",
"author_id": 763371,
"author_profile": "https://Stackoverflow.com/users/763371",
"pm_score": 1,
"selected": false,
"text": "function sortOpts(select,dir,value,trim)\n{\n value = typeof value == 'boolean' ? value : false;\n dir = ['asc','desc'].indexOf(dir) > -1 ? dir : 'asc';\n trim = typeof trim == 'boolean' ? trim : true;\n if(!select) return false;\n var opts = select.getElementsByTagName('option');\n\n var options = [];\n for(var i in opts)\n {\n if(parseInt(i)==i)\n {\n if(trim)\n {\n opts[i].innerHTML = opts[i].innerHTML.replace(/^\\s*(.*)\\s*$/,'$1');\n opts[i].value = opts[i].value.replace(/^\\s*(.*)\\s*$/,'$1');\n }\n options.push(opts[i]);\n }\n }\n options.sort(value ? sortOpts.sortVals : sortOpts.sortText);\n if(dir == 'desc') options.reverse();\n options.reverse();\n for(var i in options)\n {\n select.insertBefore(options[i],select.getElementsByTagName('option')[0]);\n }\n}\nsortOpts.sortText = function(a,b) {\n return a.innerHTML > b.innerHTML ? 1 : -1;\n}\nsortOpts.sortVals = function(a,b) {\n return a.value > b.value ? 1 : -1;\n}\n"
},
{
"answer_id": 19463371,
"author": "Tony Chiboucas",
"author_id": 1589379,
"author_profile": "https://Stackoverflow.com/users/1589379",
"pm_score": 2,
"selected": false,
"text": " sortSelect('select_object_id');\n sortSelect('select_object_id', 0);\n sortSelect(selectObject);\n sortSelect(selectObject, 0);\n sortSelect('select_object_id', 'value');\n sortSelect('select_object_id', 1);\n sortSelect(selectObject, 1);\n var myArray = [\n ['ignored0', 'ignored1', 'Z-sortme2'],\n ['ignored0', 'ignored1', 'A-sortme2'],\n ['ignored0', 'ignored1', 'C-sortme2'],\n];\n\nsortSelect(myArray,2);\n function sortSelect(selElem, sortVal) {\n\n // Checks for an object or string. Uses string as ID. \n switch(typeof selElem) {\n case \"string\":\n selElem = document.getElementById(selElem);\n break;\n case \"object\":\n if(selElem==null) return false;\n break;\n default:\n return false;\n }\n\n // Builds the options list.\n var tmpAry = new Array();\n for (var i=0;i<selElem.options.length;i++) {\n tmpAry[i] = new Array();\n tmpAry[i][0] = selElem.options[i].text;\n tmpAry[i][1] = selElem.options[i].value;\n }\n\n // allows sortVal to be optional, defaults to text.\n switch(sortVal) {\n case \"value\": // sort by value\n sortVal = 1;\n break;\n default: // sort by text\n sortVal = 0;\n }\n tmpAry.sort(function(a, b) {\n return a[sortVal] == b[sortVal] ? 0 : a[sortVal] < b[sortVal] ? -1 : 1;\n });\n\n // removes all options from the select.\n while (selElem.options.length > 0) {\n selElem.options[0] = null;\n }\n\n // recreates all options with the new order.\n for (var i=0;i<tmpAry.length;i++) {\n var op = new Option(tmpAry[i][0], tmpAry[i][1]);\n selElem.options[i] = op;\n }\n\n return true;\n}\n"
},
{
"answer_id": 20280085,
"author": "Krishna Kamat",
"author_id": 3048342,
"author_profile": "https://Stackoverflow.com/users/3048342",
"pm_score": 0,
"selected": false,
"text": "function sortlist_name()\n{\n\n var lb = document.getElementById('mylist');\n arrTexts = new Array();\n newTexts = new Array();\n txt = new Array();\n newArray =new Array();\n for(i=0; i<lb.length; i++)\n {\n arrTexts[i] = lb.options[i].text;\n }\n for(i=0;i<arrTexts.length; i++)\n {\n str = arrTexts[i].split(\" -> \");\n newTexts[i] = str[1]+' -> '+str[0];\n }\n newTexts.sort();\n for(i=0;i<newTexts.length; i++)\n {\n txt = newTexts[i].split(' -> ');\n newArray[i] = txt[1]+' -> '+txt[0];\n }\n for(i=0; i<lb.length; i++)\n {\n lb.options[i].text = newArray[i];\n lb.options[i].value = newArray[i];\n }\n}\n/***********revrse by name******/\nfunction sortreverse_name()\n{\n\n var lb = document.getElementById('mylist');\n arrTexts = new Array();\n newTexts = new Array();\n txt = new Array();\n newArray =new Array();\n for(i=0; i<lb.length; i++)\n {\n arrTexts[i] = lb.options[i].text;\n }\n for(i=0;i<arrTexts.length; i++)\n {\n str = arrTexts[i].split(\" -> \");\n newTexts[i] = str[1]+' -> '+str[0];\n }\n newTexts.reverse();\n for(i=0;i<newTexts.length; i++)\n {\n txt = newTexts[i].split(' -> ');\n newArray[i] = txt[1]+' -> '+txt[0];\n }\n for(i=0; i<lb.length; i++)\n {\n lb.options[i].text = newArray[i];\n lb.options[i].value = newArray[i];\n }\n}\n\nfunction sortlist_id() {\nvar lb = document.getElementById('mylist');\narrTexts = new Array();\n\nfor(i=0; i<lb.length; i++) {\n arrTexts[i] = lb.options[i].text;\n}\n\narrTexts.sort();\n\nfor(i=0; i<lb.length; i++) {\n lb.options[i].text = arrTexts[i];\n lb.options[i].value = arrTexts[i];\n}\n}\n\n/***********revrse by id******/\nfunction sortreverse_id() {\nvar lb = document.getElementById('mylist');\narrTexts = new Array();\n\nfor(i=0; i<lb.length; i++) {\n arrTexts[i] = lb.options[i].text;\n}\n\narrTexts.reverse();\n\nfor(i=0; i<lb.length; i++) {\n lb.options[i].text = arrTexts[i];\n lb.options[i].value = arrTexts[i];\n}\n}\n</script>\n\n\n\n ID<a href=\"javascript:sortlist_id()\"> ▲ </a> <a href=\"javascript:sortreverse_id()\">▼</a> | Name<a href=\"javascript:sortlist_name()\"> ▲ </a> <a href=\"javascript:sortreverse_name()\">▼</a><br/>\n\n<select name=mylist id=mylist size=8 style='width:150px'>\n\n<option value=\"bill\">4 -> Bill</option>\n<option value=\"carl\">5 -> Carl</option>\n<option value=\"Anton\">1 -> Anton</option>\n<option value=\"mike\">2 -> Mike</option>\n<option value=\"peter\">3 -> Peter</option>\n</select>\n<br>\n"
},
{
"answer_id": 24459808,
"author": "RPDeshaies",
"author_id": 1598891,
"author_profile": "https://Stackoverflow.com/users/1598891",
"pm_score": 1,
"selected": false,
"text": "var $options = jQuery(\"#my-dropdownlist-id > option\"); \n// or jQuery(\"#my-dropdownlist-id\").find(\"option\")\n\n$options.sort(function(a, b) {\n return a.text == b.text ? 0 : a.text < b.text ? -1 : 1\n})\n var $options = jQuery(dropDownList).find(\"option\");\n\nvar reAlpha = /[^a-zA-Z]/g;\nvar reNumeric = /[^0-9]/g;\n$options.sort(function AlphaNumericSort($a,$b) {\n var a = $a.text;\n var b = $b.text;\n var aAlpha = a.replace(reAlpha, \"\");\n var bAlpha = b.replace(reAlpha, \"\");\n if(aAlpha === bAlpha) {\n var aNumeric = parseInt(a.replace(reNumeric, \"\"), 10);\n var bNumeric = parseInt(b.replace(reNumeric, \"\"), 10);\n return aNumeric === bNumeric ? 0 : aNumeric > bNumeric ? 1 : -1;\n } else {\n return aAlpha > bAlpha ? 1 : -1;\n }\n})\n"
},
{
"answer_id": 27825253,
"author": "Arijit Basu",
"author_id": 4245458,
"author_profile": "https://Stackoverflow.com/users/4245458",
"pm_score": 1,
"selected": false,
"text": "function call() {\n var x = document.getElementById(\"mySelect\");\n var optionVal = new Array();\n\n for (i = 0; i < x.length; i++) {\n optionVal.push(x.options[i].text);\n }\n\n for (i = x.length; i >= 0; i--) {\n x.remove(i);\n }\n\n optionVal.sort();\n\n for (var i = 0; i < optionVal.length; i++) {\n var opt = optionVal[i];\n var el = document.createElement(\"option\");\n el.textContent = opt;\n el.value = opt;\n x.appendChild(el);\n }\n}\n"
},
{
"answer_id": 31652966,
"author": "Joel",
"author_id": 3689517,
"author_profile": "https://Stackoverflow.com/users/3689517",
"pm_score": 0,
"selected": false,
"text": "function sortItems(c) {\nvar options = c.options;\nArray.prototype.sort.call(options, function (a, b) {\n var aText = a.text.toLowerCase();\n var bText = b.text.toLowerCase();\n if (aText < bText) {\n return -1;\n } else if (aText > bText) {\n return 1;\n } else {\n return 0;\n }\n});\n}\n\nsortItems(document.getElementById('lstALL'));\n"
},
{
"answer_id": 56711000,
"author": "protoEvangelion",
"author_id": 6502003,
"author_profile": "https://Stackoverflow.com/users/6502003",
"pm_score": 3,
"selected": false,
"text": "const optionNodes = Array.from(selectNode.children);\nconst comparator = new Intl.Collator(lang.slice(0, 2)).compare;\n\noptionNodes.sort((a, b) => comparator(a.textContent, b.textContent));\noptionNodes.forEach((option) => selectNode.appendChild(option));\n"
},
{
"answer_id": 57998034,
"author": "Jordan Daigle",
"author_id": 6126481,
"author_profile": "https://Stackoverflow.com/users/6126481",
"pm_score": 0,
"selected": false,
"text": "/**\n * Sorting options \n * and optgroups\n * \n * @param selElem select element\n * @param optionBeforeGroup ?bool if null ignores, if true option appear before group else option appear after group\n */\nfunction sortSelect(selElem, optionBeforeGroup = null) {\n let initialValue = selElem.tagName === \"SELECT\" ? selElem.value : null; \n let allChildrens = Array.prototype.slice.call(selElem.childNodes);\n let childrens = [];\n\n for (let i = 0; i < allChildrens.length; i++) {\n if (allChildrens[i].parentNode === selElem && [\"OPTGROUP\", \"OPTION\"].includes(allChildrens[i].tagName||\"\")) {\n if (allChildrens[i].tagName == \"OPTGROUP\") {\n sortSelect(allChildrens[i]);\n }\n childrens.push(allChildrens[i]);\n }\n }\n\n childrens.sort(function(a, b){\n let x = a.tagName == \"OPTGROUP\" ? a.getAttribute(\"label\") : a.innerHTML;\n let y = b.tagName == \"OPTGROUP\" ? b.getAttribute(\"label\") : b.innerHTML;\n x = typeof x === \"undefined\" || x === null ? \"\" : (x+\"\");\n y = typeof y === \"undefined\" || y === null ? \"\" : (y+\"\");\n\n if (optionBeforeGroup === null) {\n if (x.toLowerCase().trim() < y.toLowerCase().trim()) {return -1;}\n if (x.toLowerCase().trim() > y.toLowerCase().trim()) {return 1;}\n } else if (optionBeforeGroup === true) {\n if ((a.tagName == \"OPTION\" && b.tagName == \"OPTGROUP\") || x.toLowerCase().trim() < y.toLowerCase().trim()) {return -1;}\n if ((a.tagName == \"OPTGROUP\" && b.tagName == \"OPTION\") || x.toLowerCase().trim() > y.toLowerCase().trim()) {return 1;}\n } else if (optionBeforeGroup === false) {\n if ((a.tagName == \"OPTGROUP\" && b.tagName == \"OPTION\") || x.toLowerCase().trim() < y.toLowerCase().trim()) {return -1;}\n if ((a.tagName == \"OPTION\" && b.tagName == \"OPTGROUP\") || x.toLowerCase().trim() > y.toLowerCase().trim()) {return 1;}\n }\n return 0;\n });\n\n if (optionBeforeGroup !== null) {\n childrens.sort(function(a, b){\n if (optionBeforeGroup === true) {\n if (a.tagName == \"OPTION\" && b.tagName == \"OPTGROUP\") {return -1;}\n if (a.tagName == \"OPTGROUP\" && b.tagName == \"OPTION\") {return 1;}\n } else {\n if (a.tagName == \"OPTGROUP\" && b.tagName == \"OPTION\") {return -1;}\n if (a.tagName == \"OPTION\" && b.tagName == \"OPTGROUP\") {return 1;}\n }\n return 0;\n });\n }\n\n selElem.innerHTML = \"\";\n for (let i = 0; i < childrens.length; i++) {\n selElem.appendChild(childrens[i]);\n }\n\n if (selElem.tagName === \"SELECT\") {\n selElem.value = initialValue;\n }\n}\n"
},
{
"answer_id": 67861236,
"author": "Bruno L.",
"author_id": 9160102,
"author_profile": "https://Stackoverflow.com/users/9160102",
"pm_score": 0,
"selected": false,
"text": "/** Check if a string can be parsed as a number. */\nfunction isNumber(n) { return !isNaN(parseFloat(n)) && !isNaN(n - 0) };\n\n/** Sort options of HTML elements. */\nfunction sortOptions(selectElement, exceptFirstOpt=false) {\n\n // List of options.\n var options = selectElement.options;\n // If empty list, do nothing.\n if(!options || options.length==0) return;\n\n // Array.\n var optionsArray = [];\n for (var i = (exceptFirstOpt ? 1 : 0); i < options.length; i++)\n optionsArray.push(options[i]);\n // Sort.\n optionsArray = optionsArray.sort(function (a, b) { \n let v1 = a.innerHTML.toLowerCase();\n let v2 = b.innerHTML.toLowerCase();\n if((v1==undefined || v1 == '') && (v2==undefined || v2 == ''))\n return 0;\n else if(v1==undefined || v1.trim() == '') return 1;\n else if(v2==undefined || v2.trim() == '') return -1;\n\n // If number.\n if(isNumber(v1) && isNumber(v2))\n return parseFloat(v1)>parseFloat(v2);\n\n return v1.localeCompare(v2); \n });\n\n // Update options.\n for (var i = 0; i <= optionsArray.length; i++) \n options[i + (exceptFirstOpt ? 1 : 0)] = optionsArray[i];\n // First option selected by default.\n options[0].selected = true;\n}\n"
},
{
"answer_id": 73379064,
"author": "Nathan Sutherland",
"author_id": 4367909,
"author_profile": "https://Stackoverflow.com/users/4367909",
"pm_score": 0,
"selected": false,
"text": "let selectOrDatalist = document.querySelector('#sdl');\n/* optional added option\n selectOrDatalist.insertAdjacentHTML('afterbegin', `<option id=\"${id}\" value=\"${foo}\">${bar}</option>` );\n*/\nselectOrDatalist.append(...[...selectOrDatalist.options].sort((a,b) => a.value.localeCompare(b.value)));\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13370/"
] |
278,090
|
<p>What is a good way to create and read an OpenOffice spreadsheet in Perl?</p>
|
[
{
"answer_id": 2780194,
"author": "Chloe",
"author_id": 148844,
"author_profile": "https://Stackoverflow.com/users/148844",
"pm_score": 1,
"selected": false,
"text": "use Win32::OLE;\n\nWin32::OLE->Option(Warn => 3); # Turn on warnings for easier debugging\n\n#Win32::OLE->GetActiveObject\n# Get the currently running process or create a new one\n$objServiceManager = Win32::OLE->GetActiveObject(\"com.sun.star.ServiceManager\") || Win32::OLE->new(\"com.sun.star.ServiceManager\") || die \"CreateObject: $!\"; \n\n$Stardesktop = $objServiceManager->createInstance(\"com.sun.star.frame.Desktop\");\n\n# $Stardesktop->terminate();exit; # will kill ALL OpenOffice docs!!!\n# Doc = StarDesktop.loadComponentFromURL(sURL, \"_default\", 0, aMediaDesc)\n\n$propValue[0] = $objServiceManager->Bridge_GetStruct(\"com.sun.star.beans.PropertyValue\");\n$propValue[0]->{Name} = \"Hidden\"; # This does not work!\n$propValue[0]->{Value} = 1;\n\n#Open the file and update its links if you have DDE links in your file\n$propValue[1] = $objServiceManager->Bridge_GetStruct(\"com.sun.star.beans.PropertyValue\");\n$propValue[1]->{Name} = \"UpdateDocMode\";\n$propValue[1]->{Value} = 3; # com.sun.star.document.UpdateDocMode.FULL_UPDATE\n\n$calc = $Stardesktop->loadComponentfromUrl(\"file:///C:/Documents and Settings/Chloe/Desktop/MyFile.ods\", \"MyCalc\", 0, \\@propValue );\n# load a new blank spreadsheet\n$calc = $Stardesktop->loadComponentFromURL( \"private:factory/scalc\", \"_blank\", 0, [] );\n\n# How to hide, as loading the document hidden does not work.\n$calc->getCurrentController->getFrame->getContainerWindow()->setVisible(0);\n\n$oSheet = $calc->getSheets->getByIndex(0);\n\n# how to execute an UNO command, such as menu items\n# http://wiki.services.openoffice.org/wiki/Framework/Article/OpenOffice.org_2.x_Commands\n$frame = $calc->getCurrentController->getFrame;\n$dispatchHelper = $objServiceManager->createInstance(\"com.sun.star.frame.DispatchHelper\");\n$dispatchHelper->executeDispatch(\n $frame, \n \".uno:CalculateHard\",\n #\".uno:UpdateAll\", \n #\".uno:UpdateAllLinks\", \n #\".uno:DataAreaRefresh\",\n \"_self\",\n 0,\n []\n);\n\n\n$row = 5;\n$cellValue = $oSheet->getCellByPosition(0, $row)->getString(); # get a cell value\n\n# sort in decending order\n$range = $oSheet->getCellRangeByName(\"A1:P$row\");\n$fields[0] = $objServiceManager->Bridge_GetStruct(\"com.sun.star.table.TableSortField\");\n$fields[0]->{Field} = 7; # column number\n$fields[0]->{IsAscending} = 0;\n$unoWrap = $objServiceManager->Bridge_GetValueObject;\n$unoWrap->Set (\"[]com.sun.star.table.TableSortField\", \\@fields);\n$sortDx = $range->createSortDescriptor();\n$sortDx->[0]->{Name} = \"ContainsHeader\";\n$sortDx->[0]->{Value} = 1;\n$sortDx->[3]->{Name} = \"SortFields\";\n$sortDx->[3]->{Value} = $unoWrap;\n#$sortDx->[3]->{Value} = \\@fields; # You would think this would work? It doesn't.\n$range->sort($sortDx);\n\n\n# create a new sheet to paste to\n$calc->getSheets->insertNewByName(\"NewSheet\", 1 );\n$sheet2 = $calc->getSheets->getByIndex(1);\n$calc->CurrentController->Select($sheet2);\n\n# copy row\n$pasteHere = $sheet2->getCellByPosition(0, 0)->CellAddress;\n$copyRange = $oSheet->getCellRangeByName(\"A1:Q1\")->RangeAddress;\n$oSheet->copyRange($pasteHere, $copyRange);\n\n$cellValue = $sheet2->getCellByPosition(16, $row)->getValue()); # get cell value as integer\n$date = $sheet2->getCellByPosition(5, $row)->getString(); # must get dates as strings\n\n$calc->getCurrentController->getFrame->getContainerWindow()->setVisible(1); # set visible\n$calc->close(0); # close program window\n#print Win32::OLE->LastError, \"\\n\";\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278090",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
278,112
|
<p>Is there any c library to get a video from the webcam on linux?</p>
|
[
{
"answer_id": 4025769,
"author": "karlphillip",
"author_id": 176769,
"author_profile": "https://Stackoverflow.com/users/176769",
"pm_score": 4,
"selected": false,
"text": "#include <stdio.h>\n#include \"cv.h\"\n#include \"highgui.h\"\n\n\ntypedef IplImage* (*callback_prototype)(IplImage*);\n\n\n/* \n * make_it_gray: custom callback to convert a colored frame to its grayscale version.\n * Remember that you must deallocate the returned IplImage* yourself after calling this function.\n */\nIplImage* make_it_gray(IplImage* frame)\n{\n // Allocate space for a new image\n IplImage* gray_frame = 0;\n gray_frame = cvCreateImage(cvSize(frame->width, frame->height), frame->depth, 1);\n if (!gray_frame)\n {\n fprintf(stderr, \"!!! cvCreateImage failed!\\n\" );\n return NULL;\n }\n\n cvCvtColor(frame, gray_frame, CV_RGB2GRAY);\n return gray_frame; \n}\n\n/*\n * process_video: retrieves frames from camera and executes a callback to do individual frame processing.\n * Keep in mind that if your callback takes too much time to execute, you might loose a few frames from \n * the camera.\n */\nvoid process_video(callback_prototype custom_cb)\n{ \n // Initialize camera\n CvCapture *capture = 0;\n capture = cvCaptureFromCAM(-1);\n if (!capture) \n {\n fprintf(stderr, \"!!! Cannot open initialize webcam!\\n\" );\n return;\n }\n\n // Create a window for the video \n cvNamedWindow(\"result\", CV_WINDOW_AUTOSIZE);\n\n IplImage* frame = 0;\n char key = 0;\n while (key != 27) // ESC\n { \n frame = cvQueryFrame(capture);\n if(!frame) \n {\n fprintf( stderr, \"!!! cvQueryFrame failed!\\n\" );\n break;\n }\n\n // Execute callback on each frame\n IplImage* processed_frame = (*custom_cb)(frame);\n\n // Display processed frame\n cvShowImage(\"result\", processed_frame);\n\n // Release resources\n cvReleaseImage(&processed_frame);\n\n // Exit when user press ESC\n key = cvWaitKey(10);\n }\n\n // Free memory\n cvDestroyWindow(\"result\");\n cvReleaseCapture(&capture);\n}\n\nint main( int argc, char **argv )\n{\n process_video(make_it_gray);\n\n return 0;\n}\n"
},
{
"answer_id": 40561598,
"author": "Ciro Santilli OurBigBook.com",
"author_id": 895245,
"author_profile": "https://Stackoverflow.com/users/895245",
"pm_score": 3,
"selected": false,
"text": "v4l2 ./v4l2grab outNNN.ppm ./v4l2gl gluLookAt sudo apt-get install libv4l-dev\nsudo apt-get build-dep libv4l-dev\ngit clone git://linuxtv.org/v4l-utils.git\ncd v4l-utils\n# Matching the installed version of dpkg -s libv4l-dev\ngit checkout v4l-utils-1.10.0\n./bootstrap.sh\n./configure\nmake\n# TODO: fails halfway, but it does not matter for us now.\ncd contrib/tests\nmake\n \"\" <> config.h ./v4l2grab gcc v4l2grab.c -lv4l2\n./a.out\n /* V4L2 video picture grabber\nCopyright (C) 2009 Mauro Carvalho Chehab <mchehab@infradead.org>\n\nThis program is free software; you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation version 2 of the License.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n*/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <fcntl.h>\n#include <errno.h>\n#include <sys/ioctl.h>\n#include <sys/types.h>\n#include <sys/time.h>\n#include <sys/mman.h>\n#include <linux/videodev2.h>\n#include <libv4l2.h>\n\n#define CLEAR(x) memset(&(x), 0, sizeof(x))\n\nstruct buffer {\n void *start;\n size_t length;\n};\n\nstatic void xioctl(int fh, int request, void *arg)\n{\n int r;\n\n do {\n r = v4l2_ioctl(fh, request, arg);\n } while (r == -1 && ((errno == EINTR) || (errno == EAGAIN)));\n\n if (r == -1) {\n fprintf(stderr, \"error %d, %s\\\\n\", errno, strerror(errno));\n exit(EXIT_FAILURE);\n }\n}\n\nint main(int argc, char **argv)\n{\n struct v4l2_format fmt;\n struct v4l2_buffer buf;\n struct v4l2_requestbuffers req;\n enum v4l2_buf_type type;\n fd_set fds;\n struct timeval tv;\n int r, fd = -1;\n unsigned int i, n_buffers;\n char *dev_name = \"/dev/video0\";\n char out_name[256];\n FILE *fout;\n struct buffer *buffers;\n\n fd = v4l2_open(dev_name, O_RDWR | O_NONBLOCK, 0);\n if (fd < 0) {\n perror(\"Cannot open device\");\n exit(EXIT_FAILURE);\n }\n\n CLEAR(fmt);\n fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;\n fmt.fmt.pix.width = 640;\n fmt.fmt.pix.height = 480;\n fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_RGB24;\n fmt.fmt.pix.field = V4L2_FIELD_INTERLACED;\n xioctl(fd, VIDIOC_S_FMT, &fmt);\n if (fmt.fmt.pix.pixelformat != V4L2_PIX_FMT_RGB24) {\n printf(\"Libv4l didn't accept RGB24 format. Can't proceed.\\\\n\");\n exit(EXIT_FAILURE);\n }\n if ((fmt.fmt.pix.width != 640) || (fmt.fmt.pix.height != 480))\n printf(\"Warning: driver is sending image at %dx%d\\\\n\",\n fmt.fmt.pix.width, fmt.fmt.pix.height);\n\n CLEAR(req);\n req.count = 2;\n req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;\n req.memory = V4L2_MEMORY_MMAP;\n xioctl(fd, VIDIOC_REQBUFS, &req);\n\n buffers = calloc(req.count, sizeof(*buffers));\n for (n_buffers = 0; n_buffers < req.count; ++n_buffers) {\n CLEAR(buf);\n\n buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;\n buf.memory = V4L2_MEMORY_MMAP;\n buf.index = n_buffers;\n\n xioctl(fd, VIDIOC_QUERYBUF, &buf);\n\n buffers[n_buffers].length = buf.length;\n buffers[n_buffers].start = v4l2_mmap(NULL, buf.length,\n PROT_READ | PROT_WRITE, MAP_SHARED,\n fd, buf.m.offset);\n\n if (MAP_FAILED == buffers[n_buffers].start) {\n perror(\"mmap\");\n exit(EXIT_FAILURE);\n }\n }\n\n for (i = 0; i < n_buffers; ++i) {\n CLEAR(buf);\n buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;\n buf.memory = V4L2_MEMORY_MMAP;\n buf.index = i;\n xioctl(fd, VIDIOC_QBUF, &buf);\n }\n type = V4L2_BUF_TYPE_VIDEO_CAPTURE;\n\n xioctl(fd, VIDIOC_STREAMON, &type);\n for (i = 0; i < 20; i++) {\n do {\n FD_ZERO(&fds);\n FD_SET(fd, &fds);\n\n /* Timeout. */\n tv.tv_sec = 2;\n tv.tv_usec = 0;\n\n r = select(fd + 1, &fds, NULL, NULL, &tv);\n } while ((r == -1 && (errno = EINTR)));\n if (r == -1) {\n perror(\"select\");\n return errno;\n }\n\n CLEAR(buf);\n buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;\n buf.memory = V4L2_MEMORY_MMAP;\n xioctl(fd, VIDIOC_DQBUF, &buf);\n\n sprintf(out_name, \"out%03d.ppm\", i);\n fout = fopen(out_name, \"w\");\n if (!fout) {\n perror(\"Cannot open image\");\n exit(EXIT_FAILURE);\n }\n fprintf(fout, \"P6\\n%d %d 255\\n\",\n fmt.fmt.pix.width, fmt.fmt.pix.height);\n fwrite(buffers[buf.index].start, buf.bytesused, 1, fout);\n fclose(fout);\n\n xioctl(fd, VIDIOC_QBUF, &buf);\n }\n\n type = V4L2_BUF_TYPE_VIDEO_CAPTURE;\n xioctl(fd, VIDIOC_STREAMOFF, &type);\n for (i = 0; i < n_buffers; ++i)\n v4l2_munmap(buffers[i].start, buffers[i].length);\n v4l2_close(fd);\n\n return 0;\n}\n #ifndef COMMON_V4L2_H\n#define COMMON_V4L2_H\n\n#include <errno.h>\n#include <fcntl.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys/ioctl.h>\n#include <sys/mman.h>\n#include <sys/time.h>\n#include <sys/types.h>\n\n#include <libv4l2.h>\n#include <linux/videodev2.h>\n\n#define COMMON_V4L2_CLEAR(x) memset(&(x), 0, sizeof(x))\n\ntypedef struct {\n void *start;\n size_t length;\n} CommonV4l2_Buffer;\n\ntypedef struct {\n int fd;\n CommonV4l2_Buffer *buffers;\n struct v4l2_buffer buf;\n unsigned int n_buffers;\n} CommonV4l2;\n\nvoid CommonV4l2_xioctl(int fh, unsigned long int request, void *arg)\n{\n int r;\n do {\n r = v4l2_ioctl(fh, request, arg);\n } while (r == -1 && ((errno == EINTR) || (errno == EAGAIN)));\n if (r == -1) {\n fprintf(stderr, \"error %d, %s\\n\", errno, strerror(errno));\n exit(EXIT_FAILURE);\n }\n}\n\nvoid CommonV4l2_init(CommonV4l2 *this, char *dev_name, unsigned int x_res, unsigned int y_res) {\n enum v4l2_buf_type type;\n struct v4l2_format fmt;\n struct v4l2_requestbuffers req;\n unsigned int i;\n\n this->fd = v4l2_open(dev_name, O_RDWR | O_NONBLOCK, 0);\n if (this->fd < 0) {\n perror(\"Cannot open device\");\n exit(EXIT_FAILURE);\n }\n COMMON_V4L2_CLEAR(fmt);\n fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;\n fmt.fmt.pix.width = x_res;\n fmt.fmt.pix.height = y_res;\n fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_RGB24;\n fmt.fmt.pix.field = V4L2_FIELD_INTERLACED;\n CommonV4l2_xioctl(this->fd, VIDIOC_S_FMT, &fmt);\n if ((fmt.fmt.pix.width != x_res) || (fmt.fmt.pix.height != y_res))\n printf(\"Warning: driver is sending image at %dx%d\\n\",\n fmt.fmt.pix.width, fmt.fmt.pix.height);\n COMMON_V4L2_CLEAR(req);\n req.count = 2;\n req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;\n req.memory = V4L2_MEMORY_MMAP;\n CommonV4l2_xioctl(this->fd, VIDIOC_REQBUFS, &req);\n this->buffers = calloc(req.count, sizeof(*this->buffers));\n for (this->n_buffers = 0; this->n_buffers < req.count; ++this->n_buffers) {\n COMMON_V4L2_CLEAR(this->buf);\n this->buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;\n this->buf.memory = V4L2_MEMORY_MMAP;\n this->buf.index = this->n_buffers;\n CommonV4l2_xioctl(this->fd, VIDIOC_QUERYBUF, &this->buf);\n this->buffers[this->n_buffers].length = this->buf.length;\n this->buffers[this->n_buffers].start = v4l2_mmap(NULL, this->buf.length,\n PROT_READ | PROT_WRITE, MAP_SHARED, this->fd, this->buf.m.offset);\n if (MAP_FAILED == this->buffers[this->n_buffers].start) {\n perror(\"mmap\");\n exit(EXIT_FAILURE);\n }\n }\n for (i = 0; i < this->n_buffers; ++i) {\n COMMON_V4L2_CLEAR(this->buf);\n this->buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;\n this->buf.memory = V4L2_MEMORY_MMAP;\n this->buf.index = i;\n CommonV4l2_xioctl(this->fd, VIDIOC_QBUF, &this->buf);\n }\n type = V4L2_BUF_TYPE_VIDEO_CAPTURE;\n CommonV4l2_xioctl(this->fd, VIDIOC_STREAMON, &type);\n}\n\nvoid CommonV4l2_update_image(CommonV4l2 *this) {\n fd_set fds;\n int r;\n struct timeval tv;\n\n do {\n FD_ZERO(&fds);\n FD_SET(this->fd, &fds);\n\n /* Timeout. */\n tv.tv_sec = 2;\n tv.tv_usec = 0;\n\n r = select(this->fd + 1, &fds, NULL, NULL, &tv);\n } while ((r == -1 && (errno == EINTR)));\n if (r == -1) {\n perror(\"select\");\n exit(EXIT_FAILURE);\n }\n COMMON_V4L2_CLEAR(this->buf);\n this->buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;\n this->buf.memory = V4L2_MEMORY_MMAP;\n CommonV4l2_xioctl(this->fd, VIDIOC_DQBUF, &this->buf);\n CommonV4l2_xioctl(this->fd, VIDIOC_QBUF, &this->buf);\n}\n\nchar * CommonV4l2_get_image(CommonV4l2 *this) {\n return ((char *)this->buffers[this->buf.index].start);\n}\n\nsize_t CommonV4l2_get_image_size(CommonV4l2 *this) {\n return this->buffers[this->buf.index].length;\n}\n\nvoid CommonV4l2_deinit(CommonV4l2 *this) {\n unsigned int i;\n enum v4l2_buf_type type;\n\n type = V4L2_BUF_TYPE_VIDEO_CAPTURE;\n CommonV4l2_xioctl(this->fd, VIDIOC_STREAMOFF, &type);\n for (i = 0; i < this->n_buffers; ++i)\n v4l2_munmap(this->buffers[i].start, this->buffers[i].length);\n v4l2_close(this->fd);\n free(this->buffers);\n}\n\n#endif\n #include <stdio.h>\n#include <stdlib.h>\n\n#include \"common_v4l2.h\"\n\nstatic void save_ppm(\n unsigned int i,\n unsigned int x_res,\n unsigned int y_res,\n size_t data_lenght,\n char *data\n) {\n FILE *fout;\n char out_name[256];\n\n sprintf(out_name, \"out%03d.ppm\", i);\n fout = fopen(out_name, \"w\");\n if (!fout) {\n perror(\"error: fopen\");\n exit(EXIT_FAILURE);\n }\n fprintf(fout, \"P6\\n%d %d 255\\n\", x_res, y_res);\n fwrite(data, data_lenght, 1, fout);\n fclose(fout);\n}\n\nint main(void) {\n CommonV4l2 common_v4l2;\n char *dev_name = \"/dev/video0\";\n struct buffer *buffers;\n unsigned int\n i,\n x_res = 640,\n y_res = 480\n ;\n\n CommonV4l2_init(&common_v4l2, dev_name, x_res, y_res);\n for (i = 0; i < 20; i++) {\n CommonV4l2_update_image(&common_v4l2);\n save_ppm(\n i,\n x_res,\n y_res,\n CommonV4l2_get_image_size(&common_v4l2),\n CommonV4l2_get_image(&common_v4l2)\n );\n }\n CommonV4l2_deinit(&common_v4l2);\n return EXIT_SUCCESS;\n}\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
278,121
|
<p>Its my understanding that the recommended approach to localization in WPF is to use the LocBaml tool to extract the localizable items into e.g. a csv file, translate the items into the desired language and regenerate a new sattelite assembly from this csv file. However from my experiments this seems to conflict with the generation of satellite assemblies from resources.resx files since neither is combining the resources into the single resource file but simply override any existing satellite assembly.</p>
<p>Is there a recommended approach (or even better, an existing tool) for doing a "merge" of output from LocBaml /generate and the output of running resgen on a resources.resx file (which is by default done by VS on builds). Are anybody out there tackling the same issues?</p>
|
[
{
"answer_id": 992410,
"author": "Rick Strahl",
"author_id": 11197,
"author_profile": "https://Stackoverflow.com/users/11197",
"pm_score": 3,
"selected": true,
"text": "LocBaml.exe /generate ..\\obj\\WpfLocalization.g.en-US.resources \n /trans:Res\\de.csv /out:de /culture:de\n\nREM Combine resource files w/ Assembly Linker\nal /template:WpfLocalization.exe \n /embed:de\\WpfLocalization.g.de.resources \n /embed:..\\..\\obj\\WpfLocalization.Properties.Resources.de.resources \n /culture:de /out:de\\WpfLocalization.resources.dll\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9222/"
] |
278,122
|
<p>We're using Prototype for all of our Ajax request handling and to keep things simple we simple render HTML content which is then assigned to the appropriate div using the following function:</p>
<pre><code>function ajaxModify(controller, parameters, div_id)
{
var div = $(div_id);
var request = new Ajax.Request
(
controller,
{
method: "post",
parameters: parameters,
onSuccess: function(data) {
div.innerHTML = data.responseText;
},
onFailure: function() {
div.innerHTML = "Information Temporarily Unavailable";
}
}
);
}
</code></pre>
<p>However, I occasionally need to execute Javascript within the HTML response and this method appears incapable of doing that.</p>
<p>I'm trying to keep the list of functions for Ajax calls to a minimum for a number of reasons so if there is a way to modify the existing function without breaking everywhere that it is currently being used or a way to modify the HTML response that will cause any embedded javascript to execute that would great.</p>
<p>By way of note, I've already tried adding "evalJS : 'force'" to the function to see what it would do and it didn't help things any.</p>
|
[
{
"answer_id": 278138,
"author": "Diodeus - James MacFarlane",
"author_id": 12579,
"author_profile": "https://Stackoverflow.com/users/12579",
"pm_score": 5,
"selected": true,
"text": "evalScripts:true\n"
},
{
"answer_id": 278139,
"author": "Kon",
"author_id": 22303,
"author_profile": "https://Stackoverflow.com/users/22303",
"pm_score": 0,
"selected": false,
"text": "div.innerHTML = \"<div onclick='someOtherFunctionTocall();'>\";\n"
},
{
"answer_id": 278152,
"author": "Jeroen Heijmans",
"author_id": 30748,
"author_profile": "https://Stackoverflow.com/users/30748",
"pm_score": 1,
"selected": false,
"text": "evalScripts: true"
},
{
"answer_id": 2085392,
"author": "Ray Chakrit",
"author_id": 253112,
"author_profile": "https://Stackoverflow.com/users/253112",
"pm_score": 0,
"selected": false,
"text": "div.innerHTML=...ajax response text...\nmy_function()\n function my_function() {\n function_1()\n ...\n}\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278122",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20178/"
] |
278,132
|
<p>I need to impersonate myself as a domain user in a ASP.NET application running on VMWare machine. Since the VMWare machine is not itself in the domain, ASP.NET is unable to resolve the user token (specified in web.config). Is there a way to do that?</p>
<p>Thanks in advance,
Petr</p>
|
[
{
"answer_id": 278434,
"author": "Ricardo Villamil",
"author_id": 19314,
"author_profile": "https://Stackoverflow.com/users/19314",
"pm_score": 2,
"selected": true,
"text": "using System;\nusing System.Security.Principal;\n\n/// <summary>\n/// Changes the security context the application runs under.\n/// </summary>\npublic class ImpersonateHelper : IDisposable\n{\n [System.Runtime.InteropServices.DllImport(\"Kernel32\")]\n private extern static Boolean CloseHandle(IntPtr handle);\n\n private IntPtr _token = IntPtr.Zero;\n private WindowsImpersonationContext _impersonatedUser = null;\n\n public IntPtr Token\n {\n get { return _token; }\n set { _token = value; }\n }\n\n public ImpersonateHelper(IntPtr token)\n {\n _token = token;\n }\n\n /// <summary>\n /// Switch the user to that set by the Token property\n /// </summary>\n public void Impersonate()\n {\n if (_token == IntPtr.Zero)\n _token = WindowsIdentity.GetCurrent().Token;\n\n _impersonatedUser = WindowsIdentity.Impersonate(_token);\n }\n\n /// <summary>\n /// Revert to the identity (user) before Impersonate() was called\n /// </summary>\n public void Undo()\n {\n if (_impersonatedUser != null)\n _impersonatedUser.Undo();\n }\n\n #region IDisposable Members\n private bool _isDisposed;\n\n public void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n protected virtual void Dispose(bool disposing)\n {\n if (!_isDisposed)\n {\n if (disposing)\n {\n if (_impersonatedUser != null)\n _impersonatedUser.Dispose();\n\n }\n CloseHandle(_token);\n _token = IntPtr.Zero;\n }\n _isDisposed = true;\n }\n\n ~ImpersonateHelper()\n {\n Dispose(false);\n }\n #endregion\n}\n //Run task as the impersonated user and not as NETWORKSERVICE or ASPNET (in IIS5)\ntry{\n impersonate.Impersonate();\n //Do work that needs to run as domain user here...\n}\nfinally\n{\n //Revert impersonation to NETWORKSERVICE or ASPNET\n if (impersonate != null)\n {\n impersonate.Undo();\n impersonate.Dispose();\n }\n}\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15497/"
] |
278,136
|
<p>and to spice things a bit , what is the best approach for globalization in Asp.net Mvc App </p>
|
[
{
"answer_id": 278179,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 0,
"selected": false,
"text": "\\Views\\Home\\*.asp\n\\Views\\Admin\\*.asp\n\\Views\\Products\\*.asp\n \\en\\Views\\Home\\*.asp\n\\en\\Views\\Admin\\*.asp\n\\en\\Views\\Products\\*.asp\n\\de\\Views\\Home\\*.asp\n\\de\\Views\\Admin\\*.asp\n\\de\\Views\\Products\\*.asp\n\\es\\Views\\Home\\*.asp\n\\es\\Views\\Admin\\*.asp\n\\es\\Views\\Products\\*.asp\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1409636/"
] |
278,137
|
<p>I am using some custom controls one of which is a tooltip controller that can display images, so I am using th ebelow code to instantiate it:</p>
<pre><code>Image newImage = Image.FromFile(imagePath);
e.ToolTipImage = newImage;
</code></pre>
<p>obviously could inline it but just testing at the moment. The trouble is the image is sometimes the wrong size, is there a way to set the display size. The only way I can currently see is editing the image using GDI+ or something like that. Seems like a lot of extra processing when I am only wanting to adjust display size not affect the actual image.</p>
|
[
{
"answer_id": 278166,
"author": "John Rudy",
"author_id": 14048,
"author_profile": "https://Stackoverflow.com/users/14048",
"pm_score": 2,
"selected": true,
"text": "Image newImage = Image.FromFile(myFilePath);\nSize outputSize = new Size(200, 200);\nBitmap backgroundBitmap = new Bitmap(outputSize.Width, outputSize.Height);\nusing (Bitmap tempBitmap = new Bitmap(newImage))\n{\n using (Graphics g = Graphics.FromImage(backgroundBitmap))\n {\n g.InterpolationMode = InterpolationMode.HighQualityBicubic;\n // Get the set of points that determine our rectangle for resizing.\n Point[] corners = {\n new Point(0, 0),\n new Point(backgroundBitmap.Width, 0),\n new Point(0, backgroundBitmap.Height)\n };\n g.DrawImage(tempBitmap, corners);\n }\n}\nthis.BackgroundImage = backgroundBitmap;\n using System.Drawing System.Drawing.Drawing2D"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278137",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16989/"
] |
278,140
|
<p>Is there a client event that I can use for when a DropDownList's data has been loaded/bound onto the control? I need to trigger event on their side when this happens.</p>
<hr>
<p>Basically, I am trying to lock out the controls while the data is being loaded as if there is a slowdown (not uncommon) a user can start inputting data and then lose focus as they are typing. </p>
<p>I tried doing this in the tags but the methods located there seem to stop working after the first postback! (Any help there would be greatly appreciated). As a workaround I tried attaching the events to the elements themselves and while this works for locking, using the onchange event, I am unable to unlock it upon the data successfully loading!</p>
<p>Any ideas? Thanks for the answers so far :) </p>
|
[
{
"answer_id": 635985,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": " var boolDoPostBack = false;\n\n if (__doPostBack)\n {\n // save a reference to the original __doPostBack\n var __oldDoPostBack = __doPostBack;\n\n //replace __doPostBack with another function\n __doPostBack = AlwaysFireBeforeFormSubmit;\n }\n function setdopostback()\n {\n boolDoPostBack = true;\n }\n function AlwaysFireBeforeFormSubmit (eventTarget, eventArgument)\n {\n var x= document.readyState\n\n if (x != \"complete\")\n {\n if (x == \"loading\" || x == \"interactive\" || x == \"unitialized\" || x == \"loaded\")\n { \n //do nothing with IE postback\n }\n else if (!boolDoPostBack)\n {\n //do nothing with FireFox postback\n }\n else\n {\n //alert('Allow Postback 1');\n return __oldDoPostBack (eventTarget, eventArgument);\n }\n }\n else\n {\n //alert('Allow Postback 2');\n return __oldDoPostBack (eventTarget, eventArgument);\n } \n }\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35454/"
] |
278,149
|
<p>We have an application that downloads some files in the background. Our application pops up when an Internet connection is made, and after prompting the user to accept the downloads, we'd like to switch back to the home screen while we do our stuff.</p>
<p>We can't work out how to do to this. We can emulate pressing "back" a few times, which sometimes works, but where you end up depends on what the user was doing when the Internet connection happened.</p>
<p>So, can someone provide pointers to how to do this?</p>
<p>Thanks.</p>
<p>Paul.</p>
|
[
{
"answer_id": 635985,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": " var boolDoPostBack = false;\n\n if (__doPostBack)\n {\n // save a reference to the original __doPostBack\n var __oldDoPostBack = __doPostBack;\n\n //replace __doPostBack with another function\n __doPostBack = AlwaysFireBeforeFormSubmit;\n }\n function setdopostback()\n {\n boolDoPostBack = true;\n }\n function AlwaysFireBeforeFormSubmit (eventTarget, eventArgument)\n {\n var x= document.readyState\n\n if (x != \"complete\")\n {\n if (x == \"loading\" || x == \"interactive\" || x == \"unitialized\" || x == \"loaded\")\n { \n //do nothing with IE postback\n }\n else if (!boolDoPostBack)\n {\n //do nothing with FireFox postback\n }\n else\n {\n //alert('Allow Postback 1');\n return __oldDoPostBack (eventTarget, eventArgument);\n }\n }\n else\n {\n //alert('Allow Postback 2');\n return __oldDoPostBack (eventTarget, eventArgument);\n } \n }\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278149",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21755/"
] |
278,163
|
<p>I need to catch the HTML of a ASP.NET just before it is being sent to the client in order to do last minute string manipulations on it, and then send the modified version to the client.</p>
<p>e.g.</p>
<p>The Page is loaded
Every control has been rendered correctly
The Full html of the page is ready to be transferred back to the client</p>
<p>Is there a way to that in ASP.NET?</p>
|
[
{
"answer_id": 288740,
"author": "Atanas Korchev",
"author_id": 10141,
"author_profile": "https://Stackoverflow.com/users/10141",
"pm_score": 5,
"selected": true,
"text": "protected override void Render(HtmlTextWriter writer)\n{\n StringWriter output = new StringWriter();\n base.Render(new HtmlTextWriter(output));\n //This is the rendered HTML of your page. Feel free to manipulate it.\n string outputAsString = output.ToString();\n\n writer.Write(outputAsString);\n}\n"
},
{
"answer_id": 17639722,
"author": "Uwe Keim",
"author_id": 107625,
"author_profile": "https://Stackoverflow.com/users/107625",
"pm_score": 1,
"selected": false,
"text": "UpdatePanel UpdatePanel UpdatePanel protected override void Render(HtmlTextWriter writer)\n{\n if (IsPostBack || IsCallback)\n {\n base.Render(writer);\n }\n else\n {\n using (var output = new StringWriter())\n {\n base.Render(new HtmlTextWriter(output));\n\n var outputAsString = output.ToString();\n outputAsString = doSomeManipulation(outputAsString);\n\n writer.Write(outputAsString);\n }\n }\n}\n UpdatePanel UpdatePanel Page.Render"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32582/"
] |
278,186
|
<p>I've got a simple little WPF app with a TextBox and a WebBrowser control. As I type into the TextBox the WebBrowser updates with its content.</p>
<p>But on each keystroke, when the WebBrowser updates, it makes a click sound. How can I disable the WebBrowser control's refresh click sound?</p>
<p><a href="http://img411.imageshack.us/img411/2296/appbz9.jpg" rel="nofollow noreferrer">WPF TextBox and WebBrowser controls http://img411.imageshack.us/img411/2296/appbz9.jpg</a></p>
<p>My XAML...</p>
<pre><code><TextBox Name="MyTextBox"
...
TextChanged="MyTextBox_TextChanged"
TextWrapping="Wrap"
AcceptsReturn="True"
VerticalScrollBarVisibility="Visible" />
<WebBrowser Name="MyWebBrowser" ... />
</code></pre>
<p>My Visual Basic code...</p>
<pre>
Private Sub MyTextBox_TextChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.TextChangedEventArgs)
If Not MyTextBox.Text = String.Empty Then
MyWebBrowser.NavigateToString(MyTextBox.Text)
Else
MyWebBrowser.Source = Nothing
End If
End Sub
</pre>
|
[
{
"answer_id": 288740,
"author": "Atanas Korchev",
"author_id": 10141,
"author_profile": "https://Stackoverflow.com/users/10141",
"pm_score": 5,
"selected": true,
"text": "protected override void Render(HtmlTextWriter writer)\n{\n StringWriter output = new StringWriter();\n base.Render(new HtmlTextWriter(output));\n //This is the rendered HTML of your page. Feel free to manipulate it.\n string outputAsString = output.ToString();\n\n writer.Write(outputAsString);\n}\n"
},
{
"answer_id": 17639722,
"author": "Uwe Keim",
"author_id": 107625,
"author_profile": "https://Stackoverflow.com/users/107625",
"pm_score": 1,
"selected": false,
"text": "UpdatePanel UpdatePanel UpdatePanel protected override void Render(HtmlTextWriter writer)\n{\n if (IsPostBack || IsCallback)\n {\n base.Render(writer);\n }\n else\n {\n using (var output = new StringWriter())\n {\n base.Render(new HtmlTextWriter(output));\n\n var outputAsString = output.ToString();\n outputAsString = doSomeManipulation(outputAsString);\n\n writer.Write(outputAsString);\n }\n }\n}\n UpdatePanel UpdatePanel Page.Render"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/83/"
] |
278,189
|
<p>What is the string concatenation operator in Oracle SQL? </p>
<p>Are there any "interesting" features I should be careful of? </p>
<p>(This seems obvious, but I couldn't find a previous question asking it). </p>
|
[
{
"answer_id": 278198,
"author": "Tony Andrews",
"author_id": 18747,
"author_profile": "https://Stackoverflow.com/users/18747",
"pm_score": 9,
"selected": true,
"text": "|| select 'Mr ' || ename from emp;\n 'x' || null 'x' null"
},
{
"answer_id": 279351,
"author": "Gary Myers",
"author_id": 25714,
"author_profile": "https://Stackoverflow.com/users/25714",
"pm_score": 6,
"selected": false,
"text": "select concat('a','b') from dual;\n"
},
{
"answer_id": 33642495,
"author": "Ankur",
"author_id": 5548870,
"author_profile": "https://Stackoverflow.com/users/5548870",
"pm_score": 3,
"selected": false,
"text": "DECLARE\n a VARCHAR2(30);\n b VARCHAR2(30);\n c VARCHAR2(30);\n BEGIN\n a := ' Abc '; \n b := ' def ';\n c := a || b;\n DBMS_OUTPUT.PUT_LINE(c); \n END;\n"
},
{
"answer_id": 33647100,
"author": "Fabio Fantoni",
"author_id": 4689391,
"author_profile": "https://Stackoverflow.com/users/4689391",
"pm_score": 4,
"selected": false,
"text": "select concat(a,b)\n from dual\n select 'a'||'b'||'c'||'d'\n from dual\n"
},
{
"answer_id": 60938444,
"author": "Grant Shannon",
"author_id": 6044312,
"author_profile": "https://Stackoverflow.com/users/6044312",
"pm_score": 2,
"selected": false,
"text": "CONCAT(CONCAT(,),) YYYYMMDD YYYY-MM-DD CONCAT(CONCAT(SUBSTR(DATECOL,1,4),SUBSTR(DATECOL,6,2)),SUBSTR(DATECOL,9,2)) AS YYYYMMDD\n"
},
{
"answer_id": 71880957,
"author": "Du-Lacoste",
"author_id": 3600553,
"author_profile": "https://Stackoverflow.com/users/3600553",
"pm_score": 2,
"selected": false,
"text": "Oracle SQL CONCAT || CONCAT SELECT CONCAT( string1, string2 ) FROM dual;\n CONCAT SELECT CONCAT(CONCAT('A', 'B'),'C') FROM dual;\n CONCAT SELECT 'My Name' || 'My Age' FROM dual;\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278189",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7211/"
] |
278,192
|
<p>How do I view the history of an individual file with complete details of what has changed?</p>
<p><code>git log -- [filename]</code> shows me the commit history of a file, but how do I see the file content that changed?</p>
|
[
{
"answer_id": 278239,
"author": "cori",
"author_id": 8151,
"author_profile": "https://Stackoverflow.com/users/8151",
"pm_score": 3,
"selected": false,
"text": "Repository Visualize master's History"
},
{
"answer_id": 278242,
"author": "VolkA",
"author_id": 25472,
"author_profile": "https://Stackoverflow.com/users/25472",
"pm_score": 11,
"selected": false,
"text": "git log -p -- filename\n git help log git show HEAD\n gitk\n"
},
{
"answer_id": 280140,
"author": "farktronix",
"author_id": 677,
"author_profile": "https://Stackoverflow.com/users/677",
"pm_score": 7,
"selected": false,
"text": "git whatchanged -p filename git log -p filename git blame filename"
},
{
"answer_id": 1321962,
"author": "Claudio Acciaresi",
"author_id": 48696,
"author_profile": "https://Stackoverflow.com/users/48696",
"pm_score": 12,
"selected": true,
"text": "gitk gitk [filename]\n gitk --follow [filename]\n"
},
{
"answer_id": 3458509,
"author": "yllohy",
"author_id": 417241,
"author_profile": "https://Stackoverflow.com/users/417241",
"pm_score": 6,
"selected": false,
"text": "git blame filename\n git gui blame filename\n"
},
{
"answer_id": 3737313,
"author": "George Anderson",
"author_id": 47292,
"author_profile": "https://Stackoverflow.com/users/47292",
"pm_score": 4,
"selected": false,
"text": "gitx -- <path/to/filename>"
},
{
"answer_id": 5493663,
"author": "Dan Moulding",
"author_id": 95706,
"author_profile": "https://Stackoverflow.com/users/95706",
"pm_score": 11,
"selected": false,
"text": "git log --follow -p -- path-to-file\n bar foo git log -p bar --follow foo git log --follow -p bar foo -p"
},
{
"answer_id": 8336904,
"author": "Malks",
"author_id": 627844,
"author_profile": "https://Stackoverflow.com/users/627844",
"pm_score": 3,
"selected": false,
"text": "git diff --cached\n"
},
{
"answer_id": 10929943,
"author": "Falken",
"author_id": 194443,
"author_profile": "https://Stackoverflow.com/users/194443",
"pm_score": 8,
"selected": false,
"text": "tig gitk apt-get install tig $ brew install tig tig [filename] tig"
},
{
"answer_id": 11847622,
"author": "Adi Shavit",
"author_id": 135862,
"author_profile": "https://Stackoverflow.com/users/135862",
"pm_score": 3,
"selected": false,
"text": "gitk --all <filename>\n"
},
{
"answer_id": 13448672,
"author": "Jian",
"author_id": 1205529,
"author_profile": "https://Stackoverflow.com/users/1205529",
"pm_score": 4,
"selected": false,
"text": "pip install git-playback\ngit playback [filename]\n git log -p gitk"
},
{
"answer_id": 13609201,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 3,
"selected": false,
"text": "File tree File history Blame fatal: Not a valid object name View"
},
{
"answer_id": 13730108,
"author": "John Lawrence Aspden",
"author_id": 254837,
"author_profile": "https://Stackoverflow.com/users/254837",
"pm_score": 6,
"selected": false,
"text": "git log --follow --all -p dir/file.c\n gitk --follow --all -p dir/file.c\n\ntig --follow --all -p dir/file.c\n sudo apt-get install gitk tig\n alias gdf='gitk --follow --all -p'\n gdf dir dir"
},
{
"answer_id": 16654730,
"author": "Lukasz Czerwinski",
"author_id": 330067,
"author_profile": "https://Stackoverflow.com/users/330067",
"pm_score": 2,
"selected": false,
"text": "git diff -U <filename> git config color.ui auto"
},
{
"answer_id": 17329576,
"author": "Palesz",
"author_id": 88355,
"author_profile": "https://Stackoverflow.com/users/88355",
"pm_score": 5,
"selected": false,
"text": "[alias]\n lg = log --all --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset'\\n--abbrev-commit --date=relative\n > git lg\n> git lg -- filename\n"
},
{
"answer_id": 31975658,
"author": "user3885927",
"author_id": 3885927,
"author_profile": "https://Stackoverflow.com/users/3885927",
"pm_score": 3,
"selected": false,
"text": "TortoiseGit --> Show Log Show Whole Project All Branches"
},
{
"answer_id": 31980285,
"author": "jitendrapurohit",
"author_id": 4243217,
"author_profile": "https://Stackoverflow.com/users/4243217",
"pm_score": 4,
"selected": false,
"text": "git log --pretty=short -u -L <upperLimit>,<lowerLimit>:<path_to_filename>\n"
},
{
"answer_id": 33629385,
"author": "lang2",
"author_id": 172265,
"author_profile": "https://Stackoverflow.com/users/172265",
"pm_score": 5,
"selected": false,
"text": "tig tig <filename>"
},
{
"answer_id": 56122874,
"author": "foxiris",
"author_id": 2469567,
"author_profile": "https://Stackoverflow.com/users/2469567",
"pm_score": 5,
"selected": false,
"text": "FILE HISTORY"
},
{
"answer_id": 60893144,
"author": "oracleif",
"author_id": 8469665,
"author_profile": "https://Stackoverflow.com/users/8469665",
"pm_score": 1,
"selected": false,
"text": "#!/usr/bin/env bash\n\nSTARTWITH=\"${1:-}\"\nshift 1\n\nDFILES=( \"$@\" )\n\nRunDiff()\n{\n GIT1=$1\n GIT2=$2\n shift 2\n\n if [ \"$(git diff $GIT1 $GIT2 \"$@\")\" ]\n then\n git log ${GIT1}..${GIT2}\n git difftool --tool=vimdiff $GIT1 $GIT2 \"$@\"\n fi\n}\n\nOLDVERS=\"\"\nRUNDIFF=\"\"\n\nfor NEWVERS in $(git log --format=format:%h --reverse)\ndo\n if [ \"$RUNDIFF\" ]\n then\n RunDiff $OLDVERS $NEWVERS \"${DFILES[@]}\"\n elif [ \"$OLDVERS\" ]\n then\n if [ \"$NEWVERS\" = \"${STARTWITH:=${NEWVERS}}\" ]\n then\n RUNDIFF=true\n RunDiff $OLDVERS $NEWVERS \"${DFILES[@]}\"\n fi\n fi\n OLDVERS=$NEWVERS\ndone\n\n"
},
{
"answer_id": 73318457,
"author": "Eng_Farghly",
"author_id": 5661396,
"author_profile": "https://Stackoverflow.com/users/5661396",
"pm_score": 2,
"selected": false,
"text": "git rev-list HEAD --oneline FileName git rev-list HEAD --oneline index.html 7a2bb2f update_index_with_alias\n6c03e56 update_changes\ne867142 Revert \"add_paragraph\"\n git log -p fileName"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278192",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36214/"
] |
278,213
|
<p>Why do Linux distros have different package managers?</p>
<p>I find this very strange because other software such as text editors, desktop environments and graphics software (Inkscape, Blender, GIMP) are shared among distributions. Why not have a common setup tool?</p>
|
[
{
"answer_id": 278288,
"author": "cms",
"author_id": 28532,
"author_profile": "https://Stackoverflow.com/users/28532",
"pm_score": 5,
"selected": true,
"text": ".deb .rpm"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45603/"
] |
278,215
|
<p>I'm working with an existing XML document which has a structure (in part) like so:</p>
<pre><code><Group>
<Entry>
<Name> Bob </Name>
<ID> 1 </ID>
</Entry>
<Entry>
<Name> Larry </Name>
</Entry>
</Group>
</code></pre>
<p>I'm using LINQ to XML to query the XDocument to retrieve all these entries as follows:</p>
<pre><code>var items = from g in xDocument.Root.Descendants("Group").Elements("Entry")
select new
{
name = (string)g.element("Name").Value,
id = g.Elements("ID").Count() > 0 ? (string)g.Element("ID").Value : "none"
};
</code></pre>
<p>The "ID" elements aren't always there and so my solution to this was the Count() jazz above. But I'm wondering if someone has a better way to do this. I'm still getting comfortable with this new stuff and I suspect that there may be a better way to do this than how I'm currently doing it.</p>
<p>Is there a better/more preferred way to do what I want?</p>
|
[
{
"answer_id": 278233,
"author": "Cristian Libardo",
"author_id": 16526,
"author_profile": "https://Stackoverflow.com/users/16526",
"pm_score": 2,
"selected": false,
"text": " public static string OptionalElement(this XElement actionElement, string elementName)\n {\n var element = actionElement.Element(elementName);\n return (element != null) ? element.Value : null;\n }\n id = g.OptionalElement(\"ID\") ?? \"none\"\n"
},
{
"answer_id": 278250,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 1,
"selected": false,
"text": "var items = from g in xDocument.Root.Descendants(\"Group\").Elements(\"Entry\")\n let idEl = g.Element(\"ID\")\n select new\n {\n name = (string)g.element(\"Name\").Value,\n id = idEl == null ? \"none\" : idEl.Value;\n };\n FirstOrDefault()"
},
{
"answer_id": 278365,
"author": "Jacob Carpenter",
"author_id": 26627,
"author_profile": "https://Stackoverflow.com/users/26627",
"pm_score": 6,
"selected": true,
"text": ".Value var items =\n from g in xDocument.Root.Descendants(\"Group\").Elements(\"Entry\")\n select new\n {\n name = (string) g.Element(\"Name\"),\n id = (string) g.Element(\"ID\") ?? \"none\",\n };\n ID var items =\n from g in xDocument.Root.Descendants(\"Group\").Elements(\"Entry\")\n select new\n {\n name = (string) g.Element(\"Name\"),\n id = (int?) g.Element(\"ID\"),\n };\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7862/"
] |
278,237
|
<p>I realize that this would be COMPLETELY bad practice in normal situations, but this is just for a test app that needs to be taking input from a bar code scanner (emulating a keyboard). The problem is that I need to start up some scripts while scanning, so I need the window to regain focus directly after I click the script to run it. I've tried using Activate(), BringToFront(), Focus() as well as some Win32 calls like SetForegroundWindow(), Setcapture() and SetActiveWindow()... however the best I can get any of them to do is to make the taskbar item start blinking to tell me that it <em>wants</em> to have focus, but something is stopping it. BTW, I'm running this on XP SP2 and using .NET 2.0.</p>
<p>Is this possible?</p>
<p>Edit: To clarify, I am running the scripts by double-clicking on them in explorer. So I need it to steal focus back from explorer and to the test app.</p>
|
[
{
"answer_id": 278256,
"author": "Ray Hayes",
"author_id": 7093,
"author_profile": "https://Stackoverflow.com/users/7093",
"pm_score": 5,
"selected": true,
"text": "Form true"
},
{
"answer_id": 1609443,
"author": "Ken",
"author_id": 177227,
"author_profile": "https://Stackoverflow.com/users/177227",
"pm_score": 4,
"selected": false,
"text": " // force window to have focus\n uint foreThread = GetWindowThreadProcessId(GetForegroundWindow(), IntPtr.Zero);\n uint appThread = GetCurrentThreadId();\n const uint SW_SHOW = 5;\n if (foreThread != appThread)\n {\n AttachThreadInput(foreThread, appThread, true);\n BringWindowToTop(form.Handle);\n ShowWindow(form.Handle, SW_SHOW);\n AttachThreadInput(foreThread, appThread, false);\n }\n else\n {\n BringWindowToTop(form.Handle);\n ShowWindow(form.Handle, SW_SHOW);\n }\n form.Activate();\n [DllImport(\"user32.dll\", SetLastError = true)]\nstatic extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);\n\n// When you don't want the ProcessId, use this overload and pass IntPtr.Zero for the second parameter\n[DllImport(\"user32.dll\")]\nstatic extern uint GetWindowThreadProcessId(IntPtr hWnd, IntPtr ProcessId);\n\n[DllImport(\"kernel32.dll\")]\nstatic extern uint GetCurrentThreadId();\n\n/// <summary>The GetForegroundWindow function returns a handle to the foreground window.</summary>\n[DllImport(\"user32.dll\")]\nprivate static extern IntPtr GetForegroundWindow();\n\n[DllImport(\"user32.dll\")]\nstatic extern bool AttachThreadInput(uint idAttach, uint idAttachTo, bool fAttach);\n\n[DllImport(\"user32.dll\", SetLastError = true)]\nstatic extern bool BringWindowToTop(IntPtr hWnd);\n\n[DllImport(\"user32.dll\", SetLastError = true)]\nstatic extern bool BringWindowToTop(HandleRef hWnd);\n\n[DllImport(\"user32.dll\")]\nstatic extern bool ShowWindow(IntPtr hWnd, uint nCmdShow);\n"
},
{
"answer_id": 5853542,
"author": "TallGuy",
"author_id": 62147,
"author_profile": "https://Stackoverflow.com/users/62147",
"pm_score": 6,
"selected": false,
"text": "// Get the window to the front.\nthis.TopMost = true;\nthis.TopMost = false;\n\n// 'Steal' the focus.\nthis.Activate();\n"
},
{
"answer_id": 8069072,
"author": "mxgg250",
"author_id": 862501,
"author_profile": "https://Stackoverflow.com/users/862501",
"pm_score": 3,
"selected": false,
"text": "using System.Threading; // be sure to include the System.Threading namespace\n\n //Delegates for safe multi-threading.\n delegate void DelegateGetFocus();\n private DelegateGetFocus m_getFocus;\n\n //Constructor.\n myForm()\n {\n m_getFocus = new DelegateGetFocus(this.getFocus); // initialise getFocus\n InitializeComponent();\n spawnThread(keepFocus); // call spawnThread method\n }\n\n //Spawns a new Thread.\n private void spawnThread(ThreadStart ts)\n {\n try\n {\n Thread newThread = new Thread(ts);\n newThread.IsBackground = true;\n newThread.Start();\n }\n catch(Exception e)\n {\n MessageBox.Show(e.Message, \"Exception!\", MessageBoxButtons.OK, \n MessageBoxIcon.Error);\n }\n }\n\n //Continuously call getFocus.\n private void keepFocus()\n {\n while(true)\n {\n getFocus();\n }\n }\n\n //Keeps Form on top and gives focus.\n private void getFocus()\n {\n //If we need to invoke this call from another thread.\n if (this.InvokeRequired)\n {\n try\n {\n this.Invoke(m_getFocus, new object[] { });\n }\n catch (System.ObjectDisposedException e)\n {\n // Window was destroyed. No problem but terminate application.\n Application.Exit();\n }\n }\n //Otherwise, we're safe.\n else\n {\n this.TopMost = true;\n this.Activate();\n }\n } \n}\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278237",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/194/"
] |
278,259
|
<p>I'm trying to write an iterator for results from a PDO statement but I can't find any way of rewinding to the first row. I would like to avoid the overhead of calling fetchAll and storing all the result data.</p>
<pre><code>// first loop works fine
foreach($statement as $result) {
// do something with result
}
// but subsequent loops don't
foreach($statement as $result) {
// never called
}
</code></pre>
<p>Is there some way of reseting the statement or seeking the first row?</p>
|
[
{
"answer_id": 278682,
"author": "troelskn",
"author_id": 18180,
"author_profile": "https://Stackoverflow.com/users/18180",
"pm_score": 5,
"selected": true,
"text": "fetchAll"
},
{
"answer_id": 278763,
"author": "Exception e",
"author_id": 27541,
"author_profile": "https://Stackoverflow.com/users/27541",
"pm_score": 3,
"selected": false,
"text": "$statement->rewind() PDO_MYSQL_ATTR_USE_BUFFERED_QUERY $pdo->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, 1);\n $it = new ArrayIterator($stmt->fetchAll());\n"
},
{
"answer_id": 17102074,
"author": "John K",
"author_id": 969423,
"author_profile": "https://Stackoverflow.com/users/969423",
"pm_score": 3,
"selected": false,
"text": "// Wrap a PDOStatement to iterate through all result rows. Uses a \n// local cache to allow rewinding.\nclass PDOStatementIterator implements Iterator\n{\n public\n $stmt,\n $cache,\n $next;\n\n public function __construct($stmt)\n {\n $this->cache = array();\n $this->stmt = $stmt;\n }\n\n public function rewind()\n {\n reset($this->cache);\n $this->next();\n }\n\n public function valid()\n {\n return (FALSE !== $this->next);\n }\n\n public function current()\n {\n return $this->next[1];\n }\n\n public function key()\n {\n return $this->next[0];\n }\n\n public function next()\n {\n // Try to get the next element in our data cache.\n $this->next = each($this->cache);\n\n // Past the end of the data cache\n if (FALSE === $this->next)\n {\n // Fetch the next row of data\n $row = $this->stmt->fetch(PDO::FETCH_ASSOC);\n\n // Fetch successful\n if ($row)\n {\n // Add row to data cache\n $this->cache[] = $row;\n }\n\n $this->next = each($this->cache);\n }\n }\n}\n"
},
{
"answer_id": 38876846,
"author": "Pedro Sanção",
"author_id": 2932525,
"author_profile": "https://Stackoverflow.com/users/2932525",
"pm_score": 2,
"selected": false,
"text": "PDOStatement::fetch() PDO::FETCH_ORI_* PDOStatement PDO::ATTR_CURSOR PDO::CURSOR_SCROLL $sql = \"Select * From Tabela\";\n$statement = $db->prepare($sql, array(\n PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL,\n));\n$statement->execute();\n$statement->fetch(PDO::FETCH_BOTH, PDO::FETCH_ORI_NEXT); // return next\n$statement->fetch(PDO::FETCH_BOTH, PDO::FETCH_ORI_PRIOR); // return previous\n$statement->fetch(PDO::FETCH_BOTH, PDO::FETCH_ORI_FIRST); // return first\n$statement->fetch(PDO::FETCH_BOTH, PDO::FETCH_ORI_LAST); // return last\n$statement->fetch(PDO::FETCH_BOTH, PDO::FETCH_ORI_ABS, $n); // return to $n position\n$statement->fetch(PDO::FETCH_BOTH, PDO::FETCH_ORI_REL, $n); // return to $n position relative to current\n PDO::FETCH_BOTH"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20074/"
] |
278,273
|
<p>Using C or C++, After I decrypt a file to disk- how can I guarantee it is deleted if the application crashes or the system powers off and can't clean it up properly? Using C or C++, on Windows and Linux?</p>
|
[
{
"answer_id": 278285,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 1,
"selected": false,
"text": "m(un)lock* family of functions"
},
{
"answer_id": 278652,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 2,
"selected": false,
"text": "atexit() _exit() _Exit() atexit() unlink()"
},
{
"answer_id": 279474,
"author": "Max Lybbert",
"author_id": 10593,
"author_profile": "https://Stackoverflow.com/users/10593",
"pm_score": 1,
"selected": false,
"text": "class Clean_Up_File {\n std::string filename_;\n public Clean_Up_File(std::string filename) { ... } //open/create file\n public ~Clean_Up_File() { ... } //delete file\n}\n\nint main()\n{\n Clean_Up_File file_will_be_deleted_on_program_exit(\"my_file.txt\");\n}\n std::exit(int) std::exit(int) main() SIGKILL SIGKILL"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278273",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35223/"
] |
278,278
|
<p>I'd like to change this:</p>
<pre><code><a href='foo'>
<div> Moo </div>
</a>
</code></pre>
<p>to be standards compliant (you're not supposed to have block elements in inline elements). Wiring javascript to the divs just for navigation seems like a hack and degrades accessibility.. In this case, my requirements are for 2 sets of borders on my fixed-dimension links, so the above non-compliant code works perfectly after applying styles.</p>
<p>Also, is "<code>a { display:block; }</code>" a legal way to circumvent the validation?</p>
|
[
{
"answer_id": 278305,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 1,
"selected": false,
"text": "<a > <tr > onclick"
},
{
"answer_id": 278561,
"author": "Mr. Shiny and New 安宇",
"author_id": 7867,
"author_profile": "https://Stackoverflow.com/users/7867",
"pm_score": 2,
"selected": false,
"text": "div a <div class=\"dbl_border_links\"><a href=\"blah\">Blah text</a></div>\n <a class=\"dbl_border_links\" href=\"blah\"><span>Blah text</span></a>\n <style>\n .dbl_border_links, .dbl_border_links>* {\n display: block;\n border: 1px solid;\n padding: 1px;\n }\n .dbl_border_links {\n border-color: red;\n }\n .dbl_border_links > * {\n border-color: blue;\n }\n</style>\n div a"
},
{
"answer_id": 279820,
"author": "Esteban Küber",
"author_id": 34813,
"author_profile": "https://Stackoverflow.com/users/34813",
"pm_score": 0,
"selected": false,
"text": "width:100%;height:100% display:block;"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4435/"
] |
278,286
|
<p><strike>All of the errors are on auto-generated files, not within the files that were created by me. Here are a few of them:</p>
<pre><code>'Context' is not a member of 'auth_cookies'
'ProcessRequest' cannot be declared 'Overrides' because it does not override a sub in a base class
'Server' is not a member of 'ASP.auth_cookies_aspx'
Class 'auth_cookies_aspx' must implement 'Sub ProcessRequest(context As HttpContext)' for interface 'System.Web.IHttpHandler'
</code></pre>
<p>Any help would be appreciated.</strike></p>
<p>EDIT: found out that the file it was looking for wasn't there, fixed that problem and that eliminated all the errors except one:</p>
<pre><code> Error-5: There can be only one 'page' directive.
>> C:\Users\darren\Documents\Visual Studio 2008\WebSites\gs_ontheweb\auth\cookies.aspx
</code></pre>
<p>This is the contents of the <strong><code>cookies.aspx</code></strong> page:</p>
<pre><code><%@ Page Language="VB" MasterPageFile="~/theMaster.master" AutoEventWireup="false" CodeFile="cookies.aspx.vb" Inherits="auth_cookies" title="NOM COOKIES" %>
</code></pre>
<p>UPDATE: Turns out one of linked files had a link to another .aspx page, causing 2 page directives to be loaded.</p>
|
[
{
"answer_id": 278319,
"author": "Kon",
"author_id": 22303,
"author_profile": "https://Stackoverflow.com/users/22303",
"pm_score": 2,
"selected": true,
"text": "<%@Page%> <%@Master%>"
},
{
"answer_id": 278330,
"author": "Anders",
"author_id": 25515,
"author_profile": "https://Stackoverflow.com/users/25515",
"pm_score": 0,
"selected": false,
"text": "<%@ Master Language=\"VB\" CodeFile=\"theMaster.master.vb\" Inherits=\"theMaster\" %>\n <%@Page%>"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278286",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25515/"
] |
278,290
|
<p>Is there some elegant way to add an empty option to a DropDownList bound with a LinqDataSource?</p>
|
[
{
"answer_id": 278315,
"author": "DOK",
"author_id": 27637,
"author_profile": "https://Stackoverflow.com/users/27637",
"pm_score": 4,
"selected": true,
"text": "<asp:DropDownList ID=\"categories\" runat=\"server\" AppendDataBoundItems=\"True\" AutoPostBack=\"True\" DataSourceID=\"categoriesDataSource\" DataTextField=\"CategoryName\" DataValueField=\"CategoryID\" EnableViewState=\"False\">\n <asp:ListItem Value=\"-1\">\n -- Choose a Category --\n </asp:ListItem> \n</asp:DropDownList>\n"
},
{
"answer_id": 278326,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "IEnumerable<string> public static IEnumerable<string> Prepend(this IEnumerable<string> data, string item)\n {\n return new string[] { item == null ? string.Empty : item }.Union(data);\n }\n var result = new string[]{string.Empty}.Union(from x in data select x.ToString());\n"
},
{
"answer_id": 3477928,
"author": "Cheryl G",
"author_id": 419659,
"author_profile": "https://Stackoverflow.com/users/419659",
"pm_score": 1,
"selected": false,
"text": "<asp:DropDownList ID=\"ddlQualQuestion\" runat=\"server\" DataSourceID=\"sdsQualQuestion\" DataTextField=\"ShortQuestionText\" DataValueField=\"QualificationQuestionKey\" AutoPostBack=\"true\" OnSelectedIndexChanged=\"ddlQualQuestion_SelectedIndexChanged\" OnDataBound=\"ddlQualQuestion_DataBound\" />;\n protected void ddlQualQuestion_DataBound(object sender, EventArgs e) \n{ \n ddlQualQuestion.Items.Insert(0, new ListItem(\"\", \"0\")); \n} \n"
},
{
"answer_id": 14456109,
"author": "jme-mac",
"author_id": 1996522,
"author_profile": "https://Stackoverflow.com/users/1996522",
"pm_score": 1,
"selected": false,
"text": "<asp:DropDownList ID=\"categories\" runat=\"server\" AppendDataBoundItems=\"True\" AutoPostBack=\"True\" DataSourceID=\"categoriesDataSource\" DataTextField=\"CategoryName\" DataValueField=\"CategoryID\" EnableViewState=\"False\">\n <asp:ListItem Value=\"-1\">\n -- Choose a Category --\n </asp:ListItem> \n</asp:DropDownList>\n OnSelecting=\"myGridview_Selecting\"\n protected void myGridview_Selecting(object sender, LinqDataSourceSelectEventArgs e)\n{\n if (categories.SelectedValue == \"-1\")\n {\n e.WhereParameters.Remove(\"CategoryID\");\n }\n}\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12111/"
] |
278,294
|
<p>The new Vista Audio subsystem is set up to be a chain of devices starting with the inputs, going through all the various controls (like mixers and volumen controls) and then ending up at various endpoints (like speakers or headphones).</p>
<p>My question is: Is there a tool out there that will show all the endpoints devices in the system, and what devices are chained together? Ideally, it would diagram the topology, showing what inputs where connected to what outputs, and you would be able to see all the properties for each part of the audio system.</p>
|
[
{
"answer_id": 278315,
"author": "DOK",
"author_id": 27637,
"author_profile": "https://Stackoverflow.com/users/27637",
"pm_score": 4,
"selected": true,
"text": "<asp:DropDownList ID=\"categories\" runat=\"server\" AppendDataBoundItems=\"True\" AutoPostBack=\"True\" DataSourceID=\"categoriesDataSource\" DataTextField=\"CategoryName\" DataValueField=\"CategoryID\" EnableViewState=\"False\">\n <asp:ListItem Value=\"-1\">\n -- Choose a Category --\n </asp:ListItem> \n</asp:DropDownList>\n"
},
{
"answer_id": 278326,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "IEnumerable<string> public static IEnumerable<string> Prepend(this IEnumerable<string> data, string item)\n {\n return new string[] { item == null ? string.Empty : item }.Union(data);\n }\n var result = new string[]{string.Empty}.Union(from x in data select x.ToString());\n"
},
{
"answer_id": 3477928,
"author": "Cheryl G",
"author_id": 419659,
"author_profile": "https://Stackoverflow.com/users/419659",
"pm_score": 1,
"selected": false,
"text": "<asp:DropDownList ID=\"ddlQualQuestion\" runat=\"server\" DataSourceID=\"sdsQualQuestion\" DataTextField=\"ShortQuestionText\" DataValueField=\"QualificationQuestionKey\" AutoPostBack=\"true\" OnSelectedIndexChanged=\"ddlQualQuestion_SelectedIndexChanged\" OnDataBound=\"ddlQualQuestion_DataBound\" />;\n protected void ddlQualQuestion_DataBound(object sender, EventArgs e) \n{ \n ddlQualQuestion.Items.Insert(0, new ListItem(\"\", \"0\")); \n} \n"
},
{
"answer_id": 14456109,
"author": "jme-mac",
"author_id": 1996522,
"author_profile": "https://Stackoverflow.com/users/1996522",
"pm_score": 1,
"selected": false,
"text": "<asp:DropDownList ID=\"categories\" runat=\"server\" AppendDataBoundItems=\"True\" AutoPostBack=\"True\" DataSourceID=\"categoriesDataSource\" DataTextField=\"CategoryName\" DataValueField=\"CategoryID\" EnableViewState=\"False\">\n <asp:ListItem Value=\"-1\">\n -- Choose a Category --\n </asp:ListItem> \n</asp:DropDownList>\n OnSelecting=\"myGridview_Selecting\"\n protected void myGridview_Selecting(object sender, LinqDataSourceSelectEventArgs e)\n{\n if (categories.SelectedValue == \"-1\")\n {\n e.WhereParameters.Remove(\"CategoryID\");\n }\n}\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278294",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17958/"
] |
278,296
|
<p>I've got a PHP script which I'm running from a command line (windows) that performs a variety of tasks, and the only output it gives is via 'print' statements which output direct to screen.</p>
<p>What I want to do is capture this to a log file as well.</p>
<p>I know I can do: </p>
<pre><code>php-cli script.php > log.txt
</code></pre>
<p>But the problem with this approach is that all the output is written to the log file, but I can't see how things are running in the mean time (so I can stop the process if anything dodgy is happening).</p>
<p>Just to pre-empt other possible questions, I can't change all the print's to a log statement as there are far too many of them and I'd rather not change anything in the code lest I be blamed for something going fubar. Plus there's the lack of time aspect as well. I also have to run this on a windows machine.</p>
<p>Thanks in advance :)</p>
<p>Edit: Thanks for the answers guys, in the end I went with the browser method because that was the easiest and quickest to set up, although I am convinced there is an actual answer to this problem somewhere.</p>
|
[
{
"answer_id": 278403,
"author": "Charles Beattie",
"author_id": 97554,
"author_profile": "https://Stackoverflow.com/users/97554",
"pm_score": 0,
"selected": false,
"text": "for /f \"delims=\" %a in ('php-cli script.php') do @echo %a&echo %a>>log.txt\n for /f \"delims=\" %%a in ('php-cli script.php') do @echo %%a&echo %%a>>log.txt\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278296",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11905/"
] |
278,304
|
<p>What is the best way to stop a user from resizing the top-level window of an application written in WPF?</p>
|
[
{
"answer_id": 278332,
"author": "Todd White",
"author_id": 30833,
"author_profile": "https://Stackoverflow.com/users/30833",
"pm_score": 8,
"selected": true,
"text": "ResizeMode.NoResize <Window x:Class=\"WpfApplication5.Window1\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n ResizeMode=\"NoResize\">\n</Window>\n"
},
{
"answer_id": 1142605,
"author": "Rob Sobers",
"author_id": 132931,
"author_profile": "https://Stackoverflow.com/users/132931",
"pm_score": 3,
"selected": false,
"text": "ResizeMode=\"NoResize\" WindowStyle=\"None\""
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15985/"
] |
278,308
|
<p>I've written <a href="http://www.automatous-monk.com/bluepoles/BluePoles.htm" rel="nofollow noreferrer">a Java applet</a>. A user reports that he tried to run it in Firefox 3.0.3 on OS X 10.5.5 but no go. It wants him to download a plug-in, but when he tells it to install missing plug-ins it can't find the appropriate installer...</p>
<p>What is going wrong here?</p>
|
[
{
"answer_id": 279793,
"author": "Paul Reiners",
"author_id": 7648,
"author_profile": "https://Stackoverflow.com/users/7648",
"pm_score": 1,
"selected": false,
"text": "<param name = \"type\" value = \"application/x-java-applet;version=1.6\">\n <param name = \"type\" value = \"application/x-java-applet;version=1.5\">\n type = \"application/x-java-applet;version=1.6\" \\\n type = \"application/x-java-applet;version=1.5\" \\\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278308",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7648/"
] |
278,351
|
<p>I'm painfully new to PHP, and was trying to set up phpBB on my local site. I have a stock debian install of apache2 and php5. The phpBB installer ran fine, connected to the database and created all its tables with no problem. But when I tried to open the login page, I got a 0-byte response.</p>
<p>A little digging showed that it was never making it past the call to mysql_pconnect(). The php binary just quits without error or message. Nothing at all. I tried running the following code:</p>
<pre><code><?php
$id = @mysql_pconnect('localhost','myusername', 'mypassword', true);
print "id=".$id."\n";
?>
</code></pre>
<p>and the "id=" string never prints. It just does nothing. I don't know where to look to see what error happened, or what is going on at all. All i've installed is "mysql" using pear... perhaps I'm missing something else?</p>
<p>This has got to be a path problem somewhere. The mysql extension is built nicely at</p>
<pre><code>/usr/lib/php5/20060613+lfs/mysql.so
</code></pre>
<p><strong>Answer:</strong></p>
<p>jishi: informed me that the "@" operator suppresses output, including error messages (@echo off, anyone?)</p>
<p>tomhaigh: extensions must be explicitly enabled in php.ini file. After adding the line "extension=mysql.so" to php.ini, the following code runs fine:</p>
<pre><code>% cat d.php
<?php
ini_set('display_errors', true);
error_reporting(E_ALL | E_NOTICE);
$id = mysql_pconnect('localhost','myusername', 'mypassword', true);
print "id=".$id."\n";
?>
% php -c /etc/php5/apache2/php.ini d.php
id=Resource id #4
</code></pre>
<p>JOY!</p>
|
[
{
"answer_id": 278394,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<?php\nphpinfo();\n?>\n"
},
{
"answer_id": 278467,
"author": "okoman",
"author_id": 35903,
"author_profile": "https://Stackoverflow.com/users/35903",
"pm_score": 0,
"selected": false,
"text": "pecl download mysql\n"
},
{
"answer_id": 278560,
"author": "Tom Haigh",
"author_id": 22224,
"author_profile": "https://Stackoverflow.com/users/22224",
"pm_score": 2,
"selected": true,
"text": "<?php\nini_set('display_errors', true);\nerror_reporting(E_ALL | E_NOTICE);\n$id = mysql_pconnect('localhost','myusername', 'mypassword', true);\nprint \"id=\".$id.\"\\n\";\n?>\n extension=mysql.so\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278351",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36228/"
] |
278,361
|
<p>I'm updating a long list of records. In my code, everything run as predicted until it execute the query. I get an </p>
<blockquote>
<p>Incorrect syntax near 'TempUpdatePhysicalCityStateZip' </p>
</blockquote>
<p>(my stored procedure name). I've tested it with SQL Server Management Studio and it runs fine. So, I'm not quite sure where I got it wrong. Below is my stored procedure and code:</p>
<pre><code>ALTER PROCEDURE [dbo].[TempUpdateCityStateZip]
@StoreNo nvarchar (11),
@City nvarchar(50),
@State nvarchar(2),
@Zip nvarchar(5)
AS
BEGIN
SET NOCOUNT ON;
UPDATE StoreContact
SET City = @City, State = @State, Zip = @Zip
WHERE StoreNo = @StoreNo
END
</code></pre>
<p>Here is my code:</p>
<pre><code>Dictionary<string, string> CityStateZipList = getCityStateZipList(dbPath);
using (SqlConnection conn = new SqlConnection(dbPath))
{
conn.Open();
SqlCommand cmdUpdate = new SqlCommand("TempUpdateCityStateZip", conn);
foreach (KeyValuePair<string, string> frKeyValue in CityStateZipList)
{
cmdUpdate.Parameters.Clear();
string[] strCityStateZip = frKeyValue.Value.Split(' ');
cmdUpdate.Parameters.AddWithValue("StoreNo", frKeyValue.Key.ToString());
foreach (String i in strCityStateZip)
{
double zipCode;
if (i.Length == 2)
{
cmdUpdate.Parameters.AddWithValue("State", i);
}
else if (i.Length == 5 && double.TryParse(i, out zipCode))
{
cmdUpdate.Parameters.AddWithValue("Zip", i);
}
else
{
cmdUpdate.Parameters.AddWithValue("City", i);
}
}
cmdUpdate.ExecuteNonQuery();
}
}
</code></pre>
|
[
{
"answer_id": 278380,
"author": "DOK",
"author_id": 27637,
"author_profile": "https://Stackoverflow.com/users/27637",
"pm_score": 3,
"selected": false,
"text": "cmdUpdate.CommandType = CommandType.StoredProcedure;\n"
},
{
"answer_id": 278405,
"author": "StingyJack",
"author_id": 16391,
"author_profile": "https://Stackoverflow.com/users/16391",
"pm_score": 1,
"selected": false,
"text": " cmdUpdate.Parameters.AddWithValue(\"@State\", i);\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278361",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28647/"
] |
278,362
|
<p>C# What is the easiest way to disable a control after 10 seconds? Using a Timer or a stopwatch? I'm new to both so thanks for the help.</p>
|
[
{
"answer_id": 278375,
"author": "Galwegian",
"author_id": 3201,
"author_profile": "https://Stackoverflow.com/users/3201",
"pm_score": 0,
"selected": false,
"text": "System.Windows.Forms.Timer"
},
{
"answer_id": 278376,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": false,
"text": "System.Windows.Forms.Timer System.Windows.Threading.DispatcherTimer"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
278,363
|
<p>My lack of C++ experience, or rather my early learning in garbage collected languages is really stinging me at the moment and I have a problem working with strings in C++.</p>
<p>To make it very clear, using std::string or equlivents is not an option - this is char* 's all the way.</p>
<p>So: what I need to do is very simple and basically boils down to concatenating strings. At runtime I have 2 classes.</p>
<p>One class contains "type" information in the form of a base filename.</p>
<p>in the header:</p>
<pre><code>char* mBaseName;
</code></pre>
<p>and later, in the .cpp it is loaded with info passed in from elsewhere.</p>
<pre><code>mBaseName = attributes->BaseName;
</code></pre>
<p>The 2nd class provides version information in the form of a suffix to the base file name, it's a static class and implemented like this at present:</p>
<pre><code>static const char* const suffixes[] = {"Version1", "Version", "Version3"}; //etc.
static char* GetSuffix()
{
int i = 0;
//perform checks on some data structures
i = somevalue;
return suffixes[i];
}
</code></pre>
<p>Then, at runtime the base class creates the filename it needs:</p>
<pre><code>void LoadStuff()
{
char* suffix = GetSuffix();
char* nameToUse = new char[50];
sprintf(nameToUse, "%s%s",mBaseName,suffix);
LoadAndSetupData(nameToUse);
}
</code></pre>
<p>And you can see the problem immediately. nameToUse never gets deleted, memory leak.</p>
<p>The suffixes are a fixed list, but the basefilenames are arbitrary. The name that is created needs to persist beyond the end of "LoadStuff()" as it's not clear when if and how it is used subsequently.</p>
<p>I am probably worrying too much, or being very stupid, but similar code to LoadStuff() happens in other places too, so it needs solving. It's frustrating as I don't quite know enough about the way things work to see a safe and "un-hacky" solution. In C# I'd just write:</p>
<pre><code>LoadAndSetupData(mBaseName + GetSuffix());
</code></pre>
<p>and wouldn't need to worry.</p>
<p>Any comments, suggestions, or advice much appreciated.</p>
<h2>Update</h2>
<p>The issue with the code I am calling LoadAndSetupData() is that, at some point it probably does copy the filename and keep it locally, but the actual instantiation is asynchranous, LoadAndSetupData actually puts things into a queue, and at that point at least, it expects that the string passed in still exists.</p>
<p>I do not control this code so I can't update it's function.</p>
|
[
{
"answer_id": 278411,
"author": "Evan Teran",
"author_id": 13430,
"author_profile": "https://Stackoverflow.com/users/13430",
"pm_score": 2,
"selected": false,
"text": "char * LoadStuff()\n{\n char* suffix = GetSuffix();\n char* nameToUse = new char[50];\n sprintf(\"%s%s\",mBaseName,suffix);\n\n LoadAndSetupData(nameToUse);\n return nameToUse;\n}\n char *name = LoadStuff();\n// do whatever you need to do:\ndelete [] name;\n"
},
{
"answer_id": 278415,
"author": "Dani",
"author_id": 28772,
"author_profile": "https://Stackoverflow.com/users/28772",
"pm_score": 0,
"selected": false,
"text": "LoadAndSetupData(mBaseName + GetSuffix()); \n char nameToUse[50];\n"
},
{
"answer_id": 278419,
"author": "Lou Franco",
"author_id": 3937,
"author_profile": "https://Stackoverflow.com/users/3937",
"pm_score": 2,
"selected": false,
"text": "template<class T>\nclass ArrayGuard {\n public:\n ArrayGuard(T* ptr) { _ptr = ptr; }\n ~ArrayGuard() { delete[] _ptr; }\n private:\n T* _ptr;\n ArrayGuard(const ArrayGuard&);\n ArrayGuard& operator=(const ArrayGuard&);\n}\n char* buffer = new char[50];\nArrayGuard<char *> bufferGuard(buffer);\n"
},
{
"answer_id": 278433,
"author": "JSBձոգչ",
"author_id": 8078,
"author_profile": "https://Stackoverflow.com/users/8078",
"pm_score": 0,
"selected": false,
"text": "static char *nameToUse = new char[50];\n"
},
{
"answer_id": 278464,
"author": "Eclipse",
"author_id": 8701,
"author_profile": "https://Stackoverflow.com/users/8701",
"pm_score": 2,
"selected": false,
"text": "class StringPool\n{\n struct StringReference {\n char *buffer;\n time_t created;\n } *Pool;\n\n size_t PoolSize;\n size_t Allocated;\n\n static const size_t INITIAL_SIZE = 100;\n\n void GrowBuffer()\n {\n StringReference *newPool = new StringReference[PoolSize * 2];\n for (size_t i = 0; i < Allocated; ++i)\n newPool[i] = Pool[i];\n StringReference *oldPool = Pool;\n Pool = newPool;\n delete[] oldPool;\n }\n\npublic:\n\n StringPool() : Pool(new StringReference[INITIAL_SIZE]), PoolSize(INITIAL_SIZE)\n {\n }\n\n ~StringPool()\n {\n ClearPool();\n delete[] Pool;\n }\n\n char *GetBuffer(size_t size)\n {\n if (Allocated == PoolSize)\n GrowBuffer();\n Pool[Allocated].buffer = new char[size];\n Pool[Allocated].buffer = time(NULL);\n ++Allocated;\n }\n\n void ClearPool()\n {\n for (size_t i = 0; i < Allocated; ++i)\n delete[] Pool[i].buffer;\n Allocated = 0;\n }\n\n void ClearBefore(time_t knownCleared)\n {\n size_t newAllocated = 0;\n for (size_t i = 0; i < Allocated; ++i)\n {\n if (Pool[i].created < knownCleared)\n {\n delete[] Pool[i].buffer;\n }\n else\n {\n Pool[newAllocated] = Pool[i];\n ++newAllocated;\n }\n }\n Allocated = newAllocated;\n }\n\n // This compares pointers, not strings!\n void ReleaseBuffer(char *knownCleared)\n {\n size_t newAllocated = 0;\n for (size_t i = 0; i < Allocated; ++i)\n {\n if (Pool[i].buffer == knownCleared)\n {\n delete[] Pool[i].buffer;\n }\n else\n {\n Pool[newAllocated] = Pool[i];\n ++newAllocated;\n }\n }\n Allocated = newAllocated;\n }\n\n};\n"
},
{
"answer_id": 278470,
"author": "ididak",
"author_id": 28888,
"author_profile": "https://Stackoverflow.com/users/28888",
"pm_score": 1,
"selected": false,
"text": "char nameToUse[50];\nsnprintf(nameToUse, sizeof(nameToUse), \"%s%s\",mBaseName,suffix);\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15667/"
] |
278,381
|
<p><strong>Background</strong></p>
<p>I am capturing video using the video4linux 2 spec. It is captured using a C program in real-time. I also have a Java frontend that can run both locally and remotely. The remote side was easy, I just compress the images to JPEG and ship them over a mini-http server to the client that decompresses them and shows them on the screen.</p>
<p>When we run locally, I would like some way IPC to connect directly to that memory and access the images from Java. Then, blit those to the screen using as little CPU power as possible. This is a "surveillance" type system so I could have 8-16 camera feeds running at a time.</p>
<p><strong>Question</strong></p>
<p>What is the most efficient way to move the image data (YUV420P) from the v4l2 mmap buffer to my Java app to display it on the screen? Please show code or point me to some api/specs if any are available.</p>
<p><strong>Answer</strong></p>
<p>In the interest of time, I decided to just use plain Sockets and send the data in RGB. I was able to drastically improve performance when the Java client is running on the same machine. I'm still sending JPEGs over the network if the client is running remotely. Next, I'll need to find an optimized JPEG decoder.</p>
<p>By the way, this is not 2 clients, just my CameraStream widget reads and parses both types.</p>
|
[
{
"answer_id": 278450,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 2,
"selected": false,
"text": "Socket shmat"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278381",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29773/"
] |
278,398
|
<p>I'd like to have a blank line after my bash prompt and before the output on my Mac. It should look like this would:</p>
<pre><code>echo; ls
</code></pre>
<p>Can I add a newline to my bash prompt and then go back up one line to wait for user input? Is there something obvious I'm missing?</p>
|
[
{
"answer_id": 278422,
"author": "HanClinto",
"author_id": 26933,
"author_profile": "https://Stackoverflow.com/users/26933",
"pm_score": 2,
"selected": false,
"text": "ESC [ 1 A\n0x1B 0x5B 0x31 0x41\n \\e[1A\n"
},
{
"answer_id": 278502,
"author": "warren",
"author_id": 4418,
"author_profile": "https://Stackoverflow.com/users/4418",
"pm_score": 1,
"selected": false,
"text": "'\\n\\b'"
},
{
"answer_id": 857990,
"author": "Pianosaurus",
"author_id": 44680,
"author_profile": "https://Stackoverflow.com/users/44680",
"pm_score": 2,
"selected": false,
"text": "C-v ~/.inputrc RETURN: \"\\C-e\\C-v\\n\\C-v\\n\\n\" C-v Ctrl+V ^[[A ~/.inputrc C-v: quoted-insert\nRETURN: \"\\C-e\\C-v\\n\\C-v\\n\\n\" ~/.inputrc C-x C-r C-o"
},
{
"answer_id": 977256,
"author": "Jerry Penner",
"author_id": 83680,
"author_profile": "https://Stackoverflow.com/users/83680",
"pm_score": 0,
"selected": false,
"text": "terminfo tput cuu1\n"
},
{
"answer_id": 3392660,
"author": "Dennis Williamson",
"author_id": 26428,
"author_profile": "https://Stackoverflow.com/users/26428",
"pm_score": 2,
"selected": false,
"text": "trap echo DEBUG\n $ echo foo; echo bar\n\\n\nfoo\n\\n\nbar\n PROMPT_COMMAND='_nl=true'; trap -- '$_nl && [[ $BASH_COMMAND != $PROMPT_COMMAND ]] && echo; _nl=false' DEBUG\n DEBUG $PROMPT_COMMAND $PROMPT_COMMAND echo"
},
{
"answer_id": 13019345,
"author": "Matt",
"author_id": 1766551,
"author_profile": "https://Stackoverflow.com/users/1766551",
"pm_score": 4,
"selected": false,
"text": "echo -e \"\\033[<N>A HELLO WORLD\\n\"\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1019/"
] |
278,429
|
<p>I have a piece of code looking like this : </p>
<pre><code>TAxis *axis = 0;
if (dynamic_cast<MonitorObjectH1C*>(obj))
axis = (dynamic_cast<MonitorObjectH1C*>(obj))->GetXaxis();
</code></pre>
<p>Sometimes it crashes : </p>
<pre><code>Thread 1 (Thread -1208658240 (LWP 11400)):
#0 0x0019e7a2 in _dl_sysinfo_int80 () from /lib/ld-linux.so.2
#1 0x048c67fb in __waitpid_nocancel () from /lib/tls/libc.so.6
#2 0x04870649 in do_system () from /lib/tls/libc.so.6
#3 0x048709c1 in system () from /lib/tls/libc.so.6
#4 0x001848bd in system () from /lib/tls/libpthread.so.0
#5 0x0117a5bb in TUnixSystem::Exec () from /opt/root/lib/libCore.so.5.21
#6 0x01180045 in TUnixSystem::StackTrace () from /opt/root/lib/libCore.so.5.21
#7 0x0117cc8a in TUnixSystem::DispatchSignals ()
from /opt/root/lib/libCore.so.5.21
#8 0x0117cd18 in SigHandler () from /opt/root/lib/libCore.so.5.21
#9 0x0117bf5d in sighandler () from /opt/root/lib/libCore.so.5.21
#10 <signal handler called>
#11 0x0533ddf4 in __dynamic_cast () from /usr/lib/libstdc++.so.6
</code></pre>
<p>I have no clue why it crashes. <em>obj</em> is not null (and if it was it would not be a problem, would it ?). </p>
<p>What could be the reason for a dynamic cast to crash ? </p>
<p>If it can't cast, it should just return NULL no ?</p>
|
[
{
"answer_id": 278575,
"author": "bradtgmurray",
"author_id": 1546,
"author_profile": "https://Stackoverflow.com/users/1546",
"pm_score": 4,
"selected": false,
"text": "if (MonitorObjectH1C* monitorObject = dynamic_cast<MonitorObjectH1C*>(obj))\n{\n axis = monitorObject->GetXaxis();\n}\n"
},
{
"answer_id": 280031,
"author": "bk1e",
"author_id": 8090,
"author_profile": "https://Stackoverflow.com/users/8090",
"pm_score": 6,
"selected": true,
"text": "obj obj obj obj"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20986/"
] |
278,439
|
<p>What's the best way to get a temp directory name in Windows? I see that I can use <code>GetTempPath</code> and <code>GetTempFileName</code> to create a temporary file, but is there any equivalent to the Linux / BSD <a href="http://linux.die.net/man/3/mkdtemp" rel="noreferrer"><code>mkdtemp</code></a> function for creating a temporary directory?</p>
|
[
{
"answer_id": 278457,
"author": "Scott Dorman",
"author_id": 1559,
"author_profile": "https://Stackoverflow.com/users/1559",
"pm_score": 9,
"selected": true,
"text": "public string GetTemporaryDirectory()\n{\n string tempDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());\n Directory.CreateDirectory(tempDirectory);\n return tempDirectory;\n}\n"
},
{
"answer_id": 20445952,
"author": "Steve Jansen",
"author_id": 1995977,
"author_profile": "https://Stackoverflow.com/users/1995977",
"pm_score": 5,
"selected": false,
"text": "Path.GetTempFileName() public string GetTemporaryDirectory()\n{\n string tempFolder = Path.GetTempFileName();\n File.Delete(tempFolder);\n Directory.CreateDirectory(tempFolder);\n\n return tempFolder;\n}\n"
},
{
"answer_id": 20483257,
"author": "Paulo de Barros",
"author_id": 2495163,
"author_profile": "https://Stackoverflow.com/users/2495163",
"pm_score": 1,
"selected": false,
"text": "string randomlyGeneratedFolderNamePart = Path.GetFileNameWithoutExtension(Path.GetRandomFileName());\n\nstring timeRelatedFolderNamePart = DateTime.Now.Year.ToString()\n + DateTime.Now.Month.ToString()\n + DateTime.Now.Day.ToString()\n + DateTime.Now.Hour.ToString()\n + DateTime.Now.Minute.ToString()\n + DateTime.Now.Second.ToString()\n + DateTime.Now.Millisecond.ToString();\n\nstring processRelatedFolderNamePart = System.Diagnostics.Process.GetCurrentProcess().Id.ToString();\n\nstring temporaryDirectoryName = Path.Combine( Path.GetTempPath()\n , timeRelatedFolderNamePart \n + processRelatedFolderNamePart \n + randomlyGeneratedFolderNamePart);\n"
},
{
"answer_id": 34711651,
"author": "Andrew Dennison",
"author_id": 1454085,
"author_profile": "https://Stackoverflow.com/users/1454085",
"pm_score": 3,
"selected": false,
"text": " [DllImport(@\"kernel32.dll\", EntryPoint = \"CreateDirectory\", SetLastError = true, CharSet = CharSet.Unicode)]\n [return: MarshalAs(UnmanagedType.Bool)]\n private static extern bool CreateDirectoryApi\n ([MarshalAs(UnmanagedType.LPTStr)] string lpPathName, IntPtr lpSecurityAttributes);\n\n /// <summary>\n /// Creates the directory if it does not exist.\n /// </summary>\n /// <param name=\"directoryPath\">The directory path.</param>\n /// <returns>Returns false if directory already exists. Exceptions for any other errors</returns>\n /// <exception cref=\"System.ComponentModel.Win32Exception\"></exception>\n internal static bool CreateDirectoryIfItDoesNotExist([NotNull] string directoryPath)\n {\n if (directoryPath == null) throw new ArgumentNullException(\"directoryPath\");\n\n // First ensure parent exists, since the WIN Api does not\n CreateParentFolder(directoryPath);\n\n if (!CreateDirectoryApi(directoryPath, lpSecurityAttributes: IntPtr.Zero))\n {\n Win32Exception lastException = new Win32Exception();\n\n const int ERROR_ALREADY_EXISTS = 183;\n if (lastException.NativeErrorCode == ERROR_ALREADY_EXISTS) return false;\n\n throw new System.IO.IOException(\n \"An exception occurred while creating directory'\" + directoryPath + \"'\".NewLine() + lastException);\n }\n\n return true;\n }\n"
},
{
"answer_id": 39286608,
"author": "Jan Hlavsa",
"author_id": 5922573,
"author_profile": "https://Stackoverflow.com/users/5922573",
"pm_score": 3,
"selected": false,
"text": " /// <summary>\n /// Creates the unique temporary directory.\n /// </summary>\n /// <returns>\n /// Directory path.\n /// </returns>\n public string CreateUniqueTempDirectory()\n {\n var uniqueTempDir = Path.GetFullPath(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()));\n Directory.CreateDirectory(uniqueTempDir);\n return uniqueTempDir;\n }\n"
},
{
"answer_id": 65290672,
"author": "parsa2820",
"author_id": 12321674,
"author_profile": "https://Stackoverflow.com/users/12321674",
"pm_score": 3,
"selected": false,
"text": "GetTmpDirectory public string GetTmpDirectory()\n{\n string tmpDirectory;\n\n do\n {\n tmpDirectory = Path.Combine(Path.GetTempPath(), Path.GetFileNameWithoutExtension(Path.GetRandomFileName()));\n } while (Directory.Exists(tmpDirectory));\n\n Directory.CreateDirectory(tmpDirectory);\n return tmpDirectory;\n}\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25507/"
] |
278,440
|
<p>I need to do a modulus operation on very large integers. The biggest integer supported by my platform (edit: .NET 2.0) is a 64 bit integer, which aren't big enough for the numbers I'm working with.</p>
<p>How can I do a modulus on really big integers, like 12654875632126424875387321657498462167853687516876876?</p>
<p>I have a solution that treats the number as a string and works it in pieces one by one, but I wanted to know if there's a better way.</p>
<p>Here's my function treating the number as a string. It basically does long division the way you'd do it by hand.</p>
<pre><code> Public Function MyMod(ByVal numberString As String, ByVal modby As Integer) As Integer
Dim position As Integer = -1
Dim curSubtraction As Integer = 0
While position < numberString.Length - 1
position += 1
curSubtraction = curSubtraction * 10 + CInt(numberString.Substring(position, 1))
If (curSubtraction / modby) < 1 And position = numberString.Length - 1 Then
Return curSubtraction
ElseIf (curSubtraction / modby) < 1 Then
Continue While
Else
curSubtraction = curSubtraction Mod modby
End If
End While
Return curSubtraction
End Function
</code></pre>
<p>Is there a cleaner, more efficient way?</p>
<p>EDIT: To clarify, the integers are coming from IBAN bank account numbers. According to the specification, you have to convert the IBAN account number (containing letters) into one integer. Then, you do a modulus on the integer. So, I guess you could say that the real source of the integer to perform the modulus on is a string of digits.</p>
|
[
{
"answer_id": 278468,
"author": "Tony Arkles",
"author_id": 13868,
"author_profile": "https://Stackoverflow.com/users/13868",
"pm_score": 4,
"selected": true,
"text": "(a + b) MOD n = ((a MOD n) + (b MOD n)) MOD n\n ab MOD n = (a MOD n)(b MOD n) MOD n\n"
},
{
"answer_id": 5742221,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "private static int Mod(string value, int mod) {\n if (string.IsNullOrEmpty(value)) throw new ArgumentException(\"Invalid value.\", \"value\");\n if (mod <= 0) throw new ArgumentException(\"Invalid mod.\", \"mod\");\n\n int maxLength = long.MaxValue.ToString().Length - 1;\n\n return value.Length > maxLength\n ? Mod((Convert.ToInt64(value.Substring(0, maxLength)) % mod).ToString() + value.Substring(maxLength), mod)\n : Convert.ToInt32(Convert.ToInt64(value) % mod);}\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278440",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/681/"
] |
278,466
|
<p>In an application I work on, any business logic error causes an exception to be thrown, and the calling code handles the exception. This pattern is used throughout the application and works well. </p>
<p>I have a situation where I will be attempting to execute a number of business tasks from inside the business layer. The requirement for this is that a failure of one task should not cause the process to terminate. Other tasks should still be able to execute. In other words, this is not an atomic operation. The problem I have is that at the end of the operation, I wish to notify the calling code that an exception or exceptions did occur by throwing an exception. Consider the following psuedo-code snippet:</p>
<pre><code>function DoTasks(MyTask[] taskList)
{
foreach(MyTask task in taskList)
{
try
{
DoTask(task);
}
catch(Exception ex)
{
log.add(ex);
}
}
//I want to throw something here if any exception occurred
}
</code></pre>
<p>What do I throw? I have encountered this pattern before in my career. In the past I have kept a list of all exceptions, then thrown an exception that contains all the caught exceptions. This doesn't seem like the most elegant approach. Its important to preserve as many details as possible from each exception to present to the calling code.</p>
<p>Thoughts?</p>
<hr/>
<p>Edit: The solution must be written in .Net 3.5. I cannot use any beta libraries, or the AggregateException in .Net 4.0 as mentioned by <a href="/users/23633/bradley-grainger">Bradley Grainger</a> (below) would be a nice solution for collection exceptions to throw.</p>
|
[
{
"answer_id": 278511,
"author": "Hath",
"author_id": 5186,
"author_profile": "https://Stackoverflow.com/users/5186",
"pm_score": 4,
"selected": false,
"text": "public class TaskExceptionList : Exception\n{\n public List<Exception> TaskExceptions { get; set; }\n public TaskExceptionList()\n {\n TaskExceptions = new List<Exception>();\n }\n}\n\n public void DoTasks(MyTask[] taskList)\n {\n TaskExceptionList log = new TaskExceptionList();\n foreach (MyTask task in taskList)\n {\n try\n {\n DoTask(task);\n }\n catch (Exception ex)\n {\n log.TaskExceptions.Add(ex);\n }\n }\n\n if (log.TaskExceptions.Count > 0)\n {\n throw log;\n }\n }\n public bool TryDoTasks(MyTask[] taskList, out List<Exception> exceptions)\n {\n exceptions = new List<Exception>();\n foreach (MyTask task in taskList)\n {\n try\n {\n DoTask(task);\n }\n catch (Exception ex)\n {\n exceptions.Add(ex);\n }\n }\n\n if (exceptions.Count > 0)\n {\n return false;\n }\n else\n {\n exceptions = null;\n return true;\n }\n }\n"
},
{
"answer_id": 278543,
"author": "Bradley Grainger",
"author_id": 23633,
"author_profile": "https://Stackoverflow.com/users/23633",
"pm_score": 7,
"selected": true,
"text": "AggregateException IEnumerable<Exception> System.Threading.AggregateException System.Threading System.Threading System"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13103/"
] |
278,469
|
<p>I'm starting a project which I think would benefit from bindings (I've got a source list table, several browser views, etc), but I think it would also be quite doable, and perhaps more understandable, without them. From my limited experience I've found bindings to be difficult to troubleshoot and very "magic" (e.g. it's difficult to insert logging anywhere to figure out where stuff is breaking, everything either works or it doesn't).</p>
<p>Is this just my inexperience talking (in which case I could sit down and spend some time just working on my understanding of bindings and expect things to start becoming clearer/easier) or would I be better off just writing all the glue code myself in a manner which I was sure I could understand and troubleshoot.</p>
|
[
{
"answer_id": 278597,
"author": "Peter Hosey",
"author_id": 30461,
"author_profile": "https://Stackoverflow.com/users/30461",
"pm_score": 5,
"selected": true,
"text": "NSView NSCell NSWindow NSController NSArrayController @synthesize"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278469",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1512/"
] |
278,475
|
<p>I'm trying to animate Visio objects with a loop, such as:</p>
<pre><code>For reposition = 2 To 6
xpos = reposition
ypos = reposition
sh1.SetCenter xpos, ypos
Sleep 1000
Next reposition
</code></pre>
<p>While this DOES move the object from the starting position to the ending, the intermediate steps are not visible. After a delay only the final position is displayed.</p>
<p>If I put a <code>MsgBox</code> in the loop then each intermediate position is visible but one must click a distracting, center-positioned box in order to see these.</p>
<p>How can I make the flow visible without user interaction and covering of the screen by a modal window?</p>
|
[
{
"answer_id": 278923,
"author": "DJ.",
"author_id": 10492,
"author_profile": "https://Stackoverflow.com/users/10492",
"pm_score": 3,
"selected": true,
"text": "DoEvents"
},
{
"answer_id": 281749,
"author": "user32848",
"author_id": 32848,
"author_profile": "https://Stackoverflow.com/users/32848",
"pm_score": 1,
"selected": false,
"text": "Private Declare Sub Sleep Lib \"kernel32\" (ByVal dwMilliseconds As Long)\nSub testa()\n Dim sh1 As Visio.Shape\n\n Dim pagObj As Visio.Page\n Dim xpos As Double\n Dim ypos As Double\n\n Set pagObj = ThisDocument.Pages.Item(1)\n Set sh1 = pagObj.Shapes.Item(1)\n\n Dim reposition As Double\n\n reposition = 2#\n\n While reposition < 6#\n xpos = reposition\n ypos = reposition\n\n sh1.SetCenter xpos, ypos\n\n DoEvents\n\n Sleep 100\n\n reposition = reposition + 0.2\n Wend\n\nEnd Sub\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32848/"
] |
278,476
|
<p>I must confess I'm somewhat of an OOP skeptic. Bad pedagogical and laboral experiences with object orientation didn't help. So I converted into a fervent believer in Visual Basic (the classic one!).</p>
<p>Then one day I found out C++ had changed and now had the STL and templates. I really liked that! Made the language useful. Then another day MS decided to apply facial surgery to VB, and I really hated the end result for the gratuitous changes (using "end while" instead of "wend" will make me into a better developer? Why not drop "next" for "end for", too? Why force the getter alongside the setter? Etc.) plus so much Java features which I found useless (inheritance, for instance, and the concept of a hierarchical framework).</p>
<p>And now, several years afterwards, I find myself asking this philosophical question: Is inheritance <strong>really</strong> needed?</p>
<p>The gang-of-four say we should favor object composition over inheritance. And after thinking of it, I cannot find something you can do with inheritance you cannot do with object aggregation plus interfaces. So I'm wondering, why do we even have it in the first place?</p>
<p>Any ideas? I'd love to see an example of where inheritance would be definitely needed, or where using inheritance instead of composition+interfaces can lead to a simpler and easier to modify design. In former jobs I've found if you need to change the base class, you need to modify also almost all the derived classes for they depended on the behaviour of parent. And if you make the base class' methods virtual... then not much code sharing takes place :(</p>
<p>Else, when I finally create my own programming language (a long unfulfilled desire I've found most developers share), I'd see no point in adding inheritance to it...</p>
|
[
{
"answer_id": 278527,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 4,
"selected": false,
"text": "class Point( object ):\n # some set of features: attributes, methods, etc.\n\nclass PointWithMass( Point ):\n # An additional feature: mass.\n P1 PointWithMass p1 p1-friend p1-friend Point p1 Point Point PointWithMass p1 p1 Point Point PointWithMass Point"
},
{
"answer_id": 278631,
"author": "oglester",
"author_id": 2017,
"author_profile": "https://Stackoverflow.com/users/2017",
"pm_score": 0,
"selected": false,
"text": " public abstract class GeneralPresentation\n {\n public GeneralPresentation()\n {\n MenuPages = new List<Page>();\n }\n public IEnumerable<Page> MenuPages { get; set; }\n public string Title { get; set; }\n }\n\n public class IndexPresentation : GeneralPresentation\n {\n public IndexPresentation() { IndexPage = new Page(); }\n public Page IndexPage { get; set; }\n }\n\n public class InsertPresentation : GeneralPresentation\n {\n public InsertPresentation() { \n InsertPage = new Page(); \n ValidationInfo = new PageValidationInfo(); \n }\n public PageValidationInfo ValidationInfo { get; set; }\n public Page InsertPage { get; set; }\n }\n"
},
{
"answer_id": 15721416,
"author": "Chethan",
"author_id": 377762,
"author_profile": "https://Stackoverflow.com/users/377762",
"pm_score": 1,
"selected": false,
"text": "shape <-- triangle shape shape double getArea() {return -1;} return -1 void func(B* b); ... func(new D()); Derived Base"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21258/"
] |
278,488
|
<p>You are given a 32-bit unsigned integer array with length up to 2<sup>32</sup>, with the property that more than half of the entries in the array are equal to N, for some 32-bit unsigned integer N. Find N looking at each number in the array only once and using at most 2 kB of memory.</p>
<p>Your solution must be deterministic, and guaranteed to find N.</p>
|
[
{
"answer_id": 278601,
"author": "Franci Penov",
"author_id": 17028,
"author_profile": "https://Stackoverflow.com/users/17028",
"pm_score": 2,
"selected": false,
"text": "int lNumbers = (size_of(arrNumbers)/size_of(arrNumbers[0]);\n\nfor (int i = 0; i < lNumbers; i++)\n for (int bi = 0; bi < 32; bi++)\n arrBits[i] = arrBits[i] + (arrNumbers[i] & (1 << bi)) == (1 << bi) ? 1 : 0;\n\nint N = 0;\n\nfor (int bc = 0; bc < 32; bc++)\n if (arrBits[bc] > lNumbers/2)\n N = N | (1 << bc);\n"
},
{
"answer_id": 279876,
"author": "Jason Hernandez",
"author_id": 34863,
"author_profile": "https://Stackoverflow.com/users/34863",
"pm_score": 3,
"selected": false,
"text": "public uint MostCommon(UInt32[] numberList)\n{\n uint suspect = 0;\n int suspicionStrength = -1; \n foreach (uint number in numberList)\n {\n if (number==suspect)\n {\n suspicionStrength++;\n }\n else\n {\n suspicionStrength--;\n }\n\n if (suspicionStrength<=0)\n {\n suspect = number;\n }\n }\n return suspect;\n}\n suspicionStrength"
},
{
"answer_id": 30536146,
"author": "fatih tekin",
"author_id": 2034733,
"author_profile": "https://Stackoverflow.com/users/2034733",
"pm_score": 2,
"selected": false,
"text": "a0, a1, . . . , an−1 n/2 − 1 (n−2)/2 n − 2 def goldenLeader(A):\n n = len(A)\n size = 0\n for k in xrange(n):\n if (size == 0):\n size += 1\n value = A[k]\n else:\n if (value != A[k]):\n size -= 1\n else:\n size += 1\n candidate = -1\n if (size > 0):\n candidate = value\n leader = -1\n count = 0\n for k in xrange(n):\n if (A[k] == candidate):\n count += 1\n if (count > n // 2):\n leader = candidate\n return leader\n"
},
{
"answer_id": 36243686,
"author": "Salvador Dali",
"author_id": 1090562,
"author_profile": "https://Stackoverflow.com/users/1090562",
"pm_score": 2,
"selected": false,
"text": "def majority_element(arr):\n counter, possible_element = 0, None\n for i in arr:\n if counter == 0:\n possible_element, counter = i, 1\n elif i == possible_element:\n counter += 1\n else:\n counter -= 1\n\n return possible_element\n O(n) O(n) O(1) n n O(log (n)) O(n) O(log(n))"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2683/"
] |
278,507
|
<p>At my current job we have a CMS system that is .NET/SQL Server based. While customizing a couple of the modules for some internal use, I was a little surprised to see that instead of having APIs that returned data via your typical result set that was bound to a DataGrid/DataList/Repeater control, that the APIs returned an XML node/collection, that was then passed to an XSLT transformation and rendered on the page that way.</p>
<p>What are the benefits to using a model like this?</p>
|
[
{
"answer_id": 278601,
"author": "Franci Penov",
"author_id": 17028,
"author_profile": "https://Stackoverflow.com/users/17028",
"pm_score": 2,
"selected": false,
"text": "int lNumbers = (size_of(arrNumbers)/size_of(arrNumbers[0]);\n\nfor (int i = 0; i < lNumbers; i++)\n for (int bi = 0; bi < 32; bi++)\n arrBits[i] = arrBits[i] + (arrNumbers[i] & (1 << bi)) == (1 << bi) ? 1 : 0;\n\nint N = 0;\n\nfor (int bc = 0; bc < 32; bc++)\n if (arrBits[bc] > lNumbers/2)\n N = N | (1 << bc);\n"
},
{
"answer_id": 279876,
"author": "Jason Hernandez",
"author_id": 34863,
"author_profile": "https://Stackoverflow.com/users/34863",
"pm_score": 3,
"selected": false,
"text": "public uint MostCommon(UInt32[] numberList)\n{\n uint suspect = 0;\n int suspicionStrength = -1; \n foreach (uint number in numberList)\n {\n if (number==suspect)\n {\n suspicionStrength++;\n }\n else\n {\n suspicionStrength--;\n }\n\n if (suspicionStrength<=0)\n {\n suspect = number;\n }\n }\n return suspect;\n}\n suspicionStrength"
},
{
"answer_id": 30536146,
"author": "fatih tekin",
"author_id": 2034733,
"author_profile": "https://Stackoverflow.com/users/2034733",
"pm_score": 2,
"selected": false,
"text": "a0, a1, . . . , an−1 n/2 − 1 (n−2)/2 n − 2 def goldenLeader(A):\n n = len(A)\n size = 0\n for k in xrange(n):\n if (size == 0):\n size += 1\n value = A[k]\n else:\n if (value != A[k]):\n size -= 1\n else:\n size += 1\n candidate = -1\n if (size > 0):\n candidate = value\n leader = -1\n count = 0\n for k in xrange(n):\n if (A[k] == candidate):\n count += 1\n if (count > n // 2):\n leader = candidate\n return leader\n"
},
{
"answer_id": 36243686,
"author": "Salvador Dali",
"author_id": 1090562,
"author_profile": "https://Stackoverflow.com/users/1090562",
"pm_score": 2,
"selected": false,
"text": "def majority_element(arr):\n counter, possible_element = 0, None\n for i in arr:\n if counter == 0:\n possible_element, counter = i, 1\n elif i == possible_element:\n counter += 1\n else:\n counter -= 1\n\n return possible_element\n O(n) O(n) O(1) n n O(log (n)) O(n) O(log(n))"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/71/"
] |
278,539
|
<p>I have written a simple PowerShell filter that pushes the current object down the pipeline if its date is between the specified begin and end date. The objects coming down the pipeline are always in ascending date order so as soon as the date exceeds the specified end date I know my work is done and I would like to let tell the pipeline that the upstream commands can abandon their work so that the pipeline can finish its work. I am reading some very large log files and I will frequently want to examine just a portion of the log. I am pretty sure this is not possible but I wanted to ask to be sure.</p>
|
[
{
"answer_id": 278785,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "filter FirstObject ([string]$vName = '') {\n if ($vName) {sv $vName $_ -s 1} else {$_}\n break\n}\n\nfilter FirstElements ([int]$max = 2, [string]$vName = '') {\n if ($max -le 0) {break} else {$_arr += ,$_}\n if (!--$max) {\n if ($vName) {sv $vName $_arr -s 1} else {$_arr}\n break\n }\n}\n\n# can't assign to a variable directly\n$myLog = get-eventLog security | ... | firstObject\n\n# pass the the varName\nget-eventLog security | ... | firstObject myLog\n$myLog\n\n# can't assign to a variable directly\n$myLogs = get-eventLog security | ... | firstElements 3\n\n# pass the number of elements and the varName\nget-eventLog security | ... | firstElements 3 myLogs\n$myLogs\n\n####################################\n\nget-eventLog security | % {\n if ($_.timegenerated -lt (date 11.09.08) -and`\n $_.timegenerated -gt (date 11.01.08)) {$log1 = $_; break}\n}\n\n#\n$log1\n"
},
{
"answer_id": 294213,
"author": "Emperor XLII",
"author_id": 2495,
"author_profile": "https://Stackoverflow.com/users/2495",
"pm_score": 0,
"selected": false,
"text": "-file switch -file break switch -file $someFile {\n # Parse current line for later matches.\n { $script:line = [DateTime]$_ } { }\n # If less than min date, keep looking.\n { $line -lt $minDate } { Write-Host \"skipping: $line\"; continue }\n # If greater than max date, stop checking.\n { $line -gt $maxDate } { Write-Host \"stopping: $line\"; break }\n # Otherwise, date is between min and max.\n default { Write-Host \"match: $line\" }\n}\n"
},
{
"answer_id": 9766814,
"author": "Yue Zhang",
"author_id": 1265569,
"author_profile": "https://Stackoverflow.com/users/1265569",
"pm_score": 2,
"selected": false,
"text": "gc demo.txt -ReadCount 1 | %{$num=0}{$num++; if($num -eq 5){throw \"terminated pipeline!\"}else{write-host $_}}\n"
},
{
"answer_id": 30943992,
"author": "Maximum Cookie",
"author_id": 1165691,
"author_profile": "https://Stackoverflow.com/users/1165691",
"pm_score": 3,
"selected": false,
"text": "do {\n Get-ChildItem|% { $_;break }\n} while ($false)\n function Breakable-Pipeline([ScriptBlock]$ScriptBlock) {\n do {\n . $ScriptBlock\n } while ($false)\n}\n\nBreakable-Pipeline { Get-ChildItem|% { $_;break } }\n"
},
{
"answer_id": 34832628,
"author": "mklement0",
"author_id": 45375,
"author_profile": "https://Stackoverflow.com/users/45375",
"pm_score": 2,
"selected": false,
"text": "Stop-Pipeline #requires -version 3\nFilter Stop-Pipeline {\n $sp = { Select-Object -First 1 }.GetSteppablePipeline($MyInvocation.CommandOrigin)\n $sp.Begin($true)\n $sp.Process(0)\n}\n\n# Example\n1..5 | % { if ($_ -gt 2) { Stop-Pipeline }; $_ } # -> 1, 2\n Select -First Select -First end Sort-Object Group-Object Measure-Object # !! NO output, because Sort-Object never finishes.\n1..5 | % { if ($_ -gt 2) { Stop-Pipeline }; $_ } | Sort-Object\n Select-Object -First Stop-Pipeline ForEach-Object %"
},
{
"answer_id": 35512304,
"author": "Χpẘ",
"author_id": 2460798,
"author_profile": "https://Stackoverflow.com/users/2460798",
"pm_score": 2,
"selected": false,
"text": "select-object invoke-method im select-property selp -ExpandProperty select-property invoke-method # Get the system.management.automation assembly\n$script:smaa=[appdomain]::currentdomain.getassemblies()|\n ? location -like \"*system.management.automation*\"\n# Get the StopUpstreamCommandsException class \n$script:upcet=$smaa.gettypes()| ? name -like \"*StopUpstreamCommandsException *\"\n\nfunction stop-pipeline {\n # Create a StopUpstreamCommandsException\n $upce = [activator]::CreateInstance($upcet,@($pscmdlet))\n\n $PipelineProcessor=$pscmdlet.CommandRuntime|select-property PipelineProcessor\n $commands = $PipelineProcessor|select-property commands\n $commandProcessor= $commands[0]\n\n $ci = $commandProcessor|select-property commandinfo\n $upce.RequestingCommandProcessor | im set_commandinfo @($ci)\n\n $cr = $commandProcessor|select-property commandruntime\n $upce.RequestingCommandProcessor| im set_commandruntime @($cr)\n\n $null = $PipelineProcessor|\n invoke-method recordfailure @($upce, $commandProcessor.command)\n\n if ($commands.count -gt 1) {\n $doCompletes = @()\n 1..($commands.count-1) | % {\n write-debug \"Stop-pipeline: added DoComplete for $($commands[$_])\"\n $doCompletes += $commands[$_] | invoke-method DoComplete -returnClosure\n }\n foreach ($DoComplete in $doCompletes) {\n $null = & $DoComplete\n }\n }\n\n throw $upce\n}\n select-object -returnClosure if (-not $returnClosure) {\n $methodInfo.Invoke($arguments)\n} else {\n {$methodInfo.Invoke($arguments)}.GetNewClosure()\n}\n"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278539",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30026/"
] |
278,542
|
<p>the problem I have is that I have two sets of values in a drop down list. If type 'A' is selected I want a text box to be populated with a value from the database and be read only. If Type 'B' is selected the box is to be empty and editable.</p>
<p>My original code is written in jsp/struts and I have sort of achieved this by using </p>
<p><code>onchange="javascript:submit()"</code> to reload the page, but this has the obvious drawback of saving any changes you have made which means you can't really cancel.</p>
<p>I also have other problems with the serverside validation due to this method.</p>
<p>Is there a way of making a jsp page reload on change, that way I could write javascript to change the way the page looks according to the values held in the session. That way the save/submit function will only be called when the page has properly been filled out and the server side validation will work as designed.</p>
<p>I know that this is something that AJAX is good at doing but I am trying to avoid it if possible.</p>
|
[
{
"answer_id": 279015,
"author": "Mr. Shiny and New 安宇",
"author_id": 7867,
"author_profile": "https://Stackoverflow.com/users/7867",
"pm_score": 1,
"selected": false,
"text": "<script>\n function reload() {\n document.forms[0].action=\"reloadFormData.jsp\";\n document.forms[0].submit();\n }\n</script>\n<form action=\"saveData.jsp\" method=\"post\">\n <select id=\"A\" name=\"B\" onchange=\"reload()\"><!-- blah --></select>\n <select id=\"B\" name=\"B\"><!-- blah B --></select>\n <input type=\"submit\">\n</form>\n"
},
{
"answer_id": 286877,
"author": "Stein G. Strindhaug",
"author_id": 26115,
"author_profile": "https://Stackoverflow.com/users/26115",
"pm_score": 1,
"selected": false,
"text": "<select> <input type=\"text\"> display = none disabled=\"disabled\""
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
278,564
|
<p>After some time I wanted to update my git repo, and then something went wrong. What is the proper way out of this situation?</p>
<pre><code>mblsha@siruba:~/src/psi/ $ git status
iris: needs merge
# On branch master
# Changes to be committed:
# (use "git reset HEAD <file>..." to unstage)
#
# modified: src/common.cpp
#
# Changed but not updated:
# (use "git add <file>..." to update what will be committed)
#
# unmerged: iris
#
# Untracked files:
# (use "git add <file>..." to include in what will be committed)
#
# gupdate.sh
mblsha@siruba:~/src/psi/ $ git submodule status
+cf237ef8f3d9dc058dbde47e6973e6388608ce60 iris (heads/master)
+cf237ef8f3d9dc058dbde47e6973e6388608ce60 iris (heads/master)
+cf237ef8f3d9dc058dbde47e6973e6388608ce60 iris (heads/master)
mblsha@siruba:~/src/psi/ $ cd iris
mblsha@siruba:~/src/psi/iris/ $ cat .git/HEAD
cf237ef8f3d9dc058dbde47e6973e6388608ce60
</code></pre>
|
[
{
"answer_id": 306308,
"author": "Daniel Lucraft",
"author_id": 11951,
"author_profile": "https://Stackoverflow.com/users/11951",
"pm_score": 4,
"selected": true,
"text": "1. deleting the submodule (rm -r iris)\n2. recreating it again (git submodule update)\n"
},
{
"answer_id": 835406,
"author": "Tyler",
"author_id": 101819,
"author_profile": "https://Stackoverflow.com/users/101819",
"pm_score": 2,
"selected": false,
"text": "git reset HEAD iris"
}
] |
2008/11/10
|
[
"https://Stackoverflow.com/questions/278564",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8950/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.