qid int64 4 19.1M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
304,483 | <p>I am writing a text editor which has an option to display a bullet in place of any invisible Unicode character. Unfortunately there appears to be no easy way to determine whether a Unicode character is invisible.</p>
<p>I need to find a text file containing every Unicode character in order that I can look through for invisible characters. Would anyone know where I can find such a file?</p>
<p>EDIT: I am writing this app in Cocoa for Mac OS X.</p>
| [
{
"answer_id": 304504,
"author": "Jason Coco",
"author_id": 34218,
"author_profile": "https://Stackoverflow.com/users/34218",
"pm_score": 3,
"selected": true,
"text": "NSCharacterSet* controlChars = [NSCharacterSet controlCharacterSet];\n unichar theChar = 0x000D;\nNSString* thestring = [NSStirng stringWithCharacters:&theChar length:1];\n"
},
{
"answer_id": 304725,
"author": "Jason Coco",
"author_id": 34218,
"author_profile": "https://Stackoverflow.com/users/34218",
"pm_score": 1,
"selected": false,
"text": "-(NSString*)stringByReplacingControlCharacters:(NSString*)originalString\n{\n NSUInteger length = [originalString length];\n unichar *strAsUnichar = (unichar*)malloc(length*sizeof(unichar));\n NSCharacterSet* controlChars = [NSCharacterSet controlCharacterSet];\n unichar bullet = 0x2022;\n\n [originalString getCharacters:strAsUnichar];\n for( NSUInteger i = 0; i < length; i++ ) {\n if( [controlChars characterIsMember:strAsUnichar[i]] )\n strAsUnichar[i] = bullet;\n }\n\n NSString* newString = [NSString stringWithCharacters:strAsUnichar length:length];\n free(strAsUnichar);\n\n return newString;\n}\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18091/"
] |
304,491 | <p>How do I check if a field (textbox) is empty or filled only with white spaces (spaces/enters/tabs etc.), using javascript RegExp?</p>
| [
{
"answer_id": 304500,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 4,
"selected": false,
"text": "if (myField.value.match(/\\S/)) {\n // field is not empty\n}\n// or\nif (/\\S/.test(myField.value)) {\n // field is not empty\n}\n \\s \\S \\S"
},
{
"answer_id": 304552,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 3,
"selected": false,
"text": "/^\\s*$/.test(string)\n var empty_string = /^\\s*$/; //create RegExp object for re-use\n\nif (empty_string.test(myFormField.value))\n{\n alert(\"Please be a bit more elaborate!\");\n}\n"
},
{
"answer_id": 304562,
"author": "Geo",
"author_id": 31610,
"author_profile": "https://Stackoverflow.com/users/31610",
"pm_score": 0,
"selected": false,
"text": "/\\s/ or /\\S/ /^\\s+$/ or /^\\S+$/ \nif(string.match(/^\\s+$/)) {\n alert(\"string is empty!\");\n}\n \nif(!string.match(/^\\S+$/)) {\n alert(\"string is empty!\");\n}\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
304,509 | <p>Is something like the following possible in PHP?</p>
<pre><code>$blah = 'foo1';
class foo2 extends $blah {
//...
}
class foo1 {
//...
}
</code></pre>
<p>This gives an error.</p>
<p>I want to dynamically set $blah so I can extend whatever class I want.</p>
<p><strong>Edit:</strong> The reason for wanting to do this because I wanted to use a function out of another class in a related class. In the end it would have been something like:</p>
<pre><code>Final extends foo1 extends foo2 extends foo3 extends foo4 extends parent { ... }
</code></pre>
<p>In the end I decided to instantiate the other class within the class and use it. Not the best options because they both you 2 of the same classes, but this won't be used that often, so it will work for now. </p>
| [
{
"answer_id": 304594,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 5,
"selected": true,
"text": "<?php\nfoo(); # works\n\nfunction foo(){\n print \"bar\";\n}\n <?php\n\nfoo(); #dies\n\nif( $i == 1 )\n{\n function foo(){\n print \"bar\";\n }\n}\n <?php\n$i = 1;\nif( $i == 1 )\n{\n function foo(){\n print \"bar\";\n }\n}\n\nfoo(); #works\n <?php\n\nclass A { }\nclass B { }\nif( false ){ \n class C extends B { \n public static function bar(){\n print \"baz\"; \n }\n }\n}\nC::bar(); # dies\n <?php\nclass A { }\nclass B { }\n$x = 'B'; \nif( false ){ \n class C extends $x { \n public static function bar(){\n print \"baz\"; \n }\n }\n}\nC::bar();\n---> Parse error: syntax error, unexpected T_VARIABLE, expecting T_STRING in /tmp/eg.php on line 7\n <?php\n\nclass A { }\nclass B { }\n$x = 'B'; \nif( true ){ \n $code =<<<EOF\n class C extends $x { \n public static function bar(){\n print \"baz\"; \n }\n }\nEOF;\n\n eval( $code );\n}\nC::bar();\n$o = new C; \nif ( $o instanceof $x )\n{\n print \"WIN!\\n\";\n}\n--->barWIN!\n"
},
{
"answer_id": 304605,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 2,
"selected": false,
"text": "class SuperClassOne { /* code */ }\nclass SuperClassTwo { /* code */ }\n\nclass IntermediateClass extends SuperClassOne { /* empty! */ }\n\nclass DescendantClassFoo extends IntermediateClass{ }\nclass DescendantClassBar extends IntermediateClass{ }\nclass DescendantClassBaz extends IntermediateClass{ }\n DescendantClass* class IntermediateClass extends SuperClassTwo { }\n"
},
{
"answer_id": 304698,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 2,
"selected": false,
"text": "require_once \"classes/foo_$blah.php\" eval()"
},
{
"answer_id": 1661648,
"author": "Matthew",
"author_id": 200991,
"author_profile": "https://Stackoverflow.com/users/200991",
"pm_score": -1,
"selected": false,
"text": "$blah = 'foo1';\nclass foo2 extends $$blah {\n //...\n}\n\nclass foo1 {\n //...\n}\n"
},
{
"answer_id": 6154126,
"author": "SparK",
"author_id": 773259,
"author_profile": "https://Stackoverflow.com/users/773259",
"pm_score": 1,
"selected": false,
"text": "<?php\n define(\"INHERIT\",A);\n\n class A{\n public function bark(){\n return \"I'm A\";\n }\n }\n class B{\n public function bark(){\n return \"I'm B\";\n }\n }\n\n class C extends INHERIT{}\n\n //main?\n $dog = new C();\n echo $dog->bark();\n?>\n"
},
{
"answer_id": 12675263,
"author": "whizzkid",
"author_id": 1452546,
"author_profile": "https://Stackoverflow.com/users/1452546",
"pm_score": 2,
"selected": false,
"text": "if(!class_exists('foo')) {\n class foo extends bar {\n function __construct() {\n parent::__construct();\n }\n }\n}\n\nclass myclass extends foo{\n //YOUR CLASS HERE\n}\n"
},
{
"answer_id": 28181369,
"author": "mikeytown2",
"author_id": 125684,
"author_profile": "https://Stackoverflow.com/users/125684",
"pm_score": 2,
"selected": false,
"text": "class variable_class {\n public $orginalBaseClass;\n public $orginalArgs;\n\n public function __construct() {\n // Get constructor parameters.\n $this->orginalArgs = func_get_args();\n // Get class name from args or 3rd party source.\n $classname = 'stdClass';\n\n // Pass along args to new class.\n $this->orginalBaseClass = new $classname($this->orginalArgs);\n }\n\n public function __call($name, $arguments) {\n // Pass all method calls to the orginalBaseClass.\n return call_user_func_array(array($this->orginalBaseClass, $name), $arguments);\n }\n}\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304509",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5441/"
] |
304,518 | <p>I have this piece of code in my PHP code:</p>
<pre><code>while ($row = mysqli_fetch_assoc($result))
{
extract($row);
echo "<tr>";
echo "<td bgcolor='#FFFFFF'><input id='bookArray[]' name='bookArray[]' type='checkbox' value='$book_id' />$book_id</td>";
echo "<td bgcolor='#FFFFFF'>$threat_name</td>";
echo "</tr>";
}
</code></pre>
<p>In HTML page, I want to use jQuery serialize() method to sent array of selected books in bookArray[]. In my JavaScript,</p>
<pre><code>var selectedbooks = $("book_form").serialize();
alert (selectedbooks);
</code></pre>
<p>In the alert message box, i did not get any value (empty string).</p>
<p>Previously when i am using Prototype, it worked nicely.</p>
| [
{
"answer_id": 304546,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 0,
"selected": false,
"text": "var selectedbooks = $('form#book_form').serialize();;\n"
},
{
"answer_id": 304755,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "while ($row = mysqli_fetch_assoc($result)) {\n extract($row);\n echo \"<tr>\";\n echo \"<td bgcolor='#FFFFFF'><input id='$book_id' name='bookArray[]' type='checkbox' value='$book_id' />$book_id</td>\";\n echo \"<td bgcolor='#FFFFFF'>$book_name</td>\";\n echo \"</tr>\";\n} // while\n var selectedBooks = $('form#book_form').serialize();\nalert (selectedBooks);\n\nvar url = 'saveBookList.php';\n\n// Send to server using JQuery\n$.post(url, {bookArray: selectedBooks}, function(responseData) {\n $(\"#save-result\").text(responseData);\n});\n // If you have selected from list box.\nif(isset($_POST['bookArray'])) {\n\n // Get array or bookID selected by user\n $selectedBookId = $_POST['bookArray'];\n echo $selectedBookId;\n\n foreach($selectedBookId as $selectListItem) {\n echo \"You sent this -->\" . $selectListItem . \"\\n\";\n }\n}\n"
},
{
"answer_id": 304911,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": " while ($row = mysqli_fetch_assoc($result))\n {\n extract($row);\n echo \"<tr>\";\n echo \"<td bgcolor='#FFFFFF'><input name='books' type='checkbox' value='$book_id' />$book_id</td>\";\n echo \"<td bgcolor='#FFFFFF'>$book_name</td>\";\n echo \"</tr>\";\n } // while\n var my_query_str = '';\n\n$(\"input[@type='checkbox'][@name='books']\").each(\n function()\n {\n if(this.checked)\n {\n my_query_str += \"&bookArray[]=\" + this.value;\n }\n });\n\n\n$.ajax(\n{\n type: \"POST\",\n url: \"saveBookList.php\",\n data: \"dummy_data=a\" + my_query_str,\n success:\n function(responseData)\n {\n $(\"#save-result\").empty().append(responseData);\n },\n error:\n function()\n {\n $(\"#save-result\").append(\"An error occured during processing\");\n }\n});\n"
},
{
"answer_id": 323044,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "serialize().replace(/%5B%5D/g, '[]')"
},
{
"answer_id": 1206003,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<script>\nfunction toObjectMap( queryString )\n{\n return '{\\'' + queryString.replace(/=/g, '\\':\\'').replace(/&/g, '\\',\\'') + '\\'}';\n}\n</script>\n...\n<div id=\"result\"></div>\n...\n<form onSubmit=\"$('#result').load( ajaxURL, toObjectMap( $('#formId').serialize() ) );\" ...>\n...\n"
},
{
"answer_id": 1889147,
"author": "FDisk",
"author_id": 175404,
"author_profile": "https://Stackoverflow.com/users/175404",
"pm_score": 0,
"selected": false,
"text": "var data = $(form).serialize();\n$.post('post.php', '&'+data);\n"
},
{
"answer_id": 2420307,
"author": "Gafitescu Daniel",
"author_id": 290901,
"author_profile": "https://Stackoverflow.com/users/290901",
"pm_score": 2,
"selected": false,
"text": "var arTags = new Array();\n\njQuery.map( $(\"input[name='tags[]']\") , function(obj,index)\n{\n arTags .push($(obj).val());\n});\n\nvar obj = {'new_tags' : $(\"#interest\").val() ,\n 'allready_tags[]' : arTags };\n\nvar post_data = jQuery.param(obj,true);\n\n$.ajax({\n type : 'POST',\n url : 'some_url',\n data : post_data,\n dataType : \"html\",\n success: function(htmlResponse)\n {\n\n }\n});\n"
},
{
"answer_id": 3127275,
"author": "Philo",
"author_id": 377379,
"author_profile": "https://Stackoverflow.com/users/377379",
"pm_score": 1,
"selected": false,
"text": "var myform = $(\"book_form\").serialize();\n\ndecodeURIComponent(myform);\n"
},
{
"answer_id": 3898478,
"author": "Neo",
"author_id": 405238,
"author_profile": "https://Stackoverflow.com/users/405238",
"pm_score": 0,
"selected": false,
"text": " var my_query_str = ''; \n $(\"input[@type='checkbox'][@name='books']\").each( function() { \n if(this.checked) { my_query_str += \"&bookArray[]=\" + this.value; } \n }); \n jQuery.post(\n \"saveBookList.php\",\n \"dummy_data=a\" + my_query_str ,\n function(responseData){ \n $(\"#save-result\").empty().append(responseData); \n }, \n error: function() { \n $(\"#save-result\").append(\"An error occured during processing\"); \n }\n }); \n"
},
{
"answer_id": 4964886,
"author": "Hailwood",
"author_id": 383759,
"author_profile": "https://Stackoverflow.com/users/383759",
"pm_score": 3,
"selected": false,
"text": "$_['post']['name'] $_POST['myselect'][0]... function serializePost(form) {\n var data = {};\n form = $(form).serializeArray();\n for (var i = form.length; i--;) {\n var name = form[i].name;\n var value = form[i].value;\n var index = name.indexOf('[]');\n if (index > -1) {\n name = name.substring(0, index);\n if (!(name in data)) {\n data[name] = [];\n }\n data[name].push(value);\n }\n else\n data[name] = value;\n }\n return data;\n}\n"
},
{
"answer_id": 13951516,
"author": "Deniska Axe",
"author_id": 1540635,
"author_profile": "https://Stackoverflow.com/users/1540635",
"pm_score": 1,
"selected": false,
"text": "var data = $('form').serialize();\n $.post(baseUrl+'/ajax.php',\n {action:'saveData',data:data},\n function( data ) {\n alert(data);\n });\n parse_str($_POST['data'], $searcharray);\n echo ('<PRE>');print_r($searcharray);echo ('</PRE>');\n [query] => \n[search_type] => 0\n[motive_note] => \n[id_state] => 1\n[sel_status] => Array\n (\n [8] => 0\n [7] => 1\n )\n"
},
{
"answer_id": 22759716,
"author": "Frank",
"author_id": 1957928,
"author_profile": "https://Stackoverflow.com/users/1957928",
"pm_score": 0,
"selected": false,
"text": "var selectedbooks = $('book_form input[name^=\"bookArray[\"]').serialize();\nalert (selectedbooks); \n"
},
{
"answer_id": 29632392,
"author": "bkingg",
"author_id": 3251579,
"author_profile": "https://Stackoverflow.com/users/3251579",
"pm_score": 0,
"selected": false,
"text": "data: $(this).serialize().replace(/%5B/g, '[').replace(/%5D/g, ']'),\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
304,526 | <p>I'm using the WorldPay payment gateway on a website I'm working on. It handles all the credit card authorisation, and then calls a PHP file on my server with information about the transaction. It grabs the output from my script and displays it in the WorldPay chrome.</p>
<p>I don't know the inner workings, but I imagine that they'd be using something similar to cURL to post the transaction details to my script and to then retrieve the output.</p>
<p>My script writes the necessary information into an XML file, sends an email and then thanks the customer for shopping with us.</p>
<p>My problem is that when I test my file by calling it directly (by turning off the security checks and visiting <code>http://example.com/mysite/myscript.php</code> in my browser), everything works as planned, however when I go through the payment system (so I assumed my script is being called via cURL), it fails on this line:</p>
<pre><code>$xml = simplexml_load_file('./info.xml');
</code></pre>
<p>Any ideas??</p>
<p><em>Clarification: that line returns <strong>false</strong>, which breaks the following lines.</em></p>
| [
{
"answer_id": 304556,
"author": "Grayside",
"author_id": 38408,
"author_profile": "https://Stackoverflow.com/users/38408",
"pm_score": 0,
"selected": false,
"text": "info.xml"
},
{
"answer_id": 304561,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 1,
"selected": false,
"text": "'./' \n dirname(__FILE__).'/' \n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304526",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9021/"
] |
304,530 | <p>i have two servers a main site and a static server.
i want to get a file's content from ajax in runtime, which is stored in static server.
obviously cross domain problem will occur.</p>
<p>so what i am trying to do is storing that ajax .js in the static server, so that calling the local file wont be a problem.</p>
<p>but after i include that js file from static, still that problem remains...</p>
<p>Any solutions?!</p>
| [
{
"answer_id": 304556,
"author": "Grayside",
"author_id": 38408,
"author_profile": "https://Stackoverflow.com/users/38408",
"pm_score": 0,
"selected": false,
"text": "info.xml"
},
{
"answer_id": 304561,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 1,
"selected": false,
"text": "'./' \n dirname(__FILE__).'/' \n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38578/"
] |
304,543 | <p>I'm trying to perform a simple INSERT and return the identity (auto-incrementing primary key). I've tried</p>
<pre><code>cmd.CommandText = "INSERT INTO Prototype ( ParentID ) VALUES ( NULL ); SELECT SCOPE_IDENTITY();";
</code></pre>
<p>and I receive the following error</p>
<pre>EnvironmentError: SQLite error
no such function: SCOPE_IDENTITY</pre>
<p>Does SQLite support SCOPE_IDENTITY?<br>
If so, how do I use it?<br>
If not, what are my (preferably "thread-safe") alternatives?</p>
| [
{
"answer_id": 325767,
"author": "Michael",
"author_id": 41594,
"author_profile": "https://Stackoverflow.com/users/41594",
"pm_score": 5,
"selected": false,
"text": "SELECT last_insert_rowid()"
},
{
"answer_id": 57881563,
"author": "bsigma1",
"author_id": 10704366,
"author_profile": "https://Stackoverflow.com/users/10704366",
"pm_score": 1,
"selected": false,
"text": "last_insert_rowid() last_insert_rowid()"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12971/"
] |
304,555 | <p>Is there a way that I use <a href="http://en.wikipedia.org/wiki/Microsoft_Macro_Assembler" rel="noreferrer">MASM</a> under Linux. Even tough NASM is quite popular under Linux, it still differs for some instruction style on code.</p>
| [
{
"answer_id": 304584,
"author": "Artelius",
"author_id": 31945,
"author_profile": "https://Stackoverflow.com/users/31945",
"pm_score": 2,
"selected": false,
"text": "objcopy"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
304,564 | <p>Ok, I know this is a strange question, but there is a "standard" (fan-wise at least) Unicode support for the Klingon alphabet, and since code can be written in Unicode with no problem, that means it is possible to write Kode with Klingon tokens( vars, function names, etc...).</p>
<p>For the record I've written C++ in Japanese and it works, so K++ in Klingon should work too. But I don't know of any text editor with support for Klingon. Any suggestions?</p>
| [
{
"answer_id": 304569,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 5,
"selected": true,
"text": "[ ]"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304564",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15124/"
] |
304,570 | <p>I am using asp.net mvc for an application. I've taken some guidance from Rob Conery's series on the MVC storefront. I am using a very similar data access pattern to the one that he used in the storefront.</p>
<p>However, I have added a small difference to the pattern. Each class I have created in my model has a property called IsNew. The intention on this is to allow me to specify whether I should be inserting or updating in the database.</p>
<p>Here's some code:</p>
<p>In my controller:</p>
<pre><code>OrderService orderService = new OrderService();
Order dbOrder = orderService.GetOrder(ID);
if (ModelState.IsValid)
{
dbOrder.SomeField1 = "Whatever1";
dbOrder.SomeField2 = "Whatever2";
dbOrder.DateModified = DateTime.Now;
dbOrder.IsNew = false;
orderService.SaveOrder(dbOrder);
}
</code></pre>
<p>And then in the SQLOrderRepository:</p>
<pre><code>public void SaveOrder(Order order)
{
ORDER dbOrder = new ORDER();
dbOrder.O_ID = order.ID;
dbOrder.O_SomeField1 = order.SomeField1;
dbOrder.O_SomeField2 = order.SomeField2;
dbOrder.O_DateCreated = order.DateCreated;
dbOrder.O_DateModified = order.DateModified;
if (order.IsNew)
db.ORDERs.InsertOnSubmit(dbOrder);
db.SubmitChanges();
}
</code></pre>
<p>If I change the controller code so that the dbOrder.IsNew = true; then the code works, and the values are inserted correctly.</p>
<p>However, if I set the dbOrder.IsNew = false; then nothing happens...there are no errors - it just doesn't update the order.</p>
<p>I am using DebuggerWriter here: <a href="http://www.u2u.info/Blogs/Kris/Lists/Posts/Post.aspx?ID=11" rel="nofollow noreferrer">http://www.u2u.info/Blogs/Kris/Lists/Posts/Post.aspx?ID=11</a> to trace the SQL that is being generated, and as expected, when the IsNew value is true, the Insert SQL is generated and executed properly. However, when IsNew is set to false, there appears to be no SQL generated, so nothing is executed.</p>
<p>I've verified that the issue here (<a href="https://stackoverflow.com/questions/206532/linq-not-updating-on-submitchanges">LINQ not updating on .SubmitChanges()</a>) is not the problem.</p>
<p>Any help is appreciated.</p>
| [
{
"answer_id": 304592,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 4,
"selected": true,
"text": "public void SaveOrder(Order order)\n{\n ORDER dbOrder;\n if (order.IsNew)\n {\n dbOrder = new ORDER();\n dbOrder.O_ID = order.ID;\n }\n else\n {\n dbOrder = (from o in db.ORDERS where o.O_ID == order.ID select o).Single();\n }\n\n dbOrder.O_SomeField1 = order.SomeField1;\n dbOrder.O_SomeField2 = order.SomeField2;\n dbOrder.O_DateCreated = order.DateCreated;\n dbOrder.O_DateModified = order.DateModified;\n\n if (order.IsNew)\n db.ORDERs.InsertOnSubmit(dbOrder);\n\n db.SubmitChanges();\n}\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29092/"
] |
304,576 | <p>In algebra if I make the statement x + y = 3, the variables I used will hold the values either 2 and 1 or 1 and 2. I know that assignment in programming is not the same thing, but I got to wondering. If I wanted to represent the value of, say, a quantumly weird particle, I would want my variable to have two values at the same time and to have it resolve into one or the other later. Or maybe I'm just dreaming?</p>
<p>Is it possible to say something like <code>i = 3 or 2;</code>?</p>
| [
{
"answer_id": 304612,
"author": "Andrey Shchekin",
"author_id": 39068,
"author_profile": "https://Stackoverflow.com/users/39068",
"pm_score": 3,
"selected": false,
"text": "my $a = 1|2|3 $a==1 $a==2 $a+1 2|3|4 all any b < any(1,2,3)"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304576",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29182/"
] |
304,606 | <p>When opening a window, I register a Deleted-event-handler on my business object. It is passed to the constructor as <code>business</code>:</p>
<pre><code>business.Deleted += new EventHandler<EventArgs>(business_Deleted);
</code></pre>
<p>Now the user can click a button to delete it (removing the record, you know). The event handler is registered to capture deletion by other editor windows and notifying the user ("Item has been deleted in another editor window.").</p>
<p>If the user deletes it in the current window, this message would be stupid, so I'd like to unregister the event before:</p>
<pre><code>Business business = (Business)businessBindingSource.DataSource;
business.Deleted -= new EventHandler<EventArgs>(business_Deleted);
</code></pre>
<p>My problem is simple: The message is displayed anyway, so unregistering does not work. I tried storing the EventHandler in a separate member. Does not work either.</p>
<p>Any help would be cool.</p>
<p>Matthias</p>
<p>P.S. Reading <a href="https://stackoverflow.com/questions/99790/is-it-safe-to-add-delegates-to-events-with-keyword-new#100719">this post</a>, I'm afraid that properly unregistering the event could make it unregistered for all editor windows. Could be the next problem. ;-)</p>
| [
{
"answer_id": 304619,
"author": "Ed S.",
"author_id": 1053,
"author_profile": "https://Stackoverflow.com/users/1053",
"pm_score": 0,
"selected": false,
"text": "Business business = (Business)businessBindingSource.DataSource;\n"
},
{
"answer_id": 304641,
"author": "Matthias Meid",
"author_id": 17713,
"author_profile": "https://Stackoverflow.com/users/17713",
"pm_score": 0,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Data;\nusing System.Drawing;\nusing System.Globalization;\nusing System.Linq;\nusing System.Text;\nusing System.Windows.Forms;\n\nnamespace WindowsApplication\n{\n public partial class BusinessEditor : Form\n {\n private EventHandler<EventArgs> businessDeletedHandler;\n\n public BusinessEditor(Business business)\n : this()\n {\n InitializeComponent();\n\n businessBindingSource.DataSource = business;\n\n // Registering\n businessDeletedHandler = new EventHandler<EventArgs>(business_Deleted);\n business.Deleted += businessDeletedHandler;\n }\n\n void business_Deleted(object sender, EventArgs e)\n {\n MessageBox.Show(\"Item has been deleted in another editor window.\",\n \"...\", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);\n Close();\n }\n\n private void deleteButton_Activate(object sender, EventArgs e)\n {\n Business c = (Business)businessBindingSource.DataSource;\n // Unregistering\n c.Deleted -= businessDeletedHandler;\n c.Delete();\n Close();\n }\n }\n}\n"
},
{
"answer_id": 304681,
"author": "TcKs",
"author_id": 20382,
"author_profile": "https://Stackoverflow.com/users/20382",
"pm_score": 2,
"selected": true,
"text": "c.Delete( this ); //this = window\n// ...\nvoid business_Deleted(object sender, EventArgs e) {\n bool isDeletedFromMe = false;\n if ( e is DeletedEventArgs ) { isDeletedFromMe = object.ReferenceEquals( this, e.Author ); }\n if ( false == isDeletedFromMe ) {\n MessageBox.Show(\"Item has been deleted in another editor window.\",\n \"...\", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);\n Close();\n }\n}\n void business_Deleted(object sender, EventArgs e)\n{\n if ( false == object.ReferenceEquals( sender, this.currentlyDeletingBusiness ) ) {\n MessageBox.Show(\"Item has been deleted in another editor window.\",\n \"...\", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);\n }\n Close();\n}\n\nBusiness currentlyDeletingBusiness;\nprivate void deleteButton_Activate(object sender, EventArgs e)\n{\n Business c = (Business)businessBindingSource.DataSource;\n try {\n this.currentlyDeletingBusiness = c;\n c.Delete();\n }\n finally {\n this.currentlyDeletingBusiness = null;\n }\n}\n"
},
{
"answer_id": 315034,
"author": "Yona",
"author_id": 40007,
"author_profile": "https://Stackoverflow.com/users/40007",
"pm_score": 1,
"selected": false,
"text": "private bool otherUser = true;\n\nvoid business_Deleted(object sender, EventArgs e)\n{\n if(otherUser) {\n /* Show message */\n }\n}\n\nvoid deleteButton_Activate(object sender, EventArgs e)\n{\n otherUser = false;\n /* Delete record */\n}\n"
},
{
"answer_id": 1061665,
"author": "SwDevMan81",
"author_id": 95573,
"author_profile": "https://Stackoverflow.com/users/95573",
"pm_score": 1,
"selected": false,
"text": "business.Deleted -= new EventHandler(business_Deleted);"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17713/"
] |
304,607 | <p>I am using CSS Tidy. Due to all of its compression measures, in some cases it's messing up my pages by combining or re-arranging selectors, etc. Even with the options shown below, pages with the compressed CSS do not render as they do with the uncompressed.</p>
<p>My question is: How can I configure CSS Tidy to combine all of my CSS files into one, and do nothing more than that?</p>
<pre><code>$this->settings['remove_bslash'] = false;
$this->settings['compress_colors'] = false;
$this->settings['compress_font-weight'] = false;
$this->settings['lowercase_s'] = false;
$this->settings['optimise_shorthands'] = 0;
$this->settings['remove_last_;'] = false;
$this->settings['case_properties'] = 0;
$this->settings['sort_properties'] = false;
$this->settings['sort_selectors'] = false;
$this->settings['merge_selectors'] = 0;
$this->settings['discard_invalid_properties'] = false;
$this->settings['css_level'] = 'CSS2.1';
$this->settings['preserve_css'] = true;
$this->settings['timestamp'] = false;
</code></pre>
<hr>
<p>@ypnos: In terms of configuration, I do not have a configuration file, no do I set the configuration options when I initialize the class. I just edited the csstidy() function in the actual class. I am sure my edited settings are being read because some—-but not nearly all--of the problems were fixed.</p>
<p>@Ambrose: The CSS is 30k compressed and has a number of issues I am having difficulty in tracking down. I can clearly see problems on the rendered pages, but tougher to track them down in the file generated by CSS Tidy. In some cases, the order of selectors was being changed, but by editing those settings, I at least corrected that problem. Both of your assumptions about CSS Tidy (URL and usage as PHP) are correct.</p>
<p>Since http-compression can compress the CSS from a whitespace standpoint, all I need CSS Tidy to do is combine all of my CSS files into one, without trying to manipulate the contents.</p>
| [
{
"answer_id": 304619,
"author": "Ed S.",
"author_id": 1053,
"author_profile": "https://Stackoverflow.com/users/1053",
"pm_score": 0,
"selected": false,
"text": "Business business = (Business)businessBindingSource.DataSource;\n"
},
{
"answer_id": 304641,
"author": "Matthias Meid",
"author_id": 17713,
"author_profile": "https://Stackoverflow.com/users/17713",
"pm_score": 0,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Data;\nusing System.Drawing;\nusing System.Globalization;\nusing System.Linq;\nusing System.Text;\nusing System.Windows.Forms;\n\nnamespace WindowsApplication\n{\n public partial class BusinessEditor : Form\n {\n private EventHandler<EventArgs> businessDeletedHandler;\n\n public BusinessEditor(Business business)\n : this()\n {\n InitializeComponent();\n\n businessBindingSource.DataSource = business;\n\n // Registering\n businessDeletedHandler = new EventHandler<EventArgs>(business_Deleted);\n business.Deleted += businessDeletedHandler;\n }\n\n void business_Deleted(object sender, EventArgs e)\n {\n MessageBox.Show(\"Item has been deleted in another editor window.\",\n \"...\", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);\n Close();\n }\n\n private void deleteButton_Activate(object sender, EventArgs e)\n {\n Business c = (Business)businessBindingSource.DataSource;\n // Unregistering\n c.Deleted -= businessDeletedHandler;\n c.Delete();\n Close();\n }\n }\n}\n"
},
{
"answer_id": 304681,
"author": "TcKs",
"author_id": 20382,
"author_profile": "https://Stackoverflow.com/users/20382",
"pm_score": 2,
"selected": true,
"text": "c.Delete( this ); //this = window\n// ...\nvoid business_Deleted(object sender, EventArgs e) {\n bool isDeletedFromMe = false;\n if ( e is DeletedEventArgs ) { isDeletedFromMe = object.ReferenceEquals( this, e.Author ); }\n if ( false == isDeletedFromMe ) {\n MessageBox.Show(\"Item has been deleted in another editor window.\",\n \"...\", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);\n Close();\n }\n}\n void business_Deleted(object sender, EventArgs e)\n{\n if ( false == object.ReferenceEquals( sender, this.currentlyDeletingBusiness ) ) {\n MessageBox.Show(\"Item has been deleted in another editor window.\",\n \"...\", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);\n }\n Close();\n}\n\nBusiness currentlyDeletingBusiness;\nprivate void deleteButton_Activate(object sender, EventArgs e)\n{\n Business c = (Business)businessBindingSource.DataSource;\n try {\n this.currentlyDeletingBusiness = c;\n c.Delete();\n }\n finally {\n this.currentlyDeletingBusiness = null;\n }\n}\n"
},
{
"answer_id": 315034,
"author": "Yona",
"author_id": 40007,
"author_profile": "https://Stackoverflow.com/users/40007",
"pm_score": 1,
"selected": false,
"text": "private bool otherUser = true;\n\nvoid business_Deleted(object sender, EventArgs e)\n{\n if(otherUser) {\n /* Show message */\n }\n}\n\nvoid deleteButton_Activate(object sender, EventArgs e)\n{\n otherUser = false;\n /* Delete record */\n}\n"
},
{
"answer_id": 1061665,
"author": "SwDevMan81",
"author_id": 95573,
"author_profile": "https://Stackoverflow.com/users/95573",
"pm_score": 1,
"selected": false,
"text": "business.Deleted -= new EventHandler(business_Deleted);"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/74552/"
] |
304,609 | <p>Simple question:</p>
<p>Can a swing frame be completely modal ( block all others windows ) ?</p>
<p>I tried the following, but I can still click on other apps windows ( like this browser ) </p>
<pre><code>JDialog myDialog = ....
myDialog.setModalityType(Dialog.ModalityType.APPLICATION_MODAL);
</code></pre>
<p>Plase paste some code if this is possible. </p>
| [
{
"answer_id": 304702,
"author": "Eugene Yokota",
"author_id": 3827,
"author_profile": "https://Stackoverflow.com/users/3827",
"pm_score": 1,
"selected": false,
"text": "private void toggleFullScreenWindow() {\n GraphicsEnvironment graphicsEnvironment\n = GraphicsEnvironment.getLocalGraphicsEnvironment();\n GraphicsDevice graphicsDevice\n = graphicsEnvironment.getDefaultScreenDevice();\n if(graphicsDevice.getFullScreenWindow()==null) {\n dialog.dispose(); //destroy the native resources\n dialog.setUndecorated(true);\n dialog.setVisible(true); //rebuilding the native resources\n graphicsDevice.setFullScreenWindow(dialog);\n }else{\n graphicsDevice.setFullScreenWindow(null);\n dialog.dispose();\n dialog.setUndecorated(false);\n dialog.setVisible(true);\n dialog.repaint();\n }\n requestFocusInWindow();\n}\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304609",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20654/"
] |
304,614 | <p>Unfortunately I don't have access to a *nix box at work or at home. The only way I can play with Haskell is on windows. Anyone here using Haskell on Windows? What's your setup?</p>
| [
{
"answer_id": 304635,
"author": "gimel",
"author_id": 6491,
"author_profile": "https://Stackoverflow.com/users/6491",
"pm_score": 1,
"selected": false,
"text": ".exe .msi"
},
{
"answer_id": 19611239,
"author": "Trident D'Gao",
"author_id": 139667,
"author_profile": "https://Stackoverflow.com/users/139667",
"pm_score": 5,
"selected": false,
"text": "View Show console \nimport urllib.request,os; pf = 'Package Control.sublime-package'; ipp = sublime.installed_packages_path(); urllib.request.install_opener( urllib.request.build_opener( urllib.request.ProxyHandler()) ); open(os.path.join(ipp, pf), 'wb').write(urllib.request.urlopen( 'http://sublime.wbond.net/' + pf.replace(' ','%20')).read())\n Tools Command palette Package Control: Install Package SublimeHaskell cabal install cabal-install\ncabal update\ncabal install aeson\ncabal install haskell-src-exts\ncabal install ghc-mod\ncabal install cmdargs\ncabal install haddock\n runhaskell Setup.hs configure --user\nrunhaskell Setup.hs build\nrunhaskell Setup.hs install\n C:\\Users\\Aleksey Bykov\\AppData\\Roaming\\cabal\\bin Aleksey Bykov Preferences Package settings SumblimeHaskell Settings - User {\n \"add_to_PATH\":\n [\n \"C:/Users/Aleksey Bykov/AppData/Roaming/cabal/bin/\"\n ],\n \"enable_hdevtools\": true\n}\n C:/Users/Aleksey Bykov/AppData/Roaming/cabal/bin/ hello-world.hs main::IO()\nmain = putStrLn \"Hello world!\"\n Tools Build"
},
{
"answer_id": 69543505,
"author": "Dennis Kozevnikoff",
"author_id": 10531410,
"author_profile": "https://Stackoverflow.com/users/10531410",
"pm_score": 0,
"selected": false,
"text": "Get-ExecutionPolicy\n Set-ExecutionPolicy Bypass -Scope Process\n A\n choco\n choco install haskell-dev\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304614",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20155/"
] |
304,616 | <p>Host: GoDaddy Shared Hosting</p>
<p>Trust Level: Medium</p>
<p>The following happens after I submit a valid user/pass. The database has read/write permissions and when I remove the login requirement on an admin page that updates the database work as expected.</p>
<p>Has anyone else had this issue or know what the problem is?
Anyone?</p>
<pre><code>Server Error in '/' Application.
Security Exception
Description: The application attempted to perform an operation not allowed by the security policy. To grant this application the required permission please contact your system administrator or change the application's trust level in the configuration file.
Exception Details: System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[SecurityException: Request for the permission of type 'System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.]
System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet) +0
System.Security.CodeAccessPermission.Demand() +59
System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy) +684
System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share) +114
System.Configuration.Internal.InternalConfigHost.StaticOpenStreamForRead(String streamName) +80
System.Configuration.Internal.InternalConfigHost.System.Configuration.Internal.IInternalConfigHost.OpenStreamForRead(String streamName, Boolean assertPermissions) +115
System.Configuration.Internal.InternalConfigHost.System.Configuration.Internal.IInternalConfigHost.OpenStreamForRead(String streamName) +7
System.Configuration.Internal.DelegatingConfigHost.OpenStreamForRead(String streamName) +10
System.Configuration.UpdateConfigHost.OpenStreamForRead(String streamName) +42
System.Configuration.BaseConfigurationRecord.InitConfigFromFile() +437
Version Information: Microsoft .NET Framework Version:2.0.50727.1433; ASP.NET Version:2.0.50727.1433
</code></pre>
| [
{
"answer_id": 2488591,
"author": "Rich Bennema",
"author_id": 27482,
"author_profile": "https://Stackoverflow.com/users/27482",
"pm_score": 1,
"selected": false,
"text": "// Get encryption and decryption key information from the configuration.\nConfiguration cfg =\n WebConfigurationManager.OpenWebConfiguration(System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath);\nmachineKey = (MachineKeySection)cfg.GetSection(\"system.web/machineKey\");\n\nif (machineKey.ValidationKey.Contains(\"AutoGenerate\"))\n if (PasswordFormat != MembershipPasswordFormat.Clear)\n throw new ProviderException(\"Hashed or Encrypted passwords are not supported with auto-generated keys.\");\n machineKey = (MachineKeySection)WebConfigurationManager.GetWebApplicationSection(\"system.web/machineKey\");\n"
},
{
"answer_id": 26409141,
"author": "rafaellorey",
"author_id": 4150506,
"author_profile": "https://Stackoverflow.com/users/4150506",
"pm_score": 4,
"selected": false,
"text": "<system.web>\n <customErrors mode=\"Off\"/>\n <trust level=\"Full\" />\n</system.web>\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304616",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3747/"
] |
304,617 | <p>Is there a <code>HTMLHelper</code> for file upload? Specifically, I am looking for a replace of</p>
<pre><code><input type="file"/>
</code></pre>
<p>using ASP.NET MVC HTMLHelper. </p>
<p>Or, If I use </p>
<pre><code>using (Html.BeginForm())
</code></pre>
<p>What is the HTML control for the file upload? </p>
| [
{
"answer_id": 307513,
"author": "Graviton",
"author_id": 3834,
"author_profile": "https://Stackoverflow.com/users/3834",
"pm_score": 2,
"selected": false,
"text": "BeginForm using(Html.BeginForm(\"uploadfiles\", \n\"home\", FormMethod.POST, new Dictionary<string, object>(){{\"type\", \"file\"}})\n"
},
{
"answer_id": 6348821,
"author": "balexandre",
"author_id": 28004,
"author_profile": "https://Stackoverflow.com/users/28004",
"pm_score": 4,
"selected": false,
"text": "@using (Html.BeginForm(\"Upload\", \"File\", FormMethod.Post, new { enctype = \"multipart/form-data\" }))\n{ \n <p>\n <input type=\"file\" id=\"fileUpload\" name=\"fileUpload\" size=\"23\" />\n </p>\n <p>\n <input type=\"submit\" value=\"Upload file\" /></p> \n}\n"
},
{
"answer_id": 7163720,
"author": "Paulius Zaliaduonis",
"author_id": 314454,
"author_profile": "https://Stackoverflow.com/users/314454",
"pm_score": 9,
"selected": true,
"text": "public class ViewModel\n{\n [Required, Microsoft.Web.Mvc.FileExtensions(Extensions = \"csv\", \n ErrorMessage = \"Specify a CSV file. (Comma-separated values)\")]\n public HttpPostedFileBase File { get; set; }\n}\n @using (Html.BeginForm(\"Action\", \"Controller\", FormMethod.Post, new \n { enctype = \"multipart/form-data\" }))\n{\n @Html.TextBoxFor(m => m.File, new { type = \"file\" })\n @Html.ValidationMessageFor(m => m.File)\n}\n [HttpPost]\npublic ActionResult Action(ViewModel model)\n{\n if (ModelState.IsValid)\n {\n // Use your file here\n using (MemoryStream memoryStream = new MemoryStream())\n {\n model.File.InputStream.CopyTo(memoryStream);\n }\n }\n}\n"
},
{
"answer_id": 27502746,
"author": "BornToCode",
"author_id": 1057791,
"author_profile": "https://Stackoverflow.com/users/1057791",
"pm_score": 2,
"selected": false,
"text": "public class ViewModel\n{\n public HttpPostedFileBase File { get; set; }\n\n [Required(ErrorMessage=\"A header image is required\"), FileExtensions(ErrorMessage = \"Please upload an image file.\")]\n public string FileName\n {\n get\n {\n if (File != null)\n return File.FileName;\n else\n return String.Empty;\n }\n }\n}\n @using (Html.BeginForm(\"Action\", \"Controller\", FormMethod.Post, new \n { enctype = \"multipart/form-data\" }))\n{\n @Html.TextBoxFor(m => m.File, new { type = \"file\" })\n @Html.ValidationMessageFor(m => m.FileName)\n}\n"
},
{
"answer_id": 36191555,
"author": "Luke Schafer",
"author_id": 108578,
"author_profile": "https://Stackoverflow.com/users/108578",
"pm_score": -1,
"selected": false,
"text": "@Html.Raw(Html.TextBoxFor(m => m.File).ToHtmlString().Replace(\"type=\\\"text\\\"\", \"type=\\\"file\\\"\"))\n"
},
{
"answer_id": 37131594,
"author": "Eyal",
"author_id": 1073658,
"author_profile": "https://Stackoverflow.com/users/1073658",
"pm_score": 0,
"selected": false,
"text": "public class ViewModel\n{ \n public HttpPostedFileBase File{ get; set; }\n}\n @using (Html.BeginForm(\"Action\", \"Controller\", FormMethod.Post, new \n { enctype = \"multipart/form-data\" }))\n{\n @Html.TextBoxFor(m => m.File, new { type = \"file\" }) \n}\n [HttpPost]\npublic ActionResult Action(ViewModel model)\n{\n if (ModelState.IsValid)\n {\n var postedFile = Request.Files[\"File\"];\n\n // now you can get and validate the file type:\n var isFileSupported= IsFileSupported(postedFile);\n\n }\n}\n\npublic bool IsFileSupported(HttpPostedFileBase file)\n {\n var isSupported = false;\n\n switch (file.ContentType)\n {\n\n case (\"image/gif\"):\n isSupported = true;\n break;\n\n case (\"image/jpeg\"):\n isSupported = true;\n break;\n\n case (\"image/png\"):\n isSupported = true;\n break;\n\n\n case (\"audio/mp3\"): \n isSupported = true;\n break;\n\n case (\"audio/wav\"): \n isSupported = true;\n break; \n }\n\n return isSupported;\n }\n"
},
{
"answer_id": 38763712,
"author": "Tod",
"author_id": 1109858,
"author_profile": "https://Stackoverflow.com/users/1109858",
"pm_score": 3,
"selected": false,
"text": "public static MvcHtmlString FileFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression)\n {\n return helper.FileFor(expression, null);\n }\n\npublic static MvcHtmlString FileFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes)\n {\n var builder = new TagBuilder(\"input\");\n\n var id = helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(expression));\n builder.GenerateId(id);\n builder.MergeAttribute(\"name\", id);\n builder.MergeAttribute(\"type\", \"file\");\n\n builder.MergeAttributes(new RouteValueDictionary(htmlAttributes));\n\n // Render tag\n return MvcHtmlString.Create(builder.ToString(TagRenderMode.SelfClosing));\n }\n var id = helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(expression));\n public HttpPostedFileBase NewFile { get; set; }\n @using (Html.BeginForm(\"Action\", \"Controller\", FormMethod.Post, new { enctype = \"multipart/form-data\" }))\n @Html.FileFor(x => x.NewFile)\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3834/"
] |
304,640 | <p>Assuming the following class stub:</p>
<pre><code>public class Foo<T> {
private Class<T> type;
public Foo<T> () {}
}
</code></pre>
<p>Can I store the generic type <code>T</code> into the field <code>type</code> in the constructor, without changing the constructor's signature to "<code>public Foo<T> (Class<T> type)</code>"? </p>
<p>If yes, how? If no, why?</p>
<p>"<code>type = T</code>" doesn't seem to work.</p>
| [
{
"answer_id": 304652,
"author": "JTeagle",
"author_id": 162171,
"author_profile": "https://Stackoverflow.com/users/162171",
"pm_score": -1,
"selected": false,
"text": "type = T.getClass();\n"
},
{
"answer_id": 304659,
"author": "Charles Graham",
"author_id": 7705,
"author_profile": "https://Stackoverflow.com/users/7705",
"pm_score": -1,
"selected": false,
"text": "type = T.GetType();\n"
},
{
"answer_id": 304664,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": true,
"text": "T Class<T> Object"
},
{
"answer_id": 304721,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 2,
"selected": false,
"text": "list.get (index).getClass() \n import java.util.ArrayList;\n\n/**\n * @param <T>\n */\npublic class StoreGerenericTypeInField<T>\n{\n\n private T myT = null;\n private ArrayList<T> list = new ArrayList<T>();\n\n private void setT(final T aT) { myT = aT; }\n /**\n * Attempt to do private strange initialization with T, in the hope to provoke a cast exception\n */\n public StoreGerenericTypeInField()\n {\n StringBuilder aFirstType = new StringBuilder();\n StringBuffer aSecondType = new StringBuffer();\n this.list.add((T)aFirstType);\n this.list.add((T)aSecondType);\n System.out.println(this.list.get(0).getClass().getName());\n System.out.println(this.list.get(1).getClass().getName());\n\n setT((T)aFirstType);\n System.out.println(this.myT.getClass().getName());\n setT((T)aSecondType);\n System.out.println(this.myT.getClass().getName());\n }\n /**\n * @param args\n */\n public static void main(String[] args)\n {\n StoreGerenericTypeInField<Integer> s = new StoreGerenericTypeInField<Integer>();\n }\n}\n java.lang.StringBuilder\njava.lang.StringBuffer\njava.lang.StringBuilder\njava.lang.StringBuffer\n T"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304640",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2238/"
] |
304,649 | <p>I am trying to create a custom subclass of NSScroller. I have created the class, and set it as the vertical scroller on an NSScrollView in IB. When I run my project, the <code>drawRect:</code> method is called for my subclass, so I know that it is properly connected.</p>
<p>Now, How do I change the width of my fancy new NSScroller? No matter what I do to its bounds and frame, it always wants to draw in a rectangle 15 pixels wide (the size of the default NSScroller).</p>
| [
{
"answer_id": 304743,
"author": "Jason Coco",
"author_id": 34218,
"author_profile": "https://Stackoverflow.com/users/34218",
"pm_score": 2,
"selected": false,
"text": "+(CGFloat)scrollerWidth\n{\n return 30.0;\n}\n"
},
{
"answer_id": 3324047,
"author": "DanielGibbs",
"author_id": 343486,
"author_profile": "https://Stackoverflow.com/users/343486",
"pm_score": 1,
"selected": false,
"text": "#import <Cocoa/Cocoa.h>\n\n@interface NSScroller (MyScroller)\n\n+ (CGFloat)scrollerWidth;\n+ (CGFloat)scrollerWidthForControlSize: (NSControlSize)controlSize;\n\n@end\n #import \"NSScroller-MyScroller.h\"\n#define SCROLLER_WIDTH 30.0\n\n@implementation NSScroller (MyScroller)\n\n+ (CGFloat)scrollerWidth {\n return SCROLLER_WIDTH;\n}\n\n+ (CGFloat)scrollerWidthForControlSize: (NSControlSize)controlSize {\n return SCROLLER_WIDTH;\n}\n\n@end\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33686/"
] |
304,655 | <p>Say I am declaring a class <code>C</code> and a few of the declarations are very similar. I'd like to use a function <code>f</code> to reduce code repetition for these declarations. It's possible to just declare and use <code>f</code> as usual:</p>
<pre><code>>>> class C(object):
... def f(num):
... return '<' + str(num) + '>'
... v = f(9)
... w = f(42)
...
>>> C.v
'<9>'
>>> C.w
'<42>'
>>> C.f(4)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unbound method f() must be called with C instance as first argument (got int instance instead)
</code></pre>
<p>Oops! I've inadvertently exposed <code>f</code> to the outside world, but it doesn't take a <code>self</code> argument (and can't for obvious reasons). One possibility would be to <code>del</code> the function after I use it:</p>
<pre><code>>>> class C(object):
... def f(num):
... return '<' + str(num) + '>'
... v = f(9)
... del f
...
>>> C.v
'<9>'
>>> C.f
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: type object 'C' has no attribute 'f'
</code></pre>
<p>But what if I want to use <code>f</code> again later, after the declaration? It won't do to delete the function. I could make it "private" (i.e., prefix its name with <code>__</code>) and give it the <code>@staticmethod</code> treatment, but invoking <code>staticmethod</code> objects through abnormal channels gets very funky:</p>
<pre><code>>>> class C(object):
... @staticmethod
... def __f(num):
... return '<' + str(num) + '>'
... v = __f.__get__(1)(9) # argument to __get__ is ignored...
...
>>> C.v
'<9>'
</code></pre>
<p>I have to use the above craziness because <code>staticmethod</code> objects, which are descriptors, are not themselves callable. I need to recover the function wrapped by the <code>staticmethod</code> object before I can call it.</p>
<p>There has got to be a better way to do this. How can I cleanly declare a function in a class, use it during its declaration, and also use it later from within the class? Should I even be doing this?</p>
| [
{
"answer_id": 304679,
"author": "Ali Afshar",
"author_id": 28380,
"author_profile": "https://Stackoverflow.com/users/28380",
"pm_score": 5,
"selected": true,
"text": "def f(n):\n return '<' + str(num) + '>'\n\nclass C(object):\n\n v = f(9)\n w = f(42)\n >>> f(4)\n'<4>'\n"
},
{
"answer_id": 305022,
"author": "Alex Coventry",
"author_id": 1941213,
"author_profile": "https://Stackoverflow.com/users/1941213",
"pm_score": 1,
"selected": false,
"text": "class _C:\n # Do most of the function definitions in here\n @classmethod\n def f(cls):\n return 'boo'\n\nclass C(_C):\n # Do the subsequent decoration in here\n v = _C.f()\n"
},
{
"answer_id": 305069,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 2,
"selected": false,
"text": "def create_C():\n def f(num):\n return '<' + str(num) + '>'\n\n class C(object):\n v = f(9)\n def method_using_f(self, x): return f(x*2)\n return C\n\nC=create_C()\ndel create_C\n C.method_using_f.im_func.func_closure class C(object):\n def f(num):\n return '<' + str(num) + '>'\n\n v = f(9)\n def method_using_f(self, x, f=f): return f(x*2)\n\n del f\n"
},
{
"answer_id": 305104,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 0,
"selected": false,
"text": "f import myCmod\n\nmyCmod.C.w\nmyCmod.C.v\nmyCmod.f(42)\n >>> class F(object):\n def __init__( self, num ):\n self.value= num\n self.format= \"<%d>\" % ( num, )\n\n>>> class C(object):\n w= F(42)\n v= F(9)\n\n>>> C.w\n<__main__.F object at 0x00C58C30>\n>>> C.w.format\n'<42>'\n>>> C.v.format\n'<9>'\n"
},
{
"answer_id": 305241,
"author": "user39307",
"author_id": 39307,
"author_profile": "https://Stackoverflow.com/users/39307",
"pm_score": 2,
"selected": false,
"text": "class C():\n... class F():\n... def __call__(self,num):\n... return \"<\"+str(num)+\">\"\n... f=F()\n... v=f(9)\n>>> C.v\n'<9>'\n>>> C.f(25)\n'<25>'\n>>> \n"
},
{
"answer_id": 307271,
"author": "ianb",
"author_id": 20218,
"author_profile": "https://Stackoverflow.com/users/20218",
"pm_score": 1,
"selected": false,
"text": "staticmethod class staticfunc(object):\n def __init__(self, func):\n self.func = func\n def __call__(self, *args, **kw):\n return self.func(*args, **kw)\n def __repr__(self):\n return 'staticfunc(%r)' % self.func\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304655",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39182/"
] |
304,658 | <p>I want to use PKCS#7 as a container format for some encrypted, signed content and we need to use AES in CBC mode with ISO 10126 based padding. I can't seem to find a concrete reference to an algorithm identifier to use for this combination. I can invent my own but would then lose interoperability with other tools.</p>
| [
{
"answer_id": 7419423,
"author": "Peter Dettman",
"author_id": 264294,
"author_profile": "https://Stackoverflow.com/users/264294",
"pm_score": 1,
"selected": false,
"text": "-- AES information object identifiers --\n\naes OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840)\n organization(1) gov(101) csor(3)_ nistAlgorithms(4) 1 }\n\n-- AES using CBC-chaining mode for key sizes of 128, 192, 256\n\nid-aes128-CBC OBJECT IDENTIFIER ::= { aes 2 }\nid-aes192-CBC OBJECT IDENTIFIER ::= { aes 22 }\nid-aes256-CBC OBJECT IDENTIFIER ::= { aes 42 }\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1996/"
] |
304,713 | <p>What is BPEL? I'm looking for some nice simple examples of BPEL usage. The wikipedia page isn't too enlightening. How about a "Hello world" in BPEL? A BPEL shell? A BPEL IDE?</p>
| [
{
"answer_id": 54692804,
"author": "Jesper Vernooij",
"author_id": 10059886,
"author_profile": "https://Stackoverflow.com/users/10059886",
"pm_score": 0,
"selected": false,
"text": "<shippingAdress> <itemId"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304713",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3146/"
] |
304,752 | <p>I am trying to improve the performance of the threaded application with real-time deadlines. It is running on Windows Mobile and written in C / C++. I have a suspicion that high frequency of thread switching might be causing tangible overhead, but can neither prove it or disprove it. As everybody knows, lack of proof is not a proof of opposite :).</p>
<p>Thus my question is twofold:</p>
<ul>
<li><p>If exists at all, where can I find any actual measurements of the cost of switching thread context?</p></li>
<li><p>Without spending time writing a test application, what are the ways to estimate the thread switching overhead in the existing application?</p></li>
<li><p>Does anyone know a way to find out the number of context switches (on / off) for a given thread?</p></li>
</ul>
| [
{
"answer_id": 304925,
"author": "Mecki",
"author_id": 15809,
"author_profile": "https://Stackoverflow.com/users/15809",
"pm_score": 5,
"selected": false,
"text": "#include <stdlib.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <pthread.h>\n#include <sys/time.h>\n#include <unistd.h>\n\nuint32_t COUNTER;\npthread_mutex_t LOCK;\npthread_mutex_t START;\npthread_cond_t CONDITION;\n\nvoid * threads (\n void * unused\n) {\n // Wait till we may fire away\n pthread_mutex_lock(&START);\n pthread_mutex_unlock(&START);\n\n pthread_mutex_lock(&LOCK);\n // If I'm not the first thread, the other thread is already waiting on\n // the condition, thus Ihave to wake it up first, otherwise we'll deadlock\n if (COUNTER > 0) {\n pthread_cond_signal(&CONDITION);\n }\n for (;;) {\n COUNTER++;\n pthread_cond_wait(&CONDITION, &LOCK);\n // Always wake up the other thread before processing. The other\n // thread will not be able to do anything as long as I don't go\n // back to sleep first.\n pthread_cond_signal(&CONDITION);\n }\n pthread_mutex_unlock(&LOCK); //To unlock\n}\n\nint64_t timeInMS ()\n{\n struct timeval t;\n\n gettimeofday(&t, NULL);\n return (\n (int64_t)t.tv_sec * 1000 +\n (int64_t)t.tv_usec / 1000\n );\n}\n\n\nint main (\n int argc,\n char ** argv\n) {\n int64_t start;\n pthread_t t1;\n pthread_t t2;\n int64_t myTime;\n\n pthread_mutex_init(&LOCK, NULL);\n pthread_mutex_init(&START, NULL); \n pthread_cond_init(&CONDITION, NULL);\n\n pthread_mutex_lock(&START);\n COUNTER = 0;\n pthread_create(&t1, NULL, threads, NULL);\n pthread_create(&t2, NULL, threads, NULL);\n pthread_detach(t1);\n pthread_detach(t2);\n // Get start time and fire away\n myTime = timeInMS();\n pthread_mutex_unlock(&START);\n // Wait for about a second\n sleep(1);\n // Stop both threads\n pthread_mutex_lock(&LOCK);\n // Find out how much time has really passed. sleep won't guarantee me that\n // I sleep exactly one second, I might sleep longer since even after being\n // woken up, it can take some time before I gain back CPU time. Further\n // some more time might have passed before I obtained the lock!\n myTime = timeInMS() - myTime;\n // Correct the number of thread switches accordingly\n COUNTER = (uint32_t)(((uint64_t)COUNTER * 1000) / myTime);\n printf(\"Number of thread switches in about one second was %u\\n\", COUNTER);\n return 0;\n}\n Number of thread switches in about one second was 108406\n"
},
{
"answer_id": 305394,
"author": "ctacke",
"author_id": 13154,
"author_profile": "https://Stackoverflow.com/users/13154",
"pm_score": 4,
"selected": false,
"text": "DWORD tick;\n\nmain()\n{\n HANDLE hThread = CreateThread(..., ThreadProc, CREATE_SUSPENDED, ...);\n tick = QueryPerformanceCounter();\n CeSetThreadPriority(hThread, 10); // real high\n ResumeThread(hThread);\n Sleep(10);\n}\n\nThreadProc()\n{\n tick = QueryPerformanceCounter() - tick;\n RETAILMSG(TRUE, (_T(\"ET: %i\\r\\n\"), tick));\n}\n"
},
{
"answer_id": 2350769,
"author": "Atmapuri",
"author_id": 283041,
"author_profile": "https://Stackoverflow.com/users/283041",
"pm_score": 2,
"selected": false,
"text": "double * a; \n...\nfor (i = 0; i < 1000; i ++)\n{\n a[i] = a[i] + a[i]\n}\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2877/"
] |
304,777 | <p>I'm using Cruise Control .Net 1.4 for Continuous integration and have installed it on my Windows 2000 desktop. I have Nant 0.85 for the Build. My Source control is in Borland Starteam 2005. I have the .Net 2003 framework installed which I use for creating VB.Net windows applications. I have installed CCNet and I think my CCnet.config file is configured correctly.</p>
<p>The problem that I face is that whenever I change any code and check in Starteam, the modifications are not getting detected by the CCNet server and so I cannot trigger my builds on the basis of modifications. I have to rely on forcebuild for that. But using forcebuild every 1 minute is not acceptable for my project. I want the trigger to be based on modifications. I.e. as soon as a change is detected on Starteam, the build should automatically take place.</p>
<p>My CCNet.config file is this: </p>
<p></p>
<p>
</p>
<pre><code><workingDirectory>C:\Documents and Settings\uj0011637\Desktop\StarteamCruiseControl\CCNet17Nov08</workingDirectory>
<webURL>http://172.24.120.37/ccnet</webURL>
<triggers>
<intervalTrigger name="continuous" seconds="120" buildCondition="ForceBuild" initialSeconds="120"/>
</triggers>
<sourcecontrol type="starteam">
<executable>C:\Program Files\Borland\StarTeam Cross-Platform Client 2005 R2\stcmd.exe</executable>
<project>DEL_CA_ROBOTS\Tools\CCNet17Nov08</project>
<username>600513221</username>
<password>car0b0ts</password>
<host>oscar.nat.bt.com</host>
<port>51234</port>
<autoGetSource>true</autoGetSource>
<timeout units="minutes">10</timeout>
</sourcecontrol>
<tasks>
<!-- Configure NAnt to compile the updated files -->c:\
<nant>
<executable>C:\Documents and Settings\uj0011637\Desktop\Cruise Control\nant\nant-0.85\bin\NAnt.exe</executable>
<baseDirectory>C:\Documents and Settings\uj0011637\Desktop\StarteamCruiseControl\CCNet17Nov08</baseDirectory>
<nologo>false</nologo>
<buildFile>CCNet17Nov08.build</buildFile>
<logger>NAnt.Core.XmlLogger</logger>
<buildTimeoutSeconds>1200</buildTimeoutSeconds>
</nant>
</tasks>
<!--Publishers will be done after the build has completed-->
<publishers>
<xmllogger>
<logDir>C:\Documents and Settings\uj0011637\Desktop\StarteamCruiseControl\Log</logDir>
</xmllogger>
</publishers>
<modificationDelaySeconds>10</modificationDelaySeconds>
</code></pre>
<p> </p>
<p></p>
<p>And my build file is this:</p>
<p>
</p>
<pre><code><target name="clean" description="Delete all previously compiled binaries.">
<delete>
<fileset>
</code></pre>
<pre><code> <include name="**/bin/${project::get-name()}.dll" />
<include name="**/obj/**" />
<include name="**/*.user" />
</fileset>
</delete>
</target>
</code></pre>
<pre><code><target name="rebuild" dependsontarget="clean, build ">
<zip zipfile="${project::get-name()}.zip" verbose="true">
<fileset>
<include name="**/bin/*.dll" />
<include name="**/bin/*.exe" />
</fileset>
<fileset>
<include name="*.aspx" />
<include name="*.css" />
<include name="*.config" />
<include name="*.js" />
<include name="*.asax" />
<include name="**.txt" />
<include name="**.vb" />
<include name="**.vbproj" />
<include name="**.user" />
<include name="**.sln" />
<include name="**.suo" />
<include name="**.resx" />
</fileset>
<fileset prefix="SQL">
<include name="*.sql" />
</fileset>
</zip>
</target>
<target name="unit_test" description="Run unit tests.">
<exec program="${nunit.dir}\nunit-console.exe" commandline="bin/${prjname}.exe /xml=${prjname}.xml /nologo" />
</target>
<target name="build.Console">
<solution configuration="release" solutionfile="CCNet17Nov08.sln">
</solution>
<property name="expected.output" value="bin/${prjname}.exe"/>
<fail unless="${file::exists(expected.output)}">Output file doesn't exist in ${expected.output}</fail>
</target>
</code></pre>
<p></p>
<p>Can anybody please guide me with this?</p>
| [
{
"answer_id": 320157,
"author": "user22925",
"author_id": 22925,
"author_profile": "https://Stackoverflow.com/users/22925",
"pm_score": 0,
"selected": false,
"text": "<project>DEL_CA_ROBOTS\\Tools\\CCNet17Nov08</project> <project>Project_name\\View_name</project>\n <path>StarteamFolderName</path>\n DEL_CA_ROBOTS DEL_CA_ROBOTS <project>DEL_CA_ROBOTS\\DEL_CA_ROBOTS</project>\n <path>Tools\\CCNet17Nov08</path>\n"
},
{
"answer_id": 523678,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<culture>en-US</culture>"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
304,782 | <p>What is JDBC and where can I start learning about?</p>
<p>I know it's a way to access databases with Java, but what problems does it solve? Is it an ORM (or does it try to be)? Does it abstract away differences between databases, at the syntax level? What does it do? and what does it not do?</p>
| [
{
"answer_id": 65205542,
"author": "jonathasrochadesouza",
"author_id": 14591627,
"author_profile": "https://Stackoverflow.com/users/14591627",
"pm_score": 1,
"selected": false,
"text": " Maven: \n<project xmlns=\"http://maven.apache.org/POM/4.0.0\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 \n https://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n <groupId>NameId</groupId>\n <artifactId>NameProjectJava</artifactId>\n <version>0.0.1-SNAPSHOT</version>\n <name>Package</name>\n\n <dependencies>\n\n <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->\n <dependency>\n <groupId>mysql</groupId>\n <artifactId>mysql-connector-java</artifactId>\n <version>8.0.22</version>\n </dependency>\n\n </dependencies>\n\n\n\n Instance database in the Java with JDBC:\n <project xmlns=\"http://maven.apache.org/POM/4.0.0\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 \n https://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n <groupId>NameId</groupId>\n <artifactId>NameProjectJava</artifactId>\n <version>0.0.1-SNAPSHOT</version>\n <name>Package</name>\n\n <dependencies>\n\n <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->\n <dependency>\n <groupId>mysql</groupId>\n <artifactId>mysql-connector-java</artifactId>\n <version>8.0.22</version>\n </dependency>\n\n </dependencies>\n public class DB {\n\nConnection con;\nMysqlDataSource dataSource = new MysqlDataSource();\nprivate Statement stmt;\nprivate ResultSet rs;\nstatic private DB instance;\n\nprivate DB(String host, String user, String password, int port, String dbName) throws SQLException {\n dataSource.setDatabaseName(dbName);\n dataSource.setServerName(host);\n dataSource.setUser(user);\n dataSource.setPassword(password);\n dataSource.setPort(port);\n dataSource.setServerTimezone(\"UTC\");\n}\n\nprivate Connection getConnection() throws SQLException {\n return this.dataSource.getConnection();\n}\n\npublic static DB getInstance() {\n if (instance == null) {\n try {\n instance = new DB(\"localhost\", \"root\", null, 3306, \"group3_hr\");\n } catch (SQLException e) {\n e.printStackTrace();\n }\n }\n return instance;\n}\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6068/"
] |
304,784 | <p>What is the difference between using system() to execute a binary and using the combination of fork/execvp. </p>
<p>Is there any security/portablility/performance difference.</p>
| [
{
"answer_id": 304791,
"author": "unwind",
"author_id": 28169,
"author_profile": "https://Stackoverflow.com/users/28169",
"pm_score": 3,
"selected": false,
"text": "system() exec()"
},
{
"answer_id": 304801,
"author": "flolo",
"author_id": 36472,
"author_profile": "https://Stackoverflow.com/users/36472",
"pm_score": 5,
"selected": true,
"text": "fork exec fork exec system wait system system"
},
{
"answer_id": 304884,
"author": "qrdl",
"author_id": 28494,
"author_profile": "https://Stackoverflow.com/users/28494",
"pm_score": 3,
"selected": false,
"text": "system() fork() exec() fork() exec() system() fork() exec()"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20958/"
] |
304,806 | <p>What is the best way to encode URL strings such that they are rfc2396 compliant and to decode a rfc2396 compliant string such that for example %20 is replaced with a space character?</p>
<p>edit:
URLEncoder and URLDecoder classes do <strong>not</strong> encode/decode rfc2396 compliant URLs, they encode to a MIME type of application/x-www-form-urlencoded which is used to encode HTML form parameter data.</p>
| [
{
"answer_id": 579167,
"author": "larf311",
"author_id": 31169,
"author_profile": "https://Stackoverflow.com/users/31169",
"pm_score": 5,
"selected": true,
"text": "URI uri = new URI(\"http\", \"//www.someurl.com/has spaces in url\", null);\nURL url = uri.toURL();\n String urlString = uri.toASCIIString();"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304806",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18233/"
] |
304,809 | <p>I receive some arguments into a stored procedure. These arguments are NVARCHAR's.</p>
<p>I have a problem, when I need to cast some of these values to FLOATS, because they are being received as e.g.</p>
<p>@VALUE1 NVARCHAR(100)</p>
<p>DECLARE @ChangedValue
SET @ChangedValue = CAST(@Value1 AS FLOAT)</p>
<p>E.g. @Value1 = "0,001"</p>
<p>Gives me a problem, as it expects "0.001"</p>
<p>I can't change the format of the input, but can I somehow change it on the SQL-server side? By changing all "," to "." instead?</p>
<p>Best regards, Kenn</p>
| [
{
"answer_id": 304827,
"author": "Mitch Wheat",
"author_id": 16076,
"author_profile": "https://Stackoverflow.com/users/16076",
"pm_score": 3,
"selected": true,
"text": "@VALUE1 = REPLACE(@VALUE1, ',', '.')"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304809",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39255/"
] |
304,816 | <p>I am pulling data out of an old-school ActiveX in the form of arrays of doubles. I don't initially know the final number of samples I will actually retrieve.</p>
<p>What is the most efficient way to concatenate these arrays together in C# as I pull them out of the system?</p>
| [
{
"answer_id": 304821,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 7,
"selected": true,
"text": "List<T>"
},
{
"answer_id": 306424,
"author": "Constantin",
"author_id": 20310,
"author_profile": "https://Stackoverflow.com/users/20310",
"pm_score": 2,
"selected": false,
"text": "double x = list[i / sampleSize][i % sampleSize];\n for (int iRow = 0; iRow < list.Length; ++iRow) {\n double[] row = list[iRow];\n for (int iCol = 0; iCol < row.Length; ++iCol) {\n double x = row[iCol];\n }\n}\n"
},
{
"answer_id": 309004,
"author": "Jonathan C Dickinson",
"author_id": 24064,
"author_profile": "https://Stackoverflow.com/users/24064",
"pm_score": 2,
"selected": false,
"text": "class Program\n{\n static void Main(string[] args)\n {\n FastConcat<int> i = new FastConcat<int>();\n i.Add(new int[] { 0, 1, 2, 3, 4 });\n Console.WriteLine(i[0]);\n i.Add(new int[] { 5, 6, 7, 8, 9 });\n Console.WriteLine(i[4]);\n\n Console.WriteLine(\"Enumerator:\");\n foreach (int val in i)\n Console.WriteLine(val);\n\n Console.ReadLine();\n }\n}\n\nclass FastConcat<T> : IEnumerable<T>\n{\n LinkedList<T[]> _items = new LinkedList<T[]>();\n int _count;\n\n public int Count\n {\n get\n {\n return _count;\n }\n }\n\n public void Add(T[] items)\n {\n if (items == null)\n return;\n if (items.Length == 0)\n return;\n\n _items.AddLast(items);\n _count += items.Length;\n }\n\n private T[] GetItemIndex(int realIndex, out int offset)\n {\n offset = 0; // Offset that needs to be applied to realIndex.\n int currentStart = 0; // Current index start.\n\n foreach (T[] items in _items)\n {\n currentStart += items.Length;\n if (currentStart > realIndex)\n return items;\n offset = currentStart;\n }\n return null;\n }\n\n public T this[int index]\n {\n get\n {\n int offset;\n T[] i = GetItemIndex(index, out offset);\n return i[index - offset];\n }\n set\n {\n int offset;\n T[] i = GetItemIndex(index, out offset);\n i[index - offset] = value;\n }\n }\n\n #region IEnumerable<T> Members\n\n public IEnumerator<T> GetEnumerator()\n {\n foreach (T[] items in _items)\n foreach (T item in items)\n yield return item;\n }\n\n #endregion\n\n #region IEnumerable Members\n\n System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()\n {\n return GetEnumerator();\n }\n\n #endregion\n}\n"
},
{
"answer_id": 1953729,
"author": "Michael Bahig",
"author_id": 193974,
"author_profile": "https://Stackoverflow.com/users/193974",
"pm_score": 5,
"selected": false,
"text": "String[] theHTMLFiles = Directory.GetFiles(basePath, \"*.html\");\nString[] thexmlFiles = Directory.GetFiles(basePath, \"*.xml\");\nList<String> finalList = new List<String>(theHTMLFiles.Concat<string>(thexmlFiles));\nString[] finalArray = finalList.ToArray();\n"
},
{
"answer_id": 10411892,
"author": "GeorgePotter",
"author_id": 1292730,
"author_profile": "https://Stackoverflow.com/users/1292730",
"pm_score": 5,
"selected": false,
"text": "var z = new int[x.Length + y.Length];\nx.CopyTo(z, 0);\ny.CopyTo(z, x.Length);\n"
},
{
"answer_id": 11450482,
"author": "Lenny Woods",
"author_id": 1520546,
"author_profile": "https://Stackoverflow.com/users/1520546",
"pm_score": 5,
"selected": false,
"text": "IEnumerable<T> .ToArray() byte[] firstArray = {2,45,79,33};\nbyte[] secondArray = {55,4,7,81};\nbyte[] result = firstArray.Concat(secondArray).ToArray();\n"
},
{
"answer_id": 11776322,
"author": "SGRao",
"author_id": 1571208,
"author_profile": "https://Stackoverflow.com/users/1571208",
"pm_score": 3,
"selected": false,
"text": "String[] TextFils = Directory.GetFiles(basePath, \"*.txt\");\nString[] ExcelFils = Directory.GetFiles(basePath, \"*.xls\");\nString[] finalArray = TextFils.Concat(ExcelFils).ToArray();\n String[] Fils = Directory.GetFiles(basePath, \"*.txt\");\nString[] ExcelFils = Directory.GetFiles(basePath, \"*.xls\");\nFils = Fils.Concat(ExcelFils).ToArray();\n"
},
{
"answer_id": 70981383,
"author": "rebell67",
"author_id": 18115948,
"author_profile": "https://Stackoverflow.com/users/18115948",
"pm_score": 0,
"selected": false,
"text": "StringBuilder MemoryStream MemoryStream MemoryStream MemoryStream MemoryStream"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12525/"
] |
304,819 | <p>Is there a way to detect whether IIS is enabled or not?</p>
<p>I know how to check if it is INSTALLED, but I need to know if it's installed but not enabled.</p>
<p>Also, can this be done natively via InstallShield? Checking this via .NET would be acceptable as we can write custom actions, but if there is an IS call then that would be ideal.</p>
<p>Any hints/tips are appreciated, thanks</p>
| [
{
"answer_id": 304821,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 7,
"selected": true,
"text": "List<T>"
},
{
"answer_id": 306424,
"author": "Constantin",
"author_id": 20310,
"author_profile": "https://Stackoverflow.com/users/20310",
"pm_score": 2,
"selected": false,
"text": "double x = list[i / sampleSize][i % sampleSize];\n for (int iRow = 0; iRow < list.Length; ++iRow) {\n double[] row = list[iRow];\n for (int iCol = 0; iCol < row.Length; ++iCol) {\n double x = row[iCol];\n }\n}\n"
},
{
"answer_id": 309004,
"author": "Jonathan C Dickinson",
"author_id": 24064,
"author_profile": "https://Stackoverflow.com/users/24064",
"pm_score": 2,
"selected": false,
"text": "class Program\n{\n static void Main(string[] args)\n {\n FastConcat<int> i = new FastConcat<int>();\n i.Add(new int[] { 0, 1, 2, 3, 4 });\n Console.WriteLine(i[0]);\n i.Add(new int[] { 5, 6, 7, 8, 9 });\n Console.WriteLine(i[4]);\n\n Console.WriteLine(\"Enumerator:\");\n foreach (int val in i)\n Console.WriteLine(val);\n\n Console.ReadLine();\n }\n}\n\nclass FastConcat<T> : IEnumerable<T>\n{\n LinkedList<T[]> _items = new LinkedList<T[]>();\n int _count;\n\n public int Count\n {\n get\n {\n return _count;\n }\n }\n\n public void Add(T[] items)\n {\n if (items == null)\n return;\n if (items.Length == 0)\n return;\n\n _items.AddLast(items);\n _count += items.Length;\n }\n\n private T[] GetItemIndex(int realIndex, out int offset)\n {\n offset = 0; // Offset that needs to be applied to realIndex.\n int currentStart = 0; // Current index start.\n\n foreach (T[] items in _items)\n {\n currentStart += items.Length;\n if (currentStart > realIndex)\n return items;\n offset = currentStart;\n }\n return null;\n }\n\n public T this[int index]\n {\n get\n {\n int offset;\n T[] i = GetItemIndex(index, out offset);\n return i[index - offset];\n }\n set\n {\n int offset;\n T[] i = GetItemIndex(index, out offset);\n i[index - offset] = value;\n }\n }\n\n #region IEnumerable<T> Members\n\n public IEnumerator<T> GetEnumerator()\n {\n foreach (T[] items in _items)\n foreach (T item in items)\n yield return item;\n }\n\n #endregion\n\n #region IEnumerable Members\n\n System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()\n {\n return GetEnumerator();\n }\n\n #endregion\n}\n"
},
{
"answer_id": 1953729,
"author": "Michael Bahig",
"author_id": 193974,
"author_profile": "https://Stackoverflow.com/users/193974",
"pm_score": 5,
"selected": false,
"text": "String[] theHTMLFiles = Directory.GetFiles(basePath, \"*.html\");\nString[] thexmlFiles = Directory.GetFiles(basePath, \"*.xml\");\nList<String> finalList = new List<String>(theHTMLFiles.Concat<string>(thexmlFiles));\nString[] finalArray = finalList.ToArray();\n"
},
{
"answer_id": 10411892,
"author": "GeorgePotter",
"author_id": 1292730,
"author_profile": "https://Stackoverflow.com/users/1292730",
"pm_score": 5,
"selected": false,
"text": "var z = new int[x.Length + y.Length];\nx.CopyTo(z, 0);\ny.CopyTo(z, x.Length);\n"
},
{
"answer_id": 11450482,
"author": "Lenny Woods",
"author_id": 1520546,
"author_profile": "https://Stackoverflow.com/users/1520546",
"pm_score": 5,
"selected": false,
"text": "IEnumerable<T> .ToArray() byte[] firstArray = {2,45,79,33};\nbyte[] secondArray = {55,4,7,81};\nbyte[] result = firstArray.Concat(secondArray).ToArray();\n"
},
{
"answer_id": 11776322,
"author": "SGRao",
"author_id": 1571208,
"author_profile": "https://Stackoverflow.com/users/1571208",
"pm_score": 3,
"selected": false,
"text": "String[] TextFils = Directory.GetFiles(basePath, \"*.txt\");\nString[] ExcelFils = Directory.GetFiles(basePath, \"*.xls\");\nString[] finalArray = TextFils.Concat(ExcelFils).ToArray();\n String[] Fils = Directory.GetFiles(basePath, \"*.txt\");\nString[] ExcelFils = Directory.GetFiles(basePath, \"*.xls\");\nFils = Fils.Concat(ExcelFils).ToArray();\n"
},
{
"answer_id": 70981383,
"author": "rebell67",
"author_id": 18115948,
"author_profile": "https://Stackoverflow.com/users/18115948",
"pm_score": 0,
"selected": false,
"text": "StringBuilder MemoryStream MemoryStream MemoryStream MemoryStream MemoryStream"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7140/"
] |
304,836 | <p>Forgive me for probably using the wrong term for this "application mode".</p>
<p>Our application has a problem during start in that it doesn't show a task bar icon until the main window is up, even though there are loading progress windows, logon-windows, etc. on screen before that.</p>
<p>We change the code to fix this, but unfortunately this fix, when running the app through citrix, now shows two icons, one with just the icon and no text.</p>
<p>Is there a way for me to detect that the application is running through citrix? I don't know the right term for this, but only the app window is brought to the users desktop, not the whole remote desktop.</p>
<p>If it matters, the app is written in Delphi.</p>
| [
{
"answer_id": 304867,
"author": "John Sibly",
"author_id": 1078,
"author_profile": "https://Stackoverflow.com/users/1078",
"pm_score": 5,
"selected": true,
"text": "if (GetSystemMetrics(SM_REMOTESESSION) != 0)\n{\n // We are in a remote session\n}\n #define SM_REMOTESESSION 0x1000\n"
},
{
"answer_id": 416275,
"author": "open-collar",
"author_id": 21686,
"author_profile": "https://Stackoverflow.com/users/21686",
"pm_score": 3,
"selected": false,
"text": "return System.Windows.Forms.SystemInformation.TerminalServerSession;\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/267/"
] |
304,837 | <p>I'm trying to find a way with javascript to highlight the text the user selects when they click some odd highlight button (as in <span style="background-color:yellow">highlighted text</span>). It only has to work with either WebKit or Firefox, but it seems to be well nigh impossible because it has to work in the following cases:</p>
<pre><code><p>this is text</p>
<p>I eat food</p>
</code></pre>
<p>When the user selects from "is text" through "I eat" in the browser (can't just put a span there).</p>
<p>and this case:</p>
<pre><code><span><span>this is text</span>middle text<span>this is text</span></span>
</code></pre>
<p>When the user selects from "is text" to "this is" in the browser (even though you can wrap your highlight spans around each element in the selection, I'd like to see you try to get that middle text highlighted).</p>
<p>This problem doesn't seem to be solved anywhere, frankly I doubt it's possible.</p>
<p>It would be possible if you could get the Range that you get from the selection as a string complete with html which could be parsed and then replaced, but as far as I can tell you can't get the raw html of a Range.. pity.</p>
| [
{
"answer_id": 307229,
"author": "foobar",
"author_id": 14278,
"author_profile": "https://Stackoverflow.com/users/14278",
"pm_score": 3,
"selected": false,
"text": " function load(){\n window.document.designMode = \"On\";\n //run this in a button, will highlight selected text\n window.document.execCommand(\"hiliteColor\", false, \"#768\");\n }\n <html>\n <head>\n\n </head>\n <body contentEditable=\"true\" onload=\"load()\">\n this is text\n </body>\n </html>"
},
{
"answer_id": 317399,
"author": "Cugel",
"author_id": 40353,
"author_profile": "https://Stackoverflow.com/users/40353",
"pm_score": 4,
"selected": false,
"text": "var selection = window.getSelection();\nvar range = selection.getRangeAt(0);\nvar newNode = document.createElement(\"span\");\nnewNode.setAttribute(\"style\", \"background-color: pink;\");\nrange.surroundContents(newNode); \n"
},
{
"answer_id": 12823606,
"author": "underemployedJD",
"author_id": 1725576,
"author_profile": "https://Stackoverflow.com/users/1725576",
"pm_score": 6,
"selected": false,
"text": "function highlightSelection() {\n var userSelection = window.getSelection().getRangeAt(0);\n highlightRange(userSelection);\n\n}\n\nfunction highlightRange(range) {\n var newNode = document.createElement(\"div\");\n newNode.setAttribute(\n \"style\",\n \"background-color: yellow; display: inline;\"\n );\n range.surroundContents(newNode);\n}\n function getSafeRanges(dangerous) {\n var a = dangerous.commonAncestorContainer;\n // Starts -- Work inward from the start, selecting the largest safe range\n var s = new Array(0), rs = new Array(0);\n if (dangerous.startContainer != a)\n for(var i = dangerous.startContainer; i != a; i = i.parentNode)\n s.push(i)\n ;\n if (0 < s.length) for(var i = 0; i < s.length; i++) {\n var xs = document.createRange();\n if (i) {\n xs.setStartAfter(s[i-1]);\n xs.setEndAfter(s[i].lastChild);\n }\n else {\n xs.setStart(s[i], dangerous.startOffset);\n xs.setEndAfter(\n (s[i].nodeType == Node.TEXT_NODE)\n ? s[i] : s[i].lastChild\n );\n }\n rs.push(xs);\n }\n\n // Ends -- basically the same code reversed\n var e = new Array(0), re = new Array(0);\n if (dangerous.endContainer != a)\n for(var i = dangerous.endContainer; i != a; i = i.parentNode)\n e.push(i)\n ;\n if (0 < e.length) for(var i = 0; i < e.length; i++) {\n var xe = document.createRange();\n if (i) {\n xe.setStartBefore(e[i].firstChild);\n xe.setEndBefore(e[i-1]);\n }\n else {\n xe.setStartBefore(\n (e[i].nodeType == Node.TEXT_NODE)\n ? e[i] : e[i].firstChild\n );\n xe.setEnd(e[i], dangerous.endOffset);\n }\n re.unshift(xe);\n }\n\n // Middle -- the uncaptured middle\n if ((0 < s.length) && (0 < e.length)) {\n var xm = document.createRange();\n xm.setStartAfter(s[s.length - 1]);\n xm.setEndBefore(e[e.length - 1]);\n }\n else {\n return [dangerous];\n }\n\n // Concat\n rs.push(xm);\n response = rs.concat(re); \n\n // Send to Console\n return response;\n}\n function highlightSelection() {\n var userSelection = window.getSelection().getRangeAt(0);\n var safeRanges = getSafeRanges(userSelection);\n for (var i = 0; i < safeRanges.length; i++) {\n highlightRange(safeRanges[i]);\n }\n}\n"
},
{
"answer_id": 34544306,
"author": "Nirvik Ghosh",
"author_id": 2115172,
"author_profile": "https://Stackoverflow.com/users/2115172",
"pm_score": 2,
"selected": false,
"text": "function getRangeObject(selectionObject){\n try{ \n if(selectionObject.getRangeAt)\n return selectionObject.getRangeAt(0);\n }\n catch(ex){\n console.log(ex);\n }\n}\ndocument.onmousedown = function(e){\n var text;\n if (window.getSelection) {\n /* get the Selection object */\n userSelection = window.getSelection()\n\n /* get the innerText (without the tags) */ \n text = userSelection.toString();\n\n /* Creating Range object based on the userSelection object */\n var rangeObject = getRangeObject(userSelection);\n\n /* \n This extracts the contents from the DOM literally, inclusive of the tags. \n The content extracted also disappears from the DOM \n */\n contents = rangeObject.extractContents(); \n\n var span = document.createElement(\"span\");\n span.className = \"highlight\";\n span.appendChild(contents);\n\n /* Insert your new span element in the same position from where the selected text was extracted */\n rangeObject.insertNode(span);\n\n } else if (document.selection && document.selection.type != \"Control\") {\n text = document.selection.createRange().text;\n }\n};\n"
},
{
"answer_id": 38682215,
"author": "Henrique Donati",
"author_id": 6659531,
"author_profile": "https://Stackoverflow.com/users/6659531",
"pm_score": 3,
"selected": false,
"text": "function highlightSelection() {\n var userSelection = window.getSelection();\n for(var i = 0; i < userSelection.rangeCount; i++) {\n highlightRange(userSelection.getRangeAt(i));\n }\n\n}\n\nfunction highlightRange(range) {\n var newNode = document.createElement(\"span\");\n newNode.setAttribute(\n \"style\",\n \"background-color: yellow; display: inline;\"\n );\n range.surroundContents(newNode);\n}\n"
},
{
"answer_id": 45629385,
"author": "Muhammad Bilal",
"author_id": 8449396,
"author_profile": "https://Stackoverflow.com/users/8449396",
"pm_score": 3,
"selected": false,
"text": "<!DOCTYPE html>\n <html>\n <head>\n <style type=\"text/css\">\n .highlight\n {\n background-color: yellow;\n }\n #test-text::-moz-selection { /* Code for Firefox */\n\n background: yellow;\n }\n\n #test-text::selection {\n\n background: yellow;\n }\n\n </style>\n </head>\n\n <body>\n <div id=\"div1\" style=\"border: 1px solid #000;\">\n <div id=\"test-text\">\n <h1> Hello How are you </h1>\n <p >\n Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.\n </p>\n </div>\n </div>\n <br />\n\n </body>\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n <script type=\"text/javascript\">\n mouseXPosition = 0;\n $(document).ready(function () {\n\n $(\"#test-text\").mousedown(function (e1) {\n mouseXPosition = e1.pageX;//register the mouse down position\n });\n\n $(\"#test-text\").mouseup(function (e2) {\n var highlighted = false;\n var selection = window.getSelection();\n var selectedText = selection.toString();\n var startPoint = window.getSelection().getRangeAt(0).startOffset;\n var endPoint = window.getSelection().getRangeAt(0).endOffset;\n var anchorTag = selection.anchorNode.parentNode;\n var focusTag = selection.focusNode.parentNode;\n if ((e2.pageX - mouseXPosition) < 0) {\n focusTag = selection.anchorNode.parentNode;\n anchorTag = selection.focusNode.parentNode;\n }\n if (selectedText.length === (endPoint - startPoint)) {\n highlighted = true;\n\n if (anchorTag.className !== \"highlight\") {\n highlightSelection();\n } else {\n var afterText = selectedText + \"<span class = 'highlight'>\" + anchorTag.innerHTML.substr(endPoint) + \"</span>\";\n anchorTag.innerHTML = anchorTag.innerHTML.substr(0, startPoint);\n anchorTag.insertAdjacentHTML('afterend', afterText);\n }\n\n }else{\n if(anchorTag.className !== \"highlight\" && focusTag.className !== \"highlight\"){\n highlightSelection(); \n highlighted = true;\n }\n\n }\n\n\n if (anchorTag.className === \"highlight\" && focusTag.className === 'highlight' && !highlighted) {\n highlighted = true;\n\n var afterHtml = anchorTag.innerHTML.substr(startPoint);\n var outerHtml = selectedText.substr(afterHtml.length, selectedText.length - endPoint - afterHtml.length);\n var anchorInnerhtml = anchorTag.innerHTML.substr(0, startPoint);\n var focusInnerHtml = focusTag.innerHTML.substr(endPoint);\n var focusBeforeHtml = focusTag.innerHTML.substr(0, endPoint);\n selection.deleteFromDocument();\n anchorTag.innerHTML = anchorInnerhtml;\n focusTag.innerHTml = focusInnerHtml;\n var anchorafterHtml = afterHtml + outerHtml + focusBeforeHtml;\n anchorTag.insertAdjacentHTML('afterend', anchorafterHtml);\n\n\n }\n\n if (anchorTag.className === \"highlight\" && !highlighted) {\n highlighted = true;\n var Innerhtml = anchorTag.innerHTML.substr(0, startPoint);\n var afterHtml = anchorTag.innerHTML.substr(startPoint);\n var outerHtml = selectedText.substr(afterHtml.length, selectedText.length);\n selection.deleteFromDocument();\n anchorTag.innerHTML = Innerhtml;\n anchorTag.insertAdjacentHTML('afterend', afterHtml + outerHtml);\n }\n\n if (focusTag.className === 'highlight' && !highlighted) {\n highlighted = true;\n var beforeHtml = focusTag.innerHTML.substr(0, endPoint);\n var outerHtml = selectedText.substr(0, selectedText.length - beforeHtml.length);\n selection.deleteFromDocument();\n focusTag.innerHTml = focusTag.innerHTML.substr(endPoint);\n outerHtml += beforeHtml;\n focusTag.insertAdjacentHTML('beforebegin', outerHtml );\n\n\n }\n if (!highlighted) {\n highlightSelection();\n }\n $('.highlight').each(function(){\n if($(this).html() == ''){\n $(this).remove();\n }\n });\n selection.removeAllRanges();\n });\n });\n\n function highlightSelection() {\n var selection;\n\n //Get the selected stuff\n if (window.getSelection)\n selection = window.getSelection();\n else if (typeof document.selection != \"undefined\")\n selection = document.selection;\n\n //Get a the selected content, in a range object\n var range = selection.getRangeAt(0);\n\n //If the range spans some text, and inside a tag, set its css class.\n if (range && !selection.isCollapsed) {\n if (selection.anchorNode.parentNode == selection.focusNode.parentNode) {\n var span = document.createElement('span');\n span.className = 'highlight';\n span.textContent = selection.toString();\n selection.deleteFromDocument();\n range.insertNode(span);\n // range.surroundContents(span);\n }\n }\n }\n\n </script>\n </html>\n"
},
{
"answer_id": 62856638,
"author": "lastlink",
"author_id": 2875452,
"author_profile": "https://Stackoverflow.com/users/2875452",
"pm_score": 2,
"selected": false,
"text": "import { doHighlight, deserializeHighlights, serializeHighlights, removeHighlights, optionsImpl } from \"@/../node_modules/@funktechno/texthighlighter/lib/index\";\nconst domEle = document.getElementById(\"sandbox\");\nconst options: optionsImpl = {};\nif (this.color) options.color = this.color;\nif (domEle) doHighlight(domEle, true, options);\n <div\n id=\"sandbox\"\n @mouseup=\"runHighlight($event)\"\n>text to highlight</div>\n"
},
{
"answer_id": 69070082,
"author": "Han Jelly",
"author_id": 8282550,
"author_profile": "https://Stackoverflow.com/users/8282550",
"pm_score": 0,
"selected": false,
"text": "<mark> function highlightRange(range) {\n var newNode = document.createElement('mark');\n range.surroundContents(newNode);\n}\n// original select range function\nfunction highlight() {\n var userSelection = window.getSelection();\n for(var i = 0; i < userSelection.rangeCount; i++) {\n highlightRange(userSelection.getRangeAt(i));\n }\n}\n\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304837",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14278/"
] |
304,844 | <p>I'm writing this question in the spirit of answering your own questions, since I found a solution to the problem, but if anyone has a better solution I would gladly listen to it.</p>
<p>In the application I am currently working on I am subclassing the ListView control to add some functionality of which some interacts with the ListView SelectedIndices and SelectedItems properties.</p>
<p>The problem is that when I try to unit test my subclass, the SelectedIndices and SelectedItems properties does not update when I add items to the selection. I tried both </p>
<pre><code>item.Selected = true
</code></pre>
<p>and </p>
<pre><code>listView.SelectedIndices.Add(...)
</code></pre>
<p>But SelectedIndices or SelectedItems simply does not appear to be affected. The unit tests for the other parts of the functionality works fine.</p>
<p>How can I unit test the selection dependent parts of my ListView subclass?</p>
| [
{
"answer_id": 304854,
"author": "Erik Öjebo",
"author_id": 276,
"author_profile": "https://Stackoverflow.com/users/276",
"pm_score": 4,
"selected": true,
"text": " [Test]\n public void CanGetSelectedItems()\n {\n // simple test to make sure that the SelectedIndices\n // property is updated\n using (var f = new DummyForm(listView))\n {\n f.Show();\n\n listView.SelectedIndices.Add(0);\n Assert.AreEqual(1, listView.SelectedIndices.Count);\n }\n }\n\n private class DummyForm : Form\n {\n public DummyForm(ListView listView)\n {\n // Minimize and make it not appear in taskbar to\n // avoid flicker etc when running the tests\n this.WindowState = FormWindowState.Minimized;\n this.ShowInTaskbar = false;\n this.Controls.Add(listView);\n }\n }\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/276/"
] |
304,847 | <p>I wish to set a usererror string before leaving a function, depending on the return code and variable in the function.</p>
<p>I currently have:</p>
<pre><code>Dim RetVal as RetType
try
...
if ... then
RetVal = RetType.FailedParse
end try
endif
...
finally
select case RetVal
case ...
UserStr = ...
end select
end try
return RetVal
</code></pre>
<p>Is it possible to use return RetType.FailedParse, then access this in the finally block?</p>
| [
{
"answer_id": 304860,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 3,
"selected": true,
"text": "SomeType result = default(SomeType); // for \"definite assignment\"\ntry {\n // ...\n return result;\n}\nfinally {\n // inspect \"result\"\n}\n"
},
{
"answer_id": 344042,
"author": "CestLaGalere",
"author_id": 6684,
"author_profile": "https://Stackoverflow.com/users/6684",
"pm_score": 1,
"selected": false,
"text": "Public Function MyFunc() as integer\n Try\n if DoSomething() = FAIL Then\n return FAIL\n end if\n\n Finally\n if MyFunc = FAIL then\n Me.ErrorMsg = \"failed\"\n endif\n End Try\nEnd Function\n if MyFunc = FAIL Then\n if MyFunc() = FAIL Then\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304847",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6684/"
] |
304,864 | <p>I want to check if a variable has a valid year using a regular expression. Reading the <a href="http://www.gnu.org/software/bash/manual/html_node/Conditional-Constructs.html" rel="noreferrer">bash manual</a> I understand I could use the operator =~</p>
<p>Looking at the example below, I would expect to see "not OK" but I see "OK". What am I doing wrong?</p>
<pre><code>i="test"
if [ $i=~"200[78]" ]
then
echo "OK"
else
echo "not OK"
fi
</code></pre>
| [
{
"answer_id": 304922,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 8,
"selected": true,
"text": "i=\"test\"\nif [[ $i =~ 200[78] ]] ; then\n echo \"OK\"\nelse\n echo \"not OK\"\nfi\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17876/"
] |
304,883 | <p>I just installed a linux system (Kubuntu) and was wondering if there is a program to make python programs executable for linux.</p>
| [
{
"answer_id": 304896,
"author": "Vincent Van Den Berghe",
"author_id": 39259,
"author_profile": "https://Stackoverflow.com/users/39259",
"pm_score": 9,
"selected": true,
"text": "#!/usr/bin/env python\n chmod +x myfile.py\n ./myfile.py\n"
},
{
"answer_id": 14230576,
"author": "Mohit Dabas",
"author_id": 1485906,
"author_profile": "https://Stackoverflow.com/users/1485906",
"pm_score": 3,
"selected": false,
"text": "/usr/bin/python #!/usr/bin/python\n chmod +x script_name.py ./script_name.py"
},
{
"answer_id": 39980094,
"author": "Coco",
"author_id": 4582696,
"author_profile": "https://Stackoverflow.com/users/4582696",
"pm_score": 0,
"selected": false,
"text": "alias printhello='python /home/hello_world.py'\n printhello gedit ~/.bashrc\n"
},
{
"answer_id": 48661346,
"author": "Nilesh K.",
"author_id": 8438569,
"author_profile": "https://Stackoverflow.com/users/8438569",
"pm_score": 3,
"selected": false,
"text": "hello.py which python hello.py #!/usr/bin/python chmod chmod +x hello.py ./hello.py"
},
{
"answer_id": 66703759,
"author": "Gandharva S Murthy",
"author_id": 5830392,
"author_profile": "https://Stackoverflow.com/users/5830392",
"pm_score": 0,
"selected": false,
"text": "#!/usr/bin/python\n chmod +x <script-name>.py\n <script-name>.py /usr/local/bin ln -s <path-to-your-script> /usr/local/bin/<executable-name-you-want>\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
304,885 | <p>I am using MVC architecture for a GUI application. The model class has some C functions. One of the C functions calls some methods of Objective-C class. I call those methods using an object of that class. The strange thing happening is that methods previously to the an xyz method are called perfectly but when that xyz method is called, that method and the methods after it aren't getting executed.
I don't get any errors. So can't figure out what exactly is happening.
Any ideas as to what might be the reason for this?</p>
| [
{
"answer_id": 304990,
"author": "diciu",
"author_id": 2811,
"author_profile": "https://Stackoverflow.com/users/2811",
"pm_score": 6,
"selected": false,
"text": "#import <Cocoa/Cocoa.h>\n\nid refToSelf;\n\n@interface SomeClass: NSObject\n@end\n\n@implementation SomeClass\n- (void) doNothing\n{\n NSLog(@\"Doing nothing\");\n}\n@end\n\nint otherCfunction()\n{\n [refToSelf doNothing];\n}\n\n\nint main()\n{\n\n NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];\n\n SomeClass * t = [[SomeClass alloc] init];\n refToSelf = t;\n\n otherCfunction();\n\n [pool release];\n}\n"
},
{
"answer_id": 44039705,
"author": "NoWall",
"author_id": 4345834,
"author_profile": "https://Stackoverflow.com/users/4345834",
"pm_score": 0,
"selected": false,
"text": "@implementation\n// Define a object\nClassName *thisClass;\n thisClass = self;\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304885",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39270/"
] |
304,907 | <p>I recently discovered Powershell and through that <a href="http://code.google.com/p/psake/" rel="nofollow noreferrer">PSake</a>. If you are using it and you've extended it or created tasks for it, please share!</p>
| [
{
"answer_id": 304990,
"author": "diciu",
"author_id": 2811,
"author_profile": "https://Stackoverflow.com/users/2811",
"pm_score": 6,
"selected": false,
"text": "#import <Cocoa/Cocoa.h>\n\nid refToSelf;\n\n@interface SomeClass: NSObject\n@end\n\n@implementation SomeClass\n- (void) doNothing\n{\n NSLog(@\"Doing nothing\");\n}\n@end\n\nint otherCfunction()\n{\n [refToSelf doNothing];\n}\n\n\nint main()\n{\n\n NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];\n\n SomeClass * t = [[SomeClass alloc] init];\n refToSelf = t;\n\n otherCfunction();\n\n [pool release];\n}\n"
},
{
"answer_id": 44039705,
"author": "NoWall",
"author_id": 4345834,
"author_profile": "https://Stackoverflow.com/users/4345834",
"pm_score": 0,
"selected": false,
"text": "@implementation\n// Define a object\nClassName *thisClass;\n thisClass = self;\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304907",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6846/"
] |
304,918 | <p>I have a server process built in Delphi/C++Builder with RemObjects SDK which claims to support SOAP requests.</p>
<p>What's the quickest and easiest way of testing out the SOAP support? I'd prefer not to have to learn a new language/install a new IDE/spend more than a day...</p>
<p>To clarify this, I'm already connecting to the server happily using the RO native protocol, and have SOAP enabled, but I want to test how systems NOT based on the RO SDK can use it. Using RO SOAP for both client and server doesn't accomplish this...</p>
| [
{
"answer_id": 305042,
"author": "Bruce McGee",
"author_id": 19183,
"author_profile": "https://Stackoverflow.com/users/19183",
"pm_score": 4,
"selected": true,
"text": "function GetMyServerSoap(UseWSDL: Boolean=System.False; Addr: string=''; HTTPRIO: THTTPRIO = nil): MyServerSoap;\n"
},
{
"answer_id": 1893585,
"author": "mjn",
"author_id": 80901,
"author_profile": "https://Stackoverflow.com/users/80901",
"pm_score": 2,
"selected": false,
"text": "* inspecting Web Services\n* invoking Web Services\n* developing Web Services\n* Web Services Simulation and Mocking\n* Functional, Load and Compliance testing of Web Services\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1737/"
] |
304,920 | <p>Ease of installation/use is the most important factor here - not performance.</p>
<p>Small is OK as large datasets are not expected.</p>
| [
{
"answer_id": 1386901,
"author": "Eric Schoonover",
"author_id": 3957,
"author_profile": "https://Stackoverflow.com/users/3957",
"pm_score": 1,
"selected": false,
"text": "var gds = new GraphDataSource();\ngds.Read<RdfXmlReader>(File.ReadAllText(@\"C:\\graph.owl\"));\nTable results = gds.Query(\"select ?s ?p ?o where {?s ?p ?o} limit 10\");\n"
},
{
"answer_id": 2709097,
"author": "Arto Bendiken",
"author_id": 320911,
"author_profile": "https://Stackoverflow.com/users/320911",
"pm_score": 2,
"selected": false,
"text": "$ sudo gem install rdf\n graph = RDF::Graph.load(\"http://datagraph.org/jhacker/foaf.rdf\")\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17398/"
] |
304,932 | <p>I am running into the problem of the "hanging JFileChooser" as described in the following threads:</p>
<p><a href="http://forums.sun.com/thread.jspa?threadID=5309960" rel="noreferrer">http://forums.sun.com/thread.jspa?threadID=5309960</a></p>
<p><a href="http://forums.sun.com/thread.jspa?threadID=724817" rel="noreferrer">http://forums.sun.com/thread.jspa?threadID=724817</a></p>
<p><a href="http://x86.sun.com/thread.jspa?threadID=5275999&messageID=10156541" rel="noreferrer">http://x86.sun.com/thread.jspa?threadID=5275999&messageID=10156541</a></p>
<p>I am using JVM 1.6.0_07-b06. It happens on Windows XP as well as on Windows Vista.</p>
<p>Has anybody found a workaround for this yet?</p>
| [
{
"answer_id": 322129,
"author": "luiscubal",
"author_id": 32775,
"author_profile": "https://Stackoverflow.com/users/32775",
"pm_score": 0,
"selected": false,
"text": "\npublic static JFileChooser chooser = null;\n\npublic static void doSomething(){\n if(chooser==null)\n chooser = new JFileChooser();\n //use JFileChooser\n}\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20999/"
] |
304,940 | <p>MS SQL has a convenient workaround for concatenating a column value from multiple rows into one value:</p>
<pre><code>SELECT col1
FROM table1
WHERE col2 = 'x'
ORDER by col3
FOR XML path('')
</code></pre>
<p>and that returns a nice recordset:</p>
<pre><code>XML_F52E2B61-18A1-11d1-B105-00805F49916B
----------------------------------------
<col1>Foo</col1><col1>Bar</col1>
</code></pre>
<p>only the column name in the returned recordset is rather nasty!</p>
<p>The column name seems to include random elements (or a GUID), and hence I am reluctant to use it in my application (different instances or different servers might have another GUID). Unfortunately I cannot use * to select the value, and due to the restrictions in the existing application I cannot iterate through returned columns, either...</p>
<p>Is there a way to force the column name in the returned recordset to something more sensible?</p>
| [
{
"answer_id": 304980,
"author": "kristof",
"author_id": 3241,
"author_profile": "https://Stackoverflow.com/users/3241",
"pm_score": 7,
"selected": true,
"text": "select(\nSELECT col1\n FROM table1\n WHERE col2 = 'x'\n ORDER by col3\n FOR XML path('')\n) as myName\n"
},
{
"answer_id": 11736169,
"author": "Vadym Sichkar",
"author_id": 1299375,
"author_profile": "https://Stackoverflow.com/users/1299375",
"pm_score": 2,
"selected": false,
"text": "declare @requestResultXML xml\n\nset @requestResultXML =\n (\n SELECT 'NPOIT-1.0' AS '@Interface',\n (\n select 'Query' as '@Type',\n 'GetBill' as '@Query',\n 'True' as '@CompressResult'\n FOR XML PATH('Head'), TYPE\n ),\n (\n select @pin as '@PIN',\n @period as '@Period',\n @number as '@Number',\n @barcode as '@Barcode'\n FOR XML PATH('QueryParams'), TYPE\n ) as Data\n\n FOR XML PATH('DataExchangeModule') \n )\n\nselect @requestResultXML as GetBillRequest\n"
},
{
"answer_id": 16081256,
"author": "Black Light",
"author_id": 314895,
"author_profile": "https://Stackoverflow.com/users/314895",
"pm_score": 4,
"selected": false,
"text": "select\n(\n select '@greeting' = 'hello', '@where' = 'there', '@who' = 'world'\n for xml path ('salutation'), type\n) as 'MyName'\n"
},
{
"answer_id": 27988030,
"author": "JJ Roman",
"author_id": 213292,
"author_profile": "https://Stackoverflow.com/users/213292",
"pm_score": 1,
"selected": false,
"text": "SELECT \n CAST( \n (\n SELECT \n * \n FROM (\n SELECT \n 1 AS Tag\n ,NULL AS Parent\n ...\n UNION ALL\n SELECT ...\n FOR XML EXPLICIT\n )\n ) as XML) as [MyName]\n"
},
{
"answer_id": 46972316,
"author": "Mahadev",
"author_id": 8842824,
"author_profile": "https://Stackoverflow.com/users/8842824",
"pm_score": 0,
"selected": false,
"text": "DECLARE @XmlData XML;\n\nSET @XmlData = (\n SELECT *\n FROM [dbo].[TABLE1]\n FOR XML PATH('ChildNodeDetailsResponse')\n ,ROOT('ParentNode')\n )\n\nSELECT @XmlData AS Result\n"
},
{
"answer_id": 46972555,
"author": "Mahadev",
"author_id": 8842824,
"author_profile": "https://Stackoverflow.com/users/8842824",
"pm_score": 1,
"selected": false,
"text": "DECLARE @XmlData XML;\nSET @XmlData =(SELECT * FROM [dbo].[Users] ORDER by UserName FOR XML path(''))\nSELECT @XmlData AS Result\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304940",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4505/"
] |
304,960 | <p>I was wondering if there was a way to tell if an instance of Oracle on a system has a database installed or not?</p>
<p>This is for an installation script, and I need to verify that there is an actual database in place before proceeding with the loading of my own tablespace onto that database. Has anyone tackled this problem before?</p>
<p>Cheers</p>
| [
{
"answer_id": 304971,
"author": "ninesided",
"author_id": 1030,
"author_profile": "https://Stackoverflow.com/users/1030",
"pm_score": 2,
"selected": false,
"text": "tnsping"
},
{
"answer_id": 306426,
"author": "Mac",
"author_id": 8696,
"author_profile": "https://Stackoverflow.com/users/8696",
"pm_score": 3,
"selected": false,
"text": "HKLM\\SOFTWARE\\ORACLE KEY_ KEY_OraDb10g_home1 ORA_ _AUTOSTART ORA_XE_AUTOSTART ORACLE_HOME"
},
{
"answer_id": 14247214,
"author": "Maha",
"author_id": 1572706,
"author_profile": "https://Stackoverflow.com/users/1572706",
"pm_score": -1,
"selected": false,
"text": "$yum grouplist | grep SQL\n MySQL Database client\nMySQL Database server\nPostgreSQL Database client\nPostgreSQL Database server\n $yum grouplist | grep Orac\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5827/"
] |
304,967 | <p>Are there any utilities that can examine a set of managed assemblies and tell you whether any of the types in one namespace depend on any in another? For example, say I have a <code>MyApp.BusinessRules</code> namespace and don't want it to access directly anything in <code>MyApp.GUI</code>, but both namespaces are in the same assembly. My goal is to be able to write a custom MSBuild task that verifies that various coupling rules have not been broken.</p>
<p>So far the only tool I have come across that looks like it might do this is <a href="http://www.ndepend.com/" rel="noreferrer">NDepend</a>, but I am wondering if there is a simpler solution.</p>
| [
{
"answer_id": 306445,
"author": "Patrick from NDepend team",
"author_id": 27194,
"author_profile": "https://Stackoverflow.com/users/27194",
"pm_score": 3,
"selected": true,
"text": "warnif count > 0\nlet businessRules = Application.Namespaces.WithNameLike(\"^MyApp.BusinessRules\")\nlet gui = Application.Namespaces.WithNameLike(\"^MyApp.GUI\")\n\nfrom n in businessRules.UsingAny(gui)\nlet guidNamespacesUsed = n.NamespacesUsed.Intersect(gui)\nselect new { n, guidNamespacesUsed }\n"
},
{
"answer_id": 67190249,
"author": "Alexander Christov",
"author_id": 1432407,
"author_profile": "https://Stackoverflow.com/users/1432407",
"pm_score": 1,
"selected": false,
"text": "config.nsdepcop"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304967",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7532/"
] |
304,977 | <p>Anyone know whether it is possible to put mod_python under JBoss like you can Apache HTTPD? Given that JBoss has Tomcat inside it would seem to be a reasonable thing to do.</p>
<p>If not mod_python is there any python support under JBoss which will keep the interpreter in memory?</p>
| [
{
"answer_id": 304988,
"author": "toolkit",
"author_id": 3295,
"author_profile": "https://Stackoverflow.com/users/3295",
"pm_score": 2,
"selected": false,
"text": "mod_perl"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24039/"
] |
304,979 | <p>Since there is no <code>finally</code> in C++ <a href="http://www.research.att.com/~bs/bs_faq2.html#finally" rel="noreferrer">you have to use the RAII</a> design pattern instead, if you want your code to be exception safe. One way to do this is by using the destructor of a local class like this:</p>
<pre><code>void foo() {
struct Finally {
~Finally() { /* cleanup code */ }
} finalizer();
// ...code that might throw an exception...
}
</code></pre>
<p>This is a big advantage over the straight forward solution, because you don't have to write the cleanup code 2 times:</p>
<pre><code>try {
// ...code that might throw an exception...
// cleanup code (no exception)
} catch (...) {
// cleanup code (exception)
throw;
}
</code></pre>
<p>A big disadvantage of the local class solution is that you can't directly access local variables in your cleanup code. So it will bloat your code a lot if you need access to them regardless:</p>
<pre><code>void foo() {
Task* task;
while (task = nextTask()) {
task->status = running;
struct Finally {
Task* task;
Finally(Task* task) : task(task) {}
~Finally() { task->status = idle; }
} finalizer(task);
// ...code that might throw an exception...
}
}
</code></pre>
<p><strong>So my question is:</strong> Is there a solution which combines both advantages? So that you a) don't have to write duplicate code and b) can access local variables in the cleanup code, like <code>task</code> in the last example, but without such code bloat.</p>
| [
{
"answer_id": 305061,
"author": "Sébastien RoccaSerra",
"author_id": 2797,
"author_profile": "https://Stackoverflow.com/users/2797",
"pm_score": 5,
"selected": true,
"text": "struct Finally Task ScopeGuard guard = MakeGuard(&Task::cleanup, task);\n"
},
{
"answer_id": 305868,
"author": "jalf",
"author_id": 33213,
"author_profile": "https://Stackoverflow.com/users/33213",
"pm_score": 1,
"selected": false,
"text": "void foo() {\n// Task* task;\nScopedTask task; // Some type which internally stores a Task*, but also contains a destructor for RAII cleanup\n while (task = nextTask()) {\n task->status = running;\n // ...code that might throw an exception...\n }\n}\n"
},
{
"answer_id": 313947,
"author": "Roddy",
"author_id": 1737,
"author_profile": "https://Stackoverflow.com/users/1737",
"pm_score": 2,
"selected": false,
"text": "class Runner {\nprivate:\n Task & task;\n State oldstate;\npublic:\n Runner (Task &t, State newstate) : task(t), oldstate(t.status); \n {\n task.status = newstate;\n };\n\n ~Runner() \n {\n task.status = oldstate;\n };\n};\n\nvoid foo() \n{\n Task* task;\n while (task = nextTask())\n {\n Runner r(*task, running);\n // ...code that might throw an exception...\n }\n}\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36372/"
] |
304,986 | <p>I have a GSM modem connected via USB. The modem creates 2 serial ports. The first is automatically attached to the modem, the second shows in Device Manager as "HUAWEI Mobile Connect - 3G PC UI Interface (COM6)"</p>
<p>The second port is used to get vital information from the modem, such as signal quality; to send and receive text messages; and a whole host of other functions.</p>
<p>I am writing an application that will wrap up some of the features provided by the second port. What I need is a sure fire method of identifying which COM port is the spare one. Iterating the ports and checking a response to "ATE0" is not sufficient. The modem's port is usually the lower numbered one, and when a dial up connection is not active, it will respond to "ATE0" the same as the second port.</p>
<p>What I was thinking of doing is iterating the ports and checking their friendly name, as it shows in Device Manager. That way I can link the port in my application to the port labelled "HUAWEI Mobile Connect - 3G PC UI Interface (COM6)" in Device Manager. I've just not found any information yet that will allow me to get that name programmatically.</p>
| [
{
"answer_id": 305013,
"author": "Will Dean",
"author_id": 987,
"author_profile": "https://Stackoverflow.com/users/987",
"pm_score": 3,
"selected": false,
"text": " GUID guid = GUID_DEVCLASS_PORTS;\n\nSP_DEVICE_INTERFACE_DATA interfaceData;\nZeroMemory(&interfaceData, sizeof(interfaceData));\ninterfaceData.cbSize = sizeof(interfaceData);\n\nSP_DEVINFO_DATA devInfoData;\nZeroMemory(&devInfoData, sizeof(devInfoData));\ndevInfoData.cbSize = sizeof(devInfoData);\n\nif(SetupDiEnumDeviceInfo(\n hDeviceInfo, // Our device tree\n nDevice, // The member to look for\n &devInfoData\n ))\n{\n DWORD regDataType;\n\n BYTE hardwareId[300];\n if(SetupDiGetDeviceRegistryProperty(hDeviceInfo, &devInfoData, SPDRP_HARDWAREID, ®DataType, hardwareId, sizeof(hardwareId), NULL))\n {\n...\n BYTE friendlyName[300];\n if(SetupDiGetDeviceRegistryProperty(hDeviceInfo, &devInfoData, SPDRP_FRIENDLYNAME, NULL, friendlyName, sizeof(friendlyName), NULL))\n {\n strFriendlyNames += (LPCTSTR)friendlyName;\n strFriendlyNames += '\\n';\n }\n"
},
{
"answer_id": 305581,
"author": "Richard C",
"author_id": 6389,
"author_profile": "https://Stackoverflow.com/users/6389",
"pm_score": 3,
"selected": true,
"text": "internal static string GetComPortByDescription(string Description)\n{\n string Result = string.Empty;\n Guid guid = PInvoke.GUID_DEVCLASS_PORTS;\n uint nDevice = 0;\n uint nBytes = 300;\n byte[] retval = new byte[nBytes];\n uint RequiredSize = 0;\n uint PropertyRegDataType = 0;\n\n PInvoke.SP_DEVINFO_DATA devInfoData = new PInvoke.SP_DEVINFO_DATA();\n devInfoData.cbSize = Marshal.SizeOf(typeof(PInvoke.SP_DEVINFO_DATA));\n\n IntPtr hDeviceInfo = PInvoke.SetupDiGetClassDevs(\n ref guid, \n null, \n IntPtr.Zero, \n PInvoke.DIGCF.DIGCF_PRESENT);\n\n while (PInvoke.SetupDiEnumDeviceInfo(hDeviceInfo, nDevice++, ref devInfoData))\n {\n if (PInvoke.SetupDiGetDeviceRegistryProperty(\n hDeviceInfo, \n ref devInfoData, \n PInvoke.SPDRP.SPDRP_FRIENDLYNAME,\n out PropertyRegDataType, \n retval, \n nBytes, \n out RequiredSize))\n {\n if (System.Text.Encoding.Unicode.GetString(retval).Substring(0, Description.Length).ToLower() ==\n Description.ToLower())\n {\n string tmpstring = System.Text.Encoding.Unicode.GetString(retval);\n Result = tmpstring.Substring(tmpstring.IndexOf(\"COM\"),tmpstring.IndexOf(')') - tmpstring.IndexOf(\"COM\"));\n } // if retval == description\n } // if (PInvoke.SetupDiGetDeviceRegistryProperty( ... SPDRP_FRIENDLYNAME ...\n } // while (PInvoke.SetupDiEnumDeviceInfo(hDeviceInfo, nDevice++, ref devInfoData))\n\n PInvoke.SetupDiDestroyDeviceInfoList(hDeviceInfo);\n return Result;\n}\n Result = tmpstring.Substring(tmpstring.IndexOf(\"COM\"),tmpstring.IndexOf(')') - tmpstring.IndexOf(\"COM\"));"
},
{
"answer_id": 1055087,
"author": "Ilya",
"author_id": 130066,
"author_profile": "https://Stackoverflow.com/users/130066",
"pm_score": 2,
"selected": false,
"text": "SetupDiOpenDevRegKey(hDevInfo, devInfoData, DICS_FLAG_GLOBAL, 0, DIREG_DEV, KEY_READ) HKEY REG_SZ HKEY"
},
{
"answer_id": 45613884,
"author": "Leherenn",
"author_id": 4301117,
"author_profile": "https://Stackoverflow.com/users/4301117",
"pm_score": 2,
"selected": false,
"text": "#include <windows.h>\n#include <initguid.h>\n#include <devguid.h>\n#include <setupapi.h>\n\nvoid enumerateSerialPortsFriendlyNames()\n{\n SP_DEVINFO_DATA devInfoData = {};\n devInfoData.cbSize = sizeof(devInfoData);\n\n // get the tree containing the info for the ports\n HDEVINFO hDeviceInfo = SetupDiGetClassDevs(&GUID_DEVCLASS_PORTS,\n 0,\n nullptr,\n DIGCF_PRESENT\n );\n if (hDeviceInfo == INVALID_HANDLE_VALUE)\n {\n return;\n }\n\n // iterate over all the devices in the tree\n int nDevice = 0;\n while (SetupDiEnumDeviceInfo(hDeviceInfo, // Our device tree\n nDevice++, // The member to look for\n &devInfoData))\n {\n DWORD regDataType;\n DWORD reqSize = 0;\n\n // find the size required to hold the device info\n SetupDiGetDeviceRegistryProperty(hDeviceInfo, &devInfoData, SPDRP_HARDWAREID, nullptr, nullptr, 0, &reqSize);\n BYTE* hardwareId = new BYTE[(reqSize > 1) ? reqSize : 1];\n // now store it in a buffer\n if (SetupDiGetDeviceRegistryProperty(hDeviceInfo, &devInfoData, SPDRP_HARDWAREID, ®DataType, hardwareId, sizeof(hardwareId) * reqSize, nullptr))\n {\n // find the size required to hold the friendly name\n reqSize = 0;\n SetupDiGetDeviceRegistryProperty(hDeviceInfo, &devInfoData, SPDRP_FRIENDLYNAME, nullptr, nullptr, 0, &reqSize);\n BYTE* friendlyName = new BYTE[(reqSize > 1) ? reqSize : 1];\n // now store it in a buffer\n if (!SetupDiGetDeviceRegistryProperty(hDeviceInfo, &devInfoData, SPDRP_FRIENDLYNAME, nullptr, friendlyName, sizeof(friendlyName) * reqSize, nullptr))\n {\n // device does not have this property set\n memset(friendlyName, 0, reqSize > 1 ? reqSize : 1);\n }\n // use friendlyName here\n delete[] friendlyName;\n }\n delete[] hardwareId;\n }\n}\n"
},
{
"answer_id": 63294438,
"author": "zezba9000",
"author_id": 456832,
"author_profile": "https://Stackoverflow.com/users/456832",
"pm_score": 0,
"selected": false,
"text": "public static class SerialPortUtils\n{\n private static Guid GUID_DEVCLASS_PORTS = new Guid(0x4d36e978u, 0xe325, 0x11ce, 0xbf, 0xc1, 0x08, 0x00, 0x2b, 0xe1, 0x03, 0x18);\n\n private unsafe static bool GetPortRegistryProperty(HDEVINFO classHandle, SP_DEVINFO_DATA* deviceInfo, uint spdrp, out string result)\n {\n DWORD size;\n SetupAPI.SetupDiGetDeviceRegistryPropertyW(classHandle, deviceInfo, spdrp, null, null, 0, &size);\n if (size == 0)\n {\n result = null;\n return false;\n }\n\n var resultBuffer = new byte[(int)size];\n fixed (byte* resultBufferPtr = resultBuffer)\n {\n if (SetupAPI.SetupDiGetDeviceRegistryPropertyW(classHandle, deviceInfo, spdrp, null, resultBufferPtr, size, null))\n {\n result = Encoding.Unicode.GetString(resultBufferPtr, (int)size - sizeof(char));\n return true;\n }\n else\n {\n result = null;\n return false;\n }\n }\n }\n\n public unsafe static List<SerialPortDeviceDesc> GetSerialPortDevices()\n {\n var results = new List<SerialPortDeviceDesc>();\n\n // get present ports handle\n var classHandle = SetupAPI.SetupDiGetClassDevsW(ref GUID_DEVCLASS_PORTS, null, IntPtr.Zero, SetupAPI.DIGCF_PRESENT);\n if (classHandle == Common.INVALID_HANDLE_VALUE || classHandle == HDEVINFO.Zero) throw new Exception(\"SetupDiGetClassDevsW failed\");\n\n // enumerate all ports\n var deviceInfo = new SP_DEVINFO_DATA();\n uint deviceInfoSize = (uint)Marshal.SizeOf<SP_DEVINFO_DATA>();\n deviceInfo.cbSize = deviceInfoSize;\n uint index = 0;\n while (SetupAPI.SetupDiEnumDeviceInfo(classHandle, index, &deviceInfo))\n {\n // get port name\n string portName;\n HKEY regKey = SetupAPI.SetupDiOpenDevRegKey(classHandle, &deviceInfo, SetupAPI.DICS_FLAG_GLOBAL, 0, SetupAPI.DIREG_DEV, WinNT.KEY_READ);\n if (regKey == Common.INVALID_HANDLE_VALUE || regKey == IntPtr.Zero) continue;\n using (var regHandle = new SafeRegistryHandle(regKey, true))\n using (var key = RegistryKey.FromHandle(regHandle))\n {\n portName = key.GetValue(\"PortName\") as string;\n if (string.IsNullOrEmpty(portName)) continue;\n }\n\n // get registry values\n if (!GetPortRegistryProperty(classHandle, &deviceInfo, SetupAPI.SPDRP_FRIENDLYNAME, out string friendlyName)) continue;\n if (!GetPortRegistryProperty(classHandle, &deviceInfo, SetupAPI.SPDRP_HARDWAREID, out string hardwareID)) continue;\n\n // add device\n results.Add(new SerialPortDeviceDesc(friendlyName, portName, hardwareID));\n\n // setup for next device\n ++index;\n deviceInfo = new SP_DEVINFO_DATA();\n deviceInfo.cbSize = deviceInfoSize;\n }\n\n // finish\n SetupAPI.SetupDiDestroyDeviceInfoList(classHandle);\n return results;\n }\n}\n public enum SerialPortType\n{\n Unknown,\n COM\n}\n\npublic class SerialPortDeviceDesc\n{\n public readonly string friendlyName, portName, hardwareID;\n public readonly string vid, pid;\n public readonly int portNumber = -1;\n public readonly SerialPortType portType = SerialPortType.Unknown;\n\n public SerialPortDeviceDesc(string friendlyName, string portName, string hardwareID)\n {\n this.friendlyName = friendlyName;\n this.portName = portName;\n this.hardwareID = hardwareID;\n\n if (portName.StartsWith(\"COM\") && int.TryParse(portName.Substring(\"COM\".Length), out portNumber))\n {\n portType = SerialPortType.COM;\n }\n else\n {\n portNumber = -1;\n }\n\n var rx = Regex.Match(hardwareID, @\"VID_(\\w*)&PID_(\\w*)\", RegexOptions.IgnoreCase);\n if (rx.Success)\n {\n vid = rx.Groups[1].Value;\n pid = rx.Groups[2].Value;\n }\n }\n}\n"
},
{
"answer_id": 64981067,
"author": "JOE",
"author_id": 5007540,
"author_profile": "https://Stackoverflow.com/users/5007540",
"pm_score": 1,
"selected": false,
"text": "std::vector<SerialPortInfo> comPorts = SerialPort::getSerialPortList();\nstd::cout << comPorts[0].friendlyName << std::endl;\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6389/"
] |
304,996 | <p>I'm trying to read a Paradox 5 table into a dataset or simular data structure with the view to putting it into an SQL server 2005 table. I've trawled google and SO but with not much luck. I've tried ODBC:</p>
<pre><code>public void ParadoxGet()
{
string ConnectionString = @"Driver={Microsoft Paradox Driver (*.db )};DriverID=538;Fil=Paradox 5.X;DefaultDir=C:\Data\;Dbq=C:\Data\;CollatingSequence=ASCII;";
DataSet ds = new DataSet();
ds = GetDataSetFromAdapter(ds, ConnectionString, "SELECT * FROM Growth");
foreach (String s in ds.Tables[0].Rows)
{
Console.WriteLine(s);
}
}
public DataSet GetDataSetFromAdapter(DataSet dataSet, string connectionString, string queryString)
{
using (OdbcConnection connection = new OdbcConnection(connectionString))
{
OdbcDataAdapter adapter = new OdbcDataAdapter(queryString, connection);
connection.Open();
adapter.Fill(dataSet);
connection.Close();
}
return dataSet;
}
</code></pre>
<p>This just return the error </p>
<blockquote>
<p>ERROR [HY000] [Microsoft][ODBC Paradox Driver] External table is not in the expected format.</p>
</blockquote>
<p>I've also tired OELDB (Jet 4.0) but get the same External table is not in the expected format error.</p>
<p>I have the DB file and the PX (of the Growth table) in the Data folder... Any help would be much appriciated. </p>
| [
{
"answer_id": 13853021,
"author": "Ivan Golovin",
"author_id": 1282462,
"author_profile": "https://Stackoverflow.com/users/1282462",
"pm_score": 2,
"selected": false,
"text": "// Program.cs\nstatic void Main()\n{\n Application.EnableVisualStyles();\n Application.SetCompatibleTextRenderingDefault(false);\n // it is important to open paradox connection before creating\n // the first form in the project\n if (!Data.OpenParadoxDatabase())\n return;\n Application.Run(new MainForm());\n}\n string connStr = @\"Driver={{Microsoft Paradox Driver (*.db )}};DriverID=538;\n Fil=Paradox 7.X;DefaultDir=C:\\\\DB;Dbq=C:\\\\DB;\n CollatingSequence=ASCII;\";\n private void MainForm_Load(object sender, EventArgs e)\n{\n Data.CloseParadoxDatabase();\n}\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
304,997 | <p>I have following situation:
I have loged user, standard authentication with DB table </p>
<pre><code>$authAdapter = new Zend_Auth_Adapter_DbTable(Zend_Db_Table::getDefaultAdapter());
$authAdapter->setTableName('users');
$authAdapter->setIdentityColumn('user_name');
$authAdapter->setCredentialColumn('password');
</code></pre>
<p>When user edits his profile, I save it into Db, but I need to update also storage (using standard Zend_Auth_Storage_Session). Is there any easy way how to do it? Many thanks. </p>
| [
{
"answer_id": 305048,
"author": "Martin Rázus",
"author_id": 39014,
"author_profile": "https://Stackoverflow.com/users/39014",
"pm_score": 2,
"selected": false,
"text": "$user_data = User::getUser($user_id)->toArray();\nunset($user_data['password']);\n\n$std_user = new stdClass();\n\nforeach ($user_data as $key => $value)\n{\n $std_user->$key = $value;\n}\n\n$auth = Zend_Auth::getInstance(); \n$auth->getStorage()->write($std_user); \n"
},
{
"answer_id": 305336,
"author": "Akeem",
"author_id": 35505,
"author_profile": "https://Stackoverflow.com/users/35505",
"pm_score": 3,
"selected": false,
"text": "$user = Zend_Auth::getInstance()->getIdentity();\n$user->newValue = 'new value';\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304997",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39014/"
] |
304,999 | <p>We are currently creating an InfoPath 2007 form is deployed in SharePoint 2007. In the form we populate the repeating tables with more than 60 records. However, when we're submitting the form, an error message appears. Does the number of records in the repeating table affects the submitting of the form? Also provide some workaround to resolve the issue.</p>
<p>Thanks in advance.</p>
| [
{
"answer_id": 305048,
"author": "Martin Rázus",
"author_id": 39014,
"author_profile": "https://Stackoverflow.com/users/39014",
"pm_score": 2,
"selected": false,
"text": "$user_data = User::getUser($user_id)->toArray();\nunset($user_data['password']);\n\n$std_user = new stdClass();\n\nforeach ($user_data as $key => $value)\n{\n $std_user->$key = $value;\n}\n\n$auth = Zend_Auth::getInstance(); \n$auth->getStorage()->write($std_user); \n"
},
{
"answer_id": 305336,
"author": "Akeem",
"author_id": 35505,
"author_profile": "https://Stackoverflow.com/users/35505",
"pm_score": 3,
"selected": false,
"text": "$user = Zend_Auth::getInstance()->getIdentity();\n$user->newValue = 'new value';\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/304999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24755/"
] |
305,016 | <p>I'm a hesitant upgrader when it comes to development tools. For roughly half of my product I still use D7, and for others D2006.</p>
<p>The truth is, although Unicode support is more than welcomed and very useful, it could cause me more troubles than gains with my current projects (they are more-or-less Unicode ready already). It's especially case with one of them who's performance would suffer a lot if each string takes twice as much memory as before.</p>
<p>So, Unicode aside, what are other major incentives to upgrade?</p>
| [
{
"answer_id": 319377,
"author": "Mason Wheeler",
"author_id": 32914,
"author_profile": "https://Stackoverflow.com/users/32914",
"pm_score": 2,
"selected": false,
"text": "for i := 0 to myObjectList.Count - 1 do\nbegin\n currentObject := myObjectList[i] as TMyObjectType;\n currentObject.WhateverYoureDoingWithIt;\n ...\nend;\n TObjectList<TMyObjectType> for currentObject in myObjectList do\nbegin\n currentObject.WhateverYoureDoingWithIt;\n ...\nend;\n"
},
{
"answer_id": 819677,
"author": "Peter Perháč",
"author_id": 81520,
"author_profile": "https://Stackoverflow.com/users/81520",
"pm_score": 2,
"selected": false,
"text": "program genericTList;\n\n{$APPTYPE CONSOLE}\n\nuses\n SysUtils,\n Generics.Collections;\n\nvar\n myList : TList<string>;\n s: string;\n\nbegin\n myList := TList<string>.create;\n try\n myList.Add('Peter');\n writeln('Inviting Peter');\n myList.Add('Barbie');\n writeln('Inviting Barbie');\n if myList.Contains('Bob') then writeln('Bob has managed to sneak in...') else writeln('Bob is not invited!');\n writeln('List of invited people:');\n for s in myList do writeln(s); //feels sooo goood X-)\n readln;\n finally\n FreeAndNil(myList);\n end;\nend.\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/305016",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12891/"
] |
305,035 | <p>I have to run a local shell script (windows/Linux) on a remote machine.</p>
<p>I have SSH configured on both machine A and B. My script is on machine A which will run some of my code on a remote machine, machine B.</p>
<p>The local and remote computers can be either Windows or Unix based system.</p>
<p>Is there a way to run do this using plink/ssh?</p>
| [
{
"answer_id": 305054,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 7,
"selected": false,
"text": "<hostA_shell_prompt>$ ssh user@hostB \"ls -la\"\n"
},
{
"answer_id": 305128,
"author": "dogbane",
"author_id": 7412,
"author_profile": "https://Stackoverflow.com/users/7412",
"pm_score": 8,
"selected": false,
"text": "user@host> ssh user2@host2 \"echo \\$HOME\"\n user@host> ssh user2@host2 \"echo $HOME\"\n user@host> ssh user2@host2 \"echo hello world | awk '{print \\$1}'\"\n"
},
{
"answer_id": 1930732,
"author": "Jeremy",
"author_id": 234837,
"author_profile": "https://Stackoverflow.com/users/234837",
"pm_score": 4,
"selected": false,
"text": "ssh user@remote sh ./script.unx"
},
{
"answer_id": 2732991,
"author": "Jason R. Coombs",
"author_id": 70170,
"author_profile": "https://Stackoverflow.com/users/70170",
"pm_score": 10,
"selected": false,
"text": "plink root@MachineB -m local_script.sh\n ssh root@MachineB 'bash -s' < local_script.sh\n"
},
{
"answer_id": 3872762,
"author": "Yarek T",
"author_id": 274503,
"author_profile": "https://Stackoverflow.com/users/274503",
"pm_score": 9,
"selected": false,
"text": "ssh user@host <<'ENDSSH'\n#commands to run on remote host\nENDSSH\n ' ssh user@host <<'ENDSSH'\n#commands to run on remote host\nssh user@host2 <<'END2'\n# Another bunch of commands on another host\nwall <<'ENDWALL'\nError: Out of cheese\nENDWALL\nftp ftp.example.com <<'ENDFTP'\ntest\ntest\nls\nENDFTP\nEND2\nENDSSH\n <<-END ssh user@host <<-'ENDSSH'\n #commands to run on remote host\n ssh user@host2 <<-'END2'\n # Another bunch of commands on another host\n wall <<-'ENDWALL'\n Error: Out of cheese\n ENDWALL\n ftp ftp.example.com <<-'ENDFTP'\n test\n test\n ls\n ENDFTP\n END2\nENDSSH\n"
},
{
"answer_id": 7363641,
"author": "chubbsondubs",
"author_id": 155020,
"author_profile": "https://Stackoverflow.com/users/155020",
"pm_score": 7,
"selected": false,
"text": "ssh user@host ARG1=$ARG1 ARG2=$ARG2 'bash -s' <<'ENDSSH'\n # commands to run on remote host\n echo $ARG1 $ARG2\nENDSSH\n"
},
{
"answer_id": 49951313,
"author": "alpha_989",
"author_id": 4752883,
"author_profile": "https://Stackoverflow.com/users/4752883",
"pm_score": 1,
"selected": false,
"text": "plink ssh linux linux/windows Windows plink root@MachineB -m local_script.bat plink cd C:\\Users\\ipython_user\\Desktop \npython filename.py\n local_script.bat cd C:\\Users\\ipython_user\\Desktop && python filename.py\n `plink root@MachineB -m local_script.bat`\n rem Open tunnel in the background\nstart plink.exe -ssh [username]@[hostname] -L 3307:127.0.0.1:3306 -i \"[SSH\nkey]\" -N\n\nrem Wait a second to let Plink establish the tunnel \ntimeout /t 1\n\nrem Run the task using the tunnel\n\"C:\\Program Files\\R\\R-3.2.1\\bin\\x64\\R.exe\" CMD BATCH qidash.R\n\nrem Kill the tunnel\ntaskkill /im plink.exe\n"
},
{
"answer_id": 50600992,
"author": "Mohammed Rafeeq",
"author_id": 1752917,
"author_profile": "https://Stackoverflow.com/users/1752917",
"pm_score": 1,
"selected": false,
"text": "brew install expect #!/usr/bin/expect\nset username \"enterusenamehere\"\nset password \"enterpasswordhere\"\nset hosts \"enteripaddressofhosthere\"\nspawn ssh $username@$hosts\nexpect \"$username@$hosts's password:\"\nsend -- \"$password\\n\"\nexpect \"$\"\nsend -- \"somecommand on target remote machine here\\n\"\nsleep 5\nexpect \"$\"\nsend -- \"exit\\n\"\n"
},
{
"answer_id": 52436198,
"author": "Jinmiao Luo",
"author_id": 6515101,
"author_profile": "https://Stackoverflow.com/users/6515101",
"pm_score": 2,
"selected": false,
"text": "\ntemp=`ls -a`\necho $temp\n \nssh user@host '''\ntemp=`ls -a`\necho $temp\n'''\n"
},
{
"answer_id": 53242957,
"author": "Is Ma",
"author_id": 5307015,
"author_profile": "https://Stackoverflow.com/users/5307015",
"pm_score": 3,
"selected": false,
"text": "ssh deploy@host . /home/deploy/path/to/script.sh\n"
},
{
"answer_id": 57454340,
"author": "cglotr",
"author_id": 1701442,
"author_profile": "https://Stackoverflow.com/users/1701442",
"pm_score": 5,
"selected": false,
"text": "cat ./script.sh | ssh <user>@<host>\n"
},
{
"answer_id": 57495146,
"author": "Ankush Sahu",
"author_id": 4768028,
"author_profile": "https://Stackoverflow.com/users/4768028",
"pm_score": 3,
"selected": false,
"text": "ssh user@hostname \". ~/.bashrc;/cd path-to-file/;. filename.sh\"\n"
},
{
"answer_id": 57747978,
"author": "nowat",
"author_id": 3705710,
"author_profile": "https://Stackoverflow.com/users/3705710",
"pm_score": 1,
"selected": false,
"text": "sudo apt install runoverssh\n runoverssh -s localscript.sh user host1 host2 host3...\n -s -g -n"
},
{
"answer_id": 65091414,
"author": "Anton Kornus",
"author_id": 5035328,
"author_profile": "https://Stackoverflow.com/users/5035328",
"pm_score": 4,
"selected": false,
"text": "chmod +x script.sh \nssh -i key-file root@111.222.3.444 < ./script.sh\n"
},
{
"answer_id": 65877160,
"author": "Ole Tange",
"author_id": 363028,
"author_profile": "https://Stackoverflow.com/users/363028",
"pm_score": 0,
"selected": false,
"text": "#!/bin/bash\n\nmyalias $myvar\nmyfunction $myvar\n $myvar myfunction myalias eval \"myfun() { `cat myscript.sh`; }\"\n myvar=works\nalias myalias='echo This alias'\nmyfunction() { echo This function \"$@\"; }\n myfun myfunction myvar myalias server env_parallel env_parallel -S server -N0 --nonall myfun ::: dummy\n"
},
{
"answer_id": 66086481,
"author": "KamilCuk",
"author_id": 9072753,
"author_profile": "https://Stackoverflow.com/users/9072753",
"pm_score": 2,
"selected": false,
"text": "bash bash declare bash -s declare -p declare -f declare bash somevar=\"spaces or other special characters\"\nsomevar2=\"!@#$%^\"\nanother_func() {\n mkdir -p \"$1\"\n}\nwork() {\n another_func \"$somevar\"\n touch \"$somevar\"/\"$somevar2\"\n}\nssh user@server 'bash -s' <<EOT\n$(declare -p somevar somevar2) # transfer variables values\n$(declare -f work another_func) # transfer function definitions\nwork # call the function\nEOT\n"
},
{
"answer_id": 73188439,
"author": "Johan",
"author_id": 8913302,
"author_profile": "https://Stackoverflow.com/users/8913302",
"pm_score": 0,
"selected": false,
"text": "printf printf \"cd /to/path/your/remote/machine/log \\n tail -n 100 Server.log\" | ssh <user>@<host> 'bash -s'\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/305035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
305,037 | <p>Last time I create WAS profile and WASService then I try to config and run many script for learn how to config WAS, Finally it crash so i use wasprofile delete this profile and forgot delete WASService.</p>
<p>Now I found IBM Webphere Application Server service display in services.msc list, so I tried to delete it with <code>WASService.exe</code> -remove command and windows <code>SC</code> command but I got message</p>
<pre><code>C:\Program Files\IBM\WebSphere\AppServer\bin>sc delete "IBMWAS61Service - DEV"
[SC] DeleteService FAILED 1072:
The specified service has been marked for deletion.
</code></pre>
| [
{
"answer_id": 2804099,
"author": "Onion-Knight",
"author_id": 64708,
"author_profile": "https://Stackoverflow.com/users/64708",
"pm_score": 5,
"selected": false,
"text": "regedit HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services"
},
{
"answer_id": 7202888,
"author": "Tate",
"author_id": 579735,
"author_profile": "https://Stackoverflow.com/users/579735",
"pm_score": 7,
"selected": false,
"text": "C:\\server>sc delete \"ServiceName\"\n\n[SC] DeleteService SUCCESS\n C:\\server>sc delete \"ServiceName\"\n\n[SC] OpenService FAILED 1060:\n\nThe specified service does not exist as an installed service.\n"
},
{
"answer_id": 49994819,
"author": "Fandango68",
"author_id": 2181188,
"author_profile": "https://Stackoverflow.com/users/2181188",
"pm_score": 4,
"selected": false,
"text": "refresh"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/305037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24550/"
] |
305,044 | <p>I need to avoid being vulnerable to SQL injection in my ASP.NET application. How might I accomplish this?</p>
| [
{
"answer_id": 305076,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 6,
"selected": true,
"text": "SqlCommand SqlParameter"
},
{
"answer_id": 305399,
"author": "Brian Schmitt",
"author_id": 30492,
"author_profile": "https://Stackoverflow.com/users/30492",
"pm_score": 3,
"selected": false,
"text": "SELECT * From Table1 WHERE \" + UserInput\n UserInput DBCommand"
},
{
"answer_id": 305416,
"author": "Rune Grimstad",
"author_id": 30366,
"author_profile": "https://Stackoverflow.com/users/30366",
"pm_score": 4,
"selected": false,
"text": "SqlCommand getPersons = new SqlCommand(\"SELECT * FROM Table WHERE Name = @Name\", conn); \n getPersons.Parameters.AddWithValue(\"@Name\", theName);\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/305044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22162/"
] |
305,053 | <p>I'm trying to programmatically reject a call on a BlackBerry, with Java + JDE.
I'm intercepting the <code>callIncoming</code> event, and in there I need to do something to reject a call from a specific number.</p>
<p>Does anyone know how to do that?</p>
| [
{
"answer_id": 306571,
"author": "Alexander",
"author_id": 16724,
"author_profile": "https://Stackoverflow.com/users/16724",
"pm_score": 2,
"selected": false,
"text": "EventInjector Phone.getCall(callId).getDisplayPhoneNumber() Phone.getActiveCall().getDisplayPhoneNumber()"
},
{
"answer_id": 807795,
"author": "kozen",
"author_id": 98649,
"author_profile": "https://Stackoverflow.com/users/98649",
"pm_score": 0,
"selected": false,
"text": "EventInjector"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/305053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
305,064 | <p>I'm trying to build a console application without using the CRT, or any other imports than kernel32.lib in any case. I get my code to compile, but can't wrap the linker around a few problems:</p>
<pre><code>unresolved external symbol @__security_check_cookie@4
unresolved external symbol "int __cdecl FreeLibrary(void *)" (?FreeLibrary@@YAHPAX@Z)
unresolved external symbol "void * __cdecl LoadLibraryW(wchar_t *)" (?LoadLibraryW@@YAPAXPA_W@Z)
unresolved external symbol "int (__cdecl*__cdecl GetProcAddress(void *,char *))(void)" (?GetProcAddress@@YAP6AHXZPAXPAD@Z)
unresolved external symbol _wmainCRTStartup
</code></pre>
<p>FreeLibrary, LoadLibraryW and GetProcAddress I've brought in to program explicitly, not using windows.h:</p>
<pre><code>#pragma comment(lib, "kernel32.lib")
typedef int(*FARPROC)();
void* LoadLibraryW( wchar_t* lpLibFileName );
FARPROC GetProcAddress( void* hModule, char* lpProcName );
int FreeLibrary( void* hLibModule );
</code></pre>
<p>I suppose something is wrong with my prototypes.
However, the bigger problem are <code>__security_check_cookie</code> and <code>_wmainCRTStartup</code>, which obviously have something to do with the CRT.
So I'm wondering how I'd go about overriding the default <code>int wmain(int argc, wchar_t* argv[])</code> for entrypoint, and how to get rid of whatever the security cookie is.</p>
| [
{
"answer_id": 305079,
"author": "SoapBox",
"author_id": 36384,
"author_profile": "https://Stackoverflow.com/users/36384",
"pm_score": 1,
"selected": false,
"text": "WINAPI __stdcall __cdecl"
},
{
"answer_id": 305112,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 0,
"selected": false,
"text": "main() wmain()"
},
{
"answer_id": 305219,
"author": "anon6439",
"author_id": 15477,
"author_profile": "https://Stackoverflow.com/users/15477",
"pm_score": 2,
"selected": false,
"text": "/GS- __stdcall /entry:wmain #pragma comment(lib, \"kernel32.lib\")\n\ntypedef int(*FARPROC)();\n\nextern \"C\" {\n void* __stdcall LoadLibraryW( wchar_t* lpLibFileName );\n FARPROC __stdcall GetProcAddress( void* hModule, char* lpProcName );\n int __stdcall FreeLibrary( void* hLibModule );\n typedef int (__stdcall *f_MessageBoxW_t)( unsigned long hWnd, wchar_t* lpText, wchar_t* lpCaption, unsigned long uType);\n f_MessageBoxW_t fnMsg;\n void* hUser;\n};\n\nint __stdcall wmain(int argc, wchar_t* argv[])\n{\n hUser = LoadLibraryW( L\"user32.dll\" );\n fnMsg = (f_MessageBoxW_t)GetProcAddress( hUser, \"MessageBoxW\" );\n fnMsg( 0, L\"foo\", L\"bar\", 0 );\n FreeLibrary( hUser );\n return 0;\n}\n"
},
{
"answer_id": 5135535,
"author": "airmax",
"author_id": 161906,
"author_profile": "https://Stackoverflow.com/users/161906",
"pm_score": 2,
"selected": false,
"text": "int __stdcall wmain(PVOID ThreadParam)\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/305064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15477/"
] |
305,081 | <p>For the following header I get the same two errors on all my sitemaps. It's confusing because, if Google can't read my sitemap, then how can they say that each URL has the same priority? The header counts as line 2, after the XML declaration. Google claims only to have indexed about 2% of the URLs from the maps. Please help.</p>
<blockquote>
<p>UPDATE: I think the problem is that I don't know how to validate against a schema. How to do that?</p>
</blockquote>
<pre><code><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
==Parsing error
We were unable to read your Sitemap. It may contain an entry we are
unable to recognize. Please validate your Sitemap before resubmitting.
==Notice
All the URLs in your Sitemap have the same priority...
</code></pre>
<p>UPDATE: Please be patient, first time validating XML. I don't understand the errors.</p>
<pre><code>Errors in the XML document:
4: 80 SchemaLocation: schemaLocation value = 'http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd' must have even number of URI's.
4: 80 cvc-elt.1: Cannot find the declaration of element 'urlset'.
XML document:
1 <?xml version="1.0" encoding="UTF-8"?>
2 <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
5 <url>
6 <loc>http://nutrograph.com/1-butter-salted</loc>
7 <changefreq>monthly</changefreq>
8 <priority>0.8</priority>
9 </url>
10 <url>
11 <loc>http://nutrograph.com/2-butter-whipped-with-salt</loc>
12 <changefreq>monthly</changefreq>
13 <priority>0.8</priority>
14 </url>
15 </urlset>
</code></pre>
| [
{
"answer_id": 305091,
"author": "TToni",
"author_id": 20703,
"author_profile": "https://Stackoverflow.com/users/20703",
"pm_score": 4,
"selected": true,
"text": "<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd\">\n"
},
{
"answer_id": 305098,
"author": "Mike Edwards",
"author_id": 15383,
"author_profile": "https://Stackoverflow.com/users/15383",
"pm_score": 3,
"selected": false,
"text": "<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\"\nxmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\nxsi:schemaLocation=\"http://www.sitemaps.org/schemas/sitemap/0.9\nhttp://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd\">\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/305081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33287/"
] |
305,088 | <p>I have a loader.exe with Main() that loads the 'UI' in WPF, the thing is that I want only one instance of the loader.exe, how can I achieve it? </p>
<p>Is there a way a user clicks loader.exe it should check if an existing loader.exe is running and does nothing.</p>
<p>currently I have </p>
<p>loader.exe </p>
<p>with </p>
<pre><code>main()
....
..
Load UI
...
</code></pre>
<p>the loader has no idea what its loading etc so I can't do many things with the loader project...</p>
<p>Any help n code is highly appreciated</p>
<p>Thanks in advance. </p>
| [
{
"answer_id": 305317,
"author": "tamberg",
"author_id": 3588,
"author_profile": "https://Stackoverflow.com/users/3588",
"pm_score": 3,
"selected": true,
"text": "using System.Threading;\n\nstring appSpecificGuid = \"{007400FE-003D-00A5-AFFE-DA62E35CC1F5}\"; \nbool exclusive;\nMutex m = new Mutex(true, appSpecificGuid, out exclusive);\nif (exclusive) {\n // run\n} else {\n // already running\n}\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/305088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39278/"
] |
305,092 | <p>in the <code>System.Linq</code> namespace, we can now extend our <a href="https://learn.microsoft.com/en-us/dotnet/api/system.collections.ienumerable?view=netframework-3.5" rel="noreferrer">IEnumerable's</a> to have the <a href="https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.any?view=netframework-3.5" rel="noreferrer">Any()</a> and <a href="https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.count?view=netframework-3.5" rel="noreferrer">Count()</a> <em>extension methods</em>.</p>
<p>I was told recently that if i want to check that a collection contains 1 or more items inside it, I should use the <code>.Any()</code> extension method instead of the <code>.Count() > 0</code> extension method because the <code>.Count()</code> extension method has to iterate through all the items.</p>
<p>Secondly, some collections have a <em>property</em> (not an extension method) that is <code>Count</code> or <code>Length</code>. Would it be better to use those, instead of <code>.Any()</code> or <code>.Count()</code>?</p>
<p>yea / nae?</p>
| [
{
"answer_id": 305156,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 11,
"selected": true,
"text": ".Length .Count ICollection<T> IList<T> List<T> GetEnumerator() MoveNext() Dispose() Any() IEnumerable<T> IEnumerable<T> Any() Count() ICollection<T> .Count ICollection Where ICollection<T> IEnumerable<T> Any()"
},
{
"answer_id": 11042691,
"author": "nikib3ro",
"author_id": 237858,
"author_profile": "https://Stackoverflow.com/users/237858",
"pm_score": 6,
"selected": false,
"text": ".Any() .Count() .Any() .Count() > 0 Any Count() > 0 Any con = db.Contacts.\n Where(a => a.CompanyId == companyId && a.ContactStatusId <= (int) Const.ContactStatusEnum.Reactivated\n && !a.NewsletterLogs.Any(b => b.NewsletterLogTypeId == (int) Const.NewsletterLogTypeEnum.Unsubscr)\n ).OrderBy(a => a.ContactId).\n Skip(position - 1).\n Take(1).FirstOrDefault();\n Count con = db.Contacts.\n Where(a => a.CompanyId == companyId && a.ContactStatusId <= (int) Const.ContactStatusEnum.Reactivated\n && a.NewsletterLogs.Count(b => b.NewsletterLogTypeId == (int) Const.NewsletterLogTypeEnum.Unsubscr) == 0\n ).OrderBy(a => a.ContactId).\n Skip(position - 1).\n Take(1).FirstOrDefault();\n Count Any Any ANY COUNT"
},
{
"answer_id": 20908314,
"author": "Ben",
"author_id": 335784,
"author_profile": "https://Stackoverflow.com/users/335784",
"pm_score": 4,
"selected": false,
"text": "SELECT \nCASE WHEN ( EXISTS (SELECT \n 1 AS [C1]\n FROM [Table] AS [Extent1]\n)) THEN cast(1 as bit) WHEN ( NOT EXISTS (SELECT \n 1 AS [C1]\n FROM [Table] AS [Extent2]\n)) THEN cast(0 as bit) END AS [C1]\nFROM ( SELECT 1 AS X ) AS [SingleRowTable1]\n Count() > 0 public static class QueryExtensions\n{\n public static bool Exists<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate)\n {\n return source.Count(predicate) > 0;\n }\n}\n"
},
{
"answer_id": 30500838,
"author": "kamil-mrzyglod",
"author_id": 1874991,
"author_profile": "https://Stackoverflow.com/users/1874991",
"pm_score": 5,
"selected": false,
"text": "class TestTable\n{\n [Key]\n public int Id { get; set; }\n\n public string Name { get; set; }\n\n public string Surname { get; set; }\n}\n class Program\n{\n static void Main()\n {\n using (var context = new TestContext())\n {\n context.Database.Log = Console.WriteLine;\n\n context.TestTables.Where(x => x.Surname.Contains(\"Surname\")).Any(x => x.Id > 1000);\n context.TestTables.Where(x => x.Surname.Contains(\"Surname\") && x.Name.Contains(\"Name\")).Any(x => x.Id > 1000);\n context.TestTables.Where(x => x.Surname.Contains(\"Surname\")).Count(x => x.Id > 1000);\n context.TestTables.Where(x => x.Surname.Contains(\"Surname\") && x.Name.Contains(\"Name\")).Count(x => x.Id > 1000);\n\n Console.ReadLine();\n }\n }\n}\n"
},
{
"answer_id": 41769051,
"author": "Bronks",
"author_id": 2588345,
"author_profile": "https://Stackoverflow.com/users/2588345",
"pm_score": 2,
"selected": false,
"text": "var query = //make any query here\nvar timeCount = new Stopwatch();\ntimeCount.Start();\nif (query.Count > 0)\n{\n}\ntimeCount.Stop();\nvar testCount = timeCount.Elapsed;\n\nvar timeAny = new Stopwatch();\ntimeAny.Start();\nif (query.Any())\n{\n}\ntimeAny.Stop();\nvar testAny = timeAny.Elapsed;\n"
},
{
"answer_id": 49540848,
"author": "Thiago Coelho",
"author_id": 7601484,
"author_profile": "https://Stackoverflow.com/users/7601484",
"pm_score": 2,
"selected": false,
"text": "public static int Count<TSource>(this IEnumerable<TSource> source)\n{\n if (source == null) \n throw Error.ArgumentNull(\"source\");\n\n ICollection<TSource> collectionoft = source as ICollection<TSource>;\n if (collectionoft != null) \n return collectionoft.Count;\n\n ICollection collection = source as ICollection;\n if (collection != null) \n return collection.Count;\n\n int count = 0;\n using (IEnumerator<TSource> e = source.GetEnumerator())\n {\n checked\n {\n while (e.MoveNext()) count++;\n }\n }\n return count;\n}\n"
},
{
"answer_id": 63569609,
"author": "gregmac",
"author_id": 7913,
"author_profile": "https://Stackoverflow.com/users/7913",
"pm_score": 6,
"selected": false,
"text": "ICollection ICollection<T> List<T> .Count .Count > 0 .Any() .Count() > 0 List<T> ICollection<T> .Count private int _size;\n\n public int Count {\n get {\n Contract.Ensures(Contract.Result<int>() >= 0);\n return _size; \n }\n }\n _size Add() Remove() ICollection ICollection<T> .Count IEnumerable ICollection .Any() Any() public static bool Any<TSource>(this IEnumerable<TSource> source) {\n if (source == null) throw Error.ArgumentNull(\"source\");\n using (IEnumerator<TSource> e = source.GetEnumerator()) {\n if (e.MoveNext()) return true;\n }\n return false;\n}\n List<T>.Count .Count() Count() public static int Count<TSource>(this IEnumerable<TSource> source)\n{\n ICollection<TSource> collection = source as ICollection<TSource>;\n if (collection != null)\n { \n return collection.Count;\n }\n int num = 0;\n using (IEnumerator<TSource> enumerator = source.GetEnumerator())\n {\n while (enumerator.MoveNext())\n {\n num = checked(num + 1);\n }\n return num;\n }\n}\n ICollection.Count .Any() Any() public static bool Any<TSource>(this IEnumerable<TSource> source)\n {\n //..snip..\n \n if (source is ICollection<TSource> collectionoft)\n {\n return collectionoft.Count != 0;\n }\n \n //..snip..\n\n using (IEnumerator<TSource> e = source.GetEnumerator())\n {\n return e.MoveNext();\n }\n }\n List<T> ICollection<T> Count .Count() ICollection.Count ICollection .Count > 0 .Count() > 0 ICollection.Count .Any() ICollection .Count .Any() .Count() > 0 .Count > 0 ICollection .Any() ICollection.Count > 0 .Count() > 0"
},
{
"answer_id": 67980276,
"author": "RRaveen",
"author_id": 216885,
"author_profile": "https://Stackoverflow.com/users/216885",
"pm_score": -1,
"selected": false,
"text": "class Program\n{\n static void Main()\n {\n\n //Creating List of customers\n IList<Customer> customers = new List<Customer>();\n for (int i = 0; i <= 100; i++)\n {\n Customer customer = new Customer\n {\n CustomerId = i,\n CustomerName = string.Format(\"Customer{0}\", i)\n };\n customers.Add(customer);\n }\n\n //Measuring time with count\n Stopwatch stopWatch = new Stopwatch();\n stopWatch.Start();\n if (customers.Count > 0)\n {\n Console.WriteLine(\"Customer list is not empty with count\");\n }\n stopWatch.Stop();\n Console.WriteLine(\"Time consumed with count: {0}\", stopWatch.Elapsed);\n\n //Measuring time with any\n stopWatch.Restart();\n if (customers.Any())\n {\n Console.WriteLine(\"Customer list is not empty with any\");\n }\n stopWatch.Stop();\n Console.WriteLine(\"Time consumed with count: {0}\", stopWatch.Elapsed);\n Console.ReadLine();\n\n }\n}\n\npublic class Customer\n{\n public int CustomerId { get; set; }\n public string CustomerName { get; set; }\n}\n"
},
{
"answer_id": 70020769,
"author": "vivek nuna",
"author_id": 6527049,
"author_profile": "https://Stackoverflow.com/users/6527049",
"pm_score": 0,
"selected": false,
"text": "Count() Any() Count() Any() Select() Any() Any() private static bool IsEmpty(IEnumerable<string> strings)\n{\n return !strings.Any();\n}\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/305092",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30674/"
] |
305,105 | <p>On my app i am creating a real time trace (not sure how yet but i am!) and on the sp_trace_create function in SQlServer, i know that the @maxfilesize defaults to 5, but on my app its going to be stopped when the user wants to stop it...any ideas how this can be done?</p>
<hr>
<p>Because i dont want to have to save the files...im not sure how the rollover works?
Right now im putting it on a timer loop that queries the database with all the specified events on it with a maximum file size of 1(usually doesnt take more then about 2 seconds), merges with the old lot of data in my dgview and deletes the original file. this goes round until the user tells it to stop which will stop the timer from querying the database. Not a solid method but i guess its a start! All i need now is the find out the datatypes of the columns as when im setting my values in the filters they need to go in as the matching datatype to the column... anyone have any clue where i can get a list of the datatypes? msdn have the list but no types...</p>
| [
{
"answer_id": 305110,
"author": "Mitch Wheat",
"author_id": 16076,
"author_profile": "https://Stackoverflow.com/users/16076",
"pm_score": 2,
"selected": true,
"text": "exec @rc = sp_trace_create @TraceID output, 2, N'InsertFileNameHere', @maxfilesize, NULL \n EXEC sp_trace_setstatus @ID, 0\n\nEXEC sp_trace_setstatus @ID, 2\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/305105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36243/"
] |
305,125 | <p>I have created a class to dynamically put together SQL function statements within a project. I have found this class to be pretty useful and would like to incorporate into future projects</p>
<p>namespace connectionClass</p>
<p>{</p>
<pre><code> public class connClass
{
NpgsqlConnection conn = new NpgsqlConnection(projectName.Properties.Settings.Default.ConnString);
}
</code></pre>
<p>}</p>
<p>I want to be able to dynamically input the project name without having to do it myself for every different class! the connection string will be defined within the properties settings in VS.</p>
<p>Any help would be greatly appreciated:)</p>
| [
{
"answer_id": 305198,
"author": "Chris Kimpton",
"author_id": 48310,
"author_profile": "https://Stackoverflow.com/users/48310",
"pm_score": 0,
"selected": false,
"text": "ConfigurationManager.AppSettings[\"PROJECT_NAME\"];\n"
},
{
"answer_id": 319217,
"author": "RSlaughter",
"author_id": 40848,
"author_profile": "https://Stackoverflow.com/users/40848",
"pm_score": 1,
"selected": false,
"text": "String connStr = ConfigurationManager.ConnectionStrings[\"DefaultConnStr\"].ConnectionString;\n <configuration>\n <connectionStrings>\n <add name=\"DefaultConnStr\" connectionString=\"Data Source=127.0.0.1...\"/>\n </connectionStrings>\n</configuration>\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/305125",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
305,140 | <p>Can <a href="http://en.wikipedia.org/wiki/Unicode" rel="noreferrer">Unicode</a> characters be encoded and decoded with <a href="http://en.wikipedia.org/wiki/Base64" rel="noreferrer">Base64</a>?</p>
<p>I have attempted to encode the string 'الله', but when I decoded it all I got was '????'.</p>
| [
{
"answer_id": 305155,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 4,
"selected": false,
"text": "b64 Python 2.5.1 (r251:54863, Jul 31 2008, 22:53:39)\n[GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> a = 'ûñö'\n>>> import base64\n>>> base64.b64encode(a)\n'w7vDscO2'\n>>> base64.b64decode('w7vDscO2')\n'\\xc3\\xbb\\xc3\\xb1\\xc3\\xb6'\n>>> print '\\xc3\\xbb\\xc3\\xb1\\xc3\\xb6'\nûñö\n>>> \n>>> u'üñô'\nu'\\xfc\\xf1\\xf4'\n>>> base64.b64encode(u'\\xfc\\xf1\\xf4')\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"/usr/lib/python2.5/base64.py\", line 53, in b64encode\n encoded = binascii.b2a_base64(s)[:-1]\nUnicodeEncodeError: 'ascii' codec can't encode characters in position\n0-2: ordinal not in range(128)\n>>> base64.b64encode(u'\\xfc\\xf1\\xf4'.encode('utf-8'))\n'w7zDscO0'\n>>> base64.b64decode('w7zDscO0')\n'\\xc3\\xbc\\xc3\\xb1\\xc3\\xb4'\n>>> print base64.b64decode('w7zDscO0')\nüñô\n>>> a = 'الله'\n>>> a\n'\\xd8\\xa7\\xd9\\x84\\xd9\\x84\\xd9\\x87'\n>>> base64.b64encode(a)\n'2KfZhNmE2Yc='\n>>> b = base64.b64encode(a)\n>>> print base64.b64decode(b)\nالله\n"
},
{
"answer_id": 2534262,
"author": "Scott Whitlock",
"author_id": 17635,
"author_profile": "https://Stackoverflow.com/users/17635",
"pm_score": 2,
"selected": false,
"text": "byte[] encbuf;\n\nencbuf = System.Text.Encoding.Unicode.GetBytes(input);\nstring encoded = Convert.ToBase64String(encbuf);\n byte[] decbuff;\n\ndecbuff = Convert.FromBase64String(this.ToString());\nstring decoded = System.Text.Encoding.Unicode.GetString(decbuff);\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/305140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/115/"
] |
305,152 | <p>I have a folder checked out using TortoiseSVN. If I copy a newer version of a file over the existing versioned file, TortoiseSVN correctly identifies that the file is modified.
However when I do a "diff with previous version", it reports "no differences".</p>
<p>If I use WinMerge I can see that the files ARE different.</p>
<p>Does anyone know why the TortoiseSVN diff is failing?</p>
| [
{
"answer_id": 305659,
"author": "Bert Huijben",
"author_id": 2094,
"author_profile": "https://Stackoverflow.com/users/2094",
"pm_score": 3,
"selected": true,
"text": " A revision argument can be one of:\n NUMBER revision number\n '{' DATE '}' revision at start of the date\n 'HEAD' latest in repository\n 'BASE' base rev of item's working copy\n 'COMMITTED' last commit at or before BASE\n 'PREV' revision just before COMMITTED\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/305152",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39296/"
] |
305,154 | <p>Is there an easy way within C# to check to see if a DateTime instance has been assigned a value or not?</p>
| [
{
"answer_id": 305163,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 8,
"selected": true,
"text": "Nullable<DateTime> DateTime? null DateTime null HasValue"
},
{
"answer_id": 305165,
"author": "baretta",
"author_id": 30052,
"author_profile": "https://Stackoverflow.com/users/30052",
"pm_score": 3,
"selected": false,
"text": "Nullable<DateTime>"
},
{
"answer_id": 305167,
"author": "TcKs",
"author_id": 20382,
"author_profile": "https://Stackoverflow.com/users/20382",
"pm_score": 3,
"selected": false,
"text": "DateTime? something = GetDateTime();\nbool isNull = (something == null);\nbool isNull2 = !something.HasValue;\n"
},
{
"answer_id": 305169,
"author": "Hath",
"author_id": 5186,
"author_profile": "https://Stackoverflow.com/users/5186",
"pm_score": 8,
"selected": false,
"text": "DateTime datetime = new DateTime();\n\nif (datetime == DateTime.MinValue)\n{\n //unassigned\n}\n DateTime? datetime = null;\n\n if (!datetime.HasValue)\n {\n //unassigned\n }\n"
},
{
"answer_id": 11377558,
"author": "Arcturus",
"author_id": 1202971,
"author_profile": "https://Stackoverflow.com/users/1202971",
"pm_score": 3,
"selected": false,
"text": "if(dt.GetHashCode()==0)\n{\n Console.WriteLine(\"DateTime is unassigned\"); \n} \n"
},
{
"answer_id": 23784218,
"author": "Sabine",
"author_id": 3660951,
"author_profile": "https://Stackoverflow.com/users/3660951",
"pm_score": 3,
"selected": false,
"text": "new DateTime() DateTime datetime;\n\nif (datetime == new DateTime())\n{\n //unassigned\n}\n"
},
{
"answer_id": 31678462,
"author": "sonatique",
"author_id": 4866541,
"author_profile": "https://Stackoverflow.com/users/4866541",
"pm_score": 5,
"selected": false,
"text": "public static class DateTimeUtil //or whatever name\n{\n public static bool IsEmpty(this DateTime dateTime)\n {\n return dateTime == default(DateTime);\n }\n}\n DateTime datetime = ...;\n\nif (datetime.IsEmpty())\n{\n //unassigned\n}\n"
},
{
"answer_id": 58867324,
"author": "Urasquirrel",
"author_id": 3011819,
"author_profile": "https://Stackoverflow.com/users/3011819",
"pm_score": 1,
"selected": false,
"text": "startDate = startDate <= DateTime.MinValue.AddSeconds(1) ? keepIt : resetIt\n IsKeySet: Added\nThe EntityEntry object, which holds the tracking information for each entity, has a new property called IsKeySet. IsKeySet is a great addition to the API. It checks to see if the key property in the entity has a value. This eliminates the guessing game (and related code) to see if an object already has a value in its key property (or properties if you have a composed key). IsKeySet checks to see if the value is the default value of the particular type you specified for the key property. So if it’s an int, is it 0? If it’s a Guid, is it equal to Guid.Empty (00000000-0000-0000-0000-000000000000)? If the value is not the default for the type, IsKeySet returns true.\n\nIf you know that in your system you can unequivocally differentiate a new object from a pre-existing object by the value of its key property, then IsKeySet is a really handy property for determining the state of entities.\n"
},
{
"answer_id": 71744185,
"author": "Cleber Spirlandeli",
"author_id": 5301331,
"author_profile": "https://Stackoverflow.com/users/5301331",
"pm_score": 1,
"selected": false,
"text": "public class MyClass \n{\n public DateTime? DateExample { get; set; }\n}\n DateTime? dateExample = null;\nif (!dateExample.HasValue) \n{\n Console.WriteLine(\"Is Null\"); // Is Null\n}\n\ndateExample = DateTime.Now;\nif (dateExample.HasValue)\n{\n Console.WriteLine(\"Is Not Null\"); // Is Not Null\n}\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/305154",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
305,162 | <p>Yes we're talking about ASCII codes. My appologies I'm not the Delphi dev here.</p>
| [
{
"answer_id": 306964,
"author": "Rob Kennedy",
"author_id": 33732,
"author_profile": "https://Stackoverflow.com/users/33732",
"pm_score": 1,
"selected": false,
"text": "Ord var\n wc: WideChar;\n ws: WideString;\n x: Word;\n\nx := Ord(wc);\nx := Ord(ws[1]);\n"
},
{
"answer_id": 311744,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "var\n ws: widestring;\n s: string;\nbegin\n s:=string(ws)\n"
},
{
"answer_id": 902999,
"author": "Eugene Yokota",
"author_id": 3827,
"author_profile": "https://Stackoverflow.com/users/3827",
"pm_score": 2,
"selected": false,
"text": "var\n original: WideString;\n s: AnsiString;\nbegin\n s := AnsiString(original);\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/305162",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/115/"
] |
305,177 | <p>I am using this HTML</p>
<pre><code><html>
<head>
<Title>EBAY Search</title>
</head>
<script language="JavaScript" src="ajaxlib.js"></script>
<body>
Click here <a href="#" OnClick="GetEmployee()">link</a> to show content
<div id="Result"><The result will be fetched here></div>
</body>
</html>
</code></pre>
<p>With this Javascript</p>
<pre><code>var xmlHttp
function GetEmployee()
{
xmlHttp=GetXmlHttpObject()
if(xmlHttp==null)
{
alert("Your browser is not supported")
}
var url="get_employee.php"
url=url+"cmd=GetEmployee"
url=url+"&sid="+Math.random()
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}
function FetchComplete()
{
if(xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
document.getElementById("Result").innerHTML=xmlHttp.responseText
}
if(xmlHttp.readyState==1 || xmlHttp.readyState=="loading")
{
document.getElementById("Result").innerHTML="loading"
}
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
try
{
xmlHttp =new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
</code></pre>
<p>However it is not being called. get_employee.php works fine when I call it by itself, so that is not the problem. Is there anything wrong in my code that would prevent it from being called? I cannot test with any firefox extensions, I do not have access, so please don't give that as an answer.</p>
<p>edit: the problem is the javascript is not being called at all. I fixed the question mark problem, but even just a simple javascript with an alert is not being called.</p>
| [
{
"answer_id": 305211,
"author": "dylanfm",
"author_id": 38795,
"author_profile": "https://Stackoverflow.com/users/38795",
"pm_score": 1,
"selected": false,
"text": "var url=\"get_employee.php?\"\n <script type=\"text/javascript\" src=\"ajaxlib.js\"></script>\n"
},
{
"answer_id": 305212,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": 0,
"selected": false,
"text": "getcommand.php cmd="
},
{
"answer_id": 305215,
"author": "Chris Kimpton",
"author_id": 48310,
"author_profile": "https://Stackoverflow.com/users/48310",
"pm_score": 0,
"selected": false,
"text": "var url=\"get_employee.php\"\nurl=url+\"cmd=GetEmployee\"\nurl=url+\"&sid=\"+Math.random()\n \"?cmd=GetEmployee\""
},
{
"answer_id": 305218,
"author": "Chris Kimpton",
"author_id": 48310,
"author_profile": "https://Stackoverflow.com/users/48310",
"pm_score": 0,
"selected": false,
"text": "alert(url)"
},
{
"answer_id": 305221,
"author": "Aaron Palmer",
"author_id": 24908,
"author_profile": "https://Stackoverflow.com/users/24908",
"pm_score": 1,
"selected": false,
"text": "var url=\"get_employee.php\"\n\nurl=url+\"cmd=GetEmployee\"\n\nurl=url+\"&sid=\"+Math.random()\n var url=\"get_employee.php?cmd=GetEmployee&sid=\"+Math.random();\n"
},
{
"answer_id": 305278,
"author": "Shreef",
"author_id": 29056,
"author_profile": "https://Stackoverflow.com/users/29056",
"pm_score": 2,
"selected": true,
"text": "function GetXmlHttpObject()\n{\n var xmlHttp=null;\n try\n {\n xmlHttp=new XMLHttpRequest();\n }catch (e)\n {\n\n try\n {\n xmlHttp =new ActiveXObject(\"Microsoft.XMLHTTP\");\n } \n catch (e) {}\n\n }\nreturn xmlHttp;\n}\n"
},
{
"answer_id": 305299,
"author": "Svante",
"author_id": 31615,
"author_profile": "https://Stackoverflow.com/users/31615",
"pm_score": 1,
"selected": false,
"text": "<script>"
},
{
"answer_id": 305311,
"author": "acrosman",
"author_id": 24215,
"author_profile": "https://Stackoverflow.com/users/24215",
"pm_score": 0,
"selected": false,
"text": "<a href=\"#\" OnClick=\"GetEmployee()\">link</a> <a href=\"#\" OnClick=\"GetEmployee(); return false;\">link</a>"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/305177",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1246613/"
] |
305,179 | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/210564/pdo-prepared-statements">PDO Prepared Statements</a> </p>
</blockquote>
<p>I'm using the mysqli extension in PHP and I'm wondering, is there possibly any way to see a prepared query as it will be executed on the server, e.g. The query is something like this</p>
<pre><code>select * from table1 where id = ? and name = ?
</code></pre>
<p>but I want to see the query after the values are filled in, like this:</p>
<pre><code>select * from table1 where id = 20 and name = "John"
</code></pre>
| [
{
"answer_id": 305578,
"author": "troelskn",
"author_id": 18180,
"author_profile": "https://Stackoverflow.com/users/18180",
"pm_score": 3,
"selected": true,
"text": "debugDumpParams"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/305179",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6615/"
] |
305,220 | <p>I can´t find a way to restyle the IsChecked indicator of a checkbox. As I can see from the checkbox template there´s no possibilities to restyle the indicator, just the "box" of the checkbox. Does anyone knows if it´s possibly to restyle the IsChecked indicator?</p>
| [
{
"answer_id": 305398,
"author": "Nir",
"author_id": 3509,
"author_profile": "https://Stackoverflow.com/users/3509",
"pm_score": 4,
"selected": true,
"text": "<Path \nWidth=\"7\" Height=\"7\" \nx:Name=\"CheckMark\"\nSnapsToDevicePixels=\"False\" \nStroke=\"{StaticResource GlyphBrush}\"\nStrokeThickness=\"2\"\nData=\"M 0 0 L 7 7 M 0 7 L 7 0\" />\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/305220",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37271/"
] |
305,239 | <p>Is it necessary for setter methods to have one argument? Usually setter methods accept one argument as the value of a certain property of an Object. What if I want to test first the validity which depends on another argument which is a boolean, if true, validate first, else just set the value.</p>
<p>I am getting the values from clients through ftp server. Sometimes those files contain garbage values. For instance, a phone number like #3432838#9. So before I set the value I need to remove those garbage characters. Can I do it in the setter methods? Is it a valid approach?</p>
<p>Thanks a bunch in advance!</p>
<p><strong>EDIT:</strong></p>
<p>Is this valid:</p>
<pre><code>public void setSomething(String strValue){
if(checkValidity(strValue)){
// set the value
} else {
// set the value to an empty string
}
}
</code></pre>
| [
{
"answer_id": 305249,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 5,
"selected": true,
"text": "void setCheck()\n void setter(int index, PropertyType value); // indexed setter\nvoid setter(PropertyType values[]); // array setter\n PropertyType getFoo();\nvoid setFoo(PropertyType value) throws PropertyVetoException;\n"
},
{
"answer_id": 305871,
"author": "user2427",
"author_id": 1356709,
"author_profile": "https://Stackoverflow.com/users/1356709",
"pm_score": 1,
"selected": false,
"text": "NutritionFacts cocaCola = new NutritionFacts();\ncocaCola.setServingSize(240);\ncocaCola.setServings(8);\ncocaCola.setCalories(100);\ncocaCola.setSodium(35);\ncocaCola.setCarbohydrate(27);\n NutritionFacts cocaCola = new NutritionFacts.Builder(240, 8).\n calories(100).\n sodium(35).\n carbohydrate(27).\n build();\n // Builder Pattern\npublic class NutritionFacts {\n private final int servingSize;\n private final int servings;\n private final int calories;\n private final int fat;\n private final int sodium;\n private final int carbohydrate;\n public static class Builder {\n // Required parameters\n private final int servingSize;\n private final int servings;\n // Optional parameters - initialized to default values\n private int calories = 0;\n private int fat = 0;\n private int carbohydrate = 0;\n private int sodium = 0;\n public Builder(int servingSize, int servings) {\n this.servingSize = servingSize;\n this.servings = servings;\n }\n public Builder calories(int val)\n { calories = val; return this; }\n public Builder fat(int val)\n { fat = val; return this; }\n public Builder carbohydrate(int val)\n { carbohydrate = val; return this; }\n public Builder sodium(int val)\n { sodium = val; return this; }\n public NutritionFacts build() {\n return new NutritionFacts(this);\n }\n }\n private NutritionFacts(Builder builder) {\n servingSize = builder.servingSize;\n servings = builder.servings;\n calories = builder.calories;\n fat = builder.fat;\n sodium = builder.sodium;\n carbohydrate = builder.carbohydrate;\n }\n}\n <field>"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/305239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37740/"
] |
305,265 | <p>I am using Delphi 7 and ICS components to communicate with php script and insert some data in mysql database...</p>
<p>How to post unicode data using http post ?</p>
<p>After using utf8encode from tnt controls I am doing it to post to PHP script </p>
<pre><code><?php
echo "Note = ". $_POST['note'];
if($_POST['action'] == 'i')
{
/*
* This code will add new notes to the database
*/
$sql = "INSERT INTO app_notes VALUES ('', '" . mysql_real_escape_string($_POST['username']) . "', '" . mysql_real_escape_string($_POST['note']) . "', NOW(), '')";
$result = mysql_query($sql, $link) or die('0 - Ins');
echo '1 - ' . mysql_insert_id($link);
?>
</code></pre>
<p>Delphi code : </p>
<pre><code> data := Format('date=%s&username=%s&password=%s&hash=%s&note=%s&action=%s',
[UrlEncode(FormatDateTime('yyyymmddhh:nn',now)),
UrlEncode(edtUserName.Text),
UrlEncode(getMd51(edtPassword.Text)),
UrlEncode(getMd51(dataHash)),UrlEncode(Utf8Encode(memoNote.Text)),'i'
]);
// try function StrHtmlEncode (const AStr: String): String; from IdStrings
HttpCli1.SendStream := TMemoryStream.Create;
HttpCli1.SendStream.Write(Data[1], Length(Data));
HttpCli1.SendStream.Seek(0, 0);
HttpCli1.RcvdStream := TMemoryStream.Create;
HttpCli1.URL := Trim(ActionURLEdit.Text);
HttpCli1.PostAsync;
</code></pre>
<p>But when I post that unicode value is totally different then original one that I see in Tnt Memo</p>
<p>Is there something I am missing ?!</p>
<p>Also anybody knows how to do this with Indy?</p>
<p>Thanks.</p>
| [
{
"answer_id": 306934,
"author": "Rob Kennedy",
"author_id": 33732,
"author_profile": "https://Stackoverflow.com/users/33732",
"pm_score": 3,
"selected": true,
"text": "WideString Utf8Encode AnsiString UrlEncode UrlEncode AnsiString var\n data, date, username, passhash, datahash, note: AnsiString;\n\ndate := FormatDateTime('yyyymmddhh:nn',now);\nusername := Utf8Encode(edtUserName.Text);\npasshash := getMd51(edtPassword.Text);\ndatahash := getMd51(data);\nnote := Utf8Encode(memoNote.Text);\ndata := Format('date=%s&username=%s&password=%s&hash=%s¬e=%s&action=%s',\n [UrlEncode(date),\n UrlEncode(username),\n UrlEncode(passhash),\n UrlEncode(datahash),\n UrlEncode(note),\n 'i'\n ]);\n getMd51 WideString WideString Utf8Decode Utf8Encode utf8_decode"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/305265",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27016/"
] |
305,275 | <p>I am putting together a build system and wanted to know if there is a reliable way to find out if a checked out SVN folder needs updating (i.e. is it out of sync with the repository). I want to avoid a nightly build unless something has changed. I could write a script that parses the results of the <code>svn update</code> command I guess, but I wondered if there as a command that would tell me if an update is actually required?</p>
| [
{
"answer_id": 305294,
"author": "flolo",
"author_id": 36472,
"author_profile": "https://Stackoverflow.com/users/36472",
"pm_score": 5,
"selected": true,
"text": "svn status -u\n svn status --show-updates\n"
},
{
"answer_id": 15807495,
"author": "jan",
"author_id": 1184842,
"author_profile": "https://Stackoverflow.com/users/1184842",
"pm_score": 2,
"selected": false,
"text": "cd somedir;\nsvn info -r HEAD | grep -i \"Last Changed Rev\"\nLast Changed Rev: 8544\nsvn info | grep -i \"Last Changed Rev\"\nLast Changed Rev: 8531\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/305275",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9236/"
] |
305,285 | <p>To what is the class path of a Servlet container set? </p>
<p>As per my understanding there are three components involved. The JAR files in the <code>lib</code> directory of the Servlet container and then the classes in the <code>WEB-INF/classes</code> and JAR files in the <code>WEB-INF/lib</code> directory. The classes in <code>lib</code> directory of the Servlet container are added to the system classpath and the dynamic classpath includes the JAR files in the <code>lib</code> directory and classes in the <code>classes</code> directory. </p>
<p>To what is the dynamic classpath set? Does the dynamic classpath point to all the directories under <code>WEB-INF</code> or includes all the individual classes and JAR files in <code>WEB-INF/lib</code> and <code>WEB-INF/classes</code> or just points to the two directories <code>WEB-INF/classes</code> and <code>WEB-INF/lib</code>? Say I have a directory called <code>foo</code> in <code>WEB-INF</code> containing <code>bar.properties</code>. Now is <code>bar.properties</code> also in the class path?</p>
| [
{
"answer_id": 305896,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 4,
"selected": true,
"text": "WEB-INF/classes WEB-INF/lib WEB-INF bar.properties WEB-INF/classes WEB-INF/lib"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/305285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38857/"
] |
305,287 | <p>I have a binary file - Windows static library (*.lib).<br>
Is there a simple way to find out names of the functions and their interface from that library ?</p>
<p>Something similar to <code>emfar</code> and <code>elfdump</code> utilities (on Linux systems) ?</p>
| [
{
"answer_id": 305444,
"author": "Tim Lesher",
"author_id": 14942,
"author_profile": "https://Stackoverflow.com/users/14942",
"pm_score": 9,
"selected": true,
"text": "DUMPBIN /SYMBOLS .lib DUMPBIN /EXPORTS .lib DUMPBIN /SYMBOLS"
},
{
"answer_id": 4752279,
"author": "lgwest",
"author_id": 199138,
"author_profile": "https://Stackoverflow.com/users/199138",
"pm_score": 5,
"selected": false,
"text": "ar t libfile.a lib.exe /list libfile.lib"
},
{
"answer_id": 21703818,
"author": "user3292568",
"author_id": 3292568,
"author_profile": "https://Stackoverflow.com/users/3292568",
"pm_score": 2,
"selected": false,
"text": "dumpbin /EXPORTS my_lib_name.lib"
},
{
"answer_id": 26689684,
"author": "Tanguy",
"author_id": 293527,
"author_profile": "https://Stackoverflow.com/users/293527",
"pm_score": 7,
"selected": false,
"text": "dumpbin /ARCHIVEMEMBERS openssl.x86.lib\n lib /LIST openssl.x86.lib\n"
},
{
"answer_id": 54460975,
"author": "Hilton Fernandes",
"author_id": 9195343,
"author_profile": "https://Stackoverflow.com/users/9195343",
"pm_score": 2,
"selected": false,
"text": "dumpbin.exe dumpbin /EXPORTS yourlibrary.lib dumpbin /SYMBOLS /EXPORTS yourlibrary.lib findstr grep Static"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/305287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4378/"
] |
305,291 | <p>I have a .NET Set and Deployment project which has to execute a set of really long SQL Scripts as a part of the installation process. I have used SMO dlls to make calls to the .sql script files.These SMO dlls are however not a part of the .NET framework but they come bundled with SQL Server 2005 or 2008. Now, if the setup is run on a machine which does not have SQL Server 2005/2008 installed the SQL script execution fails. This is a perfectly valid use case for my setup as the user might not have SQL server on his local machine but on a network server.
How do i embedd the SMO dll's along with the setup .msi so that it doesnt have to depend on any SMO dlls on the machine it is being run?</p>
| [
{
"answer_id": 305444,
"author": "Tim Lesher",
"author_id": 14942,
"author_profile": "https://Stackoverflow.com/users/14942",
"pm_score": 9,
"selected": true,
"text": "DUMPBIN /SYMBOLS .lib DUMPBIN /EXPORTS .lib DUMPBIN /SYMBOLS"
},
{
"answer_id": 4752279,
"author": "lgwest",
"author_id": 199138,
"author_profile": "https://Stackoverflow.com/users/199138",
"pm_score": 5,
"selected": false,
"text": "ar t libfile.a lib.exe /list libfile.lib"
},
{
"answer_id": 21703818,
"author": "user3292568",
"author_id": 3292568,
"author_profile": "https://Stackoverflow.com/users/3292568",
"pm_score": 2,
"selected": false,
"text": "dumpbin /EXPORTS my_lib_name.lib"
},
{
"answer_id": 26689684,
"author": "Tanguy",
"author_id": 293527,
"author_profile": "https://Stackoverflow.com/users/293527",
"pm_score": 7,
"selected": false,
"text": "dumpbin /ARCHIVEMEMBERS openssl.x86.lib\n lib /LIST openssl.x86.lib\n"
},
{
"answer_id": 54460975,
"author": "Hilton Fernandes",
"author_id": 9195343,
"author_profile": "https://Stackoverflow.com/users/9195343",
"pm_score": 2,
"selected": false,
"text": "dumpbin.exe dumpbin /EXPORTS yourlibrary.lib dumpbin /SYMBOLS /EXPORTS yourlibrary.lib findstr grep Static"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/305291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
305,293 | <p>Paragraph 6.7.3.8 of the C99 spec states</p>
<blockquote>If the specification of an array type includes any type qualifiers, the element type is so-qualified, not the array type. If the specification of a function type includes any type qualifiers, the behavior is undefined. </blockquote>
<p>In the <a href="http://www.open-std.org/jtc1/sc22/wg14/www/C99RationaleV5.10.pdf" rel="noreferrer">rationale</a> (logical page 87, physical page 94), an example of casting a flat pointer to a (variable length) array pointer is given.</p>
<pre><code>void g(double *ap, int n)
{
double (*a)[n] = (double (*)[n]) ap;
/* ... */ a[1][2] /* ... */
}
</code></pre>
<p>Certainly if the array <code>ap</code> is not modified within the function, it should be marked const, however the cast in</p>
<pre><code>void g(const double *ap, int n)
{
const double (*a)[n] = (const double (*)[n]) ap;
/* ... */
}
</code></pre>
<p>does not preserve the <code>const</code> qualifier since (per 6.7.3.8) it applies to the elements of the target instead of the target itself, which has array type <code>double[n]</code>. This means that compilers will rightly complain if given the appropriate flags (<code>-Wcast-qual</code> for GCC). There is no way to denote a <code>const</code> array type in C, but this cast is very useful and "correct". The <code>-Wcast-qual</code> flag is useful for identifying misuse of array parameters, but the false positives discourage its use. Note that indexing <code>a[i][j]</code> is both more readable and, with many compilers, produces better machine code than <code>ap[i*n+j]</code> since the former allows some integer arithmetic to be hoisted out of inner loops with less analysis.</p>
<p>Should compilers just treat this as a special case, effectively lifting qualifiers from the elements to the array type to determine whether a given cast removes qualifiers or should the spec be amended? Assignment is not defined for array types, so would it hurt for qualifiers to always apply to the array type rather than just the elements, in contrast to 6.7.3.8?</p>
| [
{
"answer_id": 305333,
"author": "Ken Gentle",
"author_id": 8709,
"author_profile": "https://Stackoverflow.com/users/8709",
"pm_score": 0,
"selected": false,
"text": "const double *ap double *const ap const double *const ap gcc"
},
{
"answer_id": 305341,
"author": "finnw",
"author_id": 12048,
"author_profile": "https://Stackoverflow.com/users/12048",
"pm_score": 1,
"selected": false,
"text": "-Wcast-qual void g(const double *ap, int n)\n{\n int i;\n struct box \n {\n double a[n];\n };\n const struct box *s = (const struct box *)ap;\n\n for (i=0; i<n; ++i)\n {\n doStuffWith(s->a[i]);\n /* ... */\n }\n}\n a"
},
{
"answer_id": 305504,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 4,
"selected": true,
"text": "news:comp.std.c"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/305293",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33208/"
] |
305,306 | <p>I have an Informix SQL query which returns a set of rows. It was slightly modified for the new version of the site we've been working on and our QA noticed that the new version returns different results. After investigation we've found that the only difference between two queries were in the number of fields returned.</p>
<p>FROM, WHERE and ORDER BY clauses are identical and the column names in the SELECT part did not affect the results. It was only the number of fields which caused the problem.</p>
<p>Any ideas?</p>
| [
{
"answer_id": 305309,
"author": "Ilya Kochetov",
"author_id": 15329,
"author_profile": "https://Stackoverflow.com/users/15329",
"pm_score": 2,
"selected": false,
"text": "--+ ORDERED SELECT --+ ORDERED\n name, title, salary, dname\nFROM dept, job, emp WHERE title = 'clerk' AND loc = 'Palo Alto' \n AND emp.dno = dept.dno \n AND emp.job= job.job;\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/305306",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15329/"
] |
305,307 | <p>This code works perfectly</p>
<pre><code>myNotebook = new wxNotebook( this, IDC_NOTEBOOK, wxDefaultPosition, wxSize(500, 500) );
myNotebook->AddPage( new wxNotebookPage( myNotebook, -1 ), L"TEST RECOMMENDATIONS 1" );
myNotebook->AddPage( new wxNotebookPage( myNotebook, -1 ), L"TEST RECOMMENDATIONS 2" );
myNotebook->AddPage( new wxNotebookPage( myNotebook, -1 ), L"TEST RECOMMENDATIONS 3" );
myNotebook->AddPage( new wxNotebookPage( myNotebook, -1 ), L"TEST RECOMMENDATIONS 4" );
myNotebook->AddPage( new wxNotebookPage( myNotebook, -1 ), L"TEST RECOMMENDATIONS 5" );
myNotebook->AddPage( new wxNotebookPage( myNotebook, -1 ), L"TEST RECOMMENDATIONS 6" );
</code></pre>
<p>However, the tab names are so long and numerous they have to be horizontally scrolled.</p>
<p>Using the wxNB_MULTILINE style does not work properly: the second line of tabs is obscured and unreadable</p>
<pre><code>myNotebook = new wxNotebook( this, IDC_NOTEBOOK, wxDefaultPosition, wxSize(500, 500), wxNB_MULTILINE );
myNotebook->AddPage( new wxNotebookPage( myNotebook, -1 ), L"TEST RECOMMENDATIONS 1" );
myNotebook->AddPage( new wxNotebookPage( myNotebook, -1 ), L"TEST RECOMMENDATIONS 2" );
myNotebook->AddPage( new wxNotebookPage( myNotebook, -1 ), L"TEST RECOMMENDATIONS 3" );
myNotebook->AddPage( new wxNotebookPage( myNotebook, -1 ), L"TEST RECOMMENDATIONS 4" );
myNotebook->AddPage( new wxNotebookPage( myNotebook, -1 ), L"TEST RECOMMENDATIONS 5" );
myNotebook->AddPage( new wxNotebookPage( myNotebook, -1 ), L"TEST RECOMMENDATIONS 6" );
</code></pre>
<p>How do I use the multiline style correctly?</p>
| [
{
"answer_id": 306042,
"author": "ravenspoint",
"author_id": 16582,
"author_profile": "https://Stackoverflow.com/users/16582",
"pm_score": 1,
"selected": false,
"text": " myNotebook->Layout();\n"
},
{
"answer_id": 1603195,
"author": "ravenspoint",
"author_id": 16582,
"author_profile": "https://Stackoverflow.com/users/16582",
"pm_score": 1,
"selected": false,
"text": "EVT_NOTEBOOK_PAGE_CHANGED myNotebook->GetPage( event.GetSelection() )->Move(0,40);\n"
},
{
"answer_id": 1673880,
"author": "ravenspoint",
"author_id": 16582,
"author_profile": "https://Stackoverflow.com/users/16582",
"pm_score": 1,
"selected": true,
"text": "void MyFrame::OnSize(wxSizeEvent& )\n{\n if( myNotebook ) {\n myNotebook->SetSize( GetClientRect() );\n myNotebook->Refresh();\n }\n}\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/305307",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16582/"
] |
305,320 | <p>I'm trying to learn Actionscript 2 or 3, with AS2 I eventually figured by trial and error that I could get any named instance and modify it using a string with its name using</p>
<pre><code>var theinstance = "titletext"; // actually exctracted from an array
_root[theinstance].htmlText = "New text with <b>HTML!</b>";
</code></pre>
<p>but when trying to convert the code to AS3 <code>_root</code> doesn't exist anymore. According to the <a href="http://livedocs.adobe.com/flex/3/langref/migration.html" rel="nofollow noreferrer">migration doc</a> it is somehow replaced by <code>flash.display.DisplayObject.stage</code> but apparently this is not how to do it:</p>
<pre><code>flash.display.DisplayObject.stage[theinstance].htmlText = "New text with <b>HTML!</b>";
</code></pre>
<p>and neither is this:</p>
<pre><code>flash.display.DisplayObject.stage.getChildByName(theinstance).htmlText = "New text with <b>HTML!</b>";
</code></pre>
<p>How <em>do</em> I get a child by name in actionscript 3?</p>
| [
{
"answer_id": 305347,
"author": "Matt Howell",
"author_id": 2321,
"author_profile": "https://Stackoverflow.com/users/2321",
"pm_score": 2,
"selected": false,
"text": "foo.stage\n foo.stage.someRootLevelObject.htmlText = \"Pretty <b>easy</b>\";\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/305320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26115/"
] |
305,337 | <p>I am using iText to generate PDF invoices for a J2EE web application and included on the page is an image read from a URL constructed from the request URL. In the development and test environments this works fine, but in production I get a java.io.IOException: is not a recognized imageformat.</p>
<p>If I paste the url into my browser then the correct image is returned, however the request is redirected from http to https. In my code if I hard code the redirect URL then the image is displayed correctly. </p>
<p>So it seems that when retrieving the image using com.lowagie.text.Image.getInstance(URL), the redirects on the URL are not being followed. How can I output an image from a redirected URL using iText?</p>
| [
{
"answer_id": 307756,
"author": "CFreiner",
"author_id": 36641,
"author_profile": "https://Stackoverflow.com/users/36641",
"pm_score": 2,
"selected": false,
"text": "Image.getInstance(\"yourimage.gif\");\n"
},
{
"answer_id": 3553596,
"author": "Ananthan",
"author_id": 429112,
"author_profile": "https://Stackoverflow.com/users/429112",
"pm_score": 2,
"selected": false,
"text": "Image.getInstance(\"path\")"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/305337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25464/"
] |
305,349 | <p>I have seen that there is a NVL function for PL/SQL that substitutes a value when null is encountered.<br>
But what if I want to set a field to NULL, e.g. </p>
<pre><code>EXEC SQL UPDATE mytable SET myfield=NULL WHERE otherValue=1;
</code></pre>
<p>When I run this with C++ on HPUX, 0L is used for null while on Linux the statement fails with <code>illegal value</code>.</p>
<p>Is there a generic Oracle null value/method I can use?</p>
| [
{
"answer_id": 305406,
"author": "Dave Costa",
"author_id": 6568,
"author_profile": "https://Stackoverflow.com/users/6568",
"pm_score": 2,
"selected": false,
"text": "#define NULL 0L"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/305349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
305,357 | <p>Okay i am working on someone elses code. They do alot of this:</p>
<pre><code>char description[256];
description[0]=0;
</code></pre>
<p>I know this would put a \0 in the first spot of the character array. But is this even a safe way to erase a string?</p>
<p>Also visual studio keeps reporting memory leaks, and i've pretty much tied this done to the strings that are used.</p>
<p>Ps. Yes i know about std::string, yes i use that. This isn't my code.</p>
| [
{
"answer_id": 305365,
"author": "Kyle Cronin",
"author_id": 658,
"author_profile": "https://Stackoverflow.com/users/658",
"pm_score": 2,
"selected": false,
"text": "char *str = malloc(256*sizeof(char)); // str now is a pointer to a 256-char array\n...\n// some code here\n...\nfree(str); // free the memory\n"
},
{
"answer_id": 305367,
"author": "finnw",
"author_id": 12048,
"author_profile": "https://Stackoverflow.com/users/12048",
"pm_score": 2,
"selected": false,
"text": "\\0"
},
{
"answer_id": 305414,
"author": "warren",
"author_id": 4418,
"author_profile": "https://Stackoverflow.com/users/4418",
"pm_score": 4,
"selected": true,
"text": "char description[256] = {0};\n 0 '\\0' 0 '\\0'"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/305357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34395/"
] |
305,359 | <p>I want to write a function that accepts a parameter which can be either a sequence or a single value. The type of value is str, int, etc., but I <strong>don't</strong> want it to be restricted to a hardcoded list.
In other words, I want to know if the parameter X is a sequence or something I have to convert to a sequence to avoid special-casing later. I could do</p>
<p><code>type(X) in (list, tuple)</code></p>
<p>but there may be other sequence types I'm not aware of, and no common base class.</p>
<p>-N.</p>
<p><strong>Edit</strong>: See my "answer" below for why most of these answers don't help me. Maybe you have something better to suggest.</p>
| [
{
"answer_id": 305388,
"author": "Dave Costa",
"author_id": 6568,
"author_profile": "https://Stackoverflow.com/users/6568",
"pm_score": 1,
"selected": false,
"text": "is_sequence = '__getslice__' in dir(X)\n"
},
{
"answer_id": 305397,
"author": "kgiannakakis",
"author_id": 24054,
"author_profile": "https://Stackoverflow.com/users/24054",
"pm_score": -1,
"selected": false,
"text": "x.__class__ == \"\".__class__\n"
},
{
"answer_id": 305417,
"author": "Ricardo Reyes",
"author_id": 3399,
"author_profile": "https://Stackoverflow.com/users/3399",
"pm_score": 0,
"selected": false,
"text": "if hasattr(X, '__contains__'):\n print \"X is a sequence\"\n if hasattr(X, '__iter__'):\n print \"X is a sequence\"\n for each in X:\n print each\n"
},
{
"answer_id": 305587,
"author": "Piotr Lesnicki",
"author_id": 38796,
"author_profile": "https://Stackoverflow.com/users/38796",
"pm_score": 2,
"selected": false,
"text": "__getitem__ __iter__ __iter__ __getslice__ hasattr(\"__getitem__\", X) hasattr(\"__iter__\", X)"
},
{
"answer_id": 305695,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 2,
"selected": false,
"text": "try:\n it = iter(X)\n # Iterable\nexcept TypeError:\n # Not iterable\n if not isinstance(X, basestring)\n"
},
{
"answer_id": 305997,
"author": "Brandon",
"author_id": 28916,
"author_profile": "https://Stackoverflow.com/users/28916",
"pm_score": 0,
"selected": false,
"text": "\n def _use_single_val(v):\n print v + 1 # this will fail if v is not a value type\n\n def _use_sequence(s):\n print s[0] # this will fail if s is not indexable\n\n def use_seq_or_val(item): \n try:\n _use_single_val(item)\n except TypeError:\n pass\n\n try:\n _use_sequence(item)\n except TypeError:\n pass\n\n raise TypeError, \"item not a single value or sequence\"\n"
},
{
"answer_id": 306222,
"author": "A. Coady",
"author_id": 36433,
"author_profile": "https://Stackoverflow.com/users/36433",
"pm_score": 4,
"selected": false,
"text": ">>> import collections\n>>> isinstance([], collections.Sequence)\nTrue\n>>> isinstance(0, collections.Sequence)\nFalse\n import abc\nimport collections\n\nclass Atomic(object):\n __metaclass__ = abc.ABCMeta\n @classmethod\n def __subclasshook__(cls, other):\n return not issubclass(other, collections.Sequence) or NotImplemented\n\nAtomic.register(basestring)\n assert isinstance(\"hello\", Atomic) == True\n basestring class Atomic(metaclass=abc.ABCMeta):\n @classmethod\n def __subclasshook__(cls, other):\n return not issubclass(other, collections.Sequence) or NotImplemented\n\nAtomic.register(str)\n with_metaclass() class _AtomicBase(object):\n @classmethod\n def __subclasshook__(cls, other):\n return not issubclass(other, collections.Sequence) or NotImplemented\n\nclass Atomic(abc.ABCMeta(\"NewMeta\", (_AtomicBase,), {})):\n pass\n\ntry:\n unicode = unicode\nexcept NameError: # 'unicode' is undefined, assume Python >= 3\n Atomic.register(str) # str includes unicode in Py3, make both Atomic\n Atomic.register(bytes) # bytes will also be considered Atomic (optional)\nelse:\n # basestring is the abstract superclass of both str and unicode types\n Atomic.register(basestring) # make both types of strings Atomic\n operator >>> import operator\n>>> operator.isSequenceType([])\nTrue\n>>> operator.isSequenceType(0)\nFalse\n"
},
{
"answer_id": 312368,
"author": "noamtm",
"author_id": 38557,
"author_profile": "https://Stackoverflow.com/users/38557",
"pm_score": 2,
"selected": false,
"text": "str __getitem__"
},
{
"answer_id": 331826,
"author": "muhuk",
"author_id": 42188,
"author_profile": "https://Stackoverflow.com/users/42188",
"pm_score": 2,
"selected": false,
"text": "myfunc(item)\nmyfunc(*items)\n"
},
{
"answer_id": 340801,
"author": "orip",
"author_id": 37020,
"author_profile": "https://Stackoverflow.com/users/37020",
"pm_score": 1,
"selected": false,
"text": "def is_iterable(x):\n if type(x) == str:\n return False\n try:\n iter(x)\n return True\n except TypeError:\n return False\n"
},
{
"answer_id": 425567,
"author": "Gregg Lind",
"author_id": 15842,
"author_profile": "https://Stackoverflow.com/users/15842",
"pm_score": 4,
"selected": true,
"text": "def to_sequence(arg):\n ''' \n determine whether an arg should be treated as a \"unit\" or a \"sequence\"\n if it's a unit, return a 1-tuple with the arg\n '''\n def _multiple(x): \n return hasattr(x,\"__iter__\")\n if _multiple(arg): \n return arg\n else:\n return (arg,)\n\n>>> to_sequence(\"a string\")\n('a string',)\n>>> to_sequence( (1,2,3) )\n(1, 2, 3)\n>>> to_sequence( xrange(5) )\nxrange(5)\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/305359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38557/"
] |
305,378 | <p>For some reason I can't find a way to get the equivalents of sqlite's interactive shell commands:</p>
<pre><code>.tables
.dump
</code></pre>
<p>using the Python sqlite3 API. </p>
<p>Is there anything like that?</p>
| [
{
"answer_id": 305395,
"author": "finnw",
"author_id": 12048,
"author_profile": "https://Stackoverflow.com/users/12048",
"pm_score": 5,
"selected": false,
"text": "SELECT * FROM sqlite_master;\n"
},
{
"answer_id": 305639,
"author": "converter42",
"author_id": 28974,
"author_profile": "https://Stackoverflow.com/users/28974",
"pm_score": 8,
"selected": true,
"text": "sqlite> .tab\njob snmptarget t1 t2 t3 \nsqlite> select name from sqlite_master where type = 'table';\njob\nt1\nt2\nsnmptarget\nt3\n\nsqlite> .schema job\nCREATE TABLE job (\n id INTEGER PRIMARY KEY,\n data VARCHAR\n);\nsqlite> select sql from sqlite_master where type = 'table' and name = 'job';\nCREATE TABLE job (\n id INTEGER PRIMARY KEY,\n data VARCHAR\n)\n"
},
{
"answer_id": 601222,
"author": "checkit",
"author_id": 24311,
"author_profile": "https://Stackoverflow.com/users/24311",
"pm_score": 4,
"selected": false,
"text": "# Convert file existing_db.db to SQL dump file dump.sql\nimport sqlite3, os\n\ncon = sqlite3.connect('existing_db.db')\nwith open('dump.sql', 'w') as f:\n for line in con.iterdump():\n f.write('%s\\n' % line)\n"
},
{
"answer_id": 10746045,
"author": "Davoud Taghawi-Nejad",
"author_id": 236830,
"author_profile": "https://Stackoverflow.com/users/236830",
"pm_score": 8,
"selected": false,
"text": "con = sqlite3.connect('database.db')\ncursor = con.cursor()\ncursor.execute(\"SELECT name FROM sqlite_master WHERE type='table';\")\nprint(cursor.fetchall())\n"
},
{
"answer_id": 27392638,
"author": "user3451435",
"author_id": 3451435,
"author_profile": "https://Stackoverflow.com/users/3451435",
"pm_score": 3,
"selected": false,
"text": "meta = cursor.execute(\"PRAGMA table_info('Job')\")\nfor r in meta:\n print r\n"
},
{
"answer_id": 29618411,
"author": "c9s",
"author_id": 780629,
"author_profile": "https://Stackoverflow.com/users/780629",
"pm_score": 0,
"selected": false,
"text": "$parser = new SqliteTableDefinitionParser;\n$parser->parseColumnDefinitions('x INTEGER PRIMARY KEY, y DOUBLE, z DATETIME default \\'2011-11-10\\', name VARCHAR(100)');\n"
},
{
"answer_id": 33100538,
"author": "Davoud Taghawi-Nejad",
"author_id": 236830,
"author_profile": "https://Stackoverflow.com/users/236830",
"pm_score": 7,
"selected": false,
"text": "db = sqlite3.connect('database.db')\ntable = pd.read_sql_query(\"SELECT * from table_name\", db)\ntable.to_csv(table_name + '.csv', index_label='index')\n import sqlite3\nimport pandas as pd\n\n\ndef to_csv():\n db = sqlite3.connect('database.db')\n cursor = db.cursor()\n cursor.execute(\"SELECT name FROM sqlite_master WHERE type='table';\")\n tables = cursor.fetchall()\n for table_name in tables:\n table_name = table_name[0]\n table = pd.read_sql_query(\"SELECT * from %s\" % table_name, db)\n table.to_csv(table_name + '.csv', index_label='index')\n cursor.close()\n db.close()\n"
},
{
"answer_id": 33330898,
"author": "VecH",
"author_id": 5486134,
"author_profile": "https://Stackoverflow.com/users/5486134",
"pm_score": 2,
"selected": false,
"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nif __name__ == \"__main__\":\n\n import sqlite3\n\n dbname = './db/database.db'\n try:\n print \"INITILIZATION...\"\n con = sqlite3.connect(dbname)\n cursor = con.cursor()\n cursor.execute(\"SELECT name FROM sqlite_master WHERE type='table';\")\n tables = cursor.fetchall()\n for tbl in tables:\n print \"\\n######## \"+tbl[0]+\" ########\"\n cursor.execute(\"SELECT * FROM \"+tbl[0]+\";\")\n rows = cursor.fetchall()\n for row in rows:\n print row\n print(cursor.fetchall())\n except KeyboardInterrupt:\n print \"\\nClean Exit By user\"\n finally:\n print \"\\nFinally\"\n"
},
{
"answer_id": 41007154,
"author": "RufusVS",
"author_id": 925592,
"author_profile": "https://Stackoverflow.com/users/925592",
"pm_score": 5,
"selected": false,
"text": "import sqlite3\n\ndb_filename = 'database.sqlite'\nnewline_indent = '\\n '\n\ndb=sqlite3.connect(db_filename)\ndb.text_factory = str\ncur = db.cursor()\n\nresult = cur.execute(\"SELECT name FROM sqlite_master WHERE type='table';\").fetchall()\ntable_names = sorted(zip(*result)[0])\nprint \"\\ntables are:\"+newline_indent+newline_indent.join(table_names)\n\nfor table_name in table_names:\n result = cur.execute(\"PRAGMA table_info('%s')\" % table_name).fetchall()\n column_names = zip(*result)[1]\n print (\"\\ncolumn names for %s:\" % table_name)+newline_indent+(newline_indent.join(column_names))\n\ndb.close()\nprint \"\\nexiting.\"\n import sqlite3\n\ndb_filename = 'database.sqlite'\nnewline_indent = '\\n '\n\ndb=sqlite3.connect(db_filename)\ndb.text_factory = str\ncur = db.cursor()\n\nresult = cur.execute(\"SELECT name FROM sqlite_master WHERE type='table';\").fetchall()\ntable_names = sorted(list(zip(*result))[0])\nprint (\"\\ntables are:\"+newline_indent+newline_indent.join(table_names))\n\nfor table_name in table_names:\n result = cur.execute(\"PRAGMA table_info('%s')\" % table_name).fetchall()\n column_names = list(zip(*result))[1]\n print ((\"\\ncolumn names for %s:\" % table_name)\n +newline_indent\n +(newline_indent.join(column_names)))\n\ndb.close()\nprint (\"\\nexiting.\")\n"
},
{
"answer_id": 60018870,
"author": "Mukesh Yadav",
"author_id": 167033,
"author_profile": "https://Stackoverflow.com/users/167033",
"pm_score": 5,
"selected": false,
"text": "import pandas as pd\nimport sqlite3\nconn = sqlite3.connect(\"db.sqlite3\")\ntable = pd.read_sql_query(\"SELECT name FROM sqlite_master WHERE type='table'\", conn)\nprint(table)\n"
},
{
"answer_id": 65800752,
"author": "ALee",
"author_id": 15040600,
"author_profile": "https://Stackoverflow.com/users/15040600",
"pm_score": 3,
"selected": false,
"text": "conn = sqlite3.connect('example.db')\nc = conn.cursor()\n\ndef table_info(c, conn):\n '''\n prints out all of the columns of every table in db\n c : cursor object\n conn : database connection object\n '''\n tables = c.execute(\"SELECT name FROM sqlite_master WHERE type='table';\").fetchall()\n for table_name in tables:\n table_name = table_name[0] # tables is a list of single item tuples\n table = pd.read_sql_query(\"SELECT * from {} LIMIT 0\".format(table_name), conn)\n print(table_name)\n for col in table.columns:\n print('\\t' + col)\n print()\n\ntable_info(c, conn)\n Results will be:\n\ntable1\n column1\n column2\n\ntable2\n column1\n column2\n column3 \n\netc.\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/305378",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38557/"
] |
305,386 | <p>I have two branches, the main branch(black) and a feature branch(yellow).</p>
<p>As you can see, since the feature branch was forked, it was kept up to date fetching changes from main:</p>
<p><a href="http://azkotoki.org/images/stackoverflow/tgh-reintegrate1.gif" rel="nofollow noreferrer">alt text http://azkotoki.org/images/stackoverflow/tgh-reintegrate1.gif</a></p>
<p>When I reintegrate back the feature branch to the main one, the log window shows this ugly graph:</p>
<p><a href="http://azkotoki.org/images/stackoverflow/tgh-reintegrate2.gif" rel="nofollow noreferrer">alt text http://azkotoki.org/images/stackoverflow/tgh-reintegrate2.gif</a></p>
<p>It shows each merge point as a new branch that was merged with the feature branch. If I had several feature branches this would became almost impossible to read. I also tried with <code>hg view</code> and the results are even weirder.</p>
<p>Regardless the picture shown above, the final merge results are fine, but the graph with the reintegrated branch annoys me. </p>
<p>Am I doing something wrong by merging to the feature branch too many times? Or I expect too much from tortoisehg's log window :) ?</p>
<p>Thanks in advance</p>
| [
{
"answer_id": 897037,
"author": "Martin Geisler",
"author_id": 110204,
"author_profile": "https://Stackoverflow.com/users/110204",
"pm_score": 3,
"selected": true,
"text": "0 Imported initial repo.\n1 Trivial change to also echo b.\n2 Added another echo for c.\n3 Echo for d.\n4 Echo for e.\n 0 Imported initial repo.\n1 Trivial change to also echo b.\n3 Added another echo for c.\n4 Automatic merge...\n5 Echo for d.\n6 Automatic merge...\n7 Echo for e.\n8 Automatic merge...\n 0 Imported initial repo.\n1 Trivial change to also echo b.\n2 Added another echo for c.\n3 Echo for d.\n4 Echo for e.\n5 Refactored echos to print.\n6 Automatic merge...\n7 Automatic merge...\n8 Automatic merge...\n .hg/hgrc"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/305386",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28581/"
] |
305,393 | <p>I am writing an unit test for a mvc web application that checks if a returned list of anonymous variables(in a jsonresult) is correct. therefore i need to iterate through that list but i cannot seem to find a way to do so.</p>
<p>so i have 2 methods</p>
<p>1) returns a json result . In that json result there is a property called data. that property is of type object but internally it's a list of anonymous variables</p>
<p>2) the method calls method 1 and checks if the returned jsonresult is ok.</p>
<p>if i run the test and i break the debugger i can hover over the result and see the items in it. i just don't find a way to do so in code.(just using a foreach isn't possible because at the point i need it i'm not in the method that created the anonymous method)</p>
| [
{
"answer_id": 305412,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 2,
"selected": true,
"text": "foreach object foreach (object o in myList)\n{\n // Not sure what you're actually trying to do in here...\n}\n ToString var strings = ((IEnumerable) result).Cast<object>.Select(x => x.ToString());\n strings SequenceEqual"
},
{
"answer_id": 305448,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": " var objects= ((IEnumerable)result.Data);\n foreach (object obj in objects)\n {\n //inhere i can use reflection to get the properties out of it\n }\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/305393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
305,419 | <p>How do I accomplish text wrapping of table fields in SSRS Report, and proper landscaping when rendering the report to PDF format?</p>
| [
{
"answer_id": 305427,
"author": "Aidan Ryan",
"author_id": 1042,
"author_profile": "https://Stackoverflow.com/users/1042",
"pm_score": 0,
"selected": false,
"text": "=Replace(Fields!MyField.Value, vbLf, Environment.NewLine)\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/305419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
305,422 | <p>If any one can help me with Python code:
If I input a letter, How can I print all the words start with that word?</p>
| [
{
"answer_id": 305430,
"author": "csl",
"author_id": 21028,
"author_profile": "https://Stackoverflow.com/users/21028",
"pm_score": 1,
"selected": false,
"text": "words = [\"zwei\", \"peanuts\", \"were\", \"walking\", \"down\", \"the\", \"strasse\"]\nletter = \"w\"\noutput = [x for x in words if x[0] == letter]\n output ['were', 'walking']\n"
},
{
"answer_id": 305440,
"author": "Mariano",
"author_id": 12514,
"author_profile": "https://Stackoverflow.com/users/12514",
"pm_score": 2,
"selected": false,
"text": "print [word for word in words if word.startswith(letter)]\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/305422",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
305,431 | <p><a href="http://www.w3.org/TR/xhtml1/#C_2" rel="noreferrer">W3C recommends putting a space before the closing tag in XHTML</a>, because this would give a better backwards compability with some browsers, e.g. write <code><br /></code> instead of <code><br/></code>. But are there still browsers out there, that would not tolerate that you omitted the space? (W3C do not mention which browsers cause problems.)</p>
<p>I know it doesn't make much of a diffence. I just prefer the shorter version. So unless there is a good reason I will now start coding my XHTML without spaces before closing empty tags.</p>
| [
{
"answer_id": 306181,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 1,
"selected": false,
"text": "x=\"foo\" />"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/305431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37147/"
] |
305,434 | <p>What I'm trying to do is run the same SQL select on many Oracle databases (at least a dozen), and display the output in a Gridview.</p>
<p>I've hacked together something that works but unfortunately it's very slow. I think its exacerbated by the fact that at least 1 of the dozen databases will invariably be unreachable or otherwise in an error state.</p>
<p>As well as being slow I can't help thinking it's not the best way of doing it, nor very '.NET' like.</p>
<p>I've written something similar in the past as a simple loop in PHP that just connects to each db in turn, runs the sql and writes another <code><tr></code>, and it works at least twice as fast, for a given query. But I'm not really happy with that, I'd like to improve my knowledge!</p>
<p>I'm learning C# and ASP.NET so please excuse the horrible code :)</p>
<pre><code>public void BindData(string mySQL)
{
OracleConnection myConnection;
OracleDataAdapter TempDataAdapter;
DataSet MainDataSet = new DataSet();
DataTable MainDataTable = new DataTable();
DataSet TempDataSet;
DataTable TempDataTable;
string connectionString = "";
Label1.Visible = false;
Label1.Text = "";
foreach (ListItem li in CheckBoxList1.Items)
{
if (li.Selected)
{
connectionString = "Data Source=" + li.Text + "";
connectionString += ";Persist Security Info=True;User ID=user;Password=pass;Unicode=True";
myConnection = new OracleConnection(connectionString);
try
{
TempDataAdapter = new OracleDataAdapter(mySQL, myConnection);
TempDataSet = new DataSet();
TempDataTable = new DataTable();
TempDataAdapter.Fill(TempDataSet);
TempDataTable = TempDataSet.Tables[0].Copy();
/* If the main dataset is empty, create a table by cloning from temp dataset, otherwise
copy all rows to existing table.*/
if (MainDataSet.Tables.Count == 0)
{
MainDataSet.Tables.Add(TempDataTable);
MainDataTable = MainDataSet.Tables[0];
}
else
{
foreach (DataRow dr in TempDataTable.Rows)
{
MainDataTable.ImportRow(dr);
}
}
}
catch (OracleException e)
{
Label1.Visible = true;
Label1.Text = Label1.Text + e.Message + " on " + li.Text + "<br>";
}
finally
{
if (myConnection != null)
{
myConnection.Close();
myConnection = null;
}
TempDataSet = null;
TempDataAdapter = null;
TempDataTable = null;
}
}
}
GridView1.DataSourceID = String.Empty;
if (MainDataSet.Tables.Count != 0)
{
GridView1.DataSource = MainDataSet;
if (GridView1.DataSource != null)
{
GridView1.DataBind();
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
BindData(TextBox1.Text);
}
</code></pre>
<p>Thanks!</p>
<p>UPDATE: The SQL code varies, for testing I have used very simple queries such as <code>select sysdate from dual</code> or <code>select name from v$database</code>. In eventual use, it will be much more complicated, the idea is that I should be able to run pretty much anything, hence the <code>BindData(TextBox1.Text)</code></p>
<p>UPDATE: The reason for connecting to many databases from the ASP.NET code rather than a stored proc on one or all dbs, or replicating to one db, is twofold. Firstly, the dbs in question are frequently updated replicas of several similar production environments (typically development, testing and support for each client), so anything done to the actual dbs would have to be updated or redone regularly as they are reloaded anyway. Secondly, I don't know in advance what kind of query might be run, this form lets me just type e.g. <code>select count (name) from dbusers</code> against a dozen databases without having to first think about replicating the dbusers table to a master db.</p>
| [
{
"answer_id": 306638,
"author": "Rune Grimstad",
"author_id": 30366,
"author_profile": "https://Stackoverflow.com/users/30366",
"pm_score": 3,
"selected": true,
"text": "public void BindData(string mySQL)\n{\n OracleConnection myConnection;\n // Empty connection string for now\n OracleDataAdapter MainDataAdapter = new OracleDataAdapter(mySQL, \"\"); \n DataTable MainDataTable = new DataTable();\n string connectionString = \"\";\n Label1.Visible = false;\n Label1.Text = \"\";\n\n foreach (ListItem li in CheckBoxList1.Items)\n {\n if (li.Selected)\n {\n connectionString = \"Data Source=\" + li.Text + \"\";\n connectionString += \";Persist Security Info=True;User ID=user;Password=pass;Unicode=True\";\n MainDataAdapter.SelectCommand.Connection.ConnectionString = connectionString\n try\n {\n MainDataAdapter.Fill(MainDataTable);\n }\n catch (OracleException e)\n {\n Label1.Visible = true;\n Label1.Text = Label1.Text + e.Message + \" on \" + li.Text + \"<br>\";\n }\n }\n }\n GridView1.DataSourceID = String.Empty;\n GridView1.DataSource = MainDataTable;\n GridView1.DataBind();\n}\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/305434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12744/"
] |
305,438 | <p>I need in a bash script to get details about a file when I know the inode.The system is Linux.</p>
| [
{
"answer_id": 305492,
"author": "CesarB",
"author_id": 28258,
"author_profile": "https://Stackoverflow.com/users/28258",
"pm_score": 0,
"selected": false,
"text": "find -inum -xdev"
},
{
"answer_id": 305499,
"author": "JimB",
"author_id": 32880,
"author_profile": "https://Stackoverflow.com/users/32880",
"pm_score": 3,
"selected": false,
"text": "find $SEARCHPATH -maxdepth $N -inum $INUM -exec ls -l {} \\;\n"
},
{
"answer_id": 309029,
"author": "Steve Baker",
"author_id": 13566,
"author_profile": "https://Stackoverflow.com/users/13566",
"pm_score": 3,
"selected": false,
"text": "debugfs -R \"ncheck $inode\" /dev/device 2> /dev/null | tail -1 | awk '{print $2}'\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/305438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
305,447 | <p>I need to use different database connection string and SMTP server address in my ASP.NET application depending on it is run in development or production environment. </p>
<p>The application reads settings from Web.config file via <a href="http://msdn.microsoft.com/en-us/library/system.web.configuration.webconfigurationmanager.appsettings.aspx" rel="noreferrer">WebConfigurationManager.AppSettings</a> property.</p>
<p>I use Build/Publish command to deploy the application to production server via FTP and then manually replace remote Web.config with correct one.</p>
<p>Is it possible somehow simplify the process of deployment? Thanks!</p>
| [
{
"answer_id": 305774,
"author": "Jason Slocomb",
"author_id": 34895,
"author_profile": "https://Stackoverflow.com/users/34895",
"pm_score": 6,
"selected": false,
"text": "<appSettings> <appSettings file=\".\\EnvironmentSpecificConfigurations\\dev.config\">\n\n<appSettings file=\".\\EnvironmentSpecificConfigurations\\qa.config\">\n\n<appSettings file=\".\\EnvironmentSpecificConfigurations\\production.config\">\n"
},
{
"answer_id": 3064598,
"author": "Pierre-Alain Vigeant",
"author_id": 151488,
"author_profile": "https://Stackoverflow.com/users/151488",
"pm_score": 8,
"selected": true,
"text": "app.config"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/305447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11256/"
] |
305,449 | <p>I need to upload a file using C# from a windows mobile app to a website. It's running PHP as the webservice on the other side, though I guess it really doesn't have to if there's another way to be able to get the file up there. There is no server-side ASP support, however. My problem really isn't the PHP, it's the mobile C# code. </p>
<p>Also, <strong>System.net.WebClient</strong> does NOT exist in the compact framework, so unfortunately, that simple solution is gone. </p>
<p>Let me apologize in advance, because I know this is a relatively commonly asked question, but I just can't seem to find an answer. I've spent an unseemly amount of time on this one particular problem with no solution, so any help at all would be greatly greatly appreciated. Thanks a lot!</p>
| [
{
"answer_id": 2294716,
"author": "Igor Stevebin",
"author_id": 276763,
"author_profile": "https://Stackoverflow.com/users/276763",
"pm_score": 0,
"selected": false,
"text": "using System.Data;\nusing System.Data.Sql\nusing System.Data.SqlClient;\nusing System.Web;\nusing System.Web.Services;\n\npublic class FileUploader: System.Web.Services.WebService {\n SqlConnection myConnection = new SqlConnection(\"Data Source=server name ;Initial Catalog=database name; User ID=username; Password='password';\");\n SqlCommand myCommand = new SqlCommand();\n string queryString = \"\";\n\npublic string UploadFile(byte[] f, string fileName)\n {\n // the byte array argument contains the content of the file\n // the string argument contains the name and extension\n // of the file passed in the byte array\n\nstring nm = data[0];\nstring sn =data[1];\nstring bn =data[2];\nstring st = data[3];\nbyte img = Convert.Tobyte(img);\nmyConnection.Open();\nqueryString = \"INSERT INTO tablename(Name,SchemeName,BeneficiarName,Status,Photo)\"\n\n+ \"VALUES('\" + nm + \"','\" + sn + \"','\"+ bn +\"','\" + st + \"',@img,')\";\n\nmyCommand.Parameters.AddWithValue(\"@img\",f);\nmyCommand.Connection = myConnection;\nmyCommand.CommandType = CommandType.Text; myCommand.CommandText = queryString; int res = myCommand.ExecuteNonQuery(); myConnection.Close();\n\nif (res > 0)\n{\n strres = \"File Uploaded successfully\"; }\n\nelse\n{ \n strres = \"File not uploaded\";\n}\n return strres;\n}\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/305449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39024/"
] |
305,457 | <p>When browsing the cube in Microsoft SQL Server Analysis Services 2005, I would like to peek at the MDX (supposedly) queries generated by client access tools such as Excel. Is there a tool or method that enables me to do just that?</p>
<p>I'm really looking for something like Oracle's v$sessions -- I know about sp_who and sp_who2 for the relational SQL Server, but is there one for MSAS?</p>
| [
{
"answer_id": 342998,
"author": "Darren Gosbell",
"author_id": 11860,
"author_profile": "https://Stackoverflow.com/users/11860",
"pm_score": 2,
"selected": false,
"text": "call ASSP.DMV(\"SELECT * FROM $System.DISCOVER_SESSIONS\");\n SELECT * FROM $System.DISCOVER_SESSIONS\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/305457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34704/"
] |
305,458 | <p>I need to create a site map/list, but I need the link-name to show up as well.</p>
<p>What I mean by that is given, say, www.google.com, I need the following list to be created.</p>
<pre><code>Google - www.google.com
Images - http://images.google.com/imghp?hl=en&tab=wi
...
My Account - http://images.google.com/imghp?hl=en&tab=wi
Personal Information Edit - https://www.google.com/accounts/EditUserInfo
...
My Products - https://www.google.com/accounts/EditServices
...
Privacy - http://www.google.com/intl/en/privacy.html
...
</code></pre>
<p>The list needs to be bound to a domain, say us.example.com.</p>
<p>I have tried a depth first search using a python script, with Beautiful Soup to parse the links. This was unsuccessful.</p>
<p>Anybody have any ideas on how they would do it? </p>
| [
{
"answer_id": 342998,
"author": "Darren Gosbell",
"author_id": 11860,
"author_profile": "https://Stackoverflow.com/users/11860",
"pm_score": 2,
"selected": false,
"text": "call ASSP.DMV(\"SELECT * FROM $System.DISCOVER_SESSIONS\");\n SELECT * FROM $System.DISCOVER_SESSIONS\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/305458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19731/"
] |
305,462 | <p>Is there a way to query the current DATEFORMAT SQLServer 2005 is currently using with T-SQL?</p>
<p>I have an application that reads pregenerated INSERT-statements and executes them against a database. To make the data to be inserted culture independent I store datetime-values represented in the invariant culture (month/day/year...) . The database server may run under different locales, depending on the system locale (maybe using day/month/year) , so the insert may crash because the datetime cannot be parsed.</p>
<p>I know there are the "SET LANGUAGE" and "SET DATEFORMAT" statements in T-SQL to set the locale to be used.<br>
I do not want to make these changes permanent (are they permanent?), so I'm looking for a way to read the DATEFORMAT from the DB, store it, change the format to my liking and reset it to the stored value after the data has been inserted.</p>
<p>Any ideas where to find that value in the server?</p>
| [
{
"answer_id": 305501,
"author": "George Mastros",
"author_id": 1408129,
"author_profile": "https://Stackoverflow.com/users/1408129",
"pm_score": 4,
"selected": true,
"text": "Select DatePart(Month, '1/2/2000')\n"
},
{
"answer_id": 2101563,
"author": "Scott Munro",
"author_id": 81595,
"author_profile": "https://Stackoverflow.com/users/81595",
"pm_score": 3,
"selected": false,
"text": "declare @dateFormat nvarchar(3);\nset @dateFormat = 'dmy';\n\ndeclare @originalDateFormat nvarchar(3);\nselect @originalDateFormat = date_format from sys.dm_exec_sessions where session_id = @@spid;\n\nset dateformat @dateFormat;\n\n--Returns 1.\nselect isdate('31/12/2010');\n\nset dateformat @originalDateFormat;\n"
},
{
"answer_id": 11524772,
"author": "sfnhltb",
"author_id": 1531411,
"author_profile": "https://Stackoverflow.com/users/1531411",
"pm_score": 1,
"selected": false,
"text": "create table #temp (SetOption nvarchar(50),Val nvarchar(50))\n\ninsert into #temp\nexec sp_executesql N'dbcc useroptions'\n\nselect val from #temp where setoption='dateformat'\n\ndrop table #temp\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/305462",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9602/"
] |
305,464 | <p>As the DetailsView uses <td> cells for both the header text and the data, I was wondering whether the behaviour of the control can be overridden to render the HeaderText of each row in a <th> cell?</p>
<hr>
<p>@Joel Coehoorn Thanks for the quick reply, but I was kind of hoping I wouldn't have to go down that route.</p>
<p>I was wondering whether it would be possible to override one of the control rendering methods to achieve this?</p>
<p>Someone seems to have <a href="http://forums.asp.net/p/985785/1270559.aspx" rel="nofollow noreferrer">had success rendering <th> cells</a> but did not appear to disclose details - any other suggestions would be gratefully received.</p>
| [
{
"answer_id": 305620,
"author": "Ian Oxley",
"author_id": 1904,
"author_profile": "https://Stackoverflow.com/users/1904",
"pm_score": 3,
"selected": true,
"text": "if (view.Rows.Count > 0) {\n // swap each header <td> cell for a <th> cell\n foreach (DetailsViewRow row in view.Rows) {\n if (row.RowType == DataControlRowType.DataRow) {\n DataControlFieldCell td = row.Cells[0] as DataControlFieldCell;\n // skip the last row that contains our command controls\n if (td.Controls.Count > 0) {\n continue;\n }\n\n DataControlFieldHeaderCell th = new DataControlFieldHeaderCell(td.ContainingField);\n th.Text = td.Text;\n th.Attributes.Add(\"scope\", \"row\");\n\n // add the new th and remove the old td\n row.Cells.RemoveAt(0);\n row.Cells.AddAt(0, th);\n }\n }\n}\n"
},
{
"answer_id": 70415057,
"author": "Udi Azulay",
"author_id": 12590051,
"author_profile": "https://Stackoverflow.com/users/12590051",
"pm_score": 0,
"selected": false,
"text": "protected override void InitializeRow(DetailsViewRow row, DataControlField field)\n{\n if (row.RowType == DataControlRowType.DataRow && field.ShowHeader)\n {\n DataControlFieldCell cell = new DataControlFieldHeaderCell(field);\n field.InitializeCell(cell, DataControlCellType.Header, row.RowState, DataItemIndex);\n row.Cells.Add(cell);\n cell = new DataControlFieldCell(field);\n field.InitializeCell(cell, DataControlCellType.DataCell, row.RowState, DataItemIndex);\n row.Cells.Add(cell);\n }\n else base.InitializeRow(row, field);\n}\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/305464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1904/"
] |
305,487 | <p>Access can open DBF (dBase) files, but instead of physically converting the data into MDB format, it has the ability to link to the DBF table itself. This way the DBF is "linked" to the MDB.</p>
<p>Is it possible to attach a DBF file in such manner using C#?</p>
<p><strong>Edit</strong>: I would like to use Jet and avoid using MS Access directly.</p>
| [
{
"answer_id": 305596,
"author": "Fionnuala",
"author_id": 2548,
"author_profile": "https://Stackoverflow.com/users/2548",
"pm_score": 3,
"selected": true,
"text": "Public Function Import(dsnName As String, sourceTableName As String, targetTableName As String)\n‘ if the table already existsm, delete it.\n On Error GoTo CopyTable\n DoCmd.DeleteObject acTable, targetTableName\nCopyTable:\n DoCmd.TransferDatabase _\n acImport, _\n \"ODBC Database\", _\n \"ODBC;DSN=\" + dsnName, _\n acTable, _\n sourceTableName, _\n targetTableName\nEnd Function\n object accessObject = null;\ntry\n{\n accessObject = Activator.CreateInstance(Type.GetTypeFromProgID(\"Access.Application\"));\n\n accessObject.GetType().InvokeMember(\n \"OpenCurrentDatabase\",\n System.Reflection.BindingFlags.Default System.Reflection.BindingFlags.InvokeMethod,\n null,\n accessObject,\n new Object[] { \"AccessDbase.mdb\" });\n\n accessObject.GetType().InvokeMember(\n \"Run\",\n System.Reflection.BindingFlags.Default System.Reflection.BindingFlags.InvokeMethod,\n null,\n accessObject,\n new Object[] { \"Import\", \"DSN Name\", \"Source table name\", \"Target table name\" });\n\n accessObject.GetType().InvokeMember(\n \"CloseCurrentDatabase\",\n System.Reflection.BindingFlags.Default System.Reflection.BindingFlags.InvokeMethod,\n null,\n accessObject,\n null);\n\n MessageBox.Show(\"Copy succeeded.\");\n}\ncatch (Exception ex)\n{\n string message = ex.Message;\n while (ex.InnerException != null)\n {\n ex = ex.InnerException;\n message += \"\\r\\n----\\r\\n\" + ex.Message;\n }\n MessageBox.Show(message);\n}\nfinally\n{\n if (accessObject != null)\n {\n System.Runtime.InteropServices.Marshal.ReleaseComObject(accessObject);\n accessObject = null;\n }\n}\n strLinkFile = \"C:\\Docs\\Link.mdb\"\nstrAccessFile = \"C:\\Docs\\LTD.mdb\"\n\n'Create Link... '\nSet cn = CreateObject(\"ADODB.Connection\")\ncn.Open \"Provider=Microsoft.Jet.OLEDB.4.0;\" & _\n \"Data Source=\" & strAccessFile & \";\" & _\n \"Persist Security Info=False\"\n\nSet adoCat = CreateObject(\"ADOX.Catalog\")\nSet adoCat.ActiveConnection = cn\n\nSet adoTbl = CreateObject(\"ADOX.Table\")\n\nSet adoTbl.ParentCatalog = adoCat\nadoTbl.Name = \"LinkTable\"\n\nadoTbl.properties(\"Jet OLEDB:Link Datasource\") = strLinkFile\nadoTbl.properties(\"Jet OLEDB:Link Provider String\") = \"MS Access\"\nadoTbl.properties(\"Jet OLEDB:Remote Table Name\") = \"Table1\"\nadoTbl.properties(\"Jet OLEDB:Create Link\") = True\n\n'Append the table to the tables collection '\nadoCat.Tables.Append adoTbl\n"
},
{
"answer_id": 307879,
"author": "David-W-Fenton",
"author_id": 9787,
"author_profile": "https://Stackoverflow.com/users/9787",
"pm_score": 1,
"selected": false,
"text": "dBase IV;HDR=NO;IMEX=2;DATABASE=C:\\Path\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/305487",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21704/"
] |
305,491 | <p>I'm trying to convert some code that uses datasets to LINQ. Some of the code passes column names into other functions as strings.</p>
<p>Is there anyway I can easily rewrite this into LINQ?</p>
<pre><code>string s = getElement(tr, elementName);
private string getElement (tableRow re, string elementName){
if(tr[elementName] != null){
return tr[elementName].toString()
}
}
</code></pre>
<p>OR:</p>
<pre><code>private void copy (tableRow trFrom, tableRow trTo){
foreach (DataColumn c in trFrom.Table.Columns) {
trTo[c.ColumnName] = trFrom[c.ColumnName];
}
}
</code></pre>
<p>Answer to GVS:
The reason to convert to LINQ is because it in many situations are easier to code LINQ and get better performance. It's related to another question here on stackoverflow:
<a href="https://stackoverflow.com/questions/295291/programming-pattern-using-typed-datasets-in-vs-2008">programming pattern using typed datasets</a></p>
<p>The reason I need to use the column name as a string is mainly because the column names are passed as a ID for input fields, they are then sent back to the program using AJAX (jquery).</p>
| [
{
"answer_id": 793156,
"author": "devzero",
"author_id": 37083,
"author_profile": "https://Stackoverflow.com/users/37083",
"pm_score": 2,
"selected": true,
"text": "private string getElement (tableRow tr, string element){\n string val = \"\";\n try\n {\n val = tr.GetType().GetProperty(element).GetValue(tr, null).ToString();\n }\n catch //NULL value\n {\n val = \"\";\n }\n}\n foreach (PropertyInfo c in tr.GetType().GetProperties())\n{\n thr.GetType().GetProperty(c.Name).SetValue(thr,\n tr.GetType().GetProperty(c.Name).GetValue(tr, null), null);\n}\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/305491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37083/"
] |
305,495 | <blockquote>
<p>This question exists because it has
historical significance, but it is not
considered a good, on-topic question
for this site, so please do not use it
as evidence that you can ask similar
questions here.</p>
<p>More info: <a href="https://stackoverflow.com/faq">https://stackoverflow.com/faq</a></p>
</blockquote>
<p>Anyone knows if it's possible to find all A records, CNAME or subzone records configured for a domain name?</p>
<p>For example, domain.com:</p>
<pre><code>www IN CNAME domain.com.
subdomain1 IN CNAME domain.com.
subdomain2 IN CNAME domain.com.
subdomain1 IN A 123.4.56.78.
subdomain2 IN A 123.4.56.79.
</code></pre>
<p>I want to keep a sub-domain private where I'll run an admin application (it will be password protected and on a special port, but I would prefer to keep it as private as possible).</p>
| [
{
"answer_id": 305502,
"author": "csl",
"author_id": 21028,
"author_profile": "https://Stackoverflow.com/users/21028",
"pm_score": 2,
"selected": false,
"text": "host -a -l domain.com\n"
},
{
"answer_id": 321212,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 2,
"selected": false,
"text": "NSEC3 NSEC www IN CNAME domain.com.\nsubdomain1 IN CNAME domain.com.\nsubdomain2 IN CNAME domain.com. \nsubdomain1 IN A 123.4.56.78.\nsubdomain2 IN A 123.4.56.79.\n $ORIGIN domain.com\n@ IN SOA ...\n IN A 123.4.56.78\nwww IN A 123.4.56.78\nsub1 IN A 123.4.56.79\n sub1.domain.com"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/305495",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36544/"
] |
305,509 | <p>I wanted to pass <code>calendar1.Selecteddate</code> in a <code>query string</code> from <code>gridview</code> in one page to another <code>gridview</code> (I have written <code>sqlquery</code> in that <code>gridview</code>) in another page. As seen in the below code I tried passing it but this did not work. Can anyone tell me how to pass the selected date from <code>calendar</code> in <code>query string</code></p>
<pre><code> <asp:HyperLinkField DataNavigateUrlFields="LocalIP"
DataNavigateUrlFormatString="DailyResults.aspx?
Terms={0}&column=LocalIP&
startdate=Calendar1.SelectedDate.Date.Date.ToShortDateString()
DataTextField="LocalIP" HeaderText="User" />
</code></pre>
| [
{
"answer_id": 305622,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<asp:HyperLinkField DataNavigateUrlFormatString=\"<%=GetSelectedDate()%>....\n"
},
{
"answer_id": 305638,
"author": "HectorMac",
"author_id": 1400,
"author_profile": "https://Stackoverflow.com/users/1400",
"pm_score": 0,
"selected": false,
"text": "<asp:HyperLinkField DataNavigateUrlFields=\"LocalIP\" \n DataNavigateUrlFormatString='<%# \"DailyResults.aspx?Terms={0}&column=LocalIP&startdate=\" + Calendar1.SelectedDate.Date.Date.ToShortDateString() %> DataTextField=\"LocalIP\" HeaderText=\"User\" />\n"
},
{
"answer_id": 306420,
"author": "Zachary Yates",
"author_id": 8360,
"author_profile": "https://Stackoverflow.com/users/8360",
"pm_score": 1,
"selected": false,
"text": "protected override gv1_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n HyperLink hl = new Hyperlink();\n hl.NavigateUrl = string.Format(\"DailyResults.aspx?Terms={0}&column=LocalIP&startdate={1}\", localIp, Calendar1.SelectedDate.Date.Date.ToShortDateString());\n .. set other hyperlink fields ..\n e.Row.Cells[1].Controls.Add(hl);\n}\n"
}
] | 2008/11/20 | [
"https://Stackoverflow.com/questions/305509",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.