qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
283,951
<p>This may be a painfully simply question for which I will be mocked but I am having difficulty in using filepaths in master pages. I believe this is because if a page in a sub-directory to using the master page then the filepath is incorrect.</p> <p>To fix this I need to get the filepath from the root but I can't seem to get it working.</p> <p>I tried:</p> <pre><code>&lt;script type=&quot;text/javascript&quot; src=&quot;~/jQueryScripts/jquery.js&quot;&gt;&lt;/script&gt; </code></pre> <p>and</p> <pre><code>&lt;script type=&quot;text/javascript&quot; src=&quot;../jQueryScripts/jquery.js&quot;&gt;&lt;/script&gt; </code></pre> <p>No luck on either!</p> <p>Any ideas on how I can tell it to get the filepath from the root?</p>
[ { "answer_id": 283976, "author": "Powerlord", "author_id": 15880, "author_profile": "https://Stackoverflow.com/users/15880", "pm_score": 3, "selected": true, "text": "<script type=\"text/javascript\" src=\"/jQueryScripts/jquery.js\"></script>" }, { "answer_id": 284005, "author": "DOK", "author_id": 27637, "author_profile": "https://Stackoverflow.com/users/27637", "pm_score": 1, "selected": false, "text": "runat=server <head> MasterPage <head runat=\"server\">\n" }, { "answer_id": 284037, "author": "Jeff Sheldon", "author_id": 33910, "author_profile": "https://Stackoverflow.com/users/33910", "pm_score": 1, "selected": false, "text": " public void AddJavascript(string javascriptUrl)\n { \n HtmlGenericControl script = new HtmlGenericControl(\"script\");\n script.Attributes.Add(\"type\", \"text/javascript\");\n javascriptUrl += \"?v\" + Assembly.GetExecutingAssembly().GetName().Version;\n script.Attributes.Add(\"src\", ResolveUrl(javascriptUrl));\n Page.Header.Controls.Add(script);\n }\n" }, { "answer_id": 284070, "author": "kristian", "author_id": 20377, "author_profile": "https://Stackoverflow.com/users/20377", "pm_score": 1, "selected": false, "text": "<script type=\"text/javascript\" src=\"<%=Page.ResolveUrl(\"~/jQueryScripts/jquery.js\")%>\"></script>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283951", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35454/" ]
283,956
<p>If for example you follow the link:</p> <p><code>data:application/octet-stream;base64,SGVsbG8=</code></p> <p>The browser will prompt you to download a file consisting of the data held as base64 in the hyperlink itself. Is there any way of suggesting a default name in the markup? If not, is there a JavaScript solution?</p>
[ { "answer_id": 283982, "author": "Alnitak", "author_id": 6782, "author_profile": "https://Stackoverflow.com/users/6782", "pm_score": 5, "selected": false, "text": "<a> download <a>" }, { "answer_id": 6171309, "author": "ninjagecko", "author_id": 711085, "author_profile": "https://Stackoverflow.com/users/711085", "pm_score": 2, "selected": false, "text": "<a href=\"data:...\">right-click me and select \"Save Link As...\" and save as \"example.txt\"</a>" }, { "answer_id": 6240528, "author": "sherpya", "author_id": 764426, "author_profile": "https://Stackoverflow.com/users/764426", "pm_score": 4, "selected": false, "text": "[b2e140]: DOCSHELL 6e5ae00 InternalLoad data:application/octet-stream;base64,SGVsbG8=\n[b2e140]: Found extension '' (filename is '', handling attachment: 0)\n[b2e140]: HelperAppService::DoContent: mime 'application/octet-stream', extension ''\n[b2e140]: Getting mimeinfo from type 'application/octet-stream' ext ''\n[b2e140]: Extension lookup on '' found: 0x0\n[b2e140]: Ext. lookup for '' found 0x0\n[b2e140]: OS gave back 0x43609a0 - found: 0\n[b2e140]: Searched extras (by type), rv 0x80004005\n[b2e140]: MIME Info Summary: Type 'application/octet-stream', Primary Ext ''\n[b2e140]: Type/Ext lookup found 0x43609a0\n data uri handler: netwerk/protocol/data/nsDataHandler.cpp\nwhere mozilla decides the filename: uriloader/exthandler/nsExternalHelperAppService.cpp\nInternalLoad string in the log: docshell/base/nsDocShell.cpp\n download" }, { "answer_id": 6943481, "author": "Dan Fabulich", "author_id": 54829, "author_profile": "https://Stackoverflow.com/users/54829", "pm_score": 8, "selected": false, "text": "download <a download='FileName' href='your_url'>\n download" }, { "answer_id": 12409154, "author": "cuixiping", "author_id": 988089, "author_profile": "https://Stackoverflow.com/users/988089", "pm_score": 3, "selected": false, "text": "<a download=\"abcd.cer\"\n href=\"data:application/stream;base64,MIIDhTC......\">down</a>\n" }, { "answer_id": 15832569, "author": "owencm", "author_id": 842506, "author_profile": "https://Stackoverflow.com/users/842506", "pm_score": 4, "selected": false, "text": "function downloadWithName(uri, name) {\n var link = document.createElement(\"a\");\n link.download = name;\n link.href = uri;\n link.click();\n}\n downloadWithName(\"data:,Hello%2C%20World!\", \"helloWorld.txt\")\n" }, { "answer_id": 16523173, "author": "Holf", "author_id": 169334, "author_profile": "https://Stackoverflow.com/users/169334", "pm_score": 6, "selected": false, "text": "function saveContent(fileContents, fileName)\n{\n var link = document.createElement('a');\n link.download = fileName;\n link.href = 'data:,' + fileContents;\n link.click();\n}\n" }, { "answer_id": 21915171, "author": "kgividen", "author_id": 1402620, "author_profile": "https://Stackoverflow.com/users/1402620", "pm_score": 2, "selected": false, "text": "var exportFileName = \"export-\" + filename;\n$('<a></a>', {\n \"download\": exportFileName,\n \"href\": \"data:,\" + JSON.stringify(exportData, null,5),\n \"id\": \"exportDataID\"\n}).appendTo(\"body\")[0].click().remove();\n" }, { "answer_id": 25715985, "author": "fregante", "author_id": 288906, "author_profile": "https://Stackoverflow.com/users/288906", "pm_score": 6, "selected": false, "text": "download <a download=\"logo.gif\" href=\"data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7\">Download transparent png</a> function saveAs(uri, filename) {\n var link = document.createElement('a');\n if (typeof link.download === 'string') {\n link.href = uri;\n link.download = filename;\n\n //Firefox requires the link to be in the body\n document.body.appendChild(link);\n \n //simulate click\n link.click();\n\n //remove the link when done\n document.body.removeChild(link);\n } else {\n window.open(uri);\n }\n}\n\nvar file = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'\nsaveAs(file, 'logo.gif'); download" }, { "answer_id": 28124736, "author": "Adria", "author_id": 1090770, "author_profile": "https://Stackoverflow.com/users/1090770", "pm_score": 3, "selected": false, "text": "<a href, <img src // In the service worker\nself.addEventListener( 'fetch', function(e)\n{\n if( e.request.url.startsWith( '/blobUri/' ) )\n {\n // Logic to select correct dataUri, and return it as a Response\n e.respondWith( dataURLAsRequest );\n }\n});\n" }, { "answer_id": 33917332, "author": "Sushama Pradhan", "author_id": 5143142, "author_profile": "https://Stackoverflow.com/users/5143142", "pm_score": -1, "selected": false, "text": "var isIE = /*@cc_on!@*/false || !!document.documentMode; // At least IE6\nvar sessionId ='\\n';\nvar token = '\\n';\nvar caseId = CaseIDNumber + '\\n';\nvar url = casewebUrl+'\\n';\nvar uri = sessionId + token + caseId + url;//data in file\nvar fileName = \"file.i4cvf\";// any file name with any extension\nif (isIE)\n {\n var fileData = ['\\ufeff' + uri];\n var blobObject = new Blob(fileData);\n window.navigator.msSaveOrOpenBlob(blobObject, fileName);\n }\n else //chrome\n {\n window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;\n window.requestFileSystem(window.TEMPORARY, 1024 * 1024, function (fs) {\n fs.root.getFile(fileName, { create: true }, function (fileEntry) { \n fileEntry.createWriter(function (fileWriter) {\n var fileData = ['\\ufeff' + uri];\n var blob = new Blob(fileData);\n fileWriter.addEventListener(\"writeend\", function () {\n var fileUrl = fileEntry.toURL();\n var link = document.createElement('a');\n link.href = fileUrl;\n link.download = fileName;\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n }, false);\n fileWriter.write(blob);\n }, function () { });\n }, function () { });\n }, function () { });\n }\n" }, { "answer_id": 34569480, "author": "NeutronenStern", "author_id": 5381025, "author_profile": "https://Stackoverflow.com/users/5381025", "pm_score": 2, "selected": false, "text": "function download() {\n var msg=\"Hello world!\";\n var blob = new File([msg], \"hello.bin\", {\"type\": \"application/octet-stream\"});\n\n var a = document.createElement(\"a\");\n a.href = URL.createObjectURL(blob);\n\n window.location.href=a;\n}\n <html lang=\"en\" xmlns=\"http://www.w3.org/1999/xhtml\">\n\n<head>\n <meta charset=\"utf-8\"/>\n <title>Test</title>\n <script type=\"text/javascript\" src=\"dl.js\"></script>\n</head>\n\n<body>\n<button id=\"create\" type=\"button\" onclick=\"download();\">Download</button>\n</body>\n</html>\n" }, { "answer_id": 40819952, "author": "Chad Scira", "author_id": 103696, "author_profile": "https://Stackoverflow.com/users/103696", "pm_score": -1, "selected": false, "text": "data:text/html;base64,PGEgaHJlZj0iZGF0YTp0ZXh0L2h0bWw7YmFzZTY0LFBHRWdhSEpsWmowaVVGVlVYMFJCVkVGZlZWSkpYMGhGVWtVaUlHUnZkMjVzYjJGa1BTSjBaWE4wTG1oMGJXd2lQZ284YzJOeWFYQjBQZ3BrYjJOMWJXVnVkQzV4ZFdWeWVWTmxiR1ZqZEc5eUtDZGhKeWt1WTJ4cFkyc29LVHNLUEM5elkzSnBjSFErIiBkb3dubG9hZD0idGVzdC5odG1sIj4KPHNjcmlwdD4KZG9jdW1lbnQucXVlcnlTZWxlY3RvcignYScpLmNsaWNrKCk7Cjwvc2NyaXB0Pg==\n" }, { "answer_id": 66157662, "author": "Micha", "author_id": 15191770, "author_profile": "https://Stackoverflow.com/users/15191770", "pm_score": 0, "selected": false, "text": "<a href=.. download=.. > <img src=.. download=.. > <a href=.. download=..><img src=..></a>" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283956", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
283,961
<p>I have a problem when I try to center the div block "products" because I don't know in advance the div width. Anybody have a solution?</p> <p>Update: The problem I have is I don't know how many products I'll display, I can have 1, 2 or 3 products, I can center them if it was a fixed number as I'd know the width of the parent div, I just don't know how to do it when the content is dynamic.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.product_container { text-align: center; height: 150px; } .products { height: 140px; text-align: center; margin: 0 auto; clear: ccc both; } .price { margin: 6px 2px; width: 137px; color: #666; font-size: 14pt; font-style: normal; border: 1px solid #CCC; background-color: #EFEFEF; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="product_container"&gt; &lt;div class="products" id="products"&gt; &lt;div id="product_15"&gt; &lt;img src="/images/ecommerce/card_default.png"&gt; &lt;div class="price"&gt;R$ 0,01&lt;/div&gt; &lt;/div&gt; &lt;div id="product_15"&gt; &lt;img src="/images/ecommerce/card_default.png"&gt; &lt;div class="price"&gt;R$ 0,01&lt;/div&gt; &lt;/div&gt; &lt;div id="product_15"&gt; &lt;img src="/images/ecommerce/card_default.png"&gt; &lt;div class="price"&gt;R$ 0,01&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 283974, "author": "Arief", "author_id": 34096, "author_profile": "https://Stackoverflow.com/users/34096", "pm_score": -1, "selected": false, "text": " margin: 0px auto;\n padding: 0px;\n border:0;\n width: 700px;\n" }, { "answer_id": 283985, "author": "Adam Bellaire", "author_id": 21632, "author_profile": "https://Stackoverflow.com/users/21632", "pm_score": 2, "selected": false, "text": "div width auto margin div display: inline span div" }, { "answer_id": 284064, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 7, "selected": false, "text": ".center{\n text-align:center; \n}\n\n.center > div{ /* N.B. child combinators don't work in IE6 or less */\n display:inline-block;\n}\n" }, { "answer_id": 2522640, "author": "Lionel", "author_id": 302448, "author_profile": "https://Stackoverflow.com/users/302448", "pm_score": 0, "selected": false, "text": "#mainContent {\n position:absolute;\n width:600px;\n background:#FFFF99;\n}\n\n#sidebar {\n float:left;\n margin-left:610px;\n max-width:300;\n background:#FFCCCC;\n}\n#sidebar{\n\n\n text-align:center;\n}\n <center>\n<table border=\"0\" cellspacing=\"0\">\n <tr>\n <td>\n<div id=\"mainContent\">\n1<br/>\n<br/>\n123<br/>\n123<br/>\n123<br/>\n</div><div id=\"sidebar\"><br/>\n</div></td>\n</tr>\n</table>\n</center>\n" }, { "answer_id": 6353345, "author": "Mike M. Lin", "author_id": 266536, "author_profile": "https://Stackoverflow.com/users/266536", "pm_score": 8, "selected": false, "text": ".child { /* This is the item to center... */\n display: inline-block;\n}\n.parent { /* ...and this is its parent container. */\n text-align: center;\n}\n <div class=\"product_container\">\n <div class=\"outer-center\">\n <div class=\"product inner-center\">\n </div>\n </div>\n <div class=\"clear\"/>\n</div>\n .outer-center {\n float: right;\n right: 50%;\n position: relative;\n}\n.inner-center {\n float: right;\n right: -50%;\n position: relative;\n}\n.clear {\n clear: both;\n}\n" }, { "answer_id": 6544658, "author": "JavierIEH", "author_id": 232588, "author_profile": "https://Stackoverflow.com/users/232588", "pm_score": 4, "selected": false, "text": "div.outer{\n display:inline-block;\n position:relative;\n left:50%;\n}\n\ndiv.inner{\n position:relative;\n left:-50%;\n}\n" }, { "answer_id": 8319494, "author": "Alexander Pogrebnyak", "author_id": 185722, "author_profile": "https://Stackoverflow.com/users/185722", "pm_score": 1, "selected": false, "text": "overflow: auto; hidden div.product_container div.clear <div class=\"product_container\">\n <div class=\"outer-center\">\n <div class=\"product inner-center\">\n </div>\n </div>\n</div>\n .product_container {\n overflow: auto;\n /* width property only required if you want to support IE6 */\n width: 100%;\n}\n\n.outer-center {\n float: right;\n right: 50%;\n position: relative;\n}\n\n.inner-center {\n float: right;\n right: -50%;\n position: relative;\n}\n div.clear <div class=\"product_container\">\n <div class=\"outer-center\">\n <div class=\"product inner-center\">\n </div>\n </div>\n <div style=\"clear: both;\"></div>\n</div>\n<p style=\"margin-top: 11px;\">Some text</p>\n 11px product_container" }, { "answer_id": 10647574, "author": "Shinov T", "author_id": 1402636, "author_profile": "https://Stackoverflow.com/users/1402636", "pm_score": 1, "selected": false, "text": "<div class=\"product_container\">\n<div class=\"products\" id=\"products\">\n <div id=\"product_15\" class=\"products_box\">\n <img src=\"/images/ecommerce/card_default.png\">\n <div class=\"price\">R$ 0,01</div>\n </div>\n <div id=\"product_15\" class=\"products_box\">\n <img src=\"/images/ecommerce/card_default.png\">\n <div class=\"price\">R$ 0,01</div>\n </div> \n <div id=\"product_15\" class=\"products_box\">\n <img src=\"/images/ecommerce/card_default.png\">\n <div class=\"price\">R$ 0,01</div>\n </div>\n</div>\n <pre>\n.product_container \n {\n text-align: center;\n height: 150px;\n }\n\n.products {\n left: 50%;\nheight:35px;\nfloat:left;\nposition: relative;\nmargin: 0 auto;\nwidth:auto;\n}\n.products .products_box\n{\nwidth:auto;\nheight:auto;\nfloat:left;\n right: 50%;\n position: relative;\n}\n.price {\n margin: 6px 2px;\n width: 137px;\n color: #666;\n font-size: 14pt;\n font-style: normal;\n border: 1px solid #CCC;\n background-color: #EFEFEF;\n}\n" }, { "answer_id": 11791282, "author": "Craigo", "author_id": 418057, "author_profile": "https://Stackoverflow.com/users/418057", "pm_score": 0, "selected": false, "text": "<div style=\"width:100%;height:40px;position:absolute;top:50%;margin-top:-20px;\">\n <table style=\"width:100%\"><tr><td align=\"center\">\n In the middle\n </td></tr></table>\n</div>\n" }, { "answer_id": 11899243, "author": "johndoe", "author_id": 1574023, "author_profile": "https://Stackoverflow.com/users/1574023", "pm_score": 1, "selected": false, "text": "<div class=\"product_container\">\n<div class=\"outer-center\">\n<div class=\"product inner-center\">\n </div>\n</div>\n<div class=\"clear\"></div>\n</div>\n\n.outer-center\n{\nfloat: right;\nright: 50%;\nposition: relative;\n}\n.inner-center \n{\nfloat: right;\nright: -50%;\nposition: relative;\n}\n.clear \n{\nclear: both;\n}\n\n.product_container\n{\noverflow:hidden;\n}\n" }, { "answer_id": 13413240, "author": "Greg Benner", "author_id": 1151520, "author_profile": "https://Stackoverflow.com/users/1151520", "pm_score": 2, "selected": false, "text": " .outerElement {\n display: -moz-inline-stack;\n display: inline-block;\n vertical-align: middle;\n zoom: 1;\n position: relative;\n left: 50%;\n }\n\n.innerElement {\n position: relative;\n left: -50%;\n} \n" }, { "answer_id": 16132736, "author": "somebody", "author_id": 2304644, "author_profile": "https://Stackoverflow.com/users/2304644", "pm_score": 0, "selected": false, "text": "<style type=\"text/css\">\n.container_box{\n text-align:center\n}\n.content{\n padding:10px;\n background:#ff0000;\n color:#ffffff;\n <div class=\"container_box\">\n <span class=\"content\">Hello</span>\n</div>\n" }, { "answer_id": 16928805, "author": "Nikola", "author_id": 585786, "author_profile": "https://Stackoverflow.com/users/585786", "pm_score": 1, "selected": false, "text": "#parent{\n width:600px;\n height:400px;\n background:#ffcc00;\n text-align:center;\n }\n\n#child{\n display:inline-block;\n margin:0 auto;\n background:#fff;\n } \n <div id=\"parent\">\n <div id=\"child\">voila</div>\n</div>\n" }, { "answer_id": 21320716, "author": "Maxime Rossini", "author_id": 547733, "author_profile": "https://Stackoverflow.com/users/547733", "pm_score": 7, "selected": false, "text": "display: table; text-align: center; <div class=\"container\">\n <div class=\"centered\">This content is centered</div>\n</div>\n .centered { display: table; margin: 0 auto; }\n .container {\n background-color: green;\n}\n.centered {\n display: table;\n margin: 0 auto;\n background-color: red;\n} <div class=\"container\">\n <div class=\"centered\">This content is centered</div>\n</div> <div class=\"container\">\n <div class=\"centered\">This content is centered</div>\n</div>\n .container {\n display: flex;\n flex-direction: column; /* put this if you want to stack elements vertically */\n}\n.centered { margin: 0 auto; }\n .container {\n display: flex;\n flex-direction: column; /* put this if you want to stack elements vertically */\n background-color: green;\n}\n.centered {\n margin: 0 auto;\n background-color: red;\n} <div class=\"container\">\n <div class=\"centered\">This content is centered</div>\n</div>" }, { "answer_id": 25047040, "author": "Wray Bowling", "author_id": 1281267, "author_profile": "https://Stackoverflow.com/users/1281267", "pm_score": 0, "selected": false, "text": "<style>\n.products{\n text-align:center;\n}\n\n.product{\n display:inline-block;\n text-align:left;\n\n background-image: url('http://www.color.co.uk/wp-content/uploads/2013/11/New_Product.jpg');\n background-size:25px;\n padding-left:25px;\n background-position:0 50%;\n background-repeat:no-repeat;\n}\n\n.price {\n margin: 6px 2px;\n width: 137px;\n color: #666;\n font-size: 14pt;\n font-style: normal;\n border: 1px solid #CCC;\n background-color: #EFEFEF;\n}\n</style>\n\n\n<div class=\"products\">\n <div class=\"product\">\n <div class=\"price\">R$ 0,01</div>\n </div>\n <div class=\"product\">\n <div class=\"price\">R$ 0,01</div>\n </div>\n <div class=\"product\">\n <div class=\"price\">R$ 0,01</div>\n </div>\n <div class=\"product\">\n <div class=\"price\">R$ 0,01</div>\n </div>\n <div class=\"product\">\n <div class=\"price\">R$ 0,01</div>\n </div>\n <div class=\"product\">\n <div class=\"price\">R$ 0,01</div>\n </div>\n</div>\n" }, { "answer_id": 26650821, "author": "hahaha", "author_id": 3522714, "author_profile": "https://Stackoverflow.com/users/3522714", "pm_score": 1, "selected": false, "text": "display:table; margin auto .relatedProducts {\n display: table;\n margin-left: auto;\n margin-right: auto;\n}\n .relatedProducts {\n display: table;\n margin-left: auto;\n margin-right: auto;\n}\na {\n text-decoration:none;\n} <div class=\"row relatedProducts\">\n<div class=\"homeContentTitle\" style=\"margin: 100px auto 35px; width: 250px\">Similar Products</div>\n \n<a href=\"#\">test1 </a>\n<a href=\"#\">test2 </a>\n<a href=\"#\">test3 </a>\n</div>" }, { "answer_id": 32085351, "author": "West1", "author_id": 3919052, "author_profile": "https://Stackoverflow.com/users/3919052", "pm_score": 3, "selected": false, "text": "<div class=\"outer\">\n <div class=\"target\">\n <div class=\"filler\">\n </div>\n </div>\n</div>\n\n.outer{\n width:100%;\n height: 100px;\n}\n\n.target{\n position: absolute;\n width: auto;\n height: 100px;\n left: 50%;\n transform: translateX(-50%);\n}\n\n.filler{\n position:relative;\n width:150px;\n height:20px;\n}\n left: 50% transform:translateX(-50%) width:auto" }, { "answer_id": 33843063, "author": "zloctb", "author_id": 1673376, "author_profile": "https://Stackoverflow.com/users/1673376", "pm_score": 2, "selected": false, "text": " <div class=\"row\">\n <div class=\"col\" style=\"background:red;\">content1</div>\n <div class=\"col\" style=\"\">content2</div>\n </div>\n\n\n.row {\n display: flex; /* equal height of the children */\n height:100px;\n border:1px solid red;\n width: 400px;\n justify-content:center;\n}\n" }, { "answer_id": 44135688, "author": "Frank N", "author_id": 444255, "author_profile": "https://Stackoverflow.com/users/444255", "pm_score": 5, "selected": false, "text": "display: block float display: flex display: inline-block text-align: center .wrapTwo\n text-align: center;\n.two\n display: inline-block; // instantly shrinks width\n position: relative;\ndisplay: inline-block; // instantly shrinks width\nleft: 50%;\ntransform: translateX(-50%);\n .four\n position absolute\n top 0\n left 50%\n transform translateX(-50%)\n.wrapFour\n position relative // otherwise, absolute positioning will be relative to page!\n height 50px // ensure height\n background lightgreen // just a marker\n .wrapFive\n &:after // aka 'clearfix'\n content ''\n display table\n clear both\n\n.five \n float left\n position relative\n left 50%\n transform translateX(-50%)\n .wrapSix\n display: flex\n justify-content: center\n" }, { "answer_id": 45145288, "author": "Byron", "author_id": 5311089, "author_profile": "https://Stackoverflow.com/users/5311089", "pm_score": -1, "selected": false, "text": ".parent {\n display: flex;\n flex-wrap: wrap;\n}\n\n.product {\n width: 240px;\n margin-left: auto;\n height: 127px;\n margin-right: auto;\n}\n" }, { "answer_id": 58773545, "author": "Shirley Ashby", "author_id": 4937353, "author_profile": "https://Stackoverflow.com/users/4937353", "pm_score": 0, "selected": false, "text": "#product_15{\n position: relative;\n margin: 0 auto;\n display: table;\n}\n.price, img{\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n}\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
283,965
<p>for a server based j2ee application, I need to retrieve the number of pages from word documents.. any ideas what works?</p>
[ { "answer_id": 34554452, "author": "Khalid Habib", "author_id": 1533783, "author_profile": "https://Stackoverflow.com/users/1533783", "pm_score": 0, "selected": false, "text": "Document doc = new Document(\"C:\\\\Temp\\\\file.doc\"); \n int pageCount = doc.getPageCount();\n" }, { "answer_id": 58136976, "author": "Sergiu", "author_id": 11769110, "author_profile": "https://Stackoverflow.com/users/11769110", "pm_score": 0, "selected": false, "text": " import com.aspose.cells.*;\n public int getPageCount(String filePath) throws Exception {\n Workbook book = new Workbook(filePath);\n ImageOrPrintOptions imageOrPrintOptions = new ImageOrPrintOptions();\n// Default 0 Prints all pages.\n// IgnoreBlank 1 Don't print the pages which the cells are blank.\n// IgnoreStyle 2 Don't print the pages which cells only contain styles.\n imageOrPrintOptions.setPrintingPage(PrintingPageType.IGNORE_STYLE);\n\n int pageCount = 0;\n for (int i = 0; i < book.getWorksheets().getCount(); i++) {\n Worksheet sheet = book.getWorksheets().get(i);\n\n PageSetup pageSetup = sheet.getPageSetup();\n\n pageSetup.setOrientation(PageOrientationType.PORTRAIT);\n\n pageSetup.setPaperSize(PaperSizeType.PAPER_LETTER);\n\n pageSetup.setTopMarginInch(1);\n pageSetup.setBottomMarginInch(1);\n pageSetup.setRightMarginInch(1);\n pageSetup.setLeftMarginInch(1);\n\n SheetRender sheetRender = new SheetRender(sheet, imageOrPrintOptions);\n\n int sheetPageCount = sheetRender.getPageCount();\n pageCount += sheetPageCount;\n }\n return pageCount;\n }\n import com.aspose.words.Document;\npublic int getPageCount(String filePath) throws Exception {\n Document document = new Document(filePath);\n return document.getPageCount();\n }\n import com.aspose.slides.*;\npublic int getPageCount(String filePath) throws Exception {\n Presentation presentation = new Presentation(filePath);\n return presentation.getSlides().toArray().length;\n }\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283965", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36906/" ]
283,977
<p>Does the C++ STL set data structure have a set difference operator?</p>
[ { "answer_id": 283989, "author": "Ian G", "author_id": 5764, "author_profile": "https://Stackoverflow.com/users/5764", "pm_score": 1, "selected": false, "text": "template <class InputIterator1, class InputIterator2, class OutputIterator>\nOutputIterator set_difference(InputIterator1 first1, InputIterator1 last1,\n InputIterator2 first2, InputIterator2 last2,\n OutputIterator result);\n" }, { "answer_id": 284004, "author": "PierreBdR", "author_id": 7136, "author_profile": "https://Stackoverflow.com/users/7136", "pm_score": 7, "selected": false, "text": "<algorithm> std::set_difference #include <algorithm>\n#include <set>\n#include <iterator>\n// ...\nstd::set<int> s1, s2;\n// Fill in s1 and s2 with values\nstd::set<int> result;\nstd::set_difference(s1.begin(), s1.end(), s2.begin(), s2.end(),\n std::inserter(result, result.end()));\n result s1-s2" }, { "answer_id": 1236413, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "#include <algorithms>\n #include <algorithm>\n std::insert_iterator(result, result.end()));\n std::insert_iterator<set<int> >(result, result.end()));\n" }, { "answer_id": 14148344, "author": "user1830108", "author_id": 1830108, "author_profile": "https://Stackoverflow.com/users/1830108", "pm_score": -1, "selected": false, "text": " set_difference(set1.begin(), set1.end(), set2.begin(). set2,end(),std::back_inserter(result)).\n" }, { "answer_id": 19168776, "author": "strickli", "author_id": 1612703, "author_profile": "https://Stackoverflow.com/users/1612703", "pm_score": 2, "selected": false, "text": "#include <string>\n#include <set>\n#include <boost/range/algorithm/set_algorithm.hpp>\n\nstd::set<std::string> set0, set1, setDifference;\nboost::set_difference(set0, set1, std::inserter(setDifference, setDifference.begin());\n" }, { "answer_id": 48995121, "author": "astraujums", "author_id": 841390, "author_profile": "https://Stackoverflow.com/users/841390", "pm_score": 2, "selected": false, "text": "template<class T>\nset<T> operator -(set<T> reference, set<T> items_to_remove)\n{\n set<T> result;\n std::set_difference(\n reference.begin(), reference.end(),\n items_to_remove.begin(), items_to_remove.end(),\n std::inserter(result, result.end()));\n return result;\n}\n" }, { "answer_id": 49281192, "author": "Ben", "author_id": 874660, "author_profile": "https://Stackoverflow.com/users/874660", "pm_score": 1, "selected": false, "text": "template <class Key, class Compare, class Allocator> \nstd::set<Key, Compare, Allocator> \nset_subtract(std::set<Key, Compare, Allocator>&& lhs,\n const std::set<Key, Compare, Allocator>& rhs) {\n if (lhs.empty()) { return lhs; }\n // First narrow down the overlapping range:\n const auto rhsbeg = rhs.lower_bound(*lhs.begin());\n const auto rhsend = rhs.upper_bound(*lhs.rbegin());\n for (auto i = rhsbeg; i != rhsend; ++i) {\n lhs.erase(*i);\n }\n return std::move(lhs);\n}\n Compare Compare std::function<bool(int,int)> lhs.size() lhs *i rhs.size() rhs lhs lhs = {0, 1000} rhs = {1, 2, ..., 999}" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283977", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28462/" ]
284,019
<p>What is the best way to convert a fixed length string array to a fixed lengh integer array in C++ ?</p>
[ { "answer_id": 284040, "author": "luke", "author_id": 16434, "author_profile": "https://Stackoverflow.com/users/16434", "pm_score": 3, "selected": false, "text": "#include <algorithm>\nchar foo[9] = \"asdfasdf\";\nint bar[9];\nstd::copy(foo, foo+9, bar);\n #include <algorithm>\n#include <sstream>\n#include <string>\n\ntemplate <class T>\nT parse(const std::string& str)\n{\n T temp;\n std::istringstream iss(str);\n iss >> temp;\n if(iss.bad() || iss.fail())\n {\n // handle conversion failure\n }\n return temp;\n}\n\n...\n\nstd::string foo[3];\nint bar[3];\nfoo[0] = \"67\";\nfoo[1] = \"11\";\nfoo[2] = \"42\";\n\nstd::transform(foo, foo+3, bar, parse<int>);\n" }, { "answer_id": 284087, "author": "jalf", "author_id": 33213, "author_profile": "https://Stackoverflow.com/users/33213", "pm_score": 3, "selected": false, "text": "#include <algorithm>\n\nstd::string foo[9];\nint bar[9];\n\nstd::transform(foo, foo+9, bar, MyMagicStringToIntFunction);\n" }, { "answer_id": 284102, "author": "Shadow2531", "author_id": 1697, "author_profile": "https://Stackoverflow.com/users/1697", "pm_score": 0, "selected": false, "text": "#include <iostream>\n#include <string>\n#include <vector>\n#include <iterator>\n#include <ostream>\n#include <algorithm>\n#include <sstream>\nusing namespace std;\n\nint int_from_string(const string& s) {\n istringstream ss(s);\n int i;\n ss >> i;\n return i;\n}\n\nvector<int> int_vec_from_string_vec(const vector<string>& vstr) {\n vector<int> v(vstr.size());\n transform(vstr.begin(), vstr.end(), v.begin(), int_from_string);\n return v;\n}\n\nint main() {\n const vector<string> vstr(3, \"45\");\n const vector<int> vint = int_vec_from_string_vec(vstr);\n copy(vint.begin(), vint.end(), ostream_iterator<int>(cout, \"\\n\"));\n}\n" }, { "answer_id": 284105, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 2, "selected": false, "text": "std::istringstream std::size_t const N = 3;\nstd::string a[N] = { \"10\", \"-2\", \"5\" };\nint b[N];\n\nfor(std::size_t i = 0; i < N; i++) {\n std::istringstream sstream(a[i]);\n sstream >> b[i];\n}\n std::stringstream sstream;\nfor(std::size_t i = 0; i < N; i++) {\n sstream << a[i];\n sstream >> b[i];\n sstream.clear(); \n sstream.seekp(0); sstream.seekg(0);\n}\n a b std::size_t const N = 15;\nchar a[N] = { \"this is a test\" };\nint b[N];\n\nfor(std::size_t i = 0; i < N; i++)\n b[i] = (int)(unsigned char) a[i];\n unsigned char" }, { "answer_id": 284156, "author": "Jonathan Adelson", "author_id": 8092, "author_profile": "https://Stackoverflow.com/users/8092", "pm_score": 0, "selected": false, "text": "char foo[10];\nint bar[10];\n\nfor(int i = 0; i < 10; ++i) {\n bar[i] = (int)foo[i];\n}\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
284,029
<p>I use SourceGear Vault and applyLabel="true" for a project so when it builds it will create a label in SourceGear Vault for the corresponding project.My questions are</p> <p>I have a nightly builds so what if i don't have any changes made to that project for that day then how do I define my settings....</p> <pre><code> &lt;sourcecontrol type="vault" autoGetSource="true" applyLabel="true"&gt; &lt;executable&gt;c:\program files\sourcegear\vault client\vault.exe&lt;/executable&gt; &lt;username&gt;john&lt;/username&gt; &lt;password&gt;password&lt;/password&gt; &lt;host&gt;server&lt;/host&gt; &lt;repository&gt;Default Repository&lt;/repository&gt; &lt;folder&gt;$/Projects/xxx/xxx/xxx/source/xxx/xxx/xxx/xx.source&lt;/folder&gt; &lt;ssl&gt;false&lt;/ssl&gt; &lt;timeout units="minutes"&gt;10&lt;/timeout&gt; **&lt;useWorkingDirectory&gt;false&lt;/useWorkingDirectory&gt;** &lt;workingDirectory&gt;C:\CCNET\build\xx\xx\&lt;/workingDirectory&gt; &lt;/sourcecontrol&gt; </code></pre> <p>The thing is that I don't want labels for build where there are no changes to code. </p> <p>Any help is appreciated.</p>
[ { "answer_id": 284068, "author": "Scott Dorman", "author_id": 1559, "author_profile": "https://Stackoverflow.com/users/1559", "pm_score": 2, "selected": false, "text": "<triggers> <triggers>\n <scheduleTrigger time=\"00:30\" buildCondition=\"IfModificationExists\"/>\n </triggers>\n buildCondition=\"IfModificationExists\"" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284029", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
284,038
<p>I am currently modifying some jsf application. I have two beans.</p> <ul> <li>connectionBean</li> <li>UIBean</li> </ul> <p>When I set my connection parameters in connectionBean the first time, the UIBean is able to read my connectionBean information and display the correct UI Tree.</p> <p>However when I try to set the connection parameters in the same session. My UIBean will still use the previous connectionBean information.</p> <p>It only will use after I invalidate the whole httpSession.</p> <p>Is there anyway I can make one session bean update another session bean?</p>
[ { "answer_id": 286577, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "protected Object getBackingBean( String name )\n{\n FacesContext context = FacesContext.getCurrentInstance();\n\n return context\n .getApplication().createValueBinding( String.format( \"#{%s}\", name ) ).getValue( context );\n}\n" }, { "answer_id": 934097, "author": "Martlark", "author_id": 72668, "author_profile": "https://Stackoverflow.com/users/72668", "pm_score": 1, "selected": false, "text": "protected Object getBackingBean( String name )\n{\n FacesContext context = FacesContext.getCurrentInstance();\n\n Application app = context.getApplication();\n\n ValueExpression expression = app.getExpressionFactory().createValueExpression(context.getELContext(),\n String.format(\"#{%s}\", name), Object.class);\n\n return expression.getValue(context.getELContext());\n}\n" }, { "answer_id": 9295181, "author": "Ondrej Bozek", "author_id": 668417, "author_profile": "https://Stackoverflow.com/users/668417", "pm_score": 0, "selected": false, "text": "public class FirstBean {\n\npublic static final String MANAGED_BEAN_NAME=\"firstBean\";\n\n/**\n * @return current managed bean instance\n */\npublic static FirstBean getCurrentInstance()\n{\n FacesContext context = FacesContext.getCurrentInstance();\n return (FirstBean) context.getApplication().evaluateExpressionGet(context, \"#{\" + FirstBean.MANAGED_BEAN_NAME + \"}\", TreeBean.class);\n} \n...\n ... \nFirstBean firstBean = FirstBean.getCurrentInstance(); \n...\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
284,043
<p>If I'm writing unit tests in Python (using the unittest module), is it possible to output data from a failed test, so I can examine it to help deduce what caused the error?</p> <p>I am aware of the ability to create a customized message, which can carry some information, but sometimes you might deal with more complex data, that can't easily be represented as a string.</p> <p>For example, suppose you had a class Foo, and were testing a method bar, using data from a list called testdata:</p> <pre><code>class TestBar(unittest.TestCase): def runTest(self): for t1, t2 in testdata: f = Foo(t1) self.assertEqual(f.bar(t2), 2) </code></pre> <p>If the test failed, I might want to output t1, t2 and/or f, to see why this particular data resulted in a failure. By output, I mean that the variables can be accessed like any other variables, after the test has been run.</p>
[ { "answer_id": 284110, "author": "Ned Batchelder", "author_id": 14343, "author_profile": "https://Stackoverflow.com/users/14343", "pm_score": 5, "selected": false, "text": "-s --nocapture" }, { "answer_id": 284192, "author": "monkut", "author_id": 24718, "author_profile": "https://Stackoverflow.com/users/24718", "pm_score": 4, "selected": false, "text": ">>> import random\n>>> import unittest\n>>>\n>>> class TestSequenceFunctions(unittest.TestCase):\n... def setUp(self):\n... self.seq = range(5)\n... def testshuffle(self):\n... # make sure the shuffled sequence does not lose any elements\n... random.shuffle(self.seq)\n... self.seq.sort()\n... self.assertEqual(self.seq, range(10))\n... def testchoice(self):\n... element = random.choice(self.seq)\n... error_test = 1/0\n... self.assert_(element in self.seq)\n... def testsample(self):\n... self.assertRaises(ValueError, random.sample, self.seq, 20)\n... for element in random.sample(self.seq, 5):\n... self.assert_(element in self.seq)\n...\n>>> suite = unittest.TestLoader().loadTestsFromTestCase(TestSequenceFunctions)\n>>> testResult = unittest.TextTestRunner(verbosity=2).run(suite)\ntestchoice (__main__.TestSequenceFunctions) ... ERROR\ntestsample (__main__.TestSequenceFunctions) ... ok\ntestshuffle (__main__.TestSequenceFunctions) ... FAIL\n\n======================================================================\nERROR: testchoice (__main__.TestSequenceFunctions)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"<stdin>\", line 11, in testchoice\nZeroDivisionError: integer division or modulo by zero\n\n======================================================================\nFAIL: testshuffle (__main__.TestSequenceFunctions)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"<stdin>\", line 8, in testshuffle\nAssertionError: [0, 1, 2, 3, 4] != [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n\n----------------------------------------------------------------------\nRan 3 tests in 0.031s\n\nFAILED (failures=1, errors=1)\n>>>\n>>> testResult.errors\n[(<__main__.TestSequenceFunctions testMethod=testchoice>, 'Traceback (most recent call last):\\n File \"<stdin>\"\n, line 11, in testchoice\\nZeroDivisionError: integer division or modulo by zero\\n')]\n>>>\n>>> testResult.failures\n[(<__main__.TestSequenceFunctions testMethod=testshuffle>, 'Traceback (most recent call last):\\n File \"<stdin>\n\", line 8, in testshuffle\\nAssertionError: [0, 1, 2, 3, 4] != [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\\n')]\n>>>\n" }, { "answer_id": 284326, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 6, "selected": false, "text": "import logging\nclass SomeTest( unittest.TestCase ):\n def testSomething( self ):\n log= logging.getLogger( \"SomeTest.testSomething\" )\n log.debug( \"this= %r\", self.this )\n log.debug( \"that= %r\", self.that )\n self.assertEqual( 3.14, pi )\n\nif __name__ == \"__main__\":\n logging.basicConfig( stream=sys.stderr )\n logging.getLogger( \"SomeTest.testSomething\" ).setLevel( logging.DEBUG )\n unittest.main()\n" }, { "answer_id": 284706, "author": "Silverfish", "author_id": 27415, "author_profile": "https://Stackoverflow.com/users/27415", "pm_score": 2, "selected": false, "text": "log1 = dict()\nclass TestBar(unittest.TestCase):\n def runTest(self):\n for t1, t2 in testdata:\n f = Foo(t1)\n if f.bar(t2) != 2:\n log1(\"TestBar.runTest\") = (f, t1, t2)\n self.fail(\"f.bar(t2) != 2\")\n" }, { "answer_id": 288568, "author": "orip", "author_id": 37020, "author_profile": "https://Stackoverflow.com/users/37020", "pm_score": 3, "selected": false, "text": "C:\\work> testoob tests.py --debug\nF\nDebugging for failure in test: test_foo (tests.MyTests.test_foo)\n> c:\\python25\\lib\\unittest.py(334)failUnlessEqual()\n-> (msg or '%r != %r' % (first, second))\n(Pdb) up\n> c:\\work\\tests.py(6)test_foo()\n-> self.assertEqual(x, y)\n(Pdb) l\n 1 from unittest import TestCase\n 2 class MyTests(TestCase):\n 3 def test_foo(self):\n 4 x = 1\n 5 y = 2\n 6 -> self.assertEqual(x, y)\n[EOF]\n(Pdb)\n" }, { "answer_id": 13688397, "author": "Facundo Casco", "author_id": 181337, "author_profile": "https://Stackoverflow.com/users/181337", "pm_score": 6, "selected": false, "text": "msg self.assertEqual(f.bar(t2), 2, msg='{0}, {1}'.format(t1, t2))\n" }, { "answer_id": 18791576, "author": "Max Murphy", "author_id": 2480661, "author_profile": "https://Stackoverflow.com/users/2480661", "pm_score": 1, "selected": false, "text": "import random\nimport unittest\nimport inspect\n\n\ndef store_result(f):\n \"\"\"\n Store the results of a test\n On success, store the return value.\n On failure, store the local variables where the exception was thrown.\n \"\"\"\n def wrapped(self):\n if 'results' not in self.__dict__:\n self.results = {}\n # If a test throws an exception, store local variables in results:\n try:\n result = f(self)\n except Exception as e:\n self.results[f.__name__] = {'success':False, 'locals':inspect.trace()[-1][0].f_locals}\n raise e\n self.results[f.__name__] = {'success':True, 'result':result}\n return result\n return wrapped\n\ndef suite_results(suite):\n \"\"\"\n Get all the results from a test suite\n \"\"\"\n ans = {}\n for test in suite:\n if 'results' in test.__dict__:\n ans.update(test.results)\n return ans\n\n# Example:\nclass TestSequenceFunctions(unittest.TestCase):\n\n def setUp(self):\n self.seq = range(10)\n\n @store_result\n def test_shuffle(self):\n # make sure the shuffled sequence does not lose any elements\n random.shuffle(self.seq)\n self.seq.sort()\n self.assertEqual(self.seq, range(10))\n # should raise an exception for an immutable sequence\n self.assertRaises(TypeError, random.shuffle, (1,2,3))\n return {1:2}\n\n @store_result\n def test_choice(self):\n element = random.choice(self.seq)\n self.assertTrue(element in self.seq)\n return {7:2}\n\n @store_result\n def test_sample(self):\n x = 799\n with self.assertRaises(ValueError):\n random.sample(self.seq, 20)\n for element in random.sample(self.seq, 5):\n self.assertTrue(element in self.seq)\n return {1:99999}\n\n\nsuite = unittest.TestLoader().loadTestsFromTestCase(TestSequenceFunctions)\nunittest.TextTestRunner(verbosity=2).run(suite)\n\nfrom pprint import pprint\npprint(suite_results(suite))\n {'test_choice': {'result': {7: 2}, 'success': True},\n 'test_sample': {'locals': {'self': <__main__.TestSequenceFunctions testMethod=test_sample>,\n 'x': 799},\n 'success': False},\n 'test_shuffle': {'result': {1: 2}, 'success': True}}\n" }, { "answer_id": 19538362, "author": "georgepsarakis", "author_id": 920374, "author_profile": "https://Stackoverflow.com/users/920374", "pm_score": -1, "selected": false, "text": "class MyTest(unittest.TestCase):\n def messenger(self, message):\n try:\n self.assertEqual(1, 2, msg=message)\n except AssertionError as e: \n print \"\\nMESSENGER OUTPUT: %s\" % str(e),\n" }, { "answer_id": 22187982, "author": "Orane", "author_id": 3305148, "author_profile": "https://Stackoverflow.com/users/3305148", "pm_score": 3, "selected": false, "text": "import logging\n\nclass TestBar(unittest.TestCase):\n def runTest(self):\n\n #this line is important\n logging.basicConfig()\n log = logging.getLogger(\"LOG\")\n\n for t1, t2 in testdata:\n f = Foo(t1)\n self.assertEqual(f.bar(t2), 2)\n log.warning(t1)\n" }, { "answer_id": 28546167, "author": "not-a-user", "author_id": 2965738, "author_profile": "https://Stackoverflow.com/users/2965738", "pm_score": 2, "selected": false, "text": "import unittest\nimport logging\nimport inspect\nimport os\n\nlogging_level = logging.INFO\n\ntry:\n log_file = os.environ[\"LOG_FILE\"]\nexcept KeyError:\n log_file = None\n\ndef logger(stack=None):\n if not hasattr(logger, \"initialized\"):\n logging.basicConfig(filename=log_file, level=logging_level)\n logger.initialized = True\n if not stack:\n stack = inspect.stack()\n name = stack[1][3]\n try:\n name = stack[1][0].f_locals[\"self\"].__class__.__name__ + \".\" + name\n except KeyError:\n pass\n return logging.getLogger(name)\n\ndef todo(msg):\n logger(inspect.stack()).warning(\"TODO: {}\".format(msg))\n\ndef get_pi():\n logger().info(\"sorry, I know only three digits\")\n return 3.14\n\nclass Test(unittest.TestCase):\n\n def testName(self):\n todo(\"use a better get_pi\")\n pi = get_pi()\n logger().info(\"pi = {}\".format(pi))\n todo(\"check more digits in pi\")\n self.assertAlmostEqual(pi, 3.14)\n logger().debug(\"end of this test\")\n pass\n # LOG_FILE=/tmp/log python3 -m unittest LoggerDemo\n.\n----------------------------------------------------------------------\nRan 1 test in 0.047s\n\nOK\n# cat /tmp/log\nWARNING:Test.testName:TODO: use a better get_pi\nINFO:get_pi:sorry, I know only three digits\nINFO:Test.testName:pi = 3.14\nWARNING:Test.testName:TODO: check more digits in pi\n LOG_FILE stderr" }, { "answer_id": 30038630, "author": "kenorb", "author_id": 55075, "author_profile": "https://Stackoverflow.com/users/55075", "pm_score": 2, "selected": false, "text": "logging import logging as log\n\ndef test_foo(self):\n log.debug(\"Some debug message.\")\n log.info(\"Some info message.\")\n log.warning(\"Some warning message.\")\n log.error(\"Some error message.\")\n /dev/stderr # Set-up logger\nif args.verbose or args.debug:\n logging.basicConfig( stream=sys.stdout )\n root = logging.getLogger()\n root.setLevel(logging.INFO if args.verbose else logging.DEBUG)\n ch = logging.StreamHandler(sys.stdout)\n ch.setLevel(logging.INFO if args.verbose else logging.DEBUG)\n ch.setFormatter(logging.Formatter('%(asctime)s %(levelname)s: %(name)s: %(message)s'))\n root.addHandler(ch)\nelse:\n logging.basicConfig(stream=sys.stderr)\n" }, { "answer_id": 36178137, "author": "fedorqui", "author_id": 1983854, "author_profile": "https://Stackoverflow.com/users/1983854", "pm_score": 3, "selected": false, "text": "log.debug() WARNING DEBUG import logging\n\nlog.debug(\"Some messages to be shown just when debugging or unit testing\")\n # Set log level\nloglevel = logging.DEBUG\nlogging.basicConfig(level=loglevel)\n daikiri.py make_discount() import logging\n\nlog = logging.getLogger(__name__)\n\nclass Daikiri(object):\n def __init__(self, name, price):\n self.name = name\n self.price = price\n\n def make_discount(self, percentage):\n log.debug(\"Deducting discount...\") # I want to see this message\n return self.price * percentage\n test_daikiri.py import unittest\nimport logging\nfrom .daikiri import Daikiri\n\n\nclass TestDaikiri(unittest.TestCase):\n def setUp(self):\n # Changing log level to DEBUG\n loglevel = logging.DEBUG\n logging.basicConfig(level=loglevel)\n\n self.mydaikiri = Daikiri(\"cuban\", 25)\n\n def test_drop_price(self):\n new_price = self.mydaikiri.make_discount(0)\n self.assertEqual(new_price, 0)\n\nif __name__ == \"__main__\":\n unittest.main()\n log.debug $ python -m test_daikiri\nDEBUG:daikiri:Deducting discount...\n.\n----------------------------------------------------------------------\nRan 1 test in 0.000s\n\nOK\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27415/" ]
284,049
<p>How do you get the current directory where your app is running? </p>
[ { "answer_id": 284142, "author": "Kieron", "author_id": 5791, "author_profile": "https://Stackoverflow.com/users/5791", "pm_score": 5, "selected": true, "text": "using System.IO;\nusing System.Reflection;\n\nnamespace Utilities\n{\n static public class DirectoryHelper\n {\n static public string GetCurrentDirectory ()\n {\n return Path.GetDirectoryName (Assembly.GetExecutingAssembly ().GetName ().CodeBase);\n }\n }\n}\n" }, { "answer_id": 284147, "author": "Todd", "author_id": 31940, "author_profile": "https://Stackoverflow.com/users/31940", "pm_score": 3, "selected": false, "text": "Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);\n" }, { "answer_id": 19788063, "author": "user2956093", "author_id": 2956093, "author_profile": "https://Stackoverflow.com/users/2956093", "pm_score": -1, "selected": false, "text": " Try\n\n Dim FILE_NAME As String = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase) + \"\\DBStatus\"\n\n Dim sr As IO.StreamWriter = Nothing\n If Not IO.File.Exists(FILE_NAME) Then\n sr = IO.File.CreateText(FILE_NAME)\n sr.WriteLine(strString)\n End If\n sr.Close()\n Catch ex As Exception\n\n End Try\n\n\nEnd Sub\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284049", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7024/" ]
284,052
<p>Imagine the following. </p> <ol> <li>Html is parsed into a dom tree</li> <li>Dom Nodes become available programmatically </li> <li>Dom Nodes may-or-may-not be augmented programmatically</li> <li>Augmented nodes are reserialised to html. </li> </ol> <p>I have primarily a question on how one would want the <b>"script"</b> tag to behave. </p> <pre><code>my $tree = someparser( $source ); .... print $somenode-&gt;text(); $somenode-&gt;text('arbitraryjavascript'); .... print $tree-&gt;serialize(); </code></pre> <p>Or to that effect. </p> <p>The problem occurs when deciding how to appropriately treat the contents of this field in regards to ease of use, and portability/usability of its emissions.</p> <p>What I'm wanting to do myself is this: </p> <pre><code> $somenode-&gt;text("verbatim"); </code></pre> <p>--> </p> <pre><code> &lt;script&gt; // &lt;!-- &lt;![CDATA[ verbatim // ]]&gt; --&gt; &lt;/script&gt; </code></pre> <p>So that what i produce is both somewhat safe, and validation friendly. </p> <p>But I'm indecisive if doing this magically is a good idea, and whether or not I should have code that tries to detect existing copies of 'safety blocks' and replace them/strip them on the 'parse' phase. </p> <p>If I don't strip it from input, I'm likely going to double up on the output phase, especially problematic if the output of this code is later wanted to be re-parsed. </p> <p>If i strip it from input It will have the beneficial effect that programmatically fetching the content of the script element wont see the safety blocks at either end. </p> <p>Ultimately there will be a way of toggling out some of this behaviour, but the question is what the /default/ way of handling this should be, and why. </p> <p>Its possible my entire reasoning is flawed here and the text contents should go totally unprocessed unless wanted to be processed. </p> <p>What behaviour do <strong>you</strong> look for in such a tool? Please point out anything in reasoning I may have overlooked. </p> <hr> <p><strong>TLDR Summary:</strong> How should i programmatically handle the <strong>escaping</strong> mechanism in these scripts, namely the '<code>//&lt;<code>!--&lt;![CDATA[</code></code>' safey padding at either end, with respect to input/output </p>
[ { "answer_id": 284130, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 1, "selected": false, "text": "my $html=<<'EOF'\n<script>\n//<!--<![CDATA[\nfoo\n//]]>-->\n</script>\nEOF\n#/# this line is here for the syntax highlighter\nmy $obj = parse($html); \nprint $obj->text(); \n# foo\n$obj->text(\"bar\");\nprint $obj->text(); \n# bar\nprint $obj->html(); \n# <script>\n# //<!--<![CDATA[\n# bar\n# //]]>-->\n# </script>\n <!- <!" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284052", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15614/" ]
284,060
<p>I am using a simple <a href="http://framework.zend.com/manual/en/zend.auth.html" rel="noreferrer">Zend_Auth</a> setup to authenticate users for one of my applications, using a check in the preDispatch() method in a <a href="http://framework.zend.com/manual/en/zend.controller.plugins.html" rel="noreferrer">controller plugin</a>. When anonymous users navigate to </p> <pre><code>/users/view/id/6 </code></pre> <p>for example, they should be redirected to the above URI after authentication.</p> <p>What is the best way to do this? I'd prefer not to store <code>$_SERVER['REQUEST_URI']</code> in the session. Personally, I'd find storing the entire Zend Request object to cleanest solution, but I am not sure if this is sensible and if this is the approach I should be taking.</p> <p>Any thoughts?</p>
[ { "answer_id": 284130, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 1, "selected": false, "text": "my $html=<<'EOF'\n<script>\n//<!--<![CDATA[\nfoo\n//]]>-->\n</script>\nEOF\n#/# this line is here for the syntax highlighter\nmy $obj = parse($html); \nprint $obj->text(); \n# foo\n$obj->text(\"bar\");\nprint $obj->text(); \n# bar\nprint $obj->html(); \n# <script>\n# //<!--<![CDATA[\n# bar\n# //]]>-->\n# </script>\n <!- <!" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284060", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11568/" ]
284,061
<p>I am working on an application where I have an images folder relative to my application root. I want to be able to specify this relative path in the Properties -> Settings designer eg. "\Images\". The issue I am running into is in cases where the Environment.CurrentDirectory gets changed via an OpenFileDialog the relative path doesn't resolve to the right location. Is there a way to specifiy in the Settings file a path that will imply to always start from the application directory as opposed to the current directory? I know I can always dynamically concatenate the application path to the front of the relative path, but I would like my Settings property to be able to resolve itself.</p>
[ { "answer_id": 284082, "author": "Scott Dorman", "author_id": 1559, "author_profile": "https://Stackoverflow.com/users/1559", "pm_score": 2, "selected": true, "text": "Environment.CurrentDirectory public string ExecutingAssemblyPath()\n{\n Assembly actualAssembly = Assembly.GetEntryAssembly();\n if (this.actualAssembly == null)\n {\n actualAssembly = Assembly.GetCallingAssembly();\n }\n return actualAssembly.Location;\n}\n" }, { "answer_id": 284088, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 0, "selected": false, "text": "string absolutePath = Settings.Default.ImagePath;\nif(!Path.IsPathRooted(absolutePath))\n{\n string root = Assembly.GetEntryAssembly().Location;\n root = Path.GetDirectoryName(root);\n absolutePath = Path.Combine(root, absolutePath);\n}\n GetExecutingAssembly() GetCallingAssembly()" }, { "answer_id": 487464, "author": "Sire", "author_id": 2440, "author_profile": "https://Stackoverflow.com/users/2440", "pm_score": 0, "selected": false, "text": "new System.IO.FileInfo(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile).Directory;\n Application.StartupPath\n" }, { "answer_id": 1516760, "author": "Graviton", "author_id": 3834, "author_profile": "https://Stackoverflow.com/users/3834", "pm_score": 0, "selected": false, "text": "public static string RealAssemblyFilePath()\n{\n string dllPath=Assembly.GetExecutingAssembly().CodeBase.Substring(8);\n return dllPath;\n}\n" }, { "answer_id": 6281022, "author": "Eamon Nerbonne", "author_id": 42921, "author_profile": "https://Stackoverflow.com/users/42921", "pm_score": 0, "selected": false, "text": "public static IEnumerable<DirectoryInfo> ParentDirs(this DirectoryInfo dir) {\n while (dir != null) {\n yield return dir;\n dir = dir.Parent;\n }\n}\npublic static DirectoryInfo FindDataDir(string relpath, Assembly assembly) {\n return new FileInfo((assembly).Location)\n .Directory.ParentDirs()\n .Select(dir => Path.Combine(dir.FullName + @\"\\\", relpath))\n .Where(Directory.Exists)\n .Select(path => new DirectoryInfo(path))\n .FirstOrDefault();\n}\n bin\\x64\\Release\\NonsensePath\\" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284061", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20489/" ]
284,063
<p>I'm currently refactoring code to replace Convert.To's to TryParse.</p> <p>I've come across the following bit of code which is creating and assigning a property to an object.</p> <pre><code>List&lt;Person&gt; list = new List&lt;Person&gt;(); foreach (DataRow row in dt.Rows) { var p = new Person{ RecordID = Convert.ToInt32(row["ContactID"]) }; list.Add(p); } </code></pre> <p>What I've come up with as a replacement is:</p> <pre><code>var p = new Person { RecordID = Int32.TryParse(row["ContactID"].ToString(), out RecordID) ? RecordID : RecordID }; </code></pre> <p>Any thoughts, opinions, alternatives to what I've done?</p>
[ { "answer_id": 284078, "author": "yfeldblum", "author_id": 12349, "author_profile": "https://Stackoverflow.com/users/12349", "pm_score": 4, "selected": true, "text": "public static Int32? ParseInt32(this string str) {\n Int32 k;\n if(Int32.TryParse(str, out k))\n return k;\n return null;\n}\n" }, { "answer_id": 284081, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 2, "selected": false, "text": "TryParse int? public static int? TryParseInt32(string x)\n{\n int value;\n return int.TryParse(x, out value) ? value : (int?) null;\n}\n var p = new Person { RecordID = Helpers.TryParseInt32(row[\"ContactID\"].ToString()) ?? 0 };\n" }, { "answer_id": 284097, "author": "Ali Ersöz", "author_id": 4215, "author_profile": "https://Stackoverflow.com/users/4215", "pm_score": 0, "selected": false, "text": "int recordId;\nInt32.TryParse(row[\"ContactID\"].ToString(), out recordID)\n\nforeach (DataRow row in dt.Rows)\n{\n var p = new Person{ RecordID = recordId };\n list.Add(p);\n}\n" }, { "answer_id": 54084299, "author": "alanthinker", "author_id": 10881894, "author_profile": "https://Stackoverflow.com/users/10881894", "pm_score": 0, "selected": false, "text": "private static void TryToDecimal(string str, Action<decimal> action)\n{\n if (decimal.TryParse(str, out decimal ret))\n {\n action(ret);\n }\n else\n {\n //do something you want\n }\n}\n\nTryToDecimal(strList[5], (x) => { st.LastTradePrice = x; });\nTryToDecimal(strList[3], (x) => { st.LastClosedPrice = x; });\nTryToDecimal(strList[6], (x) => { st.TopPrice = x; });\nTryToDecimal(strList[7], (x) => { st.BottomPrice = x; });\nTryToDecimal(strList[10], (x) => { st.PriceChange = x; });\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17692/" ]
284,090
<p>My class contains a <code>Dictionary&lt;T, S&gt; dict</code>, and I want to expose a <code>ReadOnlyCollection&lt;T&gt;</code> of the keys. How can I do this without copying the <code>Dictionary&lt;T, S&gt;.KeyCollection dict.Keys</code> to an array and then exposing the array as a <code>ReadOnlyCollection</code>? </p> <p>I want the <code>ReadOnlyCollection</code> to be a proper wrapper, ie. to reflect changes in the underlying Dictionary, and as I understand it copying the collection to an array will not do this (as well as seeming inefficient - I don't actually want a new collection, just to expose the underlying collection of keys...). Any ideas would be much appreciated!</p> <p>Edit: I'm using C# 2.0, so don't have extension methods such as .ToList (easily) available. </p>
[ { "answer_id": 284129, "author": "Jb Evain", "author_id": 36702, "author_profile": "https://Stackoverflow.com/users/36702", "pm_score": 4, "selected": true, "text": "var dictionary = ...;\nvar readonly_keys = new ReadOnlyCollection<T> (new CollectionListWrapper<T> (dictionary.Keys)\n);\n" }, { "answer_id": 284159, "author": "Phil Jenkins", "author_id": 35496, "author_profile": "https://Stackoverflow.com/users/35496", "pm_score": 0, "selected": false, "text": "Dictionary<int,string> dict = new Dictionary<int, string>();\n...\nReadOnlyCollection<int> roc = new ReadOnlyCollection<int>((new List<int>((IEnumerable<int>)dict.Keys)));\n" }, { "answer_id": 284218, "author": "Tamas Czinege", "author_id": 8954, "author_profile": "https://Stackoverflow.com/users/8954", "pm_score": 1, "selected": false, "text": "KeyCollection<T> ReadOnlyCollection<T>" }, { "answer_id": 284488, "author": "bruno conde", "author_id": 31136, "author_profile": "https://Stackoverflow.com/users/31136", "pm_score": 3, "selected": false, "text": "class MyListWrapper<T, TValue> : IList<T>\n{\n private Dictionary<T, TValue>.KeyCollection keys;\n\n public MyListWrapper(Dictionary<T, TValue>.KeyCollection keys)\n {\n this.keys = keys;\n }\n\n #region IList<T> Members\n\n public int IndexOf(T item)\n {\n if (item == null)\n throw new ArgumentNullException();\n IEnumerator<T> e = keys.GetEnumerator();\n int i = 0;\n while (e.MoveNext())\n {\n if (e.Current.Equals(item))\n return i;\n i++;\n }\n throw new Exception(\"Item not found!\");\n }\n\n public void Insert(int index, T item)\n {\n throw new NotImplementedException();\n }\n\n public void RemoveAt(int index)\n {\n throw new NotImplementedException();\n }\n\n public T this[int index]\n {\n get\n {\n IEnumerator<T> e = keys.GetEnumerator();\n if (index < 0 || index > keys.Count)\n throw new IndexOutOfRangeException();\n int i = 0;\n while (e.MoveNext() && i != index)\n {\n i++;\n }\n return e.Current;\n }\n set\n {\n throw new NotImplementedException();\n }\n }\n\n #endregion\n\n #region ICollection<T> Members\n\n public void Add(T item)\n {\n throw new NotImplementedException();\n }\n\n public void Clear()\n {\n throw new NotImplementedException();\n }\n\n public bool Contains(T item)\n {\n return keys.Contains(item);\n }\n\n public void CopyTo(T[] array, int arrayIndex)\n {\n keys.CopyTo(array, arrayIndex);\n }\n\n public int Count\n {\n get { return keys.Count; }\n }\n\n public bool IsReadOnly\n {\n get { return true; }\n }\n\n public bool Remove(T item)\n {\n throw new NotImplementedException();\n }\n\n #endregion\n\n #region IEnumerable<T> Members\n\n public IEnumerator<T> GetEnumerator()\n {\n return keys.GetEnumerator();\n }\n\n #endregion\n\n #region IEnumerable Members\n\n System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()\n {\n return keys.GetEnumerator();\n }\n\n #endregion\n}\n" }, { "answer_id": 37572467, "author": "Mark Sowul", "author_id": 155892, "author_profile": "https://Stackoverflow.com/users/155892", "pm_score": 1, "selected": false, "text": "KeyCollection<T> IReadOnlyCollection<T> IReadOnlyCollection<some base type> Enumerable.Contains<T> as IEnumerable ICollection<T>.Contains Dictionary.KeyCollection ICollection<T>" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6091/" ]
284,093
<p>How do I build an escape sequence string in hexadecimal notation. </p> <p>Example:</p> <pre><code>string s = "\x1A"; // this will create the hex-value 1A or dec-value 26 </code></pre> <p>I want to be able to build strings with hex-values between 00 to FF like this (in this example 1B)</p> <pre><code>string s = "\x" + "1B"; // Unrecognized escape sequence </code></pre> <p>Maybe there's another way of making hexadecimal strings...</p>
[ { "answer_id": 284116, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 6, "selected": true, "text": "Byte value = 0x0FF;\nint value = 0x1B;\n string foo = String.Format(\"{0} hex test\", 0x0BB);\n" }, { "answer_id": 284243, "author": "Nicolas Repiquet", "author_id": 36896, "author_profile": "https://Stackoverflow.com/users/36896", "pm_score": 3, "selected": false, "text": "Console.WriteLine( \"Look, I'm so happy : \\u263A\" );\n" }, { "answer_id": 284374, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 5, "selected": false, "text": "\\x \"\\x9Good compiler\"\n\"\\x9Bad compiler\"\n \"\\u0009Good compiler\"\n\"\\u0009Bad compiler\"\n \\t" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36922/" ]
284,094
<p>I have an XML document something like :::</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;?mso-application progid="Excel.Sheet"?&gt; &lt;Workbook xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="urn:schemas-microsoft-com:office:spreadsheet"&gt; &lt;Worksheet ss:Name="Worksheet1"&gt; &lt;Table&gt; &lt;Column ss:Width="100"&gt;&lt;/Column&gt; &lt;Row&gt; &lt;Cell ss:Index="1" ss:StyleID="headerStyle"&gt; &lt;Data ss:Type="String"&gt;Submitted By&lt;/Data&gt; &lt;/Cell&gt; &lt;/Row&gt; &lt;Row&gt; &lt;Cell ss:Index="1" ss:StyleID="alternatingItemStyle"&gt; &lt;Data ss:Type="String"&gt;Value1-0&lt;/Data&gt; &lt;/Cell&gt; &lt;/Row&gt; &lt;/Table&gt; &lt;AutoFilter xmlns="urn:schemas-microsoft-com:office:excel" x:Range="R1C1:R1C5"&gt;&lt;/AutoFilter&gt; &lt;/Worksheet&gt; &lt;/Workbook&gt; </code></pre> <p>The problem is when trying to select Rows with </p> <pre><code> &lt;xsl:for-each select="//Row"&gt; &lt;xsl:copy-of select="."/&gt; &lt;/xsl:for-each&gt; </code></pre> <p>It is not matching. I removed all of the name-spacing and it works fine. So, how do I get the 'select' to match Row?</p>
[ { "answer_id": 284123, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 3, "selected": false, "text": "<xsl:for-each select=\"//*[local-name() = 'Row']\">\n <xsl:copy-of select=\".\"/>\n</xsl:for-each>\n <xsl:for-each select=\"//:Row\">\n <xsl:copy-of select=\".\"/>\n</xsl:for-each>\n" }, { "answer_id": 284145, "author": "ckarras", "author_id": 5688, "author_profile": "https://Stackoverflow.com/users/5688", "pm_score": 6, "selected": true, "text": "select <xsl:stylesheet ... xmlns:os=\"urn:schemas-microsoft-com:office:spreadsheet\">\n ... \n <xsl:for-each select=\"//os:Row\">\n ...\n </xsl:for-each>\n ...\n</xsl:stylesheet>\n <xsl:for-each select=\"//*[local-name()='Row' = and namespace-uri()='urn:schemas-microsoft-com:office:spreadsheet']\">\n ...\n</xsl:for-each>\n" }, { "answer_id": 284231, "author": "ChuckB", "author_id": 28605, "author_profile": "https://Stackoverflow.com/users/28605", "pm_score": 3, "selected": false, "text": "xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"\n Workbook namespace-uri() local-name() namespace-uri()" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284094", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2017/" ]
284,115
<p>What is the best way to do cross-platform handling of hidden files? (preferably in Python, but other solutions still appreciated)</p> <p>Simply checking for a leading '.' works for *nix/Mac, and file attributes work on Windows. However, this seems a little simplistic, and also doesn't account for alternative methods of hiding things (.hidden files, etc.). Is there a standard way to deal with this?</p>
[ { "answer_id": 6365265, "author": "Jason R. Coombs", "author_id": 70170, "author_profile": "https://Stackoverflow.com/users/70170", "pm_score": 5, "selected": false, "text": "import ctypes\nimport os\n\ndef is_hidden(filepath):\n name = os.path.basename(os.path.abspath(filepath))\n return name.startswith('.') or has_hidden_attribute(filepath)\n\ndef has_hidden_attribute(filepath):\n try:\n attrs = ctypes.windll.kernel32.GetFileAttributesW(unicode(filepath))\n assert attrs != -1\n result = bool(attrs & 2)\n except (AttributeError, AssertionError):\n result = False\n return result\n from jaraco.windows import filesystem\n\ndef has_hidden_attribute(filepath):\n return filesystem.GetFileAttributes(filepath).hidden\n import os, stat\n\ndef has_hidden_attribute(filepath):\n return bool(os.stat(filepath).st_file_attributes & stat.FILE_ATTRIBUTE_HIDDEN)\n" }, { "answer_id": 15236292, "author": "abarnert", "author_id": 908494, "author_profile": "https://Stackoverflow.com/users/908494", "pm_score": 4, "selected": false, "text": "ls ~/Library pyobjc pip import Foundation\n\ndef is_hidden(path):\n url = Foundation.NSURL.fileURLWithPath_(path)\n return url.getResourceValue_forKey_error_(None, Foundation.NSURLIsHiddenKey, None)[0]\n\ndef listdir_skipping_hidden(path):\n url = Foundation.NSURL.fileURLWithPath_(path)\n fm = Foundation.NSFileManager.defaultManager()\n urls = fm.contentsOfDirectoryAtURL_includingPropertiesForKeys_options_error_(\n url, [], Foundation.NSDirectoryEnumerationSkipsHiddenFiles, None)[0]\n return [u.path() for u in urls]\n contentsOfDirectoryAtPath_error_ os.listdir is_hidden pyobjc CoreFoundation ctypes CFURLCopyResourcePropertyForKey is_hidden CFURLEnumeratorCreateForDirectoryURL ~/Library os.listdir is_hidden bytes str with try finally pyobjc import Foundation ImportError ctypes" }, { "answer_id": 31111306, "author": "Jason R. Coombs", "author_id": 70170, "author_profile": "https://Stackoverflow.com/users/70170", "pm_score": 0, "selected": false, "text": "is_hidden from jaraco import path\npath.is_hidden(file)\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284115", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2963/" ]
284,164
<p>I am using a Flex dataGrid, and need to sort some of my columns numerically.<br> Looking at the sortCompareFunction, it seems like i need to create a different function for each column that i want to sort, because my sort function has to know what field it is sorting on. </p> <p>Is there any way that I can pass the field to be sorted on into the function? so that I only need one numeric sorting function.</p>
[ { "answer_id": 722563, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "private function xmlDataGridNumericSorter(field:String):Function \n{\n\n return function (obj1:Object, obj2:Object):int \n {\n var num:Number = ((Number)(obj1.attribute(field)) - (Number)(obj2.attribute(field)));\n return (num > 0) ? 1 : ((num < 0) ? -1 : 0);\n }\n\n}\n dataGridColumn.sortCompareFunction = xmlDataGridNumericSorter(xmlAttribute.name().toString());\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32392/" ]
284,201
<p>I have a <a href="http://en.wikipedia.org/wiki/VBScript" rel="nofollow noreferrer">VBScript</a> script that starts a cmd prompt, telnets into a device and <a href="http://en.wikipedia.org/wiki/Trivial_File_Transfer_Protocol" rel="nofollow noreferrer">TFTP</a>'s the configuration to a server. It works when I am logged in and run it manually. I would like to automate it with Windows <a href="http://en.wikipedia.org/wiki/Task_Scheduler" rel="nofollow noreferrer">Task Scheduler</a>.</p> <p>Any assistance would be appreciated, here is the VBScript script:</p> <pre><code>set WshShell = WScript.CreateObject("WScript.Shell") WshShell.Run "cmd" WScript.Sleep 100 WshShell.AppActivate "C:\Windows\system32\cmd.exe" WScript.Sleep 300 WshShell.SendKeys "telnet 10.20.70.254{ENTER}" WScript.Sleep 300 WshShell.SendKeys "netscreen" WScript.Sleep 300 WshShell.SendKeys "{ENTER}" WScript.Sleep 300 WshShell.SendKeys "netscreen" WshShell.SendKeys "{ENTER}" WScript.Sleep 300 WScript.Sleep 300 WshShell.SendKeys "save conf to tftp 10.10.40.139 test.cfg{ENTER}" WScript.Sleep 200 WshShell.SendKeys "exit{ENTER}" 'close telnet session' set WshShell = WScript.CreateObject("WScript.Shell") WshShell.Run "cmd" WScript.Sleep 100 WshShell.AppActivate "C:\Windows\system32\cmd.exe" WScript.Sleep 300 WshShell.SendKeys "telnet 10.20.70.254{ENTER}" WScript.Sleep 300 WshShell.SendKeys "netscreen" WScript.Sleep 300 WshShell.SendKeys "{ENTER}" WScript.Sleep 300 WshShell.SendKeys "netscreen" WshShell.SendKeys "{ENTER}" WScript.Sleep 300 WScript.Sleep 300 WshShell.SendKeys "save conf to tftp 10.10.40.139 palsg140.cfg{ENTER}" 'repeat as needed WScript.Sleep 200 WshShell.SendKeys "exit{ENTER}" 'close telnet session' WshShell.SendKeys "{ENTER}" 'get command prompt back WScript.Sleep 200 WshShell.SendKeys "exit{ENTER}" 'close cmd.exe WshShell.SendKeys "{ENTER}" 'get command prompt back WScript.Sleep 200 WshShell.SendKeys "exit{ENTER}" 'close cmd.exe </code></pre>
[ { "answer_id": 295640, "author": "Michael Galos", "author_id": 29820, "author_profile": "https://Stackoverflow.com/users/29820", "pm_score": 1, "selected": false, "text": "telnet 10.10.40.139\nnetscreen\nnetscreen\nsave conf to tftp 10.10.40.139 palsg140.cf\nexit\n" }, { "answer_id": 1004088, "author": "scottm", "author_id": 53007, "author_profile": "https://Stackoverflow.com/users/53007", "pm_score": 1, "selected": false, "text": "cscript.exe myscript.vbs\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284201", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
284,220
<pre><code>public class Item { private int _rowID; private Guid _itemGUID; public Item() { } public int Rid { get { return _rowID; } set { } } public Guid IetmGuid { get { return _itemGuid; } set { _itemGuid= value; } } } </code></pre> <p>The above is my custom object.</p> <p>I have a list:</p> <pre><code>List&lt;V&gt; myList = someMethod; </code></pre> <p>where V is of type Item, my object.</p> <p>I want to iterate and get the properties as such</p> <pre><code>foreach(V element in mylist) { Guid test = element.IetmGuid; } </code></pre> <p>When I debug and look at the 'element' object I can see all the properties in the 'Quickwatch' but I cannot do element.IetmGuid.</p>
[ { "answer_id": 284235, "author": "TcKs", "author_id": 20382, "author_profile": "https://Stackoverflow.com/users/20382", "pm_score": 1, "selected": false, "text": "foreach( object element in myList ) {\n Item itm = element as Item;\n if ( null == itm ) { continue; }\n Guid test = itm.ItemGuid;\n}\n" }, { "answer_id": 284236, "author": "user34292", "author_id": 34292, "author_profile": "https://Stackoverflow.com/users/34292", "pm_score": 1, "selected": false, "text": "List<V> myList = someMethod;\n foreach(V element in myList)\n{\n Guid test = element.IetmGuid;\n}\n" }, { "answer_id": 284263, "author": "Daniel M", "author_id": 36559, "author_profile": "https://Stackoverflow.com/users/36559", "pm_score": 2, "selected": false, "text": "List<Item> myList = someMethod;\n" }, { "answer_id": 284266, "author": "akmad", "author_id": 1314, "author_profile": "https://Stackoverflow.com/users/1314", "pm_score": 3, "selected": false, "text": "Item public class MyGenericClass<V>\n where V : Item //This is a constraint that requires type V to be an Item (or subtype)\n{\n public void DoSomething()\n {\n List<V> myList = someMethod();\n\n foreach (V element in myList)\n {\n //This will now work because you've constrained the generic type V\n Guid test = element.IetmGuid;\n }\n }\n}\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284220", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
284,234
<p>Having played around a little with both Tkinter and wxPython, I like Tkinter much better in terms of how clean my source code looks. However, it doesn't seem to have as many features; in particular it doesn't have tabs (as in, the tabs at the top of a Firefox window).</p> <p>A little Googling on the subject offers a few suggestions. There's <a href="http://code.activestate.com/recipes/188537/" rel="noreferrer">a cookbook entry</a> with a class allowing you to use tabs, but it's very primitive. There's also <a href="http://pmw.sourceforge.net/" rel="noreferrer">Python megawidgets</a> on SourceForge, although this seems very old and gave me errors during installation.</p> <p>Does anyone have experience making tabbed GUIs in Tkinter? What did you use? Or is it simply the case that anyone who needs more powerful windowing components has to use wxPython?</p>
[ { "answer_id": 284695, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 6, "selected": true, "text": "ttk Tk 8.5 ttk import ttk\n\nhelp(ttk.Notebook)\n ttk tkinter TkDocs from tkinter import ttk\nimport tkinter as tk\nfrom tkinter.scrolledtext import ScrolledText\n\n\ndef demo():\n root = tk.Tk()\n root.title(\"ttk.Notebook\")\n\n nb = ttk.Notebook(root)\n\n # adding Frames as pages for the ttk.Notebook \n # first page, which would get widgets gridded into it\n page1 = ttk.Frame(nb)\n\n # second page\n page2 = ttk.Frame(nb)\n text = ScrolledText(page2)\n text.pack(expand=1, fill=\"both\")\n\n nb.add(page1, text='One')\n nb.add(page2, text='Two')\n\n nb.pack(expand=1, fill=\"both\")\n\n root.mainloop()\n\nif __name__ == \"__main__\":\n demo()\n NoteBook tkinter.tix tkinter.tix Tix Tk from tkinter import tix\nroot = tix.Tk()\nroot.tk.eval('package require Tix')\n tix ttk.Notebook" }, { "answer_id": 18922125, "author": "sPaz", "author_id": 1762092, "author_profile": "https://Stackoverflow.com/users/1762092", "pm_score": 3, "selected": false, "text": "from tkinter import *\n\nclass Tabs(Frame):\n\n \"\"\"Tabs for testgen output\"\"\"\n\n def __init__(self, parent):\n super(Tabs, self).__init__()\n self.parent = parent\n self.columnconfigure(10, weight=1)\n self.rowconfigure(3, weight=1)\n self.curtab = None\n self.tabs = {}\n self.addTab() \n self.pack(fill=BOTH, expand=1, padx=5, pady=5)\n\n def addTab(self):\n tabslen = len(self.tabs)\n if tabslen < 10:\n tab = {}\n btn = Button(self, text=\"Tab \"+str(tabslen), command=lambda: self.raiseTab(tabslen))\n btn.grid(row=0, column=tabslen, sticky=W+E)\n\n textbox = Text(self.parent)\n textbox.grid(row=1, column=0, columnspan=10, rowspan=2, sticky=W+E+N+S, in_=self)\n\n # Y axis scroll bar\n scrollby = Scrollbar(self, command=textbox.yview)\n scrollby.grid(row=7, column=5, rowspan=2, columnspan=1, sticky=N+S+E)\n textbox['yscrollcommand'] = scrollby.set\n\n tab['id']=tabslen\n tab['btn']=btn\n tab['txtbx']=textbox\n self.tabs[tabslen] = tab\n self.raiseTab(tabslen)\n\n def raiseTab(self, tabid):\n print(tabid)\n print(\"curtab\"+str(self.curtab))\n if self.curtab!= None and self.curtab != tabid and len(self.tabs)>1:\n self.tabs[tabid]['txtbx'].lift(self)\n self.tabs[self.curtab]['txtbx'].lower(self)\n self.curtab = tabid\n\n\ndef main():\n root = Tk()\n root.geometry(\"600x450+300+300\")\n t = Tabs(root)\n t.addTab()\n root.mainloop()\n\nif __name__ == '__main__':\n main()\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284234", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1694/" ]
284,240
<p>I have a project where there are multiple applications that have some common configuration values. I would like to have a shared .config file that is available to all of the applications using the .Net configuration object model. Each application would also have its own app.config file</p> <p>How can this best be done. I'd rather avoid using the registry as much as possible. In looking through the documentation, the OpenExeConfiguration(string exePath) method seems promising for accessing a specified config file. Is this a reasonable approach? Any other suggestions?</p>
[ { "answer_id": 284517, "author": "Thad", "author_id": 24500, "author_profile": "https://Stackoverflow.com/users/24500", "pm_score": 3, "selected": false, "text": "<appSetting configSource=\"somefile.config\"/>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284240", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35598/" ]
284,245
<p>So let's say you wanted to make a copy of a Web Form page within a .Net Project. </p> <p>Is there an easier way than:</p> <ol> <li>Copy Source Page</li> <li>Page Source Page within project to get new page</li> <li>Exclude Source Page </li> <li>Rename code behind class for new page</li> <li>Add Source Page Back</li> </ol> <p>Sometimes I miss something obvious is there a better way to do this? I know the next question would be "Why are you copying code within a project instead for reusing it?" Let's just say that's a secret;). </p>
[ { "answer_id": 284292, "author": "Kon", "author_id": 22303, "author_profile": "https://Stackoverflow.com/users/22303", "pm_score": 2, "selected": false, "text": "Inherits Page Page" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284245", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32113/" ]
284,246
<p>I'm currently working on a Google Maps project and am implementing a search function. In my search function I'm trying to have content on the side listing which search makers that were just added to the map correspond to each hall. However in assembling this string I run into a problem where my <code>side_bar_html</code> variable will not output if I do not alert the data first.</p> <p>Here is my searchMap function. The variable is declared as such: <code>var side_bar_html = "";</code></p> <pre><code>function searchMap(term, map) { closeSearch(); searchCount = 0; searchMarkers = []; var request = GXmlHttp.create(); request.open("GET", "admin/search.php?s=" + term, true); request.onreadystatechange = function() { if (request.readyState == 4) { var xmlDoc = GXml.parse(request.responseText); var points = xmlDoc.documentElement.getElementsByTagName("point"); var polygonsToShow = []; for (var i = 0; i &lt; points.length; i++) { var lat = parseFloat(points[i].getAttribute("lat")); var lng = parseFloat(points[i].getAttribute("lng")); var pid = points[i].getAttribute("id"); for(var j = 0; j &lt; polygons.length; j++) { if(polygons[j].vt_bid == pid) { polygonsToShow.push(j); } } var point = new GLatLng(lat,lng); var pname = points[i].getAttribute("name"); var curMarker = createSearchMarker(point, pid, pname,getLetter(i)); map.addOverlay(curMarker); } //olays.buildings.checked = false; : Figure out some way to uncheck the buildings overlay checkbox? for(var k = 0; k &lt; polygons.length; k++) { polygons[k].hide(); } for(var l = 0; l &lt; polygonsToShow.length; l++){ polygons[polygonsToShow[l]].show(); } } } request.send(null); alert(side_bar_html); //side_bar_html will be empty unless I alert the variable searchResults = new HtmlControl('&lt;div style="background-color:white; border:solid 1px grey; padding:2ex; overflow:auto; width:125px; margin:1px; font-size:14px;"&gt;&lt;img align="right" style="cursor: pointer;" src="http://www.thebort.com/maps/images/close.gif" onclick="closeSearch()"&gt;&lt;strong&gt;Search&lt;/strong&gt;&lt;br/&gt;' + side_bar_html + '&lt;/div&gt;', {selectable:true}); map.addControl(searchResults, new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(20, 70))); } </code></pre> <p>And the function to create a search marker:</p> <pre><code>function createSearchMarker(point, id, pname, letIcon) { var marker = new GMarker(point,letIcon); GEvent.addListener(marker, "click", function() { marker.openInfoWindowHtml('&lt;a href="#" onclick=\'tb_show("' + pname + '","admin/get_info.php?b=' + id + '&amp;KeepThis=true&amp;TB_iframe=true&amp;height=400&amp;width=600",false); return false;\'&gt;' + pname + '&lt;/a&gt;'); }); side_bar_html = side_bar_html + '&lt;a href="javascript:clickSearch(' + searchCount + ')"&gt;' + String.fromCharCode("A".charCodeAt(0) + searchCount) + ': ' + pname + '&lt;/a&gt;&lt;br&gt;'; marker.vt_id = id; searchMarkers.push(marker); searchCount++; return marker; } </code></pre> <p>I would like to keep code exposure for this project at a minimum right now so if anything needs expounding please let me know. Thanks!</p>
[ { "answer_id": 284265, "author": "Eli Courtwright", "author_id": 1694, "author_profile": "https://Stackoverflow.com/users/1694", "pm_score": 3, "selected": true, "text": "side_bar_html onreadystatechange req.send(null) onreadystatechange side_bar_html side_bar_html side_bar_html onreadystatechange" }, { "answer_id": 284284, "author": "Jared", "author_id": 1980, "author_profile": "https://Stackoverflow.com/users/1980", "pm_score": 0, "selected": false, "text": "request.onreadystatechange = function() {\n\nif (request.readyState == 4) {\n\n var xmlDoc = GXml.parse(request.responseText);\n var points = xmlDoc.documentElement.getElementsByTagName(\"point\");\n\n var polygonsToShow = [];\n for (var i = 0; i < points.length; i++) { \n var lat = parseFloat(points[i].getAttribute(\"lat\"));\n var lng = parseFloat(points[i].getAttribute(\"lng\"));\n var pid = points[i].getAttribute(\"id\");\n for(var j = 0; j < polygons.length; j++) {\n if(polygons[j].vt_bid == pid) {\n polygonsToShow.push(j);\n }\n }\n var point = new GLatLng(lat,lng); \n var pname = points[i].getAttribute(\"name\");\n var curMarker = createSearchMarker(point, pid, pname,getLetter(i)); \n map.addOverlay(curMarker);\n }\n //olays.buildings.checked = false; : Figure out some way to uncheck the buildings overlay checkbox?\n for(var k = 0; k < polygons.length; k++) {\n polygons[k].hide();\n }\n\n for(var l = 0; l < polygonsToShow.length; l++){ \n polygons[polygonsToShow[l]].show();\n }\n\n searchResults = new HtmlControl('<div style=\"background-color:white; border:solid 1px grey; padding:2ex; overflow:auto; width:125px; margin:1px; font-size:14px;\"><img align=\"right\" style=\"cursor: pointer;\" src=\"http://www.thebort.com/maps/images/close.gif\" onclick=\"closeSearch()\"><strong>Search</strong><br/>' + side_bar_html + '</div>', {selectable:true});\n map.addControl(searchResults, new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(20, 70)));\n}\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284246", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36939/" ]
284,247
<p>Recently, I started maintaining a web application which unfortunately works only with IE 6. Most of the issues are related to CSS.</p> <p>Is there any tool which can help me standardize the CSS classes to work with <strong>both</strong> <strong>IE 6 and IE 7</strong>? I understand I have to go through standards but I need something to start with quickly.</p> <p>Firebug can help me to some extend in identifying the CSS classes related to the UI elements (if the page renders on firefox). But, I was looking for something more like an advisor tool. If you have some experience to share, please feel free.</p>
[ { "answer_id": 1177213, "author": "se_pavel", "author_id": 80917, "author_profile": "https://Stackoverflow.com/users/80917", "pm_score": 1, "selected": false, "text": "css-selector { code for all browsers }\n\n*html css-selector {code for IE6 browser }\n\n*+html css-selector {code for IE7 browser } \n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284247", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4337/" ]
284,258
<p>As part of our build process I need to set the version information for all of our compiled binaries. Some of the binaries already have version information (added at compile time) and some do not. </p> <p>I want to be able to apply the following information:</p> <ul> <li>Company Name </li> <li>Copyright Notice</li> <li>Product Name </li> <li>Product Description</li> <li>File Version </li> <li>Product Version</li> </ul> <p>All of these attributes are specified by the build script and must be applied after compilation. These are standard binaries (not assemblies) compiled with C++ Builder 2007.</p> <p>How can I do this?</p>
[ { "answer_id": 2111700, "author": "filofel", "author_id": 94816, "author_profile": "https://Stackoverflow.com/users/94816", "pm_score": 4, "selected": false, "text": "verpatch /va foodll.dll %VERSION% %FILEDESCR% %COMPINFO% %PRODINFO% %BUILDINFO%\n" }, { "answer_id": 18839527, "author": "Danny Beckett", "author_id": 1563422, "author_profile": "https://Stackoverflow.com/users/1563422", "pm_score": 5, "selected": false, "text": "Resources.rc VS_VERSION_INFO VERSIONINFO\n FILEVERSION 1,0,0,0\n PRODUCTVERSION 1,0,0,0\n{\n BLOCK \"StringFileInfo\"\n {\n BLOCK \"040904b0\"\n {\n VALUE \"CompanyName\", \"ACME Inc.\\0\"\n VALUE \"FileDescription\", \"MyProg\\0\"\n VALUE \"FileVersion\", \"1.0.0.0\\0\"\n VALUE \"LegalCopyright\", \"© 2013 ACME Inc. All Rights Reserved\\0\"\n VALUE \"OriginalFilename\", \"MyProg.exe\\0\"\n VALUE \"ProductName\", \"My Program\\0\"\n VALUE \"ProductVersion\", \"1.0.0.0\\0\"\n }\n }\n BLOCK \"VarFileInfo\"\n {\n VALUE \"Translation\", 0x409, 1200\n }\n}\n .res GoRC /fo Resources.res Resources.rc\n GoRC.exe .exe ResHacker -add MyProg.exe, MyProg.exe, Resources.res,,,\n" }, { "answer_id": 35188966, "author": "a paid nerd", "author_id": 102704, "author_profile": "https://Stackoverflow.com/users/102704", "pm_score": 4, "selected": false, "text": "$ rcedit \"path-to-exe-or-dll\" --set-version-string \"Comments\" \"This is an exe\"\n$ rcedit \"path-to-exe-or-dll\" --set-file-version \"10.7\"\n$ rcedit \"path-to-exe-or-dll\" --set-product-version \"10.7\"\n" }, { "answer_id": 35429430, "author": "user3016543", "author_id": 3016543, "author_profile": "https://Stackoverflow.com/users/3016543", "pm_score": 4, "selected": false, "text": "#ifndef VERSION_H\n#define VERSION_H\n\n#define VER_FILEVERSION 0,3,0,0\n#define VER_FILEVERSION_STR \"0.3.0.0\\0\"\n\n#define VER_PRODUCTVERSION 0,3,0,0\n#define VER_PRODUCTVERSION_STR \"0.3.0.0\\0\"\n\n#define VER_COMPANYNAME_STR \"IPanera\"\n#define VER_FILEDESCRIPTION_STR \"Localiza archivos duplicados\"\n#define VER_INTERNALNAME_STR \"MyProject\"\n#define VER_LEGALCOPYRIGHT_STR \"Copyright 2016 ipanera@gmail.com\"\n#define VER_LEGALTRADEMARKS1_STR \"All Rights Reserved\"\n#define VER_LEGALTRADEMARKS2_STR VER_LEGALTRADEMARKS1_STR\n#define VER_ORIGINALFILENAME_STR \"MyProject.exe\"\n#define VER_PRODUCTNAME_STR \"My project\"\n\n#define VER_COMPANYDOMAIN_STR \"www.myurl.com\"\n\n#endif // VERSION_H\n #include <windows.h>\n#include \"version.h\"\n\nVS_VERSION_INFO VERSIONINFO\nFILEVERSION VER_FILEVERSION\nPRODUCTVERSION VER_PRODUCTVERSION\nBEGIN\n BLOCK \"StringFileInfo\"\n BEGIN\n BLOCK \"040904E4\"\n BEGIN\n VALUE \"CompanyName\", VER_COMPANYNAME_STR\n VALUE \"FileDescription\", VER_FILEDESCRIPTION_STR\n VALUE \"FileVersion\", VER_FILEVERSION_STR\n VALUE \"InternalName\", VER_INTERNALNAME_STR\n VALUE \"LegalCopyright\", VER_LEGALCOPYRIGHT_STR\n VALUE \"LegalTrademarks1\", VER_LEGALTRADEMARKS1_STR\n VALUE \"LegalTrademarks2\", VER_LEGALTRADEMARKS2_STR\n VALUE \"OriginalFilename\", VER_ORIGINALFILENAME_STR\n VALUE \"ProductName\", VER_PRODUCTNAME_STR\n VALUE \"ProductVersion\", VER_PRODUCTVERSION_STR\n END\n END\n\n BLOCK \"VarFileInfo\"\n BEGIN\n VALUE \"Translation\", 0x409, 1252\n END\nEND\n" }, { "answer_id": 54409096, "author": "CristiFati", "author_id": 4788546, "author_profile": "https://Stackoverflow.com/users/4788546", "pm_score": 4, "selected": false, "text": "e:\\Work\\Dev\\StackOverflow\\q000284258> sopr.bat\n*** Set shorter prompt to better fit when pasted in StackOverflow (or other) pages ***\n\n[prompt]> dir\n Volume in drive E is Work\n Volume Serial Number is 3655-6FED\n\n Directory of e:\\Work\\Dev\\StackOverflow\\q000284258\n\n2019-01-28 20:09 <DIR> .\n2019-01-28 20:09 <DIR> ..\n2016-11-03 09:17 5,413,376 cmake.exe\n2019-01-03 02:06 5,479,424 ResourceHacker.exe\n2019-01-28 20:30 496 ResourceHacker.ini\n 3 File(s) 10,893,296 bytes\n 2 Dir(s) 103,723,261,952 bytes free\n\n[prompt]> set PATH=%PATH%;c:\\Install\\x64\\CMake\\CMake\\3.6.3\\bin\n\n[prompt]> .\\cmake --help >nul 2>&1\n\n[prompt]> echo %errorlevel%\n0\n\n[prompt]> .\\ResourceHacker.exe -help\n\n[prompt]>\n\n==================================\nResource Hacker Command Line Help:\n==================================\n\n-help : displays these abbreviated help instructions.\n-help commandline : displays help for single commandline instructions\n-help script : displays help for script file instructions.\n\n\n\n\n[prompt]> echo %errorlevel%\n0\n -action extract -action compile [prompt]> :: Extract the resources into a file\n[prompt]> .\\ResourceHacker.exe -open .\\ResourceHacker.exe -save .\\sample.rc -action extract -mask VersionInfo,, -log con\n\n[prompt]>\n\n[28 Jan 2019, 20:58:03]\n\nCurrent Directory:\ne:\\Work\\Dev\\StackOverflow\\q000284258\n\nCommandline:\n.\\ResourceHacker.exe -open .\\ResourceHacker.exe -save .\\sample.rc -action extract -mask VersionInfo,, -log con\n\nOpen : e:\\Work\\Dev\\StackOverflow\\q000284258\\ResourceHacker.exe\nSave : e:\\Work\\Dev\\StackOverflow\\q000284258\\sample.rc\n\n\nSuccess!\n\n[prompt]> :: Modify the resource file and set our own values\n[prompt]>\n[prompt]> :: Compile the resource file\n[prompt]> .\\ResourceHacker.exe -open .\\sample.rc -save .\\sample.res -action compile -log con\n\n[prompt]>\n\n[28 Jan 2019, 20:59:51]\n\nCurrent Directory:\ne:\\Work\\Dev\\StackOverflow\\q000284258\n\nCommandline:\n.\\ResourceHacker.exe -open .\\sample.rc -save .\\sample.res -action compile -log con\n\nOpen : e:\\Work\\Dev\\StackOverflow\\q000284258\\sample.rc\nSave : e:\\Work\\Dev\\StackOverflow\\q000284258\\sample.res\n\nCompiling: e:\\Work\\Dev\\StackOverflow\\q000284258\\sample.rc\nSuccess!\n\n[prompt]> dir /b\ncmake.exe\nResourceHacker.exe\nResourceHacker.ini\nsample.rc\nsample.res\n 1 VERSIONINFO\nFILEVERSION 3,1,4,1592\nPRODUCTVERSION 2,7,1,8\nFILEOS 0x4\nFILETYPE 0x1\n{\nBLOCK \"StringFileInfo\"\n{\n BLOCK \"040904E4\"\n {\n VALUE \"CompanyName\", \"Cristi Fati\\0\"\n VALUE \"FileDescription\", \"20190128 - SO q000284258 demo\\0\"\n VALUE \"FileVersion\", \"3.1.4.1592\\0\"\n VALUE \"ProductName\", \"Colonel Panic\\0\"\n VALUE \"InternalName\", \"100\\0\"\n VALUE \"LegalCopyright\", \"(c) Cristi Fati 1999-2999\\0\"\n VALUE \"OriginalFilename\", \"ResHack\\0\"\n VALUE \"ProductVersion\", \"2.7.1.8\\0\"\n }\n}\n\nBLOCK \"VarFileInfo\"\n{\n VALUE \"Translation\", 0x0409 0x04E4 \n}\n}\n -action addoverwrite [prompt]> .\\ResourceHacker.exe -open .\\cmake.exe -save .\\cmake.exe -res .\\sample.res -action addoverwrite -mask VersionInfo,, -log con\n\n[prompt]>\n\n[28 Jan 2019, 21:17:19]\n\nCurrent Directory:\ne:\\Work\\Dev\\StackOverflow\\q000284258\n\nCommandline:\n.\\ResourceHacker.exe -open .\\cmake.exe -save .\\cmake.exe -res .\\sample.res -action addoverwrite -mask VersionInfo,, -log con\n\nOpen : e:\\Work\\Dev\\StackOverflow\\q000284258\\cmake.exe\nSave : e:\\Work\\Dev\\StackOverflow\\q000284258\\cmake.exe\nResource: e:\\Work\\Dev\\StackOverflow\\q000284258\\sample.res\n\n Added: VERSIONINFO,1,1033\n\nSuccess!\n\n[prompt]> copy ResourceHacker.exe ResourceHackerTemp.exe\n 1 file(s) copied.\n\n[prompt]> .\\ResourceHackerTemp.exe -open .\\ResourceHacker.exe -save .\\ResourceHacker.exe -res .\\sample.res -action addoverwrite -mask VersionInfo,, -log con\n\n[prompt]>\n\n[28 Jan 2019, 21:19:29]\n\nCurrent Directory:\ne:\\Work\\Dev\\StackOverflow\\q000284258\n\nCommandline:\n.\\ResourceHackerTemp.exe -open .\\ResourceHacker.exe -save .\\ResourceHacker.exe -res .\\sample.res -action addoverwrite -mask VersionInfo,, -log con\n\nOpen : e:\\Work\\Dev\\StackOverflow\\q000284258\\ResourceHacker.exe\nSave : e:\\Work\\Dev\\StackOverflow\\q000284258\\ResourceHacker.exe\nResource: e:\\Work\\Dev\\StackOverflow\\q000284258\\sample.res\n\n Modified: VERSIONINFO,1,1033\n\nSuccess!\n\n[prompt]> del /f /q ResourceHackerTemp.*\n\n[prompt]> dir\n Volume in drive E is Work\n Volume Serial Number is 3655-6FED\n\n Directory of e:\\Work\\Dev\\StackOverflow\\q000284258\n\n2019-01-28 21:20 <DIR> .\n2019-01-28 21:20 <DIR> ..\n2016-11-03 09:17 5,414,400 cmake.exe\n2019-01-03 02:06 5,479,424 ResourceHacker.exe\n2019-01-28 21:17 551 ResourceHacker.ini\n2019-01-28 20:05 1,156 sample.rc\n2019-01-28 20:59 792 sample.res\n 5 File(s) 10,896,323 bytes\n 2 Dir(s) 103,723,253,760 bytes free\n [prompt]> .\\cmake --help >nul 2>&1\n\n[prompt]> echo %errorlevel%\n0\n\n[prompt]> .\\ResourceHacker.exe -help\n\n[prompt]>\n\n==================================\nResource Hacker Command Line Help:\n==================================\n\n-help : displays these abbreviated help instructions.\n-help commandline : displays help for single commandline instructions\n-help script : displays help for script file instructions.\n\n\n\n\n[prompt]> echo %errorlevel%\n0\n" }, { "answer_id": 58716971, "author": "RDR", "author_id": 12327655, "author_profile": "https://Stackoverflow.com/users/12327655", "pm_score": 3, "selected": false, "text": " @echo off\n :start1\n set /p newVersion=Enter version number [?.?.?.?]:\n if \"%newVersion%\" == \"\" goto start1\n :start2\n set /p file=Enter EXE name [for 'program.exe' enter 'program']:\n if \"%file%\" == \"\" goto start2\n for /f \"tokens=1-4 delims=.\" %%a in ('echo %newVersion%') do (set ResVersion=%%a,%%b,%%c,%%d)\n (\n echo:VS_VERSION_INFO VERSIONINFO\n echo: FILEVERSION %ResVersion%\n echo: PRODUCTVERSION %ResVersion%\n echo:{\n echo: BLOCK \"StringFileInfo\"\n echo: {\n echo: BLOCK \"040904b0\"\n echo: {\n echo: VALUE \"CompanyName\", \"MyCompany\\0\"\n echo: VALUE \"FileDescription\", \"TestFile\\0\"\n echo: VALUE \"FileVersion\", \"%newVersion%\\0\"\n echo: VALUE \"LegalCopyright\", \"COPYRIGHT © 2019 MyCompany\\0\"\n echo: VALUE \"OriginalFilename\", \"%file%.exe\\0\"\n echo: VALUE \"ProductName\", \"Test\\0\"\n echo: VALUE \"ProductVersion\", \"%newVersion%\\0\"\n echo: }\n echo: }\n echo: BLOCK \"VarFileInfo\"\n echo: {\n echo: VALUE \"Translation\", 0x409, 1200\n echo: }\n echo:}\n ) >Resources.rc && echo setting Resources.rc\n ResourceHacker.exe -open resources.rc -save resources.res -action compile -log CONSOLE\n ResourceHacker -open \"%file%.exe\" -save \"%file%Res.exe\" -action addoverwrite -resource \"resources.res\" -log CONSOLE\n ResourceHacker.exe -open \"%file%Res.exe\" -save \"%file%Ico.exe\" -action addskip -res \"%file%.ico\" -mask ICONGROUP,MAINICON, -log CONSOLE\n xCopy /y /f \"%file%Ico.exe\" \"%file%.exe\"\n echo.\n echo.\n echo your compiled file %file%.exe is ready\n pause\n" }, { "answer_id": 66702321, "author": "Carson", "author_id": 9935654, "author_profile": "https://Stackoverflow.com/users/9935654", "pm_score": 1, "selected": false, "text": "resource resource.rc VS_VERSION_INFO VERSIONINFO\n FILEVERSION 0,0,0,0\n PRODUCTVERSION 0,0,0,0\n{\n BLOCK \"StringFileInfo\"\n {\n BLOCK \"040904b0\"\n {\n VALUE \"CompanyName\", \"\\0\"\n VALUE \"FileDescription\", \"\\0\"\n VALUE \"FileVersion\", \"0.0.0.0\\0\"\n VALUE \"LegalCopyright\", \"© 2020 Carson. All rights reserved.\\0\"\n VALUE \"OriginalFilename\", \".exe\\0\"\n VALUE \"ProductName\", \"\\0\"\n VALUE \"ProductVersion\", \"0.0.0.0\\0\"\n }\n }\n BLOCK \"VarFileInfo\"\n {\n VALUE \"Translation\", 0x0409, 1200\n }\n}\n choco install reshack -y res rc ResourceHacker.exe -open resources.rc -save resources.res ^\n -action compile -log CONSOLE\n SET INPUT_EXE=app.exe\nSET OUTPUT_EXE=app.exe\nResourceHacker.exe -open %OUTPUT_EXE% -save %OUTPUT_EXE% ^\n -resource resources.res ^\n -action addoverwrite ^\n -mask VersionInf ^\n -log CONSOLE\n SET INPUT_EXE=app.exe\nSET OUTPUT_EXE=app.exe\n\nResourceHacker.exe -open resources.rc -save resources.res ^\n -action compile -log CONSOLE\n\nResourceHacker.exe -open %OUTPUT_EXE% -save %OUTPUT_EXE% ^\n -resource resources.res ^\n -action addoverwrite ^\n -mask VersionInf ^\n -log CONSOLE\n Command Line Syntax ^" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284258", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5449/" ]
284,259
<p>Years ago when I was starting a small development project, the other developers and I sat down and agreed on a compromise brace and indentation style. It wasn't anybody's favourite, but it was something that nobody really hated. I wrote a .indentrc configuration file to that style, and had a check-in trigger that would run indent on every file as it was being checked in. That made it so that it didn't matter what style you wrote your code in, it would end up being the group standard before anybody else saw it. This had the advantage of consistency. But I've never seen anybody else do it this way before or since.</p> <p>So what say the rest of you? Great idea, or abomination?</p>
[ { "answer_id": 284289, "author": "Eli Courtwright", "author_id": 1694, "author_profile": "https://Stackoverflow.com/users/1694", "pm_score": 3, "selected": false, "text": "int x = y * z;\n int x = y*z;\n int a = b*c + d*e;\n int a = b * c + d * e;\n" }, { "answer_id": 376100, "author": "Mr. Shiny and New 安宇", "author_id": 7867, "author_profile": "https://Stackoverflow.com/users/7867", "pm_score": 2, "selected": false, "text": "String sql = \"SELECT * FROM USERS WHERE ID = ? AND NAME = ? AND IS_DELETED = 'N'\";\n String sql = \n \"SELECT * \" +\n \"FROM USERS \" + \n \"WHERE ID = ? \" + \n \" AND NAME = ? \" +\n \" AND IS_DELETED = 'N'\";\n if(x=1) print(\"blah\"); else print(\"eep!\");\n if (x = 1) {\n print(\"blah\");\n} else {\n print(\"eep!\");\n}\n" }, { "answer_id": 11445171, "author": "xuhdev", "author_id": 1150462, "author_profile": "https://Stackoverflow.com/users/1150462", "pm_score": 2, "selected": false, "text": ".editorconfig" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3333/" ]
284,269
<p>If I have an xmlreader instance how can I use it to read its current node and end up with a xmlElement instance?</p>
[ { "answer_id": 284406, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 4, "selected": true, "text": "XmlDocument XmlDocument doc = new XmlDocument();\n doc.Load(reader);\n XmlElement el = doc.DocumentElement;\n doc.LoadXml(reader.ReadOuterXml());\n using (XmlReader subReader = reader.ReadSubtree())\n {\n XmlDocument doc = new XmlDocument();\n doc.Load(subReader);\n XmlElement el = doc.DocumentElement;\n }\n" }, { "answer_id": 284580, "author": "Sunny Milenov", "author_id": 8220, "author_profile": "https://Stackoverflow.com/users/8220", "pm_score": 2, "selected": false, "text": "XmlElement myElement;\nmyXmlReader.Read();\nif (myXmlReader.NodeType == XmlNodeType.Element)\n{\n myElement = doc.CreateElement(myXmlReader.Name);\n myElement.InnerXml = myXmlReader.InnerXml;\n}\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1946/" ]
284,285
<p>I have a GPS from u-blox.com with a USB-connection and driver. The driver installs a virual COM port that pops up when you plug the USB in. Using a hyperterminal I can then watch the flow of data from the GPS.</p> <p>Then I want the data in my program, not so easy...</p> <p>I have implemented some methods using the serialPort class to read from the GPS, but am unsuccessful. I have programmed several serial device readers and writers before in C#, but this one stops me.</p> <p>As an example, the simple code in <a href="http://csharp.simpleserial.com/" rel="nofollow noreferrer">simpleSerial</a> will not give you anything unless you unplug and replug the USB.</p> <p>Have tried reading it with matlab, which works great, but as the rest of my program that needs the GPS data is in c#, that doesn't quite fix the problem.</p> <p>Is there some high level C# things going on in the serialPort class that I can circumvent? Or is there any known problems reading USB-serialports, which I assume works like my GPS?</p>
[ { "answer_id": 286098, "author": "Jon Norton", "author_id": 4797, "author_profile": "https://Stackoverflow.com/users/4797", "pm_score": -1, "selected": false, "text": "SerialPort.WriteLine \\r\\n \\n SerialPort.Write \\n" }, { "answer_id": 593450, "author": "Dan McClain", "author_id": 53587, "author_profile": "https://Stackoverflow.com/users/53587", "pm_score": 0, "selected": false, "text": " public static byte ReadByte()\n {\n byte byteRead = new byte();\n SerialPort port = new SerialPort(\"COM3\", 9600, Parity.None, 8, StopBits.One);\n port.Open();\n int byteValue = port.ReadByte();\n port.Close();\n\n byteRead = Convert.ToByte(byteValue);\n\n return byteRead;\n }\n\n public static void SendByte(byte packet)\n {\n SerialPort port = new SerialPort(\"COM3\", 9600, Parity.None, 8, StopBits.One);\n port.Open();\n byte[] writeByte = new byte[1];\n writeByte[0] = packet;\n port.Write(writeByte, 0, 1);\n port.Close();\n }\n" }, { "answer_id": 1337491, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "byte[] data = new byte[]{0xB5, 0x62, 0x06, 0x04, 0x04, 0x00,\n 0x00, 0x00, 0x00, 0x00, 0x0E, 0x64}; \nsp.Write(data, 0, data.Length);\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284285", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36927/" ]
284,310
<p>We're using Infragistics grid (most probably, we'll have 8.2 version at the end) and we want to configure row/cells appearances "on-demand" in order to be able to provide sort of "dynamic appearance".</p> <p>For example, I want some cell to be red or green, depending on its value. We might want to tweak other characteristics as well (font, size, image, etc).</p> <p>A perfect place to do it would be some event, that happen before a cell gets repainted... But it seems there is no such event in Infragistics...</p> <p>Or am I wrong? Any help?</p> <p><strong>Clarification:</strong> I'm talking about WinForms Infragistics UltraGrid</p>
[ { "answer_id": 284461, "author": "John Rudy", "author_id": 14048, "author_profile": "https://Stackoverflow.com/users/14048", "pm_score": 1, "selected": false, "text": "Paint Paint private void UltraGrid1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)\n{\n foreach (UltraGridRow r in UltraGrid1.Rows)\n {\n foreach (UltraGridCell c in r.Cells)\n {\n if (c.Text == \"foo\")\n c.Appearance.BackColor = Color.Green;\n }\n }\n}\n Private Sub UltraGrid1_Paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles UltraGrid1.Paint\n For Each r As UltraGridRow In UltraGrid1.Rows\n For Each c As UltraGridCell In r.Cells\n If c.Text = \"foo\" Then\n c.Appearance.BackColor = Color.Green\n End If\n Next\n Next\nEnd Sub\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284310", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2351099/" ]
284,321
<p>I have an application with 5 <code>UIViewController</code>s each inside a corresponding <code>UINavigationController</code>, all tucked inside a <code>UITabBarController</code> that displays 5 tabs at the bottom of the screen.</p> <p>I want to display another <code>UIViewController</code> (inside a <code>UINavigationController</code>) when a dialog button is pressed.</p> <p>This view should only be loaded and unloaded programatically; i.e. it should not appear in the tab bar. However, I want the tab bar to be visible always.</p> <p>If I add the <code>[UINavigationController view]</code> to <code>[self window]</code> the <code>UITabBar</code> is covered. If I add it to any other layer, the <code>UINavigationController</code> adds on the compensation it has for the status bar so appears further down than expected.</p> <p>A solution would be to have the 6th <code>UINavigationController</code> added to the <code>UITabBar</code> with the others, but with its <code>tabBarItem</code> hidden. Then I can show it and hide it using the <code>tabBar</code>s <code>selectedIndex</code> property.</p> <p>Accessing the <code>tabBarItem</code> through the <code>UIViewController</code> shows no obvious way of doing this.</p> <hr> <p>@wisequark, I think you completely misunderstood and you have almost rewritten the architecture of my application. However I have a separate navigation controller for each view as they are mutually exclusive and there is no concept of "drilling down".</p> <p>@Kendall, This is what I expect I will have to do - have the modal view appear with a hide button to bring back the normal interface. But it would be nice to keep the tab bar always visible, so I was just wondering if anyone knew of a way.</p>
[ { "answer_id": 284711, "author": "wisequark", "author_id": 33159, "author_profile": "https://Stackoverflow.com/users/33159", "pm_score": 4, "selected": false, "text": "UINavigationController UITabBarController UINavigationController UIViewController UINavigationController UITabBarController" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33604/" ]
284,324
<p>How can I generate valid XML in C#?</p>
[ { "answer_id": 284331, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 10, "selected": true, "text": "XmlSerializer XDocument XmlWriter XDocument Console.WriteLine(\n new XElement(\"Foo\",\n new XAttribute(\"Bar\", \"some & value\"),\n new XElement(\"Nested\", \"data\")));\n XmlDocument XmlDocument doc = new XmlDocument();\nXmlElement el = (XmlElement)doc.AppendChild(doc.CreateElement(\"Foo\"));\nel.SetAttribute(\"Bar\", \"some & value\");\nel.AppendChild(doc.CreateElement(\"Nested\")).InnerText = \"data\";\nConsole.WriteLine(doc.OuterXml);\n XmlDocument XDocument XmlWriter XmlWriter writer = XmlWriter.Create(Console.Out);\nwriter.WriteStartElement(\"Foo\");\nwriter.WriteAttributeString(\"Bar\", \"Some & value\");\nwriter.WriteElementString(\"Nested\", \"data\");\nwriter.WriteEndElement();\n XmlSerializer [Serializable]\npublic class Foo\n{\n [XmlAttribute]\n public string Bar { get; set; }\n public string Nested { get; set; }\n}\n...\nFoo foo = new Foo\n{\n Bar = \"some & value\",\n Nested = \"data\"\n};\nnew XmlSerializer(typeof(Foo)).Serialize(Console.Out, foo);\n XmlSerializer IXmlSerializable XmlSerializer" }, { "answer_id": 1365017, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": " <xs:element name=\"RootElement\">\n <xs:complexType>\n <xs:sequence>\n <xs:element name=\"Element1\" type=\"xs:string\" />\n <xs:element name=\"Element2\" type=\"xs:string\" />\n </xs:sequence>\n <xs:attribute name=\"Attribute1\" type=\"xs:integer\" use=\"optional\" />\n <xs:attribute name=\"Attribute2\" type=\"xs:boolean\" use=\"required\" />\n </xs:complexType>\n </xs:element>\n RootElement rootElement = new RootElement;\nrootElement.Element1 = \"Element1\";\nrootElement.Element2 = \"Element2\";\nrootElement.Attribute1 = 5;\nrootElement.Attribute2 = true;\n RootElement rootElement = RootElement.Load(filePath);\n rootElement.Save(string);\nrootElement.Save(textWriter);\nrootElement.Save(xmlWriter);\n rootElement.Untyped" }, { "answer_id": 1767005, "author": "Vincent", "author_id": 215034, "author_profile": "https://Stackoverflow.com/users/215034", "pm_score": 5, "selected": false, "text": "new XElement(\"Foo\",\n from s in nameValuePairList\n select\n new XElement(\"Bar\",\n new XAttribute(\"SomeAttr\", \"SomeAttrValue\"),\n new XElement(\"Name\", s.Name),\n new XElement(\"Value\", s.Value)\n )\n );\n" }, { "answer_id": 4409887, "author": "swdev", "author_id": 427793, "author_profile": "https://Stackoverflow.com/users/427793", "pm_score": 2, "selected": false, "text": "<music judul=\"Kupu-Kupu yang Lucu\" pengarang=\"Ibu Sud\" tempo=\"120\" birama=\"4/4\" nadadasar=\"1=F\" biramapembilang=\"4\" biramapenyebut=\"4\">\n <not angka=\"1\" oktaf=\"0\" naikturun=\"\" nilai=\"1\"/>\n <not angka=\"2\" oktaf=\"0\" naikturun=\"\" nilai=\"0.5\"/>\n <not angka=\"5\" oktaf=\"1\" naikturun=\"/\" nilai=\"0.25\"/>\n <not angka=\"2\" oktaf=\"0\" naikturun=\"\\\" nilai=\"0.125\"/>\n <not angka=\"1\" oktaf=\"0\" naikturun=\"\" nilai=\"0.0625\"/>\n</music>\n private void saveToolStripMenuItem_Click(object sender, EventArgs e)\n {\n saveFileDialog1.Title = \"Save Song File\";\n saveFileDialog1.Filter = \"Song Files|*.xsong\";\n if (saveFileDialog1.ShowDialog() == DialogResult.OK)\n {\n FileStream fs = new FileStream(saveFileDialog1.FileName, FileMode.Create);\n XmlTextWriter w = new XmlTextWriter(fs, Encoding.UTF8);\n w.WriteStartDocument();\n w.WriteStartElement(\"music\");\n w.WriteAttributeString(\"judul\", Program.music.getTitle());\n w.WriteAttributeString(\"pengarang\", Program.music.getAuthor());\n w.WriteAttributeString(\"tempo\", Program.music.getTempo()+\"\");\n w.WriteAttributeString(\"birama\", Program.music.getBirama());\n w.WriteAttributeString(\"nadadasar\", Program.music.getNadaDasar());\n w.WriteAttributeString(\"biramapembilang\", Program.music.getBiramaPembilang()+\"\");\n w.WriteAttributeString(\"biramapenyebut\", Program.music.getBiramaPenyebut()+\"\");\n\n for (int i = 0; i < listNotasi.Count; i++)\n {\n CNot not = listNotasi[i];\n w.WriteStartElement(\"not\");\n w.WriteAttributeString(\"angka\", not.getNot() + \"\");\n w.WriteAttributeString(\"oktaf\", not.getOktaf() + \"\");\n String naikturun=\"\";\n if(not.isTurunSetengah())naikturun=\"\\\\\";\n else if(not.isNaikSetengah())naikturun=\"/\";\n w.WriteAttributeString(\"naikturun\",naikturun);\n w.WriteAttributeString(\"nilai\", not.getNilaiNot()+\"\");\n w.WriteEndElement();\n }\n w.WriteEndElement();\n\n w.Flush();\n fs.Close();\n }\n\n }\n openFileDialog1.Title = \"Open Song File\";\nopenFileDialog1.Filter = \"Song Files|*.xsong\";\nif (openFileDialog1.ShowDialog() == DialogResult.OK)\n{\n FileStream fs = new FileStream(openFileDialog1.FileName, FileMode.Open);\n XmlTextReader r = new XmlTextReader(fs);\n\n while (r.Read())\n {\n if (r.NodeType == XmlNodeType.Element)\n {\n if (r.Name.ToLower().Equals(\"music\"))\n {\n Program.music = new CMusic(r.GetAttribute(\"judul\"),\n r.GetAttribute(\"pengarang\"),\n r.GetAttribute(\"birama\"),\n Convert.ToInt32(r.GetAttribute(\"tempo\")),\n r.GetAttribute(\"nadadasar\"),\n Convert.ToInt32(r.GetAttribute(\"biramapembilang\")),\n Convert.ToInt32(r.GetAttribute(\"biramapenyebut\")));\n }\n else\n if (r.Name.ToLower().Equals(\"not\"))\n {\n CNot not = new CNot(Convert.ToInt32(r.GetAttribute(\"angka\")), Convert.ToInt32(r.GetAttribute(\"oktaf\")));\n if (r.GetAttribute(\"naikturun\").Equals(\"/\"))\n {\n not.setNaikSetengah();\n }\n else if (r.GetAttribute(\"naikturun\").Equals(\"\\\\\"))\n {\n not.setTurunSetengah();\n }\n not.setNilaiNot(Convert.ToSingle(r.GetAttribute(\"nilai\")));\n listNotasi.Add(not);\n }\n }\n else\n if (r.NodeType == XmlNodeType.Text)\n {\n Console.WriteLine(\"\\tVALUE: \" + r.Value);\n }\n }\n}\n\n}\n}\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19020/" ]
284,325
<p>Suppose I have a process which spawns exactly one child process. Now when the parent process exits for whatever reason (normally or abnormally, by kill, ^C, assert failure or anything else) I want the child process to die. How to do that correctly?</p> <hr> <p>Some similar question on stackoverflow:</p> <ul> <li>(asked earlier) <a href="https://stackoverflow.com/questions/269494/how-can-i-cause-a-child-process-to-exit-when-the-parent-does">How can I cause a child process to exit when the parent does?</a></li> <li>(asked later) <a href="https://stackoverflow.com/questions/395877/are-child-processes-created-with-fork-automatically-killed-when-the-parent-is-k">Are child processes created with fork() automatically killed when the parent is killed?</a></li> </ul> <hr> <p>Some similar question on stackoverflow for <strong>Windows</strong>: </p> <ul> <li><a href="https://stackoverflow.com/questions/53208/how-do-i-automatically-destroy-child-processes-in-windows">How do I automatically destroy child processes in Windows?</a> </li> <li><a href="https://stackoverflow.com/questions/3342941/kill-child-process-when-parent-process-is-killed">Kill child process when parent process is killed</a></li> </ul>
[ { "answer_id": 284353, "author": "Alnitak", "author_id": 6782, "author_profile": "https://Stackoverflow.com/users/6782", "pm_score": 3, "selected": false, "text": "SIGKILL prctl(2)" }, { "answer_id": 284443, "author": "qrdl", "author_id": 28494, "author_profile": "https://Stackoverflow.com/users/28494", "pm_score": 9, "selected": true, "text": "SIGHUP PR_SET_PDEATHSIG prctl() prctl(PR_SET_PDEATHSIG, SIGHUP); man 2 prctl" }, { "answer_id": 285134, "author": "dmckee --- ex-moderator kitten", "author_id": 2509, "author_profile": "https://Stackoverflow.com/users/2509", "pm_score": 5, "selected": false, "text": "fork()" }, { "answer_id": 285334, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 1, "selected": false, "text": "exit() _exit() _Exit() exit() setsid() setpgrp()" }, { "answer_id": 4054436, "author": "Phil Rutschman", "author_id": 491530, "author_profile": "https://Stackoverflow.com/users/491530", "pm_score": 5, "selected": false, "text": "int pipes[2];\npipe(pipes)\nif (fork() == 0) {\n close(pipes[1]); /* Close the writer end in the child*/\n dup2(pipes[0], STDIN_FILENO); /* Use reader end as stdin (fixed per  maxschlepzig */\n exec(\"sh -c 'set -o monitor; child_process & read dummy; kill %1'\")\n}\n\nclose(pipes[0]); /* Close the reader end in the parent */\n" }, { "answer_id": 6484903, "author": "neoneye", "author_id": 78336, "author_profile": "https://Stackoverflow.com/users/78336", "pm_score": 4, "selected": false, "text": "void noteProcDeath(\n CFFileDescriptorRef fdref, \n CFOptionFlags callBackTypes, \n void* info) \n{\n // LOG_DEBUG(@\"noteProcDeath... \");\n\n struct kevent kev;\n int fd = CFFileDescriptorGetNativeDescriptor(fdref);\n kevent(fd, NULL, 0, &kev, 1, NULL);\n // take action on death of process here\n unsigned int dead_pid = (unsigned int)kev.ident;\n\n CFFileDescriptorInvalidate(fdref);\n CFRelease(fdref); // the CFFileDescriptorRef is no longer of any use in this example\n\n int our_pid = getpid();\n // when our parent dies we die as well.. \n LOG_INFO(@\"exit! parent process (pid %u) died. no need for us (pid %i) to stick around\", dead_pid, our_pid);\n exit(EXIT_SUCCESS);\n}\n\n\nvoid suicide_if_we_become_a_zombie(int parent_pid) {\n // int parent_pid = getppid();\n // int our_pid = getpid();\n // LOG_ERROR(@\"suicide_if_we_become_a_zombie(). parent process (pid %u) that we monitor. our pid %i\", parent_pid, our_pid);\n\n int fd = kqueue();\n struct kevent kev;\n EV_SET(&kev, parent_pid, EVFILT_PROC, EV_ADD|EV_ENABLE, NOTE_EXIT, 0, NULL);\n kevent(fd, &kev, 1, NULL, 0, NULL);\n CFFileDescriptorRef fdref = CFFileDescriptorCreate(kCFAllocatorDefault, fd, true, noteProcDeath, NULL);\n CFFileDescriptorEnableCallBacks(fdref, kCFFileDescriptorReadCallBack);\n CFRunLoopSourceRef source = CFFileDescriptorCreateRunLoopSource(kCFAllocatorDefault, fdref, 0);\n CFRunLoopAddSource(CFRunLoopGetMain(), source, kCFRunLoopDefaultMode);\n CFRelease(source);\n}\n" }, { "answer_id": 8392158, "author": "Thorbiörn Fritzon", "author_id": 1082388, "author_profile": "https://Stackoverflow.com/users/1082388", "pm_score": 1, "selected": false, "text": "kill(0, 2); /* SIGINT */\n (cat && kill 0) | python\n \"Terminated\"" }, { "answer_id": 8408293, "author": "alex K", "author_id": 1084542, "author_profile": "https://Stackoverflow.com/users/1084542", "pm_score": -1, "selected": false, "text": "check_parent () {\n parent=`ps -f|awk '$2=='$PID'{print $3 }'`\n echo \"parent:$parent\"\n let parent=$parent+0\n if [[ $parent -eq 1 ]]; then\n echo \"parent is dead, exiting\"\n exit;\n fi\n}\n\n\nPID=$$\ncnt=0\nwhile [[ 1 = 1 ]]; do\n check_parent\n ... something\ndone\n" }, { "answer_id": 14210887, "author": "jasterm007", "author_id": 1429607, "author_profile": "https://Stackoverflow.com/users/1429607", "pm_score": 1, "selected": false, "text": "prctl(PR_SET_PDEATHSIG, SIGHUP) execv Runtime.getRuntime().halt(0) ps waitpid" }, { "answer_id": 15377350, "author": "Cong Ma", "author_id": 418374, "author_profile": "https://Stackoverflow.com/users/418374", "pm_score": 3, "selected": false, "text": "kqueue socketpair() SOCK_STREAM fork() poll() POLLIN close() POLLHUP #include <unistd.h>\n#include <stdlib.h>\n#include <sys/types.h>\n#include <sys/socket.h>\n#include <poll.h>\n#include <stdio.h>\n\nint main(int argc, char ** argv)\n{\n int sv[2]; /* sv[0] for parent, sv[1] for child */\n socketpair(AF_UNIX, SOCK_STREAM, 0, sv);\n\n pid_t pid = fork();\n\n if ( pid > 0 ) { /* parent */\n close(sv[1]);\n fprintf(stderr, \"parent: pid = %d\\n\", getpid());\n sleep(100);\n exit(0);\n\n } else { /* child */\n close(sv[0]);\n fprintf(stderr, \"child: pid = %d\\n\", getpid());\n\n struct pollfd mon;\n mon.fd = sv[1];\n mon.events = POLLIN;\n\n poll(&mon, 1, -1);\n if ( mon.revents & POLLHUP )\n fprintf(stderr, \"child: parent hung up\\n\");\n exit(0);\n }\n}\n ./a.out & SIGPIPE write() unix(7) unix(4) poll(2) socketpair(2) socket(7)" }, { "answer_id": 16660458, "author": "user2168915", "author_id": 2168915, "author_profile": "https://Stackoverflow.com/users/2168915", "pm_score": 3, "selected": false, "text": "pit_t pid = getpid();\nswitch (fork())\n{\n case -1:\n {\n abort(); /* or whatever... */\n }\n default:\n {\n /* parent */\n exit(0);\n }\n case 0:\n {\n /* child */\n /* ... */\n }\n}\n\n/* Wait for parent to exit */\nwhile (getppid() != pid)\n ;\n" }, { "answer_id": 20212799, "author": "osexp2003", "author_id": 2293666, "author_profile": "https://Stackoverflow.com/users/2293666", "pm_score": 0, "selected": false, "text": "\n var childProc = require('child_process').spawn('tail', ['-f', '/dev/null'], {stdio:'ignore'});\n\n var counter=0;\n setInterval(function(){\n console.log('c '+(++counter));\n },1000);\n\n if (process.platform.slice(0,3) != 'win') {\n function killMeAndChildren() {\n /*\n * On Linux/Unix(Include Mac OS X), kill (-pid) will kill process group, usually\n * the process itself and children.\n * On Windows, an JOB object has been applied to current process and children,\n * so all children will be terminated if current process dies by anyway.\n */\n console.log('kill process group');\n process.kill(-process.pid, 'SIGKILL');\n }\n\n /*\n * When you use \"kill pid_of_this_process\", this callback will be called\n */\n process.on('SIGTERM', function(err){\n console.log('SIGTERM');\n killMeAndChildren();\n });\n }\n\n \n var pty = require('pty.js');\n\n //var term =\n pty.spawn('any_child_process', [/*any arguments*/], {\n name: 'xterm-color',\n cols: 80,\n rows: 30,\n cwd: process.cwd(),\n env: process.env\n });\n /*optionally you can install data handler\n term.on('data', function(data) {\n process.stdout.write(data);\n });\n term.write(.....);\n */\n\n" }, { "answer_id": 23401172, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 4, "selected": false, "text": "int p[2];\npipe(p);\npid_t child = fork();\nif (child == 0) {\n close(p[1]); // close write end of pipe\n setpgid(0, 0); // prevent ^C in parent from stopping this process\n child = fork();\n if (child == 0) {\n close(p[0]); // close read end of pipe (don't need it here)\n exec(...child process here...);\n exit(1);\n }\n read(p[0], 1); // returns when parent exits for any reason\n kill(child, 9);\n exit(1);\n}\n def run(*args):\n (r, w) = os.pipe()\n child = os.fork()\n if child == 0:\n os.close(w)\n os.setpgid(0, 0)\n child = os.fork()\n if child == 0:\n os.close(r)\n os.execl(args[0], *args)\n os._exit(1)\n os.read(r, 1)\n os.kill(child, 9)\n os._exit(1)\n os.close(r)\n" }, { "answer_id": 36945270, "author": "maxschlepzig", "author_id": 427158, "author_profile": "https://Stackoverflow.com/users/427158", "pm_score": 5, "selected": false, "text": "#include <sys/prctl.h> // prctl(), PR_SET_PDEATHSIG\n#include <signal.h> // signals\n#include <unistd.h> // fork()\n#include <stdio.h> // perror()\n\n// ...\n\npid_t ppid_before_fork = getpid();\npid_t pid = fork();\nif (pid == -1) { perror(0); exit(1); }\nif (pid) {\n ; // continue parent execution\n} else {\n int r = prctl(PR_SET_PDEATHSIG, SIGTERM);\n if (r == -1) { perror(0); exit(1); }\n // test in case the original parent exited just\n // before the prctl() call\n if (getppid() != ppid_before_fork)\n exit(1);\n // continue child execution ...\n prctl() prctl() execve() pid_t pid = fork();\nif (pid == -1) { perror(0); exit(1); }\nif (pid) {\n ; // continue parent execution\n} else {\n int r = prctl(PR_SET_PDEATHSIG, SIGTERM);\n if (r == -1) { perror(0); exit(1); }\n // test in case the original parent exited just\n // before the prctl() call\n if (getppid() == 1)\n exit(1);\n // continue child execution ...\n init prctl(PR_SET_CHILD_SUBREAPER, 1)" }, { "answer_id": 40238654, "author": "Ido Ran", "author_id": 355401, "author_profile": "https://Stackoverflow.com/users/355401", "pm_score": 0, "selected": false, "text": "Runtime.getRuntime().addShutdownHook InterruptedException private void startWebpackDevServer() {\n String cmd = isWindows() ? \"cmd /c gradlew webPackStart\" : \"gradlew webPackStart\";\n logger.info(\"webpack dev-server \" + cmd);\n\n Thread thread = new Thread(() -> {\n\n ProcessBuilder pb = new ProcessBuilder(cmd.split(\" \"));\n pb.redirectOutput(ProcessBuilder.Redirect.INHERIT);\n pb.redirectError(ProcessBuilder.Redirect.INHERIT);\n pb.directory(new File(\".\"));\n\n Process process = null;\n try {\n // Start the node process\n process = pb.start();\n\n // Wait for the node process to quit (blocking)\n process.waitFor();\n\n // Ensure the node process is killed\n process.destroyForcibly();\n System.setProperty(WEBPACK_SERVER_PROPERTY, \"true\");\n } catch (InterruptedException | IOException e) {\n // Ensure the node process is killed.\n // InterruptedException is thrown when the main process exit.\n logger.info(\"killing webpack dev-server\", e);\n if (process != null) {\n process.destroyForcibly();\n }\n }\n\n });\n\n thread.start();\n}\n" }, { "answer_id": 42666785, "author": "Luis Colorado", "author_id": 3899431, "author_profile": "https://Stackoverflow.com/users/3899431", "pm_score": 0, "selected": false, "text": "init(8) exit(2) getppid(2) init(2) init exit exit(2) 1 1 getppid(2) getppid(2) fork(2) getppid(2) parent id only changes once, when its parent does an call, so this should be enough to check if the result changed between calls to see that parent process has exit. This test is not valid for the actual children of the init process, because they are always children of" }, { "answer_id": 47680888, "author": "Omnifarious", "author_id": 167958, "author_profile": "https://Stackoverflow.com/users/167958", "pm_score": 2, "selected": false, "text": "SIGKILL CAP_SYS_ADMIN" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9403/" ]
284,336
<p>My colleague has written a DLL which drives Excel.<br /> When I reference his DLL in my .NET app, I get a warning:</p> <pre><code>The dependency 'Microsoft.Office.Interop.Excel' could not be found. </code></pre> <p>My app will compile.<br /> However, when I get to the bit that uses my colleague's DLL to access Excel, an exception is thrown, with the message above.</p> <p>We should have identical setups: <strong>Windows XP Pro SP3, VS2003, .NET 1.1, Office 2003</strong></p> <p>My problem seems similar to <a href="https://stackoverflow.com/questions/224181/net-microsoftofficeinteropexcel-and-interopexcel-dll">this question</a>, but I don't know if it's the same.</p> <p>Any help or suggestions gratefully received!</p> <h2>Update:</h2> <p>Thanks for answers so far!</p> <p>I have not added an explicit reference to <code>Microsoft.Office.Interop.Excel</code>.<br /> Surely I shouldn't have to?<br /> <strong>However</strong>: When I tried to add this reference, I cannot find <code>Microsoft.Office.Interop.Excel</code> in the Add Reference dialog.</p> <p>Presumably this means that I am missing a DLL?<br /> ... But I don't understand how that could happen?!</p> <h2>Update (fixed):</h2> <p>@ConcernedOfTunbridgeWells has the answer that fixed this for me: installing the Primary Interop Assemblies.</p>
[ { "answer_id": 284355, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 2, "selected": false, "text": "Microsoft.Office.Interop.Excel" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7211/" ]
284,358
<p>When serializing/de-serializing certain classes I've come across the need to flag or mark certain properties as CDATA elements (due to their content). I am currently handling this like so:</p> <pre><code> &lt;XmlElement("MessageText")&gt; _ Public Property XmlContentLeft() As XmlCDataSection Get Dim doc As New XmlDataDocument() Dim cd As XmlCDataSection = doc.CreateCDataSection(Me.MessageText) Return cd End Get Set(ByVal value As XmlCDataSection) Me.MessageText = value.Value End Set End Property &lt;XmlIgnore()&gt; _ Public Property MessageText() As String Get Return _messageText End Get Set(ByVal value As String) _messageText= value End Set End Property </code></pre> <p>Now while this works great it has drawbacks -- I now have duplicate properties for anything I want to be a CDATA element and I have to write extra code for these properties.</p> <p>So my question is whether or not there is a better way to do this? I don't want to have to write custom schemas or serialization routines for each class. In an ideal scenario I'd be able to add an attribute to these properties so they are automatically treated as CDATA elements. </p>
[ { "answer_id": 284456, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 3, "selected": true, "text": "<XmlElement(\"MessageText\")> _\nPublic Property XmlContentLeft() As XmlCDataSection\n Get\n return GetCData(Me.MessageText)\n End Get\n Set(ByVal value As XmlCDataSection)\n Me.MessageText = value.Value\n End Set\nEnd Property\n\n' this method is re-usable by any property that needs CData\nPrivate Function GetCData(ByVal value As String) As XmlCDataSection\n Static doc As New XmlDataDocument() \n return doc.CreateCDataSection(value)\nEnd Function\n\n<XmlIgnore()> _\nPublic Property MessageText() As String\n Get\n Return _messageText\n End Get\n Set(ByVal value As String)\n _messageText= value\n End Set\nEnd Property\n Static Static" }, { "answer_id": 3890019, "author": "James Close", "author_id": 470183, "author_profile": "https://Stackoverflow.com/users/470183", "pm_score": 1, "selected": false, "text": "Imports System.Xml.Serialization\nImports System.Xml\n<Serializable()> _\nPublic Class XmlCDataString\n Implements IXmlSerializable\n\n Private _strValue As String = Nothing\n\n Public Sub New()\n\n End Sub\n\n Public Sub New(ByVal strValue As String)\n _strValue = strValue\n End Sub\n\n Public Property StringValue() As String\n Get\n Return _strValue\n End Get\n Set(ByVal value As String)\n _strValue = value\n End Set\n End Property\n\n Public Shared Widening Operator CType(ByVal strValue As String) As XmlCDataString\n Return New XmlCDataString(strValue)\n End Operator\n\n Public Shared Narrowing Operator CType(ByVal cdata As XmlCDataString) As String\n Return cdata.StringValue\n End Operator\n\n Public Function GetSchema() As System.Xml.Schema.XmlSchema Implements System.Xml.Serialization.IXmlSerializable.GetSchema\n Throw New NotImplementedException\n End Function\n\n Public Sub ReadXml(ByVal reader As System.Xml.XmlReader) Implements System.Xml.Serialization.IXmlSerializable.ReadXml\n ' TODO\n End Sub\n\n Public Sub WriteXml(ByVal writer As System.Xml.XmlWriter) Implements System.Xml.Serialization.IXmlSerializable.WriteXml\n Dim doc As XmlDocument\n Dim xmlCData As XmlCDataSection\n Dim serializer As XmlSerializer\n\n doc = New XmlDataDocument()\n xmlCData = doc.CreateCDataSection(_strValue)\n serializer = New XmlSerializer(GetType(XmlCDataSection))\n serializer.Serialize(writer, xmlCData)\n\n End Sub\nEnd Class\n Private _messageText As XmlCDataString \n\nPublic Property MessageText() As XmlCDataString \n Get \n Return _messageText \n End Get \n Set(ByVal value As XmlCDataString) \n _messageText= value \n End Set \nEnd Property \n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12842/" ]
284,364
<p>What's the easiest and most robust way of altering the .NET DateTimePicker control, to allow users to enter <code>null</code> values?</p>
[ { "answer_id": 284386, "author": "splattne", "author_id": 6461, "author_profile": "https://Stackoverflow.com/users/6461", "pm_score": 4, "selected": true, "text": "Value Null DateTime.MinValue MinValue MaxValue public class NullableDateTimePicker : System.Windows.Forms.DateTimePicker\n{\n private DateTimePickerFormat originalFormat = DateTimePickerFormat.Short;\n private string originalCustomFormat;\n private bool isNull;\n\n public new DateTime Value\n {\n get => isNull ? DateTime.MinValue : base.Value;\n set\n {\n // incoming value is set to min date\n if (value == DateTime.MinValue)\n {\n // if set to min and not previously null, preserve original formatting\n if (!isNull)\n {\n originalFormat = this.Format;\n originalCustomFormat = this.CustomFormat;\n isNull = true;\n }\n\n this.Format = DateTimePickerFormat.Custom;\n this.CustomFormat = \" \";\n }\n else // incoming value is real date\n {\n // if set to real date and previously null, restore original formatting\n if (isNull)\n {\n this.Format = originalFormat;\n this.CustomFormat = originalCustomFormat;\n isNull = false;\n }\n\n base.Value = value;\n }\n }\n }\n\n protected override void OnCloseUp(EventArgs eventargs)\n {\n // on keyboard close, restore format\n if (Control.MouseButtons == MouseButtons.None)\n {\n if (isNull)\n {\n this.Format = originalFormat;\n this.CustomFormat = originalCustomFormat;\n isNull = false;\n }\n }\n base.OnCloseUp(eventargs);\n }\n\n protected override void OnKeyDown(KeyEventArgs e)\n {\n base.OnKeyDown(e);\n\n // on delete key press, set to min value (null)\n if (e.KeyCode == Keys.Delete)\n {\n this.Value = DateTime.MinValue;\n }\n }\n}\n" }, { "answer_id": 1762980, "author": "Jan Obrestad", "author_id": 214557, "author_profile": "https://Stackoverflow.com/users/214557", "pm_score": 6, "selected": false, "text": "DateTimePicker ShowCheckBox true Checked" }, { "answer_id": 33031322, "author": "Eduard", "author_id": 5421874, "author_profile": "https://Stackoverflow.com/users/5421874", "pm_score": 0, "selected": false, "text": "ShowCheckBox true private void dateTimePicker1_ValueChanged(object sender, EventArgs e)\n{\n DateTimePicker thisDateTimePicker = (DateTimePicker)sender;\n if (thisDateTimePicker.Checked == false)\n {\n thisDateTimePicker.CustomFormat = @\" \"; //space\n thisDateTimePicker.Format = DateTimePickerFormat.Custom;\n }\n else\n {\n thisDateTimePicker.Format = DateTimePickerFormat.Short;\n }\n}\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18071/" ]
284,365
<p>I'm trying to determine what situations MySQL updates an index. Say I have the following table:</p> <pre><code>CREATE TABLE MyTable ( ID INT NOT NULL AUTO_INCREMENT, MyIndexedColumn VARCHAR NOT NULL, MyNonIndexedColumn VARCHAR, PRIMARY KEY (ID), INDEX MyNewIndex(MyIndexedColumn) ) </code></pre> <p>Then I run the following SQL to insert a row:</p> <pre><code>INSERT INTO MyTable (MyIndexedColumn, MyNonIndexedColumn) VALUES ('MyTestValue', 'MyTestValue'); </code></pre> <p>I understand that this query will add some sort of hash key to a B-Tree index in MySQL for the value 'MyTestValue'.</p> <p>Now, if I run the following statement, will that force that B-Tree index to be updated, even if I haven't changed the value of the column?</p> <pre><code>UPDATE MyTable SET MyIndexedColumn = 'MyTestValue', MyNonIndexedColumn = 'A New Value' WHERE ID = 1; </code></pre> <p>Is MySQL smart enough to determine that? Or by just making that column part of the update statement, am I telling MySQL that possibly something has changed, and it should do the work to update the index?</p>
[ { "answer_id": 287880, "author": "Ezran", "author_id": 32883, "author_profile": "https://Stackoverflow.com/users/32883", "pm_score": 3, "selected": false, "text": "10k updates of an indexed column with a new value:\nA: 76.8 seconds\nB: 126.7 seconds\n\n10k updates of a non-indexed column with a new value:\nA: 27.6 seconds\nB: 22.0 seconds\n\n10k updates of a random column with its same value:\nA: 1.4 seconds\nB: 1.2 seconds\n\n10k updates of a random column with an incremented value:\nA: 12.2 seconds\nB: 50.0 seconds\n\n10k updates of an indexed column=>same value, non-indexed column=>new value:\nA: 7.0 seconds\nB: 10.5 seconds\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/650/" ]
284,368
<p>I'm trying to bind one of my model objects to the fields of a form, using Spring-MVC. Everything works fine, except that one of the attributes of the model object is an unordered collection. Doing something like</p> <pre><code> &lt;c:forEach items="${m.items}" var="i" varStatus="itemsRow"&gt; &lt;form:input path="items[${itemsRow.index}]"/&gt; &lt;/c:forEach&gt; &lt;form:errors path="items" /&gt; </code></pre> <p>would work fine for a List-type property, but for a Set throws an error when, upon submit, it tries to bind input field content to object attributes.</p> <p>Is there something in Spring that works out of the box with Sets?</p>
[ { "answer_id": 284549, "author": "zmf", "author_id": 13285, "author_profile": "https://Stackoverflow.com/users/13285", "pm_score": 1, "selected": false, "text": " <c:forEach items=\"${items}\" var=\"i\" varStatus=\"itemsRow\">\n <input name=\"items[${itemsRow.index}].fieldName\" type=\"text\"/>\n </c:forEach>\n <form:errors path=\"items\" />\n" }, { "answer_id": 5732918, "author": "Deejay", "author_id": 534804, "author_profile": "https://Stackoverflow.com/users/534804", "pm_score": -1, "selected": false, "text": " public final class LeaderboardConverter extends JsonDeserializer<Leaderboard> implements Converter<String, Leaderboard>\n {\n public Leaderboard convert(String source) throws IllegalArgumentException\n {\n Leaderboard activity = new Leaderboard();\n activity.setId(new Integer(source));\n return activity;\n }\n\n\n public Leaderboard deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException\n {\n return convert(jp.getText());\n }\n\n}\n" }, { "answer_id": 13084828, "author": "sab", "author_id": 218480, "author_profile": "https://Stackoverflow.com/users/218480", "pm_score": 2, "selected": false, "text": "private List someList = LazyList.decorate(new ArrayList(), FactoryUtils.instantiateFactory(com.abc.xyz.SomeClass.class));\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6069/" ]
284,370
<p>I'm trying to return all the child nodes of a set of navigation nodes in sharepoint, the SDK implies I should be doing something like this:</p> <pre><code>NodeColl = objSite.Navigation.TopNavigationBar Dim Node as SPNavigationNode For Each Node In NodeColl if Node.IsVisible then Response.Write("&lt;siteMapNode url=""" &amp; Node.Url &amp; """ title=""" &amp; Node.Title &amp; """ description=""" &amp; Node.Title &amp; """ &gt;" &amp; Environment.NewLine) Dim SubChildNodes as SPNavigationNodeCollection = Node.Children Response.Write(SubChildNodes.Count) 'returns 0 always even though I know theres over 20 nodes in some of the sections Dim ChildNode as SPNavigationNode For Each ChildNode in SubChildNodes if ChildNode.IsVisible then Response.Write("&lt;siteMapNode url=""" &amp; ChildNode.Url &amp; """ title=""" &amp; ChildNode.Title &amp; """ description=""" &amp; ChildNode.Title &amp; """ /&gt;" &amp; Environment.NewLine) End if Next Response.Write("&lt;/siteMapNode&gt;" &amp; Environment.NewLine) End If Next </code></pre> <p>however whenever I do, it lists the top level navigation nodes but I cannot get the children to be displayed.</p>
[ { "answer_id": 284549, "author": "zmf", "author_id": 13285, "author_profile": "https://Stackoverflow.com/users/13285", "pm_score": 1, "selected": false, "text": " <c:forEach items=\"${items}\" var=\"i\" varStatus=\"itemsRow\">\n <input name=\"items[${itemsRow.index}].fieldName\" type=\"text\"/>\n </c:forEach>\n <form:errors path=\"items\" />\n" }, { "answer_id": 5732918, "author": "Deejay", "author_id": 534804, "author_profile": "https://Stackoverflow.com/users/534804", "pm_score": -1, "selected": false, "text": " public final class LeaderboardConverter extends JsonDeserializer<Leaderboard> implements Converter<String, Leaderboard>\n {\n public Leaderboard convert(String source) throws IllegalArgumentException\n {\n Leaderboard activity = new Leaderboard();\n activity.setId(new Integer(source));\n return activity;\n }\n\n\n public Leaderboard deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException\n {\n return convert(jp.getText());\n }\n\n}\n" }, { "answer_id": 13084828, "author": "sab", "author_id": 218480, "author_profile": "https://Stackoverflow.com/users/218480", "pm_score": 2, "selected": false, "text": "private List someList = LazyList.decorate(new ArrayList(), FactoryUtils.instantiateFactory(com.abc.xyz.SomeClass.class));\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2208/" ]
284,382
<p>G'day!</p> <p>I have one million different words which I'd like to query for in a table with 15 million rows. The result of synonyms together with the word is getting processed after each query.</p> <p>table looks like this:</p> <pre><code> synonym word --------------------- ancient old anile old centenarian old darkened old distant far remote far calm gentle quite gentle </code></pre> <p>This is how it is done in Java currently:</p> <pre><code>.... PreparedStatement stmt; ResultSet wordList; ResultSet syns; ... stmt = conn.prepareStatement("select distinct word from table"); wordList = stmt.executeQuery(); while (wordList.next()) { stmt = conn.prepareStatement("select synonym from table where word=?"); stmt.setString(1, wordList.getString(1)); syns = stmt.executeQuery(); process(syns, wordList.getString(1)); } ... </code></pre> <p>This is incredible slow. What's the fastest way to do stuff like this?</p> <p>Cheers, Chris</p>
[ { "answer_id": 284399, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 3, "selected": true, "text": "select synonym from table where word in (select distinct word from table)\n process word process word select word, synonym \nfrom table \norder by word\n" }, { "answer_id": 284416, "author": "configurator", "author_id": 9536, "author_profile": "https://Stackoverflow.com/users/9536", "pm_score": 2, "selected": false, "text": "select word, synonym from table order by word" }, { "answer_id": 284424, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": 1, "selected": false, "text": "PreparedStatement stmt;\nResultSet syns;\n...\n\nstmt = conn.prepareStatement(\"select distinct \" + \n \" sy.synonm \" + \n \"from \" +\n \" table sy \" +\n \" table wd \" +\n \"where sy.word = wd.word\");\nsyns = stmt.executeQuery();\nprocess(syns);\n" }, { "answer_id": 284520, "author": "chris", "author_id": 36942, "author_profile": "https://Stackoverflow.com/users/36942", "pm_score": 0, "selected": false, "text": "....\nStatement stmt;\nResultSet rs;\nString currentWord;\nHashSet<String> syns = new HashSet<String>();\n...\n\nstmt = conn.createStatement();\nrs = stmt.executeQuery(select word, synonym from table order by word);\n\nrs.next();\ncurrentWord = rs.getString(1);\nsyns.add(rs.getString(2));\n\nwhile (rs.next()) {\n if (rs.getString(1) != currentWord) {\n process(syns, currentWord);\n syns.clear();\n currentWord = rs.getString(1);\n }\n syns.add(rs.getString(2));\n}\n...\n" }, { "answer_id": 285096, "author": "John Gardner", "author_id": 13687, "author_profile": "https://Stackoverflow.com/users/13687", "pm_score": 1, "selected": false, "text": "while (wordList.next()) {\n stmt = conn.prepareStatement(\"select synonym from table where word=?\");\n stmt.setString(1, wordList.getString(1));\n syns = stmt.executeQuery();\n\n process(syns, wordList.getString(1));\n}\n stmt = conn.prepareStatement(\"select synonym from table where word=?\");\nwhile (wordList.next()) {\n stmt.setString(1, wordList.getString(1));\n syns = stmt.executeQuery();\n\n process(syns, wordList.getString(1));\n}\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36942/" ]
284,385
<p>I wrote a small PHP application that I'd like to distribute. I'm looking for best practices so that it can be installed on most webhosts with minimal hassle.</p> <p>Briefly: It's simple tool that lets people download files once they login with a password.</p> <p>So my questions are:</p> <p>1) How should I handle configuration values? I'm not using a database, so a configuration file seems appropriate. I know that other php apps (e.g. Wordpress) use defines, but they are global and there is potential that the names will conflict. (Global variables also have the same problem, obviously.) I looked at the "ini" file mechanism built into PHP. It only allows comments at the top - so you can't annotate each setting easily - and you can't validate syntax with "php -f". Other options?</p> <p>2) How to handle templating? The application needs to pump out a form. Possibly with an error message. (e.g. "Sorry, wrong password.") I've have a class variable with the HTML form, but also allow an external template file to be used instead (specified in the config). I do some trivial search and replace - e.g. %SCRIPT% to the name of the script, %STATUS% to hold the error message. This feels a bit like reinventing the wheel, but including a templating system like Smarty is overkill. (Plus they may already have a templating system.) Other options?</p> <p>3) i18n - There are only 3 message strings, and gettext doesn't seem to be universally installed. Is it such a bad idea just to make these three strings parameters in the config file?</p> <p>4) How to best integrate with other frameworks? My app is a single class. So, I thought I could just include a php script that showed how the class was called. It would be a starting point for people who had to integrate it into another framework, but also be fine as-is for those not interested in customizing. Reasonable?</p> <p>5) GET/POST parameters - Is it bad form for a class to be looking at $_GET and $_POST? Should all values be passed into my class during construction?</p> <p>Thanks.</p>
[ { "answer_id": 284481, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": 2, "selected": false, "text": "<?php ... ?> <?php echo \"...\"?> <? ... ?> <?= \"...\" ?>" }, { "answer_id": 284533, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": true, "text": "<?php\nreturn array(\n 'option1' =&gt; 'foobar',\n 'option2' =&gt; 123,\n //and so on...\n );\n?>\n $config = (array) include 'path/to/config/file';\n" }, { "answer_id": 285797, "author": "Kornel", "author_id": 27009, "author_profile": "https://Stackoverflow.com/users/27009", "pm_score": 1, "selected": false, "text": "<?php function_exists() @missing_function() php.ini ini_get() magic_quotes" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284385", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18158/" ]
284,389
<p>I'm using <a href="http://sourceforge.net/projects/nusoap/" rel="nofollow noreferrer">nusoap</a> to connect to a soap webservice. The xml that the class sends to the service is constructed from an array, ie:</p> <pre><code>$params = array("param1" =&gt; "value1", "param2" =&gt; "value1"); $client-&gt;call('HelloWorld', $params, 'namespace', 'SOAPAction'); </code></pre> <p>This works fine. A multidimensional array also constructs a nice nested xml message. </p> <p>I encounter a problem when i need two tags with the same name:</p> <pre><code>&lt;items&gt; &lt;item&gt;value 1&lt;/item&gt; &lt;item&gt;value 2&lt;/item&gt; &lt;/item&gt; $params = array("items" =&gt; array("item" =&gt; "value 1", "item" =&gt; "value 2")); </code></pre> <p>The second item in the array overwrites the first which results in:</p> <pre><code>&lt;items&gt; &lt;item&gt;value 2&lt;/item&gt; &lt;/item&gt; </code></pre> <p>How can achieve this?</p>
[ { "answer_id": 284436, "author": "Powerlord", "author_id": 15880, "author_profile": "https://Stackoverflow.com/users/15880", "pm_score": 2, "selected": false, "text": "$test_array = array(\"item\" => \"value 1\", \"item\" => \"value 2\");\n $params = array(\"items\" => array(\"item\" => array(\"value 1\", \"value 2\")));\n" }, { "answer_id": 284492, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 1, "selected": false, "text": "$x = array(\"items\" => array(\"item\" => \"value 1\", \"item\" => \"value 2\")); \nvar_dump($x);\n\narray(1) {\n [\"items\"]=>\n array(1) {\n [\"item\"]=>\n string(7) \"value 2\"\n }\n}\n $x = array(); \n $x['items'] = array(); \n $x['items']['item']='value 1'; \n $x['items']['item']='value 2'; \n array(\"items\"=>array( \"value1\",\"value2\") ); \n array(\"items\"=>array(\"item\"=>array(\"value1\",\"value2\"))) \n $params = '<person xsi:type=\"tns:Person\"><firstname xsi:type=\"xsd:string\">Willi</firstname><age xsi:type=\"xsd:int\">22</age><gender xsi:type=\"xsd:string\">male</gender></person>';\n$result = $client->call('hello', $params);\n" }, { "answer_id": 406356, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "$params = array('items' => array('item' => array('value1', 'value2')))\n$client->call( 'action', $params );\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21238/" ]
284,394
<p>I am opening a XML file using .NET XmlReader and saving the file in another filename and it seems that the DOCTYPE declaration changes between the two files. While the newly saved file is still valid XML, I was wondering why it insisted on changing original tags.</p> <pre><code>Dim oXmlSettings As Xml.XmlReaderSettings = New Xml.XmlReaderSettings() oXmlSettings.XmlResolver = Nothing oXmlSettings.CheckCharacters = False oXmlSettings.ProhibitDtd = False oXmlSettings.IgnoreWhitespace = True Dim oXmlDoc As XmlReader = XmlReader.Create(pathToOriginalXml, oXmlSettings) Dim oDoc As XmlDocument = New XmlDocument() oDoc.Load(oXmlDoc) oDoc.Save(pathToNewXml) </code></pre> <p>The following (in the original document):</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN" "http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd"&gt; </code></pre> <p>becomes (notice the [ ] characters at the end): </p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN" "http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd"[]&gt; </code></pre>
[ { "answer_id": 1070268, "author": "Maurice Flanagan", "author_id": 38791, "author_profile": "https://Stackoverflow.com/users/38791", "pm_score": 3, "selected": false, "text": " private class NullSubsetXmlTextWriter : XmlTextWriter\n {\n public NullSubsetXmlTextWriter(String inputFileName, Encoding encoding)\n : base(inputFileName, encoding)\n {\n }\n public override void WriteDocType(string name, string pubid, string sysid, string subset)\n {\n if (subset == String.Empty)\n {\n subset = null;\n }\n base.WriteDocType(name, pubid, sysid, subset);\n }\n }\n" }, { "answer_id": 58549158, "author": "parvez", "author_id": 12271066, "author_profile": "https://Stackoverflow.com/users/12271066", "pm_score": 0, "selected": false, "text": "writer.WriteDocType(\"Name\", Nothing, \n \"http://xml.cxml.org/schemas/cXML/1.2.033/Fulfill.dtd\", Nothing) \n Nothing" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1508/" ]
284,398
<p>i've found how to bind an asp:Menu to XML. i've found how to bind an asp:Menu to a site map (which is really binding it to XML). How do you bind an asp:Menu to a database?</p> <p>The .NET Framework provides multiple data sources:</p> <ul> <li><a href="http://msdn.microsoft.com/en-us/library/system.web.ui.hierarchicaldatasourcecontrol.aspx" rel="noreferrer">HierarchicalDataSourceControl</a></li> <li><ul> <li><a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.xmldatasource.aspx" rel="noreferrer">XmlDataSource</a></li> </ul></li> <li><ul> <li><a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.sitemapdatasource.aspx" rel="noreferrer">SiteMapDataSource</a></li> </ul></li> <li><a href="http://msdn.microsoft.com/en-us/library/system.web.ui.datasourcecontrol.aspx" rel="noreferrer">DataSourceControl</a></li> <li><ul> <li><a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.sqldatasource.aspx" rel="noreferrer">SqlDataSource</a></li> </ul></li> <li><ul> <li><a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.accessdatasource.aspx" rel="noreferrer">AccessDataSource</a></li> </ul></li> <li><ul> <li><a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.linqdatasource.aspx" rel="noreferrer">LinqDataSource</a></li> </ul></li> </ul> <p>i want to use one that represents data from an SQL Server table. The data is stored in the standard <a href="http://www.answers.com/hierarchical" rel="noreferrer">hierarchical</a> format that everyone uses:</p> <pre><code>NodeID ParentNodeID Caption Url ======== ============== ========= ================= {3234... {3632... stackoverflow http://stackov... {3632... (null) Questions ~/questions.aspx {3233... (null) Tags ~/tags.aspx {3235... {3632... google http://www.goo... </code></pre> <p>And the query to return all the rows would be:</p> <pre><code>SELECT * FROM Nodes </code></pre> <p>What is the secret method that Microsoft intended me to use to mash that data into an asp:Menu?</p> <hr> <p><strong>Update:</strong> There is a good article on aspalliance.com: <a href="http://aspalliance.com/822" rel="noreferrer">Building a Database Driven Hierarchical Menu using ASP.NET 2.0</a>. Unfortunatly it describes how to perform XML data binding; while i'm interested in database binding.</p>
[ { "answer_id": 284410, "author": "splattne", "author_id": 6461, "author_profile": "https://Stackoverflow.com/users/6461", "pm_score": 3, "selected": false, "text": "protected void LoadData()\n{\n DataSet ds = new DataSet();\n string connStr = YOUR_CONNECTION_STRING_HERE;\n using(SqlConnection conn = newSqlConnection(connStr))\n {\n string sql = \"Select NodeID, Caption, Url, ParentID from Menu\";\n SqlDataAdapter da = newSqlDataAdapter(sql, conn);\n da.Fill(ds);\n da.Dispose();\n }\n ds.DataSetName = \"Menus\";\n ds.Tables[0].TableName = \"Menu\";\n DataRelation relation = newDataRelation(\"ParentChild\",\n ds.Tables[\"Menu\"].Columns[\"NodeID\"],\n ds.Tables[\"Menu\"].Columns[\"ParentID\"], true);\n\n relation.Nested = true;\n ds.Relations.Add(relation);\n\n xmlDataSource.Data = ds.GetXml();\n}\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284398", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12597/" ]
284,418
<p>I'm using system catalog views such as SYS.ALL_ OBJECTS, SYS.FOREIGN_KEYS etc. to get information about my database structure in MS SQL 2005. </p> <p>Are there equivalent functions/views for MySQL (v. 5) servers? </p>
[ { "answer_id": 284589, "author": "Nelson Miranda", "author_id": 1130097, "author_profile": "https://Stackoverflow.com/users/1130097", "pm_score": 4, "selected": true, "text": "SELECT * FROM information_schema.SCHEMATA S;\n SELECT * FROM information_schema.TABLE_CONSTRAINTS T;\n SELECT * FROM information_schema.CHARACTER_SETS C;\nSELECT * FROM information_schema.COLLATION_CHARACTER_SET_APPLICABILITY C;\nSELECT * FROM information_schema.COLLATIONS C;\nSELECT * FROM information_schema.COLUMN_PRIVILEGES C;\nSELECT * FROM information_schema.`COLUMNS` C;\nSELECT * FROM information_schema.KEY_COLUMN_USAGE K;\nSELECT * FROM information_schema.PROFILING P;\nSELECT * FROM information_schema.ROUTINES R;\nSELECT * FROM information_schema.SCHEMA_PRIVILEGES S; \nSELECT * FROM information_schema.STATISTICS S;\nSELECT * FROM information_schema.TABLE_PRIVILEGES T;\nSELECT * FROM information_schema.`TABLES` T;\nSELECT * FROM information_schema.TRIGGERS T;\nSELECT * FROM information_schema.USER_PRIVILEGES U;\nSELECT * FROM information_schema.VIEWS V;\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2899/" ]
284,420
<p>I would like to add a backcolor for specific line depending of a Property of the object binded.</p> <p>The solution I have (and it works) is to use the Event <code>DataBindingComplete</code> but I do not think it's the best solution.</p> <p>Here is the event:</p> <pre><code> private void myGrid_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e) { for (int i = 0; i &lt; this.myGrid.Rows.Count; i++) { if((this.myGrid.Rows[i].DataBoundItem as MyObject).Special) { this.myGrid.Rows[i].DefaultCellStyle.BackColor = Color.FromArgb(240, 128, 128); } } } </code></pre> <p>Any other option that would be better?</p>
[ { "answer_id": 284470, "author": "John", "author_id": 30006, "author_profile": "https://Stackoverflow.com/users/30006", "pm_score": 1, "selected": false, "text": "if(((MyObject)e.Item.DataItem).Special)\n e.Item.DefaultCellStyle.BackColor = Color.FromArgb(240, 128, 128);\n" }, { "answer_id": 284672, "author": "Juanma", "author_id": 3730, "author_profile": "https://Stackoverflow.com/users/3730", "pm_score": 4, "selected": true, "text": "dataGridView1.RowPostPaint += OnRowPostPaint;\n\nvoid OnRowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)\n{\n MyObject value = (MyObject) dataGridView1.Rows[e.RowIndex].DataBoundItem;\n DataGridViewCellStyle style = dataGridView1.Rows[e.RowIndex].DefaultCellStyle;\n\n // Do whatever you want with style and value\n ....\n}\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284420", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13913/" ]
284,422
<p>I am a new user of Extjs library, I created a grid successfully and it works just fine, now I want to use Ext.grid.GridFilters to add filtering to my grid, however I don't see this class in the Extjs source code files, where I can get the required files?</p>
[ { "answer_id": 48125182, "author": "Sachet Patil", "author_id": 4331748, "author_profile": "https://Stackoverflow.com/users/4331748", "pm_score": 0, "selected": false, "text": "store.filterBy(function(rec, id)) { return (rec.get(\"RecName\") ==\"FilterRecord\");}\n store.clearFilter();\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284422", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22449/" ]
284,428
<p>Objective-C 2.0 gave us @properties.</p> <ul> <li>They allow for introspection.</li> <li>They allow for declarative programming.</li> <li>The @synthesize and @dynamic mechanisms relieve use from having to write repetitive, stock accessors.</li> <li>Finally, there is the ‘dot’ property syntax, which some love, and some hate.</li> </ul> <p>That isn't what I'm hear to ask. Like any new feature, there is an initially tendency to want to use @property everywhere. So where is property use appropriate?</p> <p>Clearly in model objects, attributes and relationships are good fodder for properties.</p> <pre><code>@property(...) NSString *firstName; @property(...) NSString *lastName; @property(...) Person *parent; </code></pre> <p>Even synthesized/computed attributes seem like a good use case for properties.</p> <pre><code>@property(...) NSString *fullName; </code></pre> <p>Where else have you used properties? Where have you used them, then later decided it was an inappropriate use of the feature?</p> <p>Do you use properties for your private object attributes?</p> <p>Can you think of any examples of things which aren't properties in Cocoa, which at first look, seem like they might want to be properties, but after closer inspection, are actual an example of abuse or property-itis?</p>
[ { "answer_id": 284689, "author": "wisequark", "author_id": 33159, "author_profile": "https://Stackoverflow.com/users/33159", "pm_score": 3, "selected": false, "text": "@interface @interface MyObject()\n\n@property(retain) NSArray *myArray;\n\n@end\n" }, { "answer_id": 284818, "author": "benzado", "author_id": 10947, "author_profile": "https://Stackoverflow.com/users/10947", "pm_score": 3, "selected": false, "text": "if (foobar.weight > 100) {\n goober.capacity = foobar.weight;\n}\n foobar.weight int w = [foobar computeWeight];\nif (w > 100) {\n goober.capacity = w;\n}\n computeWeight" }, { "answer_id": 298767, "author": "Marc Charbonneau", "author_id": 35136, "author_profile": "https://Stackoverflow.com/users/35136", "pm_score": 0, "selected": false, "text": "stringValue" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
284,433
<p>The type 'x' is defined in an assembly that is not referenced. You must add a reference to assembly 'abc123'.</p> <p>I have a .NET 2.0 web application that references my assembly 'abc123'. The assembly exists in the GAC and I've verified that it is the correct(same) version. The rest of application has no issues except for one .aspx page. The page in question has a repeater that displays a user control as one of its "fields". Upon binding a list of type y to the repeater I pass the user control a list of type x (a property of y) as shown here:</p> <pre><code>&lt;uc1:usercontrol id="ucusercontrol " runat="server" myPublicUserControlProperty='&lt;%#Eval("CollectionOfX") %&gt;'/&gt; </code></pre> <p>On the user control's property set, I bind the list of type x to a gridview in the user control.</p> <p>One strange thing to note is that this report works fine on my development pc but not on any servers once I deploy. My pc is Windows XP, IIS6, VS2005. The servers are Windows Server 2003, IIS6.</p> <p>I hope I explained that well enough. Thanks in advance for any insight you can provide.</p>
[ { "answer_id": 285059, "author": "Aaron Daniels", "author_id": 37064, "author_profile": "https://Stackoverflow.com/users/37064", "pm_score": 6, "selected": true, "text": "<assemblies>\n <add assembly=\"MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=[MyPublicKeyToken]\"/> \n</assemblies>\n" }, { "answer_id": 9532190, "author": "Charbarred", "author_id": 1223918, "author_profile": "https://Stackoverflow.com/users/1223918", "pm_score": 1, "selected": false, "text": "type x App_Code" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36970/" ]
284,468
<p>How come the following doesn't work?</p> <pre><code>CREATE FUNCTION Test (@top integer) RETURNS TABLE AS RETURN SELECT TOP @top * FROM SomeTable GO </code></pre> <p>I just want to be able to be able to specify the number of results to be returned. [SQL Server 2000.]</p> <p>Thanks!</p>
[ { "answer_id": 284561, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 4, "selected": true, "text": "CREATE FUNCTION Test (@top integer)\n\nRETURNS TABLE\n\nAS\n\nSET ROWCOUNT @top\n\nRETURN SELECT * FROM SomeTable\n" }, { "answer_id": 284563, "author": "Jason Slocomb", "author_id": 34895, "author_profile": "https://Stackoverflow.com/users/34895", "pm_score": 0, "selected": false, "text": "SET ROWCOUNT { number | @number_var }\nArguments\n\nnumber | @number_var\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10675/" ]
284,472
<p>I have a base page, BasePage, that raises an event that displays messages to the user. Works great on all pages derived from BasePage. I want to do the same thing from user controls, but they don't inherit from BasePage. </p> <p>What I want is a central place that I can call from anywhere and in that code it will raise an event. Where is a good place to put this code:</p> <pre><code> public void DisplayMessage(string message) { RaiseEvent(new MessageNotificationEventArgs(MessageNotificationEvent, message)); } </code></pre> <p>so that I can call it from anywhere? RaiseEvent is in the UIElement class, so it needs to go somewhere that is a UIElement.</p>
[ { "answer_id": 284561, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 4, "selected": true, "text": "CREATE FUNCTION Test (@top integer)\n\nRETURNS TABLE\n\nAS\n\nSET ROWCOUNT @top\n\nRETURN SELECT * FROM SomeTable\n" }, { "answer_id": 284563, "author": "Jason Slocomb", "author_id": 34895, "author_profile": "https://Stackoverflow.com/users/34895", "pm_score": 0, "selected": false, "text": "SET ROWCOUNT { number | @number_var }\nArguments\n\nnumber | @number_var\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3047/" ]
284,475
<p>I need to style a table to have rounded corners.</p> <p>I'm just looking at how best to go about it:</p> <p>Normally when I style a div to have rounded corners, I use 2 divs with empty comments at the top and bottom, and apply sizing &amp; background image CSS to them.</p> <p>The table, however, has internal borders, so I'd have to carefully align the vertical lines in the corner bg images, to match with the true cell borders. </p> <p>Is this clear so far?</p> <p>So I was wondering how others would approach this. I think the best thing I can do is to just use one complete fixed size background image, borders and all, and overlay a borderless table on top. The table will always be the same size after all.</p> <p>Can anyone think of a better way? </p>
[ { "answer_id": 284497, "author": "Eduardo Molteni", "author_id": 2385, "author_profile": "https://Stackoverflow.com/users/2385", "pm_score": 1, "selected": false, "text": "<html>\n<head>\n <style>\n\n\n .cell1 {background: #f8f8f8 url(images/cell1.gif) no-repeat left top; height: 10px; font-size: 1px;}\n .cell2 {background: #f8f8f8 url(images/cell2.gif) repeat-x top; height: 10px; font-size: 1px; border-right: solid 1px #c3c2c2; font-weight:bold; }\n .cell3 {background: #f8f8f8 url(images/cell3.gif) no-repeat right top; height: 10px; font-size: 1px;}\n\n .cell4 {background: white url(images/cell4.gif) repeat-y left; border-bottom: solid 1px #c3c2c2; width: 13px; }\n .cell5 {background-color: #f8f8f8; padding: 5px; border-right: solid 1px #c3c2c2; font-weight:bold; border-bottom: solid 1px #c3c2c2; }\n .cell6 {background: white url(images/cell6.gif) repeat-y right; border-bottom: solid 1px #c3c2c2; width: 18px; }\n\n .cell7 {background: white url(images/cell7.gif) repeat-y left; width: 13px;}\n .cell8 {background-color: white; padding: 5px; border-right: solid 1px #c3c2c2; font-weight:normal; }\n .cell9 {background: white url(images/cell9.gif) repeat-y right; width: 18px;}\n\n\n .cell10 {background: white url(images/cell10.gif) no-repeat left bottom; height: 17px;font-size: 1px; }\n .cell11 {background: white url(images/cell11.gif) repeat-x bottom; border-right: solid 1px #c3c2c2; height: 17px; font-size: 1px; }\n .cell12 {background: white url(images/cell12.gif) no-repeat right bottom; height: 17px;font-size: 1px; }\n\n .lastcolumn, th.lastcolumn, td.lastcolumn {border-right: solid 0px #c3c2c2; }\n\n </style>\n</head>\n<body>\n\n\n<table id=\"pricing\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">\n <thead>\n <tr>\n <th class=\"cell1\"></th>\n <th class=\"cell2\">&nbsp;</th>\n <th class=\"cell2\">&nbsp;</th>\n <th class=\"cell2\">&nbsp;</th>\n <th class=\"cell2\">&nbsp;</th>\n <th class=\"cell2\">&nbsp;</th>\n <th class=\"cell2 lastcolumn\">&nbsp;</th>\n <th class=\"cell3\"></th>\n </tr>\n <tr>\n <th class=\"cell4\">&nbsp;</th>\n <th class=\"cell5\">Incoming calls</th>\n <th class=\"cell5\">National calls</th>\n <th class=\"cell5\">Calls to US &amp; Canada</th>\n <th class=\"cell5\">Calls to other Phones</th>\n <th class=\"cell5\">Calls to other Countries</th>\n <th class=\"cell5 lastcolumn\">SMS text messages</th>\n <th class=\"cell6\">&nbsp;</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td class=\"cell7\"></td>\n <td class=\"cell8\">Select</td>\n <td class=\"cell8\">country</td>\n <td class=\"cell8\">from</td>\n <td class=\"cell8\">dropdown</td>\n <td class=\"cell8\">list</td>\n <td class=\"cell8 lastcolumn\">above</td>\n <td class=\"cell9\"></td>\n </tr>\n <tr>\n <td class=\"cell10\"></td>\n <td class=\"cell11\">&nbsp;</td>\n <td class=\"cell11\">&nbsp;</td>\n <td class=\"cell11\">&nbsp;</td>\n <td class=\"cell11\">&nbsp;</td>\n <td class=\"cell11\">&nbsp;</td>\n <td class=\"cell11 lastcolumn\">&nbsp;</td>\n <td class=\"cell12\"></td>\n </tr>\n </tbody>\n</table>\n\n\n</body>\n</html>\n" }, { "answer_id": 284537, "author": "Andrew G. Johnson", "author_id": 428190, "author_profile": "https://Stackoverflow.com/users/428190", "pm_score": 1, "selected": false, "text": "table id=\"pricing\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">\n <thead>\n <tr>\n <th>Incoming calls</th>\n <th>National calls</th>\n <th>Calls to US &amp; Canada</th>\n <th>Calls to other Phones</th>\n <th>Calls to other Countries</th>\n <th>SMS text messages</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>Select</td>\n <td>country</td>\n <td>from</td>\n <td>dropdown</td>\n <td>list</td>\n <td>above</td>\n </tr>\n </tbody>\n</table>\n #pricing thead\n {\n background-image:url(\"images/pricing_top.gif\");\n background-position:top;\n background-repeat:no-repeat;\n padding:10px 0 0 /* replace 10px with the height of pricing_top.gif */\n }\n\n #pricing th\n {\n background-image:url(\"images/pricing_header_bg.gif\");\n background-repeat:repeat-y;\n border-bottom:1px solid #c3c2c2;\n width:100px /* replace 100px with the width of pricing_header_bg.gif */\n }\n\n #pricing tbody\n {\n background-image:url(\"images/pricing_bottom.gif\");\n background-position:bottom;\n background-repeat:no-repeat;\n padding:0 0 10px /* replace 10px with the height of pricing_bottom.gif */\n }\n\n #pricing td\n {\n background-image:url(\"images/pricing_cell_bg.gif\");\n background-repeat:repeat-y;\n width:100px /* replace 100px with the width of pricing_cell_bg.gif */\n }\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284475", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26107/" ]
284,491
<p>I have an assembly that may be used by more than one process at a time. If I am using a static class, would the multiple processes all use the same "instance" of that class? </p> <p>Since the processes are separate, would these be running under difference Application Domains, hence have the static "instances" separate? </p> <p>The pudding in the details here is that the assembly is being used by a custom BizTalk adapter that my be set to process the messages in parallel batches. That is what I am calling "multiple processes" above. </p>
[ { "answer_id": 284505, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 5, "selected": true, "text": "Monitor lock" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284491", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1048/" ]
284,500
<p>So here's my current code:</p> <pre><code>List&lt;string&gt; rowGroups = GetFileGroups((int)row.Cells["document_security_type"].Value); bool found = false; System.Security.Principal.WindowsPrincipal p = new System.Security.Principal.WindowsPrincipal(System.Security.Principal.WindowsIdentity.GetCurrent()); foreach (string group in rowGroups) { if (p.IsInRole(group)) { found = true; break; } } </code></pre> <p>This was done a couple of months ago by someone and I'm having difficulty grasping why its not working. The company has recently just moved from one domain name to another. So I was curious to what domain controller the p.IsInRole("String") function will use. I'm assuming its going to use the default DC by whatever the computer is using.</p> <p>The odd item is that the computers in the office where this is running could be on 2 seperate domains. In the <code>List&lt;string&gt;</code> object, i've got both domains possible. so it could contain items such as "domainA\groupA", "domainA\userB", domainB\groupC", and/or "domainB\userD".</p> <p>So my major problem is that the IsInRole function is never returning true. i know it should, i even tested it with domainA\Domain users and still get a false returned.</p> <p>Any ideas? changing the code is possible, but not wanted. i'm not 100% i can even compile it...</p>
[ { "answer_id": 284505, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 5, "selected": true, "text": "Monitor lock" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21828/" ]
284,511
<p>When trying to invoke a method on an external webservice (over the Internet) it throws me "The remote server returned an error: (407) Proxy Authentication Required."</p> <p>To solve this, I used the following code to set the proxy we use in the office:</p> <pre><code>//Set the system proxy with valid server address or IP and port. System.Net.WebProxy pry = new System.Net.WebProxy("MyHost", 8080); //The DefaultCredentials automically get username and password. pry.Credentials = System.Net.CredentialCache.DefaultCredentials; System.Net.WebRequest.DefaultWebProxy = pry; </code></pre> <p>That works fine, but now... I need to do that "less harcoded" trying to get the information from my system instead of setting that manually. </p>
[ { "answer_id": 284544, "author": "John", "author_id": 30006, "author_profile": "https://Stackoverflow.com/users/30006", "pm_score": 2, "selected": true, "text": "Services.MyService service = new Services.MyService();\nservice.UseDefaultCredentials = true;\nservice.Proxy = new System.Net.WebProxy();\nservice.Proxy.Credentials = service.Credentials;\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7720/" ]
284,514
<p>What is a git topic branch? Does it differ from an ordinary branch in some way? Are there any branches that are not topic branches?</p>
[ { "answer_id": 284817, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 8, "selected": true, "text": "git fetch git pull" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18103/" ]
284,519
<p>I am trying to store a large amount of boolean information that is determined at run-time. I was wondering what the best method might be.</p> <p>I have currently been trying to allocate the memory using: </p> <p><code>pStatus = malloc((&lt;number of data points&gt;/8) + 1);</code> </p> <p>thinking that this will give me enough bits to work with. I could then reference each boolean value using the pointer in array notation:</p> <p><code>pStatus[element]</code></p> <p>Unfortunately this does not seem to be working very well. First, I am having difficulty initializing the memory to the integer value <code>0</code>. Can this be done using <code>memset()</code>? Still, I don't think that is impacting why I crash when trying to access <code>pStatus[element]</code>. </p> <p>I am also not entirely convinced that this approach is the best one to be using. What I really want is essentially a giant bitmask that reflects the status of the boolean values. Have I missed something?</p>
[ { "answer_id": 284536, "author": "Ana Betts", "author_id": 5728, "author_profile": "https://Stackoverflow.com/users/5728", "pm_score": 3, "selected": false, "text": "pStatus[element]\n pStatus[element/8] & (1 << (element % 8))\n" }, { "answer_id": 284541, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 0, "selected": false, "text": " pStatus = malloc((<number of data points>/8) + 1);\n pStatus[element]\n pStatus[element / 8 ] \n" }, { "answer_id": 284547, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 2, "selected": false, "text": "pStatus[element >> 3] |= 1 << (element & 7);\n pStatus[element >> 3] &= ~1 << (element & 7);\n if (pStatus[element >> 3] & (1 << (element & 7)) != 0)\n pstatus = malloc((<number of data points> + 7) / 8)\n" }, { "answer_id": 284548, "author": "The Archetypal Paul", "author_id": 21755, "author_profile": "https://Stackoverflow.com/users/21755", "pm_score": 6, "selected": true, "text": "pStatus = malloc((<number of data points>/8) + 1);\n pStatus[element]\n int get_bit(int element)\n{\n uint byte_index = element/8;\n uint bit_index = element % 8;\n uint bit_mask = ( 1 << bit_index);\n\n return ((pStatus[byte_index] & bit_mask) != 0);\n}\n\nvoid set_bit (int element)\n{\n uint byte_index = element/8;\n uint bit_index = element % 8;\n uint bit_mask = ( 1 << bit_index);\n\n pStatus[byte_index] |= bit_mask);\n}\n\nvoid clear_bit (int element)\n{\n uint byte_index = element/8;\n uint bit_index = element % 8;\n uint bit_mask = ( 1 << bit_index);\n\n pStatus[byte_index] &= ~bit_mask;\n}\n" }, { "answer_id": 284550, "author": "Rhythmic Fistman", "author_id": 22147, "author_profile": "https://Stackoverflow.com/users/22147", "pm_score": 0, "selected": false, "text": "c = malloc((N+7)/8) c[n/8]=((c[n/8] & ~(0x80 >> (n%8))) | (0x80>>(n%8)));\n c[n/8] &= ~(0x80 >> (n%8));\n if(c[n/8] & (0x80 >> (n%8))) blah();\n" }, { "answer_id": 284559, "author": "philant", "author_id": 18804, "author_profile": "https://Stackoverflow.com/users/18804", "pm_score": -1, "selected": false, "text": "set_bit() get_bit()" }, { "answer_id": 284658, "author": "eaanon01", "author_id": 36986, "author_profile": "https://Stackoverflow.com/users/36986", "pm_score": -1, "selected": false, "text": "typedef unsigned char BYTE;\ntypedef unsigned short WORD;\ntypedef unsigned long int DWORD;\ntypedef unsigned long long int DDWORD;\nenum STATUS\n{\n status0 = 0x01,\n status1 = 0x02,\n status2 = 0x04,\n status3 = 0x08,\n status4 = 0x10,\n status5 = 0x20,\n status6 = 0x40,\n status7 = 0x80,\nstatus_group = status0 + status1 +status4\n};\n#define GET_STATUS( S ) ( ((status.DDBuf&(DDWORD)S)==(DDWORD)S) ? 1 : 0 )\n#define SET_STATUS( S ) ( (status.DDBuf|= (DDWORD)S) )\n#define CLR_STATUS( S ) ( (status.DDBuf&= ~(DDWORD)S) )\nstatic union {\n BYTE BBuf[8];\n WORD WWBuf[4];\n DWORD DWBuf[2];\n DDWORD DDBuf;\n}status;\n\nint main(void)\n{\n // Reset status bits\n status.BBuf[0] = 0;\n printf( \"%d \\n\", GET_STATUS( status0 ) );\n\n SET_STATUS( status0 );\n printf( \"%d \\n\", GET_STATUS( status0 ) );\n\n CLR_STATUS(status0);\n printf( \"%d \\n\", GET_STATUS( status0 ) );\n SET_STATUS( status_group );\n printf( \"%d \\n\", GET_STATUS( status0 ) );\n system( \"pause\" );\n return 0;\n}\n" }, { "answer_id": 287442, "author": "unwind", "author_id": 28169, "author_profile": "https://Stackoverflow.com/users/28169", "pm_score": 2, "selected": false, "text": "#include <limits.h>\n CHAR_BIT char" }, { "answer_id": 307177, "author": "pauldoo", "author_id": 755, "author_profile": "https://Stackoverflow.com/users/755", "pm_score": 0, "selected": false, "text": "std::vector<bool>" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284519", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35767/" ]
284,538
<p>I am trying to access my WCF service on a server from my client console application for testing. I am getting the following error: </p> <blockquote> <p>The caller was not authenticated by the service</p> </blockquote> <p>I am using <code>wsHttpBinding</code>. I'm not sure what kind of authentication the service is expecting?</p> <p> <br> <br> </p> <pre><code>&lt;behaviors&gt; &lt;serviceBehaviors&gt; &lt;behavior name="MyTrakerService.MyTrakerServiceBehavior"&gt; &lt;!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment --&gt; &lt;serviceMetadata httpGetEnabled="true"/&gt; &lt;!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information --&gt; &lt;serviceDebug includeExceptionDetailInFaults="false"/&gt; &lt;/behavior&gt; &lt;/serviceBehaviors&gt; &lt;/behaviors&gt; </code></pre> <p></p> <p><b>Update</b> It works if I change my binding to <code>&lt;endpoint "basicHttpBinding" ... /&gt;</code> (from wsHttpBinding) on the IIS 7.0 hosted, windows 2008 server</p>
[ { "answer_id": 285062, "author": "Michael Kniskern", "author_id": 26327, "author_profile": "https://Stackoverflow.com/users/26327", "pm_score": 5, "selected": false, "text": "<bindings>\n <basicHttpBinding>\n <binding name=\"MyBasicHttpBinding\">\n <security mode=\"None\">\n <transport clientCredentialType=\"None\" />\n </security>\n </binding>\n </basicHttpBinding>\n</bindings>\n<services>\n <service behaviorConfiguration=\"MyServiceBehavior\" name=\"MyService\">\n <endpoint \n binding=\"basicHttpBinding\" \n bindingConfiguration=\"MyBasicHttpBinding\"\n name=\"basicEndPoint\" \n contract=\"IMyService\" \n />\n</service>\n" }, { "answer_id": 588440, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "svc.ClientCredentials.Windows.ClientCredential.UserName = \"abc\";\nsvc.ClientCredentials.Windows.ClientCredential.Password = \"xxx\";\n" }, { "answer_id": 1599200, "author": "kishore", "author_id": 193626, "author_profile": "https://Stackoverflow.com/users/193626", "pm_score": 2, "selected": false, "text": "ADTService.ServiceClient adtService = new ADTService.ServiceClient();\nadtService.ClientCredentials.Windows.ClientCredential.UserName=\"windowsuseraccountname\";\nadtService.ClientCredentials.Windows.ClientCredential.Password=\"windowsuseraccountpassword\";\nadtService.ClientCredentials.Windows.ClientCredential.Domain=\"windowspcname\";\n" }, { "answer_id": 19769280, "author": "Brian", "author_id": 1794167, "author_profile": "https://Stackoverflow.com/users/1794167", "pm_score": 1, "selected": false, "text": " Dim binding as System.ServiceModel.WSHttpBinding \n binding= New System.ServiceModel.WSHttpBinding(System.ServiceModel.SecurityMode.None)\n System.ServiceModel.WSHttpBinding binding\n binding = new System.ServiceModel.WSHttpBinding(System.ServiceModel.SecurityMode.None);\n" }, { "answer_id": 35668305, "author": "farhang67", "author_id": 2386925, "author_profile": "https://Stackoverflow.com/users/2386925", "pm_score": 0, "selected": false, "text": "<identity> \n<servicePrincipalName value=\"example.com\" />\n</identity>\n client.ClientCredentials.Windows.ClientCredential.Domain = \"example.com\";\n client.ClientCredentials.Windows.ClientCredential.UserName = \"UserName \";\n client.ClientCredentials.Windows.ClientCredential.Password = \"Password\";\n" }, { "answer_id": 51415733, "author": "Nani", "author_id": 2617906, "author_profile": "https://Stackoverflow.com/users/2617906", "pm_score": 0, "selected": false, "text": "wsHtppBinding security none basicHttpBinding <wsHttpBinding>\n <binding name=\"soapBinding\">\n <security mode=\"None\">\n <transport clientCredentialType=\"None\" />\n <message establishSecurityContext=\"false\" />\n </security>\n </binding>\n</wsHttpBinding>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284538", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
284,545
<p><code>Html.TextBox("ParentPassword", "", new { @class = "required" })</code></p> <p>what the gosh darned heck is the @ for the @class.</p>
[ { "answer_id": 284570, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": true, "text": "class" }, { "answer_id": 284574, "author": "yfeldblum", "author_id": 12349, "author_profile": "https://Stackoverflow.com/users/12349", "pm_score": 3, "selected": false, "text": "class class @ @class class @" }, { "answer_id": 284640, "author": "splattne", "author_id": 6461, "author_profile": "https://Stackoverflow.com/users/6461", "pm_score": 3, "selected": false, "text": "Dim [String] As String\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284545", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1220/" ]
284,556
<p>I am writing a lib and a demo project. The project doesn't care which version of the lib I use (I can use sdl, directx or whatever I like as the gfx backend). To get the object I do </p> <pre><code>Obj *obj = libname_newDevice(); </code></pre> <p>Now, should I use delete or should I do <code>obj-&gt;deleteMe();</code>? I ask because I am not exactly doing new so I shouldn't be doing the delete?</p> <p>I have <code>obj-&gt;create(theType);</code> which returns a class with the Obj interface. My real question is do I need a <code>libname_deleteDevice();</code> or is <code>obj-&gt;deleteMe()</code> fine since I have a deleteMe in the interface?</p>
[ { "answer_id": 284565, "author": "Jaywalker", "author_id": 382974, "author_profile": "https://Stackoverflow.com/users/382974", "pm_score": 4, "selected": false, "text": "libname_newDevice() libname_destroyDevice (obj)" }, { "answer_id": 284584, "author": "Serge Wautier", "author_id": 12379, "author_profile": "https://Stackoverflow.com/users/12379", "pm_score": 2, "selected": false, "text": "libname_newDevice() obj->DeleteMe() libname_Delete(obj) delete" }, { "answer_id": 284645, "author": "Charles Anderson", "author_id": 11677, "author_profile": "https://Stackoverflow.com/users/11677", "pm_score": 0, "selected": false, "text": "delete this;\n" }, { "answer_id": 284663, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 3, "selected": true, "text": "class ObjWrap\n{\n public:\n ObjWrap()\n :obj(libname_newDevice())\n {}\n ~ObjWrap()\n { libname_deleteDevice(obj);}\n private:\n ObjWrap(ObjWrap const&); // Dont copy\n void operator=(ObjWrap const&); // Dont copy\n Obj* obj;\n}; // If you want to copy then you need to extra work on ref counting\n // This may need some form of smart pointer.\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
284,558
<p>I have an existing Stored Procedure which I am trying to now call with LINQ to SQL, here is the stored procedure:</p> <pre><code>ALTER procedure [dbo].[sp_SELECT_Security_ALL] ( @UID Varchar(15) ) as DECLARE @A_ID int If ISNULL(@UID,'') = '' SELECT DISTINCT App_ID, App_Name, App_Description, DB, DBNameApp_ID, For_One_EVA_List_Ind From v_Security_ALL ELSE BEGIN Select @A_ID = (Select Assignee_ID From NEO.dbo.v_Assignees Where USER_ID = @UID and Inactive_Ind = 0) SELECT DISTINCT Security_User_ID, Security_Company, Security_MailCode, Security_Last_Name, Security_First_Name, Security_User_Name, Security_User_Info, Security_User_CO_MC, Security_Email_Addr, Security_Phone, Security_Security_Level, Security_Security_Desc, Security_Security_Comment, Security_Security_Inactive_Ind, App_ID, App_Name, App_Description, DB, DBNameApp_ID, For_One_EVA_List_Ind, @A_ID as Assignee_ID From v_Security_ALL Where Security_User_ID = @UID END </code></pre> <p>My problem is that the intellsense only sees the first set of return values in the IF statement and I can not access anything from the "else" part of my stored procedure. so when I try to do this:</p> <pre><code> var apps = dataContext.sp_SELECT_Security_ALL(userId); foreach (var app in apps) { string i = app. } </code></pre> <p>On the app. part the only available values I have there is the results of the the first Select distinct above.</p> <p>Is it possible to use LINQ with this type of stored procedure?</p>
[ { "answer_id": 284565, "author": "Jaywalker", "author_id": 382974, "author_profile": "https://Stackoverflow.com/users/382974", "pm_score": 4, "selected": false, "text": "libname_newDevice() libname_destroyDevice (obj)" }, { "answer_id": 284584, "author": "Serge Wautier", "author_id": 12379, "author_profile": "https://Stackoverflow.com/users/12379", "pm_score": 2, "selected": false, "text": "libname_newDevice() obj->DeleteMe() libname_Delete(obj) delete" }, { "answer_id": 284645, "author": "Charles Anderson", "author_id": 11677, "author_profile": "https://Stackoverflow.com/users/11677", "pm_score": 0, "selected": false, "text": "delete this;\n" }, { "answer_id": 284663, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 3, "selected": true, "text": "class ObjWrap\n{\n public:\n ObjWrap()\n :obj(libname_newDevice())\n {}\n ~ObjWrap()\n { libname_deleteDevice(obj);}\n private:\n ObjWrap(ObjWrap const&); // Dont copy\n void operator=(ObjWrap const&); // Dont copy\n Obj* obj;\n}; // If you want to copy then you need to extra work on ref counting\n // This may need some form of smart pointer.\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284558", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20748/" ]
284,566
<p>I'm creating an interface wrapper for a class. The member within the class is a reference(to avoid copying the large structure). If I create a private constructor, what is the best way to initialize that reference to appease the compiler?</p> <pre><code>struct InterfaceWrapper { InterfaceWrapper( SomeHugeStructure&amp; src ):m_internal(src){}; int someElement(void) const { return m_internal.someElement; }; private: InterfaceWrapper(){} // initialize m_internal SomeHugeStructure&amp; m_internal; }; </code></pre>
[ { "answer_id": 284618, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 2, "selected": false, "text": "private:\n InterfaceWrapper();\n SomeHugeStructure& m_internal;\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16496/" ]
284,581
<p>I've got a timer running in my Delphi MDI application and I'd like to use it to pop up a message if something changes in the background. But I don't want that message to pop up when the the application has a modal dialog in the foreground because the user couldn't do anything about it. </p> <p>So what I'd like to know is how can I check for the existence of a modal dialog in my application?</p>
[ { "answer_id": 284621, "author": "mghie", "author_id": 30568, "author_profile": "https://Stackoverflow.com/users/30568", "pm_score": 5, "selected": true, "text": "var\n ActForm: TCustomForm;\nbegin\n ActForm := Screen.ActiveForm;\n if (ActForm = nil) or not (fsModal in ActForm.FormState) then begin\n\n end;\nend;\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284581", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1765/" ]
284,608
<p>I need more than the default diff! I have recently purchased "Beyond Compare" and I'd like to integrate it with svn, so its launched when I type:</p> <p>svn diff foo.c</p> <p>How do I do this?</p>
[ { "answer_id": 284666, "author": "Ned Batchelder", "author_id": 14343, "author_profile": "https://Stackoverflow.com/users/14343", "pm_score": 6, "selected": true, "text": "#!/bin/bash\n/usr/bin/bcompare $6 $7 &\nexit 0\n diff-cmd=/usr/bin/bcompare_svn\n" }, { "answer_id": 14249596, "author": "David Wu", "author_id": 1965237, "author_profile": "https://Stackoverflow.com/users/1965237", "pm_score": 2, "selected": false, "text": "#!/bin/bash\ncp $6 $6.save\ncp $7 $7.save\n{\n /usr/bin/bcompare $6.save $7.save \n rm $6.save $7.save\n} &\nexit 0\n #!/bin/bash\nbase=`echo $3 | sed -r \"s/^([^\\(]+)[ \\t]+\\((.+)\\)$/\\1.\\2/g\" | xargs -i% basename \"%\"`\ncurrent=`echo $5 | sed -r \"s/^([^\\(]+)[ \\t]\\((.+)\\)$/\\1.\\2/g\" | xargs -i% basename \"%\"`\n\nmv \"$6\" \"/tmp/$base\"\nmv \"$7\" \"/tmp/$current\"\n{\n /usr/local/bcompare/bin/bcompare \"/tmp/$base\" \"/tmp/$current\"\n rm \"/tmp/$base\" \"/tmp/$current\"\n} &\nexit 0\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3886/" ]
284,609
<p>I have a SQL Mobile database with one table. It has several columns with useful, often queried data and one column that stores a relatively large string per record (1000+ characters) that is not queried often.</p> <p>Imagine this fake schema, the "lifeStory" field is the large one.</p> <pre><code>table1 String firstName String lastName String address String lifeStory </code></pre> <p>A representative query would be</p> <pre><code>SELECT firstName, lastName, address FROM table1 WHERE firstName = :p1 </code></pre> <p>Does anyone know of any performance concerns leaving that large, infrequently queried column in this table?</p>
[ { "answer_id": 284666, "author": "Ned Batchelder", "author_id": 14343, "author_profile": "https://Stackoverflow.com/users/14343", "pm_score": 6, "selected": true, "text": "#!/bin/bash\n/usr/bin/bcompare $6 $7 &\nexit 0\n diff-cmd=/usr/bin/bcompare_svn\n" }, { "answer_id": 14249596, "author": "David Wu", "author_id": 1965237, "author_profile": "https://Stackoverflow.com/users/1965237", "pm_score": 2, "selected": false, "text": "#!/bin/bash\ncp $6 $6.save\ncp $7 $7.save\n{\n /usr/bin/bcompare $6.save $7.save \n rm $6.save $7.save\n} &\nexit 0\n #!/bin/bash\nbase=`echo $3 | sed -r \"s/^([^\\(]+)[ \\t]+\\((.+)\\)$/\\1.\\2/g\" | xargs -i% basename \"%\"`\ncurrent=`echo $5 | sed -r \"s/^([^\\(]+)[ \\t]\\((.+)\\)$/\\1.\\2/g\" | xargs -i% basename \"%\"`\n\nmv \"$6\" \"/tmp/$base\"\nmv \"$7\" \"/tmp/$current\"\n{\n /usr/local/bcompare/bin/bcompare \"/tmp/$base\" \"/tmp/$current\"\n rm \"/tmp/$base\" \"/tmp/$current\"\n} &\nexit 0\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3619/" ]
284,619
<p>i need write the code that runs when DllRegisterServer is called. i.e. when someone calls:</p> <pre><code>regsvr32 myActiveX.ocx </code></pre> <p>i'm trying to find the definitive list of required registry entries (rather than just what i can cobble together by spellunking through the registry).</p> <p>So far my expeditions have found:</p> <pre><code>HKEY_CLASSES_ROOT \MyCoolLibrary.MyCoolControl \Clsid (default) = "{myClassId}" \CLSID \{myClassId} \Control \InprocServer32 (default) = "c:\foo\myActiveX.ocx" ThreadingModel = "Apartment" \MiscStatus \1 (default) = 205201 \ProgID (default) = "MyCoolLibrary.MyCoolControl" \ToolboxBitmap32 (default) = "c:\foo\myActiveX.ocx,1" \TypeLib (default) = "{myTypeLibraryGuid}" \Verb \0 (default) = "Properties,0,2" \Version (default) = "1.0" \TypeLib \{myTypeLibraryGuid} \1.0 (default) = "MyCoolLibrary.MyCoolControl" </code></pre> <p>Now, the concerns: - what does the Control folder contain? Is it's presence indicate a control? - what's a MiscStatus of 205201 do? What would 205202 do instead? - What's the verb "Properties,0,2"? Where's "Properties,0,0" and "Properties,0,1"?</p> <p>In other words, i'm looking for the docs.</p>
[ { "answer_id": 284638, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 3, "selected": false, "text": "HKEY_CLASSES_ROOT\\CLSID\\<clsid>\\" }, { "answer_id": 285060, "author": "Ian Boyd", "author_id": 12597, "author_profile": "https://Stackoverflow.com/users/12597", "pm_score": 4, "selected": false, "text": "HKEY_CLASSES_ROOT\n \\Clsid\n \\{AE8530CF-D204-4877-9CAB-F052BF1F661F}\n HKEY_CLASSES_ROOT\n \\Clsid\n \\{AE8530CF-D204-4877-9CAB-F052BF1F661F}\n \\InprocServer32\n (default) = \"c:\\foo\\myActiveX.ocx\"\n HKEY_CLASSES_ROOT\n \\Clsid\n \\{AE8530CF-D204-4877-9CAB-F052BF1F661F}\n \\InprocServer32\n (default) = \"c:\\foo\\myActiveX.ocx\"\n ThreadingModel = \"Apartment\"\n \"MyCoolLibrary.MyCoolControl\" \"{AE8530CF-D204-4877-9CAB-F052BF1F661F}\" HKEY_CLASSES_ROOT\n \\Clsid\n \\{AE8530CF-D204-4877-9CAB-F052BF1F661F}\n \\InprocServer32\n (default) = \"c:\\foo\\myActiveX.ocx\"\n ThreadingModel = \"Apartment\"\nHKEY_CLASSES_ROOT\n \\MyCoolLibrary.MyCoolControl\n \\Clsid\n (default) = \"{AE8530CF-D204-4877-9CAB-F052BF1F661F}\"\n MyCoolLibrary.MyCoolControl\n {AE8530CF-D204-4877-9CAB-F052BF1F661F}\n HKCR\\Clsid\\{AE8530CF-D204-4877-9CAB-F052BF1F661F} HKEY_CLASSES_ROOT\n \\Clsid\n \\{AE8530CF-D204-4877-9CAB-F052BF1F661F}\n \\InprocServer32\n (default) = \"c:\\foo\\myActiveX.ocx\"\n ThreadingModel = \"Apartment\"\n \\ProgID\n (default) = \"MyCoolLibrary.MyCoolControl\"\nHKEY_CLASSES_ROOT\n \\MyCoolLibrary.MyCoolControl\n \\Clsid\n (default) = \"{AE8530CF-D204-4877-9CAB-F052BF1F661F}\"\n HKEY_CLASSES_ROOT\n \\Clsid\n \\{AE8530CF-D204-4877-9CAB-F052BF1F661F}\n \\InprocServer32\n (default) = \"c:\\foo\\myActiveX.ocx\"\n ThreadingModel = \"Apartment\"\n \\ProgID\n (default) = \"MyCoolLibrary.MyCoolControl\"\n \\TypeLib \n (default) = \"{17A5A3D4-439C-4C2A-8AB4-749B7771CDE1}\"\nHKEY_CLASSES_ROOT\n \\MyCoolLibrary.MyCoolControl\n \\Clsid\n (default) = \"{AE8530CF-D204-4877-9CAB-F052BF1F661F}\"\n HKEY_CLASSES_ROOT\n \\Clsid\n \\{AE8530CF-D204-4877-9CAB-F052BF1F661F}\n \\InprocServer32\n (default) = \"c:\\foo\\myActiveX.ocx\"\n ThreadingModel = \"Apartment\"\n \\ProgID\n (default) = \"MyCoolLibrary.MyCoolControl\"\n \\TypeLib \n (default) = \"{17A5A3D4-439C-4C2A-8AB4-749B7771CDE1}\"\nHKEY_CLASSES_ROOT\n \\MyCoolLibrary.MyCoolControl\n \\Clsid\n (default) = \"{AE8530CF-D204-4877-9CAB-F052BF1F661F}\"\nHKEY_CLASSES_ROOT\n \\TypeLib\n \\{AE8530CF-D204-4877-9CAB-F052BF1F661F}\n \\1.0\n (default) = \"My Cool ActiveX Library\"\n ...\n HKEY_CLASSES_ROOT\n \\Clsid\n \\{AE8530CF-D204-4877-9CAB-F052BF1F661F}\n \\Programmable\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284619", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12597/" ]
284,637
<p>Into some view data i have put the result of an anonymous type:</p> <pre><code> var projectData = from p in db.Projects orderby p.title select new { Title = p.title, DevURL = p.devURL ?? "N/A", QAURL = p.qaURL ?? "N/A", LiveURL = p.liveURL ?? "N/A", Users = p.GetUsers().MakeUserList() }; ViewData["ProjectSummary"] = projectData; </code></pre> <p>How do I iterate through this view data in the MVC view on the front end to say, make a table of results?</p>
[ { "answer_id": 284646, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 0, "selected": false, "text": " var projectData = (from p in db.Projects\n orderby p.title\n select new\n {\n Title = p.title,\n DevURL = p.devURL ?? \"N/A\",\n QAURL = p.qaURL ?? \"N/A\",\n LiveURL = p.liveURL ?? \"N/A\",\n Users = p.GetUsers().MakeUserList()\n }).ToList();\n" }, { "answer_id": 284665, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": true, "text": "public class Project{\n\npublic string Title {get;set;}\npublic string DevUrl {get;set;}\npublic string QAUrl {get;set;}\npublic string LiveUrl {get;set;}\npublic IEnumerable<User> Users {get;set;}\n\npublic static IEnumerable<Project> RetrieveAllProjects()\n{\n return from p in db.Projects\n orderby p.title\n select new Project\n {\n Title = p.title,\n DevURL = p.devURL ?? \"N/A\",\n QAURL = p.qaURL ?? \"N/A\",\n LiveURL = p.liveURL ?? \"N/A\",\n Users = p.GetUsers().MakeUserList()\n };\n}\n public ActionResult Index()\n{\n return View(\"Index\", Project.RetrieveAllProjects());\n}\n //snip\npublic partial class Index : ViewPage<IEnumerable<Project>>\n{\n//snip\n" }, { "answer_id": 312950, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "List<T> ViewData <% foreach (Project p in (IEnumerable<Project>)ViewData[\"ProjectSummary\"]) { %>\n <%= Html.Encode(p.Title) %>\n<% } %>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284637", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3193/" ]
284,653
<p>I've just wasted the past two hours of my life trying to create a table with an auto incrementing primary key bases on <a href="http://www.lifeaftercoffee.com/2006/02/17/how-to-create-auto-increment-columns-in-oracle/" rel="nofollow noreferrer">this tutorial</a>, The tutorial is great the issue I've been encountering is that the Create Target fails if I have a column which is a timestamp and a table that is called timestamp in the same table...</p> <p>Why doesn't oracle flag this as being an issue when I create the table?</p> <p>Here is the Sequence of commands I enter:</p> <ol> <li><p>Creating the Table:</p> <pre><code>CREATE TABLE myTable (id NUMBER PRIMARY KEY, field1 TIMESTAMP(6), timeStamp NUMBER, ); </code></pre></li> <li><p>Creating the Sequence:</p> <pre><code>CREATE SEQUENCE test_sequence START WITH 1 INCREMENT BY 1; </code></pre></li> <li><p>Creating the trigger:</p> <pre><code>CREATE OR REPLACE TRIGGER test_trigger BEFORE INSERT ON myTable REFERENCING NEW AS NEW FOR EACH ROW BEGIN SELECT test_sequence.nextval INTO :NEW.ID FROM dual; END; / </code></pre></li> </ol> <p>Here is the error message I get:</p> <pre><code>ORA-06552: PL/SQL: Compilation unit analysis terminated ORA-06553: PLS-320: the declaration of the type of this expression is incomplete or malformed </code></pre> <p>Any combination that does not have the two lines with a the word "timestamp" in them works fine. I would have thought the syntax would be enough to differentiate between the keyword and a column name. </p> <p>As I've said I don't understand why the table is created fine but oracle falls over when I try to create the trigger...</p> <p><strong>CLARIFICATION</strong></p> <p>I know that the issue is that there is a column called timestamp which may or may not be a keyword. MY issue is why it barfed when I tried to create a trigger and not when I created the table, I would have at least expected a warning.</p> <p>That said having used Oracle for a few hours, it seems a lot less verbose in it's error reporting, Maybe just because I'm using the express version though.</p> <p>If this is a bug in Oracle how would one who doesn't have a support contract go about reporting it? I'm just playing around with the express version because I have to migrate some code from MySQL to Oracle.</p>
[ { "answer_id": 284715, "author": "tragomaskhalos", "author_id": 31140, "author_profile": "https://Stackoverflow.com/users/31140", "pm_score": 1, "selected": false, "text": "timestamp xtimestamp" }, { "answer_id": 287012, "author": "pablo", "author_id": 16112, "author_profile": "https://Stackoverflow.com/users/16112", "pm_score": 4, "selected": true, "text": "# symptom: Creating Trigger fails\n# symptom: Compiling a procedure fails\n# symptom: ORA-06552: PL/SQL: %s\n# symptom: ORA-06553: PLS-%s: %s \n# symptom: PLS-320: the declaration of the type of this expression is incomplete or malformed\n # cause: One of the tables being references was created with a column name that is one of the datatypes (reserved key word). Even though the field is not referenced in the PL/SQL SQL statements, this error will still be produced.\n\n fix:\n\n Workaround:\n\n 1. Rename the column to a non-reserved word.\n 2. Create a view and alias the column to a different name.\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20400/" ]
284,662
<p>I want to transform <code>/foo/bar/..</code> to <code>/foo</code></p> <p>Is there a bash command which does this?</p> <hr> <p>Edit: in my practical case, the directory does exist.</p>
[ { "answer_id": 284664, "author": "Adam Liss", "author_id": 29157, "author_profile": "https://Stackoverflow.com/users/29157", "pm_score": 6, "selected": false, "text": "realpath // realpath.c: display the absolute path to a file or directory.\n// Adam Liss, August, 2007\n// This program is provided \"as-is\" to the public domain, without express or\n// implied warranty, for any non-profit use, provided this notice is maintained.\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <libgen.h> \n#include <limits.h>\n\nstatic char *s_pMyName;\nvoid usage(void);\n\nint main(int argc, char *argv[])\n{\n char\n sPath[PATH_MAX];\n\n\n s_pMyName = strdup(basename(argv[0]));\n\n if (argc < 2)\n usage();\n\n printf(\"%s\\n\", realpath(argv[1], sPath));\n return 0;\n} \n\nvoid usage(void)\n{\n fprintf(stderr, \"usage: %s PATH\\n\", s_pMyName);\n exit(1);\n}\n" }, { "answer_id": 284667, "author": "Tim Whitcomb", "author_id": 24895, "author_profile": "https://Stackoverflow.com/users/24895", "pm_score": 7, "selected": false, "text": "normalDir=\"`cd \"${dirToNormalize}\";pwd`\"\necho \"${normalDir}\"\n" }, { "answer_id": 284671, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 9, "selected": true, "text": "dirname /foo/bar/baz \n# /foo/bar \nbasename /foo/bar/baz\n# baz\ndirname $( dirname /foo/bar/baz ) \n# /foo \nrealpath ../foo\n# ../foo: No such file or directory\nrealpath /tmp/../tmp/../tmp\n# /tmp\n realpath realpath readlink -f /path/here/.. \n readlink -m /path/there/../../ \n realpath -s /path/here/../../\n" }, { "answer_id": 1708397, "author": "alhernau", "author_id": 207845, "author_profile": "https://Stackoverflow.com/users/207845", "pm_score": 2, "selected": false, "text": "test -x /usr/bin/readlink || readlink () {\n echo $(/bin/ls -l $1 | /bin/cut -d'>' -f 2)\n }\n\n\ntest -x /usr/bin/realpath || realpath () {\n local PATH=/bin:/usr/bin\n local inputpath=$1\n local changemade=1\n while [ $changemade -ne 0 ]\n do\n changemade=0\n local realpath=\"\"\n local token=\n for token in ${inputpath//\\// }\n do \n case $token in\n \"\"|\".\") # noop\n ;;\n \"..\") # up one directory\n changemade=1\n realpath=$(dirname $realpath)\n ;;\n *)\n if [ -h $realpath/$token ] \n then\n changemade=1\n target=`readlink $realpath/$token`\n if [ \"${target:0:1}\" = '/' ]\n then\n realpath=$target\n else\n realpath=\"$realpath/$target\"\n fi\n else\n realpath=\"$realpath/$token\"\n fi\n ;;\n esac\n done\n inputpath=$realpath\n done\n echo $realpath\n}\n\nmkdir -p /tmp/bar\n(cd /tmp ; ln -s /tmp/bar foo; ln -s ../.././usr /tmp/bar/link2usr)\necho `realpath /tmp/foo`\n" }, { "answer_id": 3339768, "author": "mattalxndr", "author_id": 334966, "author_profile": "https://Stackoverflow.com/users/334966", "pm_score": 5, "selected": false, "text": "MY_PATH=$(readlink -f \"$0\")\n" }, { "answer_id": 3373298, "author": "loevborg", "author_id": 239678, "author_profile": "https://Stackoverflow.com/users/239678", "pm_score": 6, "selected": false, "text": "abspath python -c \"import os,sys; print(os.path.abspath(sys.argv[1]))\" path/to/file realpath python -c \"import os,sys; print(os.path.realpath(sys.argv[1]))\" path/to/file path/to/file" }, { "answer_id": 6393490, "author": "Jeet", "author_id": 268330, "author_profile": "https://Stackoverflow.com/users/268330", "pm_score": 3, "selected": false, "text": "realpath get_abs_path() {\n local PARENT_DIR=$(dirname \"$1\")\n cd \"$PARENT_DIR\"\n local ABS_PATH=\"$(pwd)\"/\"$(basename \"$1\")\"\n cd - >/dev/null\n echo \"$ABS_PATH\"\n} \n pwd pwd -P" }, { "answer_id": 7717841, "author": "schmunk", "author_id": 291573, "author_profile": "https://Stackoverflow.com/users/291573", "pm_score": 3, "selected": false, "text": "pushd foo/bar/..\ndir=`pwd`\npopd\n" }, { "answer_id": 10808025, "author": "Jesse Glick", "author_id": 12916, "author_profile": "https://Stackoverflow.com/users/12916", "pm_score": 3, "selected": false, "text": "readlink ./ ../ // readlink realpath for f in $paths; do (cd $f; pwd); done\n sed /foo/bar/baz/../.. /foo/bar/.. /foo sed jrunscript -e 'for (var i = 0; i < arguments.length; i++) {println(new java.io.File(new java.io.File(arguments[i]).toURI().normalize()))}' $paths\n" }, { "answer_id": 18420863, "author": "apottere", "author_id": 1628477, "author_profile": "https://Stackoverflow.com/users/1628477", "pm_score": 3, "selected": false, "text": "resolve_dir() {\n (builtin cd `dirname \"${1/#~/$HOME}\"`'/'`basename \"${1/#~/$HOME}\"` 2>/dev/null; if [ $? -eq 0 ]; then pwd; fi)\n}\n" }, { "answer_id": 19141198, "author": "AsymLabs", "author_id": 2839332, "author_profile": "https://Stackoverflow.com/users/2839332", "pm_score": 2, "selected": false, "text": "get_realpath <absolute|relative|symlink|local file path>\n function get_realpath() {\n\nif [[ -f \"$1\" ]]\nthen \n # file *must* exist\n if cd \"$(echo \"${1%/*}\")\" &>/dev/null\n then \n # file *may* not be local\n # exception is ./file.ext\n # try 'cd .; cd -;' *works!*\n local tmppwd=\"$PWD\"\n cd - &>/dev/null\n else \n # file *must* be local\n local tmppwd=\"$PWD\"\n fi\nelse \n # file *cannot* exist\n return 1 # failure\nfi\n\n# reassemble realpath\necho \"$tmppwd\"/\"${1##*/}\"\nreturn 0 # success\n\n}\n" }, { "answer_id": 19147630, "author": "Craig", "author_id": 1489354, "author_profile": "https://Stackoverflow.com/users/1489354", "pm_score": 4, "selected": false, "text": "readlink abspath=$(readlink -f $path)\n abspath=$(readlink -e $path)\n abspath=$(readlink -m $path)\n abspath=$(cd ${path%/*} && echo $PWD/${path##*/})\n" }, { "answer_id": 23945431, "author": "coldlogic", "author_id": 3689603, "author_profile": "https://Stackoverflow.com/users/3689603", "pm_score": -1, "selected": false, "text": "stat stat -f %N ~/Documents /Users/me/Documents stat -f %Y example_symlink /usr/local/sbin/example_symlink" }, { "answer_id": 29256624, "author": "André Anjos", "author_id": 712525, "author_profile": "https://Stackoverflow.com/users/712525", "pm_score": 2, "selected": false, "text": "realpath function normpath() {\n # Remove all /./ sequences.\n local path=${1//\\/.\\//\\/}\n\n # Remove dir/.. sequences.\n while [[ $path =~ ([^/][^/]*/\\.\\./) ]]; do\n path=${path/${BASH_REMATCH[0]}/}\n done\n echo $path\n}\n" }, { "answer_id": 31086901, "author": "ϹοδεMεδιϲ", "author_id": 83005, "author_profile": "https://Stackoverflow.com/users/83005", "pm_score": 2, "selected": false, "text": "realpath readlink -f shopt -s extglob\n\nnormalise_path() {\n local path=\"$1\"\n # get rid of /../ example: /one/../two to /two\n path=\"${path//\\/*([!\\/])\\/\\.\\./}\"\n # get rid of /./ and //* example: /one/.///two to /one/two\n path=\"${path//@(\\/\\.\\/|\\/+(\\/))//}\"\n # remove the last '/.'\n echo \"${path%%/.}\"\n}\n\n$ normalise_path /home/codemedic/../codemedic////.config\n/home/codemedic/.config\n" }, { "answer_id": 34754899, "author": "Artisan72", "author_id": 3862511, "author_profile": "https://Stackoverflow.com/users/3862511", "pm_score": -1, "selected": false, "text": "node.js #!/usr/bin/env node\nprocess.stdout.write(require('path').resolve(process.argv[2]));\n" }, { "answer_id": 36045150, "author": "Edward Falk", "author_id": 338479, "author_profile": "https://Stackoverflow.com/users/338479", "pm_score": 0, "selected": false, "text": "#!/bin/sh\n\n# Version of readlink that follows links to the end; good for Mac OS X\n\nfor file in \"$@\"; do\n while [ -h \"$file\" ]; do\n l=`readlink $file`\n case \"$l\" in\n /*) file=\"$l\";;\n *) file=`dirname \"$file\"`/\"$l\"\n esac\n done\n #echo $file\n python -c \"import os,sys; print os.path.abspath(sys.argv[1])\" \"$file\"\ndone\n" }, { "answer_id": 48794465, "author": "user240515", "author_id": 240515, "author_profile": "https://Stackoverflow.com/users/240515", "pm_score": 0, "selected": false, "text": "FILEPATH=\"file.txt\"\necho $(realpath $(dirname $FILEPATH))/$(basename $FILEPATH)\n" }, { "answer_id": 49208182, "author": "bestOfSong", "author_id": 5010054, "author_profile": "https://Stackoverflow.com/users/5010054", "pm_score": 0, "selected": false, "text": "#! /bin/sh \n\nfunction normalize {\n local rc=0\n local ret\n\n if [ $# -gt 0 ] ; then\n # invalid\n if [ \"x`echo $1 | grep -E '^/\\.\\.'`\" != \"x\" ] ; then\n echo $1\n return -1\n fi\n\n # convert to absolute path\n if [ \"x`echo $1 | grep -E '^\\/'`\" == \"x\" ] ; then\n normalize \"`pwd`/$1\"\n return $?\n fi\n\n ret=`echo $1 | sed 's;/\\.\\($\\|/\\);/;g' | sed 's;/[^/]*[^/.]\\+[^/]*/\\.\\.\\($\\|/\\);/;g'`\n else\n read line\n normalize \"$line\"\n return $?\n fi\n\n if [ \"x`echo $ret | grep -E '/\\.\\.?(/|$)'`\" != \"x\" ] ; then\n ret=`normalize \"$ret\"`\n rc=$?\n fi\n\n echo \"$ret\"\n return $rc\n}\n" }, { "answer_id": 50361385, "author": "David Blevins", "author_id": 190816, "author_profile": "https://Stackoverflow.com/users/190816", "pm_score": 1, "selected": false, "text": "realpath readlink -f #!/bin/bash\n\nP=\"${1?Specify a file path}\"\n\n[ -e \"$P\" ] || { echo \"File does not exist: $P\"; exit 1; }\n\nwhile [ -h \"$P\" ] ; do\n ls=\"$(ls -ld \"$P\")\"\n link=\"$(expr \"$ls\" : '.*-> \\(.*\\)$')\"\n expr \"$link\" : '/.*' > /dev/null &&\n P=\"$link\" ||\n P=\"$(dirname \"$P\")/$link\"\ndone\necho \"$(cd \"$(dirname \"$P\")\"; pwd)/$(basename \"$P\")\"\n mkdir -p \"/tmp/test/ first path \"\nmkdir -p \"/tmp/test/ second path \"\necho \"hello\" > \"/tmp/test/ first path / red .txt \"\nln -s \"/tmp/test/ first path / red .txt \" \"/tmp/test/ second path / green .txt \"\n\ncd \"/tmp/test/ second path \"\nfullpath \" green .txt \"\ncat \" green .txt \"\n" }, { "answer_id": 61632893, "author": "Jeffrey Cash", "author_id": 6232717, "author_profile": "https://Stackoverflow.com/users/6232717", "pm_score": 2, "selected": false, "text": "realpath -sm ## A bash-only mimic of `realpath -sm`. \n## Give it path[s] as argument[s] and it will convert them to clean absolute paths\nabspath () { \n ${*+false} && { >&2 echo $FUNCNAME: missing operand; return 1; };\n local c s p IFS='/'; ## path chunk, absolute path, input path, IFS for splitting paths into chunks\n local -i r=0; ## return value\n\n for p in \"$@\"; do\n case \"$p\" in ## Check for leading backslashes, identify relative/absolute path\n '') ((r|=1)); continue;;\n //[!/]*) >&2 echo \"paths =~ ^//[^/]* are impl-defined; not my problem\"; ((r|=2)); continue;;\n /*) ;;\n *) p=\"$PWD/$p\";; ## Prepend the current directory to form an absolute path\n esac\n\n s='';\n for c in $p; do ## Let IFS split the path at '/'s\n case $c in ### NOTE: IFS is '/'; so no quotes needed here\n ''|.) ;; ## Skip duplicate '/'s and '/./'s\n ..) s=\"${s%/*}\";; ## Trim the previous addition to the absolute path string\n *) s+=/$c;; ### NOTE: No quotes here intentionally. They make no difference, it seems\n esac;\n done;\n\n echo \"${s:-/}\"; ## If xpg_echo is set, use `echo -E` or `printf $'%s\\n'` instead\n done\n return $r;\n}\n // / /// abspath realpath -sm abspath realpath -sm" }, { "answer_id": 66468913, "author": "David Pi", "author_id": 14500150, "author_profile": "https://Stackoverflow.com/users/14500150", "pm_score": 2, "selected": false, "text": "posixpath.normpath #!/usr/bin/env bash\n\n# Normalize path, eliminating double slashes, etc.\n# Usage: new_path=\"$(normpath \"${old_path}\")\"\n# Translated from Python's posixpath.normpath:\n# https://github.com/python/cpython/blob/master/Lib/posixpath.py#L337\nnormpath() {\n local IFS=/ initial_slashes='' comp comps=()\n if [[ $1 == /* ]]; then\n initial_slashes='/'\n [[ $1 == //* && $1 != ///* ]] && initial_slashes='//'\n fi\n for comp in $1; do\n [[ -z ${comp} || ${comp} == '.' ]] && continue\n if [[ ${comp} != '..' || (-z ${initial_slashes} && ${#comps[@]} -eq 0) || (\\\n ${#comps[@]} -gt 0 && ${comps[-1]} == '..') ]]; then\n comps+=(\"${comp}\")\n elif ((${#comps[@]})); then\n unset 'comps[-1]'\n fi\n done\n comp=\"${initial_slashes}${comps[*]}\"\n printf '%s\\n' \"${comp:-.}\"\n}\n new_path=\"$(normpath '/foo/bar/..')\"\necho \"${new_path}\"\n# /foo\n\nnormpath \"relative/path/with trailing slashs////\"\n# relative/path/with trailing slashs\n\nnormpath \"////a/../lot/././/mess////./here/./../\"\n# /lot/mess\n\nnormpath \"\"\n# .\n# (empty path resolved to dot)\n" }, { "answer_id": 70291479, "author": "Fabian Lehmann", "author_id": 17636526, "author_profile": "https://Stackoverflow.com/users/17636526", "pm_score": 0, "selected": false, "text": "function normalize_rel_path(){\n local path=$1\n result=\"\"\n IFS='/' read -r -a array <<< \"$path\"\n i=0\n for (( idx=${#array[@]}-1 ; idx>=0 ; idx-- )) ; do\n c=\"${array[idx]}\"\n if [ -z \"$c\" ] || [[ \"$c\" == \".\" ]];\n then\n continue\n fi\n if [[ \"$c\" == \"..\" ]]\n then\n i=$((i+1))\n elif [ \"$i\" -gt \"0\" ];\n then\n i=$((i-1))\n else\n if [ -z \"$result\" ];\n then\n result=$c\n else\n result=$c/$result\n fi\n fi\n done\n while [ \"$i\" -gt \"0\" ]; do\n i=$((i-1))\n result=\"../\"$result\n done \n unset IFS\n echo $result\n}\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21132/" ]
284,678
<p>I have an application where every now and then I'm getting a strange error. This is the piece of code:</p> <pre><code>Dim XMLWriter As New System.Xml.XmlTextWriter(Me.Context.Response.OutputStream, Encoding.UTF8) XMLWriter.WriteStartDocument() XMLWriter.WriteStartElement("Status") Message.SerializeToXML(XMLWriter) XMLWriter.WriteEndElement() XMLWriter.WriteEndDocument() XMLWriter.Flush() XMLWriter.Close() </code></pre> <p>The error i'm getting is: Message: Object reference not set to an instance of an object.</p> <p>on line XMLWriter.Flush();</p> <p>To make things more fun, this is absolutely non-reproducible. It just happens every now and then....</p> <p>Since it's happening when flushing the XML i'm guessing the Object that is now null has to be the Response.OutputStream.</p> <p>This is the relevant part of the stack trace:</p> <pre><code>Description: An unhandled exception occurred and the process was terminated. Exception: System.NullReferenceException Message: Object reference not set to an instance of an object. StackTrace: at System.Web.HttpWriter.BufferData(Byte[] data, Int32 offset, Int32 size, Boolean needToCopyData) at System.Web.HttpWriter.WriteFromStream(Byte[] data, Int32 offset, Int32 size) at System.IO.StreamWriter.Flush(Boolean flushStream, Boolean flushEncoder) at System.Xml.XmlTextWriter.Flush() at RequestData.CompleteRequest(MessageBase Message) in RequestData.vb:line 142 </code></pre> <p>My question is, in what cases could this be happening? This server is a long-polling server, so the client asks for something, and I may not answer for 30 seconds... Is it possible that this Stream will become Null if the client disconnects (ie. closes the browser window)?</p> <p>Any other ideas? (any pointers appreciated)</p>
[ { "answer_id": 284687, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 0, "selected": false, "text": "Context.Response.OutputStream XmlTextWriter" }, { "answer_id": 344439, "author": "Brian Rudolph", "author_id": 33114, "author_profile": "https://Stackoverflow.com/users/33114", "pm_score": 2, "selected": true, "text": "private void BufferData(byte[] data, int offset, int size, bool needToCopyData)\n{\n int num;\n if (this._lastBuffer != null)\n {\n num = this._lastBuffer.Append(data, offset, size);\n size -= num;\n offset += num;\n }\n else if ((!needToCopyData && (offset == 0)) && !this._responseBufferingOn)\n {\n this._buffers.Add(new HttpResponseBufferElement(data, size));\n return;\n }\n while (size > 0)\n {\n this._lastBuffer = this.CreateNewMemoryBufferElement();\n this._buffers.Add(this._lastBuffer);\n num = this._lastBuffer.Append(data, offset, size);\n offset += num;\n size -= num;\n }\n}\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284678", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3314/" ]
284,679
<p>What's the easiest way to get the data for a single table, delete a single table or break up the whole dump file into files each containing individual tables? I usually end up doing a lot of vi regex munging, but I bet there are easier ways to do these things with awk/perl, etc. The first page of Google results brings back a bunch of non-working perl scripts.</p>
[ { "answer_id": 284702, "author": "J.D. Fitz.Gerald", "author_id": 11542, "author_profile": "https://Stackoverflow.com/users/11542", "pm_score": 3, "selected": false, "text": "mysqldump -T" }, { "answer_id": 285089, "author": "mercutio", "author_id": 1951, "author_profile": "https://Stackoverflow.com/users/1951", "pm_score": 4, "selected": false, "text": "grep -n \"CREATE TABLE\" dump.sql\n head -n 268 dump.sql > tophalf.sql\ntail -n 69 tophalf.sql > yourtable.sql\n grep -n \"CREATE TABLE \" dump.sql | tr ':`(' ' ' | awk '{print $1, $4}'\n 200 FooTable\n269 BarTable\n" }, { "answer_id": 2242970, "author": "kv.", "author_id": 260731, "author_profile": "https://Stackoverflow.com/users/260731", "pm_score": 2, "selected": false, "text": "splitted.sql sed -r" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/556/" ]
284,708
<p>I have an <code>.xsd</code>, <code>.vb</code>, <code>.xsc</code>, and <code>.xss</code> file for a dataset in Visual&nbsp;Studio&nbsp;2008 that I copied over from another Visual Studio project, however I need to make changes to the dataset. Thus I got into the XSD file, created new columns, deleted ones that aren't needed, etc., etc. However I realized when I attempted to use the new dataset I did not have the Visual Basic code behind the scenes. This code is typically found in <code>dataset.designer.vb</code>. When I copied the old one over of course it was no longer valid since columns changed.</p> <p>How I can force Visual&nbsp;Studio&nbsp;2008 to use a <code>.xsd</code> file and to have it create/update its designer code?</p>
[ { "answer_id": 284764, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "*.designer.vb" }, { "answer_id": 284787, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "dataset.vb xsd.exe .vb xsd.exe xsd.exe /d /l:VB \"XSD FILE LOCATION PATH\"\n /d /l .vb C:\\Windows\\System32" }, { "answer_id": 1255159, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": ".xsd designer.vb" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284708", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
284,716
<p>I am working on an automated testing app, and am currently in the process of writing a function that compares values between two XML files that should be identical, but may not be. Here is a sample of the XML I'm trying to process:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;report xmlns="http://www.**.com/**"&gt; &lt;subreport name="RBDReport"&gt; &lt;record rowNumber="1"&gt; &lt;field name="Time"&gt; &lt;value&gt;0&lt;/value&gt; &lt;/field&gt; &lt;field name="Reliability"&gt; &lt;value&gt;1.000000&lt;/value&gt; &lt;/field&gt; &lt;field name="Unreliability"&gt; &lt;value&gt;0.000000&lt;/value&gt; &lt;/field&gt; &lt;field name="Availability"&gt; &lt;value&gt; &lt;/value&gt; &lt;/field&gt; &lt;field name="Unavailability"&gt; &lt;value&gt; &lt;/value&gt; &lt;/field&gt; &lt;field name="Failure Rate"&gt; &lt;value&gt;N/A&lt;/value&gt; &lt;/field&gt; &lt;field name="Number of Failures"&gt; &lt;value&gt; &lt;/value&gt; &lt;/field&gt; &lt;field name="Total Downtime"&gt; &lt;value&gt; &lt;/value&gt; &lt;/field&gt; &lt;/record&gt; </code></pre> <p>(Note there may be multiple <code>&lt;subreport&gt;</code> elements and within those, multiple <code>&lt;record&gt;</code> elements.)</p> <p>What I'd like is to extract the <code>&lt;value&gt;</code> tags of two documents and then compare their values. That part I know how to do. The problem is the extraction itself.</p> <p>Since I'm stuck in C++, I'm using MSXML, and have written a wrapper to allow my app to abstract away the actual XML manipulation, in case I ever decide to change my data format.</p> <p>That wrapper, CSimpleXMLParser, loads an XML document and sets its "top record" to the document element of the XML document. (CRecord being an abstract class with CXMLRecord one of its subclasses, and which gives access to child records singularly or by group, and also allowing access to the "value" of the Record (values for child elements or attributes, in the case of CXMLRecord.) A CXMLRecord contains an MSXML::MSXMLDOMNodePtr and a pointer to an instance of a CSimpleXMLParser.) The wrapper also contains utility functions for returning children, which the CXMLRecord uses to return its child records.</p> <p>In my code, I do the following (trying to return all <code>&lt;subreport&gt;</code> nodes just to see if it works):</p> <pre><code>CSimpleXMLParser parserReportData; parserReportData.OpenXMLDocument(strPathToXML); bool bGetChildrenSuccess = parserReportData.GetFirstRecord()-&gt;GetChildRecords(listpChildren, _T("subreport")); </code></pre> <p>This is always returning false. The meat of the implementation of CXMLRecord::GetChildRecords() is basically</p> <pre><code>MSXML2::IXMLDOMNodeListPtr pListChildren = m_pParser-&gt;SelectNodes(strPath, m_pXMLNode); if (pListChildren-&gt;Getlength() == 0) { return false; } for (long l = 0; l &lt; pListChildren-&gt;Getlength(); ++l) { listRecords.push_back(new CXMLRecord(pListChildren-&gt;Getitem(l), m_pParser)); } return true; </code></pre> <p>And CSimpleXMLParser::SelectNodes() is:</p> <pre><code>MSXML2::IXMLDOMNodeListPtr CSimpleXMLParser::SelectNodes(LPCTSTR strXPathFilter, MSXML2::IXMLDOMNodePtr pXMLNode) { return pXMLNode-&gt;selectNodes(_bstr_t(strXPathFilter)); } </code></pre> <p>When run, the top record is definitely being set to the <code>&lt;report&gt;</code> element properly. I can do all sorts of things with it, like getting its child nodes (through the MSXML interface, not through my wrapper) or its name, etc. I know that my wrapper <em>can</em> work, because I use it elsewhere in the app for parsing an XML configuration file, and that works flawlessly.</p> <p>I thought maybe I was doing something faulty with the XPath query expression, but every permutation I could think of gives no joy. The <code>MSXML::IXMLDOMNodeListPtr</code> returned by <code>IXMLDOMNodePtr::SelectNodes()</code> is always of length 0 when I try to deal with this XML file.</p> <p>This is driving me crazy.</p>
[ { "answer_id": 284734, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 4, "selected": true, "text": "/report/subreport/record/field/value pXMLDoc->setProperty(_bstr_t(\"SelectionNamespaces\"),\n _bstr_t(\"xmlns:r=\"http://www.**.com/**\"));\n selectNodes() /r:report/r:subreport/r:record/r:field/r:value" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24529/" ]
284,722
<p>I'm trying to insert a comment character into a string something similar to this:</p> <pre><code>-CreateVideoTracker VT1 "vt name" </code></pre> <p>becomes</p> <pre><code>-CreateVideoTracker VT1 # "vt name" </code></pre> <p>The VT1 word can actually be anything, so I'm using the regex</p> <pre><code>$line =~ s/\-CreateVideoTracker \w/\-CreateVideoTracker \w # /g; </code></pre> <p>which gives me the result:</p> <pre><code>-CreateVideoTracker w #T1 "vt name" </code></pre> <p>Is there any way to do this with a single regex, or do I need to split up the string and insert the comment manually?</p>
[ { "answer_id": 284739, "author": "Alnitak", "author_id": 6782, "author_profile": "https://Stackoverflow.com/users/6782", "pm_score": 4, "selected": true, "text": "$line =~ s/^(\\-CreateVideoTracker)\\s+(\\w+)/$1 $2 #/;\n $1 $2" }, { "answer_id": 285921, "author": "Brad Gilbert", "author_id": 1337, "author_profile": "https://Stackoverflow.com/users/1337", "pm_score": 2, "selected": false, "text": "\\K $line=~s/^\\-CreateVideoTracker\\s+\\w+\\K/ #/;\n" }, { "answer_id": 286390, "author": "ysth", "author_id": 17389, "author_profile": "https://Stackoverflow.com/users/17389", "pm_score": 0, "selected": false, "text": "$line =~ s/\\-CreateVideoTracker \\w/\\-CreateVideoTracker \\w # /g;\n $line =~ s/\\-CreateVideoTracker (\\w+)/\\-CreateVideoTracker $1 # /g;\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284722", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23504/" ]
284,732
<p><strong>First a bit of background.</strong> </p> <p>I have been working on the MS platform for my entire development career. Up until 2 weeks ago, I had never booted any other OS than 98/XP/Vista. I started using VSS long long ago, and made the change to SVN about 2 years ago. With SVN I use TortiseSVN and use the standard branch/tag/trunk setup.</p> <p>My projects are also self contained, meaning I can go to a fresh dev box, pull down a single repository, open VS, press F5 and it will run (most of the time). All dependencies are stored in a <code>lib</code> folder, source code is in a <code>src</code> folder, etc...</p> <p>In an effort to learn new things, I've decided to build a Ruby on Rails application and have created a Ubuntu based development machine. I have a SVN server up and running and am working with another person on this project. He happens to be using a Mac for his development machine.</p> <p><strong>And now for the issues.</strong></p> <p>I seem to be struggling with how to manage the various versions of ruby, rails and all of the plugin's I'm working with. I also seem to be struggling with using SVN on Ubuntu. </p> <p>So Ubuntu comes with Ruby pre-installed. I want to say it's version 1.8.5. Either way, I had a bunch of gems to install for the plugin I'm using (Community Engine). Being new to *nix, I didn't use <code>sudo</code> when installing them and ran into all sorts of issues. I ended up blowing away Ruby completely and starting fresh. That seemed to work.</p> <p>The problem is though, that after I commit my code, and the other guy gets latest, he has to go through the whole process of installing gems.</p> <p><strong>What is the best practice for managing gems and plug-ins in a RoR application?</strong> I don't care if a zillion files get added to SVN. Diskspace and network bandwidth are cheap. I just don't know how to do this correctly.</p> <p>So on to SVN.</p> <p>I have installed RapidSVN, but very frequently run into issues with folders getting locked. A couple times I realized my mistake, others, I had no clue why. But in both scenarios, i couldn't fix it. I ended up making a backup of my code, pulling down a new working copy, then manually moving over changes and being a bit smarter when committing them to the project.</p> <p>I actually RTFM a bit last night and found that I'm supposed to create a bookmark for my repos, then do a "checkout working copy" from that bookmark. I'm not sure why, but ok, that's what the manual says...</p> <p><strong>What are some best practices for using SVN on a RoR project on Ubuntu?</strong></p> <p>I'm literally looking for a step by step process on this one.</p> <p><em>edit</em> I forgot to mention, I use NetBeans for my IDE, although i have not looked to see what kind of SVN support it has, if any. I looked at RubyMine, and would love to use it, but it appears to be too unstable right now.</p>
[ { "answer_id": 285216, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 3, "selected": true, "text": "config/environment.rb config.gem sudo rake gems:install environment.rb rake gems:unpack .c gcc" }, { "answer_id": 296486, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "#!/bin/bash\n\n# reinstall the plugin in an svn friendly way\nplugin=\"some_plugin\"\nplugin_url=\"http://some_server/some_plugin/trunk\"\n\nfor f in site1 site2 site3\ndo\n echo $f\n cd ~/rails/$f\n\n svn delete vendor/plugins/$plugin\n rm -rf vendor/plugins/$plugin\n svn -m \"remove $plugin\" commit\n script/plugin install $plugin_url\n svn add vendor/plugins/$plugin\n svn -m \"add $plugin\" commit\n\ndone\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23458/" ]
284,740
<p>What is the preferred way to insert strings that can contain both single and double quotes (",') into MySql using DBI? For example, <code>$val1</code> and <code>$val2</code> can contain quotes:</p> <pre><code>my $dbh = DBI-&gt;connect( ... ); my $sql = "insert into tbl_name(col_one,col_two) values($val1, $val2)"; my $sth = $dbh-&gt;prepare($sql); $sth-&gt;execute(); </code></pre>
[ { "answer_id": 284758, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 6, "selected": true, "text": "$sth = $dbh->prepare(\"insert into tbl_name(col_one,col_two) values(?,?)\");\n$sth->execute($val1, $val2);\n $dbh->quote($var) $sql = sprintf \"SELECT foo FROM bar WHERE baz = %s\",\n $dbh->quote(q(\"Don't\"));\n" }, { "answer_id": 284762, "author": "Adam Bellaire", "author_id": 21632, "author_profile": "https://Stackoverflow.com/users/21632", "pm_score": 2, "selected": false, "text": "quote() $sql = sprintf \"SELECT foo FROM bar WHERE baz = %s\",\n $dbh->quote(\"Don't\");\n $sql = sprintf \"SELECT foo FROM bar WHERE baz = %s\",\n $dbh->quote(q(\"Don't\"));\n" }, { "answer_id": 50491382, "author": "jjohn", "author_id": 16513, "author_profile": "https://Stackoverflow.com/users/16513", "pm_score": 2, "selected": false, "text": " my $dbh = DBI->connect(...);\n my $name_pairs = get_csv_data(\"data.csv\");\n my $sth = $dbh->prepare(\"INSERT INTO t1 (first_name, last_name) VALUES (?,?)\");\n for my $pair (@$name_pairs) {\n unless ($sth->execute(@$pair)) {\n warn($sth->errstr);\n }\n }\n # Here, I am confident about the hash keys, less so about the values\n $sql = sprintf(\"INSERT INTO t1 (%s) VALUES (%s)\",\n join(\",\", keys(%hash)),\n join(\",\" map { $dbh->quote($_) } values(%hash))\n );\n $sth = $dbh->prepare($sql);\n unless ($sth->execute) {\n warn($sth->{Statement});\n }\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284740", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
284,741
<p>I have a j2me client that would post some chunked encoded data to a webserver. I'd like to process the data in python. The script is being run as a CGI one, but apparently apache will refuse a chunked encoded post request to a CGI script. As far as I could see mod_python, WSGI and FastCGI are no go too.</p> <p>I'd like to know if there is a way to have a python script process this kind of input. I'm open to any suggestion (e.g. a confoguration setting in apache2 that would assemble the chunks, a standalone python server that would do the same, etc.) I did quite a bit of googling and didn't find anything usable, which is quite strange.</p> <p>I know that resorting to java on the server side would be a solution, but I just can't imagine that this can't be solved with apache + python.</p>
[ { "answer_id": 1187738, "author": "Nathan de Vries", "author_id": 11109, "author_profile": "https://Stackoverflow.com/users/11109", "pm_score": 3, "selected": false, "text": "ProxyRequests Off\n\n<Proxy http://example.com:81>\n Order deny,allow\n Allow from all\n</Proxy>\n\n<VirtualHost *:80>\n SetEnv proxy-sendcl 1\n ProxyPass / http://example.com:81/\n ProxyPassReverse / http://example.com:81/\n ProxyPreserveHost On\n ProxyVia Full\n\n <Directory proxy:*>\n Order deny,allow\n Allow from all\n </Directory>\n\n</VirtualHost>\n\nListen 81\n\n<VirtualHost *:81>\n ServerName example.com\n # Your Python application configuration goes here\n</VirtualHost>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284741", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5695/" ]
284,744
<p>I'm creating a control and need to pass it the current logon user as a parameter (declaratively)</p> <p>I tried this but didn't work (I got "&lt;%= User.Identity.Name %>" as value):</p> <pre><code>&lt;cc1:MyControl id="myid" runat="server" User="&lt;%= User.Identity.Name %&gt;" /&gt; </code></pre> <p>Is there a way to do it?</p>
[ { "answer_id": 284747, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 0, "selected": false, "text": "User=\"<%= User.Identity.Name %>\"\n" }, { "answer_id": 284767, "author": "Josh Hinman", "author_id": 2527, "author_profile": "https://Stackoverflow.com/users/2527", "pm_score": 1, "selected": false, "text": "myid.User = User.Identity.Name\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1782/" ]
284,748
<p>Is there any way in a Win32 environment to "tune" the timeout on a socket <code>connect()</code> call? Specifically, I would like to increase the timeout length. The sockets in use are non-blocking. Thanks!</p>
[ { "answer_id": 286814, "author": "fhe", "author_id": 4445, "author_profile": "https://Stackoverflow.com/users/4445", "pm_score": 3, "selected": true, "text": "connect() select()" }, { "answer_id": 9867611, "author": "kuchi", "author_id": 903444, "author_profile": "https://Stackoverflow.com/users/903444", "pm_score": 0, "selected": false, "text": "struct timeval timeout; \ntimeout.tv_sec = 10;\ntimeout.tv_usec = 0;\n\nif (setsockopt (sockfd, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout,\n sizeof(timeout)) < 0)\n error(\"setsockopt failed\\n\");\n\nif (setsockopt (sockfd, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout,\n sizeof(timeout)) < 0)\n error(\"setsockopt failed\\n\");\n signal( SIGALRM, connect_alarm ); /* connect_alarm is you signal handler */\nalarm( secs ); /* secs is your timeout in seconds */\nif ( connect( fd, addr, addrlen ) < 0 )\n{\n if ( errno == EINTR ) /* timeout, do something below */\n ...\n}\nalarm( 0 ); /* cancel the alarm */\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16457/" ]
284,751
<p>I am writing a quick and dirty application that reads all the files from a given directory. I'm currently using the OpenFileDialog to choose a directory and just culling off the file name that it provides. It seems like there should be a way to just choose directories though, but in a quick browsing of MSDN I didn't find it. </p> <p>If you have a way in winforms or more preferably in WPF I'm all ears.</p>
[ { "answer_id": 15790253, "author": "Geoff", "author_id": 2240898, "author_profile": "https://Stackoverflow.com/users/2240898", "pm_score": 4, "selected": false, "text": "using FORMS = System.Windows.Forms;\n\nvar dialog = new System.Windows.Forms.FolderBrowserDialog();\nFORMS.DialogResult result = dialog.ShowDialog();\nif (result == FORMS.DialogResult.OK)\n{\n MessageBox.Show(\"Result: \" + dialog.SelectedPath);\n}\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1327/" ]
284,761
<p>I have an implementation of default handler. When it gets to a &nbsp; in the character data it stops parsing. Is there any reason that it is doing this? Are there additional properties that I need to set in order for it to deal with &amp;nbsp?</p>
[ { "answer_id": 285075, "author": "Ben Noland", "author_id": 32899, "author_profile": "https://Stackoverflow.com/users/32899", "pm_score": 0, "selected": false, "text": "&nbsp; &#160;" }, { "answer_id": 335689, "author": "tcurdt", "author_id": 33165, "author_profile": "https://Stackoverflow.com/users/33165", "pm_score": 3, "selected": true, "text": "<!DOCTYPE document SYSTEM \"document.dtd\" [ \n<!ENTITY nbsp \"&#160;\"> \n]>\n &#160;" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284761", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35140/" ]
284,766
<p>If I have a DrawingVisual in WPF with Opacity=0, is that enough for it not to be drawn? We have hundreds of DrawingVisuals on a Canvas, and are currently setting Opacity=0 on the visuals that are not to be displayed, and I wanted to make sure there is no rendering performance hit for rendering a DrawingVisual with Opacity=0.</p> <p>UPDATE: I have discovered through testing that there IS overhead when Opacity=0, but since DrawingVisual doesn't have a Visibility property, I don't know how else you would tell it to not be displayed unless you actualy remove it from the visual tree, so any suggestions are welcome. </p>
[ { "answer_id": 716469, "author": "eesh", "author_id": 85666, "author_profile": "https://Stackoverflow.com/users/85666", "pm_score": 2, "selected": false, "text": "DrawingGroup Drawing DrawingGroup Drawing DrawingGroup Drawing DrawingCollection DrawingGroup.Children DrawingGroup.Children.Add() DrawingCollection Insert Remove RemoveAt Clear Drawing DrawingGroup DrawingGroup Drawing DrawingGroup Drawing DrawingGroup DrawingGroup Drawing Drawing DrawingGroup" }, { "answer_id": 11899486, "author": "keft", "author_id": 762979, "author_profile": "https://Stackoverflow.com/users/762979", "pm_score": 2, "selected": true, "text": "using (DrawingContext dc = RenderOpen()) {} //Hide this visual\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18967/" ]
284,774
<p>How do you automate <a href="http://en.wikipedia.org/wiki/Integration_testing" rel="noreferrer">integration testing</a>? I use JUnit for some of these tests. This is one of the solutions or is totally wrong? What do you suggest?</p>
[ { "answer_id": 284851, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 3, "selected": false, "text": "@BeforeSuite @AfterSuite" }, { "answer_id": 285284, "author": "Johannes Brodwall", "author_id": 27658, "author_profile": "https://Stackoverflow.com/users/27658", "pm_score": 6, "selected": false, "text": "Hypersonic or H2 @BeforeSuite @Before JWebUnit @BeforeClass\npublic static void startServer() throws Exception {\n System.setProperty(\"hibernate.hbm2ddl.auto\", \"create\");\n System.setProperty(\"hibernate.dialect\", \"...\");\n DriverManagerDataSource dataSource = new DriverManagerDataSource();\n dataSource.setJdbcUrl(\"jdbc:hsqldb:mem:mytest\");\n new org.mortbay.jetty.plus.naming.Resource(\n \"jdbc/primaryDs\", dataSource);\n\n\n Server server = new Server(0);\n WebAppContext webAppContext = new WebAppContext(\"src/main/webapp\", \"/\");\n server.addHandler(webAppContext);\n server.start();\n webServerPort = server.getConnectors()[0].getLocalPort();\n}\n\n// From JWebUnit\nprivate WebTestCase tester = new WebTestCase();\n\n@Before\npublic void createTestContext() {\n tester.getTestContext().setBaseUrl(\"http://localhost:\" + webServerPort + \"/\");\n dao.deleteAll(dao.find(Product.class));\n dao.flushChanges();\n}\n\n@Test\npublic void createNewProduct() throws Exception {\n String productName = uniqueName(\"product\");\n int price = 54222;\n\n tester.beginAt(\"/products/new.html\");\n tester.setTextField(\"productName\", productName);\n tester.setTextField(\"price\", Integer.toString(price));\n tester.submit(\"Create\");\n\n Collection<Product> products = dao.find(Product.class);\n assertEquals(1, products.size());\n Product product = products.iterator().next();\n assertEquals(productName, product.getProductName());\n assertEquals(price, product.getPrice());\n}\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284774", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36678/" ]
284,775
<p>How do I convert a DateTime structure to its equivalent <a href="http://www.w3.org/Protocols/rfc822/#z28" rel="noreferrer">RFC 822 date-time</a> formatted string representation <strong>and</strong> parse this string representation back to a DateTime structure in .NET? The RFC-822 date-time format is used in a number of specifications such as the <a href="http://www.rssboard.org/rss-specification" rel="noreferrer">RSS Syndication Format</a>.</p>
[ { "answer_id": 284785, "author": "Oppositional", "author_id": 2029, "author_profile": "https://Stackoverflow.com/users/2029", "pm_score": 6, "selected": true, "text": "/// <summary>\n/// Provides methods for converting <see cref=\"DateTime\"/> structures \n/// to and from the equivalent <a href=\"http://www.w3.org/Protocols/rfc822/#z28\">RFC 822</a> \n/// string representation.\n/// </summary>\npublic class Rfc822DateTime\n{\n //============================================================\n // Private members\n //============================================================\n #region Private Members\n /// <summary>\n /// Private member to hold array of formats that RFC 822 date-time representations conform to.\n /// </summary>\n private static string[] formats = new string[0];\n /// <summary>\n /// Private member to hold the DateTime format string for representing a DateTime in the RFC 822 format.\n /// </summary>\n private const string format = \"ddd, dd MMM yyyy HH:mm:ss K\";\n #endregion\n\n //============================================================\n // Public Properties\n //============================================================\n #region Rfc822DateTimeFormat\n /// <summary>\n /// Gets the custom format specifier that may be used to represent a <see cref=\"DateTime\"/> in the RFC 822 format.\n /// </summary>\n /// <value>A <i>DateTime format string</i> that may be used to represent a <see cref=\"DateTime\"/> in the RFC 822 format.</value>\n /// <remarks>\n /// <para>\n /// This method returns a string representation of a <see cref=\"DateTime\"/> that utilizes the time zone \n /// offset (local differential) to represent the offset from Greenwich mean time in hours and minutes. \n /// The <see cref=\"Rfc822DateTimeFormat\"/> is a valid date-time format string for use \n /// in the <see cref=\"DateTime.ToString(String, IFormatProvider)\"/> method.\n /// </para>\n /// <para>\n /// The <a href=\"http://www.w3.org/Protocols/rfc822/#z28\">RFC 822</a> Date and Time specification \n /// specifies that the year will be represented as a two-digit value, but the \n /// <a href=\"http://www.rssboard.org/rss-profile#data-types-datetime\">RSS Profile</a> recommends that \n /// all date-time values should use a four-digit year. The <see cref=\"Rfc822DateTime\"/> class \n /// follows the RSS Profile recommendation when converting a <see cref=\"DateTime\"/> to the equivalent \n /// RFC 822 string representation.\n /// </para>\n /// </remarks>\n public static string Rfc822DateTimeFormat\n {\n get\n {\n return format;\n }\n }\n #endregion\n\n #region Rfc822DateTimePatterns\n /// <summary>\n /// Gets an array of the expected formats for RFC 822 date-time string representations.\n /// </summary>\n /// <value>\n /// An array of the expected formats for RFC 822 date-time string representations \n /// that may used in the <see cref=\"DateTime.TryParseExact(String, string[], IFormatProvider, DateTimeStyles, out DateTime)\"/> method.\n /// </value>\n /// <remarks>\n /// The array of the expected formats that is returned assumes that the RFC 822 time zone \n /// is represented as or converted to a local differential representation.\n /// </remarks>\n /// <seealso cref=\"ConvertZoneToLocalDifferential(String)\"/>\n public static string[] Rfc822DateTimePatterns\n {\n get\n {\n if (formats.Length > 0)\n {\n return formats;\n }\n else\n {\n formats = new string[35];\n\n // two-digit day, four-digit year patterns\n formats[0] = \"ddd',' dd MMM yyyy HH':'mm':'ss'.'fffffff zzzz\";\n formats[1] = \"ddd',' dd MMM yyyy HH':'mm':'ss'.'ffffff zzzz\";\n formats[2] = \"ddd',' dd MMM yyyy HH':'mm':'ss'.'fffff zzzz\";\n formats[3] = \"ddd',' dd MMM yyyy HH':'mm':'ss'.'ffff zzzz\";\n formats[4] = \"ddd',' dd MMM yyyy HH':'mm':'ss'.'fff zzzz\";\n formats[5] = \"ddd',' dd MMM yyyy HH':'mm':'ss'.'ff zzzz\";\n formats[6] = \"ddd',' dd MMM yyyy HH':'mm':'ss'.'f zzzz\";\n formats[7] = \"ddd',' dd MMM yyyy HH':'mm':'ss zzzz\";\n\n // two-digit day, two-digit year patterns\n formats[8] = \"ddd',' dd MMM yy HH':'mm':'ss'.'fffffff zzzz\";\n formats[9] = \"ddd',' dd MMM yy HH':'mm':'ss'.'ffffff zzzz\";\n formats[10] = \"ddd',' dd MMM yy HH':'mm':'ss'.'fffff zzzz\";\n formats[11] = \"ddd',' dd MMM yy HH':'mm':'ss'.'ffff zzzz\";\n formats[12] = \"ddd',' dd MMM yy HH':'mm':'ss'.'fff zzzz\";\n formats[13] = \"ddd',' dd MMM yy HH':'mm':'ss'.'ff zzzz\";\n formats[14] = \"ddd',' dd MMM yy HH':'mm':'ss'.'f zzzz\";\n formats[15] = \"ddd',' dd MMM yy HH':'mm':'ss zzzz\";\n\n // one-digit day, four-digit year patterns\n formats[16] = \"ddd',' d MMM yyyy HH':'mm':'ss'.'fffffff zzzz\";\n formats[17] = \"ddd',' d MMM yyyy HH':'mm':'ss'.'ffffff zzzz\";\n formats[18] = \"ddd',' d MMM yyyy HH':'mm':'ss'.'fffff zzzz\";\n formats[19] = \"ddd',' d MMM yyyy HH':'mm':'ss'.'ffff zzzz\";\n formats[20] = \"ddd',' d MMM yyyy HH':'mm':'ss'.'fff zzzz\";\n formats[21] = \"ddd',' d MMM yyyy HH':'mm':'ss'.'ff zzzz\";\n formats[22] = \"ddd',' d MMM yyyy HH':'mm':'ss'.'f zzzz\";\n formats[23] = \"ddd',' d MMM yyyy HH':'mm':'ss zzzz\";\n\n // two-digit day, two-digit year patterns\n formats[24] = \"ddd',' d MMM yy HH':'mm':'ss'.'fffffff zzzz\";\n formats[25] = \"ddd',' d MMM yy HH':'mm':'ss'.'ffffff zzzz\";\n formats[26] = \"ddd',' d MMM yy HH':'mm':'ss'.'fffff zzzz\";\n formats[27] = \"ddd',' d MMM yy HH':'mm':'ss'.'ffff zzzz\";\n formats[28] = \"ddd',' d MMM yy HH':'mm':'ss'.'fff zzzz\";\n formats[29] = \"ddd',' d MMM yy HH':'mm':'ss'.'ff zzzz\";\n formats[30] = \"ddd',' d MMM yy HH':'mm':'ss'.'f zzzz\";\n formats[31] = \"ddd',' d MMM yy HH':'mm':'ss zzzz\";\n\n // Fall back patterns\n formats[32] = \"yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK\"; // RoundtripDateTimePattern\n formats[33] = DateTimeFormatInfo.InvariantInfo.UniversalSortableDateTimePattern;\n formats[34] = DateTimeFormatInfo.InvariantInfo.SortableDateTimePattern;\n\n return formats;\n }\n }\n }\n #endregion\n\n //============================================================\n // Public Methods\n //============================================================\n #region Parse(string s)\n /// <summary>\n /// Converts the specified string representation of a date and time to its <see cref=\"DateTime\"/> equivalent.\n /// </summary>\n /// <param name=\"s\">A string containing a date and time to convert.</param>\n /// <returns>\n /// A <see cref=\"DateTime\"/> equivalent to the date and time contained in <paramref name=\"s\"/>, \n /// expressed as <i>Coordinated Universal Time (UTC)</i>.\n /// </returns>\n /// <remarks>\n /// The string <paramref name=\"s\"/> is parsed using formatting information in the <see cref=\"DateTimeFormatInfo.InvariantInfo\"/> object.\n /// </remarks>\n /// <exception cref=\"ArgumentNullException\"><paramref name=\"s\"/> is a <b>null</b> reference (Nothing in Visual Basic).</exception>\n /// <exception cref=\"ArgumentNullException\"><paramref name=\"s\"/> is an empty string.</exception>\n /// <exception cref=\"FormatException\"><paramref name=\"s\"/> does not contain a valid RFC 822 string representation of a date and time.</exception>\n public static DateTime Parse(string s)\n {\n //------------------------------------------------------------\n // Validate parameter\n //------------------------------------------------------------\n if (String.IsNullOrEmpty(s))\n {\n throw new ArgumentNullException(\"s\");\n }\n\n DateTime result;\n if (Rfc822DateTime.TryParse(s, out result))\n {\n return result;\n }\n else\n {\n throw new FormatException(String.Format(null, \"{0} is not a valid RFC 822 string representation of a date and time.\", s));\n }\n }\n #endregion\n\n #region ConvertZoneToLocalDifferential(string s)\n /// <summary>\n /// Converts the time zone component of an RFC 822 date and time string representation to its local differential (time zone offset).\n /// </summary>\n /// <param name=\"s\">A string containing an RFC 822 date and time to convert.</param>\n /// <returns>A date and time string that uses local differential to describe the time zone equivalent to the date and time contained in <paramref name=\"s\"/>.</returns>\n /// <exception cref=\"ArgumentNullException\"><paramref name=\"s\"/> is a <b>null</b> reference (Nothing in Visual Basic).</exception>\n /// <exception cref=\"ArgumentNullException\"><paramref name=\"s\"/> is an empty string.</exception>\n public static string ConvertZoneToLocalDifferential(string s)\n {\n string zoneRepresentedAsLocalDifferential = String.Empty;\n\n //------------------------------------------------------------\n // Validate parameter\n //------------------------------------------------------------\n if (String.IsNullOrEmpty(s))\n {\n throw new ArgumentNullException(\"s\");\n }\n\n if(s.EndsWith(\" UT\", StringComparison.OrdinalIgnoreCase))\n {\n zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(\" UT\") + 1) ), \"+00:00\");\n }\n else if (s.EndsWith(\" GMT\", StringComparison.OrdinalIgnoreCase))\n {\n zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(\" GMT\") + 1 ) ), \"+00:00\");\n }\n else if (s.EndsWith(\" EST\", StringComparison.OrdinalIgnoreCase))\n {\n zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(\" EST\") + 1)), \"-05:00\");\n }\n else if (s.EndsWith(\" EDT\", StringComparison.OrdinalIgnoreCase))\n {\n zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(\" EDT\") + 1)), \"-04:00\");\n }\n else if (s.EndsWith(\" CST\", StringComparison.OrdinalIgnoreCase))\n {\n zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(\" CST\") + 1)), \"-06:00\");\n }\n else if (s.EndsWith(\" CDT\", StringComparison.OrdinalIgnoreCase))\n {\n zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(\" CDT\") + 1)), \"-05:00\");\n }\n else if (s.EndsWith(\" MST\", StringComparison.OrdinalIgnoreCase))\n {\n zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(\" MST\") + 1)), \"-07:00\");\n }\n else if (s.EndsWith(\" MDT\", StringComparison.OrdinalIgnoreCase))\n {\n zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(\" MDT\") + 1)), \"-06:00\");\n }\n else if (s.EndsWith(\" PST\", StringComparison.OrdinalIgnoreCase))\n {\n zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(\" PST\") + 1)), \"-08:00\");\n }\n else if (s.EndsWith(\" PDT\", StringComparison.OrdinalIgnoreCase))\n {\n zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(\" PDT\") + 1)), \"-07:00\");\n }\n else if (s.EndsWith(\" Z\", StringComparison.OrdinalIgnoreCase))\n {\n zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(\" Z\") + 1)), \"+00:00\");\n }\n else if (s.EndsWith(\" A\", StringComparison.OrdinalIgnoreCase))\n {\n zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(\" A\") + 1)), \"-01:00\");\n }\n else if (s.EndsWith(\" M\", StringComparison.OrdinalIgnoreCase))\n {\n zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(\" M\") + 1)), \"-12:00\");\n }\n else if (s.EndsWith(\" N\", StringComparison.OrdinalIgnoreCase))\n {\n zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(\" N\") + 1)), \"+01:00\");\n }\n else if (s.EndsWith(\" Y\", StringComparison.OrdinalIgnoreCase))\n {\n zoneRepresentedAsLocalDifferential = String.Concat(s.Substring(0, (s.LastIndexOf(\" Y\") + 1)), \"+12:00\");\n }\n else\n {\n zoneRepresentedAsLocalDifferential = s;\n }\n\n return zoneRepresentedAsLocalDifferential;\n }\n #endregion\n\n #region ToString(DateTime utcDateTime)\n /// <summary>\n /// Converts the value of the specified <see cref=\"DateTime\"/> object to its equivalent string representation.\n /// </summary>\n /// <param name=\"utcDateTime\">The Coordinated Universal Time (UTC) <see cref=\"DateTime\"/> to convert.</param>\n /// <returns>A RFC 822 string representation of the value of the <paramref name=\"utcDateTime\"/>.</returns>\n /// <exception cref=\"ArgumentException\">The specified <paramref name=\"utcDateTime\"/> object does not represent a <see cref=\"DateTimeKind.Utc\">Coordinated Universal Time (UTC)</see> value.</exception>\n public static string ToString(DateTime utcDateTime)\n {\n if (utcDateTime.Kind != DateTimeKind.Utc)\n {\n throw new ArgumentException(\"utcDateTime\");\n }\n\n return utcDateTime.ToString(Rfc822DateTime.Rfc822DateTimeFormat, DateTimeFormatInfo.InvariantInfo);\n }\n #endregion\n\n #region TryParse(string s, out DateTime result)\n /// <summary>\n /// Converts the specified string representation of a date and time to its <see cref=\"DateTime\"/> equivalent.\n /// </summary>\n /// <param name=\"s\">A string containing a date and time to convert.</param>\n /// <param name=\"result\">\n /// When this method returns, contains the <see cref=\"DateTime\"/> value equivalent to the date and time \n /// contained in <paramref name=\"s\"/>, expressed as <i>Coordinated Universal Time (UTC)</i>, \n /// if the conversion succeeded, or <see cref=\"DateTime.MinValue\">MinValue</see> if the conversion failed. \n /// The conversion fails if the s parameter is a <b>null</b> reference (Nothing in Visual Basic), \n /// or does not contain a valid string representation of a date and time. \n /// This parameter is passed uninitialized.\n /// </param>\n /// <returns><b>true</b> if the <paramref name=\"s\"/> parameter was converted successfully; otherwise, <b>false</b>.</returns>\n /// <remarks>\n /// The string <paramref name=\"s\"/> is parsed using formatting information in the <see cref=\"DateTimeFormatInfo.InvariantInfo\"/> object. \n /// </remarks>\n public static bool TryParse(string s, out DateTime result)\n {\n //------------------------------------------------------------\n // Attempt to convert string representation\n //------------------------------------------------------------\n bool wasConverted = false;\n result = DateTime.MinValue;\n\n if (!String.IsNullOrEmpty(s))\n {\n DateTime parseResult;\n if (DateTime.TryParseExact(Rfc822DateTime.ConvertZoneToLocalDifferential(s), Rfc822DateTime.Rfc822DateTimePatterns, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AdjustToUniversal, out parseResult))\n {\n result = DateTime.SpecifyKind(parseResult, DateTimeKind.Utc);\n wasConverted = true;\n }\n }\n\n return wasConverted;\n }\n #endregion\n}\n" }, { "answer_id": 554093, "author": "Jeff Woodman", "author_id": 42689, "author_profile": "https://Stackoverflow.com/users/42689", "pm_score": 6, "selected": false, "text": " DateTime today = DateTime.Now;\n String rfc822 = today.ToString(\"r\");\n Console.WriteLine(\"RFC-822 date: {0}\", rfc822);\n\n DateTime parsedRFC822 = DateTime.Parse(rfc822);\n Console.WriteLine(\"Date: {0}\", parsedRFC822);\n TimeZone tz = TimeZone.CurrentTimeZone;\n\nString offset = tz.GetUtcOffset().ToString();\n// My locale is Mountain time; offset is set to \"-07:00:00\"\n// if local time is behind utc time, offset should start with \"-\".\n// otherwise, add a plus sign to the beginning of the string.\nif (!offset.StartsWith(\"-\"))\n offset = \"+\" + offset; // Add a (+) if it's a UTC+ timezone\noffset = offset.Substring(0,6); // only want the first 6 chars.\noffset = offset.Replace(\":\", \"\"); // remove colons.\n// offset now looks something like \"-0700\".\nrfc822 = rfc822.Replace(\"GMT\", offset);\n// The rfc822 string can now be parsed back to a DateTime object,\n// with the local time accounted for.\nDateTime new = DateTime.Parse(rfc822);\n" }, { "answer_id": 2465945, "author": "Kirk Liemohn", "author_id": 74276, "author_profile": "https://Stackoverflow.com/users/74276", "pm_score": 2, "selected": false, "text": "private string AsString(DateTimeOffset dateTime)\n{\n if (dateTime.Offset == Atom10FeedFormatter.zeroOffset)\n {\n return dateTime.ToUniversalTime().ToString(\"ddd, dd MMM yyyy HH:mm:ss Z\", CultureInfo.InvariantCulture);\n }\n StringBuilder builder = new StringBuilder(dateTime.T)oString(\"ddd, dd MMM yyyy HH:mm:ss zzz\", CultureInfo.InvariantCulture));\n builder.Remove(builder.Length - 3, 1);\n return builder.ToString();\n}\n" }, { "answer_id": 10426999, "author": "Eric Boumendil", "author_id": 249742, "author_profile": "https://Stackoverflow.com/users/249742", "pm_score": 1, "selected": false, "text": "private DateTimeOffset? ParseDate(string date)\n {\n const string FORMAT = \"ddd, d MMM yyyy HH:mm:ss zzz\";\n const string FORMAT2 = \"ddd, dd MMM yyyy HH:mm:ss zzz\";\n const string FORMAT3 = \"dd MMM yyyy HH:mm:ss zzz\";\n const string FORMAT4 = \"d MMM yyyy HH:mm:ss zzz\";\n DateTimeOffset d;\n if (DateTimeOffset.TryParseExact(date, new string[] { FORMAT, FORMAT2, FORMAT3, FORMAT4 }, CultureInfo.InvariantCulture, DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite, out d))\n return d;\n return null;\n }\n DateTimeOffset? date = ParseDate(\"Thu, 5 Apr 2012 23:47:37 +0200\");\nConsole.WriteLine(date.ToString());\n// => 05/04/2012 23:47:37 +02:00\n" }, { "answer_id": 12691951, "author": "Raymond Powell", "author_id": 1714561, "author_profile": "https://Stackoverflow.com/users/1714561", "pm_score": 1, "selected": false, "text": "namespace MyNamespace\n{\n public static partial class ExtensionMethods\n {\n public static string ToRFC822String(this DateTime timestamp)\n {\n return timestamp.ToString(\"ddd',' d MMM yyyy HH':'mm':'ss\")\n + \" \"\n + timestamp.ToString(\"zzzz\").Replace(\":\", \"\");\n }\n }\n }\n using MyNamespace;\n\n ....\n\n string MyRFC822String = DateTime.Now.ToRFC822String();\n" }, { "answer_id": 37550344, "author": "Sasha", "author_id": 543591, "author_profile": "https://Stackoverflow.com/users/543591", "pm_score": 2, "selected": false, "text": "System.ServiceModel.Syndication.Rss20FeedFormatter public static class DateTimeParser\n{\n public static DateTimeOffset ParseDateTimeRFC822(string dateTimeString)\n {\n StringBuilder dateTimeStringBuilder = new StringBuilder(dateTimeString.Trim());\n if (dateTimeStringBuilder.Length < 18)\n {\n throw new FormatException(\"Invalid date format. Expected date in RFC 822 format\");\n }\n if (dateTimeStringBuilder[3] == ',')\n {\n // There is a leading (e.g.) \"Tue, \", strip it off\n dateTimeStringBuilder.Remove(0, 4);\n // There's supposed to be a space here but some implementations dont have one\n RemoveExtraWhiteSpaceAtStart(dateTimeStringBuilder);\n }\n ReplaceMultipleWhiteSpaceWithSingleWhiteSpace(dateTimeStringBuilder);\n if (char.IsDigit(dateTimeStringBuilder[1]))\n {\n // two-digit day, we are good\n }\n else\n {\n dateTimeStringBuilder.Insert(0, '0');\n }\n if (dateTimeStringBuilder.Length < 19)\n {\n throw new FormatException(\"Invalid date format. Expected date in RFC 822 format\");\n }\n bool thereAreSeconds = (dateTimeStringBuilder[17] == ':');\n int timeZoneStartIndex;\n if (thereAreSeconds)\n {\n timeZoneStartIndex = 21;\n }\n else\n {\n timeZoneStartIndex = 18;\n }\n string timeZoneSuffix = dateTimeStringBuilder.ToString().Substring(timeZoneStartIndex);\n dateTimeStringBuilder.Remove(timeZoneStartIndex, dateTimeStringBuilder.Length - timeZoneStartIndex);\n bool isUtc;\n dateTimeStringBuilder.Append(NormalizeTimeZone(timeZoneSuffix, out isUtc));\n string wellFormattedString = dateTimeStringBuilder.ToString();\n\n DateTimeOffset theTime;\n string parseFormat;\n if (thereAreSeconds)\n {\n parseFormat = \"dd MMM yyyy HH:mm:ss zzz\";\n }\n else\n {\n parseFormat = \"dd MMM yyyy HH:mm zzz\";\n }\n if (DateTimeOffset.TryParseExact(wellFormattedString, parseFormat,\n CultureInfo.InvariantCulture.DateTimeFormat,\n (isUtc ? DateTimeStyles.AdjustToUniversal : DateTimeStyles.None), out theTime))\n {\n return theTime;\n }\n throw new FormatException(\"Invalid date format. Expected date in RFC 822 format\");\n }\n\n static string NormalizeTimeZone(string rfc822TimeZone, out bool isUtc)\n {\n isUtc = false;\n // return a string in \"-08:00\" format\n if (rfc822TimeZone[0] == '+' || rfc822TimeZone[0] == '-')\n {\n // the time zone is supposed to be 4 digits but some feeds omit the initial 0\n StringBuilder result = new StringBuilder(rfc822TimeZone);\n if (result.Length == 4)\n {\n // the timezone is +/-HMM. Convert to +/-HHMM\n result.Insert(1, '0');\n }\n result.Insert(3, ':');\n return result.ToString();\n }\n switch (rfc822TimeZone)\n {\n case \"UT\":\n case \"Z\":\n isUtc = true;\n return \"-00:00\";\n case \"GMT\":\n return \"-00:00\";\n case \"A\":\n return \"-01:00\";\n case \"B\":\n return \"-02:00\";\n case \"C\":\n return \"-03:00\";\n case \"D\":\n case \"EDT\":\n return \"-04:00\";\n case \"E\":\n case \"EST\":\n case \"CDT\":\n return \"-05:00\";\n case \"F\":\n case \"CST\":\n case \"MDT\":\n return \"-06:00\";\n case \"G\":\n case \"MST\":\n case \"PDT\":\n return \"-07:00\";\n case \"H\":\n case \"PST\":\n return \"-08:00\";\n case \"I\":\n return \"-09:00\";\n case \"K\":\n return \"-10:00\";\n case \"L\":\n return \"-11:00\";\n case \"M\":\n return \"-12:00\";\n case \"N\":\n return \"+01:00\";\n case \"O\":\n return \"+02:00\";\n case \"P\":\n return \"+03:00\";\n case \"Q\":\n return \"+04:00\";\n case \"R\":\n return \"+05:00\";\n case \"S\":\n return \"+06:00\";\n case \"T\":\n return \"+07:00\";\n case \"U\":\n return \"+08:00\";\n case \"V\":\n return \"+09:00\";\n case \"W\":\n return \"+10:00\";\n case \"X\":\n return \"+11:00\";\n case \"Y\":\n return \"+12:00\";\n default:\n return \"\";\n }\n }\n\n static void RemoveExtraWhiteSpaceAtStart(StringBuilder stringBuilder)\n {\n int i = 0;\n while (i < stringBuilder.Length)\n {\n if (!char.IsWhiteSpace(stringBuilder[i]))\n {\n break;\n }\n ++i;\n }\n if (i > 0)\n {\n stringBuilder.Remove(0, i);\n }\n }\n\n static void ReplaceMultipleWhiteSpaceWithSingleWhiteSpace(StringBuilder builder)\n {\n int index = 0;\n int whiteSpaceStart = -1;\n while (index < builder.Length)\n {\n if (char.IsWhiteSpace(builder[index]))\n {\n if (whiteSpaceStart < 0)\n {\n whiteSpaceStart = index;\n // normalize all white spaces to be ' ' so that the date time parsing works\n builder[index] = ' ';\n }\n }\n else if (whiteSpaceStart >= 0)\n {\n if (index > whiteSpaceStart + 1)\n {\n // there are at least 2 spaces... replace by 1\n builder.Remove(whiteSpaceStart, index - whiteSpaceStart - 1);\n index = whiteSpaceStart + 1;\n }\n whiteSpaceStart = -1;\n }\n ++index;\n }\n // we have already trimmed the start and end so there cannot be a trail of white spaces in the end\n Debug.Assert(builder.Length == 0 || builder[builder.Length - 1] != ' ', \"The string builder doesnt end in a white space\");\n }\n}\n [DateTimeOffset][1] DateTime DateTimeOffset DateTimeOffset DateTimeOffset.ToUniversalTime() DateTimeOffset.ToLocalTime()" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284775", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2029/" ]
284,776
<p>I'm automating some source control software functionality using a dot bat script but given that our svn repos are hosted in a *NIX box, I'm facing the eternal case problem between these two worlds.</p> <p>Is there any cmd.exe function to convert the value of the Windows system variable %USERNAME% to lower case?</p> <p>Thanks much in advance!</p>
[ { "answer_id": 284834, "author": "Mauro", "author_id": 2208, "author_profile": "https://Stackoverflow.com/users/2208", "pm_score": 4, "selected": true, "text": "@echo off\ngoto :end_remarks\n*************************************************************************************\n*\n*\n* authored:Sam Wofford\n* Returns lowercase of a string\n* 12:13 PM 11/13/02\n**************************************************************************************\n:end_remarks\nsetlocal\nset errorlevel=-1\nif {%1}=={} echo NO ARG GIVEN&call :Help &goto :endit\nif {%1}=={/?} call :Help &goto :endit\ncall :set_LCASE_array a b c d e f g h i j k l m n o p q r s t u v w x y z\n\n:start\nset input=%1\nset input=%input:\"=%\nset totparams=0\ncall :COUNT_PARAMS %input%\ncall :MAKE_LOWERCASE %input%\nset errorlevel=\necho %convertedstring%\nendlocal\ngoto :eof\n:endit\necho %errorlevel%\nendlocal\ngoto :eof\n\n:MAKE_LOWERCASE\n:nextstring\nif {%1}=={} goto :eof\nset string=%1\nset /a params+=1\nset STRINGCONVERTED=\nset pos=0\n:NEXT_CHAR\nset onechar=%%string^:^~%pos%,1%%\nfor /f \"tokens=1,2 delims==\" %%a in ('set onechar') do for /f %%c in ('echo %%b') do call :checkit %%c\nif not defined STRINGCONVERTED goto :NEXT_CHAR\nshift /1\nif %params% LSS %totparams% set convertedstring=%convertedstring% &:add one space,but not at end\ngoto :nextstring\ngoto :eof\n\n:Help\necho USAGE:%~n0 string OR %~n0 \"with spaces\"\necho function returns the lowercase of the string or -1 (error)\necho strings with embedded spaces needs to be in quotes Ex. \"lower case\"\necho in a batch NTscript \"for /f %%%%A in ('lcase STRING') do set var=%%%%A\"\nset errorlevel=\ngoto :eof\n\n:checkit\nset LCFOUND=\nif /i {%1}=={echo} set STRINGCONVERTED=Y&goto :eof\nset char=%1\nfor /f \"tokens=2 delims=_=\" %%A in ('set LCASE_') do call :findit %%A %char%\n:skipit\nif defined LCFOUND (set convertedstring=%convertedstring%%ucletter%) else (set convertedstring=%convertedstring%%char%)\nset /a pos+=1\ngoto :eof\n\n:set_LCASE_array\n:setit\nif {%1}=={} goto :eof\nset LCASE_%1_=%1\nSHIFT /1\ngoto :setit\n\n:findit\nif defined LCFOUND goto :eof\nset ucletter=%1\nset lcchar=%2\nif /i {%ucletter%}=={%lcchar%} set LCFOUND=yes\ngoto :eof\n\n:COUNT_PARAMS\n:COUNTPARAMS\nif {%1}=={} goto :eof\nset /a totparams+=1\nshift /1\ngoto :COUNTPARAMS \n" }, { "answer_id": 285405, "author": "SumoRunner", "author_id": 18975, "author_profile": "https://Stackoverflow.com/users/18975", "pm_score": 3, "selected": false, "text": "echo %USERNAME% | tr \"[A-Z]\" \"[a-z]\" \n echo %@lower[%USERNAME%]\n" }, { "answer_id": 23806517, "author": "Dharma Leonardi", "author_id": 2099456, "author_profile": "https://Stackoverflow.com/users/2099456", "pm_score": 4, "selected": false, "text": "@echo off\ncls\nsetlocal enabledelayedexpansion\n\nREM ***** Modify as necessary for the string source. *****\nset \"_STRING=%*\"\nif not defined _STRING set \"_STRING=%USERNAME%\"\nset _STRING\nREM ***** Modify as necessary for the string source. *****\n\nset \"_UCASE=ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\nset \"_LCASE=abcdefghijklmnopqrstuvwxyz\"\n\nfor /l %%a in (0,1,25) do (\n call set \"_FROM=%%_UCASE:~%%a,1%%\n call set \"_TO=%%_LCASE:~%%a,1%%\n call set \"_STRING=%%_STRING:!_FROM!=!_TO!%%\n)\n\nset _STRING\nendlocal\n E:\\OS.ADMIN>LCASE.BAT The Quick Fox Jumps Over The Brown Fence.\n _STRING=The Quick Fox Jumps Over The Brown Fence.\n_STRING=the quick fox jumps over the brown fence.\n" }, { "answer_id": 26182749, "author": "Adolfo", "author_id": 3075331, "author_profile": "https://Stackoverflow.com/users/3075331", "pm_score": 2, "selected": false, "text": ":: UPcase.bat ==> Store in environment variable _UPcase_ the upper case of %1\n:: -> Use quotes \"\" when the first argument has blanks or special characteres\n::\n:: Adapted from -> http://www.netikka.net/tsneti/info/tscmd039.htm\n::\n:: Note that the substitution method is case insensitive, which means that\n:: while working for this application, it is not useful for all character\n:: substitution tasks.\n::\n:: More concisely, one can capitalize (if you pardon the pun) on the fact\n:: that in for and the substitution lower and upper case source are\n:: equivalent.\n@echo off\n\n:: %~1 -> removes quotes from the first command line argument\n:: http://steve-jansen.github.io/guides/windows-batch-scripting/part-2-variables.html\n@echo off\n::setlocal EnableExtensions\n :: echo %_UPcase_%\n call :ToUpcaseWithFor \"%~1\" _UPcase_\n :: echo %_UPcase_% _doit_1_\n::endlocal & goto :EOF\ngoto :EOF\n::\n:: ======================\n:ToUpcaseWithFor\nsetlocal EnableExtensions EnableDelayedExpansion\n set var_=%~1\n for %%c in (A B C D E F G H I J K L M N O P Q R S T U V W X Y Z) do (\n set var_=!var_:%%c=%%c!\n )\nendlocal & set %2=%var_%& goto :EOF\n\n:EOF\n:: UPcase.bat ==> EOF\n" }, { "answer_id": 29118785, "author": "StackFi Neon", "author_id": 4680735, "author_profile": "https://Stackoverflow.com/users/4680735", "pm_score": 3, "selected": false, "text": "echo>%1\ndir /b/l %1>lower.tmp\nset /p result=<lower.tmp\necho %result%\n lower \"Mein BinnenMajuskel\"\n mein binnenmajuskel\n lower \"UserName\" echo>%Temp%\\%1\ndir /b/l %Temp%\\%1>%Temp%\\lower.tmp\nset /p result=<%Temp%\\lower.tmp\ndel %Temp%\\%1\ndel %Temp%\\lower.tmp\n" }, { "answer_id": 34085640, "author": "LukStorms", "author_id": 4003419, "author_profile": "https://Stackoverflow.com/users/4003419", "pm_score": 3, "selected": false, "text": "FOR @FOR /F \"delims=\" %%s IN ('<<some script oneliner>>') DO @set MYVARIABLE=%%s\n @FOR /F \"delims=\" %%s IN ('perl -e \"print lc(pop)\" %USERNAME%') DO @set USERNAME=%%s\n @FOR /F \"delims=\" %%s IN ('powershell -command \"(get-item env:'USERNAME').Value.ToLower()\"') DO @set USERNAME=%%s\n" }, { "answer_id": 57327366, "author": "Victor Mendonça Nogueira", "author_id": 11841859, "author_profile": "https://Stackoverflow.com/users/11841859", "pm_score": 3, "selected": false, "text": "if /i %USERNAME%==gb2nogu (\n // Code here\n)\n" }, { "answer_id": 60063730, "author": "Io-oI", "author_id": 8177207, "author_profile": "https://Stackoverflow.com/users/8177207", "pm_score": 0, "selected": false, "text": "Set !var:A=a! @echo off & setlocal EnableDelayedExpansion \n\ncd /d \"%~dp0\" && title <nul && title ...\\%~dpnx0 /// !time:~0,8! !date!\n\nif exist \"%tmp%\\ToUpLower.cs\" 2>nul >nul del /q /f \"%tmp%\\ToUpLower.cs\" \nset \"_where=%__appdir__%where.exe\" && set \"_csc=%windir%\\Microsoft.NET\"\n>\"%temp%\\ToUpLower.cs\" ( \necho= using System; namespace SUQ1522019 ^{class Program ^{static void Main(string[] args^) ^{\necho= if (args.Length==2 ^&^& args[0].ToLower(^)==\"-l\"^) ^{Console.WriteLine(args[1].ToLower(^)^);^} \necho= if (args.Length==2 ^&^& args[0].ToLower(^)==\"-u\"^) ^{Console.WriteLine(args[1].ToUpper(^)^);^}^}^}^}\n)\n\nset \"_arg=/t:exe /out:\"%tmp%\\ToUpLower.exe\" \"%tmp%\\ToUpLower.cs\" /platform:anycpu \"\nfor /f tokens^=* %%i in ('!_where! /r \"!_csc!\" \"csc.exe\"^|findstr /lic:\"k\\v2\\.\" \n')do \"%%~i\" !_arg! /unsafe+ /w:0 /o /nologo\n\nfor /f tokens^=* %%U in ('\"%tmp%\\ToUpLower.exe\" -u %USERNAME%')do set \"_up_case=%%U\"\nfor /f tokens^=* %%l in ('\"%tmp%\\ToUpLower.exe\" -l %USERNAME%')do set \"_low_case=%%l\"\n\necho/ Your username upcase is: !_up_case!\necho/ Your username lowcase is: !_low_case!\n\necho/ >nul 2>nul copy \"%tmp%\\ToUpLower.exe\" \".\" \ndel /q /f \"%tmp%\\ToUpLower.*\" >nul 2>nul && endlocal & goto :EOF\n %USERNAME% Your username upcase is: USERNAME\nYour username lowcase is: username\n ToUpLower.cs using System; namespace SUQ1522019 {class Program {static void Main(string[] args) {\n if (args.Length==2 && args[0].ToLower()==\"-l\") {Console.WriteLine(args[1].ToLower());} \n if (args.Length==2 && args[0].ToLower()==\"-u\") {Console.WriteLine(args[1].ToUpper());}}}}\n ToUpLower.cs using System\nnamespace SUQ1522019 \n{\n class Program \n {\n static void Main(string[] args)\n {\n if (args.Length==2 && args[0].ToLower()==\"-l\") \n {\n Console.WriteLine(args[1].ToLower());\n } \n\n if (args.Length==2 && args[0].ToLower()==\"-u\") \n {\n Console.WriteLine(args[1].ToUpper());\n }\n }\n }\n}\n csc.exe c:\\Windows\\Microsoft.NET\\Framework\\v2.0.50727\\csc.exe\nc:\\Windows\\Microsoft.NET\\Framework\\v3.5\\csc.exe\nc:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319\\csc.exe\nc:\\Windows\\Microsoft.NET\\Framework64\\v2.0.50727\\csc.exe\nc:\\Windows\\Microsoft.NET\\Framework64\\v3.5\\csc.exe\nc:\\Windows\\Microsoft.NET\\Framework64\\v4.0.30319\\csc.exe\n c:\\Windows\\Microsoft.NET\\Framework\\v2.0.50727\\csc.exe /t:exe /out:\"%tmp%\\ToUpLower.exe\" \"%tmp%\\ToUpLower.cs\" /platform:anycpu /unsafe+ /w:0 /o /nologo \n ToUpLower.exe ToUpLower.exe -l STRING \n\n:: or ..\n\nToUpLower.exe -L STRING\n ToUpLower.exe ToUpLower.exe -u string\n\n:: or ..\n\nToUpLower.exe -U string\n ToUpLower.exe echo/ copy ToUpLower.exe %temp%" }, { "answer_id": 62028288, "author": "npocmaka", "author_id": 388389, "author_profile": "https://Stackoverflow.com/users/388389", "pm_score": 3, "selected": false, "text": "result @echo off\n\nset LowerCaseMacro=for /L %%n in (1 1 2) do if %%n==2 (for %%# in (a b c d e f g h i j k l m n o p q r s t u v w x y z) do set \"result=!result:%%#=%%#!\") else setlocal enableDelayedExpansion ^& set result=\n\nset \"string=SOme STrinG WiTH lowerCAse letterS and UPCase leTTErs\"\n%LowerCaseMacro%%string%\n\necho %result%\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284776", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6992/" ]
284,778
<h2>Background</h2> <p>There are several different <a href="http://msdn.microsoft.com/en-us/library/958x11bc.aspx" rel="noreferrer">debug flags</a> you can use with the Visual Studio C++ compiler. They are:</p> <ul> <li><strong>(none)</strong> <ul> <li>Create no debugging information</li> <li>Faster compilation times</li> </ul></li> <li><strong>/Z7</strong> <ul> <li>Produce full-symbolic debugging information in the .obj files using CodeView format</li> </ul></li> <li><strong>/Zi</strong> <ul> <li>Produce full-symbolic debugging information in a .pdb file for the target using Program Database format. </li> <li>Enables support for minimal rebuilds (/Gm) which can reduce the time needed for recompilation.</li> </ul></li> <li><strong>/ZI</strong> <ul> <li>Produce debugging information like /Zi except with support for Edit-and-Continue</li> </ul></li> </ul> <h2>Issues</h2> <ul> <li><p>The /Gm flag is incompatible with the <a href="http://msdn.microsoft.com/en-us/library/bb385193.aspx" rel="noreferrer">/MP flag for Multiple Process builds</a> (Visual Studio 2005/2008)</p></li> <li><p>If you want to enable minimal rebuilds, then the /Zi flag is necessary over the /Z7 flag.</p></li> <li><p>If you are going to use the /MP flag, there is seemingly no difference between /Z7 and /Zi looking at MSDN. However, the <a href="http://www.scons.org/doc/production/HTML/scons-user/a4761.html#cv-CCPDBFLAGS" rel="noreferrer">SCons documentation</a> states that you must use /Z7 to support parallel builds.</p></li> </ul> <h2>Questions</h2> <ul> <li><p>What are the implications of using /Zi vs /Z7 in a Visual Studio C++ project? </p></li> <li><p>Are there other pros or cons for either of these options that I have missed? </p></li> <li><p>Specifically, what is the benefit of a single Program Database format (PDB) file for the target vs multiple CodeView format (.obj) files for each source?</p></li> </ul> <h2>References</h2> <p><a href="http://msdn.microsoft.com/en-us/library/958x11bc.aspx" rel="noreferrer">MDSN /Z7, /Zi, /ZI (Debug Information Format)</a></p> <p><a href="http://msdn.microsoft.com/en-us/library/bb385193.aspx" rel="noreferrer">MSDN /MP (Build with Multiple Processes)</a></p> <p><a href="http://www.scons.org/doc/production/HTML/scons-user/a4761.html#cv-CCPDBFLAGS" rel="noreferrer">SCons Construction Variables CCPDBFLAG</a></p> <p><a href="http://www.debuginfo.com/articles/gendebuginfo.html" rel="noreferrer">Debug Info</a></p>
[ { "answer_id": 54529116, "author": "Trass3r", "author_id": 594456, "author_profile": "https://Stackoverflow.com/users/594456", "pm_score": 3, "selected": false, "text": "/Z7 /Zi /Z7 /Zi /Zi /Z7 .pdb vcxxx.pdb /ZI /Zi" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284778", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2233/" ]
284,784
<p>Some databases support commands such as:</p> <pre><code>SELECT TOP 10 START AT 10 * FROM &lt;TABLE&gt; </code></pre> <p>Essentially I need to pull the first 10 records, then the next 10, then the next 10 etc. Maybe there is another way to do this but in the past I've done it like the above for databases that support 'START AT'.</p>
[ { "answer_id": 284789, "author": "StingyJack", "author_id": 16391, "author_profile": "https://Stackoverflow.com/users/16391", "pm_score": 2, "selected": false, "text": "SELECT Top 10 * \nFROM Table \nWHERE <primary key> Not IN (\n SELECT Top 10 <primaryKey> \n FROM Table \n ORDER BY <primary Key> ASC) \nORDER BY <primary Key> ASC\n" }, { "answer_id": 284840, "author": "splattne", "author_id": 6461, "author_profile": "https://Stackoverflow.com/users/6461", "pm_score": 2, "selected": false, "text": "SELECT * FROM\n(\n SELECT TOP 10 FROM\n (\n SELECT TOP (n * 10) FROM <table> ORDER BY (column) ASC\n ) AS t1 ORDER BY (column) DESC\n) AS t2 ORDER BY (column) ASC\n WITH Orders AS \n(\n SELECT SalesOrderID, OrderDate, \n ROW_NUMBER() OVER (order by OrderDate) AS 'RowNumber' \n FROM SalesOrder\n) \nSELECT * \nFROM Orders \nWHERE RowNumber between 10 and 19;\n" }, { "answer_id": 8832334, "author": "Martin Smith", "author_id": 73226, "author_profile": "https://Stackoverflow.com/users/73226", "pm_score": 3, "selected": false, "text": "SELECT * \nFROM <TABLE>\nORDER BY <SomeCol>\nOFFSET 10 ROWS\nFETCH NEXT 10 ROWS ONLY;\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284784", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5678/" ]
284,786
<p>I have the following equation</p> <blockquote> <p>1 - ((.5 * 0.83333333333333) ^ 2 + (.5 * 0.83333333333333) ^ 2 + (.5 * (1 - 0.83333333333333)) ^ 2 + (.5 * (1 - 0.83333333333333)) ^ 2) </p> </blockquote> <p>In Php5, this results in an answer of 1 as opposed to .63 (on two machines, OSx and Centos). Should I be exclusively using the bc math functions of Php to do equations like this?</p>
[ { "answer_id": 284824, "author": "nlucaroni", "author_id": 157, "author_profile": "https://Stackoverflow.com/users/157", "pm_score": 1, "selected": false, "text": " 83.3333333 = 100x\n 8.3333333 = 10x\n -----------------\n 75 = 90x\n x = 75 / 90 = 0.83333...\n" }, { "answer_id": 284848, "author": "John T", "author_id": 36457, "author_profile": "https://Stackoverflow.com/users/36457", "pm_score": 1, "selected": false, "text": "<?php\n\n$hugeDamnEquation = pow(1 - ((.5 * 0.83333333333333), 2) + pow((.5 * 0.83333333333333), 2) + pow((.5 * (1 - 0.83333333333333)), 2) + pow((.5 * (1 - 0.83333333333333)), 2));\n\necho $hugeDamnEquation;\n\n?>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284786", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
284,821
<p>I have a Lotus Domino server with a truly astounding number of Domino databases on it, arranged in various folders. </p> <p>Is there some means of exporting a list of all these databases, with their titles and creators' names, in a spreadsheet format of some kind? I have the Domino Admin and Domino Designer software, and I have or can get whatever access rights I'd need.</p>
[ { "answer_id": 1046830, "author": "Ed Schembor", "author_id": 125484, "author_profile": "https://Stackoverflow.com/users/125484", "pm_score": 3, "selected": false, "text": "Sub Initialize\n Dim db As NotesDatabase\n Dim f As Integer\n f = Freefile\n Open \"c:\\dbExport.csv\" For Output As #f\n\n Dim dbdir As New NotesDbDirectory(\"\") ' opens LOCAL - put a server name here\n Set db = dbdir.GetFirstDatabase(1247) ' all databases - NSF, NSG and NSH (no templates)\n While Not(db Is Nothing)\n Print #f, \"\"\"\" + db.Title + \"\"\", \"\"\" + db.FileName + \"\"\"\"\n Set db = dbdir.GetNextDatabase\n Wend\n Close #f\nEnd Sub\n" }, { "answer_id": 28885003, "author": "Éric Viala", "author_id": 3617432, "author_profile": "https://Stackoverflow.com/users/3617432", "pm_score": 1, "selected": false, "text": "catalog load catalog" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284821", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25468/" ]
284,826
<p>I'm on a beginner level course in prolog, doing a map colouring problem. Here's my code.</p> <pre><code>col(Colors,Map,Coloring) :- checkMap(Colors,Map,Coloring). checkMap(Colors,[Country1:Country2],Coloring) :- goodColor(Country1:Country2,Coloring,Colors). checkMap(Colors,[Country1:Country2|Rest],Coloring) :- goodColor(Country1:Country2,Coloring,Colors), checkMap(Colors,Rest,Coloring). goodColor(Country1:Country2,Coloring,Colors) :- mem(Country1:Color1,Coloring),!, mem(Country2:Color2,Coloring),!, mem(Color1,Colors), mem(Color2,Colors), not(Color1=Color2). mem(Var,[Var|_]). mem(Var,[_|Rest]) :- mem(Var,Rest). </code></pre> <p>My output looks like this:</p> <pre><code>?- col([a,b,c],[1:2,1:3,2:3],X). X = [1:a, 2:b, 3:c|_G332] ; X = [1:a, 2:c, 3:b|_G332] ; X = [1:b, 2:a, 3:c|_G332] ; X = [1:b, 2:c, 3:a|_G332] ; X = [1:c, 2:a, 3:b|_G332] ; X = [1:c, 2:b, 3:a|_G332] ; fail. </code></pre> <p>Anyone know how I can get rid of the trailing variable? I know it's mostly cosmetic, but I don't see why it's there.</p>
[ { "answer_id": 285001, "author": "Nelson", "author_id": 27366, "author_profile": "https://Stackoverflow.com/users/27366", "pm_score": 1, "selected": false, "text": "ground_terms([H|T1],[H|T2]) :- ground(H), !, ground_terms(T1,T2).\nground_terms(_,[]).\n col(Colors,Map,Coloring) :-\n checkMap(Colors,Map,Coloring1),\n ground_terms(Coloring1,Coloring).\n" }, { "answer_id": 287788, "author": "tonys", "author_id": 35439, "author_profile": "https://Stackoverflow.com/users/35439", "pm_score": 0, "selected": false, "text": "mem(Var,[Var|_]) Coloring [Var|_] col(Colors,Map,Coloring) :-\n check(Colors,Map,[],Coloring).\n\ncheck(Colors,[],Coloring,Coloring).\n\ncheck(Colors,[Country1:Country2 | T],[],L) :-\n member(Color1,Colors),\n member(Color2,Colors),\n Color1 \\== Color2,\n check(Colors,T,[Country1:Color1,Country2:Color2],L).\n\ncheck(Colors,[Country1:Country2 | T],Coloring,L) :-\n member(Country1:Color1,Coloring),\n member(Country2:Color2,Coloring),!,\n check(Colors,T,Coloring,L).\n\ncheck(Colors,[Country1:Country2 | T],Coloring,L) :-\n member(Country1:Color1,Coloring),!,\n member(Color2,Colors),\n not(member(_:Color2,Coloring)),\n check(Colors,T,[Country2:Color2|Coloring],L).\n\ncheck(Colors,[Country1:Country2 | T],Coloring,L) :-\n member(Country2:Color2,Coloring),!,\n member(Color1,Colors),\n not(member(_:Color1,Coloring)),\n check(Colors,T,[Country1:Color1|Coloring],L).\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36990/" ]
284,832
<pre><code>For Each line As String In System.IO.File.ReadAllLines("file.txt") 'Do Something' Next </code></pre> <p>and</p> <pre><code>Using f As System.IO.FileStream = System.IO.File.OpenRead("somefile.txt") Using s As System.IO.StreamReader = New System.IO.StreamReader(f) While Not s.EndOfStream Dim line As String = s.ReadLine 'put you line processing code here End While End Using End Using </code></pre> <p>are both showing as mostly red, I'm running a clean install of MS VS2005 and these codes were both recomended to me, am I missing something else I need to install or declare?</p>
[ { "answer_id": 284866, "author": "Mauro", "author_id": 2208, "author_profile": "https://Stackoverflow.com/users/2208", "pm_score": 1, "selected": false, "text": "Dim Lines As String()\nLines = System.IO.File.ReadAllLines(\"file.txt\")\n Dim sr as New StreamReader(\"somefile.txt\")\nDim line as String = sr.ReadLine()\nDo While Not line is Nothing\n line = sr.ReadLine()\n 'do something else\nLoop\n Imports System.IO\n\nModule Module1\n\nSub Main()\n Dim sr As New StreamReader(\"somefile.txt\")\n Dim line As String = sr.ReadLine()\n Do While Not line Is Nothing\n line = sr.ReadLine()\n 'do something else\n Loop\n\nEnd Sub\n\nEnd Module\n" }, { "answer_id": 284880, "author": "Gavin Miller", "author_id": 33226, "author_profile": "https://Stackoverflow.com/users/33226", "pm_score": 1, "selected": false, "text": "Public class CodeClass\n Public Sub CodeMethod\n\n Using f As System.IO.FileStream = System.IO.File.OpenRead(\"somefile.txt\")\n Using s As System.IO.StreamReader = New System.IO.StreamReader(f)\n While Not s.EndOfStream\n Dim line As String = s.ReadLine\n\n //Non-vb comment for easier to read SO code\n End While\n End Using\n End Using\n\n End Sub\nEnd Class\n" }, { "answer_id": 284955, "author": "Mauro", "author_id": 2208, "author_profile": "https://Stackoverflow.com/users/2208", "pm_score": 1, "selected": true, "text": "Dim value As String = My.Computer.FileSystem.ReadAllText(file)\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
284,833
<p>This is related to some other questions, such as: <a href="https://stackoverflow.com/questions/34987/how-to-declare-an-array-of-strings-in-c">this</a>, and some of my other questions.</p> <p>In <a href="https://stackoverflow.com/questions/34987/how-to-declare-an-array-of-strings-in-c">this question</a>, and others, we see we can declare and initialise string arrays in one nice step, for example:</p> <pre><code>const char* const list[] = {"zip", "zam", "bam"}; //from other question </code></pre> <p>This can be done in the implementation of a function with no bother, or in the body of a .cpp file, outside any scope.</p> <p>What I want to do is to have an array like this as as member of a class I am using, something like this:</p> <pre><code>class DataProvider : public SomethingElse { const char* const mStringData[] = {"Name1", "Name2", "Name3", ... "NameX"}; public: DataProvider(); ~DataProvider(); char* GetData() { int index = GetCurrentIndex(); //work out the index based on some other data return mStringData[index]; //error checking and what have you omitted } }; </code></pre> <p>But, the compiler complains and I can't seem to work out why. Is it possible to declare and initialise an array like this in one step in a class definition? Are there alternatives that are better?</p>
[ { "answer_id": 284843, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 2, "selected": false, "text": "class DataProvider {\n enum { SIZEOF_VALUES = 4 };\n const char * values[SIZEOF_VALUES];\n\n public:\n DataProvider() {\n const char * const v[SIZEOF_VALUES] = { \n \"one\", \"two\", \"three\", \"four\" \n };\n std::copy(v, v + SIZEOF_VALUES, values);\n }\n};\n /* in the header file */\nclass DataProvider {\n enum { SIZEOF_VALUES = 4 };\n static const char * const values[SIZEOF_VALUES];\n};\n\n/* in cpp file: */\n\nconst char * const DataProvider::values[SIZEOF_VALUES] = \n { \"one\", \"two\", \"three\", \"four\" };\n" }, { "answer_id": 284845, "author": "Carl Seleborg", "author_id": 2095, "author_profile": "https://Stackoverflow.com/users/2095", "pm_score": 2, "selected": false, "text": "const char* []" }, { "answer_id": 284859, "author": "Stefan Rådström", "author_id": 19981, "author_profile": "https://Stackoverflow.com/users/19981", "pm_score": 5, "selected": true, "text": "class DataProvider : public SomethingElse\n{\n static const char* const mStringData[];\n\npublic:\n DataProvider();\n ~DataProvider();\n\n const char* const GetData()\n {\n int index = GetCurrentIndex(); //work out the index based on some other data\n return mStringData[index]; //error checking and what have you omitted\n }\n\n};\n const char* const DataProvider::mStringData[] = {\"Name1\", \"Name2\", \"Name3\", ... \"NameX\"};\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15667/" ]
284,837
<p>If you have a sequence of block elements and you wanted to place margin in between them. </p> <p>Which do you prefer, margin-top or margin-bottom or both? Why?</p>
[ { "answer_id": 284852, "author": "Winston Smith", "author_id": 35086, "author_profile": "https://Stackoverflow.com/users/35086", "pm_score": 5, "selected": true, "text": "margin-bottom" }, { "answer_id": 284865, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 5, "selected": false, "text": "margin-top :first-child div.block {\n margin-top: 10px;\n}\n\ndiv.block:first-child {\n margin-top: 0;\n}\n" }, { "answer_id": 292892, "author": "Bryan M.", "author_id": 4636, "author_profile": "https://Stackoverflow.com/users/4636", "pm_score": 1, "selected": false, "text": ".content p { /* obviously choose a more elegant name */\n margin-bottom: 10px;\n}\n" }, { "answer_id": 4996389, "author": "Phil Strong", "author_id": 263943, "author_profile": "https://Stackoverflow.com/users/263943", "pm_score": 0, "selected": false, "text": ".discussion .detailed.topics { margin: 20px 0 } \n.discussion .detailed.topics .topic { margin-bottom: 30px }\n.discussion .detailed.topics .topic.last { margin-bottom: 0 }\n <div class=\"detailed topics\"> \n @if (Model.ActiveTopics != null && Model.ActiveTopics.Count > 0)\n {\n for (int i = 0; i < Model.ActiveTopics.Count(); i++)\n {\n var topic = Model.ActiveTopics[i];\n <div class=\"topic@(i == Model.ActiveTopics.Count - 1 ? \" last\" : \"\")\">\n ... \n </div>\n }\n }\n</div>\n" }, { "answer_id": 14885217, "author": "thordarson", "author_id": 2005939, "author_profile": "https://Stackoverflow.com/users/2005939", "pm_score": 4, "selected": false, "text": "+ margin-top .article + .article {\n margin-top: 10px;\n}\n /* CSS rules for legibility. */\nsection, article {\n outline: 1px solid blue;\n}\n\nsection {\n background: lightgreen;\n padding: 10px;\n}\n\nsection + section {\n margin-top: 30px;\n}\n\narticle {\n background: lightblue;\n}\n\n/* Using the + selector. */\n#PlusSelectorExample article + article {\n margin-top: 30px;\n}\n\n/* Using margin-bottom only. */\n#MarginBottomExample article {\n margin-bottom: 30px;\n}\n\n/* Using last-child. */\n#LastChildExample article {\n /* Other CSS rules for this element. */\n margin-bottom: 30px;\n}\n\n#LastChildExample article:last-child {\n margin-bottom: 0;\n} <p>The plus selector only selects an element following another. Combining the plus selector and margin-top means there's no extra space at the top since the selector doesn't apply.</p>\n<section id =\"PlusSelectorExample\">\n <article>In vel sem sed nulla scelerisque semper. Fusce dictum semper lectus, a cursus turpis fermentum vitae.</article>\n <article>Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos.</article>\n <article>Suspendisse potenti. Duis id lacus augue. Duis ultricies est viverra, dapibus est quis, pretium sapien.</article>\n</section>\n<p>Using margin-bottom leaves an extra gap at the bottom.</p>\n<section id=\"MarginBottomExample\">\n <article>In vel sem sed nulla scelerisque semper. Fusce dictum semper lectus, a cursus turpis fermentum vitae.</article>\n <article>Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos.</article>\n <article>Suspendisse potenti. Duis id lacus augue. Duis ultricies est viverra, dapibus est quis, pretium sapien.</article>\n</section>\n<p>Combining margin-bottom with last-child achieves the same as the plus operator.</p>\n<section id=\"LastChildExample\">\n <article>In vel sem sed nulla scelerisque semper. Fusce dictum semper lectus, a cursus turpis fermentum vitae.</article>\n <article>Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos.</article>\n <article>Suspendisse potenti. Duis id lacus augue. Duis ultricies est viverra, dapibus est quis, pretium sapien.</article>\n</section>" }, { "answer_id": 38053001, "author": "Robo Robok", "author_id": 4403732, "author_profile": "https://Stackoverflow.com/users/4403732", "pm_score": 2, "selected": false, "text": "<div class=\"title\">My Awesome Book</div>\n<p>Description of My Awesome Book</p>\n margin-top <p> <img src=\"icon.png\">\n<div>My Awesome Book</div>\n margin-bottom" }, { "answer_id": 52655604, "author": "ajax333221", "author_id": 908879, "author_profile": "https://Stackoverflow.com/users/908879", "pm_score": 4, "selected": false, "text": "margin-top :first-child article {\n margin-top: 2em;\n}\n\narticle:first-child {\n margin-top: 0;\n}\n\n//space at the top of the Ad\n.ad {\n margin-top: 1em;\n}\n\n//and to reduce space below the ad\n.ad + article {\n margin-top: 1em;\n}\n" }, { "answer_id": 63688860, "author": "Gosu Przmak", "author_id": 2569012, "author_profile": "https://Stackoverflow.com/users/2569012", "pm_score": 1, "selected": false, "text": "<div class=\"box\">\n <div class=\"item first\"></div>\n <div class=\"item second\"></div>\n <div class=\"item third\"></div>\n</div>\n .item:nth-child(n+2) {\n margin-top: 16px;\n}\n .item + .item {\n margin-top: 16px;\n}\n .item + .item {\n margin-top: 16px;\n}\n\n.item + .item.second {\n margin-top: 32px;\n // you could use margin-bottom here but there will be needed a different rule for handling if there is no 3rd element\n}\n\n.item.second + .item {\n margin-top: 32px;\n}\n .item {\n margin-bottom: 16px;\n}\n\n.item:last-child {\n margin-bottom: 0px;\n}\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20300/" ]
284,858
<p>My project requires a file where I will store key/value pair data that should be able to be read and modified by the user. I want the program to just expect the keys to be there, and I want to parse them from the file as quickly as possible.</p> <p>I could store them in XML, but XML is way to complex, and it would require traversing nodes, and child nodes and so on, all I want is some class that takes a file and generates key value pairs. I want as little error handling as possible, and I want it done with as little code as possible.</p> <p>I could code a class like that myself, but I'd rather learn how it's don'e in the framework than inventing the wheel twice. Are there some built in magic class in .NET (3.5) that are able to do so?</p> <pre><code>MagicClass kv = new MagicClass("Settings.ini"); // It doesn't neccesarily have to be an INI file, it can be any simple key/value pair format. string Value1 = kv.get("Key1"); ... </code></pre>
[ { "answer_id": 284881, "author": "Jb Evain", "author_id": 36702, "author_profile": "https://Stackoverflow.com/users/36702", "pm_score": 3, "selected": false, "text": "[Configuration]\nName = Jb Evain\nPhone = +330101010101\n var source = new IniConfigSource (\"Settings.ini\");\nvar config = source.Configs [\"Configuration\"];\n\nstring name = config.Get (\"Name\");\nstring phone = config.Get (\"Phone\");\n" }, { "answer_id": 284882, "author": "Jeff Kotula", "author_id": 1382162, "author_profile": "https://Stackoverflow.com/users/1382162", "pm_score": 0, "selected": false, "text": "key1=value1\nkey2=value2\n" }, { "answer_id": 284903, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 2, "selected": false, "text": "key1,value1\nkey2,value2\n...\n" }, { "answer_id": 27532519, "author": "Kyght", "author_id": 1636133, "author_profile": "https://Stackoverflow.com/users/1636133", "pm_score": 3, "selected": false, "text": "KEY=VALUE public static Dictionary<string, string> LoadConfig(string settingfile)\n{\n var dic = new Dictionary<string, string>();\n\n if (File.Exists(settingfile))\n {\n var settingdata = File.ReadAllLines(settingfile);\n for (var i = 0; i < settingdata.Length; i++)\n {\n var setting = settingdata[i];\n var sidx = setting.IndexOf(\"=\");\n if (sidx >= 0)\n {\n var skey = setting.Substring(0, sidx);\n var svalue = setting.Substring(sidx+1);\n if (!dic.ContainsKey(skey))\n {\n dic.Add(skey, svalue);\n }\n }\n }\n }\n\n return dic;\n}\n var settingfile = AssemblyDirectory + \"\\\\mycustom.setting\";\nvar settingdata = LoadConfig(settingfile);\nif (settingdata.ContainsKey(\"lastrundate\"))\n{\n DateTime lout;\n string svalue;\n if (settingdata.TryGetValue(\"lastrundate\", out svalue))\n {\n DateTime.TryParse(svalue, out lout);\n lastrun = lout;\n }\n}\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29442/" ]
284,868
<p>I am writing event data to a log file in an asp.net httphandler by using the File.AppendAllText method. I am concerned with what will happen when multiple requests are received simultaneously. Does AppendAllText lock the file it's writing to?</p>
[ { "answer_id": 284897, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 4, "selected": true, "text": "public static object LockingTarget = new object();\n\npublic void LogToFile(string msg)\n{\n lock(LockingTarget)\n {\n //append to file here as fast as possible\n }\n}\n" }, { "answer_id": 1097693, "author": "Nick Berardi", "author_id": 17, "author_profile": "https://Stackoverflow.com/users/17", "pm_score": 4, "selected": false, "text": "TextWriterTraceListener TextWriterTraceListener logListener = new TextWriterTraceListener(\"C:\\log.txt\", \"My Log Name\");\nTrace.Listeners.Add(logListener);\n Trace.WriteLine(\"Log this text\");\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
284,885
<p>I am trying to gain a better understanding of tcp/ip sockets in c#, as i want to challenge myself to see if i can create a working MMO infrastructure (game world, map, players, etc) purely for educational purposes as i have no intention of being another one of those "OMGZ iz gonna make my r0x0r MMORPG that will be better than WoW!!!", you know what im talking about.</p> <p>Anyway, i was wondering if anyone can shed some light as to how one might approach designing this kind of system and what kinds of things are required, and what i should watch out for?</p> <p>My initial idea was to break up the system into seperate client/server connections with each connection (on its own port) performing a specific task, such as updating player/monster positions, sending and receiving chat messages, etc. which to me would make processing the data easier because you wouldn't always need to put a header on the data to know what information the packet contains. </p> <p>Does that make sense and is useful or am i just way over complicating things?</p> <p>your responses are very much appreciated.</p>
[ { "answer_id": 285986, "author": "grieve", "author_id": 34329, "author_profile": "https://Stackoverflow.com/users/34329", "pm_score": 6, "selected": true, "text": "+-------------------------+-------------------+-----------------+------------------------+\n| Length of Msg (4 bytes) | MsgType (2 bytes) | Flags (4 bytes) | Msg (length - 6 bytes) |\n+-------------------------+-------------------+-----------------+------------------------+\n const uint32_t FLAG_0 = (1 << 0);\nconst uint32_t FLAG_1 = (1 << 1);\nconst uint32_t FLAG_2 = (1 << 2);\n...\nconst uint32_t RESERVED_32 = (1 << 31);\n uint32 length = MessageBuffer.ReadUint32();\nuint32 start = MessageBuffer.CurrentOffset();\nuint16 msgType = MessageBuffer.ReadUint16();\nuint32 flags = MessageBuffer.ReadUint32();\n\nif (flags & FLAG_0)\n{\n // Read out whatever FLAG_0 represents.\n // Single or multiple fields\n}\n// ...\n// read out the other flags\n// ...\n\nMessageBuffer.AdvanceToOffset(start + length);\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284885", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18811/" ]
284,889
<p>I am about to embark on a rewrite of a VB6 application in .NET 3.5sp1. The VB6 app is pretty well written and the data layer is completely based on stored procedures. I'd like to go with something automated like Linq2SQL/Entity Framework/NHibernate/SubSonic. Admittedly, I haven't used any of these tools in anything other than throwaway projects. </p> <p>The potential problem I fear I might have with all these choices is speed. For instance, right now to retrieve a single row (or the entire list), I use the following sproc:</p> <pre><code>ALTER PROCEDURE [dbo].[lst_Customers] @intID INT = NULL ,@chvName VARCHAR(100) = NULL AS SELECT Customer_id, Name FROM dbo.Customer WHERE (@intID IS NULL OR @intID = Customer_id) AND (@chvName IS NULL OR Name like ('%' + @chvName + '%')) ORDER BY name </code></pre> <p>To retrieve a single row in Linq2SQL/Entity Framework/NHibernate/SubSonic, would these solutions have to bring the entire list down to the client and find the row that I need?</p> <p>So, what's the consensus for the data access strategy for an application with a large data domain?</p>
[ { "answer_id": 285030, "author": "John Rudy", "author_id": 14048, "author_profile": "https://Stackoverflow.com/users/14048", "pm_score": 2, "selected": false, "text": "where select * from foo SPs DataTable" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284889", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9382/" ]
284,896
<p>Is it a good idea (from a design POV) to nest constructor calls for overloaded New or Factory style methods? This is mostly for simple constructors, where each overload builds on the previous one. </p> <pre><code>MyClass( arg1 ) { _arg1 = arg1; _otherField = true; _color="Blue" } MyClass( arg1, arg2) : this(arg1) { _arg2 = arg2 } MyClass( arg1, arg2, arg3) : this(arg1, ar2) { _arg3 = arg3; } </code></pre> <p>Or with factory methods:</p> <pre><code>static NewInstance(arg1 ) { _arg1 = arg1; } static NewInstance(arg1, arg2) { f = NewInstance(arg1); f._arg2 = arg2; } //... and so on </code></pre> <p>I can see a few drawbacks on both sides</p> <ul> <li>Nesting hides what the constructor is doing</li> <li>Not nesting duplicates all the functionality</li> </ul> <p>So, is doing this a good idea, or does it set me up for something I'm just not seeing as a problem. For some reason I feel uneasy doing it, mostly because it divides up the responsibility for initializing.</p> <p>Edit: <strong>@Jon Skeet</strong>: I see now why this was bothering me so much. I was doing it backwards! I wrote the whole thing and didn't even notice, it just smelled. Most other cases I have (that I wrote), do it the way you recommend, but this certainly isn't the only one that I have done like this. I do notice that the more complicated ones I did properly, but the simple ones I seem to have gone sloppy. <em>I love micro edits. I also like acronymns!</em></p>
[ { "answer_id": 284905, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 7, "selected": true, "text": "public Foo(int x, int y)\n{\n this.x = x;\n this.y = y;\n precomputedValue = x * y;\n}\n\nprivate static int DefaultY\n{\n get { return DateTime.Now.Minute; }\n}\n\npublic Foo(int x) : this(x, DefaultY)\n{\n}\n\npublic Foo() : this(1, DefaultY)\n{\n}\n public static XmlDocument FromText(string xml)\n\npublic static XmlDocument FromFile(string filename)\n" }, { "answer_id": 285129, "author": "Chris Marisic", "author_id": 37055, "author_profile": "https://Stackoverflow.com/users/37055", "pm_score": -1, "selected": false, "text": "var myclass = New MyClass { arg1 = \"lala\", arg2 =\"foo\" }\n default(typeof(arg3)).\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284896", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15127/" ]
284,899
<pre><code>private JButton jBtnDrawCircle = new JButton("Circle"); private JButton jBtnDrawSquare = new JButton("Square"); private JButton jBtnDrawTriangle = new JButton("Triangle"); private JButton jBtnSelection = new JButton("Selection"); </code></pre> <p>How do I add action listeners to these buttons, so that from a main method I can call <code>actionperformed</code> on them, so when they are clicked I can call them in my program?</p>
[ { "answer_id": 284925, "author": "Alex B", "author_id": 6180, "author_profile": "https://Stackoverflow.com/users/6180", "pm_score": 3, "selected": false, "text": "jBtnDrawCircle.addActionListener( /*class that implements ActionListener*/ );\n" }, { "answer_id": 284934, "author": "David Koelle", "author_id": 2197, "author_profile": "https://Stackoverflow.com/users/2197", "pm_score": 6, "selected": false, "text": "jBtnSelection.addActionListener(this); public void actionPerformed(ActionEvent e) actionPerformed e.getSource() jBtnSelection.addActionListener(new ActionListener() { \n public void actionPerformed(ActionEvent e) { \n selectionButtonPressed();\n } \n} ); selectionButtonPressed() jBtnSelection.addActionListener(e -> selectionButtonPressed());\n e actionPerformed(ActionEvent e) selectionButtonPressed selectionButtonPressed() selectionChanged()" }, { "answer_id": 53247880, "author": "Ronald Ortiz", "author_id": 9815517, "author_profile": "https://Stackoverflow.com/users/9815517", "pm_score": 2, "selected": false, "text": "public abstract class beep implements ActionListener {\n public static void main(String[] args) {\n JFrame f = new JFrame(\"beeper\");\n JButton button = new JButton(\"Beep me\");\n f.setVisible(true);\n f.setSize(300, 200);\n f.add(button);\n button.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent e) {\n // Insert code here\n }\n });\n }\n}\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37037/" ]