qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
129,560
|
<p>What is the C# equivalent to the sql server 2005 real type?</p>
|
[
{
"answer_id": 54152559,
"author": "George Nelson",
"author_id": 10902189,
"author_profile": "https://Stackoverflow.com/users/10902189",
"pm_score": 1,
"selected": false,
"text": "Single float String string Single float"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
129,605
|
<p>How would one go about profiling a few queries that are being run from an ASP.NET application? There is some software where I work that runs extremely slow because of the database (I think). The tables have indexes but it still drags because it's working with so much data. How can I profile to see where I can make a few minor improvements that will hopefully lead to larger speed improvements?</p>
<p>Edit: I'd like to add that the webserver likes to timeout during these long queries.</p>
|
[
{
"answer_id": 131006,
"author": "Tim",
"author_id": 10363,
"author_profile": "https://Stackoverflow.com/users/10363",
"pm_score": 1,
"selected": false,
"text": "SET STATISTICS TIME ON\nSET STATISTICS IO ON\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20471/"
] |
129,607
|
<p>I am seeing both of them used in this script I am trying to debug and the literature is just not clear. Can someone demystify this for me?</p>
|
[
{
"answer_id": 129652,
"author": "catfood",
"author_id": 12802,
"author_profile": "https://Stackoverflow.com/users/12802",
"pm_score": 3,
"selected": false,
"text": "man perlsub my local my local"
},
{
"answer_id": 129714,
"author": "J.J.",
"author_id": 21204,
"author_profile": "https://Stackoverflow.com/users/21204",
"pm_score": 7,
"selected": true,
"text": "my my $foo if (true); # $foo lives and dies within the if statement.\n my local local $var = 4;\nprint $var, \"\\n\";\n&hello;\nprint $var, \"\\n\";\n\n# subroutines\nsub hello {\n local $var = 10;\n print $var, \"\\n\";\n &gogo; # calling subroutine gogo\n print $var, \"\\n\";\n}\nsub gogo {\n $var ++;\n}\n 4\n10\n11\n4\n"
},
{
"answer_id": 129739,
"author": "Jeremy Bourque",
"author_id": 2192597,
"author_profile": "https://Stackoverflow.com/users/2192597",
"pm_score": 6,
"selected": false,
"text": "my local my foreach my $x (@foo) { print \"$x\\n\"; }\n sub Foo {\n my $x = shift;\n\n print \"$x\\n\";\n}\n $x local my local local local local sub foo { print \"$x\\n\"; }\nsub bar { local $x; $x = 2; foo(); }\n\n$x = 1;\nfoo(); # prints '1'\nbar(); # prints '2' because $x was localed in bar\nfoo(); # prints '1' again because local from foo is no longer in effect\n foo $x bar local $x $x foo bar $x local bar local $x $x foo $x my local"
},
{
"answer_id": 130460,
"author": "Drew Stephens",
"author_id": 17339,
"author_profile": "https://Stackoverflow.com/users/17339",
"pm_score": 5,
"selected": false,
"text": "local my $file_content;\n{\n local $/;\n open IN, \"foo.txt\";\n $file_content = <IN>;\n} \n local $/"
},
{
"answer_id": 131088,
"author": "Michael Carman",
"author_id": 8233,
"author_profile": "https://Stackoverflow.com/users/8233",
"pm_score": 3,
"selected": false,
"text": "my local my local my local"
},
{
"answer_id": 136851,
"author": "Aristotle Pagaltzis",
"author_id": 9410,
"author_profile": "https://Stackoverflow.com/users/9410",
"pm_score": 4,
"selected": false,
"text": "local local"
},
{
"answer_id": 1237544,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "&s;\n\nsub s()\n{\n local $s=\"5\";\n &b;\n print $s;\n}\n\nsub b()\n{\n $s++;\n}\n"
},
{
"answer_id": 15917874,
"author": "Abhishek Kulkarni",
"author_id": 1532338,
"author_profile": "https://Stackoverflow.com/users/1532338",
"pm_score": 2,
"selected": false,
"text": "our $name = \"Abhishek\";\n\nsub sub1\n{\n print \"\\nName = $name\\n\";\n local $name = \"Abhijeet\";\n\n &sub2;\n &sub3;\n}\n\nsub sub2\n{\n print \"\\nName = $name\\n\";\n}\n\nsub sub3\n{\n my $name = \"Abhinav\";\n print \"\\nName = $name\\n\";\n}\n\n\n&sub1;\n Name = Abhishek\n\nName = Abhijeet\n\nName = Abhinav\n"
},
{
"answer_id": 68783034,
"author": "Omtechnologies s",
"author_id": 16665548,
"author_profile": "https://Stackoverflow.com/users/16665548",
"pm_score": 1,
"selected": false,
"text": "sub foo { \n print \"$x\\n\"; \n}\nsub bar { my $x; $x = 2; foo(); }\n \nbar(); \n $x {} sub foo { print \"$x\\n\"; }\n\nsub bar { local $x; $x = 2; foo(); }\n \nbar(); \n"
},
{
"answer_id": 74385561,
"author": "Antti Rytsölä",
"author_id": 468921,
"author_profile": "https://Stackoverflow.com/users/468921",
"pm_score": 0,
"selected": false,
"text": "#!/usr/bin/perl\n\nsub foo { print \", x is $x\\n\"; }\n\nsub testdefault { $x++; foo(); } # prints 2\n\nsub testmy { my $x; $x++; foo(); } # prints 1\n\nsub testlocal { local $x = 2; foo(); } # prints 2. new set mandatory\n\n\nprint \"Default, everything is global\";\n$x = 1;\ntestdefault();\n\nprint \"My does not affect function calls outside\";\n$x = 1;\ntestmy();\n\nprint \"local is everything after this but initializes a new\";\n$x = 1;\ntestlocal();\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3208/"
] |
129,618
|
<p>I've installed TFS 2008, but I can't seem to access the server. When I try to connect to it in Visual Studio, I can't. If I try by browser on a remote PC, I get a generic page cannot be displayed. On the server, I get a 403. Nothing was touched in IIS and the service is running as a Network Service. Any ideas?</p>
|
[
{
"answer_id": 43316098,
"author": "Hassan Faghihi",
"author_id": 1260751,
"author_profile": "https://Stackoverflow.com/users/1260751",
"pm_score": 0,
"selected": false,
"text": "ERR_CONNECTION_TIMED_OUT http://fserver:8080/tfs"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21318/"
] |
129,628
|
<p>I keep hearing this term tossed around in several different contexts. What is it?</p>
|
[
{
"answer_id": 129823,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": -1,
"selected": false,
"text": "foreach (object item in MyList)\n{\n DoSomething(item);\n}\n MyList.ForEach(DoSometing);\n"
},
{
"answer_id": 145148,
"author": "Jörg W Mittag",
"author_id": 2988,
"author_profile": "https://Stackoverflow.com/users/2988",
"pm_score": 6,
"selected": false,
"text": "yacc yacc"
},
{
"answer_id": 8365840,
"author": "Shelby Moore III",
"author_id": 615784,
"author_profile": "https://Stackoverflow.com/users/615784",
"pm_score": 4,
"selected": false,
"text": "main() main()"
},
{
"answer_id": 15382367,
"author": "Shelby Moore III",
"author_id": 615784,
"author_profile": "https://Stackoverflow.com/users/615784",
"pm_score": 3,
"selected": false,
"text": "Applicative"
},
{
"answer_id": 24747782,
"author": "Niko Bellic",
"author_id": 3334520,
"author_profile": "https://Stackoverflow.com/users/3334520",
"pm_score": 4,
"selected": false,
"text": "#myImageId {\nheight: 100px;\nwidth: 100px;\n}\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129628",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3208/"
] |
129,642
|
<p>With C#, How do I play (Pause, Forward...) a sound file (mp3, ogg)? The file could be on the hard disk, or on the internet.</p>
<p>Is there any library or Class out there that can ease me the work ?</p>
|
[
{
"answer_id": 129750,
"author": "Ryan Lundy",
"author_id": 5486,
"author_profile": "https://Stackoverflow.com/users/5486",
"pm_score": 3,
"selected": false,
"text": "var audio = new Microsoft.VisualBasic.Devices.Audio();\naudio.Play(\"some file path\");\n"
},
{
"answer_id": 21727628,
"author": "Basil",
"author_id": 3263181,
"author_profile": "https://Stackoverflow.com/users/3263181",
"pm_score": 2,
"selected": false,
"text": " public static void TestRecordPlayer()\n {\n RecordPlayer rp = new RecordPlayer();\n rp.PropertyChanged += new PropertyChangedEventHandler(rp_PropertyChanged);\n rp.Open(new Mp3Reader(File.OpenRead(\"in.mp3\")));\n rp.Play();\n rp.Forward(1000);\n rp.Pause();\n }\n\n static void rp_PropertyChanged(object sender, PropertyChangedEventArgs e)\n {\n switch (e.PropertyName)\n {\n case RecordPlayer.StateProperty:\n RecordPlayer rp = ((RecordPlayer)sender);\n if (rp.State == DeviceState.Stopped)\n {\n rp.Close();\n }\n break;\n }\n }\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20709/"
] |
129,650
|
<p>Let's say I have many-to-many relationship (using the ActiveRecord attribute HasAndBelongsToMany) between Posts and Tags (domain object names changed to protect the innocent), and I wanted a method like <pre>FindAllPostByTags(IList<Tag> tags)</pre> that returns all Posts that have all (not just some of) the Tags in the parameter. Any way I could accomplish this either with NHibernate Expressions or HQL? I've searched through the HQL documentation and couldn't find anything that suited my needs. I hope I'm just missing something obvious!</p>
|
[
{
"answer_id": 130339,
"author": "Sander Rijken",
"author_id": 5555,
"author_profile": "https://Stackoverflow.com/users/5555",
"pm_score": 0,
"selected": false,
"text": "Junction c = Expression.Conjunction();\nforeach(Tag t in tags)\n c = c.Add( Expression.Eq(\"Tag\", t);\n\nreturn sess.CreateCriteria(typeof(Post)).Add(c).List();\n"
},
{
"answer_id": 161706,
"author": "Chris S",
"author_id": 21574,
"author_profile": "https://Stackoverflow.com/users/21574",
"pm_score": 3,
"selected": true,
"text": "IN DetachedCriteria query = DetachedCriteria.For<Post>();\nquery.CreateCriteria(\"Post\").Add(Expression.In(\"TagName\", string.Join(\",\",tags.ToArray()) );\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14064/"
] |
129,651
|
<p>In the following HTML, I'd like the frame around the image to be snug -- not to stretch out and take up all the available width in the parent container. I know there are a couple of ways to do this (including horrible things like manually setting its width to a particular number of pixels), but what is the <em>right</em> way?</p>
<p><strong>Edit:</strong> One answer suggests I turn off "display:block" -- but this causes the rendering to look malformed in every browser I've tested it in. Is there a way to get a nice-looking rendering with "display:block" off?</p>
<p><strong>Edit:</strong> If I add "float: left" to the pictureframe and "clear:both" to the P tag, it looks great. But I don't always want these frames floated to the left. Is there a more direct way to accomplish whatever "float" is doing?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.pictureframe {
display: block;
margin: 5px;
padding: 5px;
border: solid brown 2px;
background-color: #ffeecc;
}
#foo {
border: solid blue 2px;
float: left;
}
img {
display: block;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="foo">
<span class="pictureframe">
<img alt=''
src="http://stackoverflow.com/favicon.ico" />
</span>
<p>
Why is the beige rectangle so wide?
</p>
</div></code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 129706,
"author": "Jim",
"author_id": 8427,
"author_profile": "https://Stackoverflow.com/users/8427",
"pm_score": 6,
"selected": true,
"text": ".pictureframe {\n display: inline-block;\n}\n"
},
{
"answer_id": 129798,
"author": "Keeth",
"author_id": 20588,
"author_profile": "https://Stackoverflow.com/users/20588",
"pm_score": -1,
"selected": false,
"text": "$(window).load(function(){\n $('img').wrap('<div class=\"pictureFrame\"></div>');\n $('div.pictureFrame').each(function(i) {\n $(this).width($('*:first', this).width());\n });\n});\n .pictureFrame {\n background-color:#FFFFFF;\n border:1px solid #CCCCCC;\n line-height:0;\n padding:5px;\n}\n"
},
{
"answer_id": 129863,
"author": "stucampbell",
"author_id": 21379,
"author_profile": "https://Stackoverflow.com/users/21379",
"pm_score": 2,
"selected": false,
"text": "display:inline-block display:-moz-inline-block display:-moz-inline-box"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7598/"
] |
129,677
|
<p>Is there a catchall function somewhere that works well for sanitizing user input for SQL injection and XSS attacks, while still allowing certain types of HTML tags?</p>
|
[
{
"answer_id": 129767,
"author": "Peter Bailey",
"author_id": 8815,
"author_profile": "https://Stackoverflow.com/users/8815",
"pm_score": 6,
"selected": false,
"text": "strip_tags() htmlspecialchars()"
},
{
"answer_id": 130323,
"author": "troelskn",
"author_id": 18180,
"author_profile": "https://Stackoverflow.com/users/18180",
"pm_score": 11,
"selected": true,
"text": "htmlspecialchars echo print htmlspecialchars exec escapeshellcmd escapeshellarg json_encode()"
},
{
"answer_id": 130534,
"author": "SchizoDuckie",
"author_id": 18077,
"author_profile": "https://Stackoverflow.com/users/18077",
"pm_score": 6,
"selected": false,
"text": "filter_input FILTER_VALIDATE_EMAIL /**\n * Pork.FormValidator\n * Validates arrays or properties by setting up simple arrays. \n * Note that some of the regexes are for dutch input!\n * Example:\n * \n * $validations = array('name' => 'anything','email' => 'email','alias' => 'anything','pwd'=>'anything','gsm' => 'phone','birthdate' => 'date');\n * $required = array('name', 'email', 'alias', 'pwd');\n * $sanitize = array('alias');\n *\n * $validator = new FormValidator($validations, $required, $sanitize);\n * \n * if($validator->validate($_POST))\n * {\n * $_POST = $validator->sanitize($_POST);\n * // now do your saving, $_POST has been sanitized.\n * die($validator->getScript().\"<script type='text/javascript'>alert('saved changes');</script>\");\n * }\n * else\n * {\n * die($validator->getScript());\n * } \n * \n * To validate just one element:\n * $validated = new FormValidator()->validate('blah@bla.', 'email');\n * \n * To sanitize just one element:\n * $sanitized = new FormValidator()->sanitize('<b>blah</b>', 'string');\n * \n * @package pork\n * @author SchizoDuckie\n * @copyright SchizoDuckie 2008\n * @version 1.0\n * @access public\n */\nclass FormValidator\n{\n public static $regexes = Array(\n 'date' => \"^[0-9]{1,2}[-/][0-9]{1,2}[-/][0-9]{4}\\$\",\n 'amount' => \"^[-]?[0-9]+\\$\",\n 'number' => \"^[-]?[0-9,]+\\$\",\n 'alfanum' => \"^[0-9a-zA-Z ,.-_\\\\s\\?\\!]+\\$\",\n 'not_empty' => \"[a-z0-9A-Z]+\",\n 'words' => \"^[A-Za-z]+[A-Za-z \\\\s]*\\$\",\n 'phone' => \"^[0-9]{10,11}\\$\",\n 'zipcode' => \"^[1-9][0-9]{3}[a-zA-Z]{2}\\$\",\n 'plate' => \"^([0-9a-zA-Z]{2}[-]){2}[0-9a-zA-Z]{2}\\$\",\n 'price' => \"^[0-9.,]*(([.,][-])|([.,][0-9]{2}))?\\$\",\n '2digitopt' => \"^\\d+(\\,\\d{2})?\\$\",\n '2digitforce' => \"^\\d+\\,\\d\\d\\$\",\n 'anything' => \"^[\\d\\D]{1,}\\$\"\n );\n private $validations, $sanatations, $mandatories, $errors, $corrects, $fields;\n \n\n public function __construct($validations=array(), $mandatories = array(), $sanatations = array())\n {\n $this->validations = $validations;\n $this->sanitations = $sanitations;\n $this->mandatories = $mandatories;\n $this->errors = array();\n $this->corrects = array();\n }\n\n /**\n * Validates an array of items (if needed) and returns true or false\n *\n */\n public function validate($items)\n {\n $this->fields = $items;\n $havefailures = false;\n foreach($items as $key=>$val)\n {\n if((strlen($val) == 0 || array_search($key, $this->validations) === false) && array_search($key, $this->mandatories) === false) \n {\n $this->corrects[] = $key;\n continue;\n }\n $result = self::validateItem($val, $this->validations[$key]);\n if($result === false) {\n $havefailures = true;\n $this->addError($key, $this->validations[$key]);\n }\n else\n {\n $this->corrects[] = $key;\n }\n }\n \n return(!$havefailures);\n }\n\n /**\n *\n * Adds unvalidated class to thos elements that are not validated. Removes them from classes that are.\n */\n public function getScript() {\n if(!empty($this->errors))\n {\n $errors = array();\n foreach($this->errors as $key=>$val) { $errors[] = \"'INPUT[name={$key}]'\"; }\n\n $output = '$$('.implode(',', $errors).').addClass(\"unvalidated\");'; \n $output .= \"new FormValidator().showMessage();\";\n }\n if(!empty($this->corrects))\n {\n $corrects = array();\n foreach($this->corrects as $key) { $corrects[] = \"'INPUT[name={$key}]'\"; }\n $output .= '$$('.implode(',', $corrects).').removeClass(\"unvalidated\");'; \n }\n $output = \"<script type='text/javascript'>{$output} </script>\";\n return($output);\n }\n\n\n /**\n *\n * Sanitizes an array of items according to the $this->sanitations\n * sanitations will be standard of type string, but can also be specified.\n * For ease of use, this syntax is accepted:\n * $sanitations = array('fieldname', 'otherfieldname'=>'float');\n */\n public function sanitize($items)\n {\n foreach($items as $key=>$val)\n {\n if(array_search($key, $this->sanitations) === false && !array_key_exists($key, $this->sanitations)) continue;\n $items[$key] = self::sanitizeItem($val, $this->validations[$key]);\n }\n return($items);\n }\n\n\n /**\n *\n * Adds an error to the errors array.\n */ \n private function addError($field, $type='string')\n {\n $this->errors[$field] = $type;\n }\n\n /**\n *\n * Sanitize a single var according to $type.\n * Allows for static calling to allow simple sanitization\n */\n public static function sanitizeItem($var, $type)\n {\n $flags = NULL;\n switch($type)\n {\n case 'url':\n $filter = FILTER_SANITIZE_URL;\n break;\n case 'int':\n $filter = FILTER_SANITIZE_NUMBER_INT;\n break;\n case 'float':\n $filter = FILTER_SANITIZE_NUMBER_FLOAT;\n $flags = FILTER_FLAG_ALLOW_FRACTION | FILTER_FLAG_ALLOW_THOUSAND;\n break;\n case 'email':\n $var = substr($var, 0, 254);\n $filter = FILTER_SANITIZE_EMAIL;\n break;\n case 'string':\n default:\n $filter = FILTER_SANITIZE_STRING;\n $flags = FILTER_FLAG_NO_ENCODE_QUOTES;\n break;\n \n }\n $output = filter_var($var, $filter, $flags); \n return($output);\n }\n \n /** \n *\n * Validates a single var according to $type.\n * Allows for static calling to allow simple validation.\n *\n */\n public static function validateItem($var, $type)\n {\n if(array_key_exists($type, self::$regexes))\n {\n $returnval = filter_var($var, FILTER_VALIDATE_REGEXP, array(\"options\"=> array(\"regexp\"=>'!'.self::$regexes[$type].'!i'))) !== false;\n return($returnval);\n }\n $filter = false;\n switch($type)\n {\n case 'email':\n $var = substr($var, 0, 254);\n $filter = FILTER_VALIDATE_EMAIL; \n break;\n case 'int':\n $filter = FILTER_VALIDATE_INT;\n break;\n case 'boolean':\n $filter = FILTER_VALIDATE_BOOLEAN;\n break;\n case 'ip':\n $filter = FILTER_VALIDATE_IP;\n break;\n case 'url':\n $filter = FILTER_VALIDATE_URL;\n break;\n }\n return ($filter === false) ? false : filter_var($var, $filter) !== false ? true : false;\n } \n \n\n\n}\n"
},
{
"answer_id": 2405536,
"author": "Hamish Downer",
"author_id": 3189,
"author_profile": "https://Stackoverflow.com/users/3189",
"pm_score": 4,
"selected": false,
"text": "/mypage?id=53 if (isset($_GET['id'])) {\n $id = $_GET['id'];\n settype($id, 'integer');\n $result = mysql_query(\"SELECT * FROM mytable WHERE id = '$id'\");\n # now use the result\n}\n"
},
{
"answer_id": 12891974,
"author": "dangel",
"author_id": 436899,
"author_profile": "https://Stackoverflow.com/users/436899",
"pm_score": 4,
"selected": false,
"text": "filter_var SANITIZE VALIDATE"
},
{
"answer_id": 30487039,
"author": "Alejandro Silva",
"author_id": 2325440,
"author_profile": "https://Stackoverflow.com/users/2325440",
"pm_score": 3,
"selected": false,
"text": "pg_escape_literal() $username = pg_escape_literal($_POST['username']);\n pg_escape_literal()"
},
{
"answer_id": 47858335,
"author": "webaholik",
"author_id": 1296209,
"author_profile": "https://Stackoverflow.com/users/1296209",
"pm_score": 4,
"selected": false,
"text": "/* Prevent XSS input */\nfunction sanitizeXSS () {\n $_GET = filter_input_array(INPUT_GET, FILTER_SANITIZE_STRING);\n $_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);\n $_REQUEST = (array)$_POST + (array)$_GET + (array)$_REQUEST;\n}\n echo print htmlspecialchars json_encode exec() system() backtick escapeshellcmd escapeshellarg"
},
{
"answer_id": 68269541,
"author": "Anmol Mourya",
"author_id": 3318974,
"author_profile": "https://Stackoverflow.com/users/3318974",
"pm_score": -1,
"selected": false,
"text": "$data = trim(preg_replace('/[[:^print:]]/', '', $data));\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10680/"
] |
129,693
|
<p>I ruined several unit tests some time ago when I went through and refactored them to make them more <a href="http://en.wikipedia.org/wiki/Don%27t_repeat_yourself" rel="noreferrer">DRY</a>--the intent of each test was no longer clear. It seems there is a trade-off between tests' readability and maintainability. If I leave duplicated code in unit tests, they're more readable, but then if I change the <a href="http://en.wikipedia.org/wiki/System_Under_Test" rel="noreferrer">SUT</a>, I'll have to track down and change each copy of the duplicated code.</p>
<p>Do you agree that this trade-off exists? If so, do you prefer your tests to be readable, or maintainable?</p>
|
[
{
"answer_id": 130038,
"author": "ddaa",
"author_id": 11549,
"author_profile": "https://Stackoverflow.com/users/11549",
"pm_score": 6,
"selected": false,
"text": "assertPegFitsInHole assertPegIsGood"
},
{
"answer_id": 143699,
"author": "spiv",
"author_id": 22701,
"author_profile": "https://Stackoverflow.com/users/22701",
"pm_score": 7,
"selected": true,
"text": "setUp assertEqual('Joe', person.getFirstName())\nassertEqual('Bloggs', person.getLastName())\nassertEqual(23, person.getAge())\n assertPersonEqual assertPersonEqual(Person('Joe', 'Bloggs', 23), person) Person"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4766/"
] |
129,695
|
<p>I need to serialize a huge amount of data (around 2gigs) of small objects into a single file in order to be processed later by another Java process. Performance is kind of important. Can anyone suggest a good method to achieve this?</p>
|
[
{
"answer_id": 129751,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 0,
"selected": false,
"text": "Serializable"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16389/"
] |
129,740
|
<p>Can someone suggest a good module in perl which can be used to store collection of objects?</p>
<p>Or is ARRAY a good enough substitute for most of the needs?</p>
<p><strong>Update:</strong>
I am looking for a collections class because I want to be able to do an operation like compute collection level property from each element.</p>
<p>Since I need to perform many such operations, I might as well write a class which can be extended by individual objects. This class will obviously work with arrays (or may be hashes).</p>
|
[
{
"answer_id": 129763,
"author": "ethyreal",
"author_id": 18159,
"author_profile": "https://Stackoverflow.com/users/18159",
"pm_score": 0,
"selected": false,
"text": " @names = ('Paul','Michael','Jessica','Megan');\n my %petsounds = (\"cat\" => \"meow\",\n \"dog\" => \"woof\",\n \"snake\" => \"hiss\");\n"
},
{
"answer_id": 131003,
"author": "Sam Kington",
"author_id": 6832,
"author_profile": "https://Stackoverflow.com/users/6832",
"pm_score": 2,
"selected": false,
"text": "my $record = get_complex_structure();\n# $record = {\n# 'widgets' => {\n# name => 'ACME Widgets',\n# skus => [ 'WIDG01', 'WIDG02', 'WIDG03' ],\n# sales => {\n# WIDG01 => { num => 25, value => 105.24 },\n# WIDG02 => { num => 10, value => 80.02 },\n# WIDG03 => { num => 8, value => 205.80 },\n# },\n# },\n# ### and so on for 'grommets', 'nuts', 'bolts' etc.\n# }\n\nmy @standouts =\n map { $_->[0] }\n sort {\n $b->[2] <=> $a->[2] \n || $b->[1] <=> $a->[1]\n || $record->{$a->[0]}->{name} cmp $record->{$b->[0]}->{name}\n }\n map {\n my ($num, $value);\n for my $sku (@{$record->{$_}{skus}}) {\n $num += $record->{$_}{sales}{$sku}{num};\n $value += $record->{$_}{sales}{$sku}{value};\n }\n [ $_, $num, $value ];\n }\n keys %$record;\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4406/"
] |
129,746
|
<p>I am trying to set up JBoss 4.2.2 and JConsole for remote monitoring. As per many of the how-to's I have found on the web to do this you need to enable jmxremote by setting the following options in run.conf. (I realize the other two opts disable authentication)</p>
<pre><code>JAVA_OPTS="$JAVA_OPTS -Dcom.sun.management.jmxremote.port=11099"
JAVA_OPTS="$JAVA_OPTS -Dcom.sun.management.jmxremote.authenticate=false"
JAVA_OPTS="$JAVA_OPTS -Dcom.sun.management.jmxremote.ssl=false"
</code></pre>
<p>Which results in the following exception:</p>
<pre><code>13:06:56,418 INFO [TomcatDeployer] performDeployInternal :: deploy, ctxPath=/services, warUrl=.../tmp/deploy/tmp34585xxxxxxxxx.ear-contents/mDate-Services-exp.war/
13:06:57,706 WARN [AbstractServerConfig] getWebServicePort :: Unable to calculate 'WebServicePort', using default '8080'
13:06:57,711 WARN [AbstractServerConfig] getWebServicePort :: Unable to calculate 'WebServicePort', using default '8080'
13:06:58,070 WARN [AbstractServerConfig] getWebServicePort :: Unable to calculate 'WebServicePort', using default '8080'
13:06:58,071 WARN [AbstractServerConfig] getWebServicePort :: Unable to calculate 'WebServicePort', using default '8080'
13:06:58,138 ERROR [MainDeployer] start :: Could not start deployment: file:/opt/jboss-4.2.2.GA/server/default/tmp/deploy/tmp34585xxxxxxxxx.ear-contents/xxxxx-Services.war
java.lang.NullPointerException
at org.jboss.wsf.stack.jbws.WSDLFilePublisher.getPublishLocation(WSDLFilePublisher.java:303)
at org.jboss.wsf.stack.jbws.WSDLFilePublisher.publishWsdlFiles(WSDLFilePublisher.java:103)
at org.jboss.wsf.stack.jbws.PublishContractDeploymentAspect.create(PublishContractDeploymentAspect.java:52)
at org.jboss.wsf.framework.deployment.DeploymentAspectManagerImpl.deploy(DeploymentAspectManagerImpl.java:115)
at org.jboss.wsf.container.jboss42.ArchiveDeployerHook.deploy(ArchiveDeployerHook.java:97)
...
</code></pre>
<p>My application uses JWS which according to this bug:</p>
<p><a href="https://jira.jboss.org/jira/browse/JBWS-1943" rel="nofollow noreferrer">https://jira.jboss.org/jira/browse/JBWS-1943</a></p>
<p>Suggests this workaround:</p>
<pre><code>JAVA_OPTS="$JAVA_OPTS -Djavax.management.builder.initial=org.jboss.system.server.jmx.MBeanServerBuilderImpl"
JAVA_OPTS="$JAVA_OPTS -Djboss.platform.mbeanserver"
JAVA_OPTS="$JAVA_OPTS -Dcom.sun.management.jmxremote"
</code></pre>
<p>(<a href="https://developer.jboss.org/wiki/JBossWS-FAQ#jive_content_id_How_to_use_JDK_JMX_JConsole_with_JBossWS" rel="nofollow noreferrer">https://developer.jboss.org/wiki/JBossWS-FAQ#jive_content_id_How_to_use_JDK_JMX_JConsole_with_JBossWS</a>)</p>
<p>I've tried that however that then throws the following exception while trying to deploy a sar file in my ear which only contains on class which implements Schedulable for a couple of scheduled jobs my application requires:</p>
<pre><code>Caused by: java.lang.NullPointerException
at EDU.oswego.cs.dl.util.concurrent.ConcurrentReaderHashMap.hash(ConcurrentReaderHashMap.java:298)
at EDU.oswego.cs.dl.util.concurrent.ConcurrentReaderHashMap.get(ConcurrentReaderHashMap.java:410)
at org.jboss.mx.server.registry.BasicMBeanRegistry.getMBeanMap(BasicMBeanRegistry.java:959)
at org.jboss.mx.server.registry.BasicMBeanRegistry.contains(BasicMBeanRegistry.java:577)
</code></pre>
<p>Any suggestions on where to go from here?</p>
<p>EDIT:</p>
<p>I have also tried the following variation:</p>
<pre><code>JAVA_OPTS="$JAVA_OPTS -DmbipropertyFile=../server/default/conf/mbi.properties -DpropertyFile=../server/default/conf/mdate.properties -Dwicket.configuration=DEVELOPMENT"
JAVA_OPTS="$JAVA_OPTS -Djavax.management.builder.initial=org.jboss.system.server.jmx.MBeanServerBuilderImpl"
JAVA_OPTS="$JAVA_OPTS -Djboss.platform.mbeanserver"
JAVA_OPTS="$JAVA_OPTS -Dcom.sun.management.jmxremote"
</code></pre>
<p>I'm using JDK 1.6.0_01-b06</p>
|
[
{
"answer_id": 129872,
"author": "Chris Vest",
"author_id": 13251,
"author_profile": "https://Stackoverflow.com/users/13251",
"pm_score": 2,
"selected": false,
"text": "ssh -XCA"
},
{
"answer_id": 830932,
"author": "anikitin",
"author_id": 102381,
"author_profile": "https://Stackoverflow.com/users/102381",
"pm_score": 0,
"selected": false,
"text": "JBossClusterMonitor MBeanServerFactory.findMBeanServer(null)"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4419/"
] |
129,773
|
<p>When you create your mapping files, do you map your properties to fields or properties :</p>
<pre><code><hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="Foo" namespace="Foo.Bar" >
<class name="Foo" table="FOOS" batch-size="100">
[...]
<property name="FooProperty1" access="field.camelcase" column="FOO_1" type="string" length="50" />
<property name="FooProperty2" column="FOO_2" type="string" length="50" />
[...]
</class>
</hibernate-mapping>
</code></pre>
<p>Of course, please explain why :)</p>
<p>Usually, I map to properties, but mapping to fields can enable to put some "logic" in the getters/setters of the properties.</p>
<p>Is it "bad" to map to fields ? Is there a best practice ?</p>
|
[
{
"answer_id": 130199,
"author": "Matt Hinze",
"author_id": 2676,
"author_profile": "https://Stackoverflow.com/users/2676",
"pm_score": 1,
"selected": false,
"text": "set access=\"field.camelcase-underscore\""
},
{
"answer_id": 212889,
"author": "kͩeͣmͮpͥ ͩ",
"author_id": 26479,
"author_profile": "https://Stackoverflow.com/users/26479",
"pm_score": 0,
"selected": false,
"text": "public class AuditableEntity\n{\n /*...*/\n DateTime creationDate = DateTime.Now;\n /*...*/\n public DateTime CreationDate { get { return creationDate; } }\n}\n"
},
{
"answer_id": 373830,
"author": "Jafin",
"author_id": 40513,
"author_profile": "https://Stackoverflow.com/users/40513",
"pm_score": 1,
"selected": false,
"text": "<property name=\"FirstName\" access=\"field.camelcase\" /> \"From Person where FirstName = :name\";"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129773",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/971/"
] |
129,815
|
<p>I am working on a geometry problem that requires finding the intersection of two parabolic arcs in any rotation. I was able to intesect a line and a parabolic arc by rotating the plane to align the arc with an axis, but two parabolas cannot both align with an axis. I am working on deriving the formulas, but I would like to know if there is a resource already available for this.</p>
|
[
{
"answer_id": 129889,
"author": "Nils Pipenbrinck",
"author_id": 15955,
"author_profile": "https://Stackoverflow.com/users/15955",
"pm_score": 4,
"selected": true,
"text": " x(t) = ax² + bx + c\n y(t) = t;\n s = sin(angle)\n c = cos(angle)\n\n matrix = | c -s |\n | s c |\n x' (t) = x(t) * c - s*t;\ny' (t) = x(t) * s + c*t;\n xa'(t) = rotated equation of arc1 in x\n ya'(t) = rotated equation of arc1 in y.\n xb'(t) = rotated equation of arc2 in x\n yb'(t) = rotated equation of arc2 in y.\n t1 = parametric value of arc1\n t2 = parametric value of arc2\n\n 0 = xa'(t1) - xb'(t2)\n 0 = ya'(t1) - yb'(t2)\n"
},
{
"answer_id": 5440819,
"author": "Dr. belisarius",
"author_id": 353410,
"author_profile": "https://Stackoverflow.com/users/353410",
"pm_score": 1,
"selected": false,
"text": "A x^2 + B x y + CC y^2 + DD x + EE y + F == 0 \n\nwhere B^2-4 A C ==0 (so it's a parabola) \n p = {a -> 1, A -> 1, B -> 2, CC -> 1, DD -> 1, EE -> -1, F -> 1};\np1 = {ToRules@N@Reduce[\n (A x^2 + B x y + CC y^2 + DD x + EE y +F /. {y -> a x^2 } /. p) == 0, x]}\n Show[{\n Plot[a x^2 /. p, {x, -10, 10}, PlotRange -> {{-10, 10}, {-5, 5}}], \n ContourPlot[(A x^2 + B x y + CC y^2 + DD x + EE y + F /. p) == \n 0, {x, -10, 10}, {y, -10, 10}],\n Graphics[{\n PointSize[Large], Pink, Point[{x, x^2} /. p /. p1[[1]]],\n PointSize[Large], Pink, Point[{x, x^2} /. p /. p1[[2]]]\n }]}]\n 4 A F + 4 A DD x + (4 A^2 + 4 a A EE) x^2 + 4 a A B x^3 + a^2 B^2 x^4 == 0 \n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15032/"
] |
129,828
|
<p>My workplace filters our internet traffic by forcing us to go through a proxy, and unfortunately sites such as IT Conversations and Libsyn are blocked. However, mp3 files in general are not filtered, if they come from sites not on the proxy's blacklist.</p>
<p>So is there a website somewhere that will let me give it a URL and then download the MP3 at that URL and send it my way, thus slipping through the proxy?</p>
<p>Alternatively, is there some other easy way for me to get the mp3 files for these podcasts from work?</p>
<p>EDIT and UPDATE: Since I've gotten downvoted a few times, perhaps I should explain/justify my situation. I'm a contractor working at a government facility, and we use some commercial filtering software which is very aggressive and overzealous. My boss is fine with me listening to podcasts at work and is fine with me circumventing the proxy filtering, and doesn't want to deal with the significant red tape (it's the government after all) associated with getting the IT department to make an exception for IT Conversations or the Java Posse, etc. So I feel that this is an important and relevant question for programmers.</p>
<p>Unfortunately, all of the proxy websites for bypassing web filters have also been blocked, so I may have to download the podcasts I like at home in advance and then bring them into work. If can tell me about a lesser-known service I can try which might not be blocked, I'd appreciate it.</p>
|
[
{
"answer_id": 1383922,
"author": "Eli Courtwright",
"author_id": 1694,
"author_profile": "https://Stackoverflow.com/users/1694",
"pm_score": 1,
"selected": true,
"text": "#!/usr/local/bin/python\n\nimport cgitb; cgitb.enable()\nimport cgi\nfrom urllib2 import urlopen\n\ndef tohex(data):\n return \"\".join(hex(ord(char))[2:].rjust(2,\"0\") for char in data)\n\ndef fromhex(encoded):\n data = \"\"\n while encoded:\n data += chr(int(encoded[:2], 16))\n encoded = encoded[2:]\n return data\n\nif __name__==\"__main__\":\n print(\"Content-type: text/plain\")\n print(\"\")\n url = fromhex( cgi.FieldStorage()[\"target\"].value )\n contents = urlopen(url).read()\n for i in range(len(contents)/40+1):\n print( tohex(contents[40*i:40*i+40]) )\n #!/usr/bin/env python2.6\nimport os\nfrom sys import argv\nfrom urllib2 import build_opener, ProxyHandler\n\nif os.fork():\n exit()\n\ndef tohex(data):\n return \"\".join(hex(ord(char))[2:].rjust(2,\"0\") for char in data)\n\ndef fromhex(encoded):\n data = \"\"\n while encoded:\n data += chr(int(encoded[:2], 16))\n encoded = encoded[2:]\n return data\n\nif __name__==\"__main__\":\n if len(argv) < 2:\n print(\"usage: %s URL [FILENAME]\" % argv[0])\n quit()\n\n os.chdir(\"/home/courtwright/mp3s\")\n url = \"http://example.com/cgi-bin/hex.py?target=%s\" % tohex(argv[1])\n fname = argv[2] if len(argv)>2 else argv[1].split(\"/\")[-1]\n with open(fname, \"wb\") as dest:\n for line in build_opener(ProxyHandler({\"http\":\"proxy.example.com:8080\"})).open(url):\n dest.write( fromhex(line.strip()) )\n dest.flush()\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129828",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1694/"
] |
129,861
|
<p>It is a bit of a "chicken or egg" kind of query, but can someone dreamup a query that can return the name of the current database instance in which the query executes? Believe me when I say I understand the paradox: why do you need to know the name of the database instance if you're already connected to execute the query? Auditing in a multi-database environment.</p>
<p>I've looked at all the @@ globals in Books Online. "<code>SELECT @@servername</code>" comes close, but I want the name of the database instance rather than the server.</p>
|
[
{
"answer_id": 129879,
"author": "Dana",
"author_id": 7856,
"author_profile": "https://Stackoverflow.com/users/7856",
"pm_score": 6,
"selected": false,
"text": "SELECT DB_NAME()\n"
},
{
"answer_id": 129882,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "SELECT DB_NAME() AS DatabaseName\n"
},
{
"answer_id": 129887,
"author": "Gthompson83",
"author_id": 20483,
"author_profile": "https://Stackoverflow.com/users/20483",
"pm_score": 1,
"selected": false,
"text": "SELECT SERVERPROPERTY ('InstanceName') \n"
},
{
"answer_id": 129893,
"author": "Giacomo Degli Esposti",
"author_id": 20796,
"author_profile": "https://Stackoverflow.com/users/20796",
"pm_score": 3,
"selected": false,
"text": "SELECT DB_NAME()\n"
},
{
"answer_id": 130068,
"author": "Ollie",
"author_id": 4453,
"author_profile": "https://Stackoverflow.com/users/4453",
"pm_score": 3,
"selected": false,
"text": "USE DATABASE1\nGO\nCREATE PROC spGetContext AS\nSELECT DB_NAME()\nGO\nUSE DATABASE2\nGO\nEXEC DATABASE1..spGetContext\n/* RETURNS 'DATABASE1' not 'DATABASE2' */\n master.dbo.sp_MS_upd_sysobj_category USE MASTER\n/* You must begin function name with sp_ */\nCREATE FUNCTION sp_GetContext\nAS\nSELECT DB_NAME()\nGO\nEXEC sys.sp_MS_marksystemobject sp_GetContext\n\nUSE DATABASE2\n/* Note - no need to reference master when calling SP */\nEXEC sp_GetContext\n/* RETURNS 'DATABASE2' */\n"
},
{
"answer_id": 30393299,
"author": "kevin",
"author_id": 4928422,
"author_profile": "https://Stackoverflow.com/users/4928422",
"pm_score": 6,
"selected": true,
"text": "SELECT\n @@servername AS 'Server Name' -- The database server's machine name\n,@@servicename AS 'Instance Name' -- e.g.: MSSQLSERVER\n,DB_NAME() AS 'Database Name'\n,HOST_NAME() AS 'Host Name' -- The database client's machine name\n"
},
{
"answer_id": 31559056,
"author": "nad",
"author_id": 4935612,
"author_profile": "https://Stackoverflow.com/users/4935612",
"pm_score": 2,
"selected": false,
"text": "select @@servicename\n"
},
{
"answer_id": 73463689,
"author": "Kai - Kazuya Ito",
"author_id": 8172439,
"author_profile": "https://Stackoverflow.com/users/8172439",
"pm_score": 0,
"selected": false,
"text": "SELECT @@SERVICENAME -- SQLEXPRESS\nSELECT SERVERPROPERTY ('InstanceName') -- SQLEXPRESS\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/470/"
] |
129,877
|
<p>I'm writing a function to find <a href="http://projecteuler.net/index.php?section=problems&id=12" rel="noreferrer">triangle numbers</a> and the natural way to write it is recursively:</p>
<pre><code>function triangle (x)
if x == 0 then return 0 end
return x+triangle(x-1)
end
</code></pre>
<p>But attempting to calculate the first 100,000 triangle numbers fails with a stack overflow after a while. This is an ideal function to <a href="http://perl.plover.com/Memoize/" rel="noreferrer">memoize</a>, but I want a solution that will memoize any function I pass to it.</p>
|
[
{
"answer_id": 129881,
"author": "Jon Ericson",
"author_id": 1438,
"author_profile": "https://Stackoverflow.com/users/1438",
"pm_score": 2,
"selected": false,
"text": "function memoize (f)\n local cache = {}\n return function (x)\n if cache[x] then\n return cache[x]\n else\n local y = f(x)\n cache[x] = y\n return y\n end\n end\nend\n\ntriangle = memoize(triangle);\n"
},
{
"answer_id": 129903,
"author": "Romain Verdier",
"author_id": 4687,
"author_profile": "https://Stackoverflow.com/users/4687",
"pm_score": 1,
"selected": false,
"text": "public static class Memoization\n{\n public static Func<T, TResult> Memoize<T, TResult>(this Func<T, TResult> function)\n {\n var cache = new Dictionary<T, TResult>();\n var nullCache = default(TResult);\n var isNullCacheSet = false;\n return parameter =>\n {\n TResult value;\n\n if (parameter == null && isNullCacheSet)\n {\n return nullCache;\n }\n\n if (parameter == null)\n {\n nullCache = function(parameter);\n isNullCacheSet = true;\n return nullCache;\n }\n\n if (cache.TryGetValue(parameter, out value))\n {\n return value;\n }\n\n value = function(parameter);\n cache.Add(parameter, value);\n return value;\n };\n }\n}\n"
},
{
"answer_id": 129910,
"author": "Daniel Spiewak",
"author_id": 9815,
"author_profile": "https://Stackoverflow.com/users/9815",
"pm_score": 2,
"selected": false,
"text": "def memoize[A, B](f: (A)=>B) = {\n var cache = Map[A, B]()\n\n { x: A =>\n if (cache contains x) cache(x) else {\n val back = f(x)\n cache += (x -> back)\n\n back\n }\n }\n}\n memoize(f) != memoize(f) f val correctMem = memoize(memoize _)\n"
},
{
"answer_id": 141231,
"author": "Jon Ericson",
"author_id": 1438,
"author_profile": "https://Stackoverflow.com/users/1438",
"pm_score": 0,
"selected": false,
"text": "function memoize2 (f)\n local cache = {}\n return function (x, y)\n if cache[x..','..y] then\n return cache[x..','..y]\n else\n local z = f(x,y)\n cache[x..','..y] = z\n return z\n end\n end\nend\n function gcd (a, b) \n if b == 0 then return a end\n return gcd(b, a%b)\nend\n"
},
{
"answer_id": 141689,
"author": "Lee Baldwin",
"author_id": 5200,
"author_profile": "https://Stackoverflow.com/users/5200",
"pm_score": 4,
"selected": true,
"text": "local function varg_tostring(...)\n local s = select(1, ...)\n for n = 2, select('#', ...) do\n s = s..\",\"..select(n,...)\n end\n return s\nend\n\nlocal function memoize(f)\n local cache = {}\n return function (...)\n local al = varg_tostring(...)\n if cache[al] then\n return cache[al]\n else\n local y = f(...)\n cache[al] = y\n return y\n end\n end\nend\n"
},
{
"answer_id": 144633,
"author": "Aaron",
"author_id": 14153,
"author_profile": "https://Stackoverflow.com/users/14153",
"pm_score": 1,
"selected": false,
"text": "template <class Result, class Arg, class ResultStore = std::map<Arg, Result> >\nclass memoizer1{\npublic:\n template <class F>\n const Result& operator()(F f, const Arg& a){\n typename ResultStore::const_iterator it = memo_.find(a);\n if(it == memo_.end()) {\n it = memo_.insert(make_pair(a, f(a))).first;\n }\n return it->second;\n }\nprivate:\n ResultStore memo_;\n};\n int fib_(int n){\n ++total_ops;\n if(n == 0 || n == 1) \n return 1;\n else\n return fib(n-1) + fib(n-2);\n}\n int fib(int n) {\n static memoizer1<int,int> memo;\n return memo(fib_, n);\n}\n"
},
{
"answer_id": 173038,
"author": "dreeves",
"author_id": 4234,
"author_profile": "https://Stackoverflow.com/users/4234",
"pm_score": 3,
"selected": false,
"text": "triangle[0] = 0;\ntriangle[x_] := triangle[x] = x + triangle[x-1]\n triangle[x_] := x*(x+1)/2 fib[0] = 1;\nfib[1] = 1;\nfib[n_] := fib[n] = fib[n-1] + fib[n-2]\n"
},
{
"answer_id": 263308,
"author": "Hercynium",
"author_id": 14186,
"author_profile": "https://Stackoverflow.com/users/14186",
"pm_score": 1,
"selected": false,
"text": "# This is the documentation for Memoize 1.01\nuse Memoize;\nmemoize('slow_function');\nslow_function(arguments); # Is faster than it was before\n"
},
{
"answer_id": 3653922,
"author": "Norman Ramsey",
"author_id": 41661,
"author_profile": "https://Stackoverflow.com/users/41661",
"pm_score": 2,
"selected": false,
"text": "nil \"nil\" local function m(f)\n local t = { }\n local function mf(x, ...) -- memoized f\n assert(x ~= nil, 'nil passed to memoized function')\n if select('#', ...) > 0 then\n t[x] = t[x] or m(function(...) return f(x, ...) end)\n return t[x](...)\n else\n t[x] = t[x] or f(x)\n assert(t[x] ~= nil, 'memoized function returns nil')\n return t[x]\n end\n end\n return mf\nend\n"
},
{
"answer_id": 5737216,
"author": "kikito",
"author_id": 312586,
"author_profile": "https://Stackoverflow.com/users/312586",
"pm_score": 2,
"selected": false,
"text": "local globalCache = {}\n\nlocal function getFromCache(cache, args)\n local node = cache\n for i=1, #args do\n if not node.children then return {} end\n node = node.children[args[i]]\n if not node then return {} end\n end\n return node.results\nend\n\nlocal function insertInCache(cache, args, results)\n local arg\n local node = cache\n for i=1, #args do\n arg = args[i]\n node.children = node.children or {}\n node.children[arg] = node.children[arg] or {}\n node = node.children[arg]\n end\n node.results = results\nend\n\n\n-- public function\n\nlocal function memoize(f)\n globalCache[f] = { results = {} }\n return function (...)\n local results = getFromCache( globalCache[f], {...} )\n\n if #results == 0 then\n results = { f(...) }\n insertInCache(globalCache[f], {...}, results)\n end\n\n return unpack(results)\n end\nend\n\nreturn memoize\n"
},
{
"answer_id": 8204369,
"author": "Amir",
"author_id": 13480,
"author_profile": "https://Stackoverflow.com/users/13480",
"pm_score": 3,
"selected": false,
"text": "public static class Helpers\n{\n public static Func<A, R> Memoize<A, R>(this Func<A, Func<A,R>, R> f)\n {\n var map = new Dictionary<A, R>();\n Func<A, R> self = null;\n self = (a) =>\n {\n R value;\n if (map.TryGetValue(a, out value))\n return value;\n value = f(a, self);\n map.Add(a, value);\n return value;\n };\n return self;\n } \n}\n var memoized_fib = Helpers.Memoize<int, int>((n,fib) => n > 1 ? fib(n - 1) + fib(n - 2) : n);\nConsole.WriteLine(memoized_fib(40));\n"
},
{
"answer_id": 8395436,
"author": "Fractaly",
"author_id": 920769,
"author_profile": "https://Stackoverflow.com/users/920769",
"pm_score": 0,
"selected": false,
"text": "public int triangle(final int n){\n return n * (n - 1) / 2;\n}\n"
},
{
"answer_id": 15846127,
"author": "arviman",
"author_id": 315001,
"author_profile": "https://Stackoverflow.com/users/315001",
"pm_score": 0,
"selected": false,
"text": "int[] memo = new int[n+1];\nint sum = 0;\nfor(int i = 0; i <= n; ++i)\n{\n sum+=i;\n memo[i] = sum;\n}\nreturn memo[n];\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1438/"
] |
129,884
|
<p>I look for a tool/framework to make automatic acceptance-testing. The interface to create new tests should be so easy, that a non-programmer (customer, boss) will be able to add specifications for which will be tested automatically.</p>
<p>It should be some way to execute the tests from command-line, to include a run of the tests in automatic builds.</p>
<p>I prefer Java and Open-Source, but my question isn't restricted in that way.</p>
<p>What do you can recommend and please explain why your tool/framework is the best in the world.</p>
|
[
{
"answer_id": 3330126,
"author": "Bryan Ash",
"author_id": 104219,
"author_profile": "https://Stackoverflow.com/users/104219",
"pm_score": 0,
"selected": false,
"text": "Feature: Acceptance testing framework\n\n Scenario: an example speaks volumes\n Given a text example\n When it is read\n Then the simplicity will be appreciated\n Given /^a text example$/ do\n file.open(\"example.txt\", \"w\") { |file| file.write \"text example\" }\nend\n\nWhen /^it is read$/ do\n SystemUnderTest.read(\"example.txt\")\nend\n\nThen /^the simplicity will be appreciated$/ do\n SystemUnderTest.simplicity.should be_appreciated\nend\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21005/"
] |
129,890
|
<p>I'm getting lost in pointer land, I believe. I've got this (code syntax might be a little off, I am not looking at the machine with this code on it...but all the pertinent details are correct):</p>
<pre><code>NSMutableArray *tmp = [[NSMutableArray alloc] init];
</code></pre>
<p>I them pass that to a routine in another class</p>
<pre><code>- (BOOL)myRoutine: (NSMutableArray *)inArray
{
// Adds items to the array -- if I break at the end of this function, the inArray variable has a count of 10
}
</code></pre>
<p>But when the code comes back into the calling routine, [tmp count] is 0.</p>
<p>I must be missing something very simple and yet very fundamental, but for the life of me I can't see it. Can anyone point out what I'm doing wrong?</p>
<p>EDIT: www.stray-bits.com asked if I have retained a reference to it, and I said "maybe...we tried this: NSMutableArray *tmp = [[[NSMutableArray alloc] init] retain]; not sure if that is what you mean, or if I did it right.</p>
<p>EDIT2: Mike McMaster and Andy -- you guys are probably right, then. I don't have the code here (it's on a colleague's machine and they have left for the day), but to fill the array with values we were doing something along the lines of using a decoder(?) object. </p>
<p>The purpose of this function is to open a file from the iPhone, read that file into an array (it's an array of objects that we saved in a previous run of the program). That "decoder" thing has a method that puts data into the array. </p>
<p>Man, I've totally butchered this. I really hope you all can follow, and thanks for the advice. We'll look more closely at it.</p>
|
[
{
"answer_id": 130310,
"author": "Chris Hanson",
"author_id": 714,
"author_profile": "https://Stackoverflow.com/users/714",
"pm_score": 2,
"selected": false,
"text": "NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:0];\n\narray = [foo bar];\n array"
},
{
"answer_id": 147673,
"author": "lajos",
"author_id": 3740,
"author_profile": "https://Stackoverflow.com/users/3740",
"pm_score": 1,
"selected": false,
"text": "NSMuatableArray *myArray = [NSMutableArray arrayWithContentsOfFile:@\"path/to/my/file\"];\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/232/"
] |
129,898
|
<p>I have a database that stores events in it and a page with a calendar object on it. When rendering the days it looks through the months events and if any match the current day being rendered it creates a linkbutton to represent the event in the day on the calendar and adds it to that cell. I add some javascript to the linkbutton to change the window.location to a page to view event details passing EventID in the querystring ( I tried setting the postbackurl of the newly created linkbutton but it wasnt causing a postback... no luck). I need to set a Session variable ie. Session("EditMode") = "Edit" So the new page will know it is to get an existing event info rather than prepare to create a new event? Any SUGGESTIONS?</p>
|
[
{
"answer_id": 130646,
"author": "David Robbins",
"author_id": 19799,
"author_profile": "https://Stackoverflow.com/users/19799",
"pm_score": 1,
"selected": false,
"text": "<script>\nfunction OpenWindow(eventId, editMode)\n{\n var window = window.open(\"popup.aspx?eventId=\" + eventId + \"&editMode=\" + editMode);\n}\n</script>\n onclick=\"OpenWindow(eventId=\" + row[\"eventId\"].ToString() + \"&editMode=\" + editMode.ToString() + \");\"\n"
},
{
"answer_id": 5348470,
"author": "Darshan",
"author_id": 536006,
"author_profile": "https://Stackoverflow.com/users/536006",
"pm_score": 2,
"selected": false,
"text": "<s:hidden id=\"EditModeId\" value=\"%{#session.EditMode}\"/> \n alert(document.getElementById('EditModeId').value);\n"
},
{
"answer_id": 24508546,
"author": "jigar bhatt",
"author_id": 3793569,
"author_profile": "https://Stackoverflow.com/users/3793569",
"pm_score": 0,
"selected": false,
"text": "var page1 = document.getElementById(\"textbox\").value; \nsessionStorage.setItem(\"page1content\", page1);\n document.getElementById(\"textbox2\").value=sessionStorage.getItem(\"page1content\");\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16820/"
] |
129,915
|
<p>What property in Netbeans to I need to change to set the name of my java swing app in the OS X menubar and dock? I found info.plist, but changing @PROJECTNAMEASIDENTIFIEER@ in multiple keys here had no effect.</p>
<p>Thanks,
hating netbeans.</p>
|
[
{
"answer_id": 129931,
"author": "Jeremy",
"author_id": 4419,
"author_profile": "https://Stackoverflow.com/users/4419",
"pm_score": 2,
"selected": false,
"text": "nbproject/project.properties\n\nnbproject/project.xml\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10597/"
] |
129,917
|
<p>It's common knowledge that using System.Diagnostics.Process.Start is the way to launch a url from a C# applicaiton:</p>
<p>System.Diagnostics.Process.Start("<a href="http://www.mywebsite.com" rel="nofollow noreferrer">http://www.mywebsite.com</a>");</p>
<p>However, if this url is invalid the application seems to have no way of knowing that the call failed or why. Is there a better way to launch a web browser? If not, what is my best option for url validation?</p>
|
[
{
"answer_id": 129956,
"author": "Troels Thomsen",
"author_id": 20138,
"author_profile": "https://Stackoverflow.com/users/20138",
"pm_score": 4,
"selected": true,
"text": "try\n{\n var url = new Uri(\"http://www.example.com/\");\n\n Process.Start(url.AbsoluteUri);\n}\ncatch (UriFormatException)\n{\n // URL is not parsable\n}\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129917",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9251/"
] |
129,920
|
<p>I have developed a couple of extensions for Firefox, and am annoyed that it is so hard to get the extension signed. When an extension isn't signed, it says "Author not verified" when it is installed, and to me that just looks wrong.</p>
<p>I have a simple build script that builds my .xpi file from sources, and I have a licenced copy of PKZip (which according to a number of tutorials is required to build a signed xpi file that Firefox requires), but I haven't found a way to get a free/cheap certificate that actually works or a set of instructions that do the trick.</p>
<p>Since my extensions are free, I don't want to spend $400 on a commercial certificate, but I don't mind spending $50 or so to get it done. I have both Linux and Windows machines, although my build script currently uses Windows and that would be most convenient to use.</p>
<p>How have you solved this? What do I need to do to automatically and securely sign my extensions when they are built?</p>
<p>Edit: I appreciate the Google hits, but the steps they provide aren't complete enough on how to actually get a certificate that works. The feeling I get reminds me of this classic:</p>
<p><img src="https://i.stack.imgur.com/PIgLC.gif" alt="alt text" title="Then a miracle occurs..."></p>
|
[
{
"answer_id": 27707675,
"author": "Joscha",
"author_id": 217357,
"author_profile": "https://Stackoverflow.com/users/217357",
"pm_score": 1,
"selected": false,
"text": "openssl pkcs12 -in key.p12 -nodes -out private.key -nocerts Public Key of Certum Level III CA -----BEGIN CERTIFICATE-----\n[your certificate from Certum]\n-----END CERTIFICATE-----\n-----BEGIN RSA PRIVATE KEY-----\n[the private key you just converted from the .p12 file from your keychain]\n-----END RSA PRIVATE KEY-----\n-----BEGIN CERTIFICATE-----\n[the Certum Level III CA public key you just downloaded]\n-----END CERTIFICATE-----\n cert_with_key_and_ca.pem pip install https://github.com/nmaier/xpisign.py/zipball/master xpisign -k cert_with_key_and_ca.pem unsigned.xpi signed.xpi signed.xpi"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13394/"
] |
129,927
|
<p>I have a page in my vb.net web application that needs to toss a bunch of data into a text file and then present it to the user for download. What's the best / most efficient way to build such a text file on a .net web server?</p>
<p>Edit: to answer a question down below, this is going to be a download once and then throw-away kind of file.</p>
<p>Update: I glued together the suggestions by John Rudy and DavidK, and it worked perfectly. Thanks, all!</p>
|
[
{
"answer_id": 129953,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "private void Button1_Click(object sender, System.EventArgs e)\n{\n StringBuilder output = new StringBuilder;\n //populate output with the string content\n String fileName = \"textfile.txt\";\n\n Response.ContentType = \"application/octet-stream\";\n Response.AddHeader(\"Content-Disposition\", \"attachment; filename=\" + fileName);\n Response.WriteFile(output.ToString());\n\n}\n"
},
{
"answer_id": 129963,
"author": "Meff",
"author_id": 9647,
"author_profile": "https://Stackoverflow.com/users/9647",
"pm_score": 2,
"selected": false,
"text": "public void ProcessRequest(HttpContext context)\n{\n response = context.Response;\n response.ContentType = \"text/xml\"; \n using (TextWriter textWriter = new StreamWriter(response.OutputStream, System.Text.Encoding.UTF8))\n {\n XmlTextWriter writer = new XmlTextWriter(textWriter);\n writer.Formatting = Formatting.Indented;\n writer.WriteStartDocument();\n writer.WriteStartElement(\"urlset\");\n writer.WriteAttributeString(\"xmlns:xsi\", \"http://www.w3.org/2001/XMLSchema-instance\");\n writer.WriteAttributeString(\"xsi:schemaLocation\", \"http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd\");\n writer.WriteAttributeString(\"xmlns\", \"http://www.sitemaps.org/schemas/sitemap/0.9\");\n\n // Add Home Page\n writer.WriteStartElement(\"url\");\n writer.WriteElementString(\"loc\", \"http://example.com\");\n writer.WriteElementString(\"changefreq\", \"daily\");\n writer.WriteEndElement(); // url\n\n // Add code Loop here for page nodes\n /*\n {\n writer.WriteStartElement(\"url\");\n writer.WriteElementString(\"loc\", url);\n writer.WriteElementString(\"changefreq\", \"monthly\");\n writer.WriteEndElement(); // url\n }\n */\n writer.WriteEndElement(); // urlset\n } \n}\n"
},
{
"answer_id": 129998,
"author": "John Rudy",
"author_id": 14048,
"author_profile": "https://Stackoverflow.com/users/14048",
"pm_score": 3,
"selected": true,
"text": "HttpResponse response = HttpContext.Current.Response;\nresponse.Clear();\nresponse.ContentType = \"application/octet-stream\";\nresponse.Charset = \"\";\nresponse.AddHeader(\"Content-Disposition\", String.Format(\"attachment; filename=\\\"{0}\\\"\", filename));\nresponse.Flush();\nresponse.Write(text);\nresponse.End();\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19074/"
] |
129,945
|
<p>Can someone explain what exactly the string "0 but true" means in Perl? As far as I understand, it equals zero in an integer comparison, but evaluates to true when used as a boolean. Is this correct? Is this a normal behavior of the language or is this a special string treated as a special case in the interpreter?</p>
|
[
{
"answer_id": 129970,
"author": "Daniel Papasian",
"author_id": 7548,
"author_profile": "https://Stackoverflow.com/users/7548",
"pm_score": 3,
"selected": false,
"text": "if (int(\"0 but true\")) { print \"zero\"; } if (\"0 but true\") { print \"true\"; }"
},
{
"answer_id": 129986,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 7,
"selected": true,
"text": "perlsyn 0 '0' \"\" () undef ! not \"\" 0 0 0 \"0 but true\""
},
{
"answer_id": 130027,
"author": "moritz",
"author_id": 14132,
"author_profile": "https://Stackoverflow.com/users/14132",
"pm_score": 6,
"selected": false,
"text": "\"0 but true\" $ perl -wle 'print \"0 but true\" + 3'\n3\n$ perl -wle 'print \"0 but crazy\" + 3'\nArgument \"0 but crazy\" isn't numeric in addition (+) at -e line 1.\n3\n"
},
{
"answer_id": 130044,
"author": "Frosty",
"author_id": 7476,
"author_profile": "https://Stackoverflow.com/users/7476",
"pm_score": 2,
"selected": false,
"text": "if(x)\n\nfor x: yields:\n1 -> true\n0 -> false\n-1 -> true\n\"true\" -> true\n\"false\" -> true\n\"0 but true\" -> true\nint(\"0 but true\") ->false\n sub find_x()\n if($x = find_x)\n{\n print int($x) . \"\\n\";\n}\n"
},
{
"answer_id": 130139,
"author": "Jon Ericson",
"author_id": 1438,
"author_profile": "https://Stackoverflow.com/users/1438",
"pm_score": 3,
"selected": false,
"text": "while($c = characters_in_line($file)){\n ...\n};\n"
},
{
"answer_id": 145680,
"author": "jkramer",
"author_id": 12523,
"author_profile": "https://Stackoverflow.com/users/12523",
"pm_score": 2,
"selected": false,
"text": "$ strings /usr/lib/perl5/5.10.0/linux/CORE/libperl.so | grep -i true\nPerl_sv_true\n%-p did not return a true value\n0 but true\n0 but true\n"
},
{
"answer_id": 5318075,
"author": "ikegami",
"author_id": 589924,
"author_profile": "https://Stackoverflow.com/users/589924",
"pm_score": 3,
"selected": false,
"text": "\"\" \"0\" \"0 but true\" \"0 but true\" looks_like_number(\"0 but true\")"
},
{
"answer_id": 5318174,
"author": "geekosaur",
"author_id": 643977,
"author_profile": "https://Stackoverflow.com/users/643977",
"pm_score": 6,
"selected": false,
"text": "ioctl perldoc -f ioctl ioctl fcntl if OS returns: then Perl returns:\n\n -1 undefined value\n 0 string \"0 but true\"\nanything else that number\n $retval = ioctl(...) || -1;\nprintf \"System returned %d\\n\", $retval;\n \"0 but true\" -w"
},
{
"answer_id": 5318503,
"author": "David W.",
"author_id": 368630,
"author_profile": "https://Stackoverflow.com/users/368630",
"pm_score": 5,
"selected": false,
"text": "0 but true die \"You can only add two numbers\\n\" if (not add(3, -2));\ndie \"You can only add two numbers\\n\" if (not add(\"cow\", \"dog\"));\ndie \"You can only add two numbers\\n\" if (not add(3, -3));\n 1 3 -3 0 add 0 but true my $value = \"0 but true\";\nprint qq(Add 1,000,000 to it: ) . (1_000_000 + $value) . \"\\n\";\nprint \"Multiply it by 1,000,000: \" . 1_000_000 * $value . \"\\n\";\n index(\"barfoo\", \"foo\"); #This returns 3\nindex(\"barfoo\", \"bar\"); #This returns 0\nindex(\"barfoo\", \"fu\"); #This returns ...uh...\n -1 if ($position = index($string, $substring)) {\n print \"It worked!\\n\";\n}\nelse {\n print \"If failed!\\n\";\n}\n else if index undef if else"
},
{
"answer_id": 10935533,
"author": "F. Hauri",
"author_id": 1442676,
"author_profile": "https://Stackoverflow.com/users/1442676",
"pm_score": 2,
"selected": false,
"text": "for arg in \"'0 but true'\" \"1.0*('0 but true')\" \\\n \"1.0*('0 but false')\" 0 1 \"''\" \"0.0\" \\\n \"'false'\" \"'Ja'\" \"'Nein'\" \"'Oui'\" \\\n \"'Non'\" \"'Yes'\" \"'No'\" ;do\n printf \"%-32s: %s\\n\" \"$arg\" \"$(\n perl -we '\n my $ans=eval $ARGV[0];\n $ans=~s/^(Non?|Nein)$//;\n if ($ans) {\n printf \"true: |%s|\\n\",$ans\n } else {\n printf \"false: |%s|\", $ans\n };' \"$arg\"\n )\"\n done\n '0 but true' : true: |0 but true|\n1.0*('0 but true') : false: |0|\nArgument \"0 but false\" isn't numeric in multiplication (*) at (eval 1) line 1.\n1.0*('0 but false') : false: |0|\n0 : false: |0|\n1 : true: |1|\n'' : false: ||\n0.0 : false: |0|\n'false' : true: |false|\n'Ja' : true: |Ja|\n'Nein' : false: ||\n'Oui' : true: |Oui|\n'Non' : false: ||\n'Yes' : true: |Yes|\n'No' : false: ||\n man -P'less +\"/0 but [a-z]*\"' perlfunc\n\n ... \"fcntl\". Like \"ioctl\", it maps a 0 return from the system call\n into \"0 but true\" in Perl. This string is true in boolean\n context and 0 in numeric context. It is also exempt from the\n normal -w warnings on improper numeric conversions. ...\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12523/"
] |
129,958
|
<p>I have several different locations in a fairly wide area, each with a Linux server storing company data. This data changes every day in different ways at each different location. I need a way to keep this data up-to-date and synced between all these locations.</p>
<p>For example:</p>
<p>In one location someone places a set of images on their local server. In another location, someone else places a group of documents on their local server. A third location adds a handful of both images and documents to their server. In two other locations, no changes are made to their local servers at all. By the next morning, I need the servers at all five locations to have all those images and documents.</p>
<p>My first instinct is to use rsync and a cron job to do the syncing over night (1 a.m. to 6 a.m. or so), when none of the bandwidth at our locations is being used. It seems to me that it would work best to have one server be the "central" server, pulling in all the files from the other servers first. Then it would push those changes back out to each remote server? Or is there another, better way to perform this function?</p>
|
[
{
"answer_id": 130736,
"author": "Dan Udey",
"author_id": 21450,
"author_profile": "https://Stackoverflow.com/users/21450",
"pm_score": 2,
"selected": false,
"text": "pyinotify spreadsheet.doc"
},
{
"answer_id": 130795,
"author": "Jeremy Cantrell",
"author_id": 18866,
"author_profile": "https://Stackoverflow.com/users/18866",
"pm_score": 2,
"selected": false,
"text": "dpkg --get-selections dpkg --set-selections"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129958",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21885/"
] |
129,968
|
<p>Is it possible to convert a <code>com.vividsolutions.jts.geom.Geometry</code> (or a subclass of it) into a class that implements <code>java.awt.Shape</code>? Which library or method can I use to achieve that goal?</p>
|
[
{
"answer_id": 129995,
"author": "tim_yates",
"author_id": 6509,
"author_profile": "https://Stackoverflow.com/users/6509",
"pm_score": 3,
"selected": true,
"text": "com.vividsolutions.jump.workbench.ui.renderer.java2D.Java2DConverter\n"
},
{
"answer_id": 30752409,
"author": "user3776894",
"author_id": 3776894,
"author_profile": "https://Stackoverflow.com/users/3776894",
"pm_score": 3,
"selected": false,
"text": "import java.awt.Graphics;\nimport java.awt.Graphics2D;\nimport java.awt.Shape;\n\nimport javax.swing.JFrame;\nimport javax.swing.JPanel;\n\nimport com.vividsolutions.jts.awt.ShapeWriter;\nimport com.vividsolutions.jts.geom.Coordinate;\nimport com.vividsolutions.jts.geom.GeometryFactory;\nimport com.vividsolutions.jts.geom.LineString;\nimport com.vividsolutions.jts.geom.Polygon;\n\npublic class Paint extends JPanel{\n public void paint(Graphics g) {\n\n Coordinate[] coords = new Coordinate[] {new Coordinate(400, 0), new Coordinate(200, 200), new Coordinate(400, 400), new Coordinate(600, 200), new Coordinate(400, 0) };\n Polygon polygon = new GeometryFactory().createPolygon(coords);\n\n LineString ls = new GeometryFactory().createLineString(new Coordinate[] {new Coordinate(20, 20), new Coordinate(200, 20)});\n\n ShapeWriter sw = new ShapeWriter();\n Shape polyShape = sw.toShape(polygon);\n Shape linShape = sw.toShape(ls);\n\n ((Graphics2D) g).draw(polyShape);\n ((Graphics2D) g).draw(linShape);\n\n\n }\n public static void main(String[] args) {\n JFrame f = new JFrame();\n f.getContentPane().add(new Paint());\n f.setSize(700, 700);\n f.setVisible(true);\n }\n}\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/129968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21005/"
] |
130,015
|
<p>I have a Rails 2.0.2 application running with a postgresql db. The machine will receive data on a TCP port. I already have coded a working ruby multithreaded tcp server to receive the requests, but I need this code to run alongside my Rails app.</p>
<p>So I guess I need to know how to span a new process inside Rails, or how to create a worker thread that will run my threaded tcp server loop. My ruby tcp server could have access to ActiveRecord, but it's not necessary (I can always create an http request, posting the received data to the original Rails server)</p>
|
[
{
"answer_id": 130772,
"author": "Ian Terrell",
"author_id": 9269,
"author_profile": "https://Stackoverflow.com/users/9269",
"pm_score": 2,
"selected": true,
"text": "win32-service win32utils"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/130015",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18879/"
] |
130,020
|
<p>Can anyone recommend a dropdownlist control for asp.net (3.5) that can render option groups? Thanks</p>
|
[
{
"answer_id": 130046,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 7,
"selected": true,
"text": "'This codes makes the dropdownlist control recognize items with \"--\"\n'for the label or items with an OptionGroup attribute and render them\n'as <optgroup> instead of <option>.\nPublic Class DropDownListAdapter\n Inherits System.Web.UI.WebControls.Adapters.WebControlAdapter\n\n Protected Overrides Sub RenderContents(ByVal writer As HtmlTextWriter)\n Dim list As DropDownList = Me.Control\n Dim currentOptionGroup As String\n Dim renderedOptionGroups As New Generic.List(Of String)\n\n For Each item As ListItem In list.Items\n Page.ClientScript.RegisterForEventValidation(list.UniqueID, item.Value)\n If item.Attributes(\"OptionGroup\") IsNot Nothing Then\n 'The item is part of an option group\n currentOptionGroup = item.Attributes(\"OptionGroup\")\n If Not renderedOptionGroups.Contains(currentOptionGroup) Then\n 'the header was not written- do that first\n 'TODO: make this stack-based, so the same option group can be used more than once in longer select element (check the most-recent stack item instead of anything in the list)\n If (renderedOptionGroups.Count > 0) Then\n RenderOptionGroupEndTag(writer) 'need to close previous group\n End If\n RenderOptionGroupBeginTag(currentOptionGroup, writer)\n renderedOptionGroups.Add(currentOptionGroup)\n End If\n RenderListItem(item, writer)\n ElseIf item.Text = \"--\" Then 'simple separator\n RenderOptionGroupBeginTag(\"--\", writer)\n RenderOptionGroupEndTag(writer)\n Else\n 'default behavior: render the list item as normal\n RenderListItem(item, writer)\n End If\n Next item\n\n If renderedOptionGroups.Count > 0 Then\n RenderOptionGroupEndTag(writer)\n End If\n End Sub\n\n Private Sub RenderOptionGroupBeginTag(ByVal name As String, ByVal writer As HtmlTextWriter)\n writer.WriteBeginTag(\"optgroup\")\n writer.WriteAttribute(\"label\", name)\n writer.Write(HtmlTextWriter.TagRightChar)\n writer.WriteLine()\n End Sub\n\n Private Sub RenderOptionGroupEndTag(ByVal writer As HtmlTextWriter)\n writer.WriteEndTag(\"optgroup\")\n writer.WriteLine()\n End Sub\n\n Private Sub RenderListItem(ByVal item As ListItem, ByVal writer As HtmlTextWriter)\n writer.WriteBeginTag(\"option\")\n writer.WriteAttribute(\"value\", item.Value, True)\n If item.Selected Then\n writer.WriteAttribute(\"selected\", \"selected\", False)\n End If\n\n For Each key As String In item.Attributes.Keys\n writer.WriteAttribute(key, item.Attributes(key))\n Next key\n\n writer.Write(HtmlTextWriter.TagRightChar)\n HttpUtility.HtmlEncode(item.Text, writer)\n writer.WriteEndTag(\"option\")\n writer.WriteLine()\n End Sub\nEnd Class\n /* This codes makes the dropdownlist control recognize items with \"--\"\n * for the label or items with an OptionGroup attribute and render them\n * as <optgroup> instead of <option>.\n */\npublic class DropDownListAdapter : WebControlAdapter\n{\n protected override void RenderContents(HtmlTextWriter writer)\n {\n //System.Web.HttpContext.Current.Response.Write(\"here\");\n var list = (DropDownList)this.Control;\n string currentOptionGroup;\n var renderedOptionGroups = new List<string>();\n\n foreach (ListItem item in list.Items)\n {\n Page.ClientScript.RegisterForEventValidation(list.UniqueID, item.Value);\n //Is the item part of an option group?\n if (item.Attributes[\"OptionGroup\"] != null)\n {\n currentOptionGroup = item.Attributes[\"OptionGroup\"];\n //Was the option header already written, then just render the list item\n if (renderedOptionGroups.Contains(currentOptionGroup))\n RenderListItem(item, writer);\n //The header was not written,do that first\n else\n {\n //Close previous group\n if (renderedOptionGroups.Count > 0)\n RenderOptionGroupEndTag(writer);\n\n RenderOptionGroupBeginTag(currentOptionGroup, writer);\n renderedOptionGroups.Add(currentOptionGroup);\n RenderListItem(item, writer);\n }\n }\n //Simple separator\n else if (item.Text == \"--\")\n {\n RenderOptionGroupBeginTag(\"--\", writer);\n RenderOptionGroupEndTag(writer);\n }\n //Default behavior, render the list item as normal\n else\n RenderListItem(item, writer);\n }\n\n if (renderedOptionGroups.Count > 0)\n RenderOptionGroupEndTag(writer);\n }\n\n private void RenderOptionGroupBeginTag(string name, HtmlTextWriter writer)\n {\n writer.WriteBeginTag(\"optgroup\");\n writer.WriteAttribute(\"label\", name);\n writer.Write(HtmlTextWriter.TagRightChar);\n writer.WriteLine();\n }\n private void RenderOptionGroupEndTag(HtmlTextWriter writer)\n {\n writer.WriteEndTag(\"optgroup\");\n writer.WriteLine();\n }\n private void RenderListItem(ListItem item, HtmlTextWriter writer)\n {\n writer.WriteBeginTag(\"option\");\n writer.WriteAttribute(\"value\", item.Value, true);\n if (item.Selected)\n writer.WriteAttribute(\"selected\", \"selected\", false);\n\n foreach (string key in item.Attributes.Keys)\n writer.WriteAttribute(key, item.Attributes[key]);\n\n writer.Write(HtmlTextWriter.TagRightChar);\n HttpUtility.HtmlEncode(item.Text, writer);\n writer.WriteEndTag(\"option\");\n writer.WriteLine();\n }\n}\n <!--\n You can find existing browser definitions at\n <windir>\\Microsoft.NET\\Framework\\<ver>\\CONFIG\\Browsers\n-->\n<browsers>\n <browser refID=\"Default\">\n <controlAdapters>\n <adapter controlType=\"System.Web.UI.WebControls.DropDownList\" \n adapterType=\"DropDownListAdapter\" />\n </controlAdapters>\n </browser>\n</browsers>\n"
},
{
"answer_id": 1056436,
"author": "Nick Franceschina",
"author_id": 130221,
"author_profile": "https://Stackoverflow.com/users/130221",
"pm_score": 4,
"selected": false,
"text": "\n\nusing System;\nusing System.Web.UI.WebControls.Adapters;\nusing System.Web.UI;\nusing System.Web.UI.WebControls;\nusing System.Collections.Generic;\nusing System.Web;\n\n//This codes makes the dropdownlist control recognize items with \"--\"'\n//for the label or items with an OptionGroup attribute and render them'\n//as instead of .'\npublic class DropDownListAdapter : WebControlAdapter\n{\n\n protected override void RenderContents(HtmlTextWriter writer)\n {\n DropDownList list = Control as DropDownList;\n string currentOptionGroup;\n List renderedOptionGroups = new List();\n\n foreach(ListItem item in list.Items)\n {\n if (item.Attributes[\"OptionGroup\"] != null)\n {\n //'The item is part of an option group'\n currentOptionGroup = item.Attributes[\"OptionGroup\"];\n //'the option header was already written, just render the list item'\n if(renderedOptionGroups.Contains(currentOptionGroup))\n RenderListItem(item, writer);\n else\n {\n //the header was not written- do that first'\n if (renderedOptionGroups.Count > 0)\n RenderOptionGroupEndTag(writer); //'need to close previous group'\n RenderOptionGroupBeginTag(currentOptionGroup, writer);\n renderedOptionGroups.Add(currentOptionGroup);\n RenderListItem(item, writer);\n }\n }\n else if (item.Text == \"--\") //simple separator\n {\n RenderOptionGroupBeginTag(\"--\", writer);\n RenderOptionGroupEndTag(writer);\n }\n else\n {\n //default behavior: render the list item as normal'\n RenderListItem(item, writer);\n }\n }\n\n if(renderedOptionGroups.Count > 0)\n RenderOptionGroupEndTag(writer);\n }\n\n private void RenderOptionGroupBeginTag(string name, HtmlTextWriter writer)\n {\n writer.WriteBeginTag(\"optgroup\");\n writer.WriteAttribute(\"label\", name);\n writer.Write(HtmlTextWriter.TagRightChar);\n writer.WriteLine();\n }\n\n private void RenderOptionGroupEndTag(HtmlTextWriter writer)\n {\n writer.WriteEndTag(\"optgroup\");\n writer.WriteLine();\n }\n\n private void RenderListItem(ListItem item, HtmlTextWriter writer)\n {\n writer.WriteBeginTag(\"option\");\n writer.WriteAttribute(\"value\", item.Value, true);\n if (item.Selected)\n writer.WriteAttribute(\"selected\", \"selected\", false);\n\n\n foreach (string key in item.Attributes.Keys)\n writer.WriteAttribute(key, item.Attributes[key]);\n\n writer.Write(HtmlTextWriter.TagRightChar);\n HttpUtility.HtmlEncode(item.Text, writer);\n writer.WriteEndTag(\"option\");\n writer.WriteLine();\n }\n\n}\n\n\n\n"
},
{
"answer_id": 1578193,
"author": "Cédric Boivin",
"author_id": 82595,
"author_profile": "https://Stackoverflow.com/users/82595",
"pm_score": 3,
"selected": false,
"text": "protected internal override void RenderContents(HtmlTextWriter writer)\n {\n ListItemCollection items = this.Items;\n int count = items.Count;\n if (count > 0)\n {\n bool flag = false;\n for (int i = 0; i < count; i++)\n {\n ListItem item = items[i];\n if (item.Enabled)\n {\n writer.WriteBeginTag(\"option\");\n if (item.Selected)\n {\n if (flag)\n {\n this.VerifyMultiSelect();\n }\n flag = true;\n writer.WriteAttribute(\"selected\", \"selected\");\n }\n writer.WriteAttribute(\"value\", item.Value, true);\n if (item.HasAttributes)\n {\n item.Attributes.Render(writer);\n }\n if (this.Page != null)\n {\n this.Page.ClientScript.RegisterForEventValidation(this.UniqueID, item.Value);\n }\n writer.Write('>');\n HttpUtility.HtmlEncode(item.Text, writer);\n writer.WriteEndTag(\"option\");\n writer.WriteLine();\n }\n }\n }\n }\n public class DropDownListWithOptionGroup : DropDownList\n {\n public const string OptionGroupTag = \"optgroup\";\n private const string OptionTag = \"option\";\n protected override void RenderContents(System.Web.UI.HtmlTextWriter writer)\n {\n ListItemCollection items = this.Items;\n int count = items.Count; \n string tag;\n string optgroupLabel;\n if (count > 0)\n {\n bool flag = false;\n for (int i = 0; i < count; i++)\n {\n tag = OptionTag;\n optgroupLabel = null;\n ListItem item = items[i];\n if (item.Enabled)\n {\n if (item.Attributes != null && item.Attributes.Count > 0 && item.Attributes[OptionGroupTag] != null)\n {\n tag = OptionGroupTag;\n optgroupLabel = item.Attributes[OptionGroupTag];\n } \n writer.WriteBeginTag(tag);\n // NOTE(cboivin): Is optionGroup\n if (!string.IsNullOrEmpty(optgroupLabel))\n {\n writer.WriteAttribute(\"label\", optgroupLabel);\n }\n else\n {\n if (item.Selected)\n {\n if (flag)\n {\n this.VerifyMultiSelect();\n }\n flag = true;\n writer.WriteAttribute(\"selected\", \"selected\");\n }\n writer.WriteAttribute(\"value\", item.Value, true);\n if (item.Attributes != null && item.Attributes.Count > 0)\n {\n item.Attributes.Render(writer);\n }\n if (this.Page != null)\n {\n this.Page.ClientScript.RegisterForEventValidation(this.UniqueID, item.Value);\n }\n }\n writer.Write('>');\n HttpUtility.HtmlEncode(item.Text, writer);\n writer.WriteEndTag(tag);\n writer.WriteLine();\n }\n }\n }\n\n }\n }\n"
},
{
"answer_id": 1758950,
"author": "Glennular",
"author_id": 14753,
"author_profile": "https://Stackoverflow.com/users/14753",
"pm_score": 1,
"selected": false,
"text": " Protected Overloads Overrides Sub RenderContents(ByVal writer As HtmlTextWriter)\n Dim list As DropDownList = Me\n\n Dim currentOptionGroup As String\n Dim renderedOptionGroups As New List(Of String)()\n\n For Each item As ListItem In list.Items\n If item.Attributes(\"OptionGroup\") Is Nothing Then\n RenderListItem(item, writer)\n Else\n currentOptionGroup = item.Attributes(\"OptionGroup\")\n\n If renderedOptionGroups.Contains(currentOptionGroup) Then\n RenderListItem(item, writer)\n Else\n If renderedOptionGroups.Count > 0 Then\n RenderOptionGroupEndTag(writer)\n End If\n\n RenderOptionGroupBeginTag(currentOptionGroup, writer)\n renderedOptionGroups.Add(currentOptionGroup)\n\n RenderListItem(item, writer)\n End If\n End If\n Next\n\n If renderedOptionGroups.Count > 0 Then\n RenderOptionGroupEndTag(writer)\n End If\nEnd Sub\n\nPrivate Sub RenderOptionGroupBeginTag(ByVal name As String, ByVal writer As HtmlTextWriter)\n writer.WriteBeginTag(\"optgroup\")\n writer.WriteAttribute(\"label\", name)\n writer.Write(HtmlTextWriter.TagRightChar)\n writer.WriteLine()\nEnd Sub\n\nPrivate Sub RenderOptionGroupEndTag(ByVal writer As HtmlTextWriter)\n writer.WriteEndTag(\"optgroup\")\n writer.WriteLine()\nEnd Sub\n\nPrivate Sub RenderListItem(ByVal item As ListItem, ByVal writer As HtmlTextWriter)\n writer.WriteBeginTag(\"option\")\n writer.WriteAttribute(\"value\", item.Value, True)\n\n If item.Selected Then\n writer.WriteAttribute(\"selected\", \"selected\", False)\n End If\n\n For Each key As String In item.Attributes.Keys\n writer.WriteAttribute(key, item.Attributes(key))\n Next\n\n writer.Write(HtmlTextWriter.TagRightChar)\n HttpUtility.HtmlEncode(item.Text, writer)\n writer.WriteEndTag(\"option\")\n writer.WriteLine()\nEnd Sub\nProtected Overrides Function SaveViewState() As Object\n ' Create an object array with one element for the CheckBoxList's\n ' ViewState contents, and one element for each ListItem in skmCheckBoxList\n Dim state(Me.Items.Count + 1 - 1) As Object 'stupid vb array\n Dim baseState As Object = MyBase.SaveViewState()\n\n state(0) = baseState\n ' Now, see if we even need to save the view state\n Dim itemHasAttributes As Boolean = False\n\n For i As Integer = 0 To Me.Items.Count - 1\n If Me.Items(i).Attributes.Count > 0 Then\n itemHasAttributes = True\n ' Create an array of the item's Attribute's keys and values\n Dim attribKV(Me.Items(i).Attributes.Count * 2 - 1) As Object 'stupid vb array\n Dim k As Integer = 0\n For Each key As String In Me.Items(i).Attributes.Keys\n attribKV(k) = key\n k += 1\n attribKV(k) = Me.Items(i).Attributes(key)\n k += 1\n Next\n state(i + 1) = attribKV\n End If\n Next\n ' return either baseState or state, depending on whether or not\n ' any ListItems had attributes\n If (itemHasAttributes) Then\n Return state\n Else\n Return baseState\n End If\nEnd Function\n\n\nProtected Overrides Sub LoadViewState(ByVal savedState As Object)\n If savedState Is Nothing Then Return\n ' see if savedState is an object or object array\n If Not savedState.GetType.GetElementType() Is Nothing AndAlso savedState.GetType.GetElementType().Equals(GetType(Object)) Then\n\n ' we have just the base state\n MyBase.LoadViewState(savedState(0))\n 'we have an array of items with attributes\n Dim state() As Object = savedState\n MyBase.LoadViewState(state(0)) '/ load the base state\n For i As Integer = 1 To state.Length - 1\n If Not state(i) Is Nothing Then\n ' Load back in the attributes\n Dim attribKV() As Object = state(i)\n For k As Integer = 0 To attribKV.Length - 1 Step +2\n Me.Items(i - 1).Attributes.Add(attribKV(k).ToString(), attribKV(k + 1).ToString())\n Next\n End If\n Next\n Else\n 'load it normal\n MyBase.LoadViewState(savedState)\n End If\nEnd Sub\n"
},
{
"answer_id": 1942378,
"author": "Irfan",
"author_id": 236324,
"author_profile": "https://Stackoverflow.com/users/236324",
"pm_score": 5,
"selected": false,
"text": "ListItem wrapAll() foreach (ListItem item in ((DropDownList)sender).Items)\n{\n if (System.Int32.Parse(item.Value) < 5)\n item.Attributes.Add(\"classification\", \"LessThanFive\");\n else\n item.Attributes.Add(\"classification\", \"GreaterThanFive\");\n} \n $(document).ready(function() {\n //Create groups for dropdown list\n $(\"select.listsmall option[@classification='LessThanFive']\")\n .wrapAll(\"<optgroup label='Less than five'>\");\n $(\"select.listsmall option[@classification='GreaterThanFive']\")\n .wrapAll(\"<optgroup label='Greater than five'>\"); \n});\n"
},
{
"answer_id": 2117182,
"author": "Tom Miller",
"author_id": 256715,
"author_profile": "https://Stackoverflow.com/users/256715",
"pm_score": 3,
"selected": false,
"text": " public const string OptionGroupTag = \"optgroup\";\n private const string OptionTag = \"option\";\n protected override void RenderContents(System.Web.UI.HtmlTextWriter writer)\n {\n ListItemCollection items = this.Items;\n int count = items.Count;\n string tag;\n string optgroupLabel;\n if (count > 0)\n {\n bool flag = false;\n for (int i = 0; i < count; i++)\n {\n tag = OptionTag;\n optgroupLabel = null;\n ListItem item = items[i];\n if (item.Enabled)\n {\n if (item.Attributes != null && item.Attributes.Count > 0 && item.Attributes[OptionGroupTag] != null)\n {\n tag = OptionGroupTag;\n optgroupLabel = item.Attributes[OptionGroupTag];\n }\n writer.WriteBeginTag(tag);\n // NOTE(cboivin): Is optionGroup\n if (!string.IsNullOrEmpty(optgroupLabel))\n {\n writer.WriteAttribute(\"label\", optgroupLabel);\n }\n else\n {\n if (item.Selected)\n {\n if (flag)\n {\n this.VerifyMultiSelect();\n }\n flag = true;\n writer.WriteAttribute(\"selected\", \"selected\");\n }\n writer.WriteAttribute(\"value\", item.Value, true);\n if (item.Attributes != null && item.Attributes.Count > 0)\n {\n item.Attributes.Render(writer);\n }\n if (this.Page != null)\n {\n this.Page.ClientScript.RegisterForEventValidation(this.UniqueID, item.Value);\n }\n }\n writer.Write('>');\n HttpUtility.HtmlEncode(item.Text, writer);\n writer.WriteEndTag(tag);\n writer.WriteLine();\n }\n }\n }\n }\n\n protected override object SaveViewState()\n {\n object[] state = new object[this.Items.Count + 1];\n object baseState = base.SaveViewState();\n state[0] = baseState;\n bool itemHasAttributes = false;\n\n for (int i = 0; i < this.Items.Count; i++)\n {\n if (this.Items[i].Attributes.Count > 0)\n {\n itemHasAttributes = true;\n object[] attributes = new object[this.Items[i].Attributes.Count * 2];\n int k = 0;\n\n foreach (string key in this.Items[i].Attributes.Keys)\n {\n attributes[k] = key;\n k++;\n attributes[k] = this.Items[i].Attributes[key];\n k++;\n }\n state[i + 1] = attributes;\n }\n }\n\n if (itemHasAttributes)\n return state;\n return baseState;\n }\n\n protected override void LoadViewState(object savedState)\n {\n if (savedState == null)\n return;\n\n if (!(savedState.GetType().GetElementType() == null) &&\n (savedState.GetType().GetElementType().Equals(typeof(object))))\n {\n object[] state = (object[])savedState;\n base.LoadViewState(state[0]);\n\n for (int i = 1; i < state.Length; i++)\n {\n if (state[i] != null)\n {\n object[] attributes = (object[])state[i];\n for (int k = 0; k < attributes.Length; k += 2)\n {\n this.Items[i - 1].Attributes.Add\n (attributes[k].ToString(), attributes[k + 1].ToString());\n }\n }\n }\n }\n else\n {\n base.LoadViewState(savedState);\n }\n }\n"
},
{
"answer_id": 3104581,
"author": "nw.",
"author_id": 307960,
"author_profile": "https://Stackoverflow.com/users/307960",
"pm_score": 4,
"selected": false,
"text": " public class ExtendedDropDownList : System.Web.UI.WebControls.DropDownList\n{\n public const string OptionGroupTag = \"optgroup\";\n private const string OptionTag = \"option\";\n protected override void RenderContents(System.Web.UI.HtmlTextWriter writer)\n {\n ListItemCollection items = this.Items;\n int count = items.Count;\n string tag;\n string optgroupLabel;\n if (count > 0)\n {\n bool flag = false;\n string prevOptGroup = null;\n for (int i = 0; i < count; i++)\n {\n tag = OptionTag;\n optgroupLabel = null;\n ListItem item = items[i];\n if (item.Enabled)\n {\n if (item.Attributes != null && item.Attributes.Count > 0 && item.Attributes[OptionGroupTag] != null)\n {\n optgroupLabel = item.Attributes[OptionGroupTag];\n\n if (prevOptGroup != optgroupLabel)\n {\n if (prevOptGroup != null)\n {\n writer.WriteEndTag(OptionGroupTag);\n }\n writer.WriteBeginTag(OptionGroupTag);\n if (!string.IsNullOrEmpty(optgroupLabel))\n {\n writer.WriteAttribute(\"label\", optgroupLabel);\n }\n writer.Write('>');\n }\n item.Attributes.Remove(OptionGroupTag);\n prevOptGroup = optgroupLabel;\n }\n else\n {\n if (prevOptGroup != null)\n {\n writer.WriteEndTag(OptionGroupTag);\n }\n prevOptGroup = null;\n }\n\n writer.WriteBeginTag(tag);\n if (item.Selected)\n {\n if (flag)\n {\n this.VerifyMultiSelect();\n }\n flag = true;\n writer.WriteAttribute(\"selected\", \"selected\");\n }\n writer.WriteAttribute(\"value\", item.Value, true);\n if (item.Attributes != null && item.Attributes.Count > 0)\n {\n item.Attributes.Render(writer);\n }\n if (optgroupLabel != null)\n {\n item.Attributes.Add(OptionGroupTag, optgroupLabel);\n }\n if (this.Page != null)\n {\n this.Page.ClientScript.RegisterForEventValidation(this.UniqueID, item.Value);\n }\n\n writer.Write('>');\n HttpUtility.HtmlEncode(item.Text, writer);\n writer.WriteEndTag(tag);\n writer.WriteLine();\n if (i == count - 1)\n {\n if (prevOptGroup != null)\n {\n writer.WriteEndTag(OptionGroupTag);\n }\n }\n }\n }\n }\n }\n\n protected override object SaveViewState()\n {\n object[] state = new object[this.Items.Count + 1];\n object baseState = base.SaveViewState();\n state[0] = baseState;\n bool itemHasAttributes = false;\n\n for (int i = 0; i < this.Items.Count; i++)\n {\n if (this.Items[i].Attributes.Count > 0)\n {\n itemHasAttributes = true;\n object[] attributes = new object[this.Items[i].Attributes.Count * 2];\n int k = 0;\n\n foreach (string key in this.Items[i].Attributes.Keys)\n {\n attributes[k] = key;\n k++;\n attributes[k] = this.Items[i].Attributes[key];\n k++;\n }\n state[i + 1] = attributes;\n }\n }\n\n if (itemHasAttributes)\n return state;\n return baseState;\n }\n\n protected override void LoadViewState(object savedState)\n {\n if (savedState == null)\n return;\n\n if (!(savedState.GetType().GetElementType() == null) &&\n (savedState.GetType().GetElementType().Equals(typeof(object))))\n {\n object[] state = (object[])savedState;\n base.LoadViewState(state[0]);\n\n for (int i = 1; i < state.Length; i++)\n {\n if (state[i] != null)\n {\n object[] attributes = (object[])state[i];\n for (int k = 0; k < attributes.Length; k += 2)\n {\n this.Items[i - 1].Attributes.Add\n (attributes[k].ToString(), attributes[k + 1].ToString());\n }\n }\n }\n }\n else\n {\n base.LoadViewState(savedState);\n }\n }\n}\n ListItem item1 = new ListItem(\"option1\");\n item1.Attributes.Add(\"optgroup\", \"CatA\");\n ListItem item2 = new ListItem(\"option2\");\n item2.Attributes.Add(\"optgroup\", \"CatA\");\n ListItem item3 = new ListItem(\"option3\");\n item3.Attributes.Add(\"optgroup\", \"CatB\");\n ListItem item4 = new ListItem(\"option4\");\n item4.Attributes.Add(\"optgroup\", \"CatB\");\n ListItem item5 = new ListItem(\"NoOptGroup\");\n\n ddlTest.Items.Add(item1);\n ddlTest.Items.Add(item2);\n ddlTest.Items.Add(item3);\n ddlTest.Items.Add(item4);\n ddlTest.Items.Add(item5);\n <select name=\"ddlTest\" id=\"Select1\">\n <optgroup label=\"CatA\">\n <option selected=\"selected\" value=\"option1\">option1</option>\n <option value=\"option2\">option2</option>\n </optgroup>\n <optgroup label=\"CatB\">\n <option value=\"option3\">option3</option>\n <option value=\"option4\">option4</option>\n </optgroup>\n <option value=\"NoOptGroup\">NoOptGroup</option>\n </select>\n"
},
{
"answer_id": 8851045,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": " // How to use:\n // 1. Create items in a select element or asp:DropDownList control\n // 2. Set value of an option or ListItem to \"_group_\", those will be converted to optgroups\n // 3. On page onload call createOptGroups(domElement), for example like this:\n // - var lst = document.getElementById('lst');\n // - createOptGroups(lst, \"_group_\");\n // 4. You can change groupMarkerValue to anything, I used \"_group_\"\n function createOptGroups(lst, groupMarkerValue) {\n // Get an array containing the options\n var childNodes = [];\n for (var i = 0; i < lst.options.length; i++)\n childNodes.push(lst.options[i]);\n\n // Get the selected element so we can preserve selection\n var selectedIndex = lst.selectedIndex;\n var selectedChild = childNodes[selectedIndex];\n var selectedValue = selectedChild.value;\n\n // Remove all elements\n while (lst.hasChildNodes())\n lst.removeChild(lst.childNodes[0]);\n\n // Go through the array of options and convert some into groups\n var group = null;\n for (var i = 0; i < childNodes.length; i++) {\n var node = childNodes[i];\n if (node.value == groupMarkerValue) {\n group = document.createElement(\"optgroup\");\n group.label = node.text;\n group.value = groupMarkerValue;\n lst.appendChild(group);\n continue;\n }\n\n // Add to group or directly under list\n (group == null ? lst : group).appendChild(node);\n }\n\n // Preserve selected, no support for multi-selection here, sorry\n selectedChild.selected = true;\n }\n"
},
{
"answer_id": 21481634,
"author": "mhu",
"author_id": 932282,
"author_profile": "https://Stackoverflow.com/users/932282",
"pm_score": 3,
"selected": false,
"text": "private void _addSelectItem(DropDownList list, string title, string value, string group = null) {\n ListItem item = new ListItem(title, value);\n if (!String.IsNullOrEmpty(group))\n {\n item.Attributes[\"data-category\"] = group;\n }\n list.Items.Add(item);\n}\n\n...\n_addSelectItem(dropDown, \"Option 1\", \"1\");\n_addSelectItem(dropDown, \"Option 2\", \"2\", \"Category\");\n_addSelectItem(dropDown, \"Option 3\", \"3\", \"Category\");\n...\n var groups = {};\n$(\"select option[data-category]\").each(function () {\n groups[$.trim($(this).attr(\"data-category\"))] = true;\n});\n$.each(groups, function (c) {\n $(\"select option[data-category='\"+c+\"']\").wrapAll('<optgroup label=\"' + c + '\">');\n});\n"
},
{
"answer_id": 27784921,
"author": "Josh M.",
"author_id": 374198,
"author_profile": "https://Stackoverflow.com/users/374198",
"pm_score": 2,
"selected": false,
"text": "<asp:Repeater ID=\"outerRepeater\" runat=\"server\">\n <HeaderTemplate>\n <select id=\"<%= outerRepeater.ClientID %>\">\n </HeaderTemplate>\n <ItemTemplate>\n <optgroup label=\"<%# Eval(\"GroupText\") %>\">\n <asp:Repeater runat=\"server\" DataSource='<%# Eval(\"Items\") %>'>\n <ItemTemplate>\n <option value=\"<%# Eval(\"Value\") %>\"><%# Eval(\"Text\") %></option>\n </ItemTemplate>\n </asp:Repeater>\n </optgroup>\n </ItemTemplate>\n <FooterTemplate>\n </select>\n </FooterTemplate>\n</asp:Repeater>\n outerRepeater var data = (from o in thingsToDisplay\n group oby GetAlphaGrouping(o.Name) into g\n orderby g.Key\n select new\n {\n Alpha = g.Key,\n Items = g\n });\n private string GetAlphaGrouping(string value)\n{\n string firstChar = value.Substring(0, 1).ToUpper();\n int unused;\n\n if (int.TryParse(firstChar, out unused))\n return \"#\";\n\n return firstChar.ToUpper();\n}\n"
},
{
"answer_id": 59421415,
"author": "brz",
"author_id": 1465881,
"author_profile": "https://Stackoverflow.com/users/1465881",
"pm_score": 0,
"selected": false,
"text": "public class UcDropDownListWithOptGroup : DropDownList\n{\n public const string OptionGroupTag = \"optgroup\";\n private const string OptionTag = \"option\";\n\n protected override void RenderContents(HtmlTextWriter writer)\n {\n ListItemCollection items = this.Items;\n int count = items.Count;\n string tag;\n string optgroupLabel;\n if (count > 0)\n {\n bool flag = false;\n string prevOptGroup = null;\n for (int i = 0; i < count; i++)\n {\n tag = OptionTag;\n optgroupLabel = null;\n ListItem item = items[i];\n if (item.Enabled)\n {\n if (item.Attributes != null && item.Attributes.Count > 0 && item.Attributes[\"data-optgroup\"] != null)\n {\n optgroupLabel = item.Attributes[\"data-optgroup\"];\n\n if (prevOptGroup != optgroupLabel)\n {\n if (prevOptGroup != null)\n {\n writer.WriteEndTag(OptionGroupTag);\n }\n writer.WriteBeginTag(OptionGroupTag);\n if (!string.IsNullOrEmpty(optgroupLabel))\n {\n writer.WriteAttribute(\"label\", optgroupLabel);\n }\n writer.Write('>');\n }\n item.Attributes.Remove(OptionGroupTag);\n prevOptGroup = optgroupLabel;\n }\n else\n {\n if (prevOptGroup != null)\n {\n writer.WriteEndTag(OptionGroupTag);\n }\n prevOptGroup = null;\n }\n\n writer.WriteBeginTag(tag);\n if (item.Selected)\n {\n if (flag)\n {\n this.VerifyMultiSelect();\n }\n flag = true;\n writer.WriteAttribute(\"selected\", \"selected\");\n }\n writer.WriteAttribute(\"value\", item.Value, true);\n if (item.Attributes != null && item.Attributes.Count > 0)\n {\n item.Attributes.Render(writer);\n }\n if (optgroupLabel != null)\n {\n item.Attributes.Add(OptionGroupTag, optgroupLabel);\n }\n if (this.Page != null)\n {\n this.Page.ClientScript.RegisterForEventValidation(this.UniqueID, item.Value);\n }\n\n writer.Write('>');\n HttpUtility.HtmlEncode(item.Text, writer);\n writer.WriteEndTag(tag);\n writer.WriteLine();\n if (i == count - 1)\n {\n if (prevOptGroup != null)\n {\n writer.WriteEndTag(OptionGroupTag);\n }\n }\n }\n }\n }\n }\n\n protected override object SaveViewState()\n {\n object[] state = new object[this.Items.Count + 1];\n object baseState = base.SaveViewState();\n state[0] = baseState;\n bool itemHasAttributes = false;\n\n for (int i = 0; i < this.Items.Count; i++)\n {\n if (this.Items[i].Attributes.Count > 0)\n {\n itemHasAttributes = true;\n object[] attributes = new object[this.Items[i].Attributes.Count * 2];\n int k = 0;\n\n foreach (string key in this.Items[i].Attributes.Keys)\n {\n attributes[k] = key;\n k++;\n attributes[k] = this.Items[i].Attributes[key];\n k++;\n }\n state[i + 1] = attributes;\n }\n }\n\n if (itemHasAttributes)\n return state;\n return baseState;\n }\n\n protected override void LoadViewState(object savedState)\n {\n if (savedState == null)\n return;\n\n if (!(savedState.GetType().GetElementType() == null) &&\n (savedState.GetType().GetElementType().Equals(typeof(object))))\n {\n object[] state = (object[])savedState;\n base.LoadViewState(state[0]);\n\n for (int i = 1; i < state.Length; i++)\n {\n if (state[i] != null)\n {\n object[] attributes = (object[])state[i];\n for (int k = 0; k < attributes.Length; k += 2)\n {\n this.Items[i - 1].Attributes.Add\n (attributes[k].ToString(), attributes[k + 1].ToString());\n }\n }\n }\n }\n else\n {\n base.LoadViewState(savedState);\n }\n }\n\n protected override void PerformDataBinding(IEnumerable dataSource)\n {\n base.PerformDataBinding(dataSource);\n\n if (!string.IsNullOrWhiteSpace(DataOptGroupField) && OptGroupTitles != null)\n {\n var currentItems = Items;\n var dataSourceItems = dataSource.Cast<object>().ToList();\n\n var staticItemsCount = Items.Count - dataSourceItems.Count;\n\n for (var i = staticItemsCount; i < Items.Count; i++)\n {\n var dataSourceItem = dataSourceItems[i - staticItemsCount];\n var optGroupValue = DataBinder.GetPropertyValue(dataSourceItem, DataOptGroupField);\n currentItems[i].Attributes.Add(\"data-optgroup\", OptGroupTitles[optGroupValue]);\n }\n }\n }\n\n public Dictionary<object, string> OptGroupTitles { get; set; }\n public string DataOptGroupField { get; set; }\n}\n <MyControls:UcDropDownListWithOptGroup runat=\"server\" DataSourceID=\"dsX\" DataTextField=\"MyDataTextField\" DataValueField=\"MyDataValueField\" DataOptGroupField=\"IsActive\" OptGroupTitles='<%# MyGroupTitles %>' />\n public Dictionary<object, string> MyGroupTitles\n{\n get\n {\n return new Dictionary<object, string>\n {\n { true, \"Active\" },\n { false, \"Inactive\" }\n };\n }\n}\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/130020",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14072/"
] |
130,032
|
<p>Is there a built-in editor for a multi-line string in a <code>PropertyGrid</code>.</p>
|
[
{
"answer_id": 130168,
"author": "fryguybob",
"author_id": 4592,
"author_profile": "https://Stackoverflow.com/users/4592",
"pm_score": 7,
"selected": true,
"text": "System.Design.dll System.ComponentModel.Design.MultilineStringEditor public class Stuff\n{\n [Editor(typeof(MultilineStringEditor), typeof(UITypeEditor))]\n public string MultiLineProperty { get; set; }\n}\n"
},
{
"answer_id": 35866566,
"author": "Sunil Kumar",
"author_id": 663741,
"author_profile": "https://Stackoverflow.com/users/663741",
"pm_score": 2,
"selected": false,
"text": "public class MultiLineTextEditor : UITypeEditor\n{\n private IWindowsFormsEditorService _editorService;\n\n public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)\n {\n return UITypeEditorEditStyle.DropDown;\n }\n\n public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)\n {\n _editorService = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService));\n\n TextBox textEditorBox = new TextBox();\n textEditorBox.Multiline = true;\n textEditorBox.ScrollBars = ScrollBars.Vertical;\n textEditorBox.Width = 250;\n textEditorBox.Height = 150;\n textEditorBox.BorderStyle = BorderStyle.None;\n textEditorBox.AcceptsReturn = true;\n textEditorBox.Text = value as string;\n\n _editorService.DropDownControl(textEditorBox);\n\n return textEditorBox.Text;\n }\n}\n class CustomPropertyGrid\n{\n private string multiLineStr = string.Empty;\n\n [Editor(typeof(MultiLineTextEditor), typeof(UITypeEditor))]\n public string MultiLineStr\n {\n get { return multiLineStr; }\n set { multiLineStr = value; }\n }\n}\n propertyGrid1.SelectedObject = new CustomPropertyGrid();\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/130032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4592/"
] |
130,074
|
<p>python's time module seems a little haphazard. For example, here is a list of methods in there, from the docstring:</p>
<pre><code>time() -- return current time in seconds since the Epoch as a float
clock() -- return CPU time since process start as a float
sleep() -- delay for a number of seconds given as a float
gmtime() -- convert seconds since Epoch to UTC tuple
localtime() -- convert seconds since Epoch to local time tuple
asctime() -- convert time tuple to string
ctime() -- convert time in seconds to string
mktime() -- convert local time tuple to seconds since Epoch
strftime() -- convert time tuple to string according to format specification
strptime() -- parse string to time tuple according to format specification
tzset() -- change the local timezone
</code></pre>
<p>Looking at localtime() and its inverse mktime(), why is there no inverse for gmtime() ?</p>
<p>Bonus questions: what would you name the method ? How would you implement it ?</p>
|
[
{
"answer_id": 130134,
"author": "Mark Roddy",
"author_id": 9940,
"author_profile": "https://Stackoverflow.com/users/9940",
"pm_score": 2,
"selected": false,
"text": "import time\ndef mkgmtime(t):\n \"\"\"Convert UTC tuple to seconds since Epoch\"\"\"\n return time.mktime(t)-time.timezone\n"
},
{
"answer_id": 130138,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 0,
"selected": false,
"text": "def mkgmtime(fields):\n now = int(time.time())\n gmt = list(time.gmtime(now))\n gmt[8] = time.localtime(now).tm_isdst\n disp = now - time.mktime(tuple(gmt))\n return disp + time.mktime(fields)\n disp time.gmtime"
},
{
"answer_id": 18783518,
"author": "Ilialuk",
"author_id": 2121105,
"author_profile": "https://Stackoverflow.com/users/2121105",
"pm_score": 0,
"selected": false,
"text": ">>> time.ctime(time.time())\n'Fri Sep 13 12:40:08 2013'\n\n>>> utc_tuple = time.gmtime()\n>>> time.ctime(time.mktime(utc_tuple))\n'Fri Sep 13 10:40:11 2013'\n\n>>> time.ctime(time.mktime(utc_tuple) - time.timezone)\n'Fri Sep 13 12:40:11 2013'\n >>> time.localtime(time.mktime(utc_tuple) - time.timezone)\ntime.struct_time(tm_year=2013, tm_mon=9, tm_mday=13, tm_hour=12, tm_min=40, tm_sec=11, tm_wday=4, tm_yday=256, tm_isdst=1)\n >>> time.ctime(time.mktime(time.localtime(time.mktime(utc_tuple) - time.timezone)))\n'Fri Sep 13 12:40:11 2013' \n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/130074",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2900/"
] |
130,092
|
<p>Rails uses the concept of migrations to deal with model changes using the ActiveRecord API.</p>
<p>CouchDB uses JSON (nested maps and arrays) to represent its model objects.</p>
<p>In working with CouchDB so far, I don't see good ways of recognizing when the document's structure has changed (other than being disciplined as a developer), or for migrating documents from an old to a new model.</p>
<p>Are there existing features or do you have best practices for handling model changes in CouchDB?</p>
|
[
{
"answer_id": 141086,
"author": "Paul J. Davis",
"author_id": 129506,
"author_profile": "https://Stackoverflow.com/users/129506",
"pm_score": 4,
"selected": true,
"text": "{\n _id: \"foo-post\",\n _rev: \"23490AD\",\n type: \"post\",\n typevers: 0,\n moon_phase: \"full\"\n}\n"
},
{
"answer_id": 410840,
"author": "max",
"author_id": 49407,
"author_profile": "https://Stackoverflow.com/users/49407",
"pm_score": 2,
"selected": false,
"text": "schema_version def read(doc_id):\n doc = db.get(doc_id)\n if doc.schema_version == 1:\n # version 1 had names broken down too much\n doc.name = \"%s %s\" % (doc.first, doc.last)\n del doc.first\n del doc.last\n doc.schema_version = 2\n db.put(doc)\n if doc.schema_version == 2: weight\n # version 2 used kg instead of g\n doc.weight_g = doc.weight_kg * 1000\n del doc.volume_kg\n doc.schema_version = 3\n db.put(doc)\n return doc\n read(doc_id)"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/130092",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19784/"
] |
130,112
|
<p>How can you get the directory of the script that was run and use it within the .cmd file?</p>
|
[
{
"answer_id": 130118,
"author": "Kev",
"author_id": 419,
"author_profile": "https://Stackoverflow.com/users/419",
"pm_score": 7,
"selected": true,
"text": "%CD% set OLDDIR=%CD% .. do stuff .. chdir /d %OLDDIR% &rem restore current directory pushd popd %CD% set _=%CD%\\curfile.txt cd ... some other directory ... somecommand args %_% args %_% SET /? %~dp0 %0 ~dp"
},
{
"answer_id": 130136,
"author": "Landon",
"author_id": 1597,
"author_profile": "https://Stackoverflow.com/users/1597",
"pm_score": 7,
"selected": false,
"text": "%~dp0\n C:\\example\\script.bat %~dp0 C:\\example\\"
},
{
"answer_id": 1954057,
"author": "Alex. S.",
"author_id": 18300,
"author_profile": "https://Stackoverflow.com/users/18300",
"pm_score": -1,
"selected": false,
"text": "for /F \"eol= delims=~\" %%d in ('CD') do set curdir=%%d\n\npushd %curdir%\n"
},
{
"answer_id": 72832807,
"author": "bebbo",
"author_id": 1412279,
"author_profile": "https://Stackoverflow.com/users/1412279",
"pm_score": 0,
"selected": false,
"text": "%path% @echo off\nsetlocal enableextensions enabledelayedexpansion\n\nfor /f %%i in ('cd') do set CURDIR=%%i\nset LAUNCHERPATH=%~dp0\n\nif \"%LAUNCHERPATH%\" neq \"%CURDIR%\\\" goto LAUNCHERPATHOK\n\nset LIST=%PATH%\n\n:ProcessList\nfor /f \"tokens=1* delims=;\" %%a in (\"!LIST!\") do ( \n if \"%%a\" neq \"\" ( \n set x=%%a\n IF EXIST \"%%a%0.bat\" GOTO FOUND1\n IF EXIST \"%%a\\%0.bat\" GOTO FOUND0\n IF EXIST \"%%a%0\" GOTO FOUND1\n IF EXIST \"%%a\\%0\" GOTO FOUND0\n )\n if \"%%b\" NEQ \"\" (\n set List=%%b\n goto :ProcessList\n )\n)\nexit 1\n\n:FOUND0\nset x=%x%\\\n:FOUND1\nset LAUNCHERPATH=%x%\n\n:LAUNCHERPATHOK\n\necho %LAUNCHERPATH%\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/130112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3153/"
] |
130,116
|
<p>How can I read the first line from a text file using a Windows batch file? Since the file is large I only want to deal with the first line.</p>
|
[
{
"answer_id": 130154,
"author": "Ross Fuhrman",
"author_id": 9431,
"author_profile": "https://Stackoverflow.com/users/9431",
"pm_score": 4,
"selected": false,
"text": "@echo off\n\nfor /f %%a in (sample.txt) do (\n echo %%a\n exit /b\n)\n @echo off\n\nfor /f \"skip=4 tokens=1-4\" %%a in (junkl.txt) do (\n echo %%a %%b %%c %%d\n)\n"
},
{
"answer_id": 130209,
"author": "Jesse Vogt",
"author_id": 9822,
"author_profile": "https://Stackoverflow.com/users/9822",
"pm_score": 3,
"selected": false,
"text": "@echo off\nfor /f \"delims=\" %%a in ('type sample.txt') do (\necho %%a\nexit /b\n)\n"
},
{
"answer_id": 130266,
"author": "Ray Hayes",
"author_id": 7093,
"author_profile": "https://Stackoverflow.com/users/7093",
"pm_score": 2,
"selected": false,
"text": "@echo off\nfor /f \"delims=\" %%x in (%2) do (\nset %1=%%x\nexit /b\n)\n c:\\> dir > test-file\nc:\\> getline variable test-file\nc:\\> set variable \nvariable= Volume in drive C has no label.\n"
},
{
"answer_id": 130298,
"author": "indiv",
"author_id": 19719,
"author_profile": "https://Stackoverflow.com/users/19719",
"pm_score": 7,
"selected": true,
"text": "n head @echo off\n\nif [%1] == [] goto usage\nif [%2] == [] goto usage\n\ncall :print_head %1 %2\ngoto :eof\n\nREM\nREM print_head\nREM Prints the first non-blank %1 lines in the file %2.\nREM\n:print_head\nsetlocal EnableDelayedExpansion\nset /a counter=0\n\nfor /f ^\"usebackq^ eol^=^\n\n^ delims^=^\" %%a in (%2) do (\n if \"!counter!\"==\"%1\" goto :eof\n echo %%a\n set /a counter+=1\n)\n\ngoto :eof\n\n:usage\necho Usage: head.bat COUNT FILENAME\n Z:\\>head 1 \"test file.c\"\n; this is line 1\n\nZ:\\>head 3 \"test file.c\"\n; this is line 1\n this is line 2\nline 3 right here\n"
},
{
"answer_id": 130379,
"author": "PabloG",
"author_id": 394,
"author_profile": "https://Stackoverflow.com/users/394",
"pm_score": 2,
"selected": false,
"text": "@for /f %%i in ('type yourfile.txt') do @echo %%i & exit\n"
},
{
"answer_id": 6824444,
"author": "Amit Naidu",
"author_id": 209129,
"author_profile": "https://Stackoverflow.com/users/209129",
"pm_score": 5,
"selected": false,
"text": "C:\\>findstr /n . c:\\boot.ini | findstr ^1:\n\n1:[boot loader]\n\nC:\\>findstr /n . c:\\boot.ini | findstr ^3:\n\n3:default=multi(0)disk(0)rdisk(0)partition(1)\\WINNT\n\nC:\\>\n"
},
{
"answer_id": 7827243,
"author": "Spaceballs",
"author_id": 993642,
"author_profile": "https://Stackoverflow.com/users/993642",
"pm_score": 8,
"selected": false,
"text": " set /p texte=< file.txt \n echo %texte%\n"
},
{
"answer_id": 11654524,
"author": "Timo Salmi",
"author_id": 1321416,
"author_profile": "https://Stackoverflow.com/users/1321416",
"pm_score": 1,
"selected": false,
"text": "EXIT /B EXIT /B @echo off & setlocal enableextensions enabledelayedexpansion\nset myfile_=C:\\_D\\TEST\\My test file.txt\nset FirstLine=\nfor /f \"delims=\" %%i in ('type \"%myfile_%\"') do (\n if not defined FirstLine set FirstLine=%%i)\necho FirstLine=%FirstLine%\nendlocal & goto :EOF\n @echo off & setlocal enableextensions\nset myfile_=C:\\_D\\TEST\\My test file.txt\nfor /f \"tokens=* delims=\" %%a in (\n 'type \"%myfile_%\"') do (\n set FirstLine=%%a& goto _ExitForLoop)\n:_ExitForLoop\necho FirstLine=%FirstLine%\nendlocal & goto :EOF\n"
},
{
"answer_id": 40871980,
"author": "Sarath Subramanian",
"author_id": 3312636,
"author_profile": "https://Stackoverflow.com/users/3312636",
"pm_score": 2,
"selected": false,
"text": "@echo off\nsetlocal enableextensions enabledelayedexpansion\nset firstLine=1\nfor /f \"delims=\" %%i in (yourfilename.txt) do (\n if !firstLine!==1 echo %%i\n set firstLine=0\n)\nendlocal\n"
},
{
"answer_id": 49002799,
"author": "hhay",
"author_id": 9417167,
"author_profile": "https://Stackoverflow.com/users/9417167",
"pm_score": 1,
"selected": false,
"text": "setlocal enabledelayedexpansion\n@echo off\nfor /f \"delims=\" %%i in (filename.txt) do (\nif 1==1 (\nset first_line=%%i\necho !first_line!\ngoto :eof\n))\n"
},
{
"answer_id": 52422564,
"author": "mmj",
"author_id": 694360,
"author_profile": "https://Stackoverflow.com/users/694360",
"pm_score": 1,
"selected": false,
"text": "powershell powershell (Get-Content file.txt)[0]\n powershell (Get-Content file.txt)[0..3] file.txt for /f \"usebackq delims=\" %%a in (`powershell ^(Get-Content file.txt^)[0]`) do (set \"head=%%a\")\n"
},
{
"answer_id": 55766309,
"author": "Laercio",
"author_id": 11385438,
"author_profile": "https://Stackoverflow.com/users/11385438",
"pm_score": 2,
"selected": false,
"text": "file1.txt file1[1].txt file1[2].txt START/WAIT C:\\LAERCIO\\DELPHI\\CICLADOR\\dprCiclador.exe C:\\LAERCIUM\\Ciclavel.txt\n\nrem set/p ciclo=< C:\\LAERCIUM\\Ciclavel.txt:\nset/p ciclo=< C:\\LAERCIUM\\Ciclavel.txt\n\nrem echo %ciclo%:\necho %ciclo%\n"
},
{
"answer_id": 58732298,
"author": "Zimba",
"author_id": 5958708,
"author_profile": "https://Stackoverflow.com/users/5958708",
"pm_score": -1,
"selected": false,
"text": "set /p a=< file.txt & echo !a!\n for /f \"delims=\" %a in (downing.txt) do echo %a & pause>nul\n type nul > tmp & fc tmp \"%file%\" /lb %n% /t | find /v \"?\" | more +2\n"
},
{
"answer_id": 67532603,
"author": "Jayabharathi Palanisamy",
"author_id": 8830813,
"author_profile": "https://Stackoverflow.com/users/8830813",
"pm_score": 0,
"selected": false,
"text": "powershell -Command \"(gc txt1.txt) -replace (gc txt1.txt)[0], 'This is the first line' | Out-File -encoding ASCII txt1.txt\"\n"
},
{
"answer_id": 68846153,
"author": "Ingmar",
"author_id": 11519739,
"author_profile": "https://Stackoverflow.com/users/11519739",
"pm_score": 2,
"selected": false,
"text": "powershell Get-Content file.txt -Head 1"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/130116",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9822/"
] |
130,117
|
<p>Most people say <em>never</em> throw an exception out of a destructor - doing so results in undefined behavior. Stroustrup makes the point that <em>"the vector destructor explicitly invokes the destructor for every element. This implies that if an element destructor throws, the vector destruction fails... There is really no good way to protect against exceptions thrown from destructors, so the library makes no guarantees if an element destructor throws" (from Appendix E3.2)</em>.</p>
<p><a href="http://www.kolpackov.net/projects/c++/eh/dtor-1.xhtml" rel="noreferrer">This article</a> seems to say otherwise - that throwing destructors are more or less okay.</p>
<p><em>So my question is this - if throwing from a destructor results in undefined behavior, how do you handle errors that occur during a destructor?</em></p>
<p>If an error occurs during a cleanup operation, do you just ignore it? If it is an error that can potentially be handled up the stack but not right in the destructor, doesn't it make sense to throw an exception out of the destructor?</p>
<p>Obviously these kinds of errors are rare, but possible.</p>
|
[
{
"answer_id": 130123,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 9,
"selected": true,
"text": "#include <iostream>\n\nclass Bad\n{\n public:\n // Added the noexcept(false) so the code keeps its original meaning.\n // Post C++11 destructors are by default `noexcept(true)` and\n // this will (by default) call terminate if an exception is\n // escapes the destructor.\n //\n // But this example is designed to show that terminate is called\n // if two exceptions are propagating at the same time.\n ~Bad() noexcept(false)\n {\n throw 1;\n }\n};\nclass Bad2\n{\n public:\n ~Bad2()\n {\n throw 1;\n }\n};\n\n\nint main(int argc, char* argv[])\n{\n try\n {\n Bad bad;\n }\n catch(...)\n {\n std::cout << \"Print This\\n\";\n }\n\n try\n {\n if (argc > 3)\n {\n Bad bad; // This destructor will throw an exception that escapes (see above)\n throw 2; // But having two exceptions propagating at the\n // same time causes terminate to be called.\n }\n else\n {\n Bad2 bad; // The exception in this destructor will\n // cause terminate to be called.\n }\n }\n catch(...)\n {\n std::cout << \"Never print this\\n\";\n }\n\n}\n"
},
{
"answer_id": 130152,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 4,
"selected": false,
"text": "Foo Foo Foo"
},
{
"answer_id": 130178,
"author": "Doug T.",
"author_id": 8123,
"author_profile": "https://Stackoverflow.com/users/8123",
"pm_score": 4,
"selected": false,
"text": "int foo()\n{\n Object o;\n // As foo exits, o's destructor is called\n}\n class Object\n{ \n Object2 obj2;\n Object3* obj3;\n virtual ~Object()\n {\n // What should happen when this fails? How would I actually destroy this?\n delete obj3;\n\n // obj 2 fails to destruct when it goes out of scope, now what!?!?\n // should the exception propogate? \n } \n};\n class Socket\n{\n virtual ~Socket()\n {\n try \n {\n Close();\n }\n catch (...) \n {\n // Why did close fail? make sure it *really* does close here\n }\n } \n\n};\n"
},
{
"answer_id": 456630,
"author": "Tom",
"author_id": 40620,
"author_profile": "https://Stackoverflow.com/users/40620",
"pm_score": 3,
"selected": false,
"text": "class TempFile {\npublic:\n TempFile(); // throws if the file couldn't be created\n ~TempFile() throw(); // does nothing if close() was already called; never throws\n void close(); // throws if the file couldn't be deleted (e.g. file is open by another process)\n // the rest of the class omitted...\n};\n"
},
{
"answer_id": 2470770,
"author": "MartinP",
"author_id": 243879,
"author_profile": "https://Stackoverflow.com/users/243879",
"pm_score": 2,
"selected": false,
"text": "std::uncaught_exception"
},
{
"answer_id": 4098662,
"author": "Martin Ba",
"author_id": 321013,
"author_profile": "https://Stackoverflow.com/users/321013",
"pm_score": 6,
"selected": false,
"text": "void free(void* p); terminate() UncaughtExceptionCounter ScopeGuard std::uncaught_exceptions int uncaught_exceptions"
},
{
"answer_id": 41429901,
"author": "GaspardP",
"author_id": 4660481,
"author_profile": "https://Stackoverflow.com/users/4660481",
"pm_score": 3,
"selected": false,
"text": "std::terminate noexcept noexcept noexcept class MyType {\n public: ~MyType() { throw Exception(); } // ...\n };\n noexcept std::terminate noexcept(false) noexcept(false) noexcept(false) std::terminate std::uncaught_exception()"
},
{
"answer_id": 68946906,
"author": "Arthur P. Golubev",
"author_id": 1790694,
"author_profile": "https://Stackoverflow.com/users/1790694",
"pm_score": 1,
"selected": false,
"text": "std::terminate std::exception std::terminate"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/130117",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5963/"
] |
130,120
|
<p>Has anyone worked with the StarTeam COM API (Specifically, intergrating with C#).</p>
<p>I need to write a helper function that returns a directory structure out of Starteam, but all I've been able to retrieve using this API has been a list of views.</p>
<p>Has anyone else tried this?</p>
|
[
{
"answer_id": 131528,
"author": "Tim Jarvis",
"author_id": 10387,
"author_profile": "https://Stackoverflow.com/users/10387",
"pm_score": 2,
"selected": false,
"text": "void BtnFindClick(object sender, EventArgs e)\n{\n Borland.StarTeam.View v = StarTeamFinder.OpenView(\"username:pwd@server:49201/Project\");\n FolderListManager lm = new FolderListManager(v);\n lm.IncludeFolders(v.RootFolder,-1); // -1 means recursively add child folders\n StringBuilder sb = new StringBuilder();\n foreach(Folder f in lm.Folders)\n {\n sb.AppendLine(f.Path);\n }\n txtResults.Text = sb.ToString();\n}\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/130120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
] |
130,132
|
<p>My form receives asynchronous callbacks from another object on random worker threads. I have been passing the data to the main thread (where it can be used to update onscreen controls) using delegates as shown below. Performance is dreadful -- once I reach 500 updates per second, the program completely locks up. My GUI processing itself is not the problem, as I can simulate this level of updating within the form and have no problems. Is there a more efficient mechanism I should be using to hand off the data from thread to thread?</p>
<pre><code>delegate void DStatus( MyStatus obj );
DStatus _status; // set to MainThreadOnStatus during construction
// this function only called on form's owner thread
void MainThreadOnStatus( MyStatus obj )
{
// screen updates here as needed
}
// this function called by arbitrary worker threads in external facility
void OnStatus( MyStatus obj )
{
this.BeginInvoke( _status, obj );
}
</code></pre>
|
[
{
"answer_id": 130247,
"author": "Brian ONeil",
"author_id": 21371,
"author_profile": "https://Stackoverflow.com/users/21371",
"pm_score": 0,
"selected": false,
"text": "MyStatus MarshalByRefObject this.InvokeRequired"
},
{
"answer_id": 137922,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "public class Foo\n{\n private AsyncOperation _asyncOperation = null;\n private SendOrPostCallback _notifyNewItem = null;\n\n //Make sure you call this on your UI thread.\n //Alternatively you can call something like the AttachUI() below later on and catch-up with\n //your workers later.\n public Foo()\n {\n this._notifyNewItem = new SendOrPostCallback(this.NewDataInTempList);\n this._asyncOperation = AsyncOperationManager.CreateOperation(this);\n }\n\n public void AttachUI()\n {\n if (this._asyncOperation != null)\n {\n this._asyncOperation.OperationCompleted();\n this._asyncOperation = null;\n }\n\n this._asyncOperation = AsyncOperationManager.CreateOperation(this);\n //This is for catching up with the workers if they’ve been busy already\n if (this._asyncOperation != null)\n {\n this._asyncOperation.Post(this._notifyNewItem, null);\n }\n }\n\n\n private int _tempCapacity = 500;\n private object _tempListLock = new object();\n private List<MyStatus> _tempList = null;\n\n //This gets called on the worker threads..\n //Keeps adding to the same list until UI grabs it, then create a new one.\n public void Add(MyStatus status)\n {\n bool notify = false;\n lock (_tempListLock)\n {\n if (this._tempList == null)\n {\n this._tempList = new List<MyStatus>(this._tempCapacity);\n notify = true;\n }\n\n this._tempList.Add(status);\n }\n if (notify)\n {\n if (this._asyncOperation != null)\n {\n this._asyncOperation.Post(this._notifyNewItem, null);\n }\n }\n }\n\n //This gets called on your UI thread.\n private void NewDataInTempList(object o)\n {\n List<MyStatus> statusList = null;\n lock (this._tempListLock)\n {\n //Grab the list, and release the lock as soon as possible.\n statusList = this._tempList;\n this._tempList = null;\n }\n if (statusList != null)\n {\n //Deal with it here at your leasure\n }\n }\n}\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/130132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4540/"
] |
130,161
|
<p>I've gotten used to the idea that if I want/need to use alpha-trans PNGs in a cross-browser manner, that I use a background image on a div and then, in IE6-only CSS, mark the background as "none" and include the proper "filter" argument.</p>
<p>Is there another way? A better way? Is there a way to do this with the img tag and not with background images?</p>
|
[
{
"answer_id": 161860,
"author": "Ian Oxley",
"author_id": 1904,
"author_profile": "https://Stackoverflow.com/users/1904",
"pm_score": 1,
"selected": false,
"text": "/* for IE 6 */\n#banner {\n background:url(../images/banner.gif);\n}\n\n/* for other browsers */\nhtml > #banner {\n background:url(../images/banner.png);\n}\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/130161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9414/"
] |
130,165
|
<p>I have a form with some radio buttons that are disabled by default. </p>
<p>When a value gets entered into a text box, the radio buttons are enabled via javascript. The user then selects one of the radio buttons and clicks on a submit button which posts back to the server.</p>
<p>When I get back to the server, the radio button that user clicked is not showing as checked. I'll use 'rbSolid' as the radio button I'm focusing on.</p>
<p>I handle the 'onclick' event of the radio buttons, but I don't have the function doing anything yet other than firing:</p>
<blockquote>
<p>Me.rbSolid.Attributes.Add("onclick", "styleLookupChanged(this);")</p>
</blockquote>
<p>On the client, this enables the radio button when the textbox value is changed:</p>
<blockquote>
<p>document.getElementById("ctl00_MainLayoutContent_WebPanel4_rbSolid").disabled = false;</p>
</blockquote>
<p>I then click the radio button then post back via a button, but back on the server this is always false:</p>
<blockquote>
<p>If Me.rbSolid.Checked Then...</p>
</blockquote>
<p>If I have the radio button enabled by default, it shows as checked correctly.</p>
<p>Thanks for any help!</p>
|
[
{
"answer_id": 130181,
"author": "Craig",
"author_id": 7861,
"author_profile": "https://Stackoverflow.com/users/7861",
"pm_score": 4,
"selected": true,
"text": "control.enabled = false control.enabled = false control.attributes.add(\"disabled\", \"disabled\")"
},
{
"answer_id": 133262,
"author": "Chris Burgess",
"author_id": 6624,
"author_profile": "https://Stackoverflow.com/users/6624",
"pm_score": 0,
"selected": false,
"text": "Me.rbSolid.Style.Add(\"background-color\", \"red\")\n\nMe.rbSolid.Style.Add(\"disabled\", \"true\")\n disabled <span style=\"font-family:Verdana;font-size:8pt;background-color:red;Disabled:true;\">\n <input id=\"ctl00_MainLayoutContent_WebPanel4_rbSolid\" type=\"radio\" name=\"ctl00$MainLayoutContent$WebPanel4$DetailType\" value=\"rbSolid\" onclick=\"styleLookupChanged(this);\"/>\n <label for=\"ctl00_MainLayoutContent_WebPanel4_rbSolid\">Solid</label>\n</span>\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/130165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6624/"
] |
130,166
|
<p>I am trying to write a macro that would "click" a command button that is in another workbook. Is that possible? Without changing any of the code within that other workbook?</p>
|
[
{
"answer_id": 130325,
"author": "Ozgur Ozcitak",
"author_id": 976,
"author_profile": "https://Stackoverflow.com/users/976",
"pm_score": 1,
"selected": false,
"text": "Application.Run Run \"OtherWorkbook.xls!MyOtherMacro\"\n"
},
{
"answer_id": 130330,
"author": "Per Hornshøj-Schierbeck",
"author_id": 11619,
"author_profile": "https://Stackoverflow.com/users/11619",
"pm_score": 0,
"selected": false,
"text": "Worksheets(\"MySheet\").YourMethod()\n"
},
{
"answer_id": 130443,
"author": "msulis",
"author_id": 9317,
"author_profile": "https://Stackoverflow.com/users/9317",
"pm_score": -1,
"selected": false,
"text": "Public Sub RunButton(workbookName As String, worksheetName As String, controlName As String)\n Dim wkb As Workbook\n Dim wks As Worksheet\n Set wkb = Workbooks.Open(workbookName)\n wkb.Activate\n Dim obj As OLEObject\n For Each wks In wkb.Worksheets\n If wks.Name = worksheetName Then\n wks.Activate\n For Each obj In wks.OLEObjects\n If (obj.Name = controlName) Then\n obj.Activate\n SendKeys (\" \")\n End If\n Next obj\n End If\n Next wks\nEnd Sub\n"
},
{
"answer_id": 130699,
"author": "Robert Mearns",
"author_id": 5050,
"author_profile": "https://Stackoverflow.com/users/5050",
"pm_score": 1,
"selected": false,
"text": "Sub Run_Macro()\n\n Workbooks.Open Filename:=\"C:\\Book1.xls\"\n'Open the workbook containing the command button\n'Change the path and filename as required\n\n Application.Run \"Book1.xls!Macro1\"\n'Run the macro \n'Change the filename and macro name as required\n\n'If the macro is attached to a worksheet rather than a module, the code would be\n'Application.Run \"Book1.xls!Sheet1.Macro1\"\n\nEnd Sub\n"
},
{
"answer_id": 2640395,
"author": "DP.",
"author_id": 316869,
"author_profile": "https://Stackoverflow.com/users/316869",
"pm_score": 0,
"selected": false,
"text": "Private Sub xyz_Click() Public Sub ForceClickOnBouttonXYZ()\n Call xyz_Click\nEnd Sub\n Sheets(\"ABC\").Activate\nCall Sheets(\"ABC\").ForceClickOnBouttonXYZ\n Application.ScreenUpdating = False Sheets(\"ABC\").ForceClickOnBouttonXYZ Application.ScreenUpdating = True"
},
{
"answer_id": 32892880,
"author": "Robert Ovington",
"author_id": 5398425,
"author_profile": "https://Stackoverflow.com/users/5398425",
"pm_score": 0,
"selected": false,
"text": " Private Sub cmdRefreshAll_Click()\n Dim SheetName As String\n\n SheetName = \"Mon\"\n Worksheets(SheetName).Activate\n ActiveSheet.cmdRefresh_Click\n\n SheetName = \"Tue\"\n Worksheets(SheetName).Activate\n ActiveSheet.cmdRefresh_Click\n\n' \"I repeated the above code to loop through a worksheet for every day of the week\"\n\n End Sub\n"
},
{
"answer_id": 33355307,
"author": "Tristan Reischl",
"author_id": 4764487,
"author_profile": "https://Stackoverflow.com/users/4764487",
"pm_score": 3,
"selected": false,
"text": "Workbooks(\"OtherBook\").Worksheets(\"Sheet1\").CommandButton1.Value = True\n Application.Run Workbooks(\"OtherBook\").Worksheets(\"Sheet1\").Shapes(\"Button 1\").OnAction\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/130166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
130,186
|
<p>I'm having an unusual problem with an IE document with contentEditable set to true. Calling select() on a range that is positioned at the end of a text node that immediately precedes a block element causes the selection to be shifted to the right one character and appear where it shouldn't. I've submitted a bug to Microsoft against IE8. If you can, please vote for this issue so that it can be fixed.</p>
<p><a href="https://connect.microsoft.com/IE/feedback/ViewFeedback.aspx?FeedbackID=390995" rel="nofollow noreferrer">https://connect.microsoft.com/IE/feedback/ViewFeedback.aspx?FeedbackID=390995</a></p>
<p>I've written a test case to demonstrate the effect:</p>
<pre><code><html>
<body>
<iframe id="editable">
<html>
<body>
<div id="test">
Click to the right of this line -&gt;
<p id="par">Block Element</p>
</div>
</body>
</html>
</iframe>
<input id="mytrigger" type="button" value="Then Click here to Save and Restore" />
<script type="text/javascript">
window.onload = function() {
var iframe = document.getElementById('editable');
var doc = iframe.contentDocument || iframe.contentWindow.document;
// An IFRAME without a source points to a blank document. Here we'll
// copy the content we stored in between the IFRAME tags into that
// document. It's a hack to allow us to use only one HTML file for this
// test.
doc.body.innerHTML = iframe.textContent || iframe.innerHTML;
// Marke the IFRAME as an editable document
if (doc.body.contentEditable) {
doc.body.contentEditable = true;
} else {
var mydoc = doc;
doc.designMode = 'On';
}
// A function to demonstrate the bug.
var myhandler = function() {
// Step 1 Get the current selection
var selection = doc.selection || iframe.contentWindow.getSelection();
var range = selection.createRange ? selection.createRange() : selection.getRangeAt(0);
// Step 2 Restore the selection
if (range.select) {
range.select();
} else {
selection.removeAllRanges();
selection.addRange(range);
doc.body.focus();
}
}
// Set up the button to perform the test code.
var button = document.getElementById('mytrigger');
if (button.addEventListener) {
button.addEventListener('click', myhandler, false);
} else {
button.attachEvent('onclick', myhandler);
}
}
</script>
</body>
</html>
</code></pre>
<p>The problem is exposed in the myhandler function. This is all that I'm doing, there is no Step 3 in between the saving and restoring the selection, and yet the cursor moves. It doesn't seem to happen unless the selection is empty (ie. I have a blinking cursor, but no text), and it only seems to happen whenever the cursor is at the end of a text node that immediately precedes a block node.</p>
<p>It seems that the range is still in the correct position (if I call parentElement on the range it returns the div), but if I get a new range from the current selection, the new range is inside the paragraph tag, and that is its parentElement.</p>
<p><strong>How do I work around this and consistently save and restore the selection in internet explorer?</strong></p>
|
[
{
"answer_id": 822802,
"author": "Alconja",
"author_id": 68727,
"author_profile": "https://Stackoverflow.com/users/68727",
"pm_score": 1,
"selected": false,
"text": "range.select() selection.createRange() .select() if (range.boundingWidth == 0)\n{\n //looks like its already at the start of the next line down...\n alert('default position: ' + range.offsetLeft + ', ' + range.offsetTop);\n //lets move the start of the range one character back\n //(i.e. select the last char on the line)\n range.moveStart(\"character\", -1);\n //now the range looks good (except that its width will be one char);\n alert('one char back: ' + range.offsetLeft + ', ' + range.offsetTop);\n //calculate the true end of the line...\n var left = range.offsetLeft + range.boundingWidth;\n var top = range.offsetTop;\n //now we can collapse back down to 0 width range\n range.collapse();\n //the position looks right\n alert('moving to: ' + left + ', ' + top);\n //move there.\n range.moveToPoint(left, top);\n //oops... on the next line again... stupid IE.\n alert('moved to: ' + range.offsetLeft + ', ' + range.offsetTop);\n}\n // Step 2 Restore the selection\nif (range.select) {\n if (range.boundingWidth > 0) {\n range.select();\n }\n} else {\n selection.removeAllRanges();\n selection.addRange(range);\n doc.body.focus();\n}\n"
},
{
"answer_id": 827264,
"author": "Dan Eisenberg",
"author_id": 101887,
"author_profile": "https://Stackoverflow.com/users/101887",
"pm_score": 5,
"selected": true,
"text": "// Save position of cursor\nrange.pasteHTML('<span id=\"caret\"></span>')\n\n...\n\n// Create new cursor and put it in the old position\nvar caretSpan = iframe.contentWindow.document.getElementById(\"caret\");\nvar selection = iframe.contentWindow.document.selection;\nnewRange = selection.createRange();\nnewRange.moveToElementText(caretSpan);\n var selection = iframe.contentWindow.document.selection;\nvar range = selection.createRange().duplicate();\nrange.moveStart('sentence', -1000000);\nvar cursorPosition = range.text.length;\n var newRange = selection.createRange();\nnewRange.move('sentence', -1000000);\nnewRange.move('character', cursorPosition);\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/130186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8458/"
] |
130,187
|
<p>I want to index this view but because it has subquery i cant index. Can anyone suggest how to change this view so that i can index it.</p>
<pre><code>ALTER VIEW [dbo].[Recon2]
WITH SCHEMABINDING
AS
SELECT
dbo.Transactions.CustomerCode,
dbo.Customer_Master.CustomerName,
dbo.Transactions.TransDate,
dbo.Transactions.PubCode,
dbo.Transactions.TransType,
dbo.Transactions.Copies,
SUM(dbo.Transactions.TotalAmount) AS TotalAmount,
'0' AS ReceiptNo,
'2008-01-01' AS PaymentDate,
0 AS Amount,
dbo.Transactions.Period,
dbo.Transactions.Year,
dbo.Publication_Master.PubName,
dbo.Customer_Master.SalesCode,
COUNT_BIG(*) AS COUNT
FROM
dbo.Publication_Master INNER JOIN
dbo.Customer_Master INNER JOIN
dbo.Transactions ON dbo.Customer_Master.CustomerCode = dbo.Transactions.CustomerCode ON
dbo.Publication_Master.PubCode = dbo.Transactions.PubCode
WHERE
(dbo.Customer_Master.CustomerCode NOT IN
(SELECT CustomerCode
FROM dbo.StreetSaleRcpt
WHERE (PubCode = dbo.Transactions.PubCode) AND
(TransactionDate = dbo.Transactions.TransDate) AND
(Updated = 1) AND
(PeriodMonth = dbo.Transactions.Period) AND
(PeriodYear = dbo.Transactions.Year)))
GROUP BY dbo.Transactions.CustomerCode, dbo.Customer_Master.CustomerName, dbo.Transactions.TransDate, dbo.Transactions.PubCode,
dbo.Publication_Master.PubName, dbo.Customer_Master.SalesCode, dbo.Transactions.[Update], dbo.Transactions.TransType,
dbo.Transactions.Copies, dbo.Transactions.Period, dbo.Transactions.Year, dbo.Transactions.TotalAmount
</code></pre>
|
[
{
"answer_id": 130279,
"author": "Corbin March",
"author_id": 7625,
"author_profile": "https://Stackoverflow.com/users/7625",
"pm_score": 2,
"selected": false,
"text": "SELECT\ndbo.Transactions.CustomerCode, \ndbo.Customer_Master.CustomerName, \ndbo.Transactions.TransDate, \ndbo.Transactions.PubCode, \ndbo.Transactions.TransType, \ndbo.Transactions.Copies, \n'0' AS ReceiptNo, \n'2008-01-01' AS PaymentDate, \n0 AS Amount, \ndbo.Transactions.Period, \ndbo.Transactions.Year, \ndbo.Publication_Master.PubName, \ndbo.Customer_Master.SalesCode, \ndbo.StreetSaleRcpt.CustomerCode,\nSUM(dbo.Transactions.TotalAmount) AS TotalAmount, \nCOUNT_BIG(*) AS COUNT \nFROM dbo.Publication_Master \nINNER JOIN dbo.Customer_Master ON dbo.Customer_Master.CustomerCode = dbo.Transactions.CustomerCode \nINNER JOIN dbo.Transactions ON dbo.Publication_Master.PubCode = dbo.Transactions.PubCode \nLEFT OUTER JOIN dbo.StreetSaleRcpt ON (\n dbo.StreetSaleRcpt.PubCode = dbo.Transactions.PubCode \n AND dbo.StreetSaleRcpt.TransactionDate = dbo.Transactions.TransDate\n AND dbo.StreetSaleRcpt.PeriodMonth = dbo.Transactions.Period\n AND dbo.StreetSaleRcpt.PeriodYear = dbo.Transactions.Year\n AND dbo.StreetSaleRcpt.Updated = 1\n AND dbo.StreetSaleRcpt.CustomerCode = dbo.Customer_Master.CustomerCode\n)\nWHERE dbo.StreetSaleRcpt.CustomerCode IS NULL\nGROUP BY \ndbo.Transactions.CustomerCode, \ndbo.Customer_Master.CustomerName, \ndbo.Transactions.TransDate, \ndbo.Transactions.PubCode, \ndbo.Publication_Master.PubName, \ndbo.Customer_Master.SalesCode, \ndbo.Transactions.[Update], \ndbo.Transactions.TransType, \ndbo.Transactions.Copies, \ndbo.Transactions.Period, \ndbo.Transactions.Year, \ndbo.Transactions.TotalAmount,\ndbo.StreetSaleRcpt.CustomerCode\n"
},
{
"answer_id": 132733,
"author": "Tony Andrews",
"author_id": 18747,
"author_profile": "https://Stackoverflow.com/users/18747",
"pm_score": 0,
"selected": false,
"text": "ALTER VIEW [dbo].[Recon2] WITH SCHEMABINDING AS SELECT\ndbo.Transactions.CustomerCode, dbo.Customer_Master.CustomerName, dbo.Transactions.TransDate, dbo.Transactions.PubCode, dbo.Transactions.TransType, dbo.Transactions.Copies, SUM(dbo.Transactions.TotalAmount) AS TotalAmount, '0' AS ReceiptNo, '2008-01-01' AS PaymentDate, 0 AS Amount, dbo.Transactions.Period, dbo.Transactions.Year, dbo.Publication_Master.PubName, dbo.Customer_Master.SalesCode, COUNT_BIG(*) AS COUNT\nFROM dbo.Publication_Master \nINNER JOIN dbo.Customer_Master \nINNER JOIN dbo.Transactions ON dbo.Customer_Master.CustomerCode = dbo.Transactions.CustomerCode ON dbo.Publication_Master.PubCode = dbo.Transactions.PubCode \nWHERE\n(NOT EXISTS \n (SELECT NULL FROM dbo.StreetSaleRcpt \n WHERE (PubCode = dbo.Transactions.PubCode) \n AND (TransactionDate = dbo.Transactions.TransDate) \n AND (Updated = 1)\n AND (PeriodMonth = dbo.Transactions.Period) \n AND (PeriodYear = dbo.Transactions.Year)\n ANMD (CustomerCode = dbo.Customer_Master.CustomerCode)\n )\n) GROUP BY dbo.Transactions.CustomerCode, dbo.Customer_Master.CustomerName, dbo.Transactions.TransDate, dbo.Transactions.PubCode, dbo.Publication_Master.PubName, dbo.Customer_Master.SalesCode, dbo.Transactions.[Update], dbo.Transactions.TransType, dbo.Transactions.Copies, dbo.Transactions.Period, dbo.Transactions.Year, dbo.Transactions.TotalAmount\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/130187",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14752/"
] |
130,192
|
<p>I was wondering if there is a clean way to represent an is-a relationship as illustrated by this example:</p>
<p>This DB stores recording times for three types of programs: movies, game shows, drama. In an object oriented sense each of these is-a program. Each of these subclasses have different properties. Here are the tables (fk prefix indicates a foreign key):</p>
<p><em>movie</em><br>
id<br>
name<br>
fkDirector<br></p>
<p><em>gameShow</em><br>
id<br>
name<br>
fkHost<br>
fkContestant<br></p>
<p><em>drama</em><br>
id<br>
name<br></p>
<p>In OO terms the record table would in sense look like this:<br><br>
<em>record</em><br>
id<br>
fkProgram<br>
startTime<br>
endTime<br></p>
<p>The only way I can think of doing this without violating the normal forms is to have three record tables namely <em>recordMovie</em>, <em>recordGameShow</em>, and <em>recordDrama</em>.</p>
<p>Is there a way to consolidate these tables into one without violating the principles of database normalization?</p>
<p>Here are some non-working examples to illustrate the idea:</p>
<p><em>program</em><br>
id<br>
fkMovie<br>
fkGameShow<br>
fkDrama<br></p>
<p>This table violates the first normal form because it will contain nulls. For each row only one of the 3 entries will be non null.</p>
<p><em>program</em><br>
id<br>
fkSpecific ← fkMovie OR fkGameShow OR fkDrama<br>
fkType ← would indicate what table to look into<br></p>
<p>Here I will not be able to enforce referential integrity because the fkSpecific could potentially point to one of three tables.</p>
<p>I'm just trying to save the overhead of having 3 tables here instead of one. Maybe this simply isn't applicable to an RDB.</p>
|
[
{
"answer_id": 130211,
"author": "Ron Savage",
"author_id": 12476,
"author_profile": "https://Stackoverflow.com/users/12476",
"pm_score": 2,
"selected": false,
"text": "Programs:\n id,\n name,\n type_id,\n length,\n etc...\n ProgramType\n type_id,\n type_name,\n etc...\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/130192",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21906/"
] |
130,193
|
<p>Is it possible to modify a registry value (whether string or DWORD) via a .bat/.cmd script?</p>
|
[
{
"answer_id": 130202,
"author": "Rui Vieira",
"author_id": 143732,
"author_profile": "https://Stackoverflow.com/users/143732",
"pm_score": 6,
"selected": true,
"text": "Syntax:\n\n REG QUERY [ROOT\\]RegKey /v ValueName [/s]\n REG QUERY [ROOT\\]RegKey /ve --This returns the (default) value\n\n REG ADD [ROOT\\]RegKey /v ValueName [/t DataType] [/S Separator] [/d Data] [/f]\n REG ADD [ROOT\\]RegKey /ve [/d Data] [/f] -- Set the (default) value\n\n REG DELETE [ROOT\\]RegKey /v ValueName [/f]\n REG DELETE [ROOT\\]RegKey /ve [/f] -- Remove the (default) value\n REG DELETE [ROOT\\]RegKey /va [/f] -- Delete all values under this key\n\n REG COPY [\\\\SourceMachine\\][ROOT\\]RegKey [\\\\DestMachine\\][ROOT\\]RegKey\n\n REG EXPORT [ROOT\\]RegKey FileName.reg\n REG IMPORT FileName.reg\n REG SAVE [ROOT\\]RegKey FileName.hiv\n REG RESTORE \\\\MachineName\\[ROOT]\\KeyName FileName.hiv\n\n REG LOAD FileName KeyName\n REG UNLOAD KeyName\n\n REG COMPARE [ROOT\\]RegKey [ROOT\\]RegKey [/v ValueName] [Output] [/s]\n REG COMPARE [ROOT\\]RegKey [ROOT\\]RegKey [/ve] [Output] [/s]\n\nKey:\n ROOT :\n HKLM = HKey_Local_machine (default)\n HKCU = HKey_current_user\n HKU = HKey_users\n HKCR = HKey_classes_root\n\n ValueName : The value, under the selected RegKey, to edit.\n (default is all keys and values)\n\n /d Data : The actual data to store as a \"String\", integer etc\n\n /f : Force an update without prompting \"Value exists, overwrite Y/N\"\n\n \\\\Machine : Name of remote machine - omitting defaults to current machine.\n Only HKLM and HKU are available on remote machines.\n\n FileName : The filename to save or restore a registry hive.\n\n KeyName : A key name to load a hive file into. (Creating a new key)\n\n /S : Query all subkeys and values.\n\n /S Separator : Character to use as the separator in REG_MULTI_SZ values\n the default is \"\\0\" \n\n /t DataType : REG_SZ (default) | REG_DWORD | REG_EXPAND_SZ | REG_MULTI_SZ\n\n Output : /od (only differences) /os (only matches) /oa (all) /on (no output)\n"
},
{
"answer_id": 130205,
"author": "Factor Mystic",
"author_id": 1569,
"author_profile": "https://Stackoverflow.com/users/1569",
"pm_score": 5,
"selected": false,
"text": "reg reg add HKCU\\Software\\SomeProduct\nreg add HKCU\\Software\\SomeProduct /v Version /t REG_SZ /d v2.4.6\n HKEY_CURRENT_USER\\Software\\SomeProduct reg /?"
},
{
"answer_id": 170321,
"author": "nray",
"author_id": 25092,
"author_profile": "https://Stackoverflow.com/users/25092",
"pm_score": 7,
"selected": false,
"text": "/f reg add \"HKCU\\Software\\etc\\etc\" /f /v \"value\" /t REG_SZ /d \"Yes\"\n"
},
{
"answer_id": 37511806,
"author": "Shersha Fn",
"author_id": 4254056,
"author_profile": "https://Stackoverflow.com/users/4254056",
"pm_score": 4,
"selected": false,
"text": "reg add HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\etc\\etc /v Valuename /t REG_SZ /d valuedata /f \n reg add HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\https\\UserChoice /v ProgId /t REG_SZ /d IE.HTTPS /f \n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/130193",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3153/"
] |
130,208
|
<p>Assuming I have only the class name of a generic as a string in the form of "MyCustomGenericCollection(of MyCustomObjectClass)" and don't know the assembly it comes from, what is the easiest way to create an instance of that object? </p>
<p>If it helps, I know that the class implements IMyCustomInterface and is from an assembly loaded into the current AppDomain.</p>
<p>Markus Olsson gave an excellent example <a href="https://stackoverflow.com/questions/31238/c-instantiating-classes-from-xml">here</a>, but I don't see how to apply it to generics.</p>
|
[
{
"answer_id": 130241,
"author": "Jonathan Rupp",
"author_id": 12502,
"author_profile": "https://Stackoverflow.com/users/12502",
"pm_score": 4,
"selected": true,
"text": "Type t1 = Type.GetType(\"MyCustomGenericCollection\");\nType t2 = Type.GetType(\"MyCustomObjectClass\");\nType t3 = t1.MakeGenericType(new Type[] { t2 });\nConstructorInfo ci = t3.GetConstructor(Type.EmptyTypes);\nobject obj = ci.Invoke(null);\n"
},
{
"answer_id": 130245,
"author": "David Wengier",
"author_id": 489,
"author_profile": "https://Stackoverflow.com/users/489",
"pm_score": 1,
"selected": false,
"text": "foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())\n{\n // find the type of the item\n Type itemType = assembly.GetType(\"MyCustomObjectClass\", false);\n // if we didnt find it, go to the next assembly\n if (itemType == null)\n {\n continue;\n }\n // Now create a generic type for the collection\n Type colType = assembly.GetType(\"MyCusomgGenericCollection\").MakeGenericType(itemType);;\n\n IMyCustomInterface result = (IMyCustomInterface)Activator.CreateInstance(colType);\n break;\n}\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/130208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5287/"
] |
130,227
|
<p>Suppose you have a large file made up of a bunch of fixed size blocks. Each of these blocks contains some number of variable sized records. Each record must fit completely within a single block and then such records by definition are never larger than a full block. Over time, records are added to and deleted from these blocks as records come and go from this "database".</p>
<p>At some point, especially after perhaps many records are added to the database and several are removed - many of the blocks may end up only partially filled.</p>
<p>What is a good algorithm to shuffle the records around in this database to compact out unnecessary blocks at the end of the file by better filling up the partially filled blocks?</p>
<p>Requirements of the algorithm:</p>
<ul>
<li>The compaction must happen in place of the original file without temporarily extending the file by more than a few blocks at most from its starting size</li>
<li>The algorithm should not unnecessarily disturb blocks that are already mainly full</li>
<li>Entire blocks must be read or written from/to the file at one time and one should assume the write operation is relatively expensive</li>
<li>If records are moved from one block to another they must be added at their new location before being removed from their starting position so that in case the operation is interrupted no records are lost as a result of the "failed" compaction. (Assume that this temporary duplication of such records can be detected at recovery).</li>
<li>The memory that can be used for this operation can only be on the order of perhaps several blocks which is a very small percentage of the overall file size</li>
<li>Assume that records are on the order of 10 bytes to 1K bytes with an average size of maybe 100 bytes. The fixed sized blocks are on the order of 4K or 8K and that the file is on the order of 1000's of blocks.</li>
</ul>
|
[
{
"answer_id": 130321,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 2,
"selected": false,
"text": "// records should be sorted by size in memory (probably in a balanced BST)\nrecords = read last N blocks on disk;\n\nforeach (block in blocks) // read from disk into memory\n{\n if (block.hasBeenReadFrom())\n {\n // we read from this into records already\n // all remaining records are already in memory\n\n writeAllToNewBlocks(records);\n\n // this will leave some empty blocks on the disk that can either\n // be eliminated programmatically or left alone and filled during\n // normal operation\n\n foreach (record in records)\n {\n record.eraseFromOriginalLocation();\n }\n\n break;\n }\n\n while(!block.full())\n {\n moveRecords = new Array; // list of records we've moved\n\n size = block.availableSpace();\n record = records.extractBestFit(size);\n if (record == null)\n {\n break;\n }\n\n moveRecords.add(record);\n block.add(record);\n\n if (records.gettingLow())\n {\n records.readMoreFromDisk();\n }\n }\n\n if(moveRecords.size() > 0)\n {\n block.writeBackToDisk();\n foreach (record in moveRecords)\n {\n record.eraseFromOriginalLocation();\n }\n }\n}\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/130227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1553/"
] |
130,240
|
<p>I have a bunch a values I would like to add together which are entered into a form. Right now, the form has 11 lines but it could get larger in the future. I can easily add all the values together with something like:</p>
<pre><code>$total = $value1 + $value2 + ... + $value11;
</code></pre>
<p>All the values I want to add together are coming from an <code>HTML</code> form. I want to avoid javascript.</p>
<p>But, I want to avoid having to manually do it, especially if it grows much larger. This is my attempt at adding all the values together using a loop but it returns an "undefined variable" error (it is just some test code to try out the idea):</p>
<pre><code><?php
$tempTotal = 0;
$pBalance1 = 5;
$pBalance2 = 5;
$pBalance3 = 5;
for ($i = 1 ; $i <= 3 ; $i++){
$tempTotal = $tempTotal + $pBalance.$i;
}
echo $tempTotal;
?>
</code></pre>
<p>Is what I want to do possible in PHP?</p>
|
[
{
"answer_id": 130244,
"author": "Lasar",
"author_id": 9438,
"author_profile": "https://Stackoverflow.com/users/9438",
"pm_score": 4,
"selected": true,
"text": "for ($i = 1 ; $i <= 3 ; $i++){\n $varName = \"pBalance\".$i;\n $tempTotal += $$varName;\n}\n"
},
{
"answer_id": 130248,
"author": "Factor Mystic",
"author_id": 1569,
"author_profile": "https://Stackoverflow.com/users/1569",
"pm_score": 2,
"selected": false,
"text": "foreach($_POST as $key=>$value)\n{\n if(strpos($key, 'pBalance')===0)\n {\n $final_total += $value;\n }\n}\n"
},
{
"answer_id": 130251,
"author": "Doug T.",
"author_id": 8123,
"author_profile": "https://Stackoverflow.com/users/8123",
"pm_score": 0,
"selected": false,
"text": "$varName = 'pBalance' . $i;\n$tempTotal = $tempTotal + $$varName;\n"
},
{
"answer_id": 130260,
"author": "conmulligan",
"author_id": 1467,
"author_profile": "https://Stackoverflow.com/users/1467",
"pm_score": 2,
"selected": false,
"text": "$tempTotal = 0;\n\n$balances[] = 5;\n$balances[] = 5;\n$balances[] = 5;\n\nfor ($i = 0; $i <= count($balances); $i++) {\n $tempTotal = $tempTotal + $balances[$i];\n}\n foreach($balances as $balance) {\n $tempTotal += $balance;\n}\n"
},
{
"answer_id": 130277,
"author": "Keeth",
"author_id": 20588,
"author_profile": "https://Stackoverflow.com/users/20588",
"pm_score": 3,
"selected": false,
"text": "<input name=\"myInput[]\" />\n<input name=\"myInput[]\" />\n<input name=\"myInput[]\" />\n...\n $total = array_sum($_REQUEST['myInput']);\n"
},
{
"answer_id": 130283,
"author": "William Keller",
"author_id": 17095,
"author_profile": "https://Stackoverflow.com/users/17095",
"pm_score": 2,
"selected": false,
"text": "<input type=\"text\" name=\"vals[]\" value=\"one\" />\n<input type=\"text\" name=\"vals[]\" value=\"two\" />\n $_POST[\"vals\"]"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/130240",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16292/"
] |
130,262
|
<p>The Python list comprehension syntax makes it easy to filter values within a comprehension. For example:</p>
<pre><code>result = [x**2 for x in mylist if type(x) is int]
</code></pre>
<p>Will return a list of the squares of integers in mylist. However, what if the test involves some (costly) computation and you want to filter on the result? One option is:</p>
<pre><code>result = [expensive(x) for x in mylist if expensive(x)]
</code></pre>
<p>This will result in a list of non-"false" expensive(x) values, however expensive() is called twice for each x. Is there a comprehension syntax that allows you to do this test while only calling expensive once per x?</p>
|
[
{
"answer_id": 130276,
"author": "Nick",
"author_id": 5222,
"author_profile": "https://Stackoverflow.com/users/5222",
"pm_score": 5,
"selected": false,
"text": "result = [y for y in (expensive(x) for x in mylist) if y]\n"
},
{
"answer_id": 130278,
"author": "Dan Udey",
"author_id": 21450,
"author_profile": "https://Stackoverflow.com/users/21450",
"pm_score": 3,
"selected": false,
"text": "result = [x for x in map(expensive,mylist) if x]\n"
},
{
"answer_id": 130285,
"author": "yukondude",
"author_id": 726,
"author_profile": "https://Stackoverflow.com/users/726",
"pm_score": 2,
"selected": false,
"text": "expensive() x"
},
{
"answer_id": 130309,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 6,
"selected": true,
"text": "filter map result = filter (None, map (expensive, mylist))\n itertools.imap"
},
{
"answer_id": 130312,
"author": "Thomas Wouters",
"author_id": 17624,
"author_profile": "https://Stackoverflow.com/users/17624",
"pm_score": 3,
"selected": false,
"text": "def gen_expensive(mylist):\n for item in mylist:\n result = expensive(item)\n if result:\n yield result\n"
},
{
"answer_id": 133898,
"author": "Gregg Lind",
"author_id": 15842,
"author_profile": "https://Stackoverflow.com/users/15842",
"pm_score": 3,
"selected": false,
"text": "result = (expensive(x) for x in mylist)\nresult = (do_something(x) for x in result if some_condition(x))\n...\nresult = [x for x in result if x] # finally, a list\n"
},
{
"answer_id": 873661,
"author": "odwl",
"author_id": 2453648,
"author_profile": "https://Stackoverflow.com/users/2453648",
"pm_score": 1,
"selected": false,
"text": "itertools.ifilter(bool, (expensive(x) for x in mylist))\n"
},
{
"answer_id": 874319,
"author": "Paddy3118",
"author_id": 10562,
"author_profile": "https://Stackoverflow.com/users/10562",
"pm_score": 0,
"selected": false,
"text": "for result = []\nfor x in mylist:\n expense = expensive(x)\n if expense:\n result.append(expense)\n"
},
{
"answer_id": 73438697,
"author": "Karl Knechtel",
"author_id": 523612,
"author_profile": "https://Stackoverflow.com/users/523612",
"pm_score": 1,
"selected": false,
"text": "[e for x in mylist if (e:=expensive(x))]\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/130262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5222/"
] |
130,268
|
<h3>Background</h3>
<p>Normal rails eager-loading of collections works like this:</p>
<pre><code>Person.find(:all, :include=>:companies)
</code></pre>
<p>This generates some sql which does</p>
<pre><code>LEFT OUTER JOIN companies ON people.company_id = companies.id
</code></pre>
<h3>Question</h3>
<p>However, I need a custom join (this could also arise if I was using <code>find_by_sql</code>) so I can't use the vanilla <code>:include => :companies</code></p>
<p>The custom join/sql will get me all the data I need, but how can I tell activerecord that it belongs to the associated <code>Company</code> objects rather than just being a pile of extra rows?</p>
<h3>Update</h3>
<p>I need to put additional conditions in the join. Something like this:</p>
<pre><code>SELECT blah blah blah
LEFT OUTER JOIN companies ON people.company_id = companies.id AND people.magical_flag IS NULL
<Several other joins>
WHERE blahblahblah
</code></pre>
|
[
{
"answer_id": 131247,
"author": "Toby Hede",
"author_id": 14971,
"author_profile": "https://Stackoverflow.com/users/14971",
"pm_score": 3,
"selected": false,
"text": "Contractors.find(\n :all, \n :include => {:council_areas => :suburbs},\n :conditions => [\"suburbs.postcode = ?\", customer.postcode] \n) \n SELECT contractors.*, council_areas.*, suburbs.*\nFROM `contractors` \nLEFT OUTER JOIN `contractors_council_areas` ON `contractors_council_areas`.contractor_id = `contractors`.id \nLEFT OUTER JOIN `council_areas` ON `council_areas`.id = `contractors_council_areas`.council_area_id \nLEFT OUTER JOIN `council_areas_suburbs` ON `council_areas_suburbs`.council_area_id = `council_areas`.id \nLEFT OUTER JOIN `suburbs` ON `suburbs`.id = `council_areas_suburbs`.suburb_id WHERE (suburbs.postcode = '5000')\n"
},
{
"answer_id": 2447036,
"author": "Jeremiah Peschka",
"author_id": 11780,
"author_profile": "https://Stackoverflow.com/users/11780",
"pm_score": 2,
"selected": false,
"text": "Person.reflect_on_association(:companies).options[:conditions] = 'people.magical_flag IS NULL'\n"
},
{
"answer_id": 13749013,
"author": "Tomek Wałkuski",
"author_id": 907258,
"author_profile": "https://Stackoverflow.com/users/907258",
"pm_score": 2,
"selected": false,
"text": ":joins :includes \nPerson.find(\n :all,\n :joins => 'LEFT OUTER JOIN companies ON people.company_id = companies.id AND _pass_custom_conditions_here_',\n :includes => :companies\n)\n \nPerson.includes(:companies).joins('LEFT OUTER JOIN companies ON people.company_id = companies.id AND _pass_custom_conditions_here_')\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/130268",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/234/"
] |
130,273
|
<p>I'm trying to automate a program I made with a test suite via a .cmd file.</p>
<p>I can get the program that I ran's return code via %errorlevel%. </p>
<p>My program has certain return codes for each type of error.</p>
<p>For example: </p>
<p>1 - means failed for such and such a reason</p>
<p>2 - means failed for some other reason</p>
<p>...</p>
<p>echo FAILED: Test case failed, error level: %errorlevel% >> TestSuite1Log.txt</p>
<p>Instead I'd like to somehow say:</p>
<p>echo FAILED: Test case failed, error reason: lookupError(%errorlevel%) >> TestSuite1Log.txt</p>
<p>Is this possible with a .bat file? Or do I have to move to a scripting language like python/perl?</p>
|
[
{
"answer_id": 130291,
"author": "mattlant",
"author_id": 14642,
"author_profile": "https://Stackoverflow.com/users/14642",
"pm_score": 1,
"selected": false,
"text": "C:\\Users\\matt.MATTLANT>help call\nCalls one batch program from another.\n\nCALL [drive:][path]filename [batch-parameters]\n\n batch-parameters Specifies any command-line information required by the\n batch program.\n"
},
{
"answer_id": 130294,
"author": "Ray Hayes",
"author_id": 7093,
"author_profile": "https://Stackoverflow.com/users/7093",
"pm_score": 1,
"selected": false,
"text": "@echo off\nmyApp.exe\nif errorlevel 2 goto Do2\nif errorlevel 1 goto do1\necho Success\ngoto End\n\n:Do2\necho Something when 2 returned\ngoto End\n\n:Do1\necho Something when 1 returned\ngoto End\n\n:End\n @echo off\necho passed %1\ngoto Label%1\n\n:Label\necho not matched!\ngoto end\n\n:Label1\necho One\ngoto end\n\n:Label2\necho Two\ngoto end\n\n:end\n C:\\>test\npassed\nnot matched!\n\nC:\\>test 9\npassed 9\nThe system cannot find the batch label specified - Label9\n\nC:\\>test 1\npassed 1\nOne\n\nC:\\>test 2\npassed 2\nTwo\n"
},
{
"answer_id": 130308,
"author": "Franci Penov",
"author_id": 17028,
"author_profile": "https://Stackoverflow.com/users/17028",
"pm_score": 2,
"selected": false,
"text": "setlocal\n\nrem Main script\ncall :LookupErrorReason %errorlevel%\necho FAILED Test case failed, error reason: %errorreason% >> TestSuite1Log.txt\ngoto :EndOfScript\n\nrem Lookup subroutine\n:LookupErrorReason\n if %%1 == 3 set errorreason=Some reason\n if %%1 == 2 set errorreason=Another reason\n if %%1 == 1 set errorreason=Third reason\ngoto :EndOfScript\n\n:EndOfScript\nendlocal\n"
},
{
"answer_id": 130319,
"author": "David Webb",
"author_id": 3171,
"author_profile": "https://Stackoverflow.com/users/3171",
"pm_score": 5,
"selected": true,
"text": "ENABLEDELAYEDEXPANSION ! % REM Turn on Delayed Expansion\nSETLOCAL ENABLEDELAYEDEXPANSION\n\nREM Define messages as variables with the ERRORLEVEL on the end of the name\nSET MESSAGE0=Everything is fine\nSET MESSAGE1=Failed for such and such a reason\nSET MESSAGE2=Failed for some other reason\n\nREM Set ERRORLEVEL - or run command here\nSET ERRORLEVEL=2\n\nREM Print the message corresponding to the ERRORLEVEL\nECHO !MESSAGE%ERRORLEVEL%!\n HELP SETLOCAL HELP SET"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/130273",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3153/"
] |
130,292
|
<p>What is the proper way to inject a data access dependency when I do lazy loading?</p>
<p>For example I have the following class structure</p>
<pre><code>class CustomerDao : ICustomerDao
public Customer GetById(int id) {...}
class Transaction {
int customer_id; //Transaction always knows this value
Customer _customer = null;
ICustomerDao _customer_dao;
Customer GetCustomer() {
if(_customer == null)
_customer = _customer_dao.GetById(_customer_id);
return _customer
}
</code></pre>
<p>How do I get the reference to _customer_dao into the transaction object? Requiring it for the constructor seems like it wouldn't really make sense if I want the Transaction to at least look like a POCO. Is it ok to have the Transaction object reference the Inversion of Control Container directly? That also seems awkward too.</p>
<p>How do frameworks like NHibernate handle this?</p>
|
[
{
"answer_id": 131059,
"author": "Toran Billups",
"author_id": 2701,
"author_profile": "https://Stackoverflow.com/users/2701",
"pm_score": 1,
"selected": false,
"text": "public class Product\n{\n private int mProductID;\n private Supplier mSupplier;\n private ISupplierService mSupplierService;\n\n public Product()\n {\n //if you want your object to remain POCO you can use dual constr\n //this constr will be for app use, the next will be for testing\n } \n\n public Product(ISupplierService SupplierService)\n {\n mSupplierService = SupplierService;\n }\n\n public Supplier Supplier {\n get {\n if (mSupplier == null) {\n if (mSupplierService == null) {\n mSupplierService = new SupplierService();\n }\n mSupplier = mSupplierService.GetSupplierByProductID(mProductID);\n }\n return mSupplier;\n }\n set { mSupplier = value; }\n }\n}\n"
},
{
"answer_id": 131186,
"author": "Michael Lang",
"author_id": 19452,
"author_profile": "https://Stackoverflow.com/users/19452",
"pm_score": 1,
"selected": false,
"text": "public interface IDao<T>\n{\n public T GetById(int id);\n}\n\n\npublic interface ICustomerDao : IDao<Customer>\n{\n}\n\npublic class CustomerDao : ICustomerDao\n{\n public Customer GetById(int id) \n {...}\n}\n\npublic class Transaction<T> where T : class\n{\n\n int _id; //Transaction always knows this value\n T _dataObject;\n IDao<T> _dao;\n\n public Transaction(IDao<T> myDao, int id)\n {\n _id = id;\n _dao = myDao;\n }\n\n public T Get()\n {\n if (_dataObject == null)\n _dataObject = _dao.GetById(_id);\n return _dataObject;\n }\n}\n"
},
{
"answer_id": 522547,
"author": "thinkbeforecoding",
"author_id": 47001,
"author_profile": "https://Stackoverflow.com/users/47001",
"pm_score": 3,
"selected": false,
"text": "public class Lazy<T>\n{\n T value;\n Func<T> loader;\n\n public Lazy(T value) { this.value = value; }\n public Lazy(Func<T> loader { this.loader = loader; }\n\n T Value\n {\n get \n {\n if (loader != null)\n {\n value = loader();\n loader = null;\n }\n\n return value;\n }\n\n public static implicit operator T(Lazy<T> lazy)\n {\n return lazy.Value;\n }\n\n public static implicit operator Lazy<T>(T value)\n {\n return new Lazy<T>(value);\n }\n}\n public class Transaction\n{\n private static readonly Lazy<Customer> customer;\n\n public Transaction(Lazy<Customer> customer)\n {\n this.customer = customer;\n }\n\n public Customer Customer\n {\n get { return customer; } // implicit cast happen here\n }\n}\n new Transaction(new Customer(..)) // implicite cast \n //from Customer to Lazy<Customer>..\n public Transaction GetTransaction(Guid id)\n{\n custmerId = ... // find the customer id \n return new Transaction(() => dao.GetCustomer(customerId));\n}\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/130292",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
] |
130,322
|
<p>I am trying to pass a member function within a class to a function that takes a member function class pointer. The problem I am having is that I am not sure how to properly do this within the class using the this pointer. Does anyone have suggestions?</p>
<p>Here is a copy of the class that is passing the member function:</p>
<pre><code>class testMenu : public MenuScreen{
public:
bool draw;
MenuButton<testMenu> x;
testMenu():MenuScreen("testMenu"){
x.SetButton(100,100,TEXT("buttonNormal.png"),TEXT("buttonHover.png"),TEXT("buttonPressed.png"),100,40,&this->test2);
draw = false;
}
void test2(){
draw = true;
}
};
</code></pre>
<p>The function x.SetButton(...) is contained in another class, where "object" is a template.</p>
<pre><code>void SetButton(int xPos, int yPos, LPCWSTR normalFilePath, LPCWSTR hoverFilePath, LPCWSTR pressedFilePath, int Width, int Height, void (object::*ButtonFunc)()) {
BUTTON::SetButton(xPos, yPos, normalFilePath, hoverFilePath, pressedFilePath, Width, Height);
this->ButtonFunc = &ButtonFunc;
}
</code></pre>
<p>If anyone has any advice on how I can properly send this function so that I can use it later.</p>
|
[
{
"answer_id": 130402,
"author": "Matt Cruikshank",
"author_id": 8643,
"author_profile": "https://Stackoverflow.com/users/8643",
"pm_score": 4,
"selected": false,
"text": "boost::bind boost::function"
},
{
"answer_id": 130528,
"author": "Commodore Jaeger",
"author_id": 4659,
"author_profile": "https://Stackoverflow.com/users/4659",
"pm_score": 6,
"selected": true,
"text": "MenuButton::SetButton() template <class object>\nvoid MenuButton::SetButton(int xPos, int yPos, LPCWSTR normalFilePath,\n LPCWSTR hoverFilePath, LPCWSTR pressedFilePath,\n int Width, int Height, object *ButtonObj, void (object::*ButtonFunc)())\n{\n BUTTON::SetButton(xPos, yPos, normalFilePath, hoverFilePath, pressedFilePath, Width, Height);\n\n this->ButtonObj = ButtonObj;\n this->ButtonFunc = ButtonFunc;\n}\n ((ButtonObj)->*(ButtonFunc))();\n MenuButton::SetButton() testMenu::testMenu()\n :MenuScreen(\"testMenu\")\n{\n x.SetButton(100,100,TEXT(\"buttonNormal.png\"), TEXT(\"buttonHover.png\"),\n TEXT(\"buttonPressed.png\"), 100, 40, this, test2);\n draw = false;\n}\n"
},
{
"answer_id": 132073,
"author": "GKelly",
"author_id": 18744,
"author_profile": "https://Stackoverflow.com/users/18744",
"pm_score": 3,
"selected": false,
"text": "class ButtonContract\n{\n public:\n virtual void buttonAction();\n}\n\n\nclass testMenu : public MenuScreen, public virtual ButtonContract\n{\n public:\n bool draw;\n MenuButton<testMenu> x;\n\n testMenu():MenuScreen(\"testMenu\")\n {\n x.SetButton(100,100,TEXT(\"buttonNormal.png\"), \n TEXT(\"buttonHover.png\"), \n TEXT(\"buttonPressed.png\"), \n 100, 40, &this);\n draw = false;\n }\n\n //Implementation of the ButtonContract method!\n void buttonAction()\n {\n draw = true;\n }\n};\n"
},
{
"answer_id": 312716,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 2,
"selected": false,
"text": "this->ButtonFunc = &ButtonFunc;\n void (object::**ButtonFunc)() ((ButtonObj)->*(ButtonFunc))();\n"
},
{
"answer_id": 29659812,
"author": "Yuanlong Li",
"author_id": 2874994,
"author_profile": "https://Stackoverflow.com/users/2874994",
"pm_score": 3,
"selected": false,
"text": "#include <functional>\n typedef std::function<int(int,int) > Max;\n void SetHandler(Max Handler);\n SetHandler(&some function);\n class test{\npublic:\n int GetMax(int a, int b);\n...\n}\n std::placeholders test t;\nMax Handler = std::bind(&test::GetMax,&t,std::placeholders::_1,std::placeholders::_2);\nsome object.SetHandler(Handler);\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/130322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20229/"
] |
130,328
|
<p>How do I get the caller's IP address in a WebMethod?</p>
<pre><code>[WebMethod]
public void Foo()
{
// HttpRequest... ? - Not giving me any options through intellisense...
}
</code></pre>
<p>using C# and ASP.NET</p>
|
[
{
"answer_id": 130343,
"author": "Troels Thomsen",
"author_id": 20138,
"author_profile": "https://Stackoverflow.com/users/20138",
"pm_score": 2,
"selected": false,
"text": "WebService Context.Request HttpContext.Current HttpRequest"
},
{
"answer_id": 130345,
"author": "Aaron Powell",
"author_id": 11388,
"author_profile": "https://Stackoverflow.com/users/11388",
"pm_score": 2,
"selected": false,
"text": "string ipAddress = HttpContext.Current.Request.ServerVariables[\"REMOTE_ADDR\"];\n"
},
{
"answer_id": 130350,
"author": "Kev",
"author_id": 419,
"author_profile": "https://Stackoverflow.com/users/419",
"pm_score": 3,
"selected": false,
"text": "Context.Request.UserHostAddress\n"
},
{
"answer_id": 19522170,
"author": "depoip",
"author_id": 1597660,
"author_profile": "https://Stackoverflow.com/users/1597660",
"pm_score": 0,
"selected": false,
"text": "static public string sGetIP()\n{\n try\n {\n string functionReturnValue = null;\n\n String oRequestHttp =\n WebOperationContext.Current.IncomingRequest.Headers[\"User-Host-Address\"];\n if (string.IsNullOrEmpty(oRequestHttp))\n {\n OperationContext context = OperationContext.Current;\n MessageProperties prop = context.IncomingMessageProperties;\n RemoteEndpointMessageProperty endpoint =\n prop[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;\n oRequestHttp = endpoint.Address;\n }\n return functionReturnValue;\n }\n catch (Exception ex)\n {\n return \"unknown IP\";\n }\n}\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/130328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1463/"
] |
130,354
|
<p>I need to simulate a low bandwidth, high latency connection to a server in order to emulate the conditions of a VPN at a remote site. The bandwidth and latency should be tweakable so I can discover the best combination in order to run our software package.</p>
|
[
{
"answer_id": 130465,
"author": "heckj",
"author_id": 19477,
"author_profile": "https://Stackoverflow.com/users/19477",
"pm_score": 5,
"selected": false,
"text": "/etc/rc.firewall.56k ipfw add pipe 1 ip from any to any out\nipfw add pipe 2 ip from any to any in \nipfw pipe 1 config bw 56Kbit/s \nipfw pipe 2 config bw 56Kbit/s\n /etc/rc.conf firewall_type=\"open\"\n firewall_type=\"/etc/rc.firewall.56k\"\n"
},
{
"answer_id": 37373648,
"author": "Sawan",
"author_id": 2608245,
"author_profile": "https://Stackoverflow.com/users/2608245",
"pm_score": 2,
"selected": false,
"text": "tc tc"
},
{
"answer_id": 51684651,
"author": "auxten",
"author_id": 896026,
"author_profile": "https://Stackoverflow.com/users/896026",
"pm_score": 0,
"selected": false,
"text": "group:\n - \n name: china\n nodes:\n - \n ip: 10.250.1.2\n cmd: \"cd /scripts && ./YourBin args\"\n - \n ip: 10.250.1.3\n cmd: \"cd /scripts && ./YourBin args\"\n delay: \"100ms 10ms 30%\"\n loss: \"1% 10%\"\n - \n name: us\n nodes:\n - \n ip: 10.250.2.2\n cmd: \"cd /scripts && ./YourBin args\"\n - \n ip: 10.250.2.3\n cmd: \"cd /scripts && ./YourBin args\"\n delay: \"1000ms 10ms 30%\"\n loss: \"1% 10%\"\n\nnetwork:\n -\n groups:\n - china\n - us\n delay: \"200ms 10ms 1%\"\n corrupt: \"0.2%\"\n rate: \"10mbit\"\n ./generate scripts/your.yaml"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/130354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/190298/"
] |
130,396
|
<p>Is there a way to use constants in <strong>JavaScript</strong>?</p>
<p>If not, what's the common practice for specifying variables that are used as constants?</p>
|
[
{
"answer_id": 130398,
"author": "Jason Bunting",
"author_id": 1790,
"author_profile": "https://Stackoverflow.com/users/1790",
"pm_score": 5,
"selected": false,
"text": "const"
},
{
"answer_id": 130399,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 11,
"selected": true,
"text": "const const MY_CONSTANT = \"some-value\";\n var var MY_CONSTANT = \"some-value\";\n"
},
{
"answer_id": 130425,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 2,
"selected": false,
"text": "const var"
},
{
"answer_id": 130596,
"author": "Andrew Hedges",
"author_id": 11577,
"author_profile": "https://Stackoverflow.com/users/11577",
"pm_score": 3,
"selected": false,
"text": "with() with ({\n MY_CONST : 'some really important value'\n}) {\n alert(MY_CONST);\n}\n CONST var MY_CONST = 'whatever';"
},
{
"answer_id": 131286,
"author": "Burke",
"author_id": 21980,
"author_profile": "https://Stackoverflow.com/users/21980",
"pm_score": 8,
"selected": false,
"text": "var CONFIG = (function() {\n var private = {\n 'MY_CONST': '1',\n 'ANOTHER_CONST': '2'\n };\n\n return {\n get: function(name) { return private[name]; }\n };\n})();\n\nalert('MY_CONST: ' + CONFIG.get('MY_CONST')); // 1\n\nCONFIG.MY_CONST = '2';\nalert('MY_CONST: ' + CONFIG.get('MY_CONST')); // 1\n\nCONFIG.private.MY_CONST = '2'; // error\nalert('MY_CONST: ' + CONFIG.get('MY_CONST')); // 1\n"
},
{
"answer_id": 687457,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 7,
"selected": false,
"text": "const const CONSTANT_NAME = 0;\n"
},
{
"answer_id": 1626809,
"author": "C Nagle",
"author_id": 196851,
"author_profile": "https://Stackoverflow.com/users/196851",
"pm_score": 6,
"selected": false,
"text": "<script language=\"VBScript\">\n Const IE_CONST = True\n</script>\n<script type=\"text/javascript\">\n if (typeof TEST_CONST == 'undefined') {\n const IE_CONST = false;\n }\n alert(IE_CONST);\n</script>\n"
},
{
"answer_id": 4270878,
"author": "MTS",
"author_id": 519307,
"author_profile": "https://Stackoverflow.com/users/519307",
"pm_score": 4,
"selected": false,
"text": "function MY_CONSTANT() {\n return \"some-value\";\n}\n\n\nalert(MY_CONSTANT());\n"
},
{
"answer_id": 4637056,
"author": "Not a Name",
"author_id": 568455,
"author_profile": "https://Stackoverflow.com/users/568455",
"pm_score": 6,
"selected": false,
"text": "Object.defineProperty Object.defineProperty (window,'CONSTANT',{ value : 5, writable: false });\n"
},
{
"answer_id": 4714062,
"author": "Rene Saarsoo",
"author_id": 15982,
"author_profile": "https://Stackoverflow.com/users/15982",
"pm_score": 2,
"selected": false,
"text": "date.add(5, MyModule.Date.DAY).add(12, MyModule.Date.HOUR)\n date.add(5, \"days\").add(12, \"hours\")\n MyModule.Date.HOUR action === 18 action === \"save\""
},
{
"answer_id": 5591741,
"author": "Keith",
"author_id": 698164,
"author_profile": "https://Stackoverflow.com/users/698164",
"pm_score": 4,
"selected": false,
"text": "/* author Keith Evetts 2009 License: LGPL \nanonymous function sets up: \nglobal function SETCONST (String name, mixed value) \nglobal function CONST (String name) \nconstants once set may not be altered - console error is generated \nthey are retrieved as CONST(name) \nthe object holding the constants is private and cannot be accessed from the outer script directly, only through the setter and getter provided \n*/\n\n(function(){ \n var constants = {}; \n self.SETCONST = function(name,value) { \n if (typeof name !== 'string') { throw new Error('constant name is not a string'); } \n if (!value) { throw new Error(' no value supplied for constant ' + name); } \n else if ((name in constants) ) { throw new Error('constant ' + name + ' is already defined'); } \n else { \n constants[name] = value; \n return true; \n } \n }; \n self.CONST = function(name) { \n if (typeof name !== 'string') { throw new Error('constant name is not a string'); } \n if ( name in constants ) { return constants[name]; } \n else { throw new Error('constant ' + name + ' has not been defined'); } \n }; \n}()) \n\n\n// ------------- demo ---------------------------- \nSETCONST( 'VAT', 0.175 ); \nalert( CONST('VAT') );\n\n\n//try to alter the value of VAT \ntry{ \n SETCONST( 'VAT', 0.22 ); \n} catch ( exc ) { \n alert (exc.message); \n} \n//check old value of VAT remains \nalert( CONST('VAT') ); \n\n\n// try to get at constants object directly \nconstants['DODO'] = \"dead bird\"; // error \n"
},
{
"answer_id": 5840971,
"author": "mgutt",
"author_id": 318765,
"author_profile": "https://Stackoverflow.com/users/318765",
"pm_score": 4,
"selected": false,
"text": "const // define MY_FAV as a constant and give it the value 7\nconst MY_FAV = 7;\n\n// this will throw an error - Uncaught TypeError: Assignment to constant variable.\nMY_FAV = 20;\n const var function(){return} const const const Map Set WeakMap __proto__"
},
{
"answer_id": 6501627,
"author": "Webveloper",
"author_id": 424671,
"author_profile": "https://Stackoverflow.com/users/424671",
"pm_score": 2,
"selected": false,
"text": "try{\n // i can haz const?\n eval(\"const FOO='{0}';\");\n // for reals?\n var original=FOO;\n try{\n FOO='?NO!';\n }catch(err1){\n // no err from Firefox/Chrome - fails silently\n alert('err1 '+err1);\n }\n alert('const '+FOO);\n if(FOO=='?NO!'){\n // changed in Sf/Op - set back to original value\n FOO=original;\n }\n}catch(err2){\n // IE fail\n alert('err2 '+err2);\n // set var (no var keyword - Chrome/Firefox complain about redefining const)\n FOO='{0}';\n alert('var '+FOO);\n}\nalert('FOO '+FOO);\n"
},
{
"answer_id": 6742534,
"author": "Derek 朕會功夫",
"author_id": 283863,
"author_profile": "https://Stackoverflow.com/users/283863",
"pm_score": 4,
"selected": false,
"text": "const"
},
{
"answer_id": 9223523,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": " my={get constant1(){return \"constant 1\"},\n get constant2(){return \"constant 2\"},\n get constant3(){return \"constant 3\"},\n get constantN(){return \"constant N\"}\n }\n my.constant1; >> \"constant 1\" \n my.constant1 = \"new constant 1\";\n my.constant1; >> \"constant 1\" \n"
},
{
"answer_id": 11789234,
"author": "Steven Kapaun",
"author_id": 1573097,
"author_profile": "https://Stackoverflow.com/users/1573097",
"pm_score": 3,
"selected": false,
"text": "/*Tested in: IE 9.0.8; Firefox 14.0.1; Chrome 20.0.1180.60 m; Not Tested in Safari*/\n\n(function(){\n /*The two functions _define and _access are from Keith Evetts 2009 License: LGPL (SETCONST and CONST).\n They're the same just as he did them, the only things I changed are the variable names and the text\n of the error messages.\n */\n\n //object literal to hold the constants\n var j = {};\n\n /*Global function _define(String h, mixed m). I named it define to mimic the way PHP 'defines' constants.\n The argument 'h' is the name of the const and has to be a string, 'm' is the value of the const and has\n to exist. If there is already a property with the same name in the object holder, then we throw an error.\n If not, we add the property and set the value to it. This is a 'hidden' function and the user doesn't\n see any of your coding call this function. You call the _makeDef() in your code and that function calls\n this function. - You can change the error messages to whatever you want them to say.\n */\n self._define = function(h,m) {\n if (typeof h !== 'string') { throw new Error('I don\\'t know what to do.'); }\n if (!m) { throw new Error('I don\\'t know what to do.'); }\n else if ((h in j) ) { throw new Error('We have a problem!'); }\n else {\n j[h] = m;\n return true;\n }\n };\n\n /*Global function _makeDef(String t, mixed y). I named it makeDef because we 'make the define' with this\n function. The argument 't' is the name of the const and doesn't need to be all caps because I set it\n to upper case within the function, 'y' is the value of the value of the const and has to exist. I\n make different variables to make it harder for a user to figure out whats going on. We then call the\n _define function with the two new variables. You call this function in your code to set the constant.\n You can change the error message to whatever you want it to say.\n */\n self._makeDef = function(t, y) {\n if(!y) { throw new Error('I don\\'t know what to do.'); return false; }\n q = t.toUpperCase();\n w = y;\n _define(q, w);\n };\n\n /*Global function _getDef(String s). I named it getDef because we 'get the define' with this function. The\n argument 's' is the name of the const and doesn't need to be all capse because I set it to upper case\n within the function. I make a different variable to make it harder for a user to figure out whats going\n on. The function returns the _access function call. I pass the new variable and the original string\n along to the _access function. I do this because if a user is trying to get the value of something, if\n there is an error the argument doesn't get displayed with upper case in the error message. You call this\n function in your code to get the constant.\n */\n self._getDef = function(s) {\n z = s.toUpperCase();\n return _access(z, s);\n };\n\n /*Global function _access(String g, String f). I named it access because we 'access' the constant through\n this function. The argument 'g' is the name of the const and its all upper case, 'f' is also the name\n of the const, but its the original string that was passed to the _getDef() function. If there is an\n error, the original string, 'f', is displayed. This makes it harder for a user to figure out how the\n constants are being stored. If there is a property with the same name in the object holder, we return\n the constant value. If not, we check if the 'f' variable exists, if not, set it to the value of 'g' and\n throw an error. This is a 'hidden' function and the user doesn't see any of your coding call this\n function. You call the _getDef() function in your code and that function calls this function.\n You can change the error messages to whatever you want them to say.\n */\n self._access = function(g, f) {\n if (typeof g !== 'string') { throw new Error('I don\\'t know what to do.'); }\n if ( g in j ) { return j[g]; }\n else { if(!f) { f = g; } throw new Error('I don\\'t know what to do. I have no idea what \\''+f+'\\' is.'); }\n };\n\n /*The four variables below are private and cannot be accessed from the outside script except for the\n functions inside this anonymous function. These variables are strings of the four above functions and\n will be used by the all-dreaded eval() function to set them back to their original if any of them should\n be changed by a user trying to hack your code.\n */\n var _define_func_string = \"function(h,m) {\"+\" if (typeof h !== 'string') { throw new Error('I don\\\\'t know what to do.'); }\"+\" if (!m) { throw new Error('I don\\\\'t know what to do.'); }\"+\" else if ((h in j) ) { throw new Error('We have a problem!'); }\"+\" else {\"+\" j[h] = m;\"+\" return true;\"+\" }\"+\" }\";\n var _makeDef_func_string = \"function(t, y) {\"+\" if(!y) { throw new Error('I don\\\\'t know what to do.'); return false; }\"+\" q = t.toUpperCase();\"+\" w = y;\"+\" _define(q, w);\"+\" }\";\n var _getDef_func_string = \"function(s) {\"+\" z = s.toUpperCase();\"+\" return _access(z, s);\"+\" }\";\n var _access_func_string = \"function(g, f) {\"+\" if (typeof g !== 'string') { throw new Error('I don\\\\'t know what to do.'); }\"+\" if ( g in j ) { return j[g]; }\"+\" else { if(!f) { f = g; } throw new Error('I don\\\\'t know what to do. I have no idea what \\\\''+f+'\\\\' is.'); }\"+\" }\";\n\n /*Global function _doFunctionCheck(String u). I named it doFunctionCheck because we're 'checking the functions'\n The argument 'u' is the name of any of the four above function names you want to check. This function will\n check if a specific line of code is inside a given function. If it is, then we do nothing, if not, then\n we use the eval() function to set the function back to its original coding using the function string\n variables above. This function will also throw an error depending upon the doError variable being set to true\n This is a 'hidden' function and the user doesn't see any of your coding call this function. You call the\n doCodeCheck() function and that function calls this function. - You can change the error messages to\n whatever you want them to say.\n */\n self._doFunctionCheck = function(u) {\n var errMsg = 'We have a BIG problem! You\\'ve changed my code.';\n var doError = true;\n d = u;\n switch(d.toLowerCase())\n {\n case \"_getdef\":\n if(_getDef.toString().indexOf(\"z = s.toUpperCase();\") != -1) { /*do nothing*/ }\n else { eval(\"_getDef = \"+_getDef_func_string); if(doError === true) { throw new Error(errMsg); } }\n break;\n case \"_makedef\":\n if(_makeDef.toString().indexOf(\"q = t.toUpperCase();\") != -1) { /*do nothing*/ }\n else { eval(\"_makeDef = \"+_makeDef_func_string); if(doError === true) { throw new Error(errMsg); } }\n break;\n case \"_define\":\n if(_define.toString().indexOf(\"else if((h in j) ) {\") != -1) { /*do nothing*/ }\n else { eval(\"_define = \"+_define_func_string); if(doError === true) { throw new Error(errMsg); } }\n break;\n case \"_access\":\n if(_access.toString().indexOf(\"else { if(!f) { f = g; }\") != -1) { /*do nothing*/ }\n else { eval(\"_access = \"+_access_func_string); if(doError === true) { throw new Error(errMsg); } }\n break;\n default:\n if(doError === true) { throw new Error('I don\\'t know what to do.'); }\n }\n };\n\n /*Global function _doCodeCheck(String v). I named it doCodeCheck because we're 'doing a code check'. The argument\n 'v' is the name of one of the first four functions in this script that you want to check. I make a different\n variable to make it harder for a user to figure out whats going on. You call this function in your code to check\n if any of the functions has been changed by the user.\n */\n self._doCodeCheck = function(v) {\n l = v;\n _doFunctionCheck(l);\n };\n}())\n"
},
{
"answer_id": 13118516,
"author": "user1635543",
"author_id": 1635543,
"author_profile": "https://Stackoverflow.com/users/1635543",
"pm_score": 3,
"selected": false,
"text": "var constants = (function(){\n var a = 9;\n\n //GLOBAL CONSTANT (through \"return\")\n window.__defineGetter__(\"GCONST\", function(){\n return a;\n });\n\n //LOCAL CONSTANT\n return {\n get CONST(){\n return a;\n }\n }\n})();\n\nconstants.CONST = 8; //9\nalert(constants.CONST); //9\n const a = 9;\n"
},
{
"answer_id": 13194609,
"author": "tenshou",
"author_id": 778623,
"author_profile": "https://Stackoverflow.com/users/778623",
"pm_score": 4,
"selected": false,
"text": "var obj = {};\nObject.defineProperty(obj, 'CONSTANT', {\n configurable: false\n enumerable: true,\n writable: false,\n value: \"your constant value\"\n});\n this Object.defineProperty(this, 'constant', {\n enumerable: true, \n writable: false, \n value: 7, \n configurable: false\n});\n\n> constant\n=> 7\n> constant = 5\n=> 7\n"
},
{
"answer_id": 13235597,
"author": "isomorphismes",
"author_id": 563329,
"author_profile": "https://Stackoverflow.com/users/563329",
"pm_score": 2,
"selected": false,
"text": "Rhino.js const"
},
{
"answer_id": 13326757,
"author": "codemuncher",
"author_id": 1815283,
"author_profile": "https://Stackoverflow.com/users/1815283",
"pm_score": 3,
"selected": false,
"text": "var myconst = value;\n Object['myconst'] = value;\n"
},
{
"answer_id": 14723455,
"author": "Sudhanshu Yadav",
"author_id": 1906306,
"author_profile": "https://Stackoverflow.com/users/1906306",
"pm_score": 3,
"selected": false,
"text": "var iw_constant={\n name:'sudhanshu',\n age:'23'\n //all varibale come like this\n}\n iw_constant.name iw_constant.age Object.freeze(iw_constant);\n var iw_constant= (function(){\n var allConstant={\n name:'sudhanshu',\n age:'23'\n //all varibale come like this\n\n };\n\n return function(key){\n allConstant[key];\n }\n };\n iw_constant('name') iw_constant('age')"
},
{
"answer_id": 20846329,
"author": "hasen",
"author_id": 35364,
"author_profile": "https://Stackoverflow.com/users/35364",
"pm_score": 4,
"selected": false,
"text": "var constant = function(val) {\n return function() {\n return val;\n }\n}\n a = constant(10);\n\na(); // 10\n\nb = constant(20);\n\nb(); // 20\n constant"
},
{
"answer_id": 23462960,
"author": "sam",
"author_id": 822138,
"author_profile": "https://Stackoverflow.com/users/822138",
"pm_score": 6,
"selected": false,
"text": "\"use strict\";\n\nvar constants = Object.freeze({\n \"π\": 3.141592653589793 ,\n \"e\": 2.718281828459045 ,\n \"i\": Math.sqrt(-1)\n});\n\nconstants.π; // -> 3.141592653589793\nconstants.π = 3; // -> TypeError: Cannot assign to read only property 'π' …\nconstants.π; // -> 3.141592653589793\n\ndelete constants.π; // -> TypeError: Unable to delete property.\nconstants.π; // -> 3.141592653589793\n const constants"
},
{
"answer_id": 25547960,
"author": "rounce",
"author_id": 1592759,
"author_profile": "https://Stackoverflow.com/users/1592759",
"pm_score": 2,
"selected": false,
"text": "var constants = {\n MY_CONSTANT : \"myconstant\",\n SOMETHING_ELSE : 123\n }\n , constantMap = new function ConstantMap() {};\n\nfor(var c in constants) {\n !function(cKey) {\n Object.defineProperty(constantMap, cKey, {\n enumerable : true,\n get : function(name) { return constants[cKey]; }\n })\n }(c);\n}\n var foo = constantMap.MY_CONSTANT constantMap.MY_CONSTANT = \"bar\" constantMap.MY_CONSTANT === \"myconstant\""
},
{
"answer_id": 27646549,
"author": "Şafak Gür",
"author_id": 704144,
"author_profile": "https://Stackoverflow.com/users/704144",
"pm_score": 2,
"selected": false,
"text": "CONFIG.MY_CONST CONFIG.get('MY_CONST') var CONFIG = (function() {\n var constants = {\n 'MY_CONST': 1,\n 'ANOTHER_CONST': 2\n };\n\n var result = {};\n for (var n in constants)\n if (constants.hasOwnProperty(n))\n Object.defineProperty(result, n, { value: constants[n] });\n\n return result;\n}());\n"
},
{
"answer_id": 27646695,
"author": "Muhammad Reda",
"author_id": 863380,
"author_profile": "https://Stackoverflow.com/users/863380",
"pm_score": 2,
"selected": false,
"text": "$provide.constant() angularApp.constant('YOUR_CONSTANT', 'value');\n"
},
{
"answer_id": 29994502,
"author": "Gelin Luo",
"author_id": 391227,
"author_profile": "https://Stackoverflow.com/users/391227",
"pm_score": 0,
"selected": false,
"text": "var ConstJs = require('constjs');\n\nvar Colors = ConstJs.enum(\"blue red\");\n\nvar myColor = Colors.blue;\n\nconsole.log(myColor.isBlue()); // output true \nconsole.log(myColor.is('blue')); // output true \nconsole.log(myColor.is('BLUE')); // output true \nconsole.log(myColor.is(0)); // output true \nconsole.log(myColor.is(Colors.blue)); // output true \n\nconsole.log(myColor.isRed()); // output false \nconsole.log(myColor.is('red')); // output false \n\nconsole.log(myColor._id); // output blue \nconsole.log(myColor.name()); // output blue \nconsole.log(myColor.toString()); // output blue \n\n// See how CamelCase is used to generate the isXxx() functions \nvar AppMode = ConstJs.enum('SIGN_UP, LOG_IN, FORGOT_PASSWORD');\nvar curMode = AppMode.LOG_IN;\n\nconsole.log(curMode.isLogIn()); // output true \nconsole.log(curMode.isSignUp()); // output false \nconsole.log(curMode.isForgotPassword()); // output false \n var ConstJs = require('constjs');\n\nvar Weekdays = ConstJs.const(\"Mon, Tue, Wed\");\nconsole.log(Weekdays); // output {Mon: 'Mon', Tue: 'Tue', Wed: 'Wed'} \n\nvar today = Weekdays.Wed;\nconsole.log(today); // output: 'Wed'; \n var ConstJs = require('constjs');\n\nvar ColorFlags = ConstJs.bitmap(\"blue red\");\nconsole.log(ColorFlags.blue); // output false \n\nvar StyleFlags = ConstJs.bitmap(true, \"rustic model minimalist\");\nconsole.log(StyleFlags.rustic); // output true \n\nvar CityFlags = ConstJs.bitmap({Chengdu: true, Sydney: false});\nconsole.log(CityFlags.Chengdu); //output true \nconsole.log(CityFlags.Sydney); // output false \n\nvar DayFlags = ConstJs.bitmap(true, {Mon: false, Tue: true});\nconsole.log(DayFlags.Mon); // output false. Default val wont override specified val if the type is boolean \n"
},
{
"answer_id": 30034356,
"author": "Erik Lucio",
"author_id": 3512957,
"author_profile": "https://Stackoverflow.com/users/3512957",
"pm_score": 2,
"selected": false,
"text": "const name1 = value;\n"
},
{
"answer_id": 31185636,
"author": "Manohar Reddy Poreddy",
"author_id": 984471,
"author_profile": "https://Stackoverflow.com/users/984471",
"pm_score": 4,
"selected": false,
"text": "var CONST_WILD_TYPES = {\n REGULAR: 'REGULAR',\n EXPANDING: 'EXPANDING',\n STICKY: 'STICKY',\n SHIFTING: 'SHIFTING'\n};\n var wildType = CONST_WILD_TYPES.REGULAR;\n if (wildType === CONST_WILD_TYPES.REGULAR) {\n // do something here\n}\n switch (wildType) {\n case CONST_WILD_TYPES.REGULAR:\n // do something here\n break;\n case CONST_WILD_TYPES.EXPANDING:\n // do something here\n break;\n}\n"
},
{
"answer_id": 37781134,
"author": "le_m",
"author_id": 1647737,
"author_profile": "https://Stackoverflow.com/users/1647737",
"pm_score": 2,
"selected": false,
"text": "const const const let const x = 1;\nx = 2;\nconsole.log(x); // 1 ...as expected, re-assigning fails\n const o = {x: 1};\no = {x: 2};\nconsole.log(o); // {x: 1} ...as expected, re-assigning fails\n\no.x = 2;\nconsole.log(o); // {x: 2} !!! const does not make objects immutable!\n\nconst a = [];\na = [1];\nconsole.log(a); // 1 ...as expected, re-assigning fails\n\na.push(1);\nconsole.log(a); // [1] !!! const does not make objects immutable\n const ALL_CAPS const"
},
{
"answer_id": 51112979,
"author": "Srikrushna",
"author_id": 5852550,
"author_profile": "https://Stackoverflow.com/users/5852550",
"pm_score": 0,
"selected": false,
"text": "// const c;\n// c = 9; //intialization and declearation at same place\nconst c = 9;\n// const c = 9;// re-declare and initialization is not possible\nconsole.log(c);//9\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/130396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10708/"
] |
130,404
|
<p>I'm trying to find a way to "pretty print" a JavaScript data structure in a human-readable form for debugging.</p>
<p>I have a rather big and complicated data structure being stored in JS and I need to write some code to manipulate it. In order to work out what I'm doing and where I'm going wrong, what I really need is to be able to see the data structure in its entirety, and update it whenever I make changes through the UI.</p>
<p>All of this stuff I can handle myself, apart from finding a nice way to dump a JavaScript data structure to a human-readable string. JSON would do, but it really needs to be nicely formatted and indented. I'd usually use Firebug's excellent DOM dumping stuff for this, but I really need to be able to see the entire structure at once, which doesn't seem to be possible in Firebug.</p>
|
[
{
"answer_id": 130420,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 4,
"selected": false,
"text": "Firebug console.debug (\"%o\", my_object)"
},
{
"answer_id": 130479,
"author": "Jason Bunting",
"author_id": 1790,
"author_profile": "https://Stackoverflow.com/users/1790",
"pm_score": 8,
"selected": false,
"text": "var myArray = ['e', {pluribus: 'unum'}];\nvar text = JSON.stringify(myArray, null, '\\t'); //you can specify a number instead of '\\t' and that many spaces will be used for indentation...\n text [\n \"e\",\n {\n \"pluribus\": \"unum\"\n }\n]\n"
},
{
"answer_id": 130504,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 6,
"selected": true,
"text": "function DumpObject(obj)\n{\n var od = new Object;\n var result = \"\";\n var len = 0;\n\n for (var property in obj)\n {\n var value = obj[property];\n if (typeof value == 'string')\n value = \"'\" + value + \"'\";\n else if (typeof value == 'object')\n {\n if (value instanceof Array)\n {\n value = \"[ \" + value + \" ]\";\n }\n else\n {\n var ood = DumpObject(value);\n value = \"{ \" + ood.dump + \" }\";\n }\n }\n result += \"'\" + property + \"' : \" + value + \", \";\n len++;\n }\n od.dump = result.replace(/, $/, \"\");\n od.len = len;\n\n return od;\n}\n od = DumpObject(something) function DumpObjectIndented(obj, indent)\n{\n var result = \"\";\n if (indent == null) indent = \"\";\n\n for (var property in obj)\n {\n var value = obj[property];\n if (typeof value == 'string')\n value = \"'\" + value + \"'\";\n else if (typeof value == 'object')\n {\n if (value instanceof Array)\n {\n // Just let JS convert the Array to a string!\n value = \"[ \" + value + \" ]\";\n }\n else\n {\n // Recursive dump\n // (replace \" \" by \"\\t\" or something else if you prefer)\n var od = DumpObjectIndented(value, indent + \" \");\n // If you like { on the same line as the key\n //value = \"{\\n\" + od + \"\\n\" + indent + \"}\";\n // If you prefer { and } to be aligned\n value = \"\\n\" + indent + \"{\\n\" + od + \"\\n\" + indent + \"}\";\n }\n }\n result += indent + \"'\" + property + \"' : \" + value + \",\\n\";\n }\n return result.replace(/,\\n$/, \"\");\n}\n"
},
{
"answer_id": 130633,
"author": "Dan",
"author_id": 17121,
"author_profile": "https://Stackoverflow.com/users/17121",
"pm_score": 2,
"selected": false,
"text": "// Usage: dump(object)\nfunction dump(object, pad){\n var indent = '\\t'\n if (!pad) pad = ''\n var out = ''\n if (object.constructor == Array){\n out += '[\\n'\n for (var i=0; i<object.length; i++){\n out += pad + indent + dump(object[i], pad + indent) + '\\n'\n }\n out += pad + ']'\n }else if (object.constructor == Object){\n out += '{\\n'\n for (var i in object){\n out += pad + indent + i + ': ' + dump(object[i], pad + indent) + '\\n'\n }\n out += pad + '}'\n }else{\n out += object\n }\n return out\n}\n"
},
{
"answer_id": 2292443,
"author": "Peter Rust",
"author_id": 194758,
"author_profile": "https://Stackoverflow.com/users/194758",
"pm_score": 1,
"selected": false,
"text": " var temp = Array.prototype.toJSON;\n delete Array.prototype.toJSON;\n $('result').value += JSON.stringify(profile_base, null, 2);\n Array.prototype.toJSON = temp;\n"
},
{
"answer_id": 2292543,
"author": "NVI",
"author_id": 16185,
"author_profile": "https://Stackoverflow.com/users/16185",
"pm_score": 2,
"selected": false,
"text": "jsDump.parse([\n window,\n document,\n { a : 5, '1' : 'foo' },\n /^[ab]+$/g,\n new RegExp('x(.*?)z','ig'),\n alert, \n function fn( x, y, z ){\n return x + y; \n },\n true,\n undefined,\n null,\n new Date(),\n document.body,\n document.getElementById('links')\n]) [\n [Window],\n [Document],\n {\n \"1\": \"foo\",\n \"a\": 5\n },\n /^[ab]+$/g,\n /x(.*?)z/gi,\n function alert( a ){\n [code]\n },\n function fn( a, b, c ){\n [code]\n },\n true,\n undefined,\n null,\n \"Fri Feb 19 2010 00:49:45 GMT+0300 (MSK)\",\n <body id=\"body\" class=\"node\"></body>,\n <div id=\"links\">\n] JSON.stringify({f:function(){}}) // \"{}\"\nJSON.stringify(document.body) // TypeError: Converting circular structure to JSON\n"
},
{
"answer_id": 5475761,
"author": "GTM",
"author_id": 189218,
"author_profile": "https://Stackoverflow.com/users/189218",
"pm_score": 1,
"selected": false,
"text": "function dumpObject(obj, indent) \n{\n var CR = \"<br />\", SPC = \" \", result = \"\";\n if (indent == null) indent = \"\";\n\n for (var property in obj)\n {\n var value = obj[property];\n\n if (typeof value == 'string')\n {\n value = \"'\" + value + \"'\";\n }\n else if (typeof value == 'object')\n {\n if (value instanceof Array)\n {\n // Just let JS convert the Array to a string!\n value = \"[ \" + value + \" ]\";\n }\n else\n {\n var od = dumpObject(value, indent + SPC);\n value = CR + indent + \"{\" + CR + od + CR + indent + \"}\";\n }\n }\n result += indent + \"'\" + property + \"' : \" + value + \",\" + CR;\n }\n return result;\n}\n"
},
{
"answer_id": 5617276,
"author": "knowtheory",
"author_id": 333795,
"author_profile": "https://Stackoverflow.com/users/333795",
"pm_score": 3,
"selected": false,
"text": "Rhino function pp(object, depth, embedded) { \n typeof(depth) == \"number\" || (depth = 0)\n typeof(embedded) == \"boolean\" || (embedded = false)\n var newline = false\n var spacer = function(depth) { var spaces = \"\"; for (var i=0;i<depth;i++) { spaces += \" \"}; return spaces }\n var pretty = \"\"\n if ( typeof(object) == \"undefined\" ) { pretty += \"undefined\" }\n else if ( typeof(object) == \"boolean\" || \n typeof(object) == \"number\" ) { pretty += object.toString() } \n else if ( typeof(object) == \"string\" ) { pretty += \"\\\"\" + object + \"\\\"\" } \n else if ( object == null) { pretty += \"null\" } \n else if ( object instanceof(Array) ) {\n if ( object.length > 0 ) {\n if (embedded) { newline = true }\n var content = \"\"\n for each (var item in object) { content += pp(item, depth+1) + \",\\n\" + spacer(depth+1) }\n content = content.replace(/,\\n\\s*$/, \"\").replace(/^\\s*/,\"\")\n pretty += \"[ \" + content + \"\\n\" + spacer(depth) + \"]\"\n } else { pretty += \"[]\" }\n } \n else if (typeof(object) == \"object\") {\n if ( Object.keys(object).length > 0 ){\n if (embedded) { newline = true }\n var content = \"\"\n for (var key in object) { \n content += spacer(depth + 1) + key.toString() + \": \" + pp(object[key], depth+2, true) + \",\\n\" \n }\n content = content.replace(/,\\n\\s*$/, \"\").replace(/^\\s*/,\"\")\n pretty += \"{ \" + content + \"\\n\" + spacer(depth) + \"}\"\n } else { pretty += \"{}\"}\n }\n else { pretty += object.toString() }\n return ((newline ? \"\\n\" + spacer(depth) : \"\") + pretty)\n}\n js> pp({foo:\"bar\", baz: 1})\n{ foo: \"bar\",\n baz: 1\n}\njs> var taco\njs> pp({foo:\"bar\", baz: [1,\"taco\",{\"blarg\": \"moo\", \"mine\": \"craft\"}, null, taco, {}], bleep: {a:null, b:taco, c: []}})\n{ foo: \"bar\",\n baz: \n [ 1,\n \"taco\",\n { blarg: \"moo\",\n mine: \"craft\"\n },\n null,\n undefined,\n {}\n ],\n bleep: \n { a: null,\n b: undefined,\n c: []\n }\n}\n"
},
{
"answer_id": 7666217,
"author": "Davem M",
"author_id": 636938,
"author_profile": "https://Stackoverflow.com/users/636938",
"pm_score": 4,
"selected": false,
"text": "util.inspect(object, [options]);\n"
},
{
"answer_id": 11607018,
"author": "Dharmanshu Kamra",
"author_id": 1109467,
"author_profile": "https://Stackoverflow.com/users/1109467",
"pm_score": 4,
"selected": false,
"text": "<pre id=\"dump\"></pre>\n<script>\n var dump = JSON.stringify(sampleJsonObject, null, 4); \n $('#dump').html(dump)\n</script>\n"
},
{
"answer_id": 17236125,
"author": "RaphaelDDL",
"author_id": 684932,
"author_profile": "https://Stackoverflow.com/users/684932",
"pm_score": 3,
"selected": false,
"text": "console var tbl = prettyPrint( myObject, { /* options such as maxDepth, etc. */ });\ndocument.body.appendChild(tbl);\n"
},
{
"answer_id": 25574176,
"author": "aliteralmind",
"author_id": 2736496,
"author_profile": "https://Stackoverflow.com/users/2736496",
"pm_score": 0,
"selected": false,
"text": "var s = \"\";\nvar len = array.length;\nvar lenMinus1 = len - 1\nfor (var i = 0; i < len; i++) {\n s += array[i];\n if(i < lenMinus1) {\n s += \", \";\n }\n}\nalert(s);\n"
},
{
"answer_id": 66169644,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "JSON.stringify(data,null,2)\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/130404",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17121/"
] |
130,427
|
<p>Here's the situation. I have a webservice (C# 2.0), which consists of (mainly) a class inheriting from System.Web.Services.WebService. It contains a few methods, which all need to call a method that checks if they're authorized or not.</p>
<p>Basically something like this (pardon the architecture, this is purely as an example): </p>
<pre><code>public class ProductService : WebService
{
public AuthHeader AuthenticationHeader;
[WebMethod(Description="Returns true")]
[SoapHeader("AuthenticationHeader")]
public bool MethodWhichReturnsTrue()
{
if(Validate(AuthenticationHeader))
{
throw new SecurityException("Access Denied");
}
return true;
}
[WebMethod(Description="Returns false")]
[SoapHeader("AuthenticationHeader")]
public bool MethodWhichReturnsFalse()
{
if(Validate(AuthenticationHeader))
{
throw new SecurityException("Access Denied");
}
return false;
}
private bool Validate(AuthHeader authHeader)
{
return authHeader.Username == "gooduser" && authHeader.Password == "goodpassword";
}
}
</code></pre>
<p>As you can see, the method <code>Validate</code> has to be called in each method. I'm looking for a way to be able to call that method, while still being able to access the soap headers in a sane way. I've looked at the events in the <code>global.asax</code>, but I don't think I can access the headers in that class... Can I?</p>
|
[
{
"answer_id": 130690,
"author": "Timothy Lee Russell",
"author_id": 12919,
"author_profile": "https://Stackoverflow.com/users/12919",
"pm_score": 4,
"selected": true,
"text": "public class ServiceAuthHeader : SoapHeader\n{\n public string SiteKey;\n public string Password;\n\n public ServiceAuthHeader() {}\n}\n public class AuthenticationSoapExtensionAttribute : SoapExtensionAttribute\n{\n private int priority;\n\n public AuthenticationSoapExtensionAttribute()\n {\n }\n\n public override Type ExtensionType\n {\n get\n {\n return typeof(AuthenticationSoapExtension);\n }\n }\n\n public override int Priority\n {\n get\n {\n return priority;\n }\n set\n {\n priority = value;\n }\n }\n}\n public class AuthenticationSoapExtension : SoapExtension\n{\n private ServiceAuthHeader authHeader;\n\n public AuthenticationSoapExtension()\n {\n }\n\n public override object GetInitializer(Type serviceType)\n {\n return null;\n }\n\n public override object GetInitializer(LogicalMethodInfo methodInfo, SoapExtensionAttribute attribute)\n {\n return null;\n }\n\n public override void Initialize(object initializer)\n { \n }\n\n public override void ProcessMessage(SoapMessage message)\n {\n if (message.Stage == SoapMessageStage.AfterDeserialize)\n {\n foreach (SoapHeader header in message.Headers)\n {\n if (header is ServiceAuthHeader)\n {\n authHeader = (ServiceAuthHeader)header;\n\n if(authHeader.Password == TheCorrectUserPassword)\n {\n return; //confirmed\n }\n }\n }\n\n throw new SoapException(\"Unauthorized\", SoapException.ClientFaultCode);\n }\n }\n}\n public ServiceAuthHeader AuthenticationSoapHeader;\n\n[WebMethod]\n[SoapHeader(\"AuthenticationSoapHeader\")]\n[AuthenticationSoapExtension]\npublic string GetSomeStuffFromTheCloud(string IdOfWhatYouWant)\n{\n return WhatYouWant;\n}\n private ServiceAuthHeader header;\nprivate PublicService ps;\n\nheader = new ServiceAuthHeader();\nheader.SiteKey = \"Thekey\";\nheader.Password = \"Thepassword\";\nps.ServiceAuthHeaderValue = header;\n\nstring WhatYouWant = ps.GetSomeStuffFromTheCloud(SomeId);\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/130427",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/909/"
] |
130,438
|
<p>Okay. I know this looks like the typical <em>"Why didn't he just Google it or go to <a href="http://www.unicode.org/" rel="noreferrer">www.unicode.org</a> and look it up?"</em> question, but for such a simple question the answer still eludes me after checking both sources.</p>
<p>I am pretty sure that all three of these encoding systems support all of the Unicode characters, but I need to confirm it before I make that claim in a presentation. </p>
<p>Bonus question: Do these encodings differ in the number of characters they can be extended to support?</p>
|
[
{
"answer_id": 280182,
"author": "Artelius",
"author_id": 31945,
"author_profile": "https://Stackoverflow.com/users/31945",
"pm_score": 6,
"selected": false,
"text": "\\ \\n \\xFF \\x \\xF \\xFF strstr()"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/130438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30018/"
] |
130,467
|
<p>How does AOP (<em>Aspect Oriented Programming</em>) work in Drupal?</p>
<p>I have learned about AOP in terms of using it for logging and security, but how does it apply to Drupal?</p>
|
[
{
"answer_id": 11432384,
"author": "J-P",
"author_id": 327153,
"author_profile": "https://Stackoverflow.com/users/327153",
"pm_score": 2,
"selected": false,
"text": "mymodule_init() subscribe mymodule to \"hook events\" of type init\n module_invoke_all('init') notify all subscribers to \"hook events\" of type init that this has occurred\n by passing any relevant arguments to them\n and letting them run the code they define in their hook_init()\n mymodule_init() module_invoke*() mymodule_*()"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/130467",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3208/"
] |
130,486
|
<p>Does a hash shrink in Perl as you delete elements. </p>
<p>More specifically I had a perl program that I inherited that would parse a huge file ( 1 GB ) and load up a hash of hashes. it would do that same for another file and then do a comparison of different elements. The memory consumption was huge during this process and even though I added deleting hash elements has they were used the memory consumption seemed to be unaffected.</p>
<p>The script was extremely slow and such a memory hog. I know it was not well designed but any ideas about the hash memory usage?</p>
|
[
{
"answer_id": 130516,
"author": "Michael Carman",
"author_id": 8233,
"author_profile": "https://Stackoverflow.com/users/8233",
"pm_score": 4,
"selected": true,
"text": "tie"
},
{
"answer_id": 131102,
"author": "Eric Wilhelm",
"author_id": 11580,
"author_profile": "https://Stackoverflow.com/users/11580",
"pm_score": 2,
"selected": false,
"text": "cmp"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/130486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3208/"
] |
130,492
|
<p>I assume there must be a system and language independent way to just stick the "current" EOL character into a text file, but my MSDN-fu seems to be weak today. Bonus points if there is a way to do this in a web application that will put the correct EOL character for the current client's machine's OS, not the web server's.</p>
|
[
{
"answer_id": 130503,
"author": "Adrian Clark",
"author_id": 148,
"author_profile": "https://Stackoverflow.com/users/148",
"pm_score": 1,
"selected": false,
"text": "Environment.NewLine"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/130492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19074/"
] |
130,494
|
<p>I use the commercial version of Jalopy for my Java projects but it doesn't work on Groovy files. IntelliJ has a serviceable formatter but I don't like requiring a particular IDE.</p>
|
[
{
"answer_id": 41039877,
"author": "Gizmomogwai",
"author_id": 204070,
"author_profile": "https://Stackoverflow.com/users/204070",
"pm_score": 2,
"selected": false,
"text": "groovyc JAVA_OPTS -Dantlr.ast groovyc test.groovy"
},
{
"answer_id": 43545532,
"author": "zsoobhan",
"author_id": 2299951,
"author_profile": "https://Stackoverflow.com/users/2299951",
"pm_score": 2,
"selected": false,
"text": "git clone git@github.com:spidasoftware/format.git && \\\ncd format/bin && \\\n./format /path/to/groovy/file\n"
},
{
"answer_id": 47551552,
"author": "Nik Reiman",
"author_id": 14302,
"author_profile": "https://Stackoverflow.com/users/14302",
"pm_score": 1,
"selected": false,
"text": "JAVA_OPTS=-Dantlr.ast:groovy groovyc"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/130494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19113/"
] |
130,496
|
<p>When running an old MFC application in Visual Studio's debugger I've seen a lot of warnings in the Output window like the following:</p>
<blockquote>
<p>Warning: skipping non-radio button in group.</p>
</blockquote>
<p>I understand that in MFC you put radio buttons in groups to indicate which sets of radio buttons go together. If I remember correctly you do this by setting the "group" property of the first radio button to true, and then set the rest of the radio buttons "group" property to false.</p>
<p>I have three questions about this warning.</p>
<ol>
<li><p>How do you get rid of this warning? Do
you have to set the "group" property of all
non-radio button controls to true to
avoid this, or should you just set
it for the first control after the
last radio button?</p></li>
<li><p>Is there an easy way to figure
out what controls or dialogs have this problem?
I could open each dialog and
fiddle with it until the warning
pops up. This application has a lot of
dialogs though, so it would be
nice if there was an easier way.</p></li>
<li><p>What negative behavior can occur if
you don't fix this warning? In other
words, does this even matter?</p></li>
</ol>
|
[
{
"answer_id": 130571,
"author": "ChrisN",
"author_id": 3853,
"author_profile": "https://Stackoverflow.com/users/3853",
"pm_score": 4,
"selected": true,
"text": "WS_GROUP"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/130496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13728/"
] |
130,500
|
<p>We use oracle as the back-end database for our product. I have been running series of stress tests on our system and I have started noticing that oracle is much faster right after the database was restarted. Over time (a couple hours or so) the database seems to get slower and slower and I will see the database machine under more stress.</p>
<p>Running the test right after an oracle restart, i will see a 1 min load average of 5 or so and average CPU around 10-15%. After a few hours, I see the load average at 13 and CPU at 40-70%. (This is red hat linux 2x Quad core xeon, Raid 10 10k rpm sas drives).</p>
<p>My first thought was wouldn't database transactions get faster because those queries are getting cached?</p>
<p>I can't seem to figure out the problem. </p>
<p>EDIT:
Turns out this was a problem on the connecting software side due to bad design. Every action on the system created a new insert, delete, and select. With all these unique queries being generated, what was cached was constantly changing. The spike I am talking about is when the query cache filled up.</p>
|
[
{
"answer_id": 130514,
"author": "dacracot",
"author_id": 13930,
"author_profile": "https://Stackoverflow.com/users/13930",
"pm_score": 0,
"selected": false,
"text": "select\n username,\n osuser,\n lockwait,\n status,\n sql_text\nfrom\n v$session,\n v$sqltext\nwhere\n username is not null\nand\n username not in ('SYSMAN','DBSNMP')\nand\n hash_value = sql_hash_value\norder by\n username,\n hash_value,\n piece;\n"
},
{
"answer_id": 163330,
"author": "crackity_jones",
"author_id": 1474,
"author_profile": "https://Stackoverflow.com/users/1474",
"pm_score": 0,
"selected": false,
"text": "sqlplus <sys or system user>/<password>@<SID>\n SQL> execute dbms_workload_repository.create_snapshot\n SQL> execute dbms_workload_repository.create_snapshot\n SQL> start awrrpt\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/130500",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20134/"
] |
130,506
|
<p>I recently inherited a small Java program that takes information from a large database, does some processing and produces a detailed image regarding the information. The original author wrote the code using a single thread, then later modified it to allow it to use multiple threads. </p>
<p>In the code he defines a constant;</p>
<pre><code>// number of threads
public static final int THREADS = Runtime.getRuntime().availableProcessors();
</code></pre>
<p>Which then sets the number of threads that are used to create the image.</p>
<p>I understand his reasoning that the number of threads cannot be greater than the number of available processors, so set it the the amount to get the full potential out of the processor(s). Is this correct? or is there a better way to utilize the full potential of the processor(s)?</p>
<p>EDIT: To give some more clarification, The specific algorithm that is being threaded scales to the resolution of the picture being created, (1 thread per pixel). That is obviously not the best solution though. The work that this algorithm does is what takes all the time, and is wholly mathematical operations, there are no locks or other factors that will cause any given thread to sleep. I just want to maximize the programs CPU utilization to decrease the time to completion.</p>
|
[
{
"answer_id": 130541,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 2,
"selected": false,
"text": "availableProcessors()"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/130506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7613/"
] |
130,507
|
<p>I'd really like to get into some D3D coding, but I don't have the time lately to learn C++ for what will amount to a hobby project.</p>
|
[
{
"answer_id": 130541,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 2,
"selected": false,
"text": "availableProcessors()"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/130507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16942/"
] |
130,511
|
<p>How can I know what encoding will be used by PHP when sending data to the browser? I.e. with the Cotent-Type header, for instance: iso-8859-1.</p>
|
[
{
"answer_id": 130517,
"author": "William Keller",
"author_id": 17095,
"author_profile": "https://Stackoverflow.com/users/17095",
"pm_score": 0,
"selected": false,
"text": "header('Content-type: xxx/yyy');"
},
{
"answer_id": 130566,
"author": "dirtside",
"author_id": 20903,
"author_profile": "https://Stackoverflow.com/users/20903",
"pm_score": 1,
"selected": false,
"text": "Content-Type: text/html; charset=utf-8\n <?\nheader(\"Content-Type: text/html; charset=utf-8\");\n"
},
{
"answer_id": 3602862,
"author": "Piskvor left the building",
"author_id": 19746,
"author_profile": "https://Stackoverflow.com/users/19746",
"pm_score": 0,
"selected": false,
"text": "Content-Type: text/html iso-8859-2 us-ascii"
},
{
"answer_id": 8757682,
"author": "Marco Demaio",
"author_id": 260080,
"author_profile": "https://Stackoverflow.com/users/260080",
"pm_score": 2,
"selected": true,
"text": "charset charset charset <?php echo ini_get('default_charset'); ?> charset AddDefaultCharset some_charset"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/130511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5295/"
] |
130,526
|
<p>Probably a very stupid question but I can't figure how to rename an object in PowerPoint.. For example, all my Graphs are called by default "Graph 1" etc.
Could someone help me on that?
Thanks!</p>
|
[
{
"answer_id": 130684,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "ActiveWindow.Selection.ShapeRange(1).Name = \"newname\"\n"
},
{
"answer_id": 223880,
"author": "KnomDeGuerre",
"author_id": 24233,
"author_profile": "https://Stackoverflow.com/users/24233",
"pm_score": 2,
"selected": false,
"text": "Dim s As Integer, NewName As String\n\nWith ActiveWindow.Selection.SlideRange\n For s = 1 To .Shapes.Count\n .Shapes(s).Select ' So you can see the object in question\n NewName = InputBox(.Shapes(s).Name) ' Tell what current name it is and ask for new name\n If Len(NewName) > 0 Then .Shapes(s).Name = NewName ' If you typed a new name, apply it\n Next s ' 1 To .Shapes.Count\nEnd With ' ActiveWindow.Selection.SlideRange\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/130526",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
130,547
|
<p>Ok I followed the steps for setting up ruby and rails on my Vista machine and I am having a problem connecting to the database.</p>
<h2>Contents of <code>database.yml</code></h2>
<pre><code>development:
adapter: sqlserver
database: APPS_SETUP
Host: WindowsVT06\SQLEXPRESS
Username: se
Password: paswd
</code></pre>
<p>Run <code>rake db:migrate</code> from myapp directory</p>
<pre><code>----------
rake aborted!
no such file to load -- deprecated
</code></pre>
<h2><strong>ADO</strong></h2>
<p>I have dbi 0.4.0 installed and have created the ADO folder in</p>
<p><code>C:\Ruby\lib\ruby\site_ruby\1.8\DBD\ADO</code></p>
<p>I got the ado.rb from the dbi 0.2.2</p>
<p>What else should I be looking at to fix the issue connecting to the database? Please don't tell me to use MySql or Sqlite or Postgres.</p>
<p>****UPDATE****</p>
<p>I have installed the activerecord-sqlserver-adapter gem from --source=<a href="http://gems.rubyonrails.org" rel="nofollow noreferrer">http://gems.rubyonrails.org</a></p>
<p>Still not working.</p>
<p>I have verified that I can connect to the database by logging into SQL Management Studio with the credentials.</p>
<hr>
<p><strong>rake db:migrate --trace</strong></p>
<hr>
<pre><code>PS C:\Inetpub\wwwroot\myapp> rake db:migrate --trace
(in C:/Inetpub/wwwroot/myapp)
** Invoke db:migrate (first_time)
** Invoke environment (first_time)
** Execute environment
** Execute db:migrate
rake aborted!
no such file to load -- deprecated
C:/Ruby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in `gem_original_require'
C:/Ruby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in `require'
C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:510:in `require'
C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:355:in `new_constants_in'
C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:510:in `require'
C:/Ruby/lib/ruby/site_ruby/1.8/dbi.rb:48
C:/Ruby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in `gem_original_require'
C:/Ruby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in `require'
C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:510:in `require'
C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:355:in `new_constants_in'
C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:510:in `require'
C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/core_ext/kernel/requires.rb:7:in `require_library_
or_gem'
C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/core_ext/kernel/reporting.rb:11:in `silence_warnin
gs'
C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/core_ext/kernel/requires.rb:5:in `require_library_
or_gem'
C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-sqlserver-adapter-1.0.0.9250/lib/active_record/connection_adapters/sqlserver
_adapter.rb:29:in `sqlserver_connection'
C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/connection_adapters/abstract/connection_specificatio
n.rb:292:in `send'
C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/connection_adapters/abstract/connection_specificatio
n.rb:292:in `connection='
C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/connection_adapters/abstract/connection_specificatio
n.rb:260:in `retrieve_connection'
C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/connection_adapters/abstract/connection_specificatio
n.rb:78:in `connection'
C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/migration.rb:408:in `initialize'
C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/migration.rb:373:in `new'
C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/migration.rb:373:in `up'
C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/migration.rb:356:in `migrate'
C:/Ruby/lib/ruby/gems/1.8/gems/rails-2.1.1/lib/tasks/databases.rake:99
C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:621:in `call'
C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:621:in `execute'
C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:616:in `each'
C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:616:in `execute'
C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:582:in `invoke_with_call_chain'
C:/Ruby/lib/ruby/1.8/monitor.rb:242:in `synchronize'
C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:575:in `invoke_with_call_chain'
C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:568:in `invoke'
C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:2031:in `invoke_task'
C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:2009:in `top_level'
C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:2009:in `each'
C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:2009:in `top_level'
C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:2048:in `standard_exception_handling'
C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:2003:in `top_level'
C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:1982:in `run'
C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:2048:in `standard_exception_handling'
C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:1979:in `run'
C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/bin/rake:31
C:/Ruby/bin/rake:19:in `load'
C:/Ruby/bin/rake:19
PS C:\Inetpub\wwwroot\myapp>
</code></pre>
|
[
{
"answer_id": 131501,
"author": "hectorsq",
"author_id": 14755,
"author_profile": "https://Stackoverflow.com/users/14755",
"pm_score": 2,
"selected": false,
"text": "gem install activerecord-sqlserver-adapter --source=http://gems.rubyonrails.org\n"
},
{
"answer_id": 1268226,
"author": "Amol",
"author_id": 189654,
"author_profile": "https://Stackoverflow.com/users/189654",
"pm_score": 0,
"selected": false,
"text": "adapter: sqlserver\nmode: odbc\ndsn: DSN_NAME\nhost: localhost\ndatabase: App_development\nusername: uname\npassword: password\n"
},
{
"answer_id": 1981774,
"author": "John Naegle",
"author_id": 29680,
"author_profile": "https://Stackoverflow.com/users/29680",
"pm_score": 2,
"selected": false,
"text": "gem.bat install activerecord-sqlserver-adapter\n Successfully installed deprecated-2.0.1\n Successfully installed dbi-0.4.1\n Successfully installed dbd-odbc-0.2.4\n Successfully installed activerecord-sqlserver-adapter-2.2.22\n 4 gems installed\n development:\n adapter: sqlserver\n mode: odbc\n dsn: rails_development\n username: sa\n password: 12345\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/130547",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/453046/"
] |
130,564
|
<p>I am writing a page where I need an HTML table to maintain a set size. I need the headers at the top of the table to stay there at all times but I also need the body of the table to scroll no matter how many rows are added to the table. Think a mini version of excel. This seems like a simple task but almost every solution I have found on the web has some drawback. How can I solve this?</p>
|
[
{
"answer_id": 130568,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 3,
"selected": false,
"text": "<html>\n <head>\n <title>Blah</title>\n <style type=\"text/css\">\n table { width:300px; }\n tbody { height:10em; overflow:scroll;}\n td { height:auto; }\n </style>\n </head>\n <body>\n <table>\n <thead>\n <tr>\n <th>One</th><th>Two</th>\n </td>\n </tr>\n </thead>\n <tbody>\n <tr><td>Data</td><td>Data</td></tr>\n <tr><td>Data</td><td>Data</td></tr>\n <tr><td>Data</td><td>Data</td></tr>\n <tr><td>Data</td><td>Data</td></tr>\n <tr><td>Data</td><td>Data</td></tr>\n <tr><td>Data</td><td>Data</td></tr>\n <tr><td>Data</td><td>Data</td></tr>\n <tr><td>Data</td><td>Data</td></tr>\n <tr><td>Data</td><td>Data</td></tr>\n <tr><td>Data</td><td>Data</td></tr>\n <tr><td>Data</td><td>Data</td></tr>\n <tr><td>Data</td><td>Data</td></tr>\n <tr><td>Data</td><td>Data</td></tr>\n <tr><td>Data</td><td>Data</td></tr>\n <tr><td>Data</td><td>Data</td></tr>\n </tbody>\n </table>\n </body>\n</html>\n"
},
{
"answer_id": 130598,
"author": "Luke Bennett",
"author_id": 17602,
"author_profile": "https://Stackoverflow.com/users/17602",
"pm_score": 2,
"selected": false,
"text": "tbody table-layout: fixed"
},
{
"answer_id": 4786251,
"author": "Daniel Costa",
"author_id": 577842,
"author_profile": "https://Stackoverflow.com/users/577842",
"pm_score": 2,
"selected": false,
"text": "<html>\n<head>\n <title>Test</title>\n <style type=\"text/css\">\n table{\n width: 400px;\n }\n tbody {\n height: 100px;\n overflow: scroll;\n }\n div {\n height: 100px;\n width: 400px;\n position: relative;\n }\n tr.alt td {\n background-color: #EEEEEE;\n }\n </style>\n <!--[if IE]>\n <style type=\"text/css\">\n div {\n overflow-y: scroll;\n overflow-x: hidden;\n }\n thead tr {\n position: absolute;\n top: expression(this.offsetParent.scrollTop);\n }\n tbody {\n height: auto;\n }\n </style>\n <![endif]--> \n</head>\n<body>\n <div >\n <table border=\"0\" cellspacing=\"0\" cellpadding=\"0\">\n <thead>\n <tr>\n <th style=\"background: lightgreen;\">user</th>\n <th style=\"background: lightgreen;\">email</th>\n <th style=\"background: lightgreen;\">id</th>\n <th style=\"background: lightgreen;\">Y/N</th>\n </tr>\n </thead>\n <tbody align=\"center\">\n <!--[if IE]>\n <tr>\n <td colspan=\"4\">on IE it's overridden by the header</td>\n </tr>\n <![endif]--> \n <tr>\n <td>user 1</td>\n <td>user@user.com</td>\n <td>1</td>\n <td>Y</td>\n </tr>\n <tr class=\"alt\">\n <td>user 2</td>\n <td>user@user.com</td>\n <td>2</td>\n <td>N</td>\n </tr>\n <tr>\n <td>user 3</td>\n <td>user@user.com</td>\n <td>3</td>\n <td>Y</td>\n </tr>\n <tr class=\"alt\">\n <td>user 4</td>\n <td>user@user.com</td>\n <td>4</td>\n <td>N</td>\n </tr>\n <tr>\n <td>user 5</td>\n <td>user@user.com</td>\n <td>5</td>\n <td>Y</td>\n </tr>\n <tr class=\"alt\">\n <td>user 6</td>\n <td>user@user.com</td>\n <td>6</td>\n <td>N</td>\n </tr>\n <tr>\n <td>user 7</td>\n <td>user@user.com</td>\n <td>7</td>\n <td>Y</td>\n </tr>\n <tr class=\"alt\">\n <td>user 8</td>\n <td>user@user.com</td>\n <td>8</td>\n <td>N</td>\n </tr>\n </tbody>\n </table>\n </div>\n</body></html>\n"
},
{
"answer_id": 5727026,
"author": "Peter",
"author_id": 58553,
"author_profile": "https://Stackoverflow.com/users/58553",
"pm_score": 0,
"selected": false,
"text": "//Usage add Scrollify class to a table where all columns (header and body) have a fixed pixel width\n$(document).ready(function () {\n $(\"table.Scrollify\").each(function (index, element) {\n var header = $(element).children().children().first();\n var headerHtml = header.html();\n var width = $(element).outerWidth();\n var height = parseInt($(element).css(\"height\")) - header.outerHeight();\n $(element).height(\"auto\");\n header.remove();\n var html = \"<table style=\\\"border-collapse: collapse;\\\" border=\\\"1\\\" rules=\\\"all\\\" cellspacing=\\\"0\\\"><tr>\" + headerHtml +\n \"</tr></table><div style=\\\"overflow: auto;border:0;margin:0;padding:0;height:\" + height + \"px;width:\" + (parseInt(width) + scrollbarWidth()) + \"px;\\\">\" +\n $(element).parent().html() + \"</div>\";\n\n $(element).parent().html(html);\n });\n});\n\n\n//Function source: http://www.fleegix.org/articles/2006-05-30-getting-the-scrollbar-width-in-pixels\n//License: Apache License, version 2\nfunction scrollbarWidth() {\n var scr = null;\n var inn = null;\n var wNoScroll = 0;\n var wScroll = 0;\n\n // Outer scrolling div\n scr = document.createElement('div');\n scr.style.position = 'absolute';\n scr.style.top = '-1000px';\n scr.style.left = '-1000px';\n scr.style.width = '100px';\n scr.style.height = '50px';\n // Start with no scrollbar\n scr.style.overflow = 'hidden';\n\n // Inner content div\n inn = document.createElement('div');\n inn.style.width = '100%';\n inn.style.height = '200px';\n\n // Put the inner div in the scrolling div\n scr.appendChild(inn);\n // Append the scrolling div to the doc\n document.body.appendChild(scr);\n\n // Width of the inner div sans scrollbar\n wNoScroll = inn.offsetWidth;\n // Add the scrollbar\n scr.style.overflow = 'auto';\n // Width of the inner div width scrollbar\n wScroll = inn.offsetWidth;\n\n // Remove the scrolling div from the doc\n document.body.removeChild(\n document.body.lastChild);\n\n // Pixel width of the scroller\n return (wNoScroll - wScroll);\n}\n"
},
{
"answer_id": 10451681,
"author": "oHo",
"author_id": 938111,
"author_profile": "https://Stackoverflow.com/users/938111",
"pm_score": 2,
"selected": false,
"text": "thead tfoot thead tfoot tbody <style type=\"text/css\">\ntable {\n border-spacing: 0; /* workaround */\n}\ntbody {\n height: 4em; /* define the height */\n overflow-x: hidden; /* esthetics */\n overflow-y: auto; /* allow scrolling cells */\n}\ntd {\n border-left: 1px solid blue; /* workaround */\n border-bottom: 1px solid blue; /* workaround */\n}\n</style>\n\n<table>\n <thead><tr><th>Header\n <tfoot><tr><th>Footer\n <tbody>\n <tr><td>Cell 1 <tr><td>Cell 2\n <tr><td>Cell 3 <tr><td>Cell 4\n <tr><td>Cell 5 <tr><td>Cell 6\n <tr><td>Cell 7 <tr><td>Cell 8\n <tr><td>Cell 9 <tr><td>Cell 10\n <tr><td>Cell 11 <tr><td>Cell 12\n <tr><td>Cell 13 <tr><td>Cell 14\n </tbody>\n</table>\n"
},
{
"answer_id": 12846587,
"author": "Jeromy French",
"author_id": 1430996,
"author_profile": "https://Stackoverflow.com/users/1430996",
"pm_score": 4,
"selected": false,
"text": "aria-hidden=\"false\""
},
{
"answer_id": 16593762,
"author": "Deborah",
"author_id": 1224692,
"author_profile": "https://Stackoverflow.com/users/1224692",
"pm_score": 0,
"selected": false,
"text": "// get table width and match the mask width\n\nfunction setMaskWidth() { \n if (document.getElementById('mask') !==null) {\n var tableWidth = document.getElementById('theTable').offsetWidth;\n\n // match elements to the table width\n document.getElementById('mask').style.width = tableWidth + \"px\";\n }\n}\n\nfunction fixTop() {\n\n // get height of page content \n function getScrollY() {\n var y = 0;\n if( typeof ( window.pageYOffset ) == 'number' ) {\n y = window.pageYOffset;\n } else if ( document.body && ( document.body.scrollTop) ) {\n y = document.body.scrollTop;\n } else if ( document.documentElement && ( document.documentElement.scrollTop) ) {\n y = document.documentElement.scrollTop;\n }\n return [y];\n } \n\n var y = getScrollY();\n var y = y[0];\n\n if (document.getElementById('mask') !==null) {\n document.getElementById('mask').style.height = y + \"px\" ;\n\n if (document.all && document.querySelector && !document.addEventListener) {\n document.styleSheets[1].rules[0].style.top = y + \"px\" ;\n } else {\n document.styleSheets[1].cssRules[0].style.top = y + \"px\" ;\n }\n }\n\n}\n\nwindow.onscroll = function() {\n setMaskWidth();\n fixTop();\n}\n"
},
{
"answer_id": 23594455,
"author": "Jérôme Beau",
"author_id": 650104,
"author_profile": "https://Stackoverflow.com/users/650104",
"pm_score": 3,
"selected": false,
"text": "tbody block block tbody block table table table thead { \n display: table; \n width: 100%; // Fill the containing table\n}\ntbody tr {\n display: table;\n width: 100%; // Fill the containing table\n}\n thead tbody th, td { width: 20%; } fixed thead {\n table-layout: fixed; // Same layout for all cells\n}\ntbody tr {\n table-layout: fixed; // Same layout for all cells\n}\nth, td {\n width: auto; // Same width for all cells, if table has fixed layout\n} \n"
},
{
"answer_id": 25654160,
"author": "Fernando Fabreti",
"author_id": 873650,
"author_profile": "https://Stackoverflow.com/users/873650",
"pm_score": 2,
"selected": false,
"text": " table {\n overflow: scroll;\n display: block; /*inline-block*/\n height: 120px;\n }\n thead > tr {\n position: absolute;\n display: block;\n padding: 0;\n margin: 0;\n top: 0;\n background-color: gray;\n }\n tbody > tr:nth-of-type(1) {\n margin-top: 16px;\n }\n tbody tr {\n display: block;\n }\n\n td, th {\n width: 70px;\n border-style:solid;\n border-width:1px;\n border-color:black;\n }\n"
},
{
"answer_id": 38107743,
"author": "Md Rafee",
"author_id": 5998241,
"author_profile": "https://Stackoverflow.com/users/5998241",
"pm_score": 1,
"selected": false,
"text": "table.scrollTable {\n border: 1px solid #963;\n width: 718px;\n}\n\nthead.fixedHeader {\n display: block;\n}\n\nthead.fixedHeader tr {\n height: 30px;\n background: #c96;\n}\n\nthead.fixedHeader tr th {\n border-right: 1px solid black;\n}\n\ntbody.scrollContent {\n display: block;\n height: 262px;\n overflow: auto;\n}\n\ntbody.scrollContent td {\n background: #eee;\n border-right: 1px solid black;\n height: 25px;\n}\n\ntbody.scrollContent tr.alternateRow td {\n background: #fff;\n}\n\nthead.fixedHeader th {\n width: 233px;\n}\n\nthead.fixedHeader th:last-child {\n width: 251px;\n}\n\ntbody.scrollContent td {\n width: 233px;\n} <table cellspacing=\"0\" cellpadding=\"0\" class=\"scrollTable\">\n <thead class=\"fixedHeader\">\n <tr class=\"alternateRow\">\n <th>Header 1</th>\n <th>Header 2</th>\n <th>Header 3</th>\n </tr>\n </thead>\n <tbody class=\"scrollContent\">\n <tr class=\"normalRow\">\n <td>Cell Content 1</td>\n <td>Cell Content 2</td>\n <td>Cell Content 3</td>\n </tr>\n <tr class=\"alternateRow\">\n <td>More Cell Content 1</td>\n <td>More Cell Content 2</td>\n <td>More Cell Content 3</td>\n </tr>\n <tr class=\"normalRow\">\n <td>Even More Cell Content 1</td>\n <td>Even More Cell Content 2</td>\n <td>Even More Cell Content 3</td>\n </tr>\n <tr class=\"alternateRow\">\n <td>And Repeat 1</td>\n <td>And Repeat 2</td>\n <td>And Repeat 3</td>\n </tr>\n <tr class=\"normalRow\">\n <td>Cell Content 1</td>\n <td>Cell Content 2</td>\n <td>Cell Content 3</td>\n </tr>\n <tr class=\"alternateRow\">\n <td>More Cell Content 1</td>\n <td>More Cell Content 2</td>\n <td>More Cell Content 3</td>\n </tr>\n <tr class=\"normalRow\">\n <td>Even More Cell Content 1</td>\n <td>Even More Cell Content 2</td>\n <td>Even More Cell Content 3</td>\n </tr>\n <tr class=\"alternateRow\">\n <td>And Repeat 1</td>\n <td>And Repeat 2</td>\n <td>And Repeat 3</td>\n </tr>\n <tr class=\"normalRow\">\n <td>Cell Content 1</td>\n <td>Cell Content 2</td>\n <td>Cell Content 3</td>\n </tr>\n <tr class=\"alternateRow\">\n <td>More Cell Content 1</td>\n <td>More Cell Content 2</td>\n <td>More Cell Content 3</td>\n </tr>\n <tr class=\"normalRow\">\n <td>Even More Cell Content 1</td>\n <td>Even More Cell Content 2</td>\n <td>Even More Cell Content 3</td>\n </tr>\n <tr class=\"alternateRow\">\n <td>And Repeat 1</td>\n <td>And Repeat 2</td>\n <td>And Repeat 3</td>\n </tr>\n <tr class=\"normalRow\">\n <td>Cell Content 1</td>\n <td>Cell Content 2</td>\n <td>Cell Content 3</td>\n </tr>\n <tr class=\"alternateRow\">\n <td>More Cell Content 1</td>\n <td>More Cell Content 2</td>\n <td>More Cell Content 3</td>\n </tr>\n <tr class=\"normalRow\">\n <td>Even More Cell Content 1</td>\n <td>Even More Cell Content 2</td>\n <td>Even More Cell Content 3</td>\n </tr>\n <tr class=\"alternateRow\">\n <td>And Repeat 1</td>\n <td>And Repeat 2</td>\n <td>And Repeat 3</td>\n </tr>\n <tr class=\"normalRow\">\n <td>Cell Content 1</td>\n <td>Cell Content 2</td>\n <td>Cell Content 3</td>\n </tr>\n <tr class=\"alternateRow\">\n <td>More Cell Content 1</td>\n <td>More Cell Content 2</td>\n <td>More Cell Content 3</td>\n </tr>\n <tr class=\"normalRow\">\n <td>Even More Cell Content 1</td>\n <td>Even More Cell Content 2</td>\n <td>Even More Cell Content 3</td>\n </tr>\n <tr class=\"alternateRow\">\n <td>And Repeat 1</td>\n <td>And Repeat 2</td>\n <td>And Repeat 3</td>\n </tr>\n <tr class=\"normalRow\">\n <td>Cell Content 1</td>\n <td>Cell Content 2</td>\n <td>Cell Content 3</td>\n </tr>\n <tr class=\"alternateRow\">\n <td>More Cell Content 1</td>\n <td>More Cell Content 2</td>\n <td>More Cell Content 3</td>\n </tr>\n <tr class=\"normalRow\">\n <td>Even More Cell Content 1</td>\n <td>Even More Cell Content 2</td>\n <td>Even More Cell Content 3</td>\n </tr>\n <tr class=\"alternateRow\">\n <td>And Repeat 1</td>\n <td>And Repeat 2</td>\n <td>And Repeat 3</td>\n </tr>\n <tr class=\"normalRow\">\n <td>Cell Content 1</td>\n <td>Cell Content 2</td>\n <td>Cell Content 3</td>\n </tr>\n <tr class=\"alternateRow\">\n <td>More Cell Content 1</td>\n <td>More Cell Content 2</td>\n <td>More Cell Content 3</td>\n </tr>\n <tr class=\"normalRow\">\n <td>Even More Cell Content 1</td>\n <td>Even More Cell Content 2</td>\n <td>Even More Cell Content 3</td>\n </tr>\n <tr class=\"alternateRow\">\n <td>And Repeat 1</td>\n <td>And Repeat 2</td>\n <td>And Repeat 3</td>\n </tr>\n <tr class=\"normalRow\">\n <td>Cell Content 1</td>\n <td>Cell Content 2</td>\n <td>Cell Content 3</td>\n </tr>\n <tr class=\"alternateRow\">\n <td>More Cell Content 1</td>\n <td>More Cell Content 2</td>\n <td>More Cell Content 3</td>\n </tr>\n <tr class=\"normalRow\">\n <td>Even More Cell Content 1</td>\n <td>Even More Cell Content 2</td>\n <td>Even More Cell Content 3</td>\n </tr>\n <tr class=\"alternateRow\">\n <td>And Repeat 1</td>\n <td>And Repeat 2</td>\n <td>And Repeat 3</td>\n </tr>\n <tr class=\"normalRow\">\n <td>Cell Content 1</td>\n <td>Cell Content 2</td>\n <td>Cell Content 3</td>\n </tr>\n <tr class=\"alternateRow\">\n <td>More Cell Content 1</td>\n <td>More Cell Content 2</td>\n <td>More Cell Content 3</td>\n </tr>\n <tr class=\"normalRow\">\n <td>Even More Cell Content 1</td>\n <td>Even More Cell Content 2</td>\n <td>Even More Cell Content 3</td>\n </tr>\n <tr class=\"alternateRow\">\n <td>And Repeat 1</td>\n <td>And Repeat 2</td>\n <td>And Repeat 3</td>\n </tr>\n <tr class=\"normalRow\">\n <td>Cell Content 1</td>\n <td>Cell Content 2</td>\n <td>Cell Content 3</td>\n </tr>\n <tr class=\"alternateRow\">\n <td>More Cell Content 1</td>\n <td>More Cell Content 2</td>\n <td>More Cell Content 3</td>\n </tr>\n <tr class=\"normalRow\">\n <td>Even More Cell Content 1</td>\n <td>Even More Cell Content 2</td>\n <td>Even More Cell Content 3</td>\n </tr>\n <tr class=\"alternateRow\">\n <td>And Repeat 1</td>\n <td>And Repeat 2</td>\n <td>And Repeat 3</td>\n </tr>\n <tr class=\"normalRow\">\n <td>Cell Content 1</td>\n <td>Cell Content 2</td>\n <td>Cell Content 3</td>\n </tr>\n <tr class=\"alternateRow\">\n <td>More Cell Content 1</td>\n <td>More Cell Content 2</td>\n <td>More Cell Content 3</td>\n </tr>\n <tr class=\"normalRow\">\n <td>Even More Cell Content 1</td>\n <td>Even More Cell Content 2</td>\n <td>Even More Cell Content 3</td>\n </tr>\n <tr class=\"alternateRow\">\n <td>End of Cell Content 1</td>\n <td>End of Cell Content 2</td>\n <td>End of Cell Content 3</td>\n </tr>\n </tbody>\n</table>"
},
{
"answer_id": 38591386,
"author": "matthewpark319",
"author_id": 5148439,
"author_profile": "https://Stackoverflow.com/users/5148439",
"pm_score": 0,
"selected": false,
"text": ".table-fill {\n background: white;\n border-radius:3px;\n border-collapse: collapse;\n margin: auto;\n width: 100%;\n max-width: 800px;\n padding:5px;\n box-shadow: 0 5px 10px rgba(0, 0, 0, 0.1);\n animation: float 5s infinite;\n}\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/130564",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4491/"
] |
130,570
|
<p>We have recently moved back to InstallShield 2008 from rolling our own install. So, I am still trying to get up the learning curve on it. </p>
<p>We are using Firebird and a usb driver, that we couldn't find good msi install solutions. So, we have a cmd line to install firebird silently and the usb driver mostly silently.</p>
<p>We have put this code into the event handler DefaultFeatureInstalled. This works really well on the first time install. But, when I do an uninstall it trys to launch the firebird installer again, so it must be sending the DefaultFeatureInstalled event again.</p>
<p>Is their another event to use, or is there a way to detect whether its an install or uninstall in the DefaultFeatureInstalled event?</p>
|
[
{
"answer_id": 144881,
"author": "Chris Tybur",
"author_id": 741,
"author_profile": "https://Stackoverflow.com/users/741",
"pm_score": 0,
"selected": false,
"text": "string sRemove;\nnumber nBuffer;\n\nnBuffer = 256;\nif (MsiGetProperty(ISMSI_HANDLE, \"REMOVE\", sRemove, nBuffer) = ERROR_SUCCESS) then\n //do something\nendif;\n"
},
{
"answer_id": 153638,
"author": "Ray Jenkins",
"author_id": 12425,
"author_profile": "https://Stackoverflow.com/users/12425",
"pm_score": 1,
"selected": false,
"text": "string sRemove;\nnumber nBuffer;\n\nnBuffer = 256;\nif (MsiGetProperty(ISMSI_HANDLE, \"REMOVE\", sRemove, nBuffer) = ERROR_SUCCESS) then\n //do something\nendif;\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/130570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12425/"
] |
130,573
|
<p>The <a href="http://msdn.microsoft.com/en-us/library/ms724284(VS.85).aspx" rel="nofollow noreferrer"><code>FILETIME</code> structure</a> counts from January 1 1601 (presumably the start of that day) according to the Microsoft documentation, but does this include leap seconds?</p>
|
[
{
"answer_id": 3603011,
"author": "Ian Boyd",
"author_id": 12597,
"author_profile": "https://Stackoverflow.com/users/12597",
"pm_score": 5,
"selected": true,
"text": "FILETIME FILETIME FileTimeToSystemTime FileTimeToSystemTime 0..59 FILETIME var\n systemTime: TSystemTime;\n fileTime: TFileTime;\nbegin\n //Construct a system-time for the 12/31/2008 11:59:59 pm\n ZeroMemory(@systemTime, SizeOf(systemTime));\n systemtime.wYear := 2008;\n systemTime.wMonth := 12;\n systemTime.wDay := 31;\n systemTime.wHour := 23;\n systemtime.wMinute := 59;\n systemtime.wSecond := 59;\n\n //Convert it to a file time\n SystemTimeToFileTime(systemTime, {var}fileTime);\n\n //There was a leap second 12/31/2008 11:59:60 pm\n //Add one second to our filetime to reach the leap second\n filetime.dwLowDateTime := fileTime.dwLowDateTime+10000000; //10,000,000 * 100ns = 1s\n\n //Convert the filetime, sitting on a leap second, to a displayable system time\n FileTimeToSystemTime(fileTime, {var}systemTime);\n\n //And now print the system time\n ShowMessage(DateTimeToStr(SystemTimeToDateTime(systemTime)));\n 12/31/2008 11:59:59pm\n 1/1/2009 12:00:00am\n 1/1/2009 11:59:60pm\n"
},
{
"answer_id": 53015905,
"author": "Matt Johnson-Pint",
"author_id": 634824,
"author_profile": "https://Stackoverflow.com/users/634824",
"pm_score": 2,
"selected": false,
"text": "FILETIME FILETIME SYSTEMTIME FILETIME HKLM:\\SYSTEM\\CurrentControlSet\\Control\\LeapSecondInformation 0 1"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/130573",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10168/"
] |
130,574
|
<p>I seek an algorithm that will let me represent an incoming sequence of bits as letters ('a' .. 'z' ), in a minimal matter such that the stream of bits can be regenerated from the letters, without ever holding the entire sequence in memory.</p>
<p>That is, given an external bit source (each read returns a practically random bit), and user input of a number of bits, I would like to print out the minimal number of characters that can represent those bits.</p>
<p>Ideally there should be a parameterization - how much memory versus maximum bits before some waste is necessary.</p>
<p>Efficiency Goal - The same number of characters as the base-26 representation of the bits. </p>
<p>Non-solutions: </p>
<ol>
<li><p>If sufficient storage was present, store the entire sequence and use a big-integer MOD 26 operation. </p></li>
<li><p>Convert every 9 bits to 2 characters - This seems suboptimal, wasting 25% of information capacity of the letters output.</p></li>
</ol>
|
[
{
"answer_id": 130670,
"author": "Commodore Jaeger",
"author_id": 4659,
"author_profile": "https://Stackoverflow.com/users/4659",
"pm_score": 3,
"selected": false,
"text": "a 0000\nb 0001\nc 0010\nd 0011\ne 0100\nf 0101\ng 01100\nh 01101\ni 01110\nj 01111\nk 10000\nl 10001\nm 10010\nn 10011\no 10100\np 10101\nq 10110\nr 10111\ns 11000\nt 11001\nu 11010\nv 11011\nw 11100\nx 11101\ny 11110\nz 11111\n"
},
{
"answer_id": 130678,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 3,
"selected": false,
"text": "1 1"
},
{
"answer_id": 131648,
"author": "David Nehme",
"author_id": 14167,
"author_profile": "https://Stackoverflow.com/users/14167",
"pm_score": 2,
"selected": false,
"text": "number of letters number of bits bits/letter\n 1 4 4\n 2 9 4.5\n 3 14 4.67\n 4 18 4.5\n 5 23 4.6\n 6 28 4.67\n 7 32 4.57\n 8 37 4.63\n 9 42 4.67\n10 47 4.7\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/130574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
130,604
|
<p>I use int.MaxValue as a penalty and sometimes I am computing the penalties together. Is there a function or how would you create one with the most grace and efficiency that does that. </p>
<p>ie. </p>
<p>50 + 100 = 150</p>
<p>int.Max + 50 = int.Max and not int.Min + 50 </p>
|
[
{
"answer_id": 130660,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 3,
"selected": true,
"text": "int penaltySum(int a, int b)\n{\n return (int.MaxValue - a < b) ? int.MaxValue : a + b;\n}\n int penaltySum(int a, int b)\n{\n if (a > 0 && b > 0)\n {\n return (int.MaxValue - a < b) ? int.MaxValue : a + b;\n }\n\n if (a < 0 && b < 0)\n {\n return (int.MinValue - a > b) ? int.MinValue : a + b;\n }\n\n return a + b;\n}\n"
},
{
"answer_id": 130856,
"author": "Ben Griswold",
"author_id": 4115,
"author_profile": "https://Stackoverflow.com/users/4115",
"pm_score": 3,
"selected": false,
"text": "int penaltySum(int a, int b)\n{\n return (int.MaxValue - a < b) ? int.MaxValue : a + b;\n}\n [TestMethod]\npublic void PenaltySumTest()\n{\n int x = -200000; \n int y = 200000; \n int z = 0;\n\n Assert.AreEqual(z, penaltySum(x, y));\n}\n private int penaltySum(int x, int y, int max)\n{\n long result = (long) x + y;\n return result > max ? max : (int) result;\n}\n private int penaltySum(int x, int y, int max)\n{\n int result = int.MaxValue;\n\n checked\n {\n try\n {\n result = x + y;\n }\n catch\n {\n // Arithmetic operation resulted in an overflow.\n }\n }\n\n return result;\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/130604",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4694/"
] |
130,605
|
<p>I have a table of Users that includes a bitmask of roles that the user belongs to. I'd like to select users that belong to one or more of the roles in a bitmask value. For example:</p>
<pre>select *
from [User]
where UserRolesBitmask | 22 = 22</pre>
<p>This selects all users that have the roles '2', '4' or '16' in their bitmask. Is this possible to express this in a LINQ query? Thanks.</p>
|
[
{
"answer_id": 130691,
"author": "KevDog",
"author_id": 13139,
"author_profile": "https://Stackoverflow.com/users/13139",
"pm_score": 4,
"selected": true,
"text": "from u in DataContext.Users\nwhere UserRolesBitmask | 22 == 22\nselect u\n"
},
{
"answer_id": 130716,
"author": "Corin Blaikie",
"author_id": 1736,
"author_profile": "https://Stackoverflow.com/users/1736",
"pm_score": 0,
"selected": false,
"text": "ExecuteCommand DataContext.ExecuteCommand(\"select * from [User] where UserRolesBitmask | {0} = {0}\", 22);\n"
},
{
"answer_id": 1318415,
"author": "Eric",
"author_id": 47350,
"author_profile": "https://Stackoverflow.com/users/47350",
"pm_score": 4,
"selected": false,
"text": "UserRolesBitmask | 22 == 22 1==1 UserRolesBitmask & 22 == 22 UserRolesBitmask & 22 != 0"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/130605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14072/"
] |
130,614
|
<p>I've got a dictionary, something like</p>
<pre><code>Dictionary<Foo,String> fooDict
</code></pre>
<p>I step through everything in the dictionary, e.g.</p>
<pre><code>foreach (Foo foo in fooDict.Keys)
MessageBox.show(fooDict[foo]);
</code></pre>
<p>It does that in the order the foos were added to the dictionary, so the first item added is the first foo returned.</p>
<p>How can I change the cardinality so that, for example, the third foo added will be the second foo returned? In other words, I want to change its "index."</p>
|
[
{
"answer_id": 130816,
"author": "Asmor",
"author_id": 18210,
"author_profile": "https://Stackoverflow.com/users/18210",
"pm_score": 0,
"selected": false,
"text": " public void sortSections()\n {\n //OMG THIS IS UGLY!!!\n KeyValuePair<ListViewItem, TextSection>[] sortable = textSecs.ToArray();\n IOrderedEnumerable<KeyValuePair<ListViewItem, TextSection>> sorted = sortable.OrderBy(kvp => kvp.Value.cardinality);\n\n foreach (KeyValuePair<ListViewItem, TextSection> kvp in sorted)\n {\n TextSection sec = kvp.Value;\n ListViewItem key = kvp.Key;\n\n textSecs.Remove(key);\n textSecs.Add(key, sec);\n }\n }\n"
},
{
"answer_id": 130841,
"author": "Michael Lang",
"author_id": 19452,
"author_profile": "https://Stackoverflow.com/users/19452",
"pm_score": 0,
"selected": false,
"text": "public class IndexableDictionary<T1, T2> : Dictionary<T1, T2>\n{\n private SortedDictionary<int, T1> _sortedKeys;\n\n public IndexableDictionary()\n {\n _sortedKeys = new SortedDictionary<int, T1>();\n }\n public new void Add(T1 key, T2 value)\n {\n _sortedKeys.Add(_sortedKeys.Count + 1, key);\n base.Add(key, value);\n }\n\n private IEnumerable<KeyValuePair<T1, T2>> Enumerable()\n {\n foreach (T1 key in _sortedKeys.Values)\n {\n yield return new KeyValuePair<T1, T2>(key, this[key]);\n }\n }\n\n public new IEnumerator<KeyValuePair<T1, T2>> GetEnumerator()\n {\n return Enumerable().GetEnumerator();\n }\n\n public KeyValuePair<T1, T2> this[int index]\n {\n get\n {\n return new KeyValuePair<T1, T2> (_sortedKeys[index], base[_sortedKeys[index]]);\n }\n set\n {\n _sortedKeys[index] = value.Key;\n base[value.Key] = value.Value;\n }\n\n }\n\n\n}\n static void Main(string[] args)\n {\n IndexableDictionary<string, string> fooDict = new IndexableDictionary<string, string>();\n\n fooDict.Add(\"One\", \"One\");\n fooDict.Add(\"Two\", \"Two\");\n fooDict.Add(\"Three\", \"Three\");\n\n // Print One, Two, Three\n foreach (KeyValuePair<string, string> kvp in fooDict)\n Console.WriteLine(kvp.Value);\n\n\n\n KeyValuePair<string, string> temp = fooDict[1];\n fooDict[1] = fooDict[2];\n fooDict[2] = temp;\n\n\n // Print Two, One, Three\n foreach (KeyValuePair<string, string> kvp in fooDict)\n Console.WriteLine(kvp.Value);\n\n Console.ReadLine();\n }\n"
},
{
"answer_id": 130911,
"author": "Eric Schoonover",
"author_id": 3957,
"author_profile": "https://Stackoverflow.com/users/3957",
"pm_score": 3,
"selected": false,
"text": "OrderedDicationary System.Collections.Specialized"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/130614",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18210/"
] |
130,616
|
<p>I'm trying to start a service as a user and things work fine, until I try a user that doesn't have a password. Then, it fails to start (due to log-on error).</p>
<p>Am I doing something wrong or is this "by design"?</p>
<p>The code to register this service:</p>
<pre><code> SC_HANDLE schService = CreateService(
schSCManager,
strNameNoSpaces,
strServiceName,
SERVICE_ALL_ACCESS,
SERVICE_WIN32_OWN_PROCESS,
SERVICE_AUTO_START,
SERVICE_ERROR_NORMAL,
szPath,
NULL,
NULL,
NULL,
strUser,
(strPassword.IsEmpty())?NULL:strPassword);
</code></pre>
|
[
{
"answer_id": 130658,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 0,
"selected": false,
"text": "strPassword SC_HANDLE schService = CreateService( \n schSCManager, \n strNameNoSpaces, \n strServiceName, \n SERVICE_ALL_ACCESS, \n SERVICE_WIN32_OWN_PROCESS, \n SERVICE_AUTO_START, \n SERVICE_ERROR_NORMAL, \n szPath, \n NULL, \n NULL, \n NULL, \n strUser,\n\n// change this line to:\n strPassword.IsEmpty() ? L\"\" : strPassword);\n// or maybe\n strPassword);\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/130616",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20208/"
] |
130,617
|
<p>I got a program that writes some data to a file using a method like the one below.</p>
<pre><code>
public void ExportToFile(string filename)
{
using(FileStream fstream = new FileStream(filename,FileMode.Create))
using (TextWriter writer = new StreamWriter(fstream))
{
// try catch block for write permissions
writer.WriteLine(text);
}
}
</code></pre>
<p>When running the program I get an error:</p>
<blockquote>
<p>Unhandled Exception: System.UnauthorizedAccessException: Access to the path 'mypath' is denied.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access,
nt32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions
ptions, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access
FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolea
bFromProxy)</p>
</blockquote>
<p>Question: What code do I need to catch this and how do I grant the access?</p>
|
[
{
"answer_id": 130641,
"author": "Josh",
"author_id": 11702,
"author_profile": "https://Stackoverflow.com/users/11702",
"pm_score": 7,
"selected": true,
"text": "public void ExportToFile(string filename)\n{\n var permissionSet = new PermissionSet(PermissionState.None); \n var writePermission = new FileIOPermission(FileIOPermissionAccess.Write, filename);\n permissionSet.AddPermission(writePermission);\n\n if (permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet))\n {\n using (FileStream fstream = new FileStream(filename, FileMode.Create))\n using (TextWriter writer = new StreamWriter(fstream))\n {\n // try catch block for write permissions \n writer.WriteLine(\"sometext\");\n\n\n }\n }\n else\n {\n //perform some recovery action here\n }\n\n}\n"
},
{
"answer_id": 462329,
"author": "Iain",
"author_id": 5993,
"author_profile": "https://Stackoverflow.com/users/5993",
"pm_score": 5,
"selected": false,
"text": "//1. Provide early notification that the user does not have permission to write.\nFileIOPermission writePermission = new FileIOPermission(FileIOPermissionAccess.Write, filename);\nif(!SecurityManager.IsGranted(writePermission))\n{\n //No permission. \n //Either throw an exception so this can be handled by a calling function\n //or inform the user that they do not have permission to write to the folder and return.\n}\n\n//2. Attempt the action but handle permission changes.\ntry\n{\n using (FileStream fstream = new FileStream(filename, FileMode.Create))\n using (TextWriter writer = new StreamWriter(fstream))\n {\n writer.WriteLine(\"sometext\");\n }\n}\ncatch (UnauthorizedAccessException ex)\n{\n //No permission. \n //Either throw an exception so this can be handled by a calling function\n //or inform the user that they do not have permission to write to the folder and return.\n}\n"
},
{
"answer_id": 1801847,
"author": "RockWorld",
"author_id": 185550,
"author_profile": "https://Stackoverflow.com/users/185550",
"pm_score": 2,
"selected": false,
"text": " string directoryPath = \"C:\\\\XYZ\"; //folderBrowserDialog.SelectedPath;\n bool isWriteAccess = false;\n try\n {\n AuthorizationRuleCollection collection = Directory.GetAccessControl(directoryPath).GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount));\n foreach (FileSystemAccessRule rule in collection)\n {\n if (rule.AccessControlType == AccessControlType.Allow)\n {\n isWriteAccess = true;\n break;\n }\n }\n }\n catch (UnauthorizedAccessException ex)\n {\n isWriteAccess = false;\n }\n catch (Exception ex)\n {\n isWriteAccess = false;\n }\n if (!isWriteAccess)\n {\n //handle notifications \n }\n"
},
{
"answer_id": 3422394,
"author": "Pablonete",
"author_id": 73130,
"author_profile": "https://Stackoverflow.com/users/73130",
"pm_score": 3,
"selected": false,
"text": " string folder;\n AuthorizationRuleCollection rules;\n try {\n rules = Directory.GetAccessControl(folder)\n .GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount));\n } catch(Exception ex) { //Posible UnauthorizedAccessException\n throw new Exception(\"No permission\", ex);\n }\n\n var rulesCast = rules.Cast<FileSystemAccessRule>();\n if(rulesCast.Any(rule => rule.AccessControlType == AccessControlType.Deny)\n || !rulesCast.Any(rule => rule.AccessControlType == AccessControlType.Allow))\n throw new Exception(\"No permission\");\n\n //Here I have permission, ole!\n"
},
{
"answer_id": 21972598,
"author": "JGU",
"author_id": 2777695,
"author_profile": "https://Stackoverflow.com/users/2777695",
"pm_score": 2,
"selected": false,
"text": "/// <summary>\n/// Test a directory for create file access permissions\n/// </summary>\n/// <param name=\"DirectoryPath\">Full directory path</param>\n/// <returns>State [bool]</returns>\npublic static bool DirectoryCanCreate(string DirectoryPath)\n{\n if (string.IsNullOrEmpty(DirectoryPath)) return false;\n\n try\n {\n AuthorizationRuleCollection rules = Directory.GetAccessControl(DirectoryPath).GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));\n WindowsIdentity identity = WindowsIdentity.GetCurrent();\n\n foreach (FileSystemAccessRule rule in rules)\n {\n if (identity.Groups.Contains(rule.IdentityReference))\n {\n if ((FileSystemRights.CreateFiles & rule.FileSystemRights) == FileSystemRights.CreateFiles)\n {\n if (rule.AccessControlType == AccessControlType.Allow)\n return true;\n }\n }\n }\n }\n catch {}\n return false;\n}\n"
},
{
"answer_id": 25333202,
"author": "MaxOvrdrv",
"author_id": 1583649,
"author_profile": "https://Stackoverflow.com/users/1583649",
"pm_score": 3,
"selected": false,
"text": " public static bool IsReadable(this DirectoryInfo me)\n {\n\n AuthorizationRuleCollection rules;\n WindowsIdentity identity;\n try\n {\n rules = me.GetAccessControl().GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));\n identity = WindowsIdentity.GetCurrent();\n }\n catch (Exception ex)\n { //Posible UnauthorizedAccessException\n return false;\n }\n\n bool isAllow=false;\n string userSID = identity.User.Value;\n\n foreach (FileSystemAccessRule rule in rules)\n {\n if (rule.IdentityReference.ToString() == userSID || identity.Groups.Contains(rule.IdentityReference))\n {\n if ((rule.FileSystemRights.HasFlag(FileSystemRights.Read) ||\n rule.FileSystemRights.HasFlag(FileSystemRights.ReadAndExecute) ||\n rule.FileSystemRights.HasFlag(FileSystemRights.ReadAttributes) ||\n rule.FileSystemRights.HasFlag(FileSystemRights.ReadData) ||\n rule.FileSystemRights.HasFlag(FileSystemRights.ReadExtendedAttributes) ||\n rule.FileSystemRights.HasFlag(FileSystemRights.ReadPermissions)) && rule.AccessControlType == AccessControlType.Deny)\n return false;\n else if ((rule.FileSystemRights.HasFlag(FileSystemRights.Read) ||\n rule.FileSystemRights.HasFlag(FileSystemRights.ReadAndExecute) ||\n rule.FileSystemRights.HasFlag(FileSystemRights.ReadAttributes) ||\n rule.FileSystemRights.HasFlag(FileSystemRights.ReadData) ||\n rule.FileSystemRights.HasFlag(FileSystemRights.ReadExtendedAttributes) ||\n rule.FileSystemRights.HasFlag(FileSystemRights.ReadPermissions)) && rule.AccessControlType == AccessControlType.Allow)\n isAllow = true;\n }\n }\n\n return isAllow;\n }\n\n public static bool IsWriteable(this DirectoryInfo me)\n {\n AuthorizationRuleCollection rules;\n WindowsIdentity identity;\n try\n {\n rules = me.GetAccessControl().GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));\n identity = WindowsIdentity.GetCurrent();\n }\n catch (Exception ex)\n { //Posible UnauthorizedAccessException\n return false;\n }\n\n bool isAllow = false;\n string userSID = identity.User.Value;\n\n foreach (FileSystemAccessRule rule in rules)\n {\n if (rule.IdentityReference.ToString() == userSID || identity.Groups.Contains(rule.IdentityReference))\n {\n if ((rule.FileSystemRights.HasFlag(FileSystemRights.Write) ||\n rule.FileSystemRights.HasFlag(FileSystemRights.WriteAttributes) ||\n rule.FileSystemRights.HasFlag(FileSystemRights.WriteData) ||\n rule.FileSystemRights.HasFlag(FileSystemRights.WriteExtendedAttributes) ||\n rule.FileSystemRights.HasFlag(FileSystemRights.CreateDirectories) ||\n rule.FileSystemRights.HasFlag(FileSystemRights.CreateFiles)) && rule.AccessControlType == AccessControlType.Deny)\n return false;\n else if ((rule.FileSystemRights.HasFlag(FileSystemRights.Write) ||\n rule.FileSystemRights.HasFlag(FileSystemRights.WriteAttributes) ||\n rule.FileSystemRights.HasFlag(FileSystemRights.WriteData) ||\n rule.FileSystemRights.HasFlag(FileSystemRights.WriteExtendedAttributes) ||\n rule.FileSystemRights.HasFlag(FileSystemRights.CreateDirectories) ||\n rule.FileSystemRights.HasFlag(FileSystemRights.CreateFiles)) && rule.AccessControlType == AccessControlType.Allow)\n isAllow = true;\n }\n }\n\n return me.IsReadable() && isAllow;\n }\n"
},
{
"answer_id": 31040692,
"author": "xmen",
"author_id": 836308,
"author_profile": "https://Stackoverflow.com/users/836308",
"pm_score": 4,
"selected": false,
"text": "public static bool IsReadable(this DirectoryInfo di)\n{\n AuthorizationRuleCollection rules;\n WindowsIdentity identity;\n try\n {\n rules = di.GetAccessControl().GetAccessRules(true, true, typeof(SecurityIdentifier));\n identity = WindowsIdentity.GetCurrent();\n }\n catch (UnauthorizedAccessException uae)\n {\n Debug.WriteLine(uae.ToString());\n return false;\n }\n\n bool isAllow = false;\n string userSID = identity.User.Value;\n\n foreach (FileSystemAccessRule rule in rules)\n {\n if (rule.IdentityReference.ToString() == userSID || identity.Groups.Contains(rule.IdentityReference))\n {\n if ((rule.FileSystemRights.HasFlag(FileSystemRights.Read) ||\n rule.FileSystemRights.HasFlag(FileSystemRights.ReadAttributes) ||\n rule.FileSystemRights.HasFlag(FileSystemRights.ReadData)) && rule.AccessControlType == AccessControlType.Deny)\n return false;\n else if ((rule.FileSystemRights.HasFlag(FileSystemRights.Read) &&\n rule.FileSystemRights.HasFlag(FileSystemRights.ReadAttributes) &&\n rule.FileSystemRights.HasFlag(FileSystemRights.ReadData)) && rule.AccessControlType == AccessControlType.Allow)\n isAllow = true;\n\n }\n }\n return isAllow;\n}\n\npublic static bool IsWriteable(this DirectoryInfo me)\n{\n AuthorizationRuleCollection rules;\n WindowsIdentity identity;\n try\n {\n rules = me.GetAccessControl().GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));\n identity = WindowsIdentity.GetCurrent();\n }\n catch (UnauthorizedAccessException uae)\n {\n Debug.WriteLine(uae.ToString());\n return false;\n }\n\n bool isAllow = false;\n string userSID = identity.User.Value;\n\n foreach (FileSystemAccessRule rule in rules)\n {\n if (rule.IdentityReference.ToString() == userSID || identity.Groups.Contains(rule.IdentityReference))\n {\n if ((rule.FileSystemRights.HasFlag(FileSystemRights.Write) ||\n rule.FileSystemRights.HasFlag(FileSystemRights.WriteAttributes) ||\n rule.FileSystemRights.HasFlag(FileSystemRights.WriteData) ||\n rule.FileSystemRights.HasFlag(FileSystemRights.CreateDirectories) ||\n rule.FileSystemRights.HasFlag(FileSystemRights.CreateFiles)) && rule.AccessControlType == AccessControlType.Deny)\n return false;\n else if ((rule.FileSystemRights.HasFlag(FileSystemRights.Write) &&\n rule.FileSystemRights.HasFlag(FileSystemRights.WriteAttributes) &&\n rule.FileSystemRights.HasFlag(FileSystemRights.WriteData) &&\n rule.FileSystemRights.HasFlag(FileSystemRights.CreateDirectories) &&\n rule.FileSystemRights.HasFlag(FileSystemRights.CreateFiles)) && rule.AccessControlType == AccessControlType.Allow)\n isAllow = true;\n\n }\n }\n return isAllow;\n}\n"
},
{
"answer_id": 46452349,
"author": "jinzai",
"author_id": 3843815,
"author_profile": "https://Stackoverflow.com/users/3843815",
"pm_score": 0,
"selected": false,
"text": " Private Function CheckUserAccessLevel(folder As String) As Boolean\nTry\n Dim newDir As String = String.Format(\"{0}{1}{2}\",\n folder,\n If(folder.EndsWith(\"\\\"),\n \"\",\n \"\\\"),\n \"LookWhatICanDo\")\n Dim lookWhatICanDo = Directory.CreateDirectory(newDir)\n\n Directory.Delete(newDir)\n Return True\n\nCatch ex As Exception\n Return False\nEnd Try\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/130617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1361/"
] |
130,618
|
<p>I would like to find out if a particular python datetime object is older than X hours or minutes. I am trying to do something similar to: </p>
<pre><code>if (datetime.now() - self.timestamp) > 100
# Where 100 is either seconds or minutes
</code></pre>
<p>This generates a type error. </p>
<p>What is the proper way to do date time comparison in python? I already looked at <a href="http://wiki.python.org/moin/WorkingWithTime" rel="noreferrer">WorkingWithTime</a> which is close but not exactly what I want. I assume I just want the datetime object represented in seconds so that I can do a normal int comparison. </p>
<p>Please post lists of datetime best practices.</p>
|
[
{
"answer_id": 130623,
"author": "William Keller",
"author_id": 17095,
"author_profile": "https://Stackoverflow.com/users/17095",
"pm_score": 0,
"selected": false,
"text": "datetime.fromtimestamp"
},
{
"answer_id": 130647,
"author": "Jerub",
"author_id": 14648,
"author_profile": "https://Stackoverflow.com/users/14648",
"pm_score": 1,
"selected": false,
"text": "def seconds_difference(stamp1, stamp2):\n delta = stamp1 - stamp2\n return 24*60*60*delta.days + delta.seconds + delta.microseconds/1000000.\n if seconds_difference(datetime.datetime.now(), timestamp) < 100:\n pass\n"
},
{
"answer_id": 130652,
"author": "William",
"author_id": 9193,
"author_profile": "https://Stackoverflow.com/users/9193",
"pm_score": 3,
"selected": false,
"text": "if datetime.datetime.now() - timestamp > datetime.timedelta(seconds = 5):\n print 'older'\n"
},
{
"answer_id": 130665,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 8,
"selected": true,
"text": "datetime.timedelta >>> from datetime import datetime, timedelta\n>>> then = datetime.now() - timedelta(hours = 2)\n>>> now = datetime.now()\n>>> (now - then) > timedelta(days = 1)\nFalse\n>>> (now - then) > timedelta(hours = 1)\nTrue\n if (datetime.now() - self.timestamp) > timedelta(seconds = 100)\n if (datetime.now() - self.timestamp) > timedelta(minutes = 100)\n"
},
{
"answer_id": 130669,
"author": "Jeremy Cantrell",
"author_id": 18866,
"author_profile": "https://Stackoverflow.com/users/18866",
"pm_score": 0,
"selected": false,
"text": "# self.timestamp should be a datetime object\nif (datetime.now() - self.timestamp).seconds > 100:\n print \"object is over 100 seconds old\"\n"
},
{
"answer_id": 10546316,
"author": "Chong Ying Fan",
"author_id": 1388716,
"author_profile": "https://Stackoverflow.com/users/1388716",
"pm_score": 3,
"selected": false,
"text": "if (datetime.now() - self.timestamp).total_seconds() > 100:\n"
},
{
"answer_id": 67727197,
"author": "Golden Lion",
"author_id": 4001177,
"author_profile": "https://Stackoverflow.com/users/4001177",
"pm_score": 0,
"selected": false,
"text": "start_time=datetime(\n year=2021,\n month=5,\n day=27,\n hour=10,\n minute=24,\n microsecond=0)\n\n end_time=datetime.now()\n delta=(end_time-start_time)\n\n seconds_in_day = 24 * 60 * 60\n seconds_in_hour= 1 * 60 * 60\n\n elapsed_seconds=delta.days * seconds_in_day + delta.seconds\n\n hours= int(elapsed_seconds/seconds_in_hour)\n minutes= int((elapsed_seconds - (hours*seconds_in_hour))/60)\n\n print(\"Hours {} Minutes {}\".format(hours,minutes))\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/130618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20794/"
] |
130,636
|
<p>When I try to compile the newest version of Clisp on Ubuntu 8.04 I always get this error after running configure:</p>
<pre><code>Configure findings:
FFI: no (user requested: default)
readline: yes (user requested: yes)
libsigsegv: no, consider installing GNU libsigsegv
./configure: libsigsegv was not detected, thus some features, such as
generational garbage collection and
stack overflow detection in interpreted Lisp code
cannot be provided.
Please do this:
mkdir tools; cd tools; prefix=`pwd`/i686-pc-linux-gnu
wget http://ftp.gnu.org/pub/gnu/libsigsegv/libsigsegv-2.5.tar.gz
tar xfz libsigsegv-2.5.tar.gz
cd libsigsegv-2.5
./configure --prefix=${prefix} && make && make check && make install
cd ../..
./configure --with-libsigsegv-prefix=${prefix} --with-readline --with-unicode --with-module=i18n --with-module=gdbm --with-module=pcre --with-module=readline --with-module=regexp
If you insist on building without libsigsegv, please pass
--ignore-absence-of-libsigsegv
to this script:
./configure --ignore-absence-of-libsigsegv --with-readline --with-unicode --with-module=i18n --with-module=gdbm --with-module=pcre --with-module=readline --with-module=regexp
</code></pre>
<p>I've tried doing as requested, but it didn't help: it seems to ignore the <code>--with-libsigsegv-prefix</code> option. I also tried putting installing libsigsegv in a standard location (<code>/usr/local</code>). Oh, and of course, Ubuntu tells me that libsigsegv and libsigsegv-dev are installed in the system.</p>
<p>I'd really like to be able to compile this version of Clips, as it introduces some serious improvements over the version shipped with Ubuntu (I'd also like to have PCRE).</p>
|
[
{
"answer_id": 130752,
"author": "Luís Oliveira",
"author_id": 2967,
"author_profile": "https://Stackoverflow.com/users/2967",
"pm_score": 3,
"selected": true,
"text": "sudo apt-get install libsigsegv-dev libreadline5-dev\n\n# as of 7.10, Ubuntu's libffcall1-dev is broken and I had to get it from CVS\n# and make sure CLISP didn't use Ubuntu's version.\nsudo apt-get remove libffcall1-dev libffcall1\ncvs -z3 -d:pserver:anonymous@cvs.sv.gnu.org:/sources/libffcall co -P ffcall\ncd ffcall; ./configure; make\nsudo make install\n\ncvs -z3 -d:pserver:anonymous@clisp.cvs.sourceforge.net:/cvsroot/clisp co -P clisp\ncd clisp\n./configure --with-libffcall-prefix=/usr/local --prefix=/home/luis/Software\nulimit -s 16384\ncd src; make install\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/130636",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19922/"
] |
130,637
|
<p>I am trying to figure out a crash in my application.
WinDbg tells me the following: (using dashes in place of underscores)</p>
<p><br><b>LAST-CONTROL-TRANSFER: from 005f5c7e to 6e697474
<br>DEFAULT-BUCKET-ID: BAD_IP
<br>BUGCHECK-STR: ACCESS-VIOLATION</b></p>
<p>It is obvious to me that 6e697474 is NOT a valid address.
<br><br>I have three questions:
<br>1) Does the "BAD_IP" bucket ID mean "Bad Instruction Pointer?"
<br>2) This is a multi-threaded application so one consideration was that the object whose function I was attempting to call went out of scope. Does anyone know if that would lead to the same error message?
<br>3) What else might cause an error like this? One of my co-workers suggested that it might be a <b>stack overflow</b> issue, but WinDBG in the past has proven rather reliable at detecting and pointing these out. (not that I'm sure about the voodoo it does in the background to diagnose that). </p>
|
[
{
"answer_id": 133212,
"author": "Mike Dimmick",
"author_id": 6970,
"author_profile": "https://Stackoverflow.com/users/6970",
"pm_score": 0,
"selected": false,
"text": "vfptr"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/130637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
130,640
|
<p>I would like to be able to say things like</p>
<p><strong>cd [.fred]</strong> and have my default directory go there,
and my prompt change to indicate the full path to my current location.</p>
|
[
{
"answer_id": 131275,
"author": "chimp",
"author_id": 18364,
"author_profile": "https://Stackoverflow.com/users/18364",
"pm_score": 3,
"selected": false,
"text": "cd:==set default $ cd:==set default $ set prompt='f$env(\"default\")'"
},
{
"answer_id": 223455,
"author": "Luc M",
"author_id": 14673,
"author_profile": "https://Stackoverflow.com/users/14673",
"pm_score": 3,
"selected": true,
"text": "CD == \"@sys$login:godir.com\"\n SD ?\nSD a_directory\n...\n $ noeud = f$trnlnm(\"SYS$NODE\") - \"::\"\n$ if noeud .eqs. \"HQSVYC\" then noeud = \"¥\"\n$!\n$ noeud = noeud - \"MQO\"\n$ def_dir = f$directory()\n$ def_dir = f$extract(1,f$length(def_dir)-2,def_dir)\n$boucle:\n$ i = f$locate(\".\",def_dir)\n$ if i .eq. f$length(def_dir) then goto fin_boucle\n$ def_dir = f$extract(i+1,f$length(def_dir)-1,def_dir)\n$ goto boucle\n$!\n$fin_boucle:\n$! temp = \"''noeud' ''def_dir' \" + \"''car_prompt'\"\n$ temp = \"''noeud'\" -\n + \" ''def_dir' \" -\n + \"''f$logical(\"\"environnement\"\")'\" -\n + \"''car_prompt'\"\n$! temp = \"''noeud'\" -\n$! + \"''def_dir'\" -\n$! + \"''f$logical(\"\"environnement\"\")'\" -\n$! + \"''car_prompt'\"\n$ set prompt=\"''temp' \"\n$!\n$! PROMPT.COM\n$!\n $!\n$! GODIR.COM\n$!\n$ set noon\n$ set_prompt = \"@sys$login:prompt.com\"\n$ if f$type(TAB_DIR_N) .nes. \"\" then goto 10$\n$ goto 20$\n$ INIT:\n$ temp2 = \"INIT\"\n$ CLEAR:\n$ temp = 0\n$\n$ INIT2:\n$ temp = temp +1\n$ if temp .gt. TAB_DIR_N then goto INIT3\n$ delete/symb/glo TAB_DIR_'temp'\n$ goto INIT2\n$\n$ INIT3:\n$ P1 = \"\"\n$ if temp2 .eqs. \"INIT\" then goto 20$\n$ delete/symb/glo TAB_DIR_N\n$ delete/symb/glo TAB_DIR_P\n$ delete/symb/glo TAB_DIR_I\n$ exit\n$\n$ 20$:\n$ TAB_DIR_N == 1\n$ TAB_DIR_P == 1\n$ TAB_DIR_I == 1\n$ if \"''car_prompt'\" .eqs. \"\" then car_prompt == \">\"\n$ TAB_DIR_1 == f$parse(f$dir(),,,\"device\")+f$dir()\n$ 10$:\n$ if P1 .eqs. \"\" then goto LIST\n$ if P1 .eqs. \"?\" then goto SHOW\n$ if P1 .eqs. \".\" then P1 = \"[]\"\n$ if P1 .eqs. \"^\" then goto SET_CUR\n$ if (P1 .eqs. \"<\") .or. (P1 .eqs. \">\") .or. -\n (P1 .eqs. \"..\") then P1 = \"[-]\"\n$ if (P1 .eqs. \"*\") .or. (P1 .eqs. \"0\") then goto HOME\n$ if (P1 .eqs. \"P\") .or. (P1 .eqs. \"p\") then goto PREVIOUS\n$ if (P1 .eqs. \"H\") .or. (P1 .eqs. \"h\") then goto HELP\n$ if (P1 .eqs. \"S\") .or. (P1 .eqs. \"s\") then goto SET_PROMPT\n$ if (P1 .eqs. \"G\") .or. (P1 .eqs. \"g\") then goto SET_PROMPT_GRAPHIC\n$ temp2 = \"\"\n$ if (P1 .eqs. \"~INIT\") .or. (P1 .eqs. \"~init\") then goto INIT\n$ if (P1 .eqs. \"~CLEAR\") .or. (P1 .eqs. \"~clear\") then goto CLEAR\n$\n$! *** Specification par un numero\n$ temp = f$extract(0,1,P1)\n$ if temp .eqs. \"-\" then goto DELETE\n$ temp2 = \"\"\n$boucle_reculer:\n$ if temp .nes. \"\\\" then goto fin_reculer\n$ temp2 = temp2 + \"-.\"\n$ P1 = P1 - \"\\\"\n$ temp = f$extract(0,1,P1)\n$ goto boucle_reculer\n$!\n$fin_reculer:\n$ P1 = temp2 + P1\n$ if (P1 .lts. \"0\") .or. (P1 .gts. \"9\") then goto SPEC\n$ temp = f$integer(\"''P1'\")\n$ if temp .eq. 0 then goto HOME\n$ if (temp .lt. 1) .or. (temp .gt. TAB_DIR_N) then goto ERR\n$ TAB_DIR_P == TAB_DIR_I\n$ TAB_DIR_I == temp\n$ goto SET2\n$\n$ SPEC:\n$! *** Specification relative de directory\n$\n$ temp = f$parse(\"[.''P1']\",\"missing.mis\")\n$ DD = f$extract(0,f$locate(\"]\",temp)+1,temp)\n$ if DD .nes. \"\" then goto SET1\n$\n$! *** Specification de directory principal\n$\n$ temp = f$parse(\"[''P1']\",\"missing.mis\")\n$ DD = f$extract(0,f$locate(\"]\",temp)+1,temp)\n$ if DD .nes. \"\" then goto SET1\n$\n$ temp = f$parse(\"[''P1']\",\"sys$login:missing.mis\")\n$ DD = f$extract(0,f$locate(\"]\",temp)+1,temp)\n$ if DD .nes. \"\" then goto SET1\n$\n$! *** Specification exacte de directory\n$\n$ temp = f$parse(P1,\"missing.mis\")\n$ if f$locate(\"]\"+P1,temp) .ne. f$length(temp) then goto ERR\n$ if f$locate(\".][\",temp) .ne. f$length(temp) then temp = temp - \"][\"\n$ DD = f$extract(0,f$locate(\"]\",temp)+1,temp)\n$! if DD .eqs. TAB_DIR_'TAB_DIR_I' then goto SHOW\n$ if DD .eqs. TAB_DIR_'TAB_DIR_I' then goto SET2\n$ if DD .nes. \"\" then goto SET1\n$\n$ temp = f$parse(P1,\"sys$login:missing.mis\")\n$ if f$locate(\"]\"+P1,temp) .ne. f$length(temp) then goto ERR\n$ if f$locate(\".][\",temp) .ne. f$length(temp) then temp = temp - \"][\"\n$ DD = f$extract(0,f$locate(\"]\",temp)+1,temp)\n$! if DD .eqs. TAB_DIR_'TAB_DIR_I' then goto SHOW\n$ if DD .eqs. TAB_DIR_'TAB_DIR_I' then goto SET2\n$ if DD .nes. \"\" then goto SET1\n$\n$ goto ERR\n$\n$ HOME:\n$ DD = \"SYS$LOGIN\"\n$\n$ SET1:\n$ Set On\n$ On error then goto ERR1\n$ set message/nofac/noid/nosever/notext\n$ Set def 'DD'\n$ dir/output=nl:\n$ set message/fac/id/sever/text\n$ temp = f$parse(f$dir()) - \".;\"\n$ if temp .nes. \"\" then goto SET1F\n$ ERR1:\n$ set message/fac/id/sever/text\n$ temp = TAB_DIR_'TAB_DIR_I'\n$ Set def 'temp'\n$ goto ERR\n$ SET1F:\n$ I = 0\n$ LOOP1:\n$ I = I + 1\n$ if temp .eqs. TAB_DIR_'I' then goto FOUND\n$ if I .lt. TAB_DIR_N then goto LOOP1\n$\n$ TAB_DIR_N == TAB_DIR_N + 1\n$ TAB_DIR_P == TAB_DIR_I\n$ TAB_DIR_I == TAB_DIR_N\n$ TAB_DIR_'TAB_DIR_I' == temp\n$ goto SHOW\n$\n$ FOUND:\n$ TAB_DIR_P == TAB_DIR_I\n$ TAB_DIR_I == I\n$ goto SET2\n$\n$ SET_PROMPT:\n$ car_prompt == \"''P2'\"\n$ set_prompt\n$ exit\n$\n$ PREVIOUS:\n$ temp = TAB_DIR_P\n$ TAB_DIR_P == TAB_DIR_I\n$ TAB_DIR_I == temp\n$\n$ SET_CUR:\n$ SET2:\n$ DD = TAB_DIR_'TAB_DIR_I'\n$ set def 'DD'\n$\n$ SHOW:\n$ temp = TAB_DIR_'TAB_DIR_I'\n$ ws \" ''TAB_DIR_I' * ''temp'\"\n$ set_prompt\n$ exit\n$\n$ LIST:\n$ I = 0\n$ LOOP2:\n$ I = I + 1\n$ temp = TAB_DIR_'I'\n$ if I .eq. TAB_DIR_I then goto L_CUR\n$ if I .eq. TAB_DIR_P then GOTO L_PRE\n$ ws \" ''I' = ''temp'\"\n$ goto F_LOOP2\n$ L_CUR:\n$ ws \" ''I' * ''temp'\"\n$ goto F_LOOP2\n$ L_PRE:\n$ ws \" ''I' + ''temp'\"\n$\n$ F_LOOP2:\n$ if I .lt. TAB_DIR_N then goto LOOP2\n$ set_prompt\n$\n$ exit\n$\n$ DELETE:\n$ P1 = P1 - \"-\"\n$ temp2 = f$integer(\"''P1'\")\n$ DEL_1:\n$ temp = f$integer(\"''P1'\")\n$ if (temp .lt. 1) .or. (temp .gt. TAB_DIR_N) then goto ERR\n$ if temp .eq. TAB_DIR_I then goto ERR\n$ if temp .lt. TAB_DIR_I then TAB_DIR_I == TAB_DIR_I - 1\n$ if temp .eq. TAB_DIR_P then TAB_DIR_P == TAB_DIR_I\n$ if temp .lt. TAB_DIR_P then TAB_DIR_P == TAB_DIR_P - 1\n$ LOOP3:\n$ if temp .eq. TAB_DIR_N then goto F_LOOP3\n$ temp3 = temp + 1\n$ TAB_DIR_'temp' == TAB_DIR_'temp3'\n$ temp = temp + 1\n$ goto LOOP3\n$ F_LOOP3:\n$ delete/symb/glo tab_dir_'tab_dir_n'\n$ TAB_DIR_N == TAB_DIR_N - 1\n$ if P2 .eqs. \"\" then goto FIN_DEL\n$ temp2 = temp2 + 1\n$ if temp2 .le. f$integer(\"''P2'\") then goto DEL_1\n$ FIN_DEL:\n$ goto LIST\n$\n$ ERR:\n$ ws \"*** ERREUR ***\"\n$ exit\n$\n$ HELP:\n$ ws \" H Show this menu\"\n$ ws \" null Show a list of directories\"\n$ ws \" ? Show current directory\"\n$ ws \" < or [-] or\"\n$ ws \" > or .. Remonte d'un niveau de directory\"\n$ ws \" * ou 0 Return to SYS$LOGIN\"\n$ ws \" P Last directory \"\n$ ws \" . ou [] Set cureent directory\"\n$ ws \" ^ Return to next directory\"\n$ ws \" x Set def to number x\"\n$ ws \" -x Remove the number x\"\n$ ws \" -x y Remove from x to y\"\n$ ws \" ddd Set def to [ddd] or [.ddd] or ddd:\"\n$ ws \" \\ddd Set def to [-.ddd]\"\n$ ws \" S \"\">>\"\" Modify prompt for >>\"\n$ ws \" ~INIT Initialize to current directory \"\n$ ws \" (and delete all others references)\"\n$ ws \" ~CLEAR Remove all references\n$ ws \"\"\n$\n$ exit\n$\n$ SET_PROMPT_GRAPHIC:\n$ temp = \"''P2'\"\n$ i=0\n$ car_prompt == \"\"\n$ GRAPH_BOUCLE:\n$ t=f$extract(i,1,temp)\n$ if (t .eqs. \"e\") .or. (t .eqs. \"E\") then t=\"ESC\"\n$ if (t .eqs. \"g\") .or. (t .eqs. \"G\") then t=\"ESC(0\"\n$ V° (} .L-_. \"N\") .-_. (} .L-_. \"H\") }NL+ }=\"ESC(B\"\n$ car_prompt == car_prompt + t\n$ i = i+1\n$ if i .lts. f$length(temp) then goto GRAPH_BOUCLE\n$\n$ set_prompt\n$ exit\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/130640",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7734/"
] |
130,664
|
<p>I have a command line executable that alters some bits in a file that i want to use from my program.
Is it possible to create my own executable that uses this tool and distribute only one executable?</p>
<p>[edit] Clarification:</p>
<p>The command line tool takes an offset and some bits and changes the bits at this offset in a given file. So I want to create a patcher for an application that changes specific bits to a specific value, so what I can do i write something like a batch file to do it but i want to create an executable that does it, i.e. embed the tool into a wrapper program that calls it with specific values.</p>
<p>I can code wrapper in (windows) c\c++, asm but no .net please.</p>
|
[
{
"answer_id": 130685,
"author": "Adam Pierce",
"author_id": 5324,
"author_profile": "https://Stackoverflow.com/users/5324",
"pm_score": 2,
"selected": false,
"text": "Open destination file\nOpen main exe as a binary file\nCopy main exe to destination file\noffset = size of main exe\nOpen 2nd exe as a binary file\nCopy 2nd exe to the output file\nWrite the offset to the output file\n Find the location of our own EXE file (GetModuleFileName() under Windows)\nOpen the file in binary mode\nSeek to the end minus sizeof(offset) (typically 4 bytes)\nRead the offset value\nSeek to the offset position\nOpen a temporary file in binary mode\nRead bytes from the main EXE and write to the temporary file\nLaunch the temporary file\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/130664",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14587/"
] |
130,698
|
<p>I want to wrap a <a href="https://en.wikipedia.org/wiki/One-liner_program#Perl" rel="nofollow noreferrer">Perl one-liner</a> in a batch file. For a (trivial) example, in a Unix shell, I could quote up a command like this:</p>
<pre><code>perl -e 'print localtime() . "\n"'
</code></pre>
<p>But DOS chokes on that with this helpful error message:</p>
<blockquote>
<p>Can't find string terminator "'" anywhere before EOF at -e line 1.</p>
</blockquote>
<p>What's the best way to do this within a <a href="https://en.wikipedia.org/wiki/Batch_file" rel="nofollow noreferrer">.bat file</a>?</p>
|
[
{
"answer_id": 130726,
"author": "brian d foy",
"author_id": 2766176,
"author_profile": "https://Stackoverflow.com/users/2766176",
"pm_score": 5,
"selected": true,
"text": "perl -e \"print scalar localtime() . qq(\\n)\"\n -l perl -le \"print scalar localtime()\"\n"
},
{
"answer_id": 130728,
"author": "tye",
"author_id": 21496,
"author_profile": "https://Stackoverflow.com/users/21496",
"pm_score": 3,
"selected": false,
"text": "perl -e \"print localtime() . qq(\\n)\"\nperl -e \"print localtime() . $/\"\nperl -le \"print ''.localtime()\"\n perl -E \"say scalar localtime()\"\n"
},
{
"answer_id": 130731,
"author": "David Nehme",
"author_id": 14167,
"author_profile": "https://Stackoverflow.com/users/14167",
"pm_score": 1,
"selected": false,
"text": "perl -e \"print localtime();\"\n"
},
{
"answer_id": 131086,
"author": "puetzk",
"author_id": 14312,
"author_profile": "https://Stackoverflow.com/users/14312",
"pm_score": 1,
"selected": false,
"text": "perl -e \"print localtime() . \"\"\\n\"\"\"\n"
},
{
"answer_id": 162528,
"author": "Christopher G. Lewis",
"author_id": 13532,
"author_profile": "https://Stackoverflow.com/users/13532",
"pm_score": 2,
"selected": false,
"text": "C:\\>perl -e \"print localtime() . \"\"\\n\"\"\"\nThu Oct 2 09:17:32 2008\n"
}
] |
2008/09/24
|
[
"https://Stackoverflow.com/questions/130698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21938/"
] |
130,708
|
<p>I am developing an ASP.NET Ajax form, and decided to make most of the site in one page, because it isn't a very involved site (it's more of a form). In the codebehind, I have been making my code more organized by adding regions to it (inside are the click events of the controls, etc).</p>
<p>When I expand a region, all the subroutines and child regions are expanded. Is there an option in Visual Studio to prevent this from happening? I'd like to be able to expand a region, and then expand the region or subroutine I'd like to edit, rather than contracting all the subroutines and child regions to prevent me from getting distracted by my fat code. :)</p>
|
[
{
"answer_id": 130722,
"author": "Ben Hoffstein",
"author_id": 4482,
"author_profile": "https://Stackoverflow.com/users/4482",
"pm_score": 2,
"selected": false,
"text": "Ctrl + M, Ctrl + M Collapse or expand the block you?re currently in.\nCtrl + M, Ctrl + O Collapse all blocks in the file\nCtrl + M, Ctrl + L Expand all blocks in the file\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/130708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20900/"
] |
130,711
|
<p>I wonder how long it would usually take for:</p>
<ol>
<li>Professional</li>
<li>Average</li>
<li>Beginner</li>
</ol>
<p>to setup and configure CI for a new project?</p>
|
[
{
"answer_id": 131284,
"author": "Jörg W Mittag",
"author_id": 2988,
"author_profile": "https://Stackoverflow.com/users/2988",
"pm_score": 3,
"selected": true,
"text": "rake"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/130711",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15396/"
] |
130,720
|
<p>In certain cases, I can't seem to get components to receive events.</p>
<p>[edit] </p>
<p>To clarify, the example code is just for demonstration sake, what I was really asking was if there was a central location that a listener could be added, to which one can reliably dispatch events to and from arbitrary objects.</p>
<p>I ended up using parentApplication to dispatch and receive the event I needed to handle.</p>
<p>[/edit]</p>
<p>If two components have differing parents, or as in the example below, one is a popup, it would seem the event never reaches the listener (See the method "popUp" for the dispatch that doesn't work):</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="absolute"
initialize="init()">
<mx:Script>
<![CDATA[
import mx.controls.Menu;
import mx.managers.PopUpManager;
// Add listeners
public function init():void
{
this.addEventListener("child", handleChild);
this.addEventListener("stepchild", handleStepchild);
}
// Handle the no pop button event
public function noPop(event:Event):void
{
dispatchEvent(new Event("child"));
}
// Handle the pop up
public function popUp(event:Event):void
{
var menu:Menu = new Menu();
var btnMenu:Button = new Button();
btnMenu.label = "stepchild";
menu.addChild(btnMenu);
PopUpManager.addPopUp(menu, this);
// neither of these work...
this.callLater(btnMenu.dispatchEvent, [new Event("stepchild", true)]);
btnMenu.dispatchEvent(new Event("stepchild", true));
}
// Event handlers
public function handleChild(event:Event):void
{
trace("I handled child");
}
public function handleStepchild(event:Event):void {
trace("I handled stepchild");
}
]]>
</mx:Script>
<mx:VBox>
<mx:Button label="NoPop" id="btnNoPop" click="noPop(event)"/>
<mx:Button label="PopUp" id="btnPop" click="popUp(event)"/>
</mx:VBox>
</mx:Application>
</code></pre>
<p><strong>I can think of work-arounds, but it seems like there ought to be some central event bus...</strong> </p>
<p>Am I missing something?</p>
|
[
{
"answer_id": 131046,
"author": "Antti",
"author_id": 6037,
"author_profile": "https://Stackoverflow.com/users/6037",
"pm_score": 0,
"selected": false,
"text": "this btnMenu this this"
},
{
"answer_id": 133032,
"author": "Verdant",
"author_id": 450527,
"author_profile": "https://Stackoverflow.com/users/450527",
"pm_score": 3,
"selected": true,
"text": "dispatchEvent(new Event(\"stepchild\", true));\n btnMenu.addEventListener(\"stepchild\",handleStepChild);\nbtnMenu.dispatchEvent(new Event(\"stepchild\",true));\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/130720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16258/"
] |
130,721
|
<p>My DBA requires all database access to be done through trusted domain account. This can be done if you set the web.config . This requires the user to login or to be on the domain for IE pass the credentials through. I want to impersonate a user by using code. I am using the code found in this knowledgebase article:</p>
<p><a href="http://support.microsoft.com/kb/306158" rel="nofollow noreferrer">http://support.microsoft.com/kb/306158</a></p>
<p>It works great, I pass in the credentials, impersonate the user, then make the call to the database and data is returned. </p>
<p>The problem is if I go to another page, I lose my impersonated credentials. This means every time I make a call to the database I have to run the impersonate code. </p>
<p>If IIS can impersonate a domain user for all pages, then why can I not impersonate a user while using code?</p>
<p>It seems to be something with thread context switching. I have tried setting the alwaysFlowImpersonatingPolicy in the Aspnet.config file and it did not work.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms229553.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms229553.aspx</a></p>
<p>Any suggestion? Is it even possible to do what I want?</p>
|
[
{
"answer_id": 130808,
"author": "Kev",
"author_id": 419,
"author_profile": "https://Stackoverflow.com/users/419",
"pm_score": 1,
"selected": false,
"text": "<alwaysFlowImpersonationPolicy>"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/130721",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/678/"
] |
130,730
|
<p>I have an immutable class with some private fields that are set during the constructor execution. I want to unit test this constructor but I'm not sure the "best practice" in this case.</p>
<p><strong>Simple Example</strong></p>
<p>This class is defined in Assembly1:</p>
<pre><code>public class Class2Test
{
private readonly string _StringProperty;
public Class2Test()
{
_StringProperty = ConfigurationManager.AppSettings["stringProperty"];
}
}
</code></pre>
<p>This class is defined in Assembly2:</p>
<pre><code>[TestClass]
public class TestClass
{
[TestMethod]
public void Class2Test_Default_Constructor()
{
Class2Test x = new Class2Test();
//what do I assert to validate that the field was set properly?
}
}
</code></pre>
<p><strong>EDIT 1</strong>: I have answered this question with a potential solution but I'm not sure if it's the "right way to go". So if you think you have a better idea please post it.</p>
<p>This example isn't really worth testing, but assume the constructor has some more complex logic. Is the best approach to avoid testing the constructor and to just assume it works if all the tests for the methods on the class work?</p>
<p><strong>EDIT 2</strong>: Looks like I made the sample a little to simple. I have updated it with a more reasonable situation.</p>
|
[
{
"answer_id": 130732,
"author": "Eric Schoonover",
"author_id": 3957,
"author_profile": "https://Stackoverflow.com/users/3957",
"pm_score": 1,
"selected": false,
"text": "[InternalsVisibleTo] public class Class2Test\n{\n private readonly string _StringProperty;\n internal string StringProperty { get { return _StringProperty; } }\n\n public Class2Test(string stringProperty)\n {\n _StringProperty = stringProperty;\n }\n}\n Assert.AreEqual(x.StringProperty, \"something\");\n Class2Test"
},
{
"answer_id": 130735,
"author": "Matt Hinze",
"author_id": 2676,
"author_profile": "https://Stackoverflow.com/users/2676",
"pm_score": 4,
"selected": true,
"text": "public Class2Test()\n{\n _StringProperty = ConfigurationManager.AppSettings[\"stringProperty\"];\n}\n ConfigurationManager.AppSettings Class2Test WebConfigSettingsReader"
},
{
"answer_id": 130785,
"author": "Jim Burger",
"author_id": 20164,
"author_profile": "https://Stackoverflow.com/users/20164",
"pm_score": 1,
"selected": false,
"text": " public interface IConfigManager\n {\n string FooSetting { get; set; }\n }\n\n public class Class2Test\n {\n private IConfigManager _config;\n public Class2Test(IConfigManager configManager)\n {\n _config = configManager; \n }\n\n public void methodToTest()\n {\n //do something important with ConfigManager.FooSetting\n var important = _config.FooSetting;\n return important;\n }\n }\n\n [TestClass]\n public class When_doing_something_important\n {\n [TestMethod]\n public void Should_use_configuration_values()\n {\n IConfigManager fake = new FakeConfigurationManager();\n //setup state\n fake.FooSetting = \"foo\";\n var sut = new Class2Test(fake);\n Assert.AreEqual(\"foo\", sut.methodToTest());\n }\n }\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/130730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3957/"
] |
130,734
|
<p>It's been a while since I've had to do any HTML-like code in <code>Vim</code>, but recently I came across this again. Say I'm writing some simple <code>HTML</code>:</p>
<pre><code><html><head><title>This is a title</title></head></html>
</code></pre>
<p>How do I write those closing tags for title, head and html down quickly? I feel like I'm missing some really simple way here that does not involve me going through writing them all down one by one.</p>
<p>Of course I can use <kbd>Ctrl</kbd><kbd>P</kbd> to autocomplete the individual tag names but what gets me on my laptop keyboard is actually getting the brackets and slash right.</p>
|
[
{
"answer_id": 130741,
"author": "Ian P",
"author_id": 10853,
"author_profile": "https://Stackoverflow.com/users/10853",
"pm_score": 6,
"selected": true,
"text": "Functions and mappings to close open HTML/XML tags\n"
},
{
"answer_id": 134990,
"author": "hakamadare",
"author_id": 17597,
"author_profile": "https://Stackoverflow.com/users/17597",
"pm_score": 6,
"selected": false,
"text": "<p> > <p></p> > <p>> <p> </p> %!"
},
{
"answer_id": 532656,
"author": "sjh",
"author_id": 64591,
"author_profile": "https://Stackoverflow.com/users/64591",
"pm_score": 6,
"selected": false,
"text": "imap ,/ </<C-X><C-O>\n"
},
{
"answer_id": 4439015,
"author": "thanthese",
"author_id": 412407,
"author_profile": "https://Stackoverflow.com/users/412407",
"pm_score": 5,
"selected": false,
"text": "ul > li.item-$*3 <ul>\n <li class=\"item-1\"></li>\n <li class=\"item-2\"></li>\n <li class=\"item-3\"></li>\n</ul>\n <C-e> html > head > title{This is a title}\n <html>\n <head>\n <title>This is a title</title>\n </head>\n</html>\n"
},
{
"answer_id": 8424959,
"author": "Preet Kukreti",
"author_id": 1086804,
"author_profile": "https://Stackoverflow.com/users/1086804",
"pm_score": 4,
"selected": false,
"text": "1. Expand Abbreviation\n\n Type abbreviation as 'div>p#foo$*3>a' and type '<c-y>,'.\n ---------------------\n <div>\n <p id=\"foo1\">\n <a href=\"\"></a>\n </p>\n <p id=\"foo2\">\n <a href=\"\"></a>\n </p>\n <p id=\"foo3\">\n <a href=\"\"></a>\n </p>\n </div>\n ---------------------\n\n2. Wrap with Abbreviation\n\n Write as below.\n ---------------------\n test1\n test2\n test3\n ---------------------\n Then do visual select(line wize) and type '<c-y>,'.\n If you request 'Tag:', then type 'ul>li*'.\n ---------------------\n <ul>\n <li>test1</li>\n <li>test2</li>\n <li>test3</li>\n </ul>\n ---------------------\n\n...\n\n12. Make anchor from URL\n\n Move cursor to URL\n ---------------------\n http://www.google.com/\n ---------------------\n Type '<c-y>a'\n ---------------------\n <a href=\"http://www.google.com/\">Google</a>\n ---------------------\n"
},
{
"answer_id": 11925400,
"author": "Keith Pinson",
"author_id": 834176,
"author_profile": "https://Stackoverflow.com/users/834176",
"pm_score": 4,
"selected": false,
"text": "closetag.vim inoremap ><Tab> ><Esc>F<lyt>o</<C-r>\"><Esc>O<Space>\n <p>[Tab]\n <p>\n |\n</p>\n | inoremap ><Tab> ><Esc> F< l yt> o</ <C-r>\" \" ><Esc> O<Space>"
},
{
"answer_id": 13086685,
"author": "mloskot",
"author_id": 151641,
"author_profile": "https://Stackoverflow.com/users/151641",
"pm_score": 3,
"selected": false,
"text": ":iabbrev </ </<C-X><C-O> autocmd FileType xml set omnifunc=xmlcomplete#CompleteTags"
},
{
"answer_id": 39022513,
"author": "Nick Erhardt",
"author_id": 6619924,
"author_profile": "https://Stackoverflow.com/users/6619924",
"pm_score": 3,
"selected": false,
"text": "filename.html.erb some_file.html.erb <p>Year: <%= @year %><p> .html.erb inoremap ><Tab> ><Esc>?<[a-z]<CR>lyiwo</<C-r>\"><Esc>O\n <div class=\"foo\">[Tab]\n <div class=\"foo\">\n |\n<div>\n | inoremap ><Tab> ><Esc>?<[a-z]<CR>lyiwh/[^%]><CR>la</<C-r>\"><Esc>F<i\n <div class=\"foo\">[Tab]\n <div class=\"foo\">|<div>\n | >[Tab] >[Tab] >>"
},
{
"answer_id": 42428601,
"author": "Sheharyar",
"author_id": 1533054,
"author_profile": "https://Stackoverflow.com/users/1533054",
"pm_score": 4,
"selected": false,
"text": "vim-closetag vundle README <table|\n <table>|</table>\n <table>\n |\n</table>\n |"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/130734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10098/"
] |
130,740
|
<p>I have the following program:</p>
<pre><code>~/test> cat test.cc
int main()
{
int i = 3;
int j = __sync_add_and_fetch(&i, 1);
return 0;
}
</code></pre>
<p>I'm compiling this program using GCC 4.2.2 on Linux running on a multi-cpu 64-bit Intel machine:</p>
<pre><code>~/test> uname --all
Linux doom 2.6.9-67.ELsmp #1 SMP Wed Nov 7 13:56:44 EST 2007 x86_64 x86_64 x86_64 GNU/Linux
</code></pre>
<p>When I compile the program in 64-bit mode, it compiles and links fine:</p>
<pre><code>~/test> /share/tools/gcc-4.2.2/bin/g++ test.cc
~/test>
</code></pre>
<p>When I compile it in 32-bit mode, I get the following error:</p>
<pre><code>~/test> /share/tools/gcc-4.2.2/bin/g++ -m32 test.cc
/tmp/ccEVHGkB.o(.text+0x27): In function `main':
: undefined reference to `__sync_add_and_fetch_4'
collect2: ld returned 1 exit status
~/test>
</code></pre>
<p>Although I will never actually run on a 32-bit processor, I do need a 32-bit executable so I can link with some 32-bit libraries.</p>
<p>My 2 questions are:</p>
<ol>
<li><p>Why do I get a link error when I compile in 32-bit mode?</p></li>
<li><p>Is there some way to get the program to compile and link, while still being able to link with a 32-bit library?</p></li>
</ol>
|
[
{
"answer_id": 130754,
"author": "Dan Udey",
"author_id": 21450,
"author_profile": "https://Stackoverflow.com/users/21450",
"pm_score": 5,
"selected": true,
"text": "__sync_add_and_fetch_4"
},
{
"answer_id": 130813,
"author": "Bruno Rijsman",
"author_id": 21435,
"author_profile": "https://Stackoverflow.com/users/21435",
"pm_score": 5,
"selected": false,
"text": "~/test> /share/tools/gcc-4.2.2/bin/g++ -m32 test.cc\n/tmp/ccYnYLj6.o(.text+0x27): In function `main':\n: undefined reference to `__sync_add_and_fetch_4'\ncollect2: ld returned 1 exit status\n\n~/test> /share/tools/gcc-4.2.2/bin/g++ -m32 -march=i386 test.cc\n/tmp/ccOr3ww8.o(.text+0x22): In function `main':\n: undefined reference to `__sync_add_and_fetch_4'\ncollect2: ld returned 1 exit status\n\n~/test> /share/tools/gcc-4.2.2/bin/g++ -m32 -march=i486 test.cc\n\n~/test> /share/tools/gcc-4.2.2/bin/g++ -m32 -march=pentium test.cc\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/130740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21435/"
] |
130,748
|
<p>I've got a form where I have two radio buttons and two interchangeable controls (made up of a ListView and a handful of buttons). Based on which radio button is selected I want to display the proper control to the user.</p>
<p>The way I'm doing this now is just loading both controls and setting up an OnRadioButtonSelectionChanged() method which gets called at form load (to set the initial state) and at any time the selection is changed. This method just sets the visible property on each control to the proper value.</p>
<p>This seems to work well enough, but I was curious as to if there was a better or more common way of doing it?</p>
|
[
{
"answer_id": 130805,
"author": "Lloyd Cotten",
"author_id": 21807,
"author_profile": "https://Stackoverflow.com/users/21807",
"pm_score": 3,
"selected": true,
"text": "private void OnRadioButtonCheckedChanged(object sender, EventArgs e)\n{\n Control1.Visible = RadioButton1.Checked;\n Control2.Visible = RadioButton2.Checked;\n}\n"
},
{
"answer_id": 170638,
"author": "Andrei Rînea",
"author_id": 1796,
"author_profile": "https://Stackoverflow.com/users/1796",
"pm_score": 2,
"selected": false,
"text": "private void Form1_Load(object sender, EventArgs e)\n{\n txtA.DataBindings.Add(\"Visible\", rbA, \"Checked\");\n txtB.DataBindings.Add(\"Visible\", rbB, \"Checked\");\n}\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/130748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1512/"
] |
130,753
|
<p>On Sql Server 2000, is there a way to find out the date and time when a stored procedure was last executed? </p>
|
[
{
"answer_id": 130758,
"author": "Ben Hoffstein",
"author_id": 4482,
"author_profile": "https://Stackoverflow.com/users/4482",
"pm_score": 5,
"selected": false,
"text": "declare @proc_nm sysname\n\n-- select the procedure name here\nset @proc_nm = 'usp_test'\n\nselect s.last_execution_time\nfrom sys.dm_exec_query_stats s\ncross apply sys.dm_exec_query_plan (s.plan_handle) p\nwhere object_name(p.objectid, db_id('AdventureWorks')) = @proc_nm \n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/130753",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3294/"
] |
130,763
|
<p>I want my Python script to copy files on Vista. When I run it from a normal <code>cmd.exe</code> window, no errors are generated, yet the files are NOT copied. If I run <code>cmd.exe</code> "as administator" and then run my script, it works fine.</p>
<p>This makes sense since User Account Control (UAC) normally prevents many file system actions.</p>
<p>Is there a way I can, from within a Python script, invoke a UAC elevation request (those dialogs that say something like "such and such app needs admin access, is this OK?")</p>
<p>If that's not possible, is there a way my script can at least detect that it is not elevated so it can fail gracefully?</p>
|
[
{
"answer_id": 138970,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 0,
"selected": false,
"text": "runas /user:Administrator \"python your_script.py\"\n"
},
{
"answer_id": 11746382,
"author": "Jorenko",
"author_id": 7161,
"author_profile": "https://Stackoverflow.com/users/7161",
"pm_score": 6,
"selected": false,
"text": "import os\nimport sys\nimport win32com.shell.shell as shell\nASADMIN = 'asadmin'\n\nif sys.argv[-1] != ASADMIN:\n script = os.path.abspath(sys.argv[0])\n params = ' '.join([script] + sys.argv[1:] + [ASADMIN])\n shell.ShellExecuteEx(lpVerb='runas', lpFile=sys.executable, lpParameters=params)\n sys.exit(0)\n"
},
{
"answer_id": 32230199,
"author": "KenV99",
"author_id": 3697388,
"author_profile": "https://Stackoverflow.com/users/3697388",
"pm_score": 3,
"selected": false,
"text": "import pythoncom\nfrom win32com.shell import shell,shellcon\n\ndef copy(src,dst,flags=shellcon.FOF_NOCONFIRMATION):\n \"\"\" Copy files using the built in Windows File copy dialog\n\n Requires absolute paths. Does NOT create root destination folder if it doesn't exist.\n Overwrites and is recursive by default \n @see http://msdn.microsoft.com/en-us/library/bb775799(v=vs.85).aspx for flags available\n \"\"\"\n # @see IFileOperation\n pfo = pythoncom.CoCreateInstance(shell.CLSID_FileOperation,None,pythoncom.CLSCTX_ALL,shell.IID_IFileOperation)\n\n # Respond with Yes to All for any dialog\n # @see http://msdn.microsoft.com/en-us/library/bb775799(v=vs.85).aspx\n pfo.SetOperationFlags(flags)\n\n # Set the destionation folder\n dst = shell.SHCreateItemFromParsingName(dst,None,shell.IID_IShellItem)\n\n if type(src) not in (tuple,list):\n src = (src,)\n\n for f in src:\n item = shell.SHCreateItemFromParsingName(f,None,shell.IID_IShellItem)\n pfo.CopyItem(item,dst) # Schedule an operation to be performed\n\n # @see http://msdn.microsoft.com/en-us/library/bb775780(v=vs.85).aspx\n success = pfo.PerformOperations()\n\n # @see sdn.microsoft.com/en-us/library/bb775769(v=vs.85).aspx\n aborted = pfo.GetAnyOperationsAborted()\n return success is None and not aborted \n"
},
{
"answer_id": 34216774,
"author": "Berwyn",
"author_id": 1232094,
"author_profile": "https://Stackoverflow.com/users/1232094",
"pm_score": 2,
"selected": false,
"text": "def spawn_as_administrator():\n \"\"\" Spawn ourself with administrator rights and wait for new process to exit\n Make the new process use the same console as the old one.\n Raise Exception() if we could not get a handle for the new re-run the process\n Raise pywintypes.error() if we could not re-spawn\n Return the exit code of the new process,\n or return None if already running the second admin process. \"\"\"\n #pylint: disable=no-name-in-module,import-error\n import win32event, win32api, win32process\n import win32com.shell.shell as shell\n if '--admin' in sys.argv:\n return None\n script = os.path.abspath(sys.argv[0])\n params = ' '.join([script] + sys.argv[1:] + ['--admin'])\n SEE_MASK_NO_CONSOLE = 0x00008000\n SEE_MASK_NOCLOSE_PROCESS = 0x00000040\n process = shell.ShellExecuteEx(lpVerb='runas', lpFile=sys.executable, lpParameters=params, fMask=SEE_MASK_NO_CONSOLE|SEE_MASK_NOCLOSE_PROCESS)\n hProcess = process['hProcess']\n if not hProcess:\n raise Exception(\"Could not identify administrator process to install drivers\")\n # It is necessary to wait for the elevated process or else\n # stdin lines are shared between 2 processes: they get one line each\n INFINITE = -1\n win32event.WaitForSingleObject(hProcess, INFINITE)\n exitcode = win32process.GetExitCodeProcess(hProcess)\n win32api.CloseHandle(hProcess)\n return exitcode\n"
},
{
"answer_id": 41930586,
"author": "Martín De la Fuente",
"author_id": 6535374,
"author_profile": "https://Stackoverflow.com/users/6535374",
"pm_score": 8,
"selected": true,
"text": "import ctypes, sys\n\ndef is_admin():\n try:\n return ctypes.windll.shell32.IsUserAnAdmin()\n except:\n return False\n\nif is_admin():\n # Code of your program here\nelse:\n # Re-run the program with admin rights\n ctypes.windll.shell32.ShellExecuteW(None, \"runas\", sys.executable, \" \".join(sys.argv), None, 1)\n ctypes.windll.shell32.ShellExecuteW(None, u\"runas\", unicode(sys.executable), unicode(\" \".join(sys.argv)), None, 1)\n py2exe cx_freeze pyinstaller sys.argv[1:] sys.argv ctypes sys"
},
{
"answer_id": 42787518,
"author": "Noctis Skytower",
"author_id": 216356,
"author_profile": "https://Stackoverflow.com/users/216356",
"pm_score": 3,
"selected": false,
"text": "sys.argv[0] subprocess.list2cmdline(sys.argv) #! /usr/bin/env python3\nimport ctypes\nimport enum\nimport subprocess\nimport sys\n\n# Reference:\n# msdn.microsoft.com/en-us/library/windows/desktop/bb762153(v=vs.85).aspx\n\n\n# noinspection SpellCheckingInspection\nclass SW(enum.IntEnum):\n HIDE = 0\n MAXIMIZE = 3\n MINIMIZE = 6\n RESTORE = 9\n SHOW = 5\n SHOWDEFAULT = 10\n SHOWMAXIMIZED = 3\n SHOWMINIMIZED = 2\n SHOWMINNOACTIVE = 7\n SHOWNA = 8\n SHOWNOACTIVATE = 4\n SHOWNORMAL = 1\n\n\nclass ERROR(enum.IntEnum):\n ZERO = 0\n FILE_NOT_FOUND = 2\n PATH_NOT_FOUND = 3\n BAD_FORMAT = 11\n ACCESS_DENIED = 5\n ASSOC_INCOMPLETE = 27\n DDE_BUSY = 30\n DDE_FAIL = 29\n DDE_TIMEOUT = 28\n DLL_NOT_FOUND = 32\n NO_ASSOC = 31\n OOM = 8\n SHARE = 26\n\n\ndef bootstrap():\n if ctypes.windll.shell32.IsUserAnAdmin():\n main()\n else:\n # noinspection SpellCheckingInspection\n hinstance = ctypes.windll.shell32.ShellExecuteW(\n None,\n 'runas',\n sys.executable,\n subprocess.list2cmdline(sys.argv),\n None,\n SW.SHOWNORMAL\n )\n if hinstance <= 32:\n raise RuntimeError(ERROR(hinstance))\n\n\ndef main():\n # Your Code Here\n print(input('Echo: '))\n\n\nif __name__ == '__main__':\n bootstrap()\n"
},
{
"answer_id": 49759083,
"author": "Orsiris de Jong",
"author_id": 2635443,
"author_profile": "https://Stackoverflow.com/users/2635443",
"pm_score": 2,
"selected": false,
"text": "__file__ sys.argv[0] pip install command_runner from command_runner.elevate import elevate\n\ndef main():\n \"\"\"My main function that should be elevated\"\"\"\n print(\"Who's the administrator, now ?\")\n\nif __name__ == '__main__':\n elevate(main)\n import sys,ctypes,platform\n\ndef is_admin():\n try:\n return ctypes.windll.shell32.IsUserAnAdmin()\n except:\n raise False\n\nif __name__ == '__main__':\n\n if platform.system() == \"Windows\":\n if is_admin():\n main(sys.argv[1:])\n else:\n # Re-run the program with admin rights, don't use __file__ since py2exe won't know about it\n # Use sys.argv[0] as script path and sys.argv[1:] as arguments, join them as lpstr, quoting each parameter or spaces will divide parameters\n lpParameters = \"\"\n # Litteraly quote all parameters which get unquoted when passed to python\n for i, item in enumerate(sys.argv[0:]):\n lpParameters += '\"' + item + '\" '\n try:\n ctypes.windll.shell32.ShellExecuteW(None, \"runas\", sys.executable, lpParameters , None, 1)\n except:\n sys.exit(1)\n else:\n main(sys.argv[1:])\n"
},
{
"answer_id": 58513700,
"author": "Irving Moy",
"author_id": 4505578,
"author_profile": "https://Stackoverflow.com/users/4505578",
"pm_score": 4,
"selected": false,
"text": "elevate"
},
{
"answer_id": 72732324,
"author": "BaiJiFeiLong",
"author_id": 5254103,
"author_profile": "https://Stackoverflow.com/users/5254103",
"pm_score": 1,
"selected": false,
"text": "import ctypes, sys\n\nctypes.windll.shell32.IsUserAnAdmin() or ctypes.windll.shell32.ShellExecuteW(\n None, \"runas\", sys.executable, \" \".join(sys.argv), None, 1) > 32 and exit()\n\n\n import ctypes, sys\n\nctypes.windll.shell32.IsUserAnAdmin() or (ctypes.windll.shell32.ShellExecuteW(\n None, \"runas\", sys.executable, \" \".join(sys.argv), None, 1) > 32, exit())\n # Created by BaiJiFeiLong@gmail.com at 2022/6/24\nimport ctypes\nimport sys\n\n\ndef request_uac_or_skip():\n ctypes.windll.shell32.IsUserAnAdmin() or ctypes.windll.shell32.ShellExecuteW(\n None, \"runas\", sys.executable, \" \".join(sys.argv), None, 1) > 32 and sys.exit()\n\n\ndef request_uac_or_exit():\n ctypes.windll.shell32.IsUserAnAdmin() or (ctypes.windll.shell32.ShellExecuteW(\n None, \"runas\", sys.executable, \" \".join(sys.argv), None, 1) > 32, sys.exit())\n\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/130763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10559/"
] |
130,775
|
<p>As far as variable naming conventions go, should iterators be named <code>i</code> or something more semantic like <code>count</code>? If you don't use <code>i</code>, why not? If you feel that <code>i</code> is acceptable, are there cases of iteration where it shouldn't be used?</p>
|
[
{
"answer_id": 130807,
"author": "Ian P",
"author_id": 10853,
"author_profile": "https://Stackoverflow.com/users/10853",
"pm_score": 3,
"selected": false,
"text": "foreach (Product p in ProductList)\n{\n // Do something with p\n}\n"
},
{
"answer_id": 130810,
"author": "Josh",
"author_id": 11702,
"author_profile": "https://Stackoverflow.com/users/11702",
"pm_score": 6,
"selected": true,
"text": "for(int i = 0; i < 10; i++)\n{\n // i is well known here to be the index\n objectCollection[i].SomeProperty = someValue;\n}\n for(int currentRow = 0; currentRow < numRows; currentRow++)\n{\n for(int currentCol = 0; currentCol < numCols; currentCol++)\n {\n someTable[currentRow][currentCol] = someValue;\n }\n} \n"
},
{
"answer_id": 130811,
"author": "Dan Udey",
"author_id": 21450,
"author_profile": "https://Stackoverflow.com/users/21450",
"pm_score": 0,
"selected": false,
"text": "i filecounter"
},
{
"answer_id": 130812,
"author": "Clinton Dreisbach",
"author_id": 6262,
"author_profile": "https://Stackoverflow.com/users/6262",
"pm_score": 2,
"selected": false,
"text": "i"
},
{
"answer_id": 130833,
"author": "Andrew Edgecombe",
"author_id": 11694,
"author_profile": "https://Stackoverflow.com/users/11694",
"pm_score": 0,
"selected": false,
"text": "filecounter i i for i"
},
{
"answer_id": 131045,
"author": "MusiGenesis",
"author_id": 14606,
"author_profile": "https://Stackoverflow.com/users/14606",
"pm_score": 2,
"selected": false,
"text": "for (int i = 0; i < 10; i++)\n{\n for (int j = 0; j < 10; j++)\n {\n string s = datarow[i][j].ToString(); // or worse\n }\n}\n"
},
{
"answer_id": 131087,
"author": "Giovanni Galbo",
"author_id": 4050,
"author_profile": "https://Stackoverflow.com/users/4050",
"pm_score": 2,
"selected": false,
"text": "foreach(Input i in inputs)\n{\n Process(i);\n\n}\n"
},
{
"answer_id": 132611,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "foreach(DataRow dr in datatable.Rows)\n{\n //do stuff to/with datarow dr here\n}\n"
},
{
"answer_id": 134450,
"author": "just mike",
"author_id": 12293,
"author_profile": "https://Stackoverflow.com/users/12293",
"pm_score": 0,
"selected": false,
"text": "// recommended style ● // \"typical\" single-letter style\n ●\nfor (ii=0; ii<10; ++ii) { ● for (i=0; i<10; ++i) {\n for (jj=0; jj<10; ++jj) { ● for (j=0; j<10; ++j) {\n mm[ii][jj] = ii * jj; ● m[i][j] = i * j;\n } ● }\n} ● } i"
},
{
"answer_id": 4089959,
"author": "JohnFx",
"author_id": 30018,
"author_profile": "https://Stackoverflow.com/users/30018",
"pm_score": -1,
"selected": false,
"text": "for(int i = 0; i < 10; i++)\n{\n // i is well known here to be the index\n objectCollection[i].SomeProperty = someValue;\n}\n for(int objectCollectionIndex = 0; objectCollectionIndex < 10; objectCollectionIndex ++)\n{\n objectCollection[objectCollectionIndex].SomeProperty = someValue;\n}\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/130775",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13281/"
] |
130,789
|
<p>I heard that decision tables in relational database have been researched a lot in academia. I also know that business rules engines use decision tables and that many BPMS use them as well.
I was wondering if people today use decision tables within their relational databases?</p>
|
[
{
"answer_id": 132483,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 2,
"selected": true,
"text": "def decision_table( aRow ):\n result= connection.execute( \"SELECT replacement_value FROM transformation WHERE old_value = ?\", aRow['somecolumn'] )\n replacement= result.fetchone()\n aRow['anotherColumn']= result['replacement_value']\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/130789",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19272/"
] |
130,790
|
<p>I have some C# code in an ASP.Net application that does this:</p>
<p>Bitmap bmp = new Bitmap(1184, 1900);</p>
<p>And occasionally it throws an exception "Parameter is not valid". Now i've been googling around and apparently GDI+ is infamous for throwing random exceptions, and lots of people have had this problem, but nobody has a solution to it! I've checked the system and it has plenty of both RAM and swap space.
Now in the past if i do an 'iisreset' then the problem goes away, but it comes back in a few days. But i'm not convinced i've caused a memory leak, because as i say above there is plenty of ram+swap free.</p>
<p>Anyone have any solutions?</p>
|
[
{
"answer_id": 170946,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 3,
"selected": false,
"text": "using System.Windows.Media.Imaging;\nclass Program {\n public static void Main(string[] args) {\n var bmp = new WriteableBitmap(1184, 1900, 96.0, 96.0, PixelFormat.Bgr32, null);\n }\n}\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/130790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
130,794
|
<p>There have been several questions already posted with specific questions about <a href="http://en.wikipedia.org/wiki/Dependency_injection" rel="noreferrer">dependency injection</a>, such as when to use it and what frameworks are there for it. However,</p>
<p><strong>What is dependency injection and when/why should or shouldn't it be used?</strong></p>
|
[
{
"answer_id": 130862,
"author": "wds",
"author_id": 10098,
"author_profile": "https://Stackoverflow.com/users/10098",
"pm_score": 12,
"selected": true,
"text": "SomeClass() public SomeClass() {\n myObject = Factory.getObject();\n}\n myObject SomeClass() myObject myObject public SomeClass (MyClass myObject) {\n this.myObject = myObject;\n}\n myObject"
},
{
"answer_id": 131766,
"author": "Adam Ness",
"author_id": 21973,
"author_profile": "https://Stackoverflow.com/users/21973",
"pm_score": 8,
"selected": false,
"text": "public class PersonService {\n public void addManager( Person employee, Person newManager ) { ... }\n public void removeManager( Person employee, Person oldManager ) { ... }\n public Group getGroupByManager( Person manager ) { ... }\n}\n\npublic class GroupMembershipService() {\n public void addPersonToGroup( Person person, Group group ) { ... }\n public void removePersonFromGroup( Person person, Group group ) { ... }\n} \n PersonService::addManager PersonService::removeManager GroupMembershipService GroupMembershipService PersonService GroupMembershipService GroupMembershipService PersonService GroupMembershipService GroupMembershipService GroupMembershipService PersonService GroupMembershipService GroupMembershipService PersonService PersonService PersonService GroupMembershipService GroupMembershipService GroupMembershipService PersonService PersonService"
},
{
"answer_id": 6085922,
"author": "gtiwari333",
"author_id": 607637,
"author_profile": "https://Stackoverflow.com/users/607637",
"pm_score": 10,
"selected": false,
"text": "Car Car Car class Car{\n private Wheel wh = new NepaliRubberWheel();\n private Battery bt = new ExcideBattery();\n\n //The rest\n}\n Car Wheel NepaliRubberWheel() ChineseRubberWheel() Car Dependency Injection Wheel dependency wheel Car class Car{\n private Wheel wh; // Inject an Instance of Wheel (dependency of car) at runtime\n private Battery bt; // Inject an Instance of Battery (dependency of car) at runtime\n Car(Wheel wh,Battery bt) {\n this.wh = wh;\n this.bt = bt;\n }\n //Or we can have setters\n void setWheel(Wheel wh) {\n this.wh = wh;\n }\n}\n"
},
{
"answer_id": 16328631,
"author": "JaneGoodall",
"author_id": 2167210,
"author_profile": "https://Stackoverflow.com/users/2167210",
"pm_score": 6,
"selected": false,
"text": "public class Example { \n private DatabaseThingie myDatabase; \n\n public Example() { \n myDatabase = new DatabaseThingie(); \n } \n\n public void doStuff() { \n ... \n myDatabase.getData(); \n ... \n } \n} \n public class Example { \n private DatabaseThingie myDatabase; \n\n public Example(DatabaseThingie useThisDatabaseInstead) { \n myDatabase = useThisDatabaseInstead; \n }\n\n public void doStuff() { \n ... \n myDatabase.getData(); \n ... \n } \n}\n"
},
{
"answer_id": 18964312,
"author": "uvsmtid",
"author_id": 441652,
"author_profile": "https://Stackoverflow.com/users/441652",
"pm_score": 5,
"selected": false,
"text": "source import dependent.sh #!/bin/sh\n# Dependent\ntouch \"one.txt\" \"two.txt\"\narchive_files \"one.txt\" \"two.txt\"\n archive_files archive_files archive_files_zip.sh zip #!/bin/sh\n# Dependency\nfunction archive_files {\n zip files.zip \"$@\"\n}\n source injector.sh #!/bin/sh \n# Injector\nsource ./archive_files_zip.sh\nsource ./dependent.sh\n archive_files archive_files tar xz dependent.sh #!/bin/sh\n# Dependent\n\n# dependency look-up\nsource ./archive_files_zip.sh\n\ntouch \"one.txt\" \"two.txt\"\narchive_files \"one.txt\" \"two.txt\"\n"
},
{
"answer_id": 20970795,
"author": "Piyush Deshpande",
"author_id": 2394846,
"author_profile": "https://Stackoverflow.com/users/2394846",
"pm_score": 4,
"selected": false,
"text": "public class Person {\n public Person() {}\n\n public IDAO Address {\n set { addressdao = value; }\n get {\n if (addressdao == null)\n throw new MemberAccessException(\"addressdao\" +\n \" has not been initialized\");\n return addressdao;\n }\n }\n\n public Address GetAddress() {\n // ... code that uses the addressdao object\n // to fetch address details from the datasource ...\n }\n\n // Should not be called directly;\n // use the public property instead\n private IDAO addressdao;\n"
},
{
"answer_id": 26889535,
"author": "Alex",
"author_id": 1187785,
"author_profile": "https://Stackoverflow.com/users/1187785",
"pm_score": 3,
"selected": false,
"text": "public class MyDao {\n\n protected DataSource dataSource = new DataSourceImpl(\n \"driver\", \"url\", \"user\", \"password\");\n\n //data access methods...\n public Person readPerson(int primaryKey) {...} \n}\n public class MyDao {\n\n protected DataSource dataSource = null;\n\n public MyDao(String driver, String url, String user, String password) {\n this.dataSource = new DataSourceImpl(driver, url, user, password);\n }\n\n //data access methods...\n public Person readPerson(int primaryKey) {...}\n}\n DataSourceImpl DataSourceImpl MyDao MyDao"
},
{
"answer_id": 29929112,
"author": "StuartLC",
"author_id": 314291,
"author_profile": "https://Stackoverflow.com/users/314291",
"pm_score": 5,
"selected": false,
"text": "DI D SOLID interface abstract class pure virtual class \"I need to create/use a Foo and invoke method `GetBar()`\"\n Foo \"I need to invoke something which offers `GetBar()`\"\n Create MyDepClass public class MyLogger\n{\n public void LogRecord(string somethingToLog)\n {\n Console.WriteLine(\"{0:HH:mm:ss} - {1}\", DateTime.Now, somethingToLog);\n }\n}\n static System.DateTime System.Console DIP MyLogger public interface IClock\n{\n DateTime Now { get; }\n}\n Console TextWriter constructor Setter Injection setXyz() {set;} readonly final public class MyLogger : ILogger // Others will depend on our logger.\n{\n private readonly TextWriter _output;\n private readonly IClock _clock;\n\n // Dependencies are injected through the constructor\n public MyLogger(TextWriter stream, IClock clock)\n {\n _output = stream;\n _clock = clock;\n }\n\n public void LogRecord(string somethingToLog)\n {\n // We can now use our dependencies through the abstraction \n // and without knowledge of the lifespans of the dependencies\n _output.Write(\"{0:yyyy-MM-dd HH:mm:ss} - {1}\", _clock.Now, somethingToLog);\n }\n}\n Clock DateTime.Now [Test]\npublic void LoggingMustRecordAllInformationAndStampTheTime()\n{\n // Arrange\n var mockClock = new Mock<IClock>();\n mockClock.Setup(c => c.Now).Returns(new DateTime(2015, 4, 11, 12, 31, 45));\n var fakeConsole = new StringWriter();\n\n // Act\n new MyLogger(fakeConsole, mockClock.Object)\n .LogRecord(\"Foo\");\n\n // Assert\n Assert.AreEqual(\"2015-04-11 12:31:45 - Foo\", fakeConsole.ToString());\n}\n IoC IBar ConcreteBar IDisposable Disposing new new ..() new"
},
{
"answer_id": 30603464,
"author": "Phil Goetz",
"author_id": 1122081,
"author_profile": "https://Stackoverflow.com/users/1122081",
"pm_score": 3,
"selected": false,
"text": "$foo = Foo->new($bar);\n gcc -c foo.cpp; gcc -c bar.cpp\n gcc foo.o bar.o -o bar\n"
},
{
"answer_id": 32679456,
"author": "hariprasad",
"author_id": 3632455,
"author_profile": "https://Stackoverflow.com/users/3632455",
"pm_score": 2,
"selected": false,
"text": "package com.deepam.hidden;\n\npublic interface BookInterface {\n\npublic BookInterface setHeight(int height);\npublic BookInterface setPages(int pages); \npublic int getHeight();\npublic int getPages(); \n\npublic String toString();\n}\n package com.deepam.hidden;\n\npublic class FictionBook implements BookInterface {\nint height = 0; // height in cm\nint pages = 0; // number of pages\n\n/** constructor */\npublic FictionBook() {\n // TODO Auto-generated constructor stub\n}\n\n@Override\npublic FictionBook setHeight(int height) {\n this.height = height;\n return this;\n}\n\n@Override\npublic FictionBook setPages(int pages) {\n this.pages = pages;\n return this; \n}\n\n@Override\npublic int getHeight() {\n // TODO Auto-generated method stub\n return height;\n}\n\n@Override\npublic int getPages() {\n // TODO Auto-generated method stub\n return pages;\n}\n\n@Override\npublic String toString(){\n return (\"height: \" + height + \", \" + \"pages: \" + pages);\n}\n}\n package com.deepam.hidden;\n\nimport java.lang.reflect.Constructor;\nimport java.lang.reflect.InvocationTargetException;\n\npublic class Subscriber {\nBookInterface book;\n\n/** constructor*/\npublic Subscriber() {\n // TODO Auto-generated constructor stub\n}\n\n// injection I\npublic void setBook(BookInterface book) {\n this.book = book;\n}\n\n// injection II\npublic BookInterface setBook(String bookName) {\n try {\n Class<?> cl = Class.forName(bookName);\n Constructor<?> constructor = cl.getConstructor(); // use it for parameters in constructor\n BookInterface book = (BookInterface) constructor.newInstance();\n //book = (BookInterface) Class.forName(bookName).newInstance();\n } catch (InstantiationException e) {\n e.printStackTrace();\n } catch (IllegalAccessException e) {\n e.printStackTrace();\n } catch (ClassNotFoundException e) {\n e.printStackTrace();\n } catch (NoSuchMethodException e) {\n e.printStackTrace();\n } catch (SecurityException e) {\n e.printStackTrace();\n } catch (IllegalArgumentException e) {\n e.printStackTrace();\n } catch (InvocationTargetException e) {\n e.printStackTrace();\n }\n return book;\n}\n\npublic BookInterface getBook() {\n return book;\n}\n\npublic static void main(String[] args) {\n\n}\n\n}\n package com.deepam.implement;\n\nimport com.deepam.hidden.Subscriber;\nimport com.deepam.hidden.FictionBook;\n\npublic class CallHiddenImplBook {\n\npublic CallHiddenImplBook() {\n // TODO Auto-generated constructor stub\n}\n\npublic void doIt() {\n Subscriber ab = new Subscriber();\n\n // injection I\n FictionBook bookI = new FictionBook();\n bookI.setHeight(30); // cm\n bookI.setPages(250);\n ab.setBook(bookI); // inject\n System.out.println(\"injection I \" + ab.getBook().toString());\n\n // injection II\n FictionBook bookII = ((FictionBook) ab.setBook(\"com.deepam.hidden.FictionBook\")).setHeight(5).setPages(108); // inject and set\n System.out.println(\"injection II \" + ab.getBook().toString()); \n}\n\npublic static void main(String[] args) {\n CallHiddenImplBook kh = new CallHiddenImplBook();\n kh.doIt();\n}\n}\n"
},
{
"answer_id": 34081752,
"author": "Harleen",
"author_id": 5527914,
"author_profile": "https://Stackoverflow.com/users/5527914",
"pm_score": 4,
"selected": false,
"text": "public class Triangle {\n\nprivate String type;\n\npublic String getType(){\n return type;\n }\n\npublic Triangle(String type){ //constructor injection\n this.type=type;\n }\n}\n<bean id=triangle\" class =\"com.test.dependencyInjection.Triangle\">\n <constructor-arg value=\"20\"/>\n </bean>\n public class Triangle{\n\n private String type;\n\n public String getType(){\n return type;\n }\n public void setType(String type){ //setter injection\n this.type = type;\n }\n }\n\n<!-- setter injection -->\n <bean id=\"triangle\" class=\"com.test.dependencyInjection.Triangle\">\n <property name=\"type\" value=\"equivialteral\"/>\n"
},
{
"answer_id": 34206179,
"author": "Nikos M.",
"author_id": 3591273,
"author_profile": "https://Stackoverflow.com/users/3591273",
"pm_score": 3,
"selected": false,
"text": ".25"
},
{
"answer_id": 36431786,
"author": "Anwar Husain",
"author_id": 1921855,
"author_profile": "https://Stackoverflow.com/users/1921855",
"pm_score": 4,
"selected": false,
"text": "surgeon who can concentrate on surgery"
},
{
"answer_id": 40312799,
"author": "wakqasahmed",
"author_id": 2314594,
"author_profile": "https://Stackoverflow.com/users/2314594",
"pm_score": 6,
"selected": false,
"text": "Switch(){\nPermanentBulb = new Bulb();\nPermanentBulb.Toggle();\n}\n Switch(AnyBulb){ //pass it whichever bulb you like\nAnyBulb.Toggle();\n}\n public class SwitchTest { \n TestToggleBulb() { \n MockBulb mockbulb = new MockBulb(); \n\n // MockBulb is a subclass of Bulb, so we can \n // \"inject\" it here: \n Switch switch = new Switch(mockBulb); \n\n switch.ToggleBulb(); \n mockBulb.AssertToggleWasCalled(); \n } \n}\n\npublic class Switch { \n private Bulb myBulb; \n\n public Switch() { \n myBulb = new Bulb(); \n } \n\n public Switch(Bulb useThisBulbInstead) { \n myBulb = useThisBulbInstead; \n } \n\n public void ToggleBulb() { \n ... \n myBulb.Toggle(); \n ... \n } \n}`\n"
},
{
"answer_id": 44945310,
"author": "user2771704",
"author_id": 2771704,
"author_profile": "https://Stackoverflow.com/users/2771704",
"pm_score": 8,
"selected": false,
"text": "public class Car\n{\n public Car()\n {\n GasEngine engine = new GasEngine();\n engine.Start();\n }\n}\n\npublic class GasEngine\n{\n public void Start()\n {\n Console.WriteLine(\"I use gas as my fuel!\");\n }\n}\n Car car = new Car();\n public interface IEngine\n {\n void Start();\n }\n\n public class GasEngine : IEngine\n {\n public void Start()\n {\n Console.WriteLine(\"I use gas as my fuel!\");\n }\n }\n\n public class ElectricityEngine : IEngine\n {\n public void Start()\n {\n Console.WriteLine(\"I am electrocar\");\n }\n }\n\n public class Car\n {\n private readonly IEngine _engine;\n public Car(IEngine engine)\n {\n _engine = engine;\n }\n\n public void Run()\n {\n _engine.Start();\n }\n }\n Car gasCar = new Car(new GasEngine());\n gasCar.Run();\n Car electroCar = new Car(new ElectricityEngine());\n electroCar.Run();\n"
},
{
"answer_id": 47090662,
"author": "SAMUEL",
"author_id": 2761513,
"author_profile": "https://Stackoverflow.com/users/2761513",
"pm_score": 5,
"selected": false,
"text": "Public MyClass{\n DependentClass dependentObject\n /*\n At somewhere in our code we need to instantiate \n the object with new operator inorder to use it or perform some method.\n */ \n dependentObject= new DependentClass();\n dependentObject.someMethod();\n}\n Public MyClass{\n /* Dependency injector will instantiate object*/\n DependentClass dependentObject\n\n /*\n At somewhere in our code we perform some method. \n The process of instantiation will be handled by the dependency injector\n */ \n \n dependentObject.someMethod();\n}\n"
},
{
"answer_id": 49269907,
"author": "Linh",
"author_id": 5381331,
"author_profile": "https://Stackoverflow.com/users/5381331",
"pm_score": 4,
"selected": false,
"text": "Client Service Client Service public class Service {\n public void doSomeThingInService() {\n // ...\n }\n}\n public class Client {\n public void doSomeThingInClient() {\n Service service = new Service();\n service.doSomeThingInService();\n }\n}\n public class Client {\n Service service = new Service();\n public void doSomeThingInClient() {\n service.doSomeThingInService();\n }\n}\n public class Client {\n Service service;\n public Client() {\n service = new Service();\n }\n public void doSomeThingInClient() {\n service.doSomeThingInService();\n }\n}\n Client client = new Client();\nclient.doSomeThingInService();\n Client Service Service public class Client {\n Service service;\n\n Client(Service service) {\n this.service = service;\n }\n\n // Example Client has 2 dependency \n // Client(Service service, IDatabas database) {\n // this.service = service;\n // this.database = database;\n // }\n\n public void doSomeThingInClient() {\n service.doSomeThingInService();\n }\n}\n Client client = new Client(new Service());\n// Client client = new Client(new Service(), new SqliteDatabase());\nclient.doSomeThingInClient();\n public class Client {\n Service service;\n\n public void setService(Service service) {\n this.service = service;\n }\n\n public void doSomeThingInClient() {\n service.doSomeThingInService();\n }\n}\n Client client = new Client();\nclient.setService(new Service());\nclient.doSomeThingInClient();\n Dependency Injection Client new Service() Service Injector public class Injector {\n public static Service provideService(){\n return new Service();\n }\n\n public static IDatabase provideDatatBase(){\n return new SqliteDatabase();\n }\n public static ObjectA provideObjectA(){\n return new ObjectA(provideService(...));\n }\n}\n Service service = Injector.provideService();\n Service Constructor Injection Client Client Constructor Injection Service Client Client Service Service Service Service Client"
},
{
"answer_id": 59837213,
"author": "王玉略",
"author_id": 8409280,
"author_profile": "https://Stackoverflow.com/users/8409280",
"pm_score": 1,
"selected": false,
"text": "class Injector {\n constructor() {\n this.dependencies = {};\n this.register = (key, value) => {\n this.dependencies[key] = value;\n };\n }\n resolve(...args) {\n let func = null;\n let deps = null;\n let scope = null;\n const self = this;\n if (typeof args[0] === 'string') {\n func = args[1];\n deps = args[0].replace(/ /g, '').split(',');\n scope = args[2] || {};\n } else {\n func = args[0];\n deps = func.toString().match(/^function\\s*[^\\(]*\\(\\s*([^\\)]*)\\)/m)[1].replace(/ /g, '').split(',');\n scope = args[1] || {};\n }\n return (...args) => {\n func.apply(scope || {}, deps.map(dep => self.dependencies[dep] && dep != '' ? self.dependencies[dep] : args.shift()));\n }\n }\n}\n\ninjector = new Injector();\n\ninjector.register('module1', () => { console.log('hello') });\ninjector.register('module2', () => { console.log('world') });\n\nvar doSomething1 = injector.resolve(function (module1, module2, other) {\n module1();\n module2();\n console.log(other);\n});\ndoSomething1(\"Other\");\n\nconsole.log('--------')\n\nvar doSomething2 = injector.resolve('module1,module2,', function (a, b, c) {\n a();\n b();\n console.log(c);\n});\ndoSomething2(\"Other\");\n"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/130794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1354/"
] |
130,801
|
<p>I'm using GNU autotools for the build system on a particular project. I want to start writing automated tests for verifcation. I would like to just type "make check" to have it automatically run these. My project is in C++, although I am still curious about writing automated tests for other languages as well.</p>
<p><em>Is this compatible with pretty much every unit testing framework out there (I was thinking of using cppunit)? How do I hook these unit testing frameworks into make check? Can I make sure that I don't require the unit test software to be installed to be able to configure and build the rest of the project?</em></p>
|
[
{
"answer_id": 174142,
"author": "jonner",
"author_id": 78437,
"author_profile": "https://Stackoverflow.com/users/78437",
"pm_score": 6,
"selected": true,
"text": "make check TESTS TESTS=my-test-executable\n make check TESTS TESTS=my-first-test my-second-test my-third-test\n"
},
{
"answer_id": 20277301,
"author": "Dongho Yoo",
"author_id": 1309262,
"author_profile": "https://Stackoverflow.com/users/1309262",
"pm_score": 4,
"selected": false,
"text": " configure.ac\n Makefile.am\n src/Makefile.am\n src/foo.c\n tests/check_foo.c\n tests/Makefile.am\n ./configure.ac ./tests/Makefile.am TESTS = check_foo\ncheck_PROGRAMS = check_foo\ncheck_foo_SOURCES = check_foo.c $(top_builddir)/src/foo.h\ncheck_foo_CFLAGS = @CHECK_CFLAGS@\n ./tests/check_foo.c START_TEST (test_foo)\n{\n ck_assert( foo() == 0 );\n ck_assert_int_eq( foo(), 0);\n}\nEND_TEST\n\n/// And there are some tcase_xxx codes to run this test\n"
},
{
"answer_id": 46856458,
"author": "wedesoft",
"author_id": 382784,
"author_profile": "https://Stackoverflow.com/users/382784",
"pm_score": 1,
"selected": false,
"text": "TESTS check_PROGRAMS check_PROGRAMS check_PROGRAMS=testsuite\n\ntestsuite_SOURCES=...\ntestsuite_CFLAGS=...\ntestsuite_LDADD=...\n\ncheck-local:\n ./testsuite\n"
},
{
"answer_id": 60347950,
"author": "Lloyd Rochester",
"author_id": 5005311,
"author_profile": "https://Stackoverflow.com/users/5005311",
"pm_score": 2,
"selected": false,
"text": "#src/Makefile.am\ncheck_PROGRAMS = test1 test2\ntest1_SOURCES = test/test1.c code_needed_to_test1.h code_needed_to_test1.c\ntest2_SOURCES = test/test2.c code_needed_to_test2.h code_needed_to_test2.c\nTESTS = $(check_PROGRAMS)\n make check $ make check\n...\nPASS: test1\nPASS: test2\n============================================================================\nTestsuite summary for foo 1.0\n============================================================================\n# TOTAL: 2\n# PASS: 2\n# SKIP: 0\n# XFAIL: 0\n# FAIL: 0\n# XPASS: 0\n# ERROR: 0\n============================================================================\n make dist src/test/* make distcheck make check"
}
] |
2008/09/25
|
[
"https://Stackoverflow.com/questions/130801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5963/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.