qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
list
input
stringlengths
12
45k
output
stringlengths
2
31.8k
283,202
<p>we are writing tests for a COM library written in VB 6.0.The problem we are facing is that, we are unable to access events declared in VB( withevents). We get exception, "object does not support set of events". How can we overcome this problem?</p>
[ { "answer_id": 295316, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>For example, we have a class in VB 6.0 called DatabaseCommand.</p>\n\n<pre><code>Option Explicit\n\nPublic Event SavedSuccessfully()\n\nPublic Sub Execute(ByVal vAge As Integer, ByVal vName As String, ByVal vAddress As String)\n\n RaiseEvent SavedSuccessfully\n\nEnd Sub\n</code></pre>\n\n<p>Now, personclass</p>\n\n<pre><code>Private WithEvents dbCommand As DatabaseCommand\n\nPublic Sub Init(ByVal vDBCommand As DatabaseCommand)\n\n Set dbCommand = vDBCommand\n\nEnd Sub\n\nPrivate Sub dbCommand_SavedSuccessfully()\n 'not implemented\nEnd Sub\n</code></pre>\n\n<p>Now, when try to test this ( after compiling the vb project)</p>\n\n<pre><code>MockRepository repository = new MockRepository();\n\nPersonLib.DatabaseCommand db = repository.DynamicMock&lt;PersonLib.DatabaseCommand&gt;();\n\nPersonLib.PersonClass person = new PersonLib.PersonClass();\n\nperson.Init(db); --- this line throws error - Object or class does not support the set of events\n</code></pre>\n" }, { "answer_id": 299579, "author": "Mike Spross", "author_id": 17862, "author_profile": "https://Stackoverflow.com/users/17862", "pm_score": 2, "selected": false, "text": "<p>Your mocking framework is the problem here. The mock object returned by this call:</p>\n\n<pre><code>repository.DynamicMock&lt;PersonLib.DatabaseCommand&gt;();\n</code></pre>\n\n<p>implements the <code>DatabaseCommand</code> class's interface, but does not mock its events. Therefore, when you pass an instance of this mock object to your VB6 code, which expects to receive a DatabaseCommand object that can raise events, it won't work. </p>\n\n<p>When you pass the mock object to your <code>PersonClass.Init</code> method, here is simplified version of what is happening:</p>\n\n<ol>\n<li><p>The code gets to this line in <code>PersonClass.Init</code>:</p>\n\n<p><code>Set dbCommand = vDBCommand</code></p></li>\n<li><p>VB6 asks the object on the right-hand side of the <code>Set</code> statement if it supports the same events that the <code>DatabaseCommand</code> class does (VB6 does this because you declared <code>dbCommand</code> with the <code>WithEvents</code> keyword, so it will try to set up an event sink to receive events from the <code>dbCommand</code> object).</p></li>\n<li><p>The object you passed in, however, being a mock object and not a real <code>DatabaseCommand</code> object, doesn't actually implement the events that the real <code>DatabaseCommand</code> class implements. When VB6 encounters this, it raises the error you are seeing.</p></li>\n</ol>\n\n<p>I can't think of a way to make the mock object support the same events that the <code>DatabaseCommand</code> class does in order make your test code work (well, I can think of one way, but it would involve redesigning your classes), but I may post more later if I find a more reasonable solution.</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283202", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
we are writing tests for a COM library written in VB 6.0.The problem we are facing is that, we are unable to access events declared in VB( withevents). We get exception, "object does not support set of events". How can we overcome this problem?
Your mocking framework is the problem here. The mock object returned by this call: ``` repository.DynamicMock<PersonLib.DatabaseCommand>(); ``` implements the `DatabaseCommand` class's interface, but does not mock its events. Therefore, when you pass an instance of this mock object to your VB6 code, which expects to receive a DatabaseCommand object that can raise events, it won't work. When you pass the mock object to your `PersonClass.Init` method, here is simplified version of what is happening: 1. The code gets to this line in `PersonClass.Init`: `Set dbCommand = vDBCommand` 2. VB6 asks the object on the right-hand side of the `Set` statement if it supports the same events that the `DatabaseCommand` class does (VB6 does this because you declared `dbCommand` with the `WithEvents` keyword, so it will try to set up an event sink to receive events from the `dbCommand` object). 3. The object you passed in, however, being a mock object and not a real `DatabaseCommand` object, doesn't actually implement the events that the real `DatabaseCommand` class implements. When VB6 encounters this, it raises the error you are seeing. I can't think of a way to make the mock object support the same events that the `DatabaseCommand` class does in order make your test code work (well, I can think of one way, but it would involve redesigning your classes), but I may post more later if I find a more reasonable solution.
283,209
<p>do I have to register the HttpVerb constraint in my route definition (when i'm registering routes) if i have decorated my action method with the [AcceptVerbs(..)] attribute already?</p> <p>eg. i have this.</p> <pre><code>[AcceptVerbs(HttpVerbs.Post)] public ActionResult Create(FormCollection formCollection) { .. } </code></pre> <p>do i need to add this to the route that refers to this action, as a constraint?</p>
[ { "answer_id": 284020, "author": "anonymous", "author_id": 36602, "author_profile": "https://Stackoverflow.com/users/36602", "pm_score": 2, "selected": false, "text": "<p>Nope -- Create will only respond to POST requests.</p>\n\n<p>You can have other implementations of Create with different AcceptVerb attributes, or one with no attribute that will catch all other requests.</p>\n\n<p>If that was your only Create method, any GET (or other non-POST) request would result in a 404.</p>\n\n<p>I assume under the hood this is all being done by the routing engine anyways. [edit: nope, see Haacked's post]</p>\n" }, { "answer_id": 285850, "author": "Haacked", "author_id": 598, "author_profile": "https://Stackoverflow.com/users/598", "pm_score": 6, "selected": true, "text": "<p>The difference between the two is the following: Let's assume the <code>Create</code> method in question is on the <code>HomeController</code>.</p>\n\n<p>Using the <code>AcceptVerbs</code> attribute does not affect routing. It's actually something used by the action invoker. What it allows you to do is have 2 action methods on a controller with the same name that each respond to a different HTTP Method.</p>\n\n<pre><code>public ActionResult Create(int id) { .. }\n\n[AcceptVerbs(HttpVerbs.Post)]\npublic ActionResult Create(FormCollection formCollection) { .. }\n</code></pre>\n\n<p>So when a request for <code>/home/create</code> comes in, the route will match and hand off the request to the controller's invoker. The invoker then invokes the correct method by looking at the <code>AcceptVerbs</code> attribute.</p>\n\n<p>Using the <code>HttpMethodConstraint</code> in routing will make it such that the route itself will not match the request. So when a POST request comes in for <code>/home/create</code>, neither action method will be called because that route will not match the request. It's possible that another route <em>will</em> match that request though.</p>\n\n<p>Part of the reason for the overlap here is that Routing is a feature of ASP.NET 3.5 SP1 and isn't specific to MVC. MVC uses Routing, but Routing is also used by Dynamic Data and we plan to integrate routing with ASP.NET Web Forms.</p>\n" }, { "answer_id": 2549310, "author": "MrByte", "author_id": 19710, "author_profile": "https://Stackoverflow.com/users/19710", "pm_score": 1, "selected": false, "text": "<p>First decorate like this:</p>\n\n<pre><code>[ActionName(\"ItemEdit\"), AcceptVerbs(HttpVerbs.Post)]\npublic virtual object ItemSave(Menu sampleInput)\n</code></pre>\n\n<p>then you need to add route like this:</p>\n\n<pre><code> AddRoute(\n \"SampleEdit\",\n \"Admin/{sampleID}/Edit\",\n new { controller = \"Sample\", action = \"ItemEdit\", validateAntiForgeryToken = true },\n new { areaID = new IsGuid() },\n new { Namespaces = controllerNamespaces }\n );\n</code></pre>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283209", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30674/" ]
do I have to register the HttpVerb constraint in my route definition (when i'm registering routes) if i have decorated my action method with the [AcceptVerbs(..)] attribute already? eg. i have this. ``` [AcceptVerbs(HttpVerbs.Post)] public ActionResult Create(FormCollection formCollection) { .. } ``` do i need to add this to the route that refers to this action, as a constraint?
The difference between the two is the following: Let's assume the `Create` method in question is on the `HomeController`. Using the `AcceptVerbs` attribute does not affect routing. It's actually something used by the action invoker. What it allows you to do is have 2 action methods on a controller with the same name that each respond to a different HTTP Method. ``` public ActionResult Create(int id) { .. } [AcceptVerbs(HttpVerbs.Post)] public ActionResult Create(FormCollection formCollection) { .. } ``` So when a request for `/home/create` comes in, the route will match and hand off the request to the controller's invoker. The invoker then invokes the correct method by looking at the `AcceptVerbs` attribute. Using the `HttpMethodConstraint` in routing will make it such that the route itself will not match the request. So when a POST request comes in for `/home/create`, neither action method will be called because that route will not match the request. It's possible that another route *will* match that request though. Part of the reason for the overlap here is that Routing is a feature of ASP.NET 3.5 SP1 and isn't specific to MVC. MVC uses Routing, but Routing is also used by Dynamic Data and we plan to integrate routing with ASP.NET Web Forms.
283,222
<p>What's the best way to take some plain text (not PHP code) which contains PHP-style variables, and then substitute in the value of the variable. This is kinda hard to describe, so here's an example.</p> <pre><code>// -- myFile.txt -- Mary had a little $pet. // -- parser.php -- $pet = "lamb"; // open myFile.txt and transform it such that... $newContents = "Mary had a little lamb."; </code></pre> <p>I've been considering using a regex or perhaps <code>eval()</code>, though I'm not sure which would be easiest. This script is only going to be running locally, so any worries regarding security issues and <code>eval()</code> do not apply <em>(i think?)</em>.</p> <p>I'll also just add that I can get all the necessary variables into an array by using <code>get_defined_vars()</code>:</p> <pre><code>$allVars = get_defined_vars(); echo $pet; // "lamb" echo $allVars['pet']; // "lamb" </code></pre>
[ { "answer_id": 283231, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 2, "selected": false, "text": "<p>Here's what I've just come up with, but I'd still be interested to know if there's a better way. Cheers.</p>\n\n<pre><code>$allVars = get_defined_vars();\n$file = file_get_contents('myFile.txt');\n\nforeach ($allVars as $var =&gt; $val) {\n $file = preg_replace(\"@\\\\$\" . $var . \"([^a-zA-Z_0-9\\x7f-\\xff]|$)@\", $val . \"\\\\1\", $file);\n}\n</code></pre>\n" }, { "answer_id": 283232, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 4, "selected": false, "text": "<p>Regex would be easy enough. And it would not care about things that <code>eval()</code> would consider a syntax error.</p>\n\n<p>Here's the pattern to find PHP style variable names.</p>\n\n<pre><code>\\$\\w+\n</code></pre>\n\n<p>I would probably take this general pattern and use a PHP array to look up each match I've found (using (<code>preg_replace_callback()</code>). That way the regex needs to be applied only once, which is faster on the long run.</p>\n\n<pre><code>$allVars = get_defined_vars();\n$file = file_get_contents('myFile.txt');\n\n// unsure if you have to use single or double backslashes here for PHP to understand\npreg_replace_callback ('/\\$(\\w+)/', \"find_replacements\", $file);\n\n// replace callback function\nfunction find_replacements($match)\n{\n global $allVars;\n if (array_key_exists($match[1], $allVars))\n return $allVars[$match[1]];\n else\n return $match[0];\n}\n</code></pre>\n" }, { "answer_id": 283237, "author": "Noah Goodrich", "author_id": 20178, "author_profile": "https://Stackoverflow.com/users/20178", "pm_score": 0, "selected": false, "text": "<p>Depending on the situation, <a href=\"http://us2.php.net/manual/en/function.str-replace.php\" rel=\"nofollow noreferrer\">str_replace</a> might do the trick.</p>\n\n<p>Example:</p>\n\n<pre><code>// -- myFile.txt --\nMary had a little %pet%.\n\n// -- parser.php --\n$pet = \"lamb\";\n$fileName = myFile.txt\n\n$currentContents = file_get_contents($fileName);\n\n$newContents = str_replace('%pet%', $pet, $currentContents);\n\n// $newContents == 'Mary had a little lamb.'\n</code></pre>\n\n<p>When you look at str_replace note that search and replace parameters can take arrays of values to search for and replace.</p>\n" }, { "answer_id": 283339, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 4, "selected": true, "text": "<p>If it's from a trusted source you can use (dramatic pause) <a href=\"http://www.php.net/eval\" rel=\"noreferrer\">eval()</a> (gasps of horror from the audience).</p>\n\n<pre><code>$text = 'this is a $test'; // single quotes to simulate getting it from a file\n$test = 'banana';\n$text = eval('return \"' . addslashes($text) . '\";');\necho $text; // this is a banana\n</code></pre>\n" }, { "answer_id": 285501, "author": "Zak", "author_id": 2112692, "author_profile": "https://Stackoverflow.com/users/2112692", "pm_score": 2, "selected": false, "text": "<p>Does it have to be $pet? Could it be <code>&lt;?= $pet ?&gt;</code> instead? Because if so, just use include. This is the whole idea of php as a templating engine.</p>\n\n<pre><code>//myFile.txt\nMary had a little &lt;?= $pet ?&gt;.\n\n//parser.php\n\n$pet = \"lamb\";\nob_start();\ninclude(\"myFile.txt\");\n$contents = ob_end_clean();\n\necho $contents;\n</code></pre>\n\n<p>This will echo out :</p>\n\n<pre><code>Mary had a little lamb.\n</code></pre>\n" }, { "answer_id": 285514, "author": "user37125", "author_id": 37125, "author_profile": "https://Stackoverflow.com/users/37125", "pm_score": -1, "selected": false, "text": "<p>You could use <a href=\"http://www.php.net/strtr\" rel=\"nofollow noreferrer\">strtr</a>:</p>\n\n<pre><code>$text = file_get_contents('/path/to/myFile.txt'); // \"Mary had a little $pet.\"\n$allVars = get_defined_vars(); // array('pet' =&gt; 'lamb');\n$translate = array();\n\nforeach ($allVars as $key =&gt; $value) {\n $translate['$' . $key] = $value; // prepend '$' to vars to match text\n}\n\n// translate is now array('$pet' =&gt; 'lamb');\n\n$text = strtr($text, $translate);\n\necho $text; // \"Mary had a little lamb.\"\n</code></pre>\n\n<p>You probably want to do the prepending in get_defined_vars(), so you don't loop the variables twice. Or better yet, just make sure whatever keys you assign initially match the identifier you use in myFile.txt.</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9021/" ]
What's the best way to take some plain text (not PHP code) which contains PHP-style variables, and then substitute in the value of the variable. This is kinda hard to describe, so here's an example. ``` // -- myFile.txt -- Mary had a little $pet. // -- parser.php -- $pet = "lamb"; // open myFile.txt and transform it such that... $newContents = "Mary had a little lamb."; ``` I've been considering using a regex or perhaps `eval()`, though I'm not sure which would be easiest. This script is only going to be running locally, so any worries regarding security issues and `eval()` do not apply *(i think?)*. I'll also just add that I can get all the necessary variables into an array by using `get_defined_vars()`: ``` $allVars = get_defined_vars(); echo $pet; // "lamb" echo $allVars['pet']; // "lamb" ```
If it's from a trusted source you can use (dramatic pause) [eval()](http://www.php.net/eval) (gasps of horror from the audience). ``` $text = 'this is a $test'; // single quotes to simulate getting it from a file $test = 'banana'; $text = eval('return "' . addslashes($text) . '";'); echo $text; // this is a banana ```
283,251
<p>I need to read account number from Maestro/Mastercard with smart card reader. I am using Java 1.6 and its javax.smartcardio package. I need to send APDU command which will ask EMV application stored on card's chip for PAN number. Problem is, I cannot find regular byte array to construct APDU command which will return needed data anywhere... </p>
[ { "answer_id": 283452, "author": "Rasmus Faber", "author_id": 5542, "author_profile": "https://Stackoverflow.com/users/5542", "pm_score": 0, "selected": false, "text": "<p>You need to do construct a CommandAPDU object and pass it to the transmit()-command.</p>\n\n<p>You should be able to find the precise command in the documentation for your smartcard, but here is one example:</p>\n\n<pre><code>byte[] readFile(CardChannel channel) throws CardException {\n CommandAPDU command = new CommandAPDU(0xB0, 0x60, 0x10, 0x00);\n ResponseAPDU response = channel.transmit(command);\n return response.getData();\n}\n</code></pre>\n" }, { "answer_id": 283760, "author": "Rasmus Faber", "author_id": 5542, "author_profile": "https://Stackoverflow.com/users/5542", "pm_score": 0, "selected": false, "text": "<p>Did you try looking up in your documentation what 0x6D00 means? It looks like it might mean that the ENVELOPE command is not supported. Have you tried using T=0 protocol instead of T=1?</p>\n\n<p>I would not expect my example to work on your card. I don't know which APDUs the Maestro/MasterCard-supports, so I couldn't give you a working example.</p>\n\n<p>Try giving the command an explicit expected length like this:</p>\n\n<pre><code>byte[] readPan(CardChannel channel) throws CardException {\n CommandAPDU command = new CommandAPDU(0x00, 0xB2, 0x5a, 0x14, 250);\n ResponseAPDU response = channel.transmit(command);\n return response.getData();\n}\n</code></pre>\n" }, { "answer_id": 286681, "author": "Rasmus Faber", "author_id": 5542, "author_profile": "https://Stackoverflow.com/users/5542", "pm_score": 4, "selected": true, "text": "<p>You shouldn't need to wrap the APDU further. The API layer should take care of that.</p>\n\n<p>It looks like the 0x6D00 response just means that the application did not support the INS.</p>\n\n<p>Just troubleshooting now, but you did start out by selecting the MasterCard application, right?</p>\n\n<p>I.e. something like this:</p>\n\n<pre><code>void selectApplication(CardChannel channel) throws CardException {\n byte[] masterCardRid = new byte[]{0xA0, 0x00, 0x00, 0x00, 0x04};\n CommandAPDU command = new CommandAPDU(0x00, 0xA4, 0x04, 0x00, masterCardRid);\n ResponseAPDU response = channel.transmit(command);\n return response.getData();\n}\n</code></pre>\n" }, { "answer_id": 304591, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>here is some working example: </p>\n\n<pre><code>CardChannel channel = card.getBasicChannel(); \n\n byte[] selectMaestro={(byte)0x00, (byte)0xA4,(byte)0x04,(byte)0x00 ,(byte)0x07 ,(byte)0xA0 ,(byte)0x00 ,(byte)0x00 ,(byte)0x00 ,(byte)0x04 ,(byte)0x30 ,(byte)0x60 ,(byte)0x00};\n byte[] getProcessingOptions={(byte)0x80,(byte)0xA8,(byte)0x00,(byte)0x00,(byte)0x02,(byte)0x83,(byte)0x00,(byte)0x00};\n byte[] readRecord={(byte)0x00,(byte)0xB2,(byte)0x02,(byte)0x0C,(byte)0x00};\n\n ResponseAPDU r=null;\n\n try {\n ATR atr = card.getATR(); //reset kartice\n\n CommandAPDU capdu=new CommandAPDU( selectMaestro );\n\n r=card.getBasicChannel().transmit( capdu );\n\n capdu=new CommandAPDU(getProcessingOptions);\n r=card.getBasicChannel().transmit( capdu );\n\n\n capdu=new CommandAPDU(readRecord);\n r=card.getBasicChannel().transmit( capdu );\n</code></pre>\n\n<p>This works with Maestro card, I can read PAN number, yet now I need to read MasterCard's PAN number. I do not know should I change the read record APDU or select application APDU. Anyone familiar with APDUs? </p>\n" }, { "answer_id": 556248, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<pre><code>atr = open();\nprints(atr);\n\nprints(\"[Step 1] Select 1PAY.SYS.DDF01 to get the PSE directory\");\ncmd = new ISOSelect(ISOSelect.SELECT_AID, EMV4_1.AID_1PAY_SYS_DDF01);\ncard_response = execute(cmd);\nprints(card_response);\nSFI = NumUtil.hex2String((byte)((1 &lt; &lt; 3) | 4));\n\n// try SFI 1 record 1\nprints(\"[Step 2] Send READ RECORD with 0 to find out where the record is\");\nread = new EMVReadRecord(SFI, \"01\", \"00\");\ncard_response = execute(read);\nprints(card_response);\nbyte_size = NumUtil.hex2String(card_response.getStatusWord().getSw2());\n\nprints(\"[Step 3] Send READ RECORD with 1C to get the PSE data\");\nread = new EMVReadRecord(SFI, \"01\", byte_size);\ncard_response = execute(read);\nprints(card_response);\n// the AID is A0000000031010\nprints(\"[Step 4] Now that we know the AID, select the application\");\n\ncmd = new ISOSelect(ISOSelect.SELECT_AID, \"A0000000031010\");\ncard_response = execute(cmd);\nprints(card_response);\nprints(\"[Step 5] Send GET PROCESSING OPTIONS command\");\n\ncmd = new EMVGetProcessingOptions();\ncard_response = execute(cmd);\nprints(card_response);\n\n// SFI for the first group of AFL is 0C\n\nprints(\"[Step 6] Send READ RECORD with 0 to find out where the record is\");\nread = new EMVReadRecord(\"0C\", \"01\", \"00\");\ncard_response = execute(read);\nprints(card_response);\nbyte_size = NumUtil.hex2String(card_response.getStatusWord().getSw2());\n\nprints(\"[Step 7] Use READ RECORD with the given number of bytes to retrieve the data\");\nread = new EMVReadRecord(\"0C\", \"01\", byte_size);\ncard_response = execute(read);\nprints(card_response);\n\ndata = new TLV(card_response.getData());\n\nclose();\n</code></pre>\n" }, { "answer_id": 25202288, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>what about using a scanner, getting a picture of the card, scanning the content of the picture with a good java ocr library ( like <a href=\"http://ocr4j.sourceforge.net/\" rel=\"nofollow\">http://ocr4j.sourceforge.net/</a> for example ) and search for a (usually) 16 digit sequence XXXX-XXXX-XXXX-XXXX , then you will get the PAN from any EMV card using java.</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283251", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I need to read account number from Maestro/Mastercard with smart card reader. I am using Java 1.6 and its javax.smartcardio package. I need to send APDU command which will ask EMV application stored on card's chip for PAN number. Problem is, I cannot find regular byte array to construct APDU command which will return needed data anywhere...
You shouldn't need to wrap the APDU further. The API layer should take care of that. It looks like the 0x6D00 response just means that the application did not support the INS. Just troubleshooting now, but you did start out by selecting the MasterCard application, right? I.e. something like this: ``` void selectApplication(CardChannel channel) throws CardException { byte[] masterCardRid = new byte[]{0xA0, 0x00, 0x00, 0x00, 0x04}; CommandAPDU command = new CommandAPDU(0x00, 0xA4, 0x04, 0x00, masterCardRid); ResponseAPDU response = channel.transmit(command); return response.getData(); } ```
283,284
<p>When I create a TFS report of a query with the Excel integration features (we are using Excel 2003), Excel resets formatting of all cells after clicking the "Refresh" button in the TFS Toolbar.</p> <p>Our team likes to print this report and drag it into our weekly meeting as it accurately lists all our open tasks. Bad formatting is a pain, though: Vertical alignment set to "bottom" and no borders on cells makes it nearly impossible to know when one Task/Bug starts and the other ends...</p>
[ { "answer_id": 291674, "author": "user37826", "author_id": 37826, "author_profile": "https://Stackoverflow.com/users/37826", "pm_score": 1, "selected": false, "text": "<p>My guess is that since Microsoft is playing up this feature in the VS 2010 CTP, it's not currently supported.</p>\n\n<p>Your best bet may be to create a sheet with all of the appropriate formatting and then cut and paste from the <em>live</em> excel sheet into the formatted sheet.</p>\n" }, { "answer_id": 298088, "author": "Daren Thomas", "author_id": 2260, "author_profile": "https://Stackoverflow.com/users/2260", "pm_score": 3, "selected": true, "text": "<p>I ended up doing this:</p>\n\n<ul>\n<li><code>tfpt.exe</code> (<a href=\"http://msdn.microsoft.com/en-us/tfs2008/bb980963.aspx\" rel=\"nofollow noreferrer\">Team Foundation Power Tools</a>) </li>\n<li>query for xml: <code>tfpt query /format:xml</code> (add your query name here etc.)</li>\n<li>convert that to a html table with XSL</li>\n<li>write a simple batch script to do above steps</li>\n<li>(Profit!!!)</li>\n</ul>\n\n<p>This is the XSL script I used (will need tweeking if you use other fields):</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;\n\n&lt;xsl:stylesheet version=\"1.0\" \n xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" \n xmlns:spss=\"http://xml.spss.com/spss/oms\"\n exclude-result-prefixes=\"spss\"&gt;\n\n&lt;xsl:template match=\"/\"&gt;\n&lt;html&gt;\n &lt;head&gt;\n &lt;title&gt;All active Work Items&lt;/title&gt;\n &lt;/head&gt;\n &lt;body&gt;\n &lt;table border=\"1\" frame=\"border\" rules=\"all\"&gt;\n &lt;tr&gt;&lt;th&gt;ID&lt;/th&gt;&lt;th&gt;Area Path&lt;/th&gt;&lt;th&gt;Assigned To&lt;/th&gt;&lt;th&gt;Title&lt;/th&gt;&lt;th&gt;Description&lt;/th&gt;&lt;/tr&gt;\n &lt;xsl:for-each select=\".//WorkItem\"&gt;\n &lt;tr&gt;\n &lt;td&gt;&lt;xsl:value-of select=\"./Field[@RefName='System.Id']/@Value\"/&gt;&lt;/td&gt;\n &lt;td&gt;&lt;xsl:value-of select=\"./Field[@RefName='System.AreaPath']/@Value\"/&gt;&lt;/td&gt;\n &lt;td&gt;&lt;xsl:value-of select=\"./Field[@RefName='System.AssignedTo']/@Value\"/&gt;&lt;/td&gt;\n &lt;td&gt;&lt;xsl:value-of select=\"./Field[@RefName='System.Title']/@Value\"/&gt;&lt;/td&gt;\n &lt;td&gt;&lt;xsl:value-of select=\"./Field[@RefName='System.Description']/@Value\"/&gt;&lt;/td&gt;\n &lt;/tr&gt;\n &lt;/xsl:for-each&gt;\n &lt;/table&gt; \n &lt;/body&gt; \n&lt;/html&gt;\n&lt;/xsl:template&gt;\n\n&lt;/xsl:stylesheet&gt;\n</code></pre>\n" }, { "answer_id": 571445, "author": "user69130", "author_id": 69130, "author_profile": "https://Stackoverflow.com/users/69130", "pm_score": 1, "selected": false, "text": "<p>I ran into the same issue... </p>\n\n<p>TFS Refresh is not so bad, but when the query stops working and you have to re-add it, it inserts rows to do the data creation, leaving any links to the info corrupted (or looking in the wrong place!)</p>\n\n<p>I ended up with the TFS query going into a \"TFS Query\" sheet, which I referenced from the sheet that does calculations on the query fields (it uses Indirect, Offset, and Match functions so that there is no calculation dependence from the sheet with the TFS Query sheet. This works like a charm, and I can even delete the query, and re-add it later.</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283284", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2260/" ]
When I create a TFS report of a query with the Excel integration features (we are using Excel 2003), Excel resets formatting of all cells after clicking the "Refresh" button in the TFS Toolbar. Our team likes to print this report and drag it into our weekly meeting as it accurately lists all our open tasks. Bad formatting is a pain, though: Vertical alignment set to "bottom" and no borders on cells makes it nearly impossible to know when one Task/Bug starts and the other ends...
I ended up doing this: * `tfpt.exe` ([Team Foundation Power Tools](http://msdn.microsoft.com/en-us/tfs2008/bb980963.aspx)) * query for xml: `tfpt query /format:xml` (add your query name here etc.) * convert that to a html table with XSL * write a simple batch script to do above steps * (Profit!!!) This is the XSL script I used (will need tweeking if you use other fields): ``` <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:spss="http://xml.spss.com/spss/oms" exclude-result-prefixes="spss"> <xsl:template match="/"> <html> <head> <title>All active Work Items</title> </head> <body> <table border="1" frame="border" rules="all"> <tr><th>ID</th><th>Area Path</th><th>Assigned To</th><th>Title</th><th>Description</th></tr> <xsl:for-each select=".//WorkItem"> <tr> <td><xsl:value-of select="./Field[@RefName='System.Id']/@Value"/></td> <td><xsl:value-of select="./Field[@RefName='System.AreaPath']/@Value"/></td> <td><xsl:value-of select="./Field[@RefName='System.AssignedTo']/@Value"/></td> <td><xsl:value-of select="./Field[@RefName='System.Title']/@Value"/></td> <td><xsl:value-of select="./Field[@RefName='System.Description']/@Value"/></td> </tr> </xsl:for-each> </table> </body> </html> </xsl:template> </xsl:stylesheet> ```
283,294
<p>I found a lot of info about how to debug simple Python programs with Emacs. But what if I want to debug a Django application? I run the development server and I would like to somehow attach to the process from Emacs and then set breakpoints, etc. Similar to Visual Studio's "attach to process". How to do that?</p>
[ { "answer_id": 284058, "author": "Ned Batchelder", "author_id": 14343, "author_profile": "https://Stackoverflow.com/users/14343", "pm_score": 0, "selected": false, "text": "<p>I don't really know anything about it, but putting \"debugging Python with emacs\" into Google gave me this page about <a href=\"http://twistedmatrix.com/projects/core/documentation/howto/debug-with-emacs.html\" rel=\"nofollow noreferrer\">debugging twisted with emacs</a>, so it seems to be possible.</p>\n" }, { "answer_id": 284607, "author": "Ben", "author_id": 3553, "author_profile": "https://Stackoverflow.com/users/3553", "pm_score": 4, "selected": false, "text": "<p>This isn't emacs specific, but you can use the Python debugger by adding the following to a Django view function:</p>\n\n<p><code>import pdb; pdb.set_trace()</code></p>\n\n<p>Now when you run the development server and view the page, your browser will appear to hang or load very slowly - switch over to your console, and you have access to the full debugger. You can inspect AND modify state of your application via an interactive shell - check out the Python documentation for the debugger, or this link for some <a href=\"http://www.onlamp.com/pub/a/python/2005/09/01/debugger.html\" rel=\"noreferrer\">Python debugging examples</a></p>\n\n<hr>\n\n<p>If all you need is logging, add the following to your <code>settings.py</code>:</p>\n\n<pre><code>logging.basicConfig(\n level = logging.DEBUG,\n format = '%(asctime)s %(levelname)s %(message)s',\n filename = '/tmp/mylog.log',\n filemode = 'w'\n)\n</code></pre>\n\n<p>Now you can log messages to <code>/tmp/mylog.log</code> by adding the following to any view function:</p>\n\n<pre><code>import logging\nlogging.debug(\"Something happened\")\n</code></pre>\n" }, { "answer_id": 286703, "author": "Chad", "author_id": 37309, "author_profile": "https://Stackoverflow.com/users/37309", "pm_score": 2, "selected": false, "text": "<p>Here's something I found last night that will do exactly what you want when the program crashes:</p>\n\n<p><a href=\"http://code.google.com/p/django-command-extensions/\" rel=\"nofollow noreferrer\">http://code.google.com/p/django-command-extensions/</a></p>\n\n<p>Once you install that you can run:</p>\n\n<blockquote>\n <p>python manage.py runserver_plus</p>\n</blockquote>\n\n<p>and you will have an interactive <code>AJAX console</code> on your <code>Error</code> page. (Obviously, be careful with the amount of access people have to this web server when running in that mode.)</p>\n\n<p>GitHub: <a href=\"https://github.com/django-extensions/django-extensions\" rel=\"nofollow noreferrer\">https://github.com/django-extensions/django-extensions</a></p>\n\n<p>You can get Django Extensions by using pip or easy_install:</p>\n\n<blockquote>\n <p>$ pip install django-extensions or $ easy_install django-extensions</p>\n</blockquote>\n\n<p>If you want to install it from source, grab the git repository from GitHub and run setup.py:</p>\n\n<blockquote>\n <p>$ git clone git://github.com/django-extensions/django-extensions.git<br>\n $ cd django-extensions<br>\n $ python setup.py install</p>\n</blockquote>\n" }, { "answer_id": 1665783, "author": "Matthew Talbert", "author_id": 27611, "author_profile": "https://Stackoverflow.com/users/27611", "pm_score": 5, "selected": true, "text": "<p>Start pdb like this:</p>\n\n<p><kbd>M-x</kbd> <code>pdb</code></p>\n\n<p>Then, start the Django development server:</p>\n\n<pre><code>python manage.py runserver --noreload\n</code></pre>\n\n<p>Once you have the (Pdb) prompt, you need to do this:</p>\n\n<pre><code>import sys\nsys.path.append('/path/to/directory/containing/views.py')\n</code></pre>\n\n<p>Once you've done this, you should be able to set breakpoints normally. Just navigate to the line number you want, and </p>\n\n<p><kbd>C-x</kbd> <kbd>SPC</kbd></p>\n" }, { "answer_id": 7398616, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>About the general non-emacs-exclusive way, there is a very nice screencast out there you might be interested in: <a href=\"http://ericholscher.com/blog/2008/aug/31/using-pdb-python-debugger-django-debugging-series-/\" rel=\"nofollow\">http://ericholscher.com/blog/2008/aug/31/using-pdb-python-debugger-django-debugging-series-/</a></p>\n\n<p>The emacs integration described above doesn't work for me yet. It doesn't really seem to connect to the running application.</p>\n\n<p>Further I consider this blog post here very interesting: <a href=\"http://web.archive.org/web/20101230072606/http://panela.blog-city.com/python_and_emacs_5_pdb_and_emacs.htm\" rel=\"nofollow\">http://web.archive.org/web/20101230072606/http://panela.blog-city.com/python_and_emacs_5_pdb_and_emacs.htm</a></p>\n\n<p>cu\nRoman</p>\n" }, { "answer_id": 7418949, "author": "user111443", "author_id": 111443, "author_profile": "https://Stackoverflow.com/users/111443", "pm_score": 1, "selected": false, "text": "<p>Because recent versions of Emacs python mode do support 'pdbtrack' functionality by default, all you need is just set up breakpoint in your code this way:</p>\n\n<pre><code>import pdb; pdb.set_trace()\n</code></pre>\n\n<p>Also, you have to start your Django application devserver from within Emacs shell: </p>\n\n<p><kbd>M-x</kbd> <code>shell</code></p>\n\n<p>And then, in the shell, start the Django development server:</p>\n\n<pre><code>python ./manage.py runserver\n</code></pre>\n\n<p>P.S. No need for specific pdb sessions or --noreload flag. Noreload would require you to manually restart your applications and so I do not find this useful for Emacs.</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5475/" ]
I found a lot of info about how to debug simple Python programs with Emacs. But what if I want to debug a Django application? I run the development server and I would like to somehow attach to the process from Emacs and then set breakpoints, etc. Similar to Visual Studio's "attach to process". How to do that?
Start pdb like this: `M-x` `pdb` Then, start the Django development server: ``` python manage.py runserver --noreload ``` Once you have the (Pdb) prompt, you need to do this: ``` import sys sys.path.append('/path/to/directory/containing/views.py') ``` Once you've done this, you should be able to set breakpoints normally. Just navigate to the line number you want, and `C-x` `SPC`
283,295
<p>According to MSDN</p> <blockquote> <p>The return value specifies the result of the message processing; it depends on the message sent.</p> </blockquote> <p>I know it is defined as </p> <pre><code>typedef LONG_PTR LRESULT; </code></pre> <p>Meaning it will be 8 bytes on 64bit machine but it doesn't!</p> <p>Does anyone know if it is safe to assume that only the lower 4 bytes are used and store it as an <code>INT</code> (for example).</p>
[ { "answer_id": 283337, "author": "James Ogden", "author_id": 3198, "author_profile": "https://Stackoverflow.com/users/3198", "pm_score": 3, "selected": true, "text": "<p>No it's not safe, because the return value is defined by the message being sent and the handler.</p>\n\n<p>If you control the handler and the message then it'd be possible, it's not safe in the general case. </p>\n\n<p>James</p>\n" }, { "answer_id": 283347, "author": "Maverique", "author_id": 4373, "author_profile": "https://Stackoverflow.com/users/4373", "pm_score": 1, "selected": false, "text": "<p>No it is not safe in general. Do not assume the downcast. Also, useful is to compile your code with /RTCc which ensures inadvertent casts are asserted at runtime.</p>\n" }, { "answer_id": 283445, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": 1, "selected": false, "text": "<p>Definitely not safe. If the message return is indeed a pointer, it is very well possible for the pointer to have its 33rd bit set - especially on machines with >4GB memory.</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283295", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14587/" ]
According to MSDN > > The return value specifies the result > of the message processing; it depends > on the message sent. > > > I know it is defined as ``` typedef LONG_PTR LRESULT; ``` Meaning it will be 8 bytes on 64bit machine but it doesn't! Does anyone know if it is safe to assume that only the lower 4 bytes are used and store it as an `INT` (for example).
No it's not safe, because the return value is defined by the message being sent and the handler. If you control the handler and the message then it'd be possible, it's not safe in the general case. James
283,297
<p>I have a dll that must be useable from C etc, so I cant use string objects etc as a normal would, but I'm not sure on how to do this safely..</p> <pre><code>const char *GetString() { std::stringstream ss; ss &lt;&lt; "The random number is: " &lt;&lt; rand(); return ss.str().c_str(); } </code></pre> <p>could the c string be destroyed when ss falls off the stack? I'm assuming so...</p> <p>Another option may be to create a new string on the heap, but what is going to deallocate that?</p> <pre><code>const char *GetString() { std::stringstream ss; ss &lt;&lt; "The random number is: " &lt;&lt; rand(); char *out = new char[ss.str().size()]; strcpy(ss.str().c_str(), out); return out;//is out ever deleted? } </code></pre> <p>The same goes for pointers to other things as well as strings.</p>
[ { "answer_id": 283308, "author": "shoosh", "author_id": 9611, "author_profile": "https://Stackoverflow.com/users/9611", "pm_score": 1, "selected": false, "text": "<p>The first would actually not work because the stringstream deallocates it's space on destruction. So if you try to de-reference that pointer there is a good chance that your program would crash. </p>\n\n<p>The second option you mention is how it's usually done and the user of the function is required to deallocate the space. IIf this is a C program which uses the function make sure you allocate with malloc() and free with free() </p>\n\n<p>Another option is to return an address of a static char array. This is relevant if you know in advance a good upper bound to the length. More importantly this should be used ONLY if there is no chance that the function is going to be called from two different threads at the same time because using a static array essentially makes your function non-<a href=\"http://en.wikipedia.org/wiki/Reentrant_(subroutine)\" rel=\"nofollow noreferrer\">reentrant</a>.</p>\n" }, { "answer_id": 283312, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Well obviously anytime you are returning pointers to memory allocated inside a function the deallocating must come externally, unless you are using garbage collection. If you don't want to do this, allocate a character buffer b efore calling GetString() and change the prototype to</p>\n\n<p>int get_string(const char* buffer);</p>\n\n<p>Then fill up the buffer. But returning a point to malloced data is fine.</p>\n" }, { "answer_id": 283313, "author": "jab", "author_id": 20367, "author_profile": "https://Stackoverflow.com/users/20367", "pm_score": 0, "selected": false, "text": "<p>If you declare ss as static you can avoid the problem. This could be a good solution if your program runs on a single-thread enviroment.</p>\n" }, { "answer_id": 283314, "author": "Pieter", "author_id": 5822, "author_profile": "https://Stackoverflow.com/users/5822", "pm_score": 0, "selected": false, "text": "<p>You have to allocate the string on the heap if you want to safely return it, also allocate with malloc() i.s.o. new() when writing C functions.</p>\n\n<p>When you return pointers (and, unlike in C++, in C you have no real choice many times), deallocation is always a concern. There isn't really a definitive solution.</p>\n\n<p>One way of handling this I've seen in quite some API's is calling all function either</p>\n\n<pre><code>CreateString()\n</code></pre>\n\n<p>When memory needs to be deallocated by the caller, and</p>\n\n<pre><code>GetString()\n</code></pre>\n\n<p>when that's not an issue.</p>\n\n<p>This is anything but foolproof of course, but given enough discipline it's the best method I've seen to be honest...</p>\n" }, { "answer_id": 283317, "author": "n-alexander", "author_id": 23420, "author_profile": "https://Stackoverflow.com/users/23420", "pm_score": 4, "selected": true, "text": "<p>The first variant doesn't work because you're returning a pointer into a stack object, which will get destroyed. (More presisely, you return a pointer to a heap memory, whch will have been deleted().) Worse still, it may even work for some time, if nobody's overwriting the memory, making it very hard to debug.</p>\n\n<p>Next, you can not return a const char* unless you return a pointer to a static string like this:</p>\n\n<pre><code>const char *GetString()\n{\n return \"a static string in DATA segment - no need to delete\";\n}\n</code></pre>\n\n<p>You second variant has the problem of returning memory allocated with new() into a C program that will call free(). Those may not be compatible.</p>\n\n<p>If you return a string to C, there are 2 way to do that:</p>\n\n<pre><code>char *GetString()\n{\n std::stringstream ss;\n ss &lt;&lt; \"The random number is: \" &lt;&lt; rand();\n return strdup( ss.str().c_str() ); // allocated in C style with malloc()\n}\n\nvoid foo()\n{\n char *p = GetString();\n printf(\"string: %s\", p));\n free( p ); // must not forget to free(), must not use delete()\n}\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>char *GetString(char *buffer, size_t len)\n{\n std::stringstream ss;\n ss &lt;&lt; \"The random number is: \" &lt;&lt; rand();\n return strncpy(buffer, ss.str().c_str(), len); // caller allocates memory\n}\n\nvoid foo()\n{\n char buffer[ 100 ];\n printf(\"string: %s\", GetString(buffer, sizeof( buffer ))); // no memory leaks\n}\n</code></pre>\n\n<p>depending on you memory handling policy.</p>\n\n<p>As a rule, you can NOT ever return a pointer or a reference to an automatic object in C++. This is one of common mistakes analyzed in many C++ books.</p>\n" }, { "answer_id": 283399, "author": "sep", "author_id": 30333, "author_profile": "https://Stackoverflow.com/users/30333", "pm_score": 0, "selected": false, "text": "<p>If thread-safety is not important,</p>\n\n<pre><code>const char *GetString()\n{\n static char *out;\n std::stringstream ss;\n ss &lt;&lt; \"The random number is: \" &lt;&lt; rand();\n delete[] out;\n char *out = new char[ss.str().size()];\n strcpy(ss.str().c_str(), out);\n return out;//is out ever deleted?\n}\n</code></pre>\n\n<p>Then the function can take over the responsibility of deallocating the string.</p>\n\n<p>If thread-safety is important,</p>\n\n<p>Then the best method is to pass it in as an argument, as in,</p>\n\n<pre><code>void GetString(char *out, int maxlen);\n</code></pre>\n\n<p>I observe this is what happens when the old non thread-safe APIs are changed to thread-safe.</p>\n" }, { "answer_id": 283418, "author": "Enno", "author_id": 30404, "author_profile": "https://Stackoverflow.com/users/30404", "pm_score": 0, "selected": false, "text": "<p>After the function is called, you will want the caller to be responsible for the memory of the string (and especially for de-allocating it). Unless you want to use static variables, but there be dragons! The best way to do this cleanly is to have the caller do the allocation of the memory in the first place:</p>\n\n<pre><code>void foo() {\n char result[64];\n GetString(result, sizeof(result));\n puts(result);\n}</code></pre>\n\n<p>and then GetString should look like this:</p>\n\n<pre><code>int GetString(char * dst, size_t len) {\n std::stringstream ss;\n ss &lt;&lt; \"The random number is: \" &lt;&lt; rand();\n strncpy(ss.str().c_str(), dst, len);\n}</code></pre>\n\n<p>Passing the maximum buffer length and using strncpy() will avoid accidentally overwriting the buffer.</p>\n" }, { "answer_id": 283745, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 2, "selected": false, "text": "<p>Over the years C boiled this down to 2 standard methods:</p>\n\n<ul>\n<li>Caller passes in buffer.<br>\nThere are three versions of this.<br>\nVersion 1: Pass a buffer and a length.<br>\nVersion 2: Documentation specifies an expected min buffer size.<br>\nVersion 3: Pre-Flight. Function returns the min buffer required. caller calls twice first time with a NULL buffer.\n\n<ul>\n<li>Example: read()</li>\n</ul></li>\n<li>Use a static buffer that is valid until the next call.\n\n<ul>\n<li>Example: tmpname()</li>\n</ul></li>\n</ul>\n\n<p>A few non standard ones returned memory that you had to explicitly free</p>\n\n<ul>\n<li>strdup() pops to mind.<br>\nCommon extension but not actually in the standard. </li>\n</ul>\n" }, { "answer_id": 24023830, "author": "Alex", "author_id": 175157, "author_profile": "https://Stackoverflow.com/users/175157", "pm_score": 0, "selected": false, "text": "<p>The answers so far don't address a very significant issue, namely what to do if the length of the required buffer for the result is unknown and can change between calls, even with the same arguments (such as reading a value from a database), so I'm providing what I consider to be the best way to handle this situation.</p>\n\n<p>If the size is not known in advance, consider passing a callback function to your function, which receives the <code>const char*</code> as a parameter:</p>\n\n<pre><code>typedef void (*ResultCallback)( void* context, const char* result );\n\nvoid Foo( ResultCallback resultCallback, void* context )\n{\n std::string s = \"....\";\n resultCallback( context, s.c_str() );\n}\n</code></pre>\n\n<p>The implementation of <code>ResultCallback</code> can allocate the needed memory and copy the buffer pointed to by <code>result</code>. I'm assuming C so I'm not casting to/from <code>void*</code> explicitly.</p>\n\n<pre><code>void UserCallback( void* context, const char* result )\n{\n char** copied = context;\n *copied = malloc( strlen(result)+1 );\n strcpy( *copied, result );\n}\n\nvoid User()\n{\n char* result = NULL;\n\n Foo( UserCallback, &amp;result );\n\n // Use result...\n if( result != NULL )\n printf(\"%s\", result);\n\n free( result );\n}\n</code></pre>\n\n<p>This is the most portable solution and handles even the toughest cases where the size of the returned string cannot be known in advance.</p>\n" }, { "answer_id": 24025260, "author": "Deduplicator", "author_id": 3204551, "author_profile": "https://Stackoverflow.com/users/3204551", "pm_score": 0, "selected": false, "text": "<p>There are various methods, developed over time, to return a variable amount of data from a function.</p>\n\n<ol>\n<li>Caller passes in buffer.\n\n<ol>\n<li>The neccessary size is documented and not passed, too short buffers are <a href=\"https://stackoverflow.com/questions/2397984/undefined-unspecified-and-implementation-defined-behavior\">Undefined Behavior</a>: <code>strcpy()</code></li>\n<li>The neccessary size is documented and passed, errors are signaled by the return value: <code>strcpy_s()</code></li>\n<li>The neccessary size is unknown, but can be queried by calling the function with buffer-length 0: <code>snprintf</code></li>\n<li>The neccessary size is unknown and cannot be queried, as much as fits in a buffer of passed size is returned. If neccessary, additional calls must be made to get the rest: <code>fread</code></li>\n<li><strong>⚠</strong> The neccessary size is unknown, cannot be queried, and passing too small a buffer is <a href=\"https://stackoverflow.com/questions/2397984/undefined-unspecified-and-implementation-defined-behavior\">Undefined Behavior</a>. This is a design defect, therefore the function is deprecated / removed in newer versions, and just mentioned here for completeness: <code>gets</code>.</li>\n</ol></li>\n<li>Caller passes a callback:\n\n<ol>\n<li>The callback-function gets a context-parameter: <code>qsort_s</code></li>\n<li>The callback-function gets no context-parameter. Getting the context requires magic: <code>qsort</code></li>\n</ol></li>\n<li>Caller passes an allocator: Not found in the C standard library. All allocator-aware C++ containers support that though.</li>\n<li>Callee contract specifies the deallocator. Calling the wrong one is <a href=\"https://stackoverflow.com/questions/2397984/undefined-unspecified-and-implementation-defined-behavior\">Undefined Behavior</a>: <code>fopen</code>-><code>fclose</code> <code>strdup</code>-><code>free</code></li>\n<li>Callee returns an object which contains the deallocator: COM-Objects <code>std::shared_ptr</code></li>\n<li>Callee uses an internal shared buffer: <code>asctime</code></li>\n</ol>\n\n<p>In general, whenever the user has to guess the size or look it up in the manual, he will sometimes get it wrong. If he does not get it wrong, a later revision might invalidate his careful work, so it doesn't matter he was once right. Anyway, this way lies <a href=\"https://stackoverflow.com/questions/2397984/undefined-unspecified-and-implementation-defined-behavior\">madness (UB)</a>.</p>\n\n<p>For the rest, choose the most comfortable and efficient one you can.</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6266/" ]
I have a dll that must be useable from C etc, so I cant use string objects etc as a normal would, but I'm not sure on how to do this safely.. ``` const char *GetString() { std::stringstream ss; ss << "The random number is: " << rand(); return ss.str().c_str(); } ``` could the c string be destroyed when ss falls off the stack? I'm assuming so... Another option may be to create a new string on the heap, but what is going to deallocate that? ``` const char *GetString() { std::stringstream ss; ss << "The random number is: " << rand(); char *out = new char[ss.str().size()]; strcpy(ss.str().c_str(), out); return out;//is out ever deleted? } ``` The same goes for pointers to other things as well as strings.
The first variant doesn't work because you're returning a pointer into a stack object, which will get destroyed. (More presisely, you return a pointer to a heap memory, whch will have been deleted().) Worse still, it may even work for some time, if nobody's overwriting the memory, making it very hard to debug. Next, you can not return a const char\* unless you return a pointer to a static string like this: ``` const char *GetString() { return "a static string in DATA segment - no need to delete"; } ``` You second variant has the problem of returning memory allocated with new() into a C program that will call free(). Those may not be compatible. If you return a string to C, there are 2 way to do that: ``` char *GetString() { std::stringstream ss; ss << "The random number is: " << rand(); return strdup( ss.str().c_str() ); // allocated in C style with malloc() } void foo() { char *p = GetString(); printf("string: %s", p)); free( p ); // must not forget to free(), must not use delete() } ``` or: ``` char *GetString(char *buffer, size_t len) { std::stringstream ss; ss << "The random number is: " << rand(); return strncpy(buffer, ss.str().c_str(), len); // caller allocates memory } void foo() { char buffer[ 100 ]; printf("string: %s", GetString(buffer, sizeof( buffer ))); // no memory leaks } ``` depending on you memory handling policy. As a rule, you can NOT ever return a pointer or a reference to an automatic object in C++. This is one of common mistakes analyzed in many C++ books.
283,300
<p>I have a django project pro1 with several apps: app1, app2, app3 and so on. I want to display some top level template that contains blocks from each and every app:</p> <p>example_base_template.html:</p> <pre><code>[header /] [left nav bar]{{ app1 rendered template }}[/left nav bar] [right nav bar]{{ app2 rendered template }}[/right nav bar] [center section]{{ app1 main functionality template }}[/center section] [footer]{{ app3 rendered template }}{{ app4 rendered template }}[/footer] </code></pre> <p>All those app templates are dynamic, that use DB. How to do that in the most proper and elegant way? Or maybe the question is how to connect 4 different views to one URL?</p>
[ { "answer_id": 284870, "author": "Alex Koshelev", "author_id": 19772, "author_profile": "https://Stackoverflow.com/users/19772", "pm_score": 2, "selected": false, "text": "<p>You can use a <a href=\"http://docs.djangoproject.com/en/dev/ref/templates/builtins/#include\" rel=\"nofollow noreferrer\">{% include %}</a> tag. But It doesn't help you a lot. The better solution is to write custom <a href=\"http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#inclusion-tags\" rel=\"nofollow noreferrer\">inclusion tag</a> with needed template and functionality.</p>\n\n<p>You cannot (in simple way) mix several views into one. Try tags its pretty django solution.</p>\n" }, { "answer_id": 284900, "author": "Peter Rowell", "author_id": 17017, "author_profile": "https://Stackoverflow.com/users/17017", "pm_score": 2, "selected": true, "text": "<p>We had a problem similar to this and the key is getting the correct data into the Context. What we did was breakout the data creation/Context filling for each view into a separate build-the-context routine. The original views just call their respective routine and then render their template. The composite view calls each of the context-builders and then renders the master template, which then includes the sub-templates.</p>\n\n<p>This is where we ran into a bit of a problem with the Django templating system. We were caching template fragments and some of these fragments took data that was very expensive to generate. If the fragment was not stale, we definitely did not want to do the work. But delaying the work until we knew we needed it meant we were now in the template and:</p>\n\n<ul>\n<li>You can't pass parameters to methods from within a template.</li>\n<li>The django.template.__init__.Variable._resolve_lookup() method was broken in that if you passed a callable, it wouldn't call it! If you reference a method of an object in the context, that works just fine.</li>\n</ul>\n\n<p>The reason for needing callables to work is that it permits you to pass in a curried function -- i.e. a function that already has some (or all) of its parameters specified, but <em>which has not yet been called.</em> So the view (or the context build in the case) should be able to curry a full-specified function (remember, you can't pass params in the templates themselves) so that the template <em>when it needed to</em> could invoke the callable, get the data, and away we go.</p>\n\n<p>We took two separate approaches to this:</p>\n\n<ul>\n<li>We used the <a href=\"http://www.djangosnippets.org/snippets/9/\" rel=\"nofollow noreferrer\">expr template tag from djangosnippets.org</a></li>\n<li>We hacked the django template code to make callables work (I used a submitted but not yet handled patch).</li>\n</ul>\n\n<p>Since we did this site I have learned that we might have been able to solve it by using generators as delayed data producers. The generators act sort of like a curried function (in that you can pass arbitrary params for the setup), but the template engine sees them as just another iterator. There is a <a href=\"http://www.dabeaz.com/generators-uk/\" rel=\"nofollow noreferrer\">great tutorial</a> on this subject. Note: generators are not arrays and you can only consume them once, so some of your logic may need to be tweaked.</p>\n\n<p>Next time I think we'll just go with <a href=\"http://jinja.pocoo.org/2/\" rel=\"nofollow noreferrer\">jinja2 templates</a> and stop screwing with Django's templates.</p>\n" }, { "answer_id": 284940, "author": "Sam Corder", "author_id": 2351, "author_profile": "https://Stackoverflow.com/users/2351", "pm_score": 1, "selected": false, "text": "<p>I did this by writing custom template tags for each application I wanted to include. At first my template tags just passed back hard coded html. Later I found that the tags could load their own template fragments. There was also a snippet somewhere that was a generic latest content tag that worked pretty well.</p>\n" }, { "answer_id": 406732, "author": "akaihola", "author_id": 15770, "author_profile": "https://Stackoverflow.com/users/15770", "pm_score": 0, "selected": false, "text": "<p>Many reusable apps (esp. those selected into the <a href=\"http://pinaxproject.com/\" rel=\"nofollow noreferrer\">Pinax</a> project) serve as great examples on how to use custom template tags to insert content. James Bennett's <a href=\"http://www.youtube.com/watch?v=A-S0tqpPga4\" rel=\"nofollow noreferrer\">talk</a> in DjangoCon 2008 may also help.</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36832/" ]
I have a django project pro1 with several apps: app1, app2, app3 and so on. I want to display some top level template that contains blocks from each and every app: example\_base\_template.html: ``` [header /] [left nav bar]{{ app1 rendered template }}[/left nav bar] [right nav bar]{{ app2 rendered template }}[/right nav bar] [center section]{{ app1 main functionality template }}[/center section] [footer]{{ app3 rendered template }}{{ app4 rendered template }}[/footer] ``` All those app templates are dynamic, that use DB. How to do that in the most proper and elegant way? Or maybe the question is how to connect 4 different views to one URL?
We had a problem similar to this and the key is getting the correct data into the Context. What we did was breakout the data creation/Context filling for each view into a separate build-the-context routine. The original views just call their respective routine and then render their template. The composite view calls each of the context-builders and then renders the master template, which then includes the sub-templates. This is where we ran into a bit of a problem with the Django templating system. We were caching template fragments and some of these fragments took data that was very expensive to generate. If the fragment was not stale, we definitely did not want to do the work. But delaying the work until we knew we needed it meant we were now in the template and: * You can't pass parameters to methods from within a template. * The django.template.\_\_init\_\_.Variable.\_resolve\_lookup() method was broken in that if you passed a callable, it wouldn't call it! If you reference a method of an object in the context, that works just fine. The reason for needing callables to work is that it permits you to pass in a curried function -- i.e. a function that already has some (or all) of its parameters specified, but *which has not yet been called.* So the view (or the context build in the case) should be able to curry a full-specified function (remember, you can't pass params in the templates themselves) so that the template *when it needed to* could invoke the callable, get the data, and away we go. We took two separate approaches to this: * We used the [expr template tag from djangosnippets.org](http://www.djangosnippets.org/snippets/9/) * We hacked the django template code to make callables work (I used a submitted but not yet handled patch). Since we did this site I have learned that we might have been able to solve it by using generators as delayed data producers. The generators act sort of like a curried function (in that you can pass arbitrary params for the setup), but the template engine sees them as just another iterator. There is a [great tutorial](http://www.dabeaz.com/generators-uk/) on this subject. Note: generators are not arrays and you can only consume them once, so some of your logic may need to be tweaked. Next time I think we'll just go with [jinja2 templates](http://jinja.pocoo.org/2/) and stop screwing with Django's templates.
283,316
<p>I'm having a problem where a jQuery setting against an .html() property on a selected element is returning the error 'nodeName' is null or not an object. This only occurs on IE6 and IE7, but not FF2, FF3, Opera (latest Nov 12,2008) or Safari (again, latest).</p>
[ { "answer_id": 283328, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I resolved the problem. The example looks like this:</p>\n\n<p>$('#section #detail .data').html(data);</p>\n\n<p>...where data is HTML returned from an AJAX call, and this bug only occurs on IE6 and IE7 on the second attempt AJAX call, not the first. It's inexplicable. The error returned is:</p>\n\n<pre><code>'nodeName' is null or not an object\n</code></pre>\n\n<p>The fix is to simply clear the variable first before setting:</p>\n\n<p>$('#section #detail .data').html('');\n$('#section #detail .data').html(data);</p>\n\n<p>And then IE6 and IE7 started working again with it.</p>\n\n<p>BTW, I had to install Visual Web Developer 2008 Express Edition to get a debugger working in IE7. That info is <a href=\"http://www.berniecode.com/blog/2007/03/08/how-to-debug-javascript-with-visual-web-developer-express/\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 283334, "author": "The Archetypal Paul", "author_id": 21755, "author_profile": "https://Stackoverflow.com/users/21755", "pm_score": 0, "selected": false, "text": "<p>I don't know if it's connected, but we've had what sounds like a similar issue where the DOM doesn't have the children/text of a element that we know exist (because we see them rendered on the screen!)</p>\n\n<p>Selecting something else, then selecting the elememt again seemed to fix the issue - suddenly, the children appear. So what happens if you select you element, select something else, select your element again?</p>\n" }, { "answer_id": 283340, "author": "Rob", "author_id": 34224, "author_profile": "https://Stackoverflow.com/users/34224", "pm_score": 0, "selected": false, "text": "<p>Do you have any idea what kinds of nodes you might be running up against? Or, are you running in IE quirks mode? There might be some kinds of nodes such as #text that don't show up correctly in the DOM in quirks mode.</p>\n\n<pre><code>&lt;!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;</code></pre>\n" }, { "answer_id": 5487368, "author": "Oscar", "author_id": 660432, "author_profile": "https://Stackoverflow.com/users/660432", "pm_score": 2, "selected": false, "text": "<p>It looks to me like a bug in JQuery. The exception is thrown at line 605 in 1.5.1:</p>\n\n<pre><code>nodeName: function( elem, name ) {\n return elem.nodeName &amp;&amp; elem.nodeName.toUpperCase() === name.toUpperCase();\n},\n</code></pre>\n\n<p>The function returns true if the nodeName of object <code>elem</code> is identical to the String <code>name</code>. If not, or if there is no nodeName at <code>elem</code>, we return false. However, <code>elem</code> is not tested before it is used. So if <code>elem</code> is null, the invocation of its <code>.nodeName</code> member throws a null pointer exception.</p>\n\n<p>A simple fix is to include <code>elem</code> at the beginning of the short-circuit <strong>AND</strong> clause:</p>\n\n<pre><code>return elem &amp;&amp; elem.nodeName &amp;&amp; elem.nodeName.toUpperCase()...\n</code></pre>\n\n<p>Now if <code>elem</code> is null, the function will return false at the first test in the clause and never try to invoke <code>elem.nodeName</code>, thus avoiding the NPE.</p>\n\n<p>I didn't check them all (it's used a lot), but in many cases where this function is used, <code>elem</code> <strong>is</strong> tested before the function call. But not in all cases, apparently.</p>\n" }, { "answer_id": 9820685, "author": "Mohd Farid", "author_id": 229609, "author_profile": "https://Stackoverflow.com/users/229609", "pm_score": 1, "selected": false, "text": "<p>For me it was happening on IE when I was trying to select an element that did not existed. I was trying to get its index amongst its siblings which was returned as -1. Then I tried showing this element by getting it by index from its parent.It resulted in this error.</p>\n\n<p>Thus, I put a check whether the index is not equal to -1. This solved the issue for me.</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283316", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm having a problem where a jQuery setting against an .html() property on a selected element is returning the error 'nodeName' is null or not an object. This only occurs on IE6 and IE7, but not FF2, FF3, Opera (latest Nov 12,2008) or Safari (again, latest).
I resolved the problem. The example looks like this: $('#section #detail .data').html(data); ...where data is HTML returned from an AJAX call, and this bug only occurs on IE6 and IE7 on the second attempt AJAX call, not the first. It's inexplicable. The error returned is: ``` 'nodeName' is null or not an object ``` The fix is to simply clear the variable first before setting: $('#section #detail .data').html(''); $('#section #detail .data').html(data); And then IE6 and IE7 started working again with it. BTW, I had to install Visual Web Developer 2008 Express Edition to get a debugger working in IE7. That info is [here](http://www.berniecode.com/blog/2007/03/08/how-to-debug-javascript-with-visual-web-developer-express/).
283,348
<p>I'm trying to use the Visitor Pattern and I have as follows:</p> <pre><code>public class EnumerableActions&lt;T&gt; : IEnumerableActions&lt;T&gt; { private IEnumerable&lt;T&gt; itemsToActOn; public EnumerableActions ( IEnumerable&lt;T&gt; itemsToActOn ) { this.itemsToActOn = itemsToActOn; } public void VisitAllItemsUsing ( IVisitor&lt;T&gt; visitor ) { foreach (T t in itemsToActOn) { visitor.Visit ( t );// after this, the item is unaffected. } } </code></pre> <p>The visitor :</p> <pre><code>internal class TagMatchVisitor : IVisitor&lt;Tag&gt; { private readonly IList&lt;Tag&gt; _existingTags; public TagMatchVisitor ( IList&lt;Tag&gt; existingTags ) { _existingTags = existingTags; } #region Implementation of IVisitor&lt;Tag&gt; public void Visit ( Tag newItem ) { Tag foundTag = _existingTags.FirstOrDefault(tg =&gt; tg.TagName.Equals(newItem.TagName, StringComparison.OrdinalIgnoreCase)); if (foundTag != null) newItem = foundTag; // replace the existing item with this one. } #endregion } </code></pre> <p>And where I'm calling the visitor :</p> <pre><code>IList&lt;Tag&gt; tags = ..get the list; tags.VisitAllItemsUsing(new TagMatchVisitor(existingTags)); </code></pre> <p>So .. where am I losing the reference ? after newItem = foundTag - I expect that in the foreach in the visitor I would have the new value - obviously that's not happening.</p> <p><strong>Edit</strong> I think I found the answer - in a foreach the variable is readonly.</p> <p><a href="http://discuss.joelonsoftware.com/default.asp?dotnet.12.521767.19" rel="nofollow noreferrer">http://discuss.joelonsoftware.com/default.asp?dotnet.12.521767.19</a></p>
[ { "answer_id": 283359, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": true, "text": "<p>For that to work, firstly \"newItem\" would have to be \"ref\". Secondly, you'd need to do something with the updated value after the delegate invoke (an enumerator doesn't offer any ability to update contents). But most updates to collections will break enumerators anyway!</p>\n\n<p>Your replacing \"newItem\" will not be visible to the client otherwise. However, changes to <em>properties</em> of the tag (assuming it is a reference type and mutable) will be.</p>\n\n<p>For this to work, itemsToActOn would have to be <code>IList&lt;T&gt;</code> - then you could use:</p>\n\n<pre><code>for(int i = 0 ; i &lt; itemsToActOn.Count ; i++)\n{\n T value = itemsToActOn[i];\n visitor.Visit(ref t)\n itemsToActOn[i] = value;\n}\n</code></pre>\n\n<p>Or if you could use <code>T Visit(T)</code></p>\n\n<pre><code>for(int i = 0 ; i &lt; itemsToActOn.Count ; i++)\n{\n itemsToActOn[i] = visitor.Visit(itemsToActOn[i]);\n}\n</code></pre>\n" }, { "answer_id": 283376, "author": "sirrocco", "author_id": 5246, "author_profile": "https://Stackoverflow.com/users/5246", "pm_score": 0, "selected": false, "text": "<p>Yes, you're right - but I'm using an IEnumerable in that place so can't really do a for on it. </p>\n\n<p>However I guess it's more correct to return a new list instead of affecting the current one. So I'm using a ValueReturningVisitor - inspired(taken?:) ) from Jean-Paul S. Boodhoo. </p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283348", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5246/" ]
I'm trying to use the Visitor Pattern and I have as follows: ``` public class EnumerableActions<T> : IEnumerableActions<T> { private IEnumerable<T> itemsToActOn; public EnumerableActions ( IEnumerable<T> itemsToActOn ) { this.itemsToActOn = itemsToActOn; } public void VisitAllItemsUsing ( IVisitor<T> visitor ) { foreach (T t in itemsToActOn) { visitor.Visit ( t );// after this, the item is unaffected. } } ``` The visitor : ``` internal class TagMatchVisitor : IVisitor<Tag> { private readonly IList<Tag> _existingTags; public TagMatchVisitor ( IList<Tag> existingTags ) { _existingTags = existingTags; } #region Implementation of IVisitor<Tag> public void Visit ( Tag newItem ) { Tag foundTag = _existingTags.FirstOrDefault(tg => tg.TagName.Equals(newItem.TagName, StringComparison.OrdinalIgnoreCase)); if (foundTag != null) newItem = foundTag; // replace the existing item with this one. } #endregion } ``` And where I'm calling the visitor : ``` IList<Tag> tags = ..get the list; tags.VisitAllItemsUsing(new TagMatchVisitor(existingTags)); ``` So .. where am I losing the reference ? after newItem = foundTag - I expect that in the foreach in the visitor I would have the new value - obviously that's not happening. **Edit** I think I found the answer - in a foreach the variable is readonly. <http://discuss.joelonsoftware.com/default.asp?dotnet.12.521767.19>
For that to work, firstly "newItem" would have to be "ref". Secondly, you'd need to do something with the updated value after the delegate invoke (an enumerator doesn't offer any ability to update contents). But most updates to collections will break enumerators anyway! Your replacing "newItem" will not be visible to the client otherwise. However, changes to *properties* of the tag (assuming it is a reference type and mutable) will be. For this to work, itemsToActOn would have to be `IList<T>` - then you could use: ``` for(int i = 0 ; i < itemsToActOn.Count ; i++) { T value = itemsToActOn[i]; visitor.Visit(ref t) itemsToActOn[i] = value; } ``` Or if you could use `T Visit(T)` ``` for(int i = 0 ; i < itemsToActOn.Count ; i++) { itemsToActOn[i] = visitor.Visit(itemsToActOn[i]); } ```
283,350
<p>In Erlang, every process has a group leader, and when a process wants to print something (i.e. it calls the io library or does something similar), it will send a message to its group leader.</p> <p>My question is, where can I find the specification of these messages? Or in general, the specification of what a group leader should do?</p> <p>I managed to find out with some experimenting that sometimes the process sends an <code>{io_request, Sender, GroupLeader, Request}</code> term, and the answer is an <code>{io_reply, GroupLeader, ok}</code> term, but there may be other cases.</p>
[ { "answer_id": 296496, "author": "archaelus", "author_id": 9040, "author_profile": "https://Stackoverflow.com/users/9040", "pm_score": 4, "selected": true, "text": "<p><a href=\"https://erlangcentral.org/erlang-rationale-2/\" rel=\"nofollow noreferrer\">The Erlang Rationale (video)</a> or <a href=\"http://www.erlang-factory.com/upload/presentations/329/EFKR10-ErlangRationale.pdf\" rel=\"nofollow noreferrer\">(slides)</a>; is a good source of information, as is the source code for <a href=\"http://github.com/mfoemmel/erlang-otp/tree/master/lib/kernel/src/user.erl#L182\" rel=\"nofollow noreferrer\">user.erl</a>.</p>\n\n<p>In short:</p>\n\n<pre><code> {io_request, From, ReplyAs, Request}\n %From is the process to send the reply to, \n %ReplyAs is any term the caller desires to \n %match up the request and the response. (returned verbatim in the reply)\n {io_reply, ReplyAs, Reply}\n</code></pre>\n\n<p>Some requests in user.erl:</p>\n\n<pre><code> {put_chars, IoList} % puts the iolist\n {put_chars, M,F,A} % puts the result of apply(M,F,A)\n {get_geometry, 'rows' | 'columns'} % returns the number of rows or columns of the console\n {get_line, Prompt} % calls io_lib:collect_line(Prompt)\n {get_chars, Prompt, Mod, Func, ExtraArgs} \n {get_until, Prompt, Mod, Func, Args}\n {setopts, Options} % only option supported by user is 'binary' \n % (binary mode if present in Options, list mode otherwise)\n</code></pre>\n" }, { "answer_id": 19479510, "author": "luksan", "author_id": 166131, "author_profile": "https://Stackoverflow.com/users/166131", "pm_score": 1, "selected": false, "text": "<p>The Erlang I/O protocol is described in detail here:</p>\n\n<p><a href=\"http://www.erlang.org/doc/apps/stdlib/io_protocol.html\" rel=\"nofollow\">http://www.erlang.org/doc/apps/stdlib/io_protocol.html</a></p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17916/" ]
In Erlang, every process has a group leader, and when a process wants to print something (i.e. it calls the io library or does something similar), it will send a message to its group leader. My question is, where can I find the specification of these messages? Or in general, the specification of what a group leader should do? I managed to find out with some experimenting that sometimes the process sends an `{io_request, Sender, GroupLeader, Request}` term, and the answer is an `{io_reply, GroupLeader, ok}` term, but there may be other cases.
[The Erlang Rationale (video)](https://erlangcentral.org/erlang-rationale-2/) or [(slides)](http://www.erlang-factory.com/upload/presentations/329/EFKR10-ErlangRationale.pdf); is a good source of information, as is the source code for [user.erl](http://github.com/mfoemmel/erlang-otp/tree/master/lib/kernel/src/user.erl#L182). In short: ``` {io_request, From, ReplyAs, Request} %From is the process to send the reply to, %ReplyAs is any term the caller desires to %match up the request and the response. (returned verbatim in the reply) {io_reply, ReplyAs, Reply} ``` Some requests in user.erl: ``` {put_chars, IoList} % puts the iolist {put_chars, M,F,A} % puts the result of apply(M,F,A) {get_geometry, 'rows' | 'columns'} % returns the number of rows or columns of the console {get_line, Prompt} % calls io_lib:collect_line(Prompt) {get_chars, Prompt, Mod, Func, ExtraArgs} {get_until, Prompt, Mod, Func, Args} {setopts, Options} % only option supported by user is 'binary' % (binary mode if present in Options, list mode otherwise) ```
283,374
<p>To recap for those .NET gurus who might not know the Java API:</p> <p><a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/ConcurrentHashMap.html" rel="nofollow noreferrer">ConcurrentHashMap</a> in Java has atomic methods (i.e. require no external locking) for common Map modification operations such as:</p> <pre><code>putIfAbsent(K key, V value) remove(Object key, Object value) replace(K key, V value) </code></pre> <p>It also allows iteration over the keyset without locking (it takes a copy at the start of iteration) and <code>get()</code> operations can generally be interleaved with calls to <code>put()</code> without blocking (it uses fine grained lock striping <a href="http://en.wiktionary.org/wiki/IIRC" rel="nofollow noreferrer">IIRC</a>).</p> <p>Anyway, my question is: <strong>does .NET have an equivalent Dictionary implementation?</strong></p> <p>I guess more generally, I'd be keen to know if .NET has a more general set of thread safe collection libraries. Or concurrency utilities in general - equivalent to <a href="http://en.wikipedia.org/wiki/Doug_Lea" rel="nofollow noreferrer">Doug Lea</a>'s <code>java.util.concurrent</code> libraries.</p>
[ { "answer_id": 283400, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 2, "selected": false, "text": "<p>EDIT: This was written prior to .NET 4 being released, when obviously there's <code>ConcurrentDictionary</code>. I'm leaving it here as a reference for those needing .NET 3.5.</p>\n\n<p>I don't know of any equivalent to <code>ConcurrentHashMap</code>.</p>\n\n<p>In terms of general concurrency utilities - .NET has always provided a bit more than the basics which Java used to provide, in terms of <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.mutex.aspx\" rel=\"nofollow noreferrer\"><code>Mutex</code></a>, <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.manualresetevent.aspx\" rel=\"nofollow noreferrer\"><code>ManualResetEvent</code></a>, <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.autoresetevent.aspx\" rel=\"nofollow noreferrer\"><code>AutoResetEvent</code></a> and <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.readerwriterlock.aspx\" rel=\"nofollow noreferrer\"><code>ReaderWriterLock</code></a>; then more recently (.NET 2.0) <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.semaphore.aspx\" rel=\"nofollow noreferrer\"><code>Semaphore</code></a> and (.NET 3.5) <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.readerwriterlockslim.aspx\" rel=\"nofollow noreferrer\"><code>ReaderWriterLockSlim</code></a> - as well as the process-wide thread pool, of course.</p>\n\n<p>A bigger shake-up will come in .NET 4.0 when Parallel Extensions arrives - that should make concurrency <em>much</em> simpler. Likewise the <a href=\"http://channel9.msdn.com/pdc2008/TL55/\" rel=\"nofollow noreferrer\">Coordination and Concurrency Runtime</a> is finally breaking free of the shackles of the Microsoft Robotics Studio, although I'm not clear on exactly where it's headed (whether it'll be part of .NET itself, or a separate library).</p>\n" }, { "answer_id": 283415, "author": "Maxam", "author_id": 15310, "author_profile": "https://Stackoverflow.com/users/15310", "pm_score": 3, "selected": true, "text": "<p>Not that I know of. The closest thing to what you're looking for would probably be the Synchronized method of the Hashtable, which returns a (sort of) thread-safe wrapper around the hashtable. It's only thread-safe for multiple writers or multiple readers, though. If I recall correctly, a mixture of writers and readers will not be thread-safe.</p>\n" }, { "answer_id": 283441, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "<p>Personally, I find that having individual methods as synchronized generally isn't as useful as it sounds.</p>\n\n<p>Commonly, you might want to do a related \"get\" and \"put\" in close succession, and if another thread is looking at the same values you have an immediate thread race. Likewise (depending on the scenario) you don't <em>want</em> somebody reading values that you are working on.</p>\n\n<p>For a broad approach, simply using an external <code>Monitor</code> (<code>lock(...)</code> can work well for many situations. It is simple, light-weight, and unless you are under <strong>heavy</strong> thread load, more than adequate.</p>\n\n<p>For more complex scenarios, things like <code>ReaderWriterLockSlim</code> etc are more flexible. But I'd start simple, and only change things if profiling shows there is a genuine contention issue.</p>\n\n<p>As Jon notes, with Parallel Extension comes a a whole new slew of high performance synchronization devices; from what I can see (for example <a href=\"http://www.betanews.com/article/Everyone_talk_at_once_NET_40_will_include_Parallel_Extensions/1223931673\" rel=\"nofollow noreferrer\">here</a>, <a href=\"http://blogs.msdn.com/pfxteam/archive/2008/10/10/8994927.aspx\" rel=\"nofollow noreferrer\">here</a> and <a href=\"http://msdn.microsoft.com/en-us/magazine/cc817396.aspx\" rel=\"nofollow noreferrer\">here</a>), this is part of .NET 4.0</p>\n" }, { "answer_id": 1993061, "author": "Olmo", "author_id": 38670, "author_profile": "https://Stackoverflow.com/users/38670", "pm_score": 4, "selected": false, "text": "<p>The incoming .Net 4.0 has a <a href=\"http://msdn.microsoft.com/en-us/library/dd287191(VS.100).aspx\" rel=\"noreferrer\">ConcurrentDictionary</a> class, it has a convenient <a href=\"http://msdn.microsoft.com/en-us/library/ee378677(VS.100).aspx\" rel=\"noreferrer\">GetOrAdd</a> method.</p>\n\n<pre><code>public TValue GetOrAdd(\n TKey key,\n Func&lt;TKey, TValue&gt; valueFactory\n)\n</code></pre>\n\n<p>Very useful for global server caches. </p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283374", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1853/" ]
To recap for those .NET gurus who might not know the Java API: [ConcurrentHashMap](http://java.sun.com/javase/6/docs/api/java/util/concurrent/ConcurrentHashMap.html) in Java has atomic methods (i.e. require no external locking) for common Map modification operations such as: ``` putIfAbsent(K key, V value) remove(Object key, Object value) replace(K key, V value) ``` It also allows iteration over the keyset without locking (it takes a copy at the start of iteration) and `get()` operations can generally be interleaved with calls to `put()` without blocking (it uses fine grained lock striping [IIRC](http://en.wiktionary.org/wiki/IIRC)). Anyway, my question is: **does .NET have an equivalent Dictionary implementation?** I guess more generally, I'd be keen to know if .NET has a more general set of thread safe collection libraries. Or concurrency utilities in general - equivalent to [Doug Lea](http://en.wikipedia.org/wiki/Doug_Lea)'s `java.util.concurrent` libraries.
Not that I know of. The closest thing to what you're looking for would probably be the Synchronized method of the Hashtable, which returns a (sort of) thread-safe wrapper around the hashtable. It's only thread-safe for multiple writers or multiple readers, though. If I recall correctly, a mixture of writers and readers will not be thread-safe.
283,377
<p>Consider the following signature in C#:</p> <pre><code>double Divide(int numerator, int denominator); </code></pre> <p>Is there a performance difference between the following implementations?</p> <pre><code>return (double)numerator / denominator; return numerator / (double)denominator; return (double)numerator / (double)denominator; </code></pre> <p>I'm assuming that both of the above return the same answer.</p> <p>Have I missed any other equivalent solution?</p>
[ { "answer_id": 283386, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 4, "selected": true, "text": "<p>Have you tried comparing the IL (for example, with <a href=\"http://www.red-gate.com/products/reflector/\" rel=\"nofollow noreferrer\">Reflector</a>)?</p>\n\n<pre><code>static double A(int numerator, int denominator)\n{ return (double)numerator / denominator; }\n\nstatic double B(int numerator, int denominator)\n{ return numerator / (double)denominator; }\n\nstatic double C(int numerator, int denominator)\n{ return (double)numerator / (double)denominator; }\n</code></pre>\n\n<p>All three become (give or take the name):</p>\n\n<pre><code>.method private hidebysig static float64 A(int32 numerator, int32 denominator) cil managed\n{\n .maxstack 8\n L_0000: ldarg.0 // pushes numerator onto the stack\n L_0001: conv.r8 // converts the value at the top of the stack to double\n L_0002: ldarg.1 // pushes denominator onto the stack\n L_0003: conv.r8 // converts the value at the top of the stack to double\n L_0004: div // pops two values, divides, and pushes the result\n L_0005: ret // pops the value from the top of the stack as the return value\n}\n</code></pre>\n\n<p>So no: there is exactly zero difference.</p>\n" }, { "answer_id": 283393, "author": "Maxam", "author_id": 15310, "author_profile": "https://Stackoverflow.com/users/15310", "pm_score": 1, "selected": false, "text": "<p>Even if you use VB.NET, both numerator and denominator are converted to doubles before doing the actual division, so your examples are the same.</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24874/" ]
Consider the following signature in C#: ``` double Divide(int numerator, int denominator); ``` Is there a performance difference between the following implementations? ``` return (double)numerator / denominator; return numerator / (double)denominator; return (double)numerator / (double)denominator; ``` I'm assuming that both of the above return the same answer. Have I missed any other equivalent solution?
Have you tried comparing the IL (for example, with [Reflector](http://www.red-gate.com/products/reflector/))? ``` static double A(int numerator, int denominator) { return (double)numerator / denominator; } static double B(int numerator, int denominator) { return numerator / (double)denominator; } static double C(int numerator, int denominator) { return (double)numerator / (double)denominator; } ``` All three become (give or take the name): ``` .method private hidebysig static float64 A(int32 numerator, int32 denominator) cil managed { .maxstack 8 L_0000: ldarg.0 // pushes numerator onto the stack L_0001: conv.r8 // converts the value at the top of the stack to double L_0002: ldarg.1 // pushes denominator onto the stack L_0003: conv.r8 // converts the value at the top of the stack to double L_0004: div // pops two values, divides, and pushes the result L_0005: ret // pops the value from the top of the stack as the return value } ``` So no: there is exactly zero difference.
283,392
<p>At the moment I have a set of divs, generated dynamically by php and all having their ids starting with 'itembox', with a count number appended. I have a droppable garbage bin area on the page so that the user can delete an individual itembox by fdragging and dropping on to the bin.</p> <p>My problem is that the droppable won't seem to activate when I drag the original, while it will function (perfectly) when I have helper: 'clone' set. Unfortunately, though, when dragging, the cloning function takes its clone from the first iteration of the itembox, no matter which itembox is actually dragged.</p> <p>So I'm looking for a solution to either make the droppable accept an original or force the cloning function to take its clone from the itembox actually dragged.</p>
[ { "answer_id": 283978, "author": "Tamas Czinege", "author_id": 8954, "author_profile": "https://Stackoverflow.com/users/8954", "pm_score": 2, "selected": true, "text": "<p>I guess the problem must lie in the accept option of your droppable initializer. Just try the following:</p>\n\n<pre><code>$('#mydroppable').droppable(\n{\n accept: function() { return true; },\n drop: function () { alert(\"Dropped!\"); }\n});\n</code></pre>\n\n<p>Now this will accept everything, so you should probably implement some filtering in the accept function but none the less this should work.</p>\n" }, { "answer_id": 8167529, "author": "Wikki", "author_id": 460966, "author_profile": "https://Stackoverflow.com/users/460966", "pm_score": 0, "selected": false, "text": "<p>You can also try the below solution.</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\n$(document).ready(function(){\n $('.srcfield').draggable({\n revert: true \n });\n\n $('#trash').droppable({\n accept : \".srcfield\",\n over: function(){\n $(this).removeClass('out').addClass('over');\n },`enter code here`\n out: function(){\n $(this).removeClass('over').addClass('out');\n },\n drop: function(ev, ui){\n //var answer = confirm('Delete this item?');\n var theTitle = $(ui.draggable).attr(\"title\");\n $(this).html(\"&lt;u&gt;\"+theTitle+\"&lt;/u&gt;&lt;br/&gt; is deleted!\");\n }\n });\n});\n&lt;/script&gt;\n\n\n&lt;body&gt;\n &lt;div id=\"trash\" class=\"out\"&gt;\n &lt;span&gt;Trash&lt;/span&gt;\n &lt;/div&gt;\n &lt;div id=\"sourcefields\"&gt;\n &lt;div class=\"srcfield\" title=\"First Name\"&gt;&lt;span&gt;First Name&lt;/span&gt;&lt;/div&gt;\n &lt;div class=\"srcfield\" title=\"Last Name\"&gt;&lt;span&gt;Last Name&lt;/span&gt;&lt;/div&gt;\n &lt;div class=\"srcfield\" title=\"Age\"&gt;&lt;span&gt;Age&lt;/span&gt;&lt;/div&gt;\n &lt;/div&gt;\n&lt;/body&gt;\n</code></pre>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28527/" ]
At the moment I have a set of divs, generated dynamically by php and all having their ids starting with 'itembox', with a count number appended. I have a droppable garbage bin area on the page so that the user can delete an individual itembox by fdragging and dropping on to the bin. My problem is that the droppable won't seem to activate when I drag the original, while it will function (perfectly) when I have helper: 'clone' set. Unfortunately, though, when dragging, the cloning function takes its clone from the first iteration of the itembox, no matter which itembox is actually dragged. So I'm looking for a solution to either make the droppable accept an original or force the cloning function to take its clone from the itembox actually dragged.
I guess the problem must lie in the accept option of your droppable initializer. Just try the following: ``` $('#mydroppable').droppable( { accept: function() { return true; }, drop: function () { alert("Dropped!"); } }); ``` Now this will accept everything, so you should probably implement some filtering in the accept function but none the less this should work.
283,417
<p>I have a toolstrip containing, among other things, a ToolStripComboBox and a ToolStripButton. I want to add a ContextMenuStrip to both of them, but I don't have direct access to the toolstrip or its other contents, so I can't set the context menu of the toolstrip.</p> <p>Setting the ContextMenuStrip for the ToolStripComboBox is easy:</p> <pre><code>myToolStripComboBox.ComboBox.ContextMenuStrip = myContextMenu; </code></pre> <p>but there's no obvious equivalent for the ToolStripButton. How do I add a ContextMenuStrip to a ToolStripButton?</p>
[ { "answer_id": 283429, "author": "TcKs", "author_id": 20382, "author_profile": "https://Stackoverflow.com/users/20382", "pm_score": 0, "selected": false, "text": "<p>It's because a ToolStripComboBox contains \"System.Windows.Forms.ComboBox\" control, but \"ToolStripButton\" does not contains \"System.Windows.Forms.Control\". Its special toolstrip item, which's button is maintained by toolstip.</p>\n\n<p>You should use ContextMenu on toolstip or you can add dropdown to toolstripbutton item.</p>\n" }, { "answer_id": 314954, "author": "Jeff Yates", "author_id": 23234, "author_profile": "https://Stackoverflow.com/users/23234", "pm_score": 2, "selected": false, "text": "<p>You will need to set the context menu to the ToolStrip and then handle the Popup of the context menu or a related event and hit test which button the mouse is over to determine if you should show the ToolStrip's context menu and what it should contain.</p>\n" }, { "answer_id": 354468, "author": "AlexeyMK", "author_id": 5021, "author_profile": "https://Stackoverflow.com/users/5021", "pm_score": 0, "selected": false, "text": "<p>Good question. You might be able to get access to the parent <code>toolstrip</code> (<code>myToolStripButton.Parent</code> or something similar) and attach the context-menu there.</p>\n" }, { "answer_id": 1774863, "author": "Jason D", "author_id": 215962, "author_profile": "https://Stackoverflow.com/users/215962", "pm_score": 3, "selected": true, "text": "<p>What Jeff Yates has suggested should work. </p>\n\n<p>However, another alternative is to create your own derived classes (MyToolSTripButton, MyToolStripTextBox ...etc) give these items a ContextMenuStrip property that you can set at design time, and have your derived classes detect the right mouse down, or whatever other events will trigger the display of the context menu.</p>\n\n<p>This offloads any of the knowledge needed to only those items interested.</p>\n\n<p>Below is one such example using ToolStripTextBox as the item.</p>\n\n<pre><code>public class MyTextBox : ToolStripTextBox\n{\n ContextMenuStrip _contextMenuStrip;\n\n public ContextMenuStrip ContextMenuStrip\n {\n get { return _contextMenuStrip; }\n set { _contextMenuStrip = value; }\n }\n\n protected override void OnMouseDown(MouseEventArgs e)\n {\n if (e.Button == MouseButtons.Right)\n {\n if (_contextMenuStrip !=null)\n _contextMenuStrip.Show(Parent.PointToScreen(e.Location));\n }\n }\n}\n</code></pre>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283417", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15371/" ]
I have a toolstrip containing, among other things, a ToolStripComboBox and a ToolStripButton. I want to add a ContextMenuStrip to both of them, but I don't have direct access to the toolstrip or its other contents, so I can't set the context menu of the toolstrip. Setting the ContextMenuStrip for the ToolStripComboBox is easy: ``` myToolStripComboBox.ComboBox.ContextMenuStrip = myContextMenu; ``` but there's no obvious equivalent for the ToolStripButton. How do I add a ContextMenuStrip to a ToolStripButton?
What Jeff Yates has suggested should work. However, another alternative is to create your own derived classes (MyToolSTripButton, MyToolStripTextBox ...etc) give these items a ContextMenuStrip property that you can set at design time, and have your derived classes detect the right mouse down, or whatever other events will trigger the display of the context menu. This offloads any of the knowledge needed to only those items interested. Below is one such example using ToolStripTextBox as the item. ``` public class MyTextBox : ToolStripTextBox { ContextMenuStrip _contextMenuStrip; public ContextMenuStrip ContextMenuStrip { get { return _contextMenuStrip; } set { _contextMenuStrip = value; } } protected override void OnMouseDown(MouseEventArgs e) { if (e.Button == MouseButtons.Right) { if (_contextMenuStrip !=null) _contextMenuStrip.Show(Parent.PointToScreen(e.Location)); } } } ```
283,431
<p>My record sheet app has a menu option for creating a new, blank record sheet. When I open a sheet window, I can open new windows without a problem, using subprocess.Popen() to do it.</p> <p>However, under Windows (I haven't tested it on other OSes yet), if I open a new window then use the "open file" dialog to populate the fields with data from a file, I'm no longer able to create new windows. Once it's populated, Windows gives me the </p> <blockquote> <p>'foo.py' is not recognized as an internal or external command, operable program or batch file.</p> </blockquote> <p>I don't understand what would cause Windows to suddenly not recognize the Popen() call. I don't have any code that would affect it in any way that I'm aware of.</p>
[ { "answer_id": 283545, "author": "Ali Afshar", "author_id": 28380, "author_profile": "https://Stackoverflow.com/users/28380", "pm_score": 3, "selected": true, "text": "<p>From the error message, it looks like you need to pass the full path of \"foo.py\" to your Popen call. Normally just having \"foo.py\" will search in your current working directory, but this can be a bit unpredictable on Windows, I have found. Yours seems to be jumping around with the open file dialog.</p>\n\n<p>Secondly, just for good measure, it would seem like you would need to pass foo.py as an argument to python.exe executable, rather than executing foo.py itself. Again, I would specify this by path.</p>\n\n<p>So to be safe, something like:</p>\n\n<pre><code>subprocess.Popen([r'C:\\Python2.5\\python.exe', r'C:\\path\\to\\foo.py'])\n</code></pre>\n" }, { "answer_id": 286436, "author": "crystalattice", "author_id": 18676, "author_profile": "https://Stackoverflow.com/users/18676", "pm_score": 0, "selected": false, "text": "<p>The suggested answer seems to have fixed the problem. I also realized that I needed to use <strong>os.name</strong> to determine which OS is being used, then I can use the correct path format for loading the external Python file.</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283431", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18676/" ]
My record sheet app has a menu option for creating a new, blank record sheet. When I open a sheet window, I can open new windows without a problem, using subprocess.Popen() to do it. However, under Windows (I haven't tested it on other OSes yet), if I open a new window then use the "open file" dialog to populate the fields with data from a file, I'm no longer able to create new windows. Once it's populated, Windows gives me the > > 'foo.py' is not recognized as an internal or external command, operable > program or batch file. > > > I don't understand what would cause Windows to suddenly not recognize the Popen() call. I don't have any code that would affect it in any way that I'm aware of.
From the error message, it looks like you need to pass the full path of "foo.py" to your Popen call. Normally just having "foo.py" will search in your current working directory, but this can be a bit unpredictable on Windows, I have found. Yours seems to be jumping around with the open file dialog. Secondly, just for good measure, it would seem like you would need to pass foo.py as an argument to python.exe executable, rather than executing foo.py itself. Again, I would specify this by path. So to be safe, something like: ``` subprocess.Popen([r'C:\Python2.5\python.exe', r'C:\path\to\foo.py']) ```
283,435
<p>I have been banging my head against a brick wall trying to deploy my MVC app on IIS6 (<a href="https://stackoverflow.com/questions/275920/aspnet-mvc-on-iis-6-wildcard-mapping-the-incoming-request-does-not-match-any-ro">linked question</a>)</p> <p>I have scrapped wildcard mapping for the time being and am trying to get the .mvc extension working. Everything is configured correctly in IIS and the .mvc extension is pointing to the .NET dll for all verb types (unchecked verify if exists option).</p> <p>Each time I make a request, all I get is the .NET 404 page. /Home.mvc and /Home.mvc/Index all return that page.</p> <p>I have not made any changes to the default Web.config and all my routes are configured with extenionless and extension based equivalents.</p> <p>I appreciate how easy this configuration must be (sound) for everyone reading who has got it working but I assure you I am not doing anything different and mine will not work. I even tried deploying it on a different server with IIS6 and the same problems happened there too.</p> <p>Could there be any other reasons why the routing module/handler is completely missing the request and letting it fall through to the standard .NET 404 error? Strange permissions?</p> <p>For the IIS 404 errors, I updated the custom error setting so it called the Default.aspx page in the route of the site. This is the default page from the MVC beta template generated in visual studio, which does the following in the code behind:</p> <pre><code>HttpContext.Current.RewritePath(Request.ApplicationPath); IHttpHandler httpHandler = new MvcHttpHandler(); httpHandler.ProcessRequest(HttpContext.Current); </code></pre> <p>This just then gives me the error from the previous post:</p> <pre><code>[HttpException (0x80004005): The incoming request does not match any route.] System.Web.Routing.UrlRoutingHandler.ProcessRequest(HttpContextBase httpContext) +15589 System.Web.Routing.UrlRoutingHandler.ProcessRequest(HttpContext httpContext) +40 System.Web.Routing.UrlRoutingHandler.System.Web.IHttpHandler.ProcessRequest(HttpContext context) +7 ...... </code></pre>
[ { "answer_id": 283938, "author": "anonymous", "author_id": 36602, "author_profile": "https://Stackoverflow.com/users/36602", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>I have not made any changes to the\n default Web.config and all my routes\n are configured with extenionless and\n extension based equivalents.</p>\n</blockquote>\n\n<p>Whats the order of the extension and extensionless routes?</p>\n\n<p>I would either remove extensionless (since you are using extensions), or make sure it is added after extension routes (due to the first match nature of routing).</p>\n\n<p>Also, check out <a href=\"http://www.asp.net/learn/mvc/tutorial-08-cs.aspx\" rel=\"nofollow noreferrer\">http://www.asp.net/learn/mvc/tutorial-08-cs.aspx</a> and simply double check you have IIS setup right (it sounds like you do).</p>\n" }, { "answer_id": 284705, "author": "Tim Peel", "author_id": 31412, "author_profile": "https://Stackoverflow.com/users/31412", "pm_score": 0, "selected": false, "text": "<p>Thanks huey, been through that post too - everything configured the same.</p>\n\n<p>My extensionless routes are output before the extension ones, purely because I intend to use an ISAPI rewrite module and want any URLs generated from my route table to be clean. They will then be re-written to the extenion based ones.</p>\n\n<p>I don't even care about extensionless URLs though at the moment, would just like to get a version working so I can show the client! I've really enjoyed the MVC stuff up to now but this has taken the shine off things.</p>\n\n<p>Thanks again for your assistance.</p>\n" }, { "answer_id": 285830, "author": "Haacked", "author_id": 598, "author_profile": "https://Stackoverflow.com/users/598", "pm_score": 1, "selected": false, "text": "<p>Try starting with the simplest configuration possible. Change your Route definitions to use .aspx instead of .mvc and see if /home.aspx/index works or not.</p>\n" }, { "answer_id": 285853, "author": "Tim Peel", "author_id": 31412, "author_profile": "https://Stackoverflow.com/users/31412", "pm_score": 3, "selected": true, "text": "<p>My <a href=\"https://stackoverflow.com/questions/275920/aspnet-mvc-on-iis-6-wildcard-mapping-the-incoming-request-does-not-match-any-ro\">original problem</a> has been solved by <a href=\"https://stackoverflow.com/users/36849/oli\">Oli</a> who pointed out that the Global.asax file is needed with the website. I was using NAnt/MSBuild to deploy my release package and the Global.asax file was not included. This file can be ignored in all our .NET 2 projects, and has been with all our NAnt deployment structure, so I didn't spare it a thought.</p>\n\n<p>One to note for the future. Something I didn't spot so all credit to <a href=\"https://stackoverflow.com/users/36849/oli\">Oli</a>. Thanks again!</p>\n" }, { "answer_id": 1788201, "author": "Alex Ilyin", "author_id": 114103, "author_profile": "https://Stackoverflow.com/users/114103", "pm_score": 0, "selected": false, "text": "<p>Url rewriting can help you to solve the problem. I've implemented solution allowing to deploy MVC application at any IIS version even when virtual hosting is used.\n<a href=\"http://www.codeproject.com/KB/aspnet/iis-aspnet-url-rewriting.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/aspnet/iis-aspnet-url-rewriting.aspx</a></p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31412/" ]
I have been banging my head against a brick wall trying to deploy my MVC app on IIS6 ([linked question](https://stackoverflow.com/questions/275920/aspnet-mvc-on-iis-6-wildcard-mapping-the-incoming-request-does-not-match-any-ro)) I have scrapped wildcard mapping for the time being and am trying to get the .mvc extension working. Everything is configured correctly in IIS and the .mvc extension is pointing to the .NET dll for all verb types (unchecked verify if exists option). Each time I make a request, all I get is the .NET 404 page. /Home.mvc and /Home.mvc/Index all return that page. I have not made any changes to the default Web.config and all my routes are configured with extenionless and extension based equivalents. I appreciate how easy this configuration must be (sound) for everyone reading who has got it working but I assure you I am not doing anything different and mine will not work. I even tried deploying it on a different server with IIS6 and the same problems happened there too. Could there be any other reasons why the routing module/handler is completely missing the request and letting it fall through to the standard .NET 404 error? Strange permissions? For the IIS 404 errors, I updated the custom error setting so it called the Default.aspx page in the route of the site. This is the default page from the MVC beta template generated in visual studio, which does the following in the code behind: ``` HttpContext.Current.RewritePath(Request.ApplicationPath); IHttpHandler httpHandler = new MvcHttpHandler(); httpHandler.ProcessRequest(HttpContext.Current); ``` This just then gives me the error from the previous post: ``` [HttpException (0x80004005): The incoming request does not match any route.] System.Web.Routing.UrlRoutingHandler.ProcessRequest(HttpContextBase httpContext) +15589 System.Web.Routing.UrlRoutingHandler.ProcessRequest(HttpContext httpContext) +40 System.Web.Routing.UrlRoutingHandler.System.Web.IHttpHandler.ProcessRequest(HttpContext context) +7 ...... ```
My [original problem](https://stackoverflow.com/questions/275920/aspnet-mvc-on-iis-6-wildcard-mapping-the-incoming-request-does-not-match-any-ro) has been solved by [Oli](https://stackoverflow.com/users/36849/oli) who pointed out that the Global.asax file is needed with the website. I was using NAnt/MSBuild to deploy my release package and the Global.asax file was not included. This file can be ignored in all our .NET 2 projects, and has been with all our NAnt deployment structure, so I didn't spare it a thought. One to note for the future. Something I didn't spot so all credit to [Oli](https://stackoverflow.com/users/36849/oli). Thanks again!
283,447
<p>When my IronPython program gets to the line </p> <pre><code>import wx </code></pre> <p>I get this message:</p> <pre><code>A first chance exception of type 'IronPython.Runtime.Exceptions.PythonImportErrorException' occurred in IronPython.dll Additional information: No module named _core_ </code></pre> <p>although I do have the file wx\_core_.pyd. Also, before attempting the import, I have the lines: </p> <pre><code>sys.path.append('c:\\Python24\\Lib\\site-packages') sys.path.append('c:\\Python24\\Lib\\site-packages\\wx-2.6-msw-unicode') sys.path.append('c:\\Python24\\Lib\\site-packages\\wx-2.6-msw-unicode\\wx') sys.path.append('c:\\Python24\\Lib\\site-packages\\wx-2.6-msw-unicode\\wx\\lib') sys.path.append('c:\\Python24\\Lib\\site-packages\\wx-2.6-msw-unicode\\wxpython\\lib') sys.path.append('c:\\Python24\\Lib\\site-packages\\wxaddons') </code></pre> <p>which I hoped would let IronPython find everything it needed. </p>
[ { "answer_id": 283520, "author": "Ali Afshar", "author_id": 28380, "author_profile": "https://Stackoverflow.com/users/28380", "pm_score": 4, "selected": true, "text": "<p>No, this won't work. Wx bindings (like most other \"python bindings\") are actually compiled against CPython.</p>\n\n<p>In this regards they are not just packages on sys.path to be found, as you have tried. They actually depend on CPython itself. <a href=\"http://www.python.org/doc/2.5.2/ext/ext.html\" rel=\"nofollow noreferrer\">This rather dry document explains the process.</a></p>\n\n<p>Note: There was a mission by some of the crew at Resolver Systems to allow you to use CPython bindings with IronPython (called <a href=\"http://code.google.com/p/ironclad/\" rel=\"nofollow noreferrer\">IronClad</a>) but this is in its early stages, and I think they will concentrate on getting things like Numpy working first, GUI toolkits will always be the last, and hardest.</p>\n" }, { "answer_id": 284800, "author": "technomalogical", "author_id": 6173, "author_profile": "https://Stackoverflow.com/users/6173", "pm_score": 3, "selected": false, "text": "<p>While wxPython is unavailable for the reasons listed by @Ali, you may want to take a look at <a href=\"http://wxnet.sourceforge.net/\" rel=\"noreferrer\">wx.NET</a>. You could use IronPython to call these assemblies instead, and it should be cross-platform (I'm assuming that's what you're after, or you would just use WinForms). If all you're looking for is API compatibility, I think you're out of luck :(</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11677/" ]
When my IronPython program gets to the line ``` import wx ``` I get this message: ``` A first chance exception of type 'IronPython.Runtime.Exceptions.PythonImportErrorException' occurred in IronPython.dll Additional information: No module named _core_ ``` although I do have the file wx\\_core\_.pyd. Also, before attempting the import, I have the lines: ``` sys.path.append('c:\\Python24\\Lib\\site-packages') sys.path.append('c:\\Python24\\Lib\\site-packages\\wx-2.6-msw-unicode') sys.path.append('c:\\Python24\\Lib\\site-packages\\wx-2.6-msw-unicode\\wx') sys.path.append('c:\\Python24\\Lib\\site-packages\\wx-2.6-msw-unicode\\wx\\lib') sys.path.append('c:\\Python24\\Lib\\site-packages\\wx-2.6-msw-unicode\\wxpython\\lib') sys.path.append('c:\\Python24\\Lib\\site-packages\\wxaddons') ``` which I hoped would let IronPython find everything it needed.
No, this won't work. Wx bindings (like most other "python bindings") are actually compiled against CPython. In this regards they are not just packages on sys.path to be found, as you have tried. They actually depend on CPython itself. [This rather dry document explains the process.](http://www.python.org/doc/2.5.2/ext/ext.html) Note: There was a mission by some of the crew at Resolver Systems to allow you to use CPython bindings with IronPython (called [IronClad](http://code.google.com/p/ironclad/)) but this is in its early stages, and I think they will concentrate on getting things like Numpy working first, GUI toolkits will always be the last, and hardest.
283,454
<p>I have been working with hibernate/JPA on JBoss for some months now and have one question that I can't find an answer or solution for.</p> <p>It seems like when creating new entity beans I'm not able to do a query before I at least have called EntityManager.persist(entityBean), or else I get the following error:</p> <p><code>TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing</code></p> <p>An example:</p> <pre><code>Job job = new Job(); Collection&lt;Task&gt; tasks = job.getTasks(); //entityManager.persist(job); ActionPlan actionPlan = (ActionPlan) entityManager.createNamedQuery("ActionPlan.findByCommand"). setParameter("type", RunOperation.Install).getSingleResult(); Task task = Task.getTask(actionPlan); task.setActionPlan(actionPlan); tasks.add(task); task.setJob(job); </code></pre> <p>My problem is that I can't call createNamedQuery without first persisting 'job' (the line that is commented out). ActionPlan has a relation to Job, but the NamedQuery (findByCommand) does not join on Job. What bothers me is that I need to persist Job in order to query the database, when the new created Job is not even interesting in this context.<br> Moving the call to persist() to the end of the snippet yields the above mentioned error.</p> <p>I'm aware that the object I'm working on is not persisted, but persisting makes it impossible to rollback if an error occurs.</p> <p>I believe there is a solution for this, so if someone has the answer I would be very thankful. What am I missing?</p>
[ { "answer_id": 283628, "author": "Georgy Bolyuba", "author_id": 4052, "author_profile": "https://Stackoverflow.com/users/4052", "pm_score": 2, "selected": false, "text": "<p>It seems logical that you cannot query for something which is not in the database yet, no? What you can do is to start using transactions. In a simple case your session will have one transaction which will be open until you close your session. At that moment transaction will be commited and all your changes will be persisted. All you need is to rollback your transaction in case of error.</p>\n\n<p>P.S. <a href=\"http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/Session.html\" rel=\"nofollow noreferrer\">Here at the bottom</a> you can find \"A typical transaction should use the following idiom\". </p>\n\n<pre><code>Session sess = factory.openSession();\nTransaction tx;\ntry {\ntx = sess.beginTransaction();\n //do some work\n ...\n tx.commit();\n}\ncatch (Exception e) {\n if (tx!=null) tx.rollback();\n throw e;\n}\nfinally {\n sess.close();\n}\n</code></pre>\n" }, { "answer_id": 283717, "author": "homaxto", "author_id": 16152, "author_profile": "https://Stackoverflow.com/users/16152", "pm_score": 0, "selected": false, "text": "<p>I am aware that I can't query what has not yet been persisted - and this is not the case either. What I want to find is other Entity beans. Not just the same type, but any type of the Entity beans that I have. And then I get the TransientObjectException.</p>\n\n<p>Did I mention I use JBoss? I believe that using J2EE and JPA the server is in control of my transactions, and the last I want to do is interfere with it?! So for me, besides using requiresNew, etc. I don't mess with transactions - the server does.</p>\n\n<p>Maybe I should move the hibernate tag, because actually I'm using JPA - JBoss uses hibernate. So please relate to that in any code examples.</p>\n" }, { "answer_id": 286360, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Even if you persist object you still can rollback it. Only after invoking flush on EntityManager would case synchronizing to the underlying database.</p>\n" }, { "answer_id": 286502, "author": "homaxto", "author_id": 16152, "author_profile": "https://Stackoverflow.com/users/16152", "pm_score": 0, "selected": false, "text": "<p>Well I think that the answers and reading up a bit in the Java EE 5Tutorial has given me the right answer.</p>\n\n<p>On the contrary of my belief, persist() does <em>not</em> flush to the database, it only moves the Entity bean to the persisted state. What tricked me is that I noticed that after calling persist the entity actually gets persisted to the database anyway (and maybe the word 'save' in the error message). I took this as flush was called ending my transaction, but if I get themalkolm right, I am still able to rollback - by myself or by the server on an exception.</p>\n\n<p>So the conclusion I make is; persist should just be called, whenever a new entity is made, as long as it is not in relation to another entity already persisted.<br>\nThen the transaction is maintained and the server likes you a little bit more ;)</p>\n\n<p>What is left her is that I still don't understand why I am not able to make a query without everything being in a persisted state.</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283454", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16152/" ]
I have been working with hibernate/JPA on JBoss for some months now and have one question that I can't find an answer or solution for. It seems like when creating new entity beans I'm not able to do a query before I at least have called EntityManager.persist(entityBean), or else I get the following error: `TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing` An example: ``` Job job = new Job(); Collection<Task> tasks = job.getTasks(); //entityManager.persist(job); ActionPlan actionPlan = (ActionPlan) entityManager.createNamedQuery("ActionPlan.findByCommand"). setParameter("type", RunOperation.Install).getSingleResult(); Task task = Task.getTask(actionPlan); task.setActionPlan(actionPlan); tasks.add(task); task.setJob(job); ``` My problem is that I can't call createNamedQuery without first persisting 'job' (the line that is commented out). ActionPlan has a relation to Job, but the NamedQuery (findByCommand) does not join on Job. What bothers me is that I need to persist Job in order to query the database, when the new created Job is not even interesting in this context. Moving the call to persist() to the end of the snippet yields the above mentioned error. I'm aware that the object I'm working on is not persisted, but persisting makes it impossible to rollback if an error occurs. I believe there is a solution for this, so if someone has the answer I would be very thankful. What am I missing?
It seems logical that you cannot query for something which is not in the database yet, no? What you can do is to start using transactions. In a simple case your session will have one transaction which will be open until you close your session. At that moment transaction will be commited and all your changes will be persisted. All you need is to rollback your transaction in case of error. P.S. [Here at the bottom](http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/Session.html) you can find "A typical transaction should use the following idiom". ``` Session sess = factory.openSession(); Transaction tx; try { tx = sess.beginTransaction(); //do some work ... tx.commit(); } catch (Exception e) { if (tx!=null) tx.rollback(); throw e; } finally { sess.close(); } ```
283,456
<p>Anyone know a good and effective way to search/match for a byte pattern in an byte[] array and then return the positions.</p> <p>For example</p> <pre><code>byte[] pattern = new byte[] {12,3,5,76,8,0,6,125}; byte[] toBeSearched = new byte[] {23,36,43,76,125,56,34,234,12,3,5,76,8,0,6,125,234,56,211,122,22,4,7,89,76,64,12,3,5,76,8,0,6,125} </code></pre>
[ { "answer_id": 283469, "author": "Eugene Yokota", "author_id": 3827, "author_profile": "https://Stackoverflow.com/users/3827", "pm_score": -1, "selected": false, "text": "<p>You can put the byte array into <a href=\"http://msdn.microsoft.com/en-us/library/ezh7k8d5.aspx\" rel=\"nofollow noreferrer\">String</a> and run match by IndexOf. Or you can at least reuse <a href=\"http://en.wikipedia.org/wiki/String_searching_algorithm\" rel=\"nofollow noreferrer\">existing algorithms</a> on string matching.</p>\n\n<pre><code> [STAThread]\n static void Main(string[] args)\n {\n byte[] pattern = new byte[] {12,3,5,76,8,0,6,125};\n byte[] toBeSearched = new byte[] {23,36,43,76,125,56,34,234,12,3,5,76,8,0,6,125,234,56,211,122,22,4,7,89,76,64,12,3,5,76,8,0,6,125};\n string needle, haystack;\n\n unsafe \n {\n fixed(byte * p = pattern) {\n needle = new string((SByte *) p, 0, pattern.Length);\n } // fixed\n\n fixed (byte * p2 = toBeSearched) \n {\n haystack = new string((SByte *) p2, 0, toBeSearched.Length);\n } // fixed\n\n int i = haystack.IndexOf(needle, 0);\n System.Console.Out.WriteLine(i);\n }\n }\n</code></pre>\n" }, { "answer_id": 283509, "author": "Tamir", "author_id": 30879, "author_profile": "https://Stackoverflow.com/users/30879", "pm_score": -1, "selected": false, "text": "<p>toBeSearched.Except(pattern) will return you differences\ntoBeSearched.Intersect(pattern) will produce set of intersections\nGenerally, you should look into extended methods within Linq extensions</p>\n" }, { "answer_id": 283596, "author": "bruno conde", "author_id": 31136, "author_profile": "https://Stackoverflow.com/users/31136", "pm_score": 4, "selected": false, "text": "<p>My solution:</p>\n\n<pre><code>class Program\n{\n public static void Main()\n {\n byte[] pattern = new byte[] {12,3,5,76,8,0,6,125};\n\n byte[] toBeSearched = new byte[] { 23, 36, 43, 76, 125, 56, 34, 234, 12, 3, 5, 76, 8, 0, 6, 125, 234, 56, 211, 122, 22, 4, 7, 89, 76, 64, 12, 3, 5, 76, 8, 0, 6, 125};\n\n List&lt;int&gt; positions = SearchBytePattern(pattern, toBeSearched);\n\n foreach (var item in positions)\n {\n Console.WriteLine(\"Pattern matched at pos {0}\", item);\n }\n\n }\n\n static public List&lt;int&gt; SearchBytePattern(byte[] pattern, byte[] bytes)\n {\n List&lt;int&gt; positions = new List&lt;int&gt;();\n int patternLength = pattern.Length;\n int totalLength = bytes.Length;\n byte firstMatchByte = pattern[0];\n for (int i = 0; i &lt; totalLength; i++)\n {\n if (firstMatchByte == bytes[i] &amp;&amp; totalLength - i &gt;= patternLength)\n {\n byte[] match = new byte[patternLength];\n Array.Copy(bytes, i, match, 0, patternLength);\n if (match.SequenceEqual&lt;byte&gt;(pattern))\n {\n positions.Add(i);\n i += patternLength - 1;\n }\n }\n }\n return positions;\n }\n}\n</code></pre>\n" }, { "answer_id": 283648, "author": "Jb Evain", "author_id": 36702, "author_profile": "https://Stackoverflow.com/users/36702", "pm_score": 6, "selected": false, "text": "<p>May I suggest something that doesn't involve creating strings, copying arrays or unsafe code:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\n\nstatic class ByteArrayRocks\n{ \n static readonly int[] Empty = new int[0];\n\n public static int[] Locate (this byte[] self, byte[] candidate)\n {\n if (IsEmptyLocate(self, candidate))\n return Empty;\n\n var list = new List&lt;int&gt;();\n\n for (int i = 0; i &lt; self.Length; i++)\n {\n if (!IsMatch(self, i, candidate))\n continue;\n\n list.Add(i);\n }\n\n return list.Count == 0 ? Empty : list.ToArray();\n }\n\n static bool IsMatch (byte[] array, int position, byte[] candidate)\n {\n if (candidate.Length &gt; (array.Length - position))\n return false;\n\n for (int i = 0; i &lt; candidate.Length; i++)\n if (array[position + i] != candidate[i])\n return false;\n\n return true;\n }\n\n static bool IsEmptyLocate (byte[] array, byte[] candidate)\n {\n return array == null\n || candidate == null\n || array.Length == 0\n || candidate.Length == 0\n || candidate.Length &gt; array.Length;\n }\n\n static void Main()\n {\n var data = new byte[] { 23, 36, 43, 76, 125, 56, 34, 234, 12, 3, 5, 76, 8, 0, 6, 125, 234, 56, 211, 122, 22, 4, 7, 89, 76, 64, 12, 3, 5, 76, 8, 0, 6, 125 };\n var pattern = new byte[] { 12, 3, 5, 76, 8, 0, 6, 125 };\n\n foreach (var position in data.Locate(pattern))\n Console.WriteLine(position);\n }\n}\n</code></pre>\n\n<p><strong>Edit (by IAbstract)</strong> - <em>moving contents of <a href=\"https://stackoverflow.com/a/283815/210709\">post</a> here since it is not an answer</em></p>\n\n<p>Out of curiosity, I've created a small benchmark with different answers.</p>\n\n<p>Here are the results for a million iterations:</p>\n\n<pre><code>solution [Locate]: 00:00:00.7714027\nsolution [FindAll]: 00:00:03.5404399\nsolution [SearchBytePattern]: 00:00:01.1105190\nsolution [MatchBytePattern]: 00:00:03.0658212\n</code></pre>\n" }, { "answer_id": 283662, "author": "Constantin", "author_id": 20310, "author_profile": "https://Stackoverflow.com/users/20310", "pm_score": 1, "selected": false, "text": "<p>Here's my (not the most performant) solution. It relies on the fact that bytes/latin-1 conversion is lossless, which is <em>not</em> true for bytes/ASCII or bytes/UTF8 conversions.</p>\n\n<p>It's advantages are that It Works (tm) for any byte values (some other solutions work incorrectly with bytes 0x80-0xff) and can be extended to perform more advanced regex\nmatching.</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.Text.RegularExpressions;\n\nclass C {\n\n public static void Main() {\n byte[] data = {0, 100, 0, 255, 100, 0, 100, 0, 255};\n byte[] pattern = {0, 255};\n foreach (int i in FindAll(data, pattern)) {\n Console.WriteLine(i);\n }\n }\n\n public static IEnumerable&lt;int&gt; FindAll(\n byte[] haystack,\n byte[] needle\n ) {\n // bytes &lt;-&gt; latin-1 conversion is lossless\n Encoding latin1 = Encoding.GetEncoding(\"iso-8859-1\");\n string sHaystack = latin1.GetString(haystack);\n string sNeedle = latin1.GetString(needle);\n for (Match m = Regex.Match(sHaystack, Regex.Escape(sNeedle));\n m.Success; m = m.NextMatch()) {\n yield return m.Index;\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 283895, "author": "Davy Landman", "author_id": 11098, "author_profile": "https://Stackoverflow.com/users/11098", "pm_score": 1, "selected": false, "text": "<p>I would use a solution which does matching by converting to a string...</p>\n\n<p>You should write a simple function implementing the <a href=\"http://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm\" rel=\"nofollow noreferrer\">Knuth-Morris-Pratt searching algorithm</a>. This will be the fastest simple algorithm you can use to find the correct indexes.(You could use <a href=\"http://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string_search_algorithm\" rel=\"nofollow noreferrer\">Boyer-Moore</a> but it will require more setup.</p>\n\n<p>After you have optimized the algorithm, you could try to look for other kind of optimizations. But you should start with the basics.</p>\n\n<p>For example, the current \"fastest\" is the Locate solution by Jb Evian.</p>\n\n<p>if you look at the core</p>\n\n<pre><code> for (int i = 0; i &lt; self.Length; i++) {\n if (!IsMatch (self, i, candidate))\n continue;\n\n list.Add (i);\n }\n</code></pre>\n\n<p>After a match of the sub algorithm, it will start to find a match at i + 1, but you already know that the first possible match would be i + candidate.Length. So if you add,</p>\n\n<pre><code>i += candidate.Length -2; // -2 instead of -1 because the i++ will add the last index\n</code></pre>\n\n<p>it will be a lot faster when you expect a lot of occurrences of the subset in the superset. (Bruno Conde already does this in his solution)</p>\n\n<p>But this is just a half of the KNP algorithm, you should also add an extra parameter to the IsMatch method called numberOfValidMatches which would be an out parameter.</p>\n\n<p>this would resolve to the following:</p>\n\n<pre><code>int validMatches = 0;\nif (!IsMatch (self, i, candidate, out validMatches))\n{\n i += validMatches - 1; // -1 because the i++ will do the last one\n continue;\n}\n</code></pre>\n\n<p>and</p>\n\n<pre><code>static bool IsMatch (byte [] array, int position, byte [] candidate, out int numberOfValidMatches)\n{\n numberOfValidMatches = 0;\n if (candidate.Length &gt; (array.Length - position))\n return false;\n\n for (i = 0; i &lt; candidate.Length; i++)\n {\n if (array [position + i] != candidate [i])\n return false;\n numberOfValidMatches++; \n }\n\n return true;\n}\n</code></pre>\n\n<p>A little bit of refactoring and you could use the numberOfValidMatches as the loop variable, and rewrite the Locate loop using a while to avoid the -2 and -1. But I just wanted to make clear how you could add the KMP algorithm.</p>\n" }, { "answer_id": 283909, "author": "VVS", "author_id": 21038, "author_profile": "https://Stackoverflow.com/users/21038", "pm_score": 4, "selected": false, "text": "<p>Use the efficient <a href=\"http://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string_search_algorithm\" rel=\"noreferrer\">Boyer-Moore algorithm</a>. </p>\n\n<p>It's designed to find strings withing strings but you need little imagination to project this to byte arrays.</p>\n\n<p>In general the best answer is: use any string searching algorithm that you like :).</p>\n" }, { "answer_id": 283935, "author": "Alnitak", "author_id": 6782, "author_profile": "https://Stackoverflow.com/users/6782", "pm_score": 1, "selected": false, "text": "<p>Jb Evain's answer has:</p>\n\n<pre><code> for (int i = 0; i &lt; self.Length; i++) {\n if (!IsMatch (self, i, candidate))\n continue;\n list.Add (i);\n }\n</code></pre>\n\n<p>and then the IsMatch function first checks whether <code>candidate</code> goes beyond the length of the array being searched.</p>\n\n<p>This would be more efficient if the <code>for</code> loop were coded:</p>\n\n<pre><code> for (int i = 0, n = self.Length - candidate.Length + 1; i &lt; n; ++i) {\n if (!IsMatch (self, i, candidate))\n continue;\n list.Add (i);\n }\n</code></pre>\n\n<p>at this point one <em>could</em> also eliminate the test from the start of <code>IsMatch</code>, so long as you contract via pre-conditions never to call it with \"illegal' parameters.\nNote: Fixed an off-by-one bug in 2019.</p>\n" }, { "answer_id": 284026, "author": "Davy Landman", "author_id": 11098, "author_profile": "https://Stackoverflow.com/users/11098", "pm_score": 1, "selected": false, "text": "<p>I've created a new function using the tips from my answer and the answer by Alnitak.</p>\n\n<pre><code>public static List&lt;Int32&gt; LocateSubset(Byte[] superSet, Byte[] subSet)\n{\n if ((superSet == null) || (subSet == null))\n {\n throw new ArgumentNullException();\n }\n if ((superSet.Length &lt; subSet.Length) || (superSet.Length == 0) || (subSet.Length == 0))\n {\n return new List&lt;Int32&gt;();\n }\n var result = new List&lt;Int32&gt;();\n Int32 currentIndex = 0;\n Int32 maxIndex = superSet.Length - subSet.Length;\n while (currentIndex &lt; maxIndex)\n {\n Int32 matchCount = CountMatches(superSet, currentIndex, subSet);\n if (matchCount == subSet.Length)\n {\n result.Add(currentIndex);\n }\n currentIndex++;\n if (matchCount &gt; 0)\n {\n currentIndex += matchCount - 1;\n }\n }\n return result;\n}\n\nprivate static Int32 CountMatches(Byte[] superSet, int startIndex, Byte[] subSet)\n{\n Int32 currentOffset = 0;\n while (currentOffset &lt; subSet.Length)\n {\n if (superSet[startIndex + currentOffset] != subSet[currentOffset])\n {\n break;\n }\n currentOffset++;\n }\n return currentOffset;\n}\n</code></pre>\n\n<p>the only part I'm not so happy about is the</p>\n\n<pre><code> currentIndex++;\n if (matchCount &gt; 0)\n {\n currentIndex += matchCount - 1;\n }\n</code></pre>\n\n<p>part... I would have like to use a if else to avoid the -1, but this results in a better branch prediction (although I'm not that sure it will matter that much)..</p>\n" }, { "answer_id": 284104, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Why make the simple difficult? This can be done in any language using for loops. Here is one in C#:</p>\n\n<pre>\nusing System;\nusing System.Collections.Generic;\n\nnamespace BinarySearch\n{\n class Program\n {\n static void Main(string[] args)\n {\n byte[] pattern = new byte[] {12,3,5,76,8,0,6,125};\n byte[] toBeSearched = new byte[] {23,36,43,76,125,56,34,234,12,3,5,76,8,0,6,125,234,56,211,<br>122,22,4,7,89,76,64,12,3,5,76,8,0,6,125};\n\n List&lt;int&gt; occurences = findOccurences(toBeSearched, pattern);\n\n foreach(int occurence in occurences) {\n Console.WriteLine(\"Found match starting at 0-based index: \" + occurence);\n }\n\n\n }\n\n static List&lt;int&gt; findOccurences(byte[] haystack, byte[] needle)\n {\n List&lt;int&gt; occurences = new List&lt;int&gt;();\n\n for (int i = 0; i &lt; haystack.Length; i++)\n {\n if (needle[0] == haystack[i])\n {\n bool found = true;\n int j, k;\n for (j = 0, k = i; j &lt; needle.Length; j++, k++)\n {\n if (k &gt;= haystack.Length || needle[j] != haystack[k])\n {\n found = false;\n break;\n }\n }\n if (found)\n {\n occurences.Add(i - 1);\n i = k;\n }\n }\n }\n return occurences;\n }\n }\n}\n\n\n\n\n</pre>\n" }, { "answer_id": 284154, "author": "Anders R", "author_id": 36504, "author_profile": "https://Stackoverflow.com/users/36504", "pm_score": 1, "selected": false, "text": "<p>thanks for taking the time...</p>\n\n<p>This is the code that i was using/testing with before I asked my question...\nThe reason I ask this question was that I´m certain of that I´m not using the optimal code to do this... so thanks again for taking the time!</p>\n\n<pre><code> private static int CountPatternMatches(byte[] pattern, byte[] bytes)\n {\n int counter = 0;\n\n for (int i = 0; i &lt; bytes.Length; i++)\n {\n if (bytes[i] == pattern[0] &amp;&amp; (i + pattern.Length) &lt; bytes.Length)\n {\n for (int x = 1; x &lt; pattern.Length; x++)\n {\n if (pattern[x] != bytes[x+i])\n {\n break;\n }\n\n if (x == pattern.Length -1)\n {\n counter++;\n i = i + pattern.Length;\n }\n }\n }\n }\n\n return counter;\n }\n</code></pre>\n\n<p>Anyone that see any errors in my code? Is this considered as an hackish approach?\nI have tried almost every sample you guys have posted and I seems to get some variations in the match results. I have been running my tests with ~10Mb byte array as my toBeSearched array. </p>\n" }, { "answer_id": 332667, "author": "GoClimbColorado", "author_id": 42239, "author_profile": "https://Stackoverflow.com/users/42239", "pm_score": 4, "selected": false, "text": "<p>Originally I posted some old code I used but was curious about Jb Evain's <a href=\"http://monoport.com/38177\" rel=\"nofollow noreferrer\">benchmarks</a>. I found that my solution was stupid slow. It appears that bruno conde's <a href=\"https://stackoverflow.com/questions/283456/byte-array-pattern-search#283596\">SearchBytePattern</a> is the fastest. I could not figure why especially since he uses an Array.Copy and an Extension method. But there is proof in Jb's tests, so kudos to bruno.</p>\n\n<p>I simplified the bits even further, so hopefully this will be the clearest and simplest solution. (All the hard work done by bruno conde) The enhancements are:</p>\n\n<ul>\n<li>Buffer.BlockCopy </li>\n<li>Array.IndexOf&lt;byte&gt;</li>\n<li>while loop instead of a for loop</li>\n<li>start index parameter</li>\n<li><p>converted to extension method</p>\n\n<pre><code>public static List&lt;int&gt; IndexOfSequence(this byte[] buffer, byte[] pattern, int startIndex) \n{\n List&lt;int&gt; positions = new List&lt;int&gt;();\n int i = Array.IndexOf&lt;byte&gt;(buffer, pattern[0], startIndex); \n while (i &gt;= 0 &amp;&amp; i &lt;= buffer.Length - pattern.Length) \n {\n byte[] segment = new byte[pattern.Length];\n Buffer.BlockCopy(buffer, i, segment, 0, pattern.Length); \n if (segment.SequenceEqual&lt;byte&gt;(pattern))\n positions.Add(i);\n i = Array.IndexOf&lt;byte&gt;(buffer, pattern[0], i + 1);\n }\n return positions; \n}\n</code></pre></li>\n</ul>\n\n<p>Note that, the last statement in the <code>while</code> block should be <code>i = Array.IndexOf&lt;byte&gt;(buffer, pattern[0], i + 1);</code> instead of <code>i = Array.IndexOf&lt;byte&gt;(buffer, pattern[0], i + pattern.Length);</code>. Look at the comment by Johan. A simple test could prove that:</p>\n\n<pre><code>byte[] pattern = new byte[] {1, 2};\nbyte[] toBeSearched = new byte[] { 1, 1, 2, 1, 12 };\n</code></pre>\n\n<p>With <code>i = Array.IndexOf&lt;byte&gt;(buffer, pattern[0], i + pattern.Length);</code>, nothing returned. <code>i = Array.IndexOf&lt;byte&gt;(buffer, pattern[0], i + 1);</code> returns the correct result.</p>\n" }, { "answer_id": 1271069, "author": "Steve Hiner", "author_id": 10221, "author_profile": "https://Stackoverflow.com/users/10221", "pm_score": 1, "selected": false, "text": "<p>Speed isn't everything. Did you check them for consistency?</p>\n\n<p>I didn't test all the code listed here. I tested my own code (which wasn't totally consistent, I admit) and IndexOfSequence. I found that for many tests IndexOfSequence was quite a bit faster than my code but with repeated testing I found that it was less consistent. In particular it seems to have the most trouble with finding patterns at the end of the array but it will miss them in the middle of the array too sometimes.</p>\n\n<p>My test code isn't designed for efficiency, I just wanted to have a bunch of random data with some known strings inside. That test pattern is roughly like a boundary marker in an http form upload stream. That's what I was looking for when I ran across this code so I figured I'd test it with the kind of data I'll be searching for. It appears that the longer the pattern is the more often IndexOfSequence will miss a value.</p>\n\n<pre><code>private static void TestMethod()\n{\n Random rnd = new Random(DateTime.Now.Millisecond);\n string Pattern = \"-------------------------------65498495198498\";\n byte[] pattern = Encoding.ASCII.GetBytes(Pattern);\n\n byte[] testBytes;\n int count = 3;\n for (int i = 0; i &lt; 100; i++)\n {\n StringBuilder TestString = new StringBuilder(2500);\n TestString.Append(Pattern);\n byte[] buf = new byte[1000];\n rnd.NextBytes(buf);\n TestString.Append(Encoding.ASCII.GetString(buf));\n TestString.Append(Pattern);\n rnd.NextBytes(buf);\n TestString.Append(Encoding.ASCII.GetString(buf));\n TestString.Append(Pattern);\n testBytes = Encoding.ASCII.GetBytes(TestString.ToString());\n\n List&lt;int&gt; idx = IndexOfSequence(ref testBytes, pattern, 0);\n if (idx.Count != count)\n {\n Console.Write(\"change from {0} to {1} on iteration {2}: \", count, idx.Count, i);\n foreach (int ix in idx)\n {\n Console.Write(\"{0}, \", ix);\n }\n Console.WriteLine();\n count = idx.Count;\n }\n }\n\n Console.WriteLine(\"Press ENTER to exit\");\n Console.ReadLine();\n}\n</code></pre>\n\n<p>(obviously I converted IndexOfSequence from an extension back into a normal method for this testing)</p>\n\n<p>Here's a sample run of my output:</p>\n\n<pre><code>change from 3 to 2 on iteration 1: 0, 2090,\nchange from 2 to 3 on iteration 2: 0, 1045, 2090,\nchange from 3 to 2 on iteration 3: 0, 1045,\nchange from 2 to 3 on iteration 4: 0, 1045, 2090,\nchange from 3 to 2 on iteration 6: 0, 2090,\nchange from 2 to 3 on iteration 7: 0, 1045, 2090,\nchange from 3 to 2 on iteration 11: 0, 2090,\nchange from 2 to 3 on iteration 12: 0, 1045, 2090,\nchange from 3 to 2 on iteration 14: 0, 2090,\nchange from 2 to 3 on iteration 16: 0, 1045, 2090,\nchange from 3 to 2 on iteration 17: 0, 1045,\nchange from 2 to 3 on iteration 18: 0, 1045, 2090,\nchange from 3 to 1 on iteration 20: 0,\nchange from 1 to 3 on iteration 21: 0, 1045, 2090,\nchange from 3 to 2 on iteration 22: 0, 2090,\nchange from 2 to 3 on iteration 23: 0, 1045, 2090,\nchange from 3 to 2 on iteration 24: 0, 2090,\nchange from 2 to 3 on iteration 25: 0, 1045, 2090,\nchange from 3 to 2 on iteration 26: 0, 2090,\nchange from 2 to 3 on iteration 27: 0, 1045, 2090,\nchange from 3 to 2 on iteration 43: 0, 1045,\nchange from 2 to 3 on iteration 44: 0, 1045, 2090,\nchange from 3 to 2 on iteration 48: 0, 1045,\nchange from 2 to 3 on iteration 49: 0, 1045, 2090,\nchange from 3 to 2 on iteration 50: 0, 2090,\nchange from 2 to 3 on iteration 52: 0, 1045, 2090,\nchange from 3 to 2 on iteration 54: 0, 1045,\nchange from 2 to 3 on iteration 57: 0, 1045, 2090,\nchange from 3 to 2 on iteration 62: 0, 1045,\nchange from 2 to 3 on iteration 63: 0, 1045, 2090,\nchange from 3 to 2 on iteration 72: 0, 2090,\nchange from 2 to 3 on iteration 73: 0, 1045, 2090,\nchange from 3 to 2 on iteration 75: 0, 2090,\nchange from 2 to 3 on iteration 76: 0, 1045, 2090,\nchange from 3 to 2 on iteration 78: 0, 1045,\nchange from 2 to 3 on iteration 79: 0, 1045, 2090,\nchange from 3 to 2 on iteration 81: 0, 2090,\nchange from 2 to 3 on iteration 82: 0, 1045, 2090,\nchange from 3 to 2 on iteration 85: 0, 2090,\nchange from 2 to 3 on iteration 86: 0, 1045, 2090,\nchange from 3 to 2 on iteration 89: 0, 2090,\nchange from 2 to 3 on iteration 90: 0, 1045, 2090,\nchange from 3 to 2 on iteration 91: 0, 2090,\nchange from 2 to 1 on iteration 92: 0,\nchange from 1 to 3 on iteration 93: 0, 1045, 2090,\nchange from 3 to 1 on iteration 99: 0,\n</code></pre>\n\n<p>I don't mean to pick on IndexOfSequence, it just happened to be the one I started working with today. I noticed at the end of the day that it seemed to be missing patterns in the data so I wrote my own pattern matcher tonight. It's not as fast though. I'm going to tweak it a bit more to see if I can get it 100% consistent before I post it.</p>\n\n<p>I just wanted to remind everyone that they should test things like this to make sure they give good, repeatable results before you trust them in production code.</p>\n" }, { "answer_id": 1807740, "author": "Sorin S.", "author_id": 219941, "author_profile": "https://Stackoverflow.com/users/219941", "pm_score": 1, "selected": false, "text": "<p>I tried various solutions and ended up modifying the SearchBytePattern one. I tested on a 30k sequence and it is, fast :)</p>\n\n<pre><code> static public int SearchBytePattern(byte[] pattern, byte[] bytes)\n {\n int matches = 0;\n for (int i = 0; i &lt; bytes.Length; i++)\n {\n if (pattern[0] == bytes[i] &amp;&amp; bytes.Length - i &gt;= pattern.Length)\n {\n bool ismatch = true;\n for (int j = 1; j &lt; pattern.Length &amp;&amp; ismatch == true; j++)\n {\n if (bytes[i + j] != pattern[j])\n ismatch = false;\n }\n if (ismatch)\n {\n matches++;\n i += pattern.Length - 1;\n }\n }\n }\n return matches;\n }\n</code></pre>\n\n<p>Let me know your thoughts.</p>\n" }, { "answer_id": 5227131, "author": "Foubar", "author_id": 649008, "author_profile": "https://Stackoverflow.com/users/649008", "pm_score": 2, "selected": false, "text": "<p>These are the simplest and fastest methods you can use, and there wouldn't be anything faster than these. It is unsafe but that's what we use pointers for is speed. So here I offer you my extension methods that I use search for a single, and a list of indices of the occurrences. I would like to say this is the cleanest code here.</p>\n\n<pre><code> public static unsafe long IndexOf(this byte[] Haystack, byte[] Needle)\n {\n fixed (byte* H = Haystack) fixed (byte* N = Needle)\n {\n long i = 0;\n for (byte* hNext = H, hEnd = H + Haystack.LongLength; hNext &lt; hEnd; i++, hNext++)\n {\n bool Found = true;\n for (byte* hInc = hNext, nInc = N, nEnd = N + Needle.LongLength; Found &amp;&amp; nInc &lt; nEnd; Found = *nInc == *hInc, nInc++, hInc++) ;\n if (Found) return i;\n }\n return -1;\n }\n }\n public static unsafe List&lt;long&gt; IndexesOf(this byte[] Haystack, byte[] Needle)\n {\n List&lt;long&gt; Indexes = new List&lt;long&gt;();\n fixed (byte* H = Haystack) fixed (byte* N = Needle)\n {\n long i = 0;\n for (byte* hNext = H, hEnd = H + Haystack.LongLength; hNext &lt; hEnd; i++, hNext++)\n {\n bool Found = true;\n for (byte* hInc = hNext, nInc = N, nEnd = N + Needle.LongLength; Found &amp;&amp; nInc &lt; nEnd; Found = *nInc == *hInc, nInc++, hInc++) ;\n if (Found) Indexes.Add(i);\n }\n return Indexes;\n }\n }\n</code></pre>\n\n<p>Benchmarked with Locate, it is 1.2-1.4x faster</p>\n" }, { "answer_id": 6568360, "author": "Jay", "author_id": 390720, "author_profile": "https://Stackoverflow.com/users/390720", "pm_score": 1, "selected": false, "text": "<p>Here is a solution I came up with. I included notes I found along the way with the implementation. It can match forward, backward and with different (in/dec)remement amounts e.g. direction; starting at any offset in the haystack.</p>\n\n<p>Any input would be awesome!</p>\n\n<pre><code> /// &lt;summary&gt;\n /// Matches a byte array to another byte array\n /// forwards or reverse\n /// &lt;/summary&gt;\n /// &lt;param name=\"a\"&gt;byte array&lt;/param&gt;\n /// &lt;param name=\"offset\"&gt;start offset&lt;/param&gt;\n /// &lt;param name=\"len\"&gt;max length&lt;/param&gt;\n /// &lt;param name=\"b\"&gt;byte array&lt;/param&gt;\n /// &lt;param name=\"direction\"&gt;to move each iteration&lt;/param&gt;\n /// &lt;returns&gt;true if all bytes match, otherwise false&lt;/returns&gt;\n internal static bool Matches(ref byte[] a, int offset, int len, ref byte[] b, int direction = 1)\n {\n #region Only Matched from offset Within a and b, could not differ, e.g. if you wanted to mach in reverse for only part of a in some of b that would not work\n //if (direction == 0) throw new ArgumentException(\"direction\");\n //for (; offset &lt; len; offset += direction) if (a[offset] != b[offset]) return false;\n //return true;\n #endregion\n //Will match if b contains len of a and return a a index of positive value\n return IndexOfBytes(ref a, ref offset, len, ref b, len) != -1;\n }\n\n///Here is the Implementation code\n\n /// &lt;summary&gt;\n /// Swaps two integers without using a temporary variable\n /// &lt;/summary&gt;\n /// &lt;param name=\"a\"&gt;&lt;/param&gt;\n /// &lt;param name=\"b\"&gt;&lt;/param&gt;\n internal static void Swap(ref int a, ref int b)\n {\n a ^= b;\n b ^= a;\n a ^= b;\n }\n\n /// &lt;summary&gt;\n /// Swaps two bytes without using a temporary variable\n /// &lt;/summary&gt;\n /// &lt;param name=\"a\"&gt;&lt;/param&gt;\n /// &lt;param name=\"b\"&gt;&lt;/param&gt;\n internal static void Swap(ref byte a, ref byte b)\n {\n a ^= b;\n b ^= a;\n a ^= b;\n }\n\n /// &lt;summary&gt;\n /// Can be used to find if a array starts, ends spot Matches or compltely contains a sub byte array\n /// Set checkLength to the amount of bytes from the needle you want to match, start at 0 for forward searches start at hayStack.Lenght -1 for reverse matches\n /// &lt;/summary&gt;\n /// &lt;param name=\"a\"&gt;Needle&lt;/param&gt;\n /// &lt;param name=\"offset\"&gt;Start in Haystack&lt;/param&gt;\n /// &lt;param name=\"len\"&gt;Length of required match&lt;/param&gt;\n /// &lt;param name=\"b\"&gt;Haystack&lt;/param&gt;\n /// &lt;param name=\"direction\"&gt;Which way to move the iterator&lt;/param&gt;\n /// &lt;returns&gt;Index if found, otherwise -1&lt;/returns&gt;\n internal static int IndexOfBytes(ref byte[] needle, ref int offset, int checkLength, ref byte[] haystack, int direction = 1)\n {\n //If the direction is == 0 we would spin forever making no progress\n if (direction == 0) throw new ArgumentException(\"direction\");\n //Cache the length of the needle and the haystack, setup the endIndex for a reverse search\n int needleLength = needle.Length, haystackLength = haystack.Length, endIndex = 0, workingOffset = offset;\n //Allocate a value for the endIndex and workingOffset\n //If we are going forward then the bound is the haystackLength\n if (direction &gt;= 1) endIndex = haystackLength;\n #region [Optomization - Not Required]\n //{\n\n //I though this was required for partial matching but it seems it is not needed in this form\n //workingOffset = needleLength - checkLength;\n //}\n #endregion\n else Swap(ref workingOffset, ref endIndex); \n #region [Optomization - Not Required]\n //{ \n //Otherwise we are going in reverse and the endIndex is the needleLength - checkLength \n //I though the length had to be adjusted but it seems it is not needed in this form\n //endIndex = needleLength - checkLength;\n //}\n #endregion\n #region [Optomized to above]\n //Allocate a value for the endIndex\n //endIndex = direction &gt;= 1 ? haystackLength : needleLength - checkLength,\n //Determine the workingOffset\n //workingOffset = offset &gt; needleLength ? offset : needleLength; \n //If we are doing in reverse swap the two\n //if (workingOffset &gt; endIndex) Swap(ref workingOffset, ref endIndex);\n //Else we are going in forward direction do the offset is adjusted by the length of the check\n //else workingOffset -= checkLength;\n //Start at the checkIndex (workingOffset) every search attempt\n #endregion\n //Save the checkIndex (used after the for loop is done with it to determine if the match was checkLength long)\n int checkIndex = workingOffset;\n #region [For Loop Version]\n ///Optomized with while (single op)\n ///for (int checkIndex = workingOffset; checkIndex &lt; endIndex; offset += direction, checkIndex = workingOffset)\n ///{\n ///Start at the checkIndex\n /// While the checkIndex &lt; checkLength move forward\n /// If NOT (the needle at the checkIndex matched the haystack at the offset + checkIndex) BREAK ELSE we have a match continue the search \n /// for (; checkIndex &lt; checkLength; ++checkIndex) if (needle[checkIndex] != haystack[offset + checkIndex]) break; else continue;\n /// If the match was the length of the check\n /// if (checkIndex == checkLength) return offset; //We are done matching\n ///}\n #endregion\n //While the checkIndex &lt; endIndex\n while (checkIndex &lt; endIndex)\n {\n for (; checkIndex &lt; checkLength; ++checkIndex) if (needle[checkIndex] != haystack[offset + checkIndex]) break; else continue;\n //If the match was the length of the check\n if (checkIndex == checkLength) return offset; //We are done matching\n //Move the offset by the direction, reset the checkIndex to the workingOffset\n offset += direction; checkIndex = workingOffset; \n }\n //We did not have a match with the given options\n return -1;\n }\n</code></pre>\n" }, { "answer_id": 6964519, "author": "Victor", "author_id": 647559, "author_profile": "https://Stackoverflow.com/users/647559", "pm_score": 2, "selected": false, "text": "<p>I'm a little late to the party\nHow about using Boyer Moore algorithm but search for bytes instead of strings.\nc# code below.</p>\n\n<p>EyeCode Inc.</p>\n\n<pre><code>class Program {\n static void Main(string[] args) {\n byte[] text = new byte[] {12,3,5,76,8,0,6,125,23,36,43,76,125,56,34,234,12,4,5,76,8,0,6,125,234,56,211,122,22,4,7,89,76,64,12,3,5,76,8,0,6,123};\n byte[] pattern = new byte[] {12,3,5,76,8,0,6,125};\n\n BoyerMoore tmpSearch = new BoyerMoore(pattern,text);\n\n Console.WriteLine(tmpSearch.Match());\n Console.ReadKey();\n }\n\n public class BoyerMoore {\n\n private static int ALPHABET_SIZE = 256;\n\n private byte[] text;\n private byte[] pattern;\n\n private int[] last;\n private int[] match;\n private int[] suffix;\n\n public BoyerMoore(byte[] pattern, byte[] text) {\n this.text = text;\n this.pattern = pattern;\n last = new int[ALPHABET_SIZE];\n match = new int[pattern.Length];\n suffix = new int[pattern.Length];\n }\n\n\n /**\n * Searches the pattern in the text.\n * returns the position of the first occurrence, if found and -1 otherwise.\n */\n public int Match() {\n // Preprocessing\n ComputeLast();\n ComputeMatch();\n\n // Searching\n int i = pattern.Length - 1;\n int j = pattern.Length - 1; \n while (i &lt; text.Length) {\n if (pattern[j] == text[i]) {\n if (j == 0) { \n return i;\n }\n j--;\n i--;\n } \n else {\n i += pattern.Length - j - 1 + Math.Max(j - last[text[i]], match[j]);\n j = pattern.Length - 1;\n }\n }\n return -1; \n } \n\n\n /**\n * Computes the function last and stores its values in the array last.\n * last(Char ch) = the index of the right-most occurrence of the character ch\n * in the pattern; \n * -1 if ch does not occur in the pattern.\n */\n private void ComputeLast() {\n for (int k = 0; k &lt; last.Length; k++) { \n last[k] = -1;\n }\n for (int j = pattern.Length-1; j &gt;= 0; j--) {\n if (last[pattern[j]] &lt; 0) {\n last[pattern[j]] = j;\n }\n }\n }\n\n\n /**\n * Computes the function match and stores its values in the array match.\n * match(j) = min{ s | 0 &lt; s &lt;= j &amp;&amp; p[j-s]!=p[j]\n * &amp;&amp; p[j-s+1]..p[m-s-1] is suffix of p[j+1]..p[m-1] }, \n * if such s exists, else\n * min{ s | j+1 &lt;= s &lt;= m \n * &amp;&amp; p[0]..p[m-s-1] is suffix of p[j+1]..p[m-1] }, \n * if such s exists,\n * m, otherwise,\n * where p is the pattern and m is its length.\n */\n private void ComputeMatch() {\n /* Phase 1 */\n for (int j = 0; j &lt; match.Length; j++) { \n match[j] = match.Length;\n } //O(m) \n\n ComputeSuffix(); //O(m)\n\n /* Phase 2 */\n //Uses an auxiliary array, backwards version of the KMP failure function.\n //suffix[i] = the smallest j &gt; i s.t. p[j..m-1] is a prefix of p[i..m-1],\n //if there is no such j, suffix[i] = m\n\n //Compute the smallest shift s, such that 0 &lt; s &lt;= j and\n //p[j-s]!=p[j] and p[j-s+1..m-s-1] is suffix of p[j+1..m-1] or j == m-1}, \n // if such s exists,\n for (int i = 0; i &lt; match.Length - 1; i++) {\n int j = suffix[i + 1] - 1; // suffix[i+1] &lt;= suffix[i] + 1\n if (suffix[i] &gt; j) { // therefore pattern[i] != pattern[j]\n match[j] = j - i;\n } \n else {// j == suffix[i]\n match[j] = Math.Min(j - i + match[i], match[j]);\n }\n }\n\n /* Phase 3 */\n //Uses the suffix array to compute each shift s such that\n //p[0..m-s-1] is a suffix of p[j+1..m-1] with j &lt; s &lt; m\n //and stores the minimum of this shift and the previously computed one.\n if (suffix[0] &lt; pattern.Length) {\n for (int j = suffix[0] - 1; j &gt;= 0; j--) {\n if (suffix[0] &lt; match[j]) { match[j] = suffix[0]; }\n }\n {\n int j = suffix[0];\n for (int k = suffix[j]; k &lt; pattern.Length; k = suffix[k]) {\n while (j &lt; k) {\n if (match[j] &gt; k) {\n match[j] = k;\n }\n j++;\n }\n }\n }\n }\n }\n\n\n /**\n * Computes the values of suffix, which is an auxiliary array, \n * backwards version of the KMP failure function.\n * \n * suffix[i] = the smallest j &gt; i s.t. p[j..m-1] is a prefix of p[i..m-1],\n * if there is no such j, suffix[i] = m, i.e. \n\n * p[suffix[i]..m-1] is the longest prefix of p[i..m-1], if suffix[i] &lt; m.\n */\n private void ComputeSuffix() { \n suffix[suffix.Length-1] = suffix.Length; \n int j = suffix.Length - 1;\n for (int i = suffix.Length - 2; i &gt;= 0; i--) { \n while (j &lt; suffix.Length - 1 &amp;&amp; !pattern[j].Equals(pattern[i])) {\n j = suffix[j + 1] - 1;\n }\n if (pattern[j] == pattern[i]) { \n j--; \n }\n suffix[i] = j + 1;\n }\n }\n\n }\n\n}\n</code></pre>\n" }, { "answer_id": 10140221, "author": "Ravi", "author_id": 1330682, "author_profile": "https://Stackoverflow.com/users/1330682", "pm_score": 0, "selected": false, "text": "<p>Here's a simple code i wrote using only basic data types:\n(It returns the index of first occurance) </p>\n\n<pre><code>private static int findMatch(byte[] data, byte[] pattern) {\n if(pattern.length &gt; data.length){\n return -1;\n }\n for(int i = 0; i&lt;data.length ;){\n int j;\n for(j=0;j&lt;pattern.length;j++){\n\n if(pattern[j]!=data[i])\n break;\n i++;\n }\n if(j==pattern.length){\n System.out.println(\"Pattern found at : \"+(i - pattern.length ));\n return i - pattern.length ;\n }\n if(j!=0)continue;\n i++;\n }\n\n return -1;\n}\n</code></pre>\n" }, { "answer_id": 11866989, "author": "Matten", "author_id": 524475, "author_profile": "https://Stackoverflow.com/users/524475", "pm_score": 3, "selected": false, "text": "<p>I was missing a LINQ method/answer :-)</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Searches in the haystack array for the given needle using the default equality operator and returns the index at which the needle starts.\n/// &lt;/summary&gt;\n/// &lt;typeparam name=\"T\"&gt;Type of the arrays.&lt;/typeparam&gt;\n/// &lt;param name=\"haystack\"&gt;Sequence to operate on.&lt;/param&gt;\n/// &lt;param name=\"needle\"&gt;Sequence to search for.&lt;/param&gt;\n/// &lt;returns&gt;Index of the needle within the haystack or -1 if the needle isn't contained.&lt;/returns&gt;\npublic static IEnumerable&lt;int&gt; IndexOf&lt;T&gt;(this T[] haystack, T[] needle)\n{\n if ((needle != null) &amp;&amp; (haystack.Length &gt;= needle.Length))\n {\n for (int l = 0; l &lt; haystack.Length - needle.Length + 1; l++)\n {\n if (!needle.Where((data, index) =&gt; !haystack[l + index].Equals(data)).Any())\n {\n yield return l;\n }\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 14712207, "author": "YujiSoftware", "author_id": 1932017, "author_profile": "https://Stackoverflow.com/users/1932017", "pm_score": 5, "selected": false, "text": "<p>Use <strong>LINQ Methods.</strong></p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public static IEnumerable&lt;int&gt; PatternAt(byte[] source, byte[] pattern)\n{\n for (int i = 0; i &lt; source.Length; i++)\n {\n if (source.Skip(i).Take(pattern.Length).SequenceEqual(pattern))\n {\n yield return i;\n }\n }\n}\n</code></pre>\n\n<p>Very simple!</p>\n" }, { "answer_id": 20557026, "author": "ApeShoes", "author_id": 3097613, "author_profile": "https://Stackoverflow.com/users/3097613", "pm_score": 0, "selected": false, "text": "<p>Just another answer that is easy to follow and pretty efficient for a O(n) type of\noperation without using unsafe code or copying parts of the source arrays.</p>\n\n<p>Be sure to test. Some of the suggestions found on this topic are susceptible to gotta situations.</p>\n\n<pre><code> static void Main(string[] args)\n {\n // 1 1 1 1 1 1 1 1 1 1 2 2 2\n // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9\n byte[] buffer = new byte[] { 1, 0, 2, 3, 4, 5, 6, 7, 8, 9, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 5, 5, 0, 5, 5, 1, 2 };\n byte[] beginPattern = new byte[] { 1, 0, 2 };\n byte[] middlePattern = new byte[] { 8, 9, 10 };\n byte[] endPattern = new byte[] { 9, 10, 11 };\n byte[] wholePattern = new byte[] { 1, 0, 2, 3, 4, 5, 6, 7, 8, 9, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };\n byte[] noMatchPattern = new byte[] { 7, 7, 7 };\n\n int beginIndex = ByteArrayPatternIndex(buffer, beginPattern);\n int middleIndex = ByteArrayPatternIndex(buffer, middlePattern);\n int endIndex = ByteArrayPatternIndex(buffer, endPattern);\n int wholeIndex = ByteArrayPatternIndex(buffer, wholePattern);\n int noMatchIndex = ByteArrayPatternIndex(buffer, noMatchPattern);\n }\n\n /// &lt;summary&gt;\n /// Returns the index of the first occurrence of a byte array within another byte array\n /// &lt;/summary&gt;\n /// &lt;param name=\"buffer\"&gt;The byte array to be searched&lt;/param&gt;\n /// &lt;param name=\"pattern\"&gt;The byte array that contains the pattern to be found&lt;/param&gt;\n /// &lt;returns&gt;If buffer contains pattern then the index of the first occurrence of pattern within buffer; otherwise, -1&lt;/returns&gt;\n public static int ByteArrayPatternIndex(byte[] buffer, byte[] pattern)\n {\n if (buffer != null &amp;&amp; pattern != null &amp;&amp; pattern.Length &lt;= buffer.Length)\n {\n int resumeIndex;\n for (int i = 0; i &lt;= buffer.Length - pattern.Length; i++)\n {\n if (buffer[i] == pattern[0]) // Current byte equals first byte of pattern\n {\n resumeIndex = 0;\n for (int x = 1; x &lt; pattern.Length; x++)\n {\n if (buffer[i + x] == pattern[x])\n {\n if (x == pattern.Length - 1) // Matched the entire pattern\n return i;\n else if (resumeIndex == 0 &amp;&amp; buffer[i + x] == pattern[0]) // The current byte equals the first byte of the pattern so start here on the next outer loop iteration\n resumeIndex = i + x;\n }\n else\n {\n if (resumeIndex &gt; 0)\n i = resumeIndex - 1; // The outer loop iterator will increment so subtract one\n else if (x &gt; 1)\n i += (x - 1); // Advance the outer loop variable since we already checked these bytes\n break;\n }\n }\n }\n }\n }\n return -1;\n }\n\n /// &lt;summary&gt;\n /// Returns the indexes of each occurrence of a byte array within another byte array\n /// &lt;/summary&gt;\n /// &lt;param name=\"buffer\"&gt;The byte array to be searched&lt;/param&gt;\n /// &lt;param name=\"pattern\"&gt;The byte array that contains the pattern to be found&lt;/param&gt;\n /// &lt;returns&gt;If buffer contains pattern then the indexes of the occurrences of pattern within buffer; otherwise, null&lt;/returns&gt;\n /// &lt;remarks&gt;A single byte in the buffer array can only be part of one match. For example, if searching for 1,2,1 in 1,2,1,2,1 only zero would be returned.&lt;/remarks&gt;\n public static int[] ByteArrayPatternIndex(byte[] buffer, byte[] pattern)\n {\n if (buffer != null &amp;&amp; pattern != null &amp;&amp; pattern.Length &lt;= buffer.Length)\n {\n List&lt;int&gt; indexes = new List&lt;int&gt;();\n int resumeIndex;\n for (int i = 0; i &lt;= buffer.Length - pattern.Length; i++)\n {\n if (buffer[i] == pattern[0]) // Current byte equals first byte of pattern\n {\n resumeIndex = 0;\n for (int x = 1; x &lt; pattern.Length; x++)\n {\n if (buffer[i + x] == pattern[x])\n {\n if (x == pattern.Length - 1) // Matched the entire pattern\n indexes.Add(i);\n else if (resumeIndex == 0 &amp;&amp; buffer[i + x] == pattern[0]) // The current byte equals the first byte of the pattern so start here on the next outer loop iteration\n resumeIndex = i + x;\n }\n else\n {\n if (resumeIndex &gt; 0)\n i = resumeIndex - 1; // The outer loop iterator will increment so subtract one\n else if (x &gt; 1)\n i += (x - 1); // Advance the outer loop variable since we already checked these bytes\n break;\n }\n }\n }\n }\n if (indexes.Count &gt; 0)\n return indexes.ToArray();\n }\n return null;\n }\n</code></pre>\n" }, { "answer_id": 31107925, "author": "Dylan Nicholson", "author_id": 2006109, "author_profile": "https://Stackoverflow.com/users/2006109", "pm_score": 2, "selected": false, "text": "<p>My version of Foubar's answer above, which avoids searching past the end of the haystack, and allows specifying a starting offset. Assumes needle is not empty or longer than the haystack. </p>\n\n<pre><code>public static unsafe long IndexOf(this byte[] haystack, byte[] needle, long startOffset = 0)\n{ \n fixed (byte* h = haystack) fixed (byte* n = needle)\n {\n for (byte* hNext = h + startOffset, hEnd = h + haystack.LongLength + 1 - needle.LongLength, nEnd = n + needle.LongLength; hNext &lt; hEnd; hNext++)\n for (byte* hInc = hNext, nInc = n; *nInc == *hInc; hInc++)\n if (++nInc == nEnd)\n return hNext - h;\n return -1;\n }\n}\n</code></pre>\n" }, { "answer_id": 38048468, "author": "eocron", "author_id": 5639688, "author_profile": "https://Stackoverflow.com/users/5639688", "pm_score": 2, "selected": false, "text": "<p>You can use ORegex:</p>\n\n<pre><code>var oregex = new ORegex&lt;byte&gt;(\"{0}{1}{2}\", x=&gt; x==12, x=&gt; x==3, x=&gt; x==5);\nvar toSearch = new byte[]{1,1,12,3,5,1,12,3,5,5,5,5};\n\nvar found = oregex.Matches(toSearch);\n</code></pre>\n\n<p>Will be found two matches:</p>\n\n<pre><code>i:2;l:3\ni:6;l:3\n</code></pre>\n\n<p>Complexity: O(n*m) in worst case, in real life it is O(n) because of internal state machine. It is faster than .NET Regex in some cases. It is compact, fast and designed especialy for array pattern matching.</p>\n" }, { "answer_id": 38625726, "author": "Ing. Gerardo Sánchez", "author_id": 4685116, "author_profile": "https://Stackoverflow.com/users/4685116", "pm_score": 5, "selected": false, "text": "<p>This is my propossal, more simple and faster:</p>\n<pre><code>int Search(byte[] src, byte[] pattern)\n{\n int maxFirstCharSlot = src.Length - pattern.Length + 1;\n for (int i = 0; i &lt; maxFirstCharSlot; i++)\n {\n if (src[i] != pattern[0]) // compare only first byte\n continue;\n \n // found a match on first byte, now try to match rest of the pattern\n for (int j = pattern.Length - 1; j &gt;= 1; j--) \n {\n if (src[i + j] != pattern[j]) break;\n if (j == 1) return i;\n }\n }\n return -1;\n}\n</code></pre>\n<p>The logic behind this code is this: in first place it search ONLY THE FIRST BYTE (this is the key improvement) and when is found this first byte, i try to match the rest of pattern</p>\n" }, { "answer_id": 41414219, "author": "Mehmet", "author_id": 6250518, "author_profile": "https://Stackoverflow.com/users/6250518", "pm_score": 0, "selected": false, "text": "<p>I tried to understand Sanchez's proposal and make faster search.Below code's performance nearly equal.But code is more understandable.</p>\n\n<pre><code>public int Search3(byte[] src, byte[] pattern)\n {\n int index = -1;\n\n for (int i = 0; i &lt; src.Length; i++)\n {\n if (src[i] != pattern[0])\n {\n continue;\n }\n else\n {\n bool isContinoue = true;\n for (int j = 1; j &lt; pattern.Length; j++)\n {\n if (src[++i] != pattern[j])\n {\n isContinoue = true;\n break;\n }\n if(j == pattern.Length - 1)\n {\n isContinoue = false;\n }\n }\n if ( ! isContinoue)\n {\n index = i-( pattern.Length-1) ;\n break;\n }\n }\n }\n return index;\n }\n</code></pre>\n" }, { "answer_id": 51892503, "author": "Codehack", "author_id": 2513355, "author_profile": "https://Stackoverflow.com/users/2513355", "pm_score": 0, "selected": false, "text": "<p>This is my own approach on the topic. I used pointers to ensure that it is faster on larger arrays. This function will return the first occurence of the sequence (which is what I needed in my own case). </p>\n\n<p>I am sure you can modify it a little bit in order to return a list with all occurences.</p>\n\n<p>What I do is fairly simple. I loop through the source array (haystack) until I find the first byte of the pattern (needle). When the first byte is found, I continue checking separately if the next bytes match the next bytes of the pattern. If not, I continue searching as normal, from the index (in the haystack) I was previously on, before trying to match the needle.</p>\n\n<p>So here's the code:</p>\n\n<pre><code> public unsafe int IndexOfPattern(byte[] src, byte[] pattern)\n {\n fixed(byte *srcPtr = &amp;src[0])\n fixed (byte* patternPtr = &amp;pattern[0])\n {\n for (int x = 0; x &lt; src.Length; x++)\n {\n byte currentValue = *(srcPtr + x);\n\n if (currentValue != *patternPtr) continue;\n\n bool match = false;\n\n for (int y = 0; y &lt; pattern.Length; y++)\n {\n byte tempValue = *(srcPtr + x + y);\n if (tempValue != *(patternPtr + y))\n {\n match = false;\n break;\n }\n\n match = true;\n }\n\n if (match)\n return x;\n }\n }\n return -1;\n }\n</code></pre>\n\n<p>Safe code below:</p>\n\n<pre><code> public int IndexOfPatternSafe(byte[] src, byte[] pattern)\n {\n for (int x = 0; x &lt; src.Length; x++)\n {\n byte currentValue = src[x];\n if (currentValue != pattern[0]) continue;\n\n bool match = false;\n\n for (int y = 0; y &lt; pattern.Length; y++)\n {\n byte tempValue = src[x + y];\n if (tempValue != pattern[y])\n {\n match = false;\n break;\n }\n\n match = true;\n }\n\n if (match)\n return x;\n }\n\n return -1;\n }\n</code></pre>\n" }, { "answer_id": 56125234, "author": "spludlow", "author_id": 8815031, "author_profile": "https://Stackoverflow.com/users/8815031", "pm_score": 0, "selected": false, "text": "<p>I hit this problem the other day, try this:</p>\n\n<pre><code> public static long FindBinaryPattern(byte[] data, byte[] pattern)\n {\n using (MemoryStream stream = new MemoryStream(data))\n {\n return FindBinaryPattern(stream, pattern);\n }\n }\n public static long FindBinaryPattern(string filename, byte[] pattern)\n {\n using (FileStream stream = new FileStream(filename, FileMode.Open))\n {\n return FindBinaryPattern(stream, pattern);\n }\n }\n public static long FindBinaryPattern(Stream stream, byte[] pattern)\n {\n byte[] buffer = new byte[1024 * 1024];\n int patternIndex = 0;\n int read;\n while ((read = stream.Read(buffer, 0, buffer.Length)) &gt; 0)\n {\n for (int bufferIndex = 0; bufferIndex &lt; read; ++bufferIndex)\n {\n if (buffer[bufferIndex] == pattern[patternIndex])\n {\n ++patternIndex;\n if (patternIndex == pattern.Length)\n return stream.Position - (read - bufferIndex) - pattern.Length + 1;\n }\n else\n {\n patternIndex = 0;\n }\n }\n }\n return -1;\n }\n</code></pre>\n\n<p>It does nothing clever, keeps it simple.</p>\n" }, { "answer_id": 58347430, "author": "Kevinoid", "author_id": 503410, "author_profile": "https://Stackoverflow.com/users/503410", "pm_score": 3, "selected": false, "text": "<p>If you are using .NET Core 2.1 or later (or a .NET Standard 2.1 or later platform) you can use the <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.memoryextensions.indexof?view=netcore-3.0\" rel=\"nofollow noreferrer\"><code>MemoryExtensions.IndexOf</code></a> extension method with the <a href=\"https://github.com/dotnet/corefxlab/blob/master/docs/specs/span.md\" rel=\"nofollow noreferrer\">new <code>Span</code> type</a>:</p>\n<pre class=\"lang-csharp prettyprint-override\"><code>int matchIndex = toBeSearched.AsSpan().IndexOf(pattern);\n</code></pre>\n<p>To find all occurrences, you could use something like:</p>\n<pre class=\"lang-csharp prettyprint-override\"><code>public static IEnumerable&lt;int&gt; IndexesOf(this byte[] haystack, byte[] needle,\n int startIndex = 0, bool includeOverlapping = false)\n{\n int matchIndex = haystack.AsSpan(startIndex).IndexOf(needle);\n while (matchIndex &gt;= 0)\n {\n yield return startIndex + matchIndex;\n startIndex += matchIndex + (includeOverlapping ? 1 : needle.Length);\n matchIndex = haystack.AsSpan(startIndex).IndexOf(needle);\n }\n}\n</code></pre>\n<p>Unfortunately, the <a href=\"https://github.com/dotnet/corefx/blob/v3.0.0/src/Common/src/CoreLib/System/SpanHelpers.Byte.cs#L23\" rel=\"nofollow noreferrer\">implementation in .NET Core 2.1 - 3.0</a> uses an iterated &quot;optimized single-byte search on first-byte then check remainder&quot; approach rather than a <a href=\"https://stackoverflow.com/q/3183582\">fast string search algorithm</a>, but that could change in a future release. (See <a href=\"https://github.com/dotnet/runtime/issues/60866\" rel=\"nofollow noreferrer\">dotnet/runtime#60866</a>.)</p>\n" }, { "answer_id": 70309679, "author": "Philipp Schumacher", "author_id": 8712203, "author_profile": "https://Stackoverflow.com/users/8712203", "pm_score": 0, "selected": false, "text": "<p>I use a simple generic method</p>\n<pre><code>void Main()\n{\n Console.WriteLine(new[]{255,1,3,4,8,99,92,9,0,5,128}.Position(new[]{9,0}));\n \n Console.WriteLine(&quot;Philipp&quot;.ToArray().Position(&quot;il&quot;.ToArray()));\n\n Console.WriteLine(new[] { &quot;Mo&quot;, &quot;Di&quot;, &quot;Mi&quot;, &quot;Do&quot;, &quot;Fr&quot;, &quot;Sa&quot;, &quot;So&quot;,&quot;Mo&quot;, &quot;Di&quot;, &quot;Mi&quot;, &quot;Do&quot;, &quot;Fr&quot;, &quot;Sa&quot;, &quot;So&quot;}.Position(new[] { &quot;Fr&quot;, &quot;Sa&quot; }, 7));\n}\n\nstatic class Extensions\n{\n public static int Position&lt;T&gt;(this T[] source, T[] pattern, int start = 0)\n {\n var matchLenght = 0;\n foreach (var indexSource in Enumerable.Range(start, source.Length - pattern.Length))\n foreach (var indexPattern in Enumerable.Range(0, pattern.Length))\n if (source[indexSource + indexPattern].Equals(pattern[indexPattern]))\n if (++matchLenght == pattern.Length)\n return indexSource;\n return -1;\n }\n}\n</code></pre>\n<p>Output:</p>\n<pre><code>7\n2\n11\n</code></pre>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36504/" ]
Anyone know a good and effective way to search/match for a byte pattern in an byte[] array and then return the positions. For example ``` byte[] pattern = new byte[] {12,3,5,76,8,0,6,125}; byte[] toBeSearched = new byte[] {23,36,43,76,125,56,34,234,12,3,5,76,8,0,6,125,234,56,211,122,22,4,7,89,76,64,12,3,5,76,8,0,6,125} ```
May I suggest something that doesn't involve creating strings, copying arrays or unsafe code: ``` using System; using System.Collections.Generic; static class ByteArrayRocks { static readonly int[] Empty = new int[0]; public static int[] Locate (this byte[] self, byte[] candidate) { if (IsEmptyLocate(self, candidate)) return Empty; var list = new List<int>(); for (int i = 0; i < self.Length; i++) { if (!IsMatch(self, i, candidate)) continue; list.Add(i); } return list.Count == 0 ? Empty : list.ToArray(); } static bool IsMatch (byte[] array, int position, byte[] candidate) { if (candidate.Length > (array.Length - position)) return false; for (int i = 0; i < candidate.Length; i++) if (array[position + i] != candidate[i]) return false; return true; } static bool IsEmptyLocate (byte[] array, byte[] candidate) { return array == null || candidate == null || array.Length == 0 || candidate.Length == 0 || candidate.Length > array.Length; } static void Main() { var data = new byte[] { 23, 36, 43, 76, 125, 56, 34, 234, 12, 3, 5, 76, 8, 0, 6, 125, 234, 56, 211, 122, 22, 4, 7, 89, 76, 64, 12, 3, 5, 76, 8, 0, 6, 125 }; var pattern = new byte[] { 12, 3, 5, 76, 8, 0, 6, 125 }; foreach (var position in data.Locate(pattern)) Console.WriteLine(position); } } ``` **Edit (by IAbstract)** - *moving contents of [post](https://stackoverflow.com/a/283815/210709) here since it is not an answer* Out of curiosity, I've created a small benchmark with different answers. Here are the results for a million iterations: ``` solution [Locate]: 00:00:00.7714027 solution [FindAll]: 00:00:03.5404399 solution [SearchBytePattern]: 00:00:01.1105190 solution [MatchBytePattern]: 00:00:03.0658212 ```
283,460
<p>While connecting .NET to sybase server I got this error message:</p> <blockquote> <p>[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified</p> </blockquote> <p>This has worked properly before. System DSN with same details worked and data connection through vs.net also worked.</p> <p>I am using VS.NET 2005.</p> <p>Any suggestions?</p>
[ { "answer_id": 292261, "author": "user37887", "author_id": 37887, "author_profile": "https://Stackoverflow.com/users/37887", "pm_score": -1, "selected": false, "text": "<p>Perform the following steps:</p>\n\n<ol>\n<li>Start the Registry Editor by typing <code>regedit</code> in the Run window.</li>\n<li>Select the following key in the registry: <code>HKEY_LOCAL_MACHINE\\SOFTWARE\\ODBC</code>.</li>\n<li>In the Security menu, click Permissions.</li>\n<li>Grant Full Permission to the account which is being used for making connections.</li>\n<li>Quit the Registry Editor.</li>\n</ol>\n" }, { "answer_id": 5034297, "author": "SqlRyan", "author_id": 8114, "author_profile": "https://Stackoverflow.com/users/8114", "pm_score": 5, "selected": false, "text": "<p>If you're working with an x64 server, keep in mind that there are different ODBC settings for x86 and x64 applications. The \"Data Sources (ODBC)\" tool in the Administrative Tools list takes you to the x64 version. To view/edit the x86 ODBC settings, you'll need to run that version of the tool manually:</p>\n\n<pre><code>%windir%\\SysWOW64\\odbcad32.exe (%windir% is usually C:\\Windows)\n</code></pre>\n\n<p>When your app runs as x64, it will use the x64 data sources, and when it runs as x86, it will use those data sources instead.</p>\n" }, { "answer_id": 23347440, "author": "Midhun Kumar Singh Alluru", "author_id": 1815750, "author_profile": "https://Stackoverflow.com/users/1815750", "pm_score": 2, "selected": false, "text": "<p>I got a similar error, which was resolved by installing the corresponding MySQL drivers from:</p>\n\n<p><a href=\"http://www.connectionstrings.com/mysql-connector-odbc-5-2/info-and-download/\" rel=\"nofollow\">http://www.connectionstrings.com/mysql-connector-odbc-5-2/info-and-download/</a></p>\n\n<p>and by performing the following steps:</p>\n\n<ol>\n<li>Go to IIS and Application Pools in the left menu.</li>\n<li>Select <i>relevant application pool</i> which is assigned to the project.</li>\n<li>Click the <i>Set Application Pool Defaults</i>.</li>\n<li>In General Tab, set the <i>Enable 32 Bit Application</i> entry to \"True\".</li>\n</ol>\n\n<p>Reference:</p>\n\n<p><a href=\"http://www.codeproject.com/Tips/305249/ERROR-IM-Microsoft-ODBC-Driver-Manager-Data-sou\" rel=\"nofollow\">http://www.codeproject.com/Tips/305249/ERROR-IM-Microsoft-ODBC-Driver-Manager-Data-sou</a></p>\n" }, { "answer_id": 40742152, "author": "Withnail", "author_id": 1293222, "author_profile": "https://Stackoverflow.com/users/1293222", "pm_score": 0, "selected": false, "text": "<p>For anyone coming to this latterly, I was having this problem over a Windows network, and offer an additional thing to check: </p>\n\n<p>Python script connecting would work from commandline on my (linux) machine, but some users had problems connecting - that it worked from CLI suggested the DSN and credentials were right. The issue for us was that the group security policy required the ODBC credentials to be set on every machine. Once we added that (for some reason, the user had three of the four ODBC credentials they needed for our various systems), they were able to connect. </p>\n\n<p>You can of course do that at group level, but as it was a simple omission on the part of one machine, I did it in <code>Control Panel &gt; ODBC Drivers &gt; New</code> </p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
While connecting .NET to sybase server I got this error message: > > [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified > > > This has worked properly before. System DSN with same details worked and data connection through vs.net also worked. I am using VS.NET 2005. Any suggestions?
If you're working with an x64 server, keep in mind that there are different ODBC settings for x86 and x64 applications. The "Data Sources (ODBC)" tool in the Administrative Tools list takes you to the x64 version. To view/edit the x86 ODBC settings, you'll need to run that version of the tool manually: ``` %windir%\SysWOW64\odbcad32.exe (%windir% is usually C:\Windows) ``` When your app runs as x64, it will use the x64 data sources, and when it runs as x86, it will use those data sources instead.
283,464
<p>Is there any such thing as a virtual Lineprinter.I mean a software emulation of a printer, that outputs to screen.</p> <p>I have a project to change the output of print job. My past experience with a lineprinter was tedious rounds of</p> <pre><code>loop: print walk down two flights check the output walk back up two flights edit code got loop: </code></pre> <p>Anyone who thinks a lineprinter can be installed in a programmers office has not used a LinePrinter!</p> <p>Googles just turning up printer emulation, as in printers that emulate other printers or virtual printer ports!</p>
[ { "answer_id": 292261, "author": "user37887", "author_id": 37887, "author_profile": "https://Stackoverflow.com/users/37887", "pm_score": -1, "selected": false, "text": "<p>Perform the following steps:</p>\n\n<ol>\n<li>Start the Registry Editor by typing <code>regedit</code> in the Run window.</li>\n<li>Select the following key in the registry: <code>HKEY_LOCAL_MACHINE\\SOFTWARE\\ODBC</code>.</li>\n<li>In the Security menu, click Permissions.</li>\n<li>Grant Full Permission to the account which is being used for making connections.</li>\n<li>Quit the Registry Editor.</li>\n</ol>\n" }, { "answer_id": 5034297, "author": "SqlRyan", "author_id": 8114, "author_profile": "https://Stackoverflow.com/users/8114", "pm_score": 5, "selected": false, "text": "<p>If you're working with an x64 server, keep in mind that there are different ODBC settings for x86 and x64 applications. The \"Data Sources (ODBC)\" tool in the Administrative Tools list takes you to the x64 version. To view/edit the x86 ODBC settings, you'll need to run that version of the tool manually:</p>\n\n<pre><code>%windir%\\SysWOW64\\odbcad32.exe (%windir% is usually C:\\Windows)\n</code></pre>\n\n<p>When your app runs as x64, it will use the x64 data sources, and when it runs as x86, it will use those data sources instead.</p>\n" }, { "answer_id": 23347440, "author": "Midhun Kumar Singh Alluru", "author_id": 1815750, "author_profile": "https://Stackoverflow.com/users/1815750", "pm_score": 2, "selected": false, "text": "<p>I got a similar error, which was resolved by installing the corresponding MySQL drivers from:</p>\n\n<p><a href=\"http://www.connectionstrings.com/mysql-connector-odbc-5-2/info-and-download/\" rel=\"nofollow\">http://www.connectionstrings.com/mysql-connector-odbc-5-2/info-and-download/</a></p>\n\n<p>and by performing the following steps:</p>\n\n<ol>\n<li>Go to IIS and Application Pools in the left menu.</li>\n<li>Select <i>relevant application pool</i> which is assigned to the project.</li>\n<li>Click the <i>Set Application Pool Defaults</i>.</li>\n<li>In General Tab, set the <i>Enable 32 Bit Application</i> entry to \"True\".</li>\n</ol>\n\n<p>Reference:</p>\n\n<p><a href=\"http://www.codeproject.com/Tips/305249/ERROR-IM-Microsoft-ODBC-Driver-Manager-Data-sou\" rel=\"nofollow\">http://www.codeproject.com/Tips/305249/ERROR-IM-Microsoft-ODBC-Driver-Manager-Data-sou</a></p>\n" }, { "answer_id": 40742152, "author": "Withnail", "author_id": 1293222, "author_profile": "https://Stackoverflow.com/users/1293222", "pm_score": 0, "selected": false, "text": "<p>For anyone coming to this latterly, I was having this problem over a Windows network, and offer an additional thing to check: </p>\n\n<p>Python script connecting would work from commandline on my (linux) machine, but some users had problems connecting - that it worked from CLI suggested the DSN and credentials were right. The issue for us was that the group security policy required the ODBC credentials to be set on every machine. Once we added that (for some reason, the user had three of the four ODBC credentials they needed for our various systems), they were able to connect. </p>\n\n<p>You can of course do that at group level, but as it was a simple omission on the part of one machine, I did it in <code>Control Panel &gt; ODBC Drivers &gt; New</code> </p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15710/" ]
Is there any such thing as a virtual Lineprinter.I mean a software emulation of a printer, that outputs to screen. I have a project to change the output of print job. My past experience with a lineprinter was tedious rounds of ``` loop: print walk down two flights check the output walk back up two flights edit code got loop: ``` Anyone who thinks a lineprinter can be installed in a programmers office has not used a LinePrinter! Googles just turning up printer emulation, as in printers that emulate other printers or virtual printer ports!
If you're working with an x64 server, keep in mind that there are different ODBC settings for x86 and x64 applications. The "Data Sources (ODBC)" tool in the Administrative Tools list takes you to the x64 version. To view/edit the x86 ODBC settings, you'll need to run that version of the tool manually: ``` %windir%\SysWOW64\odbcad32.exe (%windir% is usually C:\Windows) ``` When your app runs as x64, it will use the x64 data sources, and when it runs as x86, it will use those data sources instead.
283,465
<p>What's your preferred way of wrapping lines of code, especially when it comes to long argument lists?</p> <p>There has been several questions relating to wrapping lines (such as <a href="https://stackoverflow.com/questions/268284/when-writing-code-do-you-wrap-text-or-not">When writing code do you wrap text or not?</a> and <a href="https://stackoverflow.com/questions/276022/line-width-formatting-standard">Line width formatting standard</a>), but I haven't been able to find one which covers where to wrap a line of code.</p> <p>Let's say we have a line of code that keeps going and going like this example:</p> <pre><code>int SomeReturnValue = SomeMethodWithLotsOfArguments(Argument1, Argument2, Argument3, Argument4); </code></pre> <p><strong>How should that be wrapped?</strong></p> <p>Here's a few ways I can think of, and some of their downsides:</p> <pre><code>int SomeReturnValue = SomeMethodWithLotsOfArguments(Argument1, Argument2, Argument3, Argument4); </code></pre> <p>I personally don't prefer that option because the formatting seems to visually separate the argument list from the method I am trying to call, especially since there is an assignment equals sign ("=") right above the orphanged arguments on the new line.</p> <p>So, for a while I went with the following approach:</p> <pre><code>int SomeReturnValue = SomeMethodWithLotsOfArguments(Argument1, Argument2, Argument3, Argument4); </code></pre> <p>Here, the arguments are all bundled together, all on the side of the method's first argument. However, one catch is that the argument list won't always line up in the second line onwards because of the number of spaces that the tab indents. (And typing extra spaces for formatting would be too time consuming.)</p> <p>An <a href="https://stackoverflow.com/questions/268284/when-writing-code-do-you-wrap-text-or-not#269025">answer</a> in the one of the previous questions suggested the following format:</p> <pre><code>int SomeReturnValue = SomeMethodWithLotsOfArguments( Argument1, Argument2, Argument3, Argument4 ); </code></pre> <p>I actually like this format, due to its visual appeal, but it also it does visually separate the arguments from the method that the list belongs to. Also, I prefer to have a single method call not take up too many lines.</p> <p>So, my question is, <em>without getting into the issue of preventing a code of line from getting too long in the first place</em>, <strong>how would you recommend wrapping lines of code?</strong> Specifically, <strong>where is a good place to break a line of code, when it comes to long argument lists?</strong></p>
[ { "answer_id": 283483, "author": "Dheer", "author_id": 17266, "author_profile": "https://Stackoverflow.com/users/17266", "pm_score": 4, "selected": false, "text": "<p>The option 3 suggested</p>\n\n<pre><code>int SomeReturnValue = SomeMethodWithLotsOfArguments(\n Argument1,\n Argument2,\n Argument3,\n Argument4\n);\n</code></pre>\n\n<p>is a better way as it gives a good feel.\nIf the lengths of arguments are more or less same, then we can put them together so that they line up as a table for example</p>\n\n<pre><code>int SomeReturnValue = SomeMethodWithLotsOfArguments(\n Argument1, Argument2, Argument3, Argument4,\n Argument005, Argument006, Argument7, Argument8\n);\n</code></pre>\n" }, { "answer_id": 283493, "author": "Galwegian", "author_id": 3201, "author_profile": "https://Stackoverflow.com/users/3201", "pm_score": 0, "selected": false, "text": "<p>In functions with long parameter list, I wrap after each one or two parameters for readability (always keeping the same number of parameters on each line):</p>\n\n<pre><code>int SomeReturnValue = SomeMethodWithLotsOfArguments(Argument1,\n Argument2,\n Argument3,\n Argument4);\n</code></pre>\n\n<p>OR</p>\n\n<pre><code>int SomeReturnValue = SomeMethodWithLotsOfArguments(Argument1, Argument2,\n Argument3, Argument4);\n</code></pre>\n\n<p>depending on the list/parameter length.</p>\n" }, { "answer_id": 283578, "author": "kenny", "author_id": 3225, "author_profile": "https://Stackoverflow.com/users/3225", "pm_score": 4, "selected": false, "text": "<pre><code>int SomeReturnValue = SomeMethodWithLotsOfArguments\n( Argument1,\n Argument2,\n Argument3,\n Argument4\n);\n</code></pre>\n" }, { "answer_id": 283579, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 2, "selected": false, "text": "<p>Personally, I dislike the second option, too close of Ascii art, with its inconveniences in code: change the name of the function, you have to re-indent all arguments. And somehow it bloats the file. Plus it doesn't do work well if you use hard tabs in code.</p>\n\n<p>Most of the time, I use the first option, but I adopted the Eclipse rule of two indents for continuation lines, as it stands out better from normal indentation (particularly if you split conditional instructions).</p>\n\n<p>Sometime I use the second option, eg. if the opening parenthesis is already near of my line length limit...<br>\nAdvantage: you can add a line comment after each parameter.<br>\nOr I do like Dheer, grouping arguments until they fill the line width.</p>\n\n<p>The fact the arguments are separated from the function name never bothered me, they are still near and quite grouped. At worst, I can put blank lines around the function call.</p>\n" }, { "answer_id": 283647, "author": "Inshallah", "author_id": 36862, "author_profile": "https://Stackoverflow.com/users/36862", "pm_score": 1, "selected": false, "text": "<p>I always break before the assignment if that leaves the righthandside unbroken.\nThis is usful in languages like Java, where you have to explictly declare the type of the value that's assigned.</p>\n\n<pre><code>SomeVeryVerboseTypeName SomeReturnValue\n = SomeMethodWithLotsOfArguments(Argument1, Argument2, ...);\n</code></pre>\n" }, { "answer_id": 283655, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 0, "selected": false, "text": "<p>I also use the ‘consistent indenting option’ as quoted by Edward Kmett. If there are a <em>lot</em> of arguments I tend to line-group them by relatedness where possible.</p>\n\n<p>But for this particular example I'd probably leave it on one line, it's not <em>that</em> long.</p>\n\n<p>I can't stand the ‘dangling wrap’ format as it can easily provide visual confusion conflicting with the (much more important) indenting. Dangling wraps are considered the ‘default’ style for many languages at the moment, but I don't know how it got that way. It's IMHO horrible.</p>\n" }, { "answer_id": 283670, "author": "bendin", "author_id": 33412, "author_profile": "https://Stackoverflow.com/users/33412", "pm_score": 1, "selected": false, "text": "<p>For me, it depends on just how long the argument list is. I don't like end of line layout much and it almost requires for editor support (e.g. emacs) to do it well.</p>\n\n<p>If the method call is short enough to get it on one line, I'll do this:</p>\n\n<pre><code>int SomeReturnValue =\n SomeMethodWithLotsOfArguments(Argument1, Argument2, ...);\n</code></pre>\n\n<p>If method and variable fit on one line and arguments on another, I've done this:</p>\n\n<pre><code>int SomeReturnValue = SomeMethodWithLotsOfArguments\n (Argument1, Argument2, ... );\n</code></pre>\n\n<p>That makes my LISPy heart smile, but drive my colleagues nuts, so I've relented:</p>\n\n<pre><code>int SomeReturnValue = SomeMethodWithLotsOfArguments(\n Argument1, Argument2, ... );\n</code></pre>\n\n<p>I guess I'm just trying to say I haven't found a solution I'm really happy with, though this has some appeal for the really overlong cases due to its similarity to how we lay out curlies:</p>\n\n<pre><code>int SomeReturnValue = SomeMethodWithLotsOfArguments(\n Argument1, \n Argument2,\n);\n</code></pre>\n" }, { "answer_id": 283798, "author": "basszero", "author_id": 287, "author_profile": "https://Stackoverflow.com/users/287", "pm_score": 1, "selected": false, "text": "<p>warning: I use IDEs. If you're not an IDE user, just skip this.</p>\n\n<p>When working with others:</p>\n\n<p>I tend to stick with whatever convention is currently adopted by the team. Even better if the team uses an IDE with code format support. Always stick w/ the team/IDE format conventions. Can't tell you how many times I've been burned by \"version-contro-diff-hell-due-to-reformats\"</p>\n\n<p>When working alone:</p>\n\n<p>I string the method on, line length isn't a problem for me. I've got a nice widescreen monitor and horizontal scrollbars were invented for a reason. On top of that, navigating source code is much more than visually scrolling now that many IDEs have utilities like call trees, find references, and refactoring tools.</p>\n" }, { "answer_id": 283818, "author": "Anders Sandvig", "author_id": 1709, "author_profile": "https://Stackoverflow.com/users/1709", "pm_score": 3, "selected": false, "text": "<p>I prefer this way:</p>\n\n<pre><code>int SomeReturnValue = SomeMethodWithLotsOfArguments(Argument1, Argument2, \n Argument3, Argument4);\n</code></pre>\n\n<p>Where the line ends closest to your current max line width (whatever that is) and the next line is indented your usual indent level (whatever that is) relative to the equals sign.</p>\n\n<p>Not sure why, but I think it's the most readable option in most situations. However, I chose not to be pedantic about these things and I always prefer whatever is most readable for a given section of code, even if that may break some indenting or formatting rules (within limits, of course).</p>\n\n<p>One example of this would be if the function required many arguments or the argiments where themselves complex, then I might chose something like this instead:</p>\n\n<pre><code>int SomeReturnValue = SomeMethodWithLotsOfArguments(\n Argument1 + Expression1 + Expression2, \n Argument2 - Expression3 * Expression4, \n Argument3, \n Argument4 * Expression5 + Expression6 - Expression7);\n</code></pre>\n\n<p>Of course, if the argument expressions are very long or complex it would be better to do the calculations before the function call and use temporary values to store the results.</p>\n" }, { "answer_id": 283846, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 1, "selected": false, "text": "<p>There is no definitive answer for me on this. I do it on a case by case basis. If the function name is long, i definitely don't indent the other arguments to the same column as the previous arguments. If the function name is short, i usually indent following arguments to the same column, collecting as many arguments i can on one line (not one argument = one line). But if there is some pleasing symmetry, like in </p>\n\n<pre><code>int a = foo(a + b,\n c + d);\n</code></pre>\n\n<p>i would probably break that rule, and have the same number of arguments on each line.</p>\n" }, { "answer_id": 283876, "author": "Martin Cote", "author_id": 9936, "author_profile": "https://Stackoverflow.com/users/9936", "pm_score": 3, "selected": false, "text": "<p>I try to keep the lines short. In this case, I would break before the assignment and after each parameter. I also put the comma at the beginning of the line to make it easy to add new arguments:</p>\n\n<pre><code>int SomeReturnValue \n = SomeMethodWithLotsOfArguments(\n Argument1\n , Argument2\n , Argument3\n , Argument4\n );\n</code></pre>\n\n<p>Using this kind of layout is a lot of work in Visual Studio, but Emacs makes it automatic for me.</p>\n" }, { "answer_id": 283948, "author": "MikeJ", "author_id": 10676, "author_profile": "https://Stackoverflow.com/users/10676", "pm_score": 1, "selected": false, "text": "<p>Most have made great suggestions about indenting and this is great for API functions that you don't control. If you do control the API, I would suggest that once you ahve more than 3 arguments you should create some form of structure and pass the structure to the routine. Once you get above 3 arguments the chance of passing them in the wrong order goes way, way up. It also gives more visibility to the type and meaning of the parameters.</p>\n\n<pre><code>someStruct.x = somevalue;\nsomestruct.y = someothervalue;\n\nint someResturnValue - SomeMethod(somestruct);\n</code></pre>\n" }, { "answer_id": 24954701, "author": "Abdillah", "author_id": 1391782, "author_profile": "https://Stackoverflow.com/users/1391782", "pm_score": 1, "selected": false, "text": "<h3>First</h3>\n\n<p>If the args short enough and have (almost) similar length, I think below visually good enough</p>\n\n<pre><code>int variable_with_really_long_name = functionWhichDoMore(Argument1, ArgumentA2, \n ArgumentA3, Argument4, \n ArgumentA5, Argument6);\n</code></pre>\n\n<h3>Second</h3>\n\n<p>When It getting worse, one column of argument really help</p>\n\n<pre><code>int variable_with_really_long_name = somefunctionWhichDoMore(Argument_Expand1, \n Argument2, \n Argument_Expand3, \n Argument_Expand4, \n Argument_Expand5, \n Argument6);\n</code></pre>\n\n<h3>Third</h3>\n\n<p>But, now, How if it is worsen! What now? Try this one</p>\n\n<pre><code>int variable_with_really_long_name = someFunctionWhichDoMore\n (\n Argument_Expand_More1, \n Argument_Expand_More2, \n Argument_Expand3, Argument4, \n Argument_Expand_More5, Argument6\n );\n</code></pre>\n\n<p>By the way, if you want a consistent look, use the third in all condition above.</p>\n\n<p>Justify : Neatly put on and we know that it is a function call with lots of (6) args. And I like my code looks neat and <code>!(so_ugly)</code>.</p>\n\n<p><em>Critics are welcome. Please comment up.</em></p>\n" }, { "answer_id": 25313265, "author": "Gio", "author_id": 3200088, "author_profile": "https://Stackoverflow.com/users/3200088", "pm_score": 0, "selected": false, "text": "<p>I prefer the following</p>\n\n<pre><code>int variable_with_really_long_name = functionWhichDoMore(\n Argument1, ArgumentA2, ArgumentA3, Argument4, \n ArgumentA5, Argument6);\n\nint i = foo(Argument1, ArgumentA2, ArgumentA3, Argument4, \n ArgumentA5, Argument6);\n</code></pre>\n\n<p>Both are consistent with each other, when reaching 80 chars, I go the next line and place 2 indents of 4 spaces each. My argumentation for this is as follows:</p>\n\n<ul>\n<li><p>I use 2 indents of 4 spaces each, in order to clearly visualize the fact that it concerns a wrapped line and not an indented code block.</p></li>\n<li><p>This way of indenting keeps the code nicely indented because it always follows the same indenting pattern, 2 indents for line wrapping, 1 indent for code blocks.</p></li>\n<li><p>Placing every argument on a separate line can result in very large methods, hence I prefer arguments sequentially on one or more lines.</p></li>\n<li><p>This way of line wrapping can be configured in an IDE such as Eclipse, providing the ability of auto-formatting.</p></li>\n</ul>\n\n<p>However there is one important note, there can be exceptional cases where the following occurs:</p>\n\n<pre><code>int variable_with_really_long_name = functionWhichDoMore(arg1,\n arg2)\n</code></pre>\n\n<p>I will try to avoid this, if it happens I will do the following</p>\n\n<pre><code>int variable_with_really_long_name = functionWhichDoMore(arg1, arg2)\n</code></pre>\n\n<p>Yes, I will pas my 120 char max. code line length convention, my convention is actually flexible on this, max 120 to 140 chars, normally I wrap after 120, however in this case I will go to max. 140 chars. The disadvantage of this is of course that it cannot be configured for auto-formatting in an IDE such as eclipse.</p>\n\n<p>ps. I know some people think 120 chars is way to much for code line length, but that's an whole other discussion. The conventions above can of course also be applied for 80 / 100 chars.</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283465", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17172/" ]
What's your preferred way of wrapping lines of code, especially when it comes to long argument lists? There has been several questions relating to wrapping lines (such as [When writing code do you wrap text or not?](https://stackoverflow.com/questions/268284/when-writing-code-do-you-wrap-text-or-not) and [Line width formatting standard](https://stackoverflow.com/questions/276022/line-width-formatting-standard)), but I haven't been able to find one which covers where to wrap a line of code. Let's say we have a line of code that keeps going and going like this example: ``` int SomeReturnValue = SomeMethodWithLotsOfArguments(Argument1, Argument2, Argument3, Argument4); ``` **How should that be wrapped?** Here's a few ways I can think of, and some of their downsides: ``` int SomeReturnValue = SomeMethodWithLotsOfArguments(Argument1, Argument2, Argument3, Argument4); ``` I personally don't prefer that option because the formatting seems to visually separate the argument list from the method I am trying to call, especially since there is an assignment equals sign ("=") right above the orphanged arguments on the new line. So, for a while I went with the following approach: ``` int SomeReturnValue = SomeMethodWithLotsOfArguments(Argument1, Argument2, Argument3, Argument4); ``` Here, the arguments are all bundled together, all on the side of the method's first argument. However, one catch is that the argument list won't always line up in the second line onwards because of the number of spaces that the tab indents. (And typing extra spaces for formatting would be too time consuming.) An [answer](https://stackoverflow.com/questions/268284/when-writing-code-do-you-wrap-text-or-not#269025) in the one of the previous questions suggested the following format: ``` int SomeReturnValue = SomeMethodWithLotsOfArguments( Argument1, Argument2, Argument3, Argument4 ); ``` I actually like this format, due to its visual appeal, but it also it does visually separate the arguments from the method that the list belongs to. Also, I prefer to have a single method call not take up too many lines. So, my question is, *without getting into the issue of preventing a code of line from getting too long in the first place*, **how would you recommend wrapping lines of code?** Specifically, **where is a good place to break a line of code, when it comes to long argument lists?**
The option 3 suggested ``` int SomeReturnValue = SomeMethodWithLotsOfArguments( Argument1, Argument2, Argument3, Argument4 ); ``` is a better way as it gives a good feel. If the lengths of arguments are more or less same, then we can put them together so that they line up as a table for example ``` int SomeReturnValue = SomeMethodWithLotsOfArguments( Argument1, Argument2, Argument3, Argument4, Argument005, Argument006, Argument7, Argument8 ); ```
283,468
<p>In C# you can use verbatim strings like this:</p> <pre><code>@"\\server\share\file.txt" </code></pre> <p>Is there something similar in JavaScript?</p>
[ { "answer_id": 283642, "author": "Timothy Khouri", "author_id": 11917, "author_profile": "https://Stackoverflow.com/users/11917", "pm_score": 5, "selected": true, "text": "<p>No, there isn't support for that in JavaScript. And that workaround seems very problematic as you now lose the ability to have forward slashes.</p>\n\n<p>I've run into this issue myself when I needed to build an alert message or something from an ASP.NET back end, and stick it in a JavaScript alert on the front end. The issue was that developers could enter anything in the Page.Alert() method.</p>\n\n<p>What I did to solve this was as follows:</p>\n\n<pre><code>public void Alert(string message)\n{\n message = message.Replace(\"\\\\\", \"\\\\\\\\\")\n .Replace(\"\\r\\n\", \"\\n\")\n .Replace(\"\\n\", \"\\\\n\")\n .Replace(\"\\t\", \"\\\\t\")\n .Replace(\"\\\"\", \"\\\\\\\"\");\n\n // and now register my JavaScript with this safe string.\n}\n</code></pre>\n" }, { "answer_id": 284022, "author": "James Hughes", "author_id": 34671, "author_profile": "https://Stackoverflow.com/users/34671", "pm_score": 2, "selected": false, "text": "<p>I'll re-iterate what's been said before - verbatim strings aren't possible in javascript. It's actually easy to escape valid escape characters like <code>\\n \\\\ \\t</code> etc but the problem comes from escaping non-valid characters due to the way they are handled in the different functions they become incompatible. For example</p>\n\n<pre><code>\"\\a\".replace(\"\\a\",\"\\\\a\") // WORKS \\a\n\"aa\\a\".replace(\"\\a\", \"\\\\a\") // FAILS \\aaa\n</code></pre>\n\n<p>Also if you look at an array of illegal special characters eg <code>[\"\\a\"]</code> the character will just look like an <code>a</code>. This makes doing what you want essentially impossible.</p>\n\n<p>Hope that at least clears it up for you.</p>\n" }, { "answer_id": 284483, "author": "Mr. Muskrat", "author_id": 2657951, "author_profile": "https://Stackoverflow.com/users/2657951", "pm_score": 2, "selected": false, "text": "<p>Big kludge of a workaround...</p>\n\n<pre><code>&lt;html&gt;\n&lt;head&gt;\n&lt;script&gt;\nfunction foo() {\n var string = document.getElementById('foo').innerHTML;\n alert(string);\n}\nwindow.onload=foo;\n&lt;/script&gt;\n&lt;style&gt;\n#foo{\n display: none;\n}\n&lt;/style&gt;\n&lt;/head&gt;\n&lt;body&gt;\nCalling foo on page load.\n&lt;div id=\"foo\"&gt;\\\\server\\path\\to\\file.txt&lt;/div&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 35571428, "author": "John Leidegren", "author_id": 58961, "author_profile": "https://Stackoverflow.com/users/58961", "pm_score": 4, "selected": false, "text": "<p><strong>Template strings</strong> do support line breaks.</p>\n<pre><code>`so you can\ndo this if you want`\n</code></pre>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals\" rel=\"noreferrer\">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals</a></p>\n<p>It does not of course prevent expansion from occurring the in the text, and by extension, code execution but maybe that's a good thing?</p>\n<blockquote>\n<p><strong>Note:</strong> I don't think there's a way to take an existing string and run it through expression interpolation. This makes it impossible to inject code this way since the code has to originate in the source. I don't know of an API that can do expression interpolation on-demand.</p>\n<p><strong>Note 2:</strong> Template strings are a ES2015 / ES6 feature. Support in every browser except (wait for it...) IE! However, Edge does support template strings.</p>\n<p><strong>Note 3:</strong> Template strings expand escape sequences, if you have a string inside a string that string will expand its escape sequences.</p>\n<pre><code>`&quot;A\\nB&quot;`\n</code></pre>\n<p>...will result in:</p>\n<pre><code>&quot;A\nB&quot;\n</code></pre>\n<p>...which will not work with <code>JSON.parse</code> because there's now a new-line in the string literal. Might be good to know.</p>\n</blockquote>\n" }, { "answer_id": 35681749, "author": "estani", "author_id": 1182464, "author_profile": "https://Stackoverflow.com/users/1182464", "pm_score": 3, "selected": false, "text": "<p>This is a very old thread, but still here's a workaround:</p>\n\n<pre><code>function verbatim(fn){return fn.toString().match(/[^]*\\/\\*\\s*([^]*)\\s*\\*\\/\\}$/)[1]}\n</code></pre>\n\n<p>Which you will use as this:</p>\n\n<pre><code>var myText = verbatim(function(){/*This\n is a multiline \\a\\n\\0 verbatim line*/})\n</code></pre>\n\n<p>Basically what happens here is that js treats comments indeed as verbatim strings. Furthermore, these are store along with the function. So what happens here is that we create a function with some verbatim comments which we extract in the verbatim function.</p>\n" }, { "answer_id": 44212558, "author": "LitoMore", "author_id": 7819703, "author_profile": "https://Stackoverflow.com/users/7819703", "pm_score": 4, "selected": false, "text": "<p>Just use <code>String.raw()</code></p>\n\n<pre><code>String.raw`\\n`\n</code></pre>\n\n<p>will output</p>\n\n<pre><code>\\\\n\n</code></pre>\n\n<hr>\n\n<p>But I don't know how to solve the case:</p>\n\n<pre><code>String.raw`hello`hello` // It will throw an TypeError\nString.raw`hello\\`hello` // Output is 'hello\\\\`hello'\n</code></pre>\n\n<p>I don't know how to deal with <code>`</code> :(</p>\n" }, { "answer_id": 63055984, "author": "Numan Bin Tariq", "author_id": 9097483, "author_profile": "https://Stackoverflow.com/users/9097483", "pm_score": 2, "selected": false, "text": "<p>Yes, we can use static <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/raw\" rel=\"nofollow noreferrer\">String.raw()</a>.It was introduced in ECMAScript 6 (ES6). This is similar to the r prefix in Python, or the @ prefix in C# for string literals.</p>\n<p>This is used to get the raw string form of template strings (that is the original, uninterpreted text).</p>\n<p>Syntax:</p>\n<pre><code>String.raw(callSite, ...substitutions)\nor \nString.raw`template string`\n</code></pre>\n<p>Example:</p>\n<pre><code>const filePath_SimpleString = 'C:\\\\Development\\\\profile\\\\aboutme.html';\nconst filePath_RawString = String.raw`C:\\Development\\profile\\aboutme.html`;\n \nconsole.log(`The file was uploaded from: ${filePath}`);\nconsole.log(`The file was uploaded from: ${filePath}`);\n \n// expected output will be same: \n//&quot;The file was uploaded from: C:\\Development\\profile\\aboutme.html&quot;\n</code></pre>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4830/" ]
In C# you can use verbatim strings like this: ``` @"\\server\share\file.txt" ``` Is there something similar in JavaScript?
No, there isn't support for that in JavaScript. And that workaround seems very problematic as you now lose the ability to have forward slashes. I've run into this issue myself when I needed to build an alert message or something from an ASP.NET back end, and stick it in a JavaScript alert on the front end. The issue was that developers could enter anything in the Page.Alert() method. What I did to solve this was as follows: ``` public void Alert(string message) { message = message.Replace("\\", "\\\\") .Replace("\r\n", "\n") .Replace("\n", "\\n") .Replace("\t", "\\t") .Replace("\"", "\\\""); // and now register my JavaScript with this safe string. } ```
283,470
<p>i get the following error when trying to run a flex application (which has been working fine!). I was playing around with some different setttings trying to optimize the compiled size. I've put these settings back to the defaults as much as I thought but still getting issues.</p> <p>I remember getting this error before but cant seem to remember how I fixed it - nor any useful information about how to fix it again! </p> <p>Anybody know?</p> <p>VerifyError: Error #1014: Class IAutomationObject could not be found.</p> <pre><code>at flash.display::MovieClip/nextFrame() at mx.managers::SystemManager/deferredNextFrame()[E:\dev\3.1.0\frameworks\projects\framework\src\mx\managers\SystemManager.as:299] at mx.managers::SystemManager/preloader_initProgressHandler()[E:\dev\3.1.0\frameworks\projects\framework\src\mx\managers\SystemManager.as:2225] at flash.events::EventDispatcher/dispatchEventFunction() at flash.events::EventDispatcher/dispatchEvent() at mx.preloaders::Preloader/timerHandler()[E:\dev\3.1.0\frameworks\projects\framework\src\mx\preloaders\Preloader.as:398] at flash.utils::Timer/_timerDispatch() at flash.utils::Timer/tick() </code></pre>
[ { "answer_id": 283642, "author": "Timothy Khouri", "author_id": 11917, "author_profile": "https://Stackoverflow.com/users/11917", "pm_score": 5, "selected": true, "text": "<p>No, there isn't support for that in JavaScript. And that workaround seems very problematic as you now lose the ability to have forward slashes.</p>\n\n<p>I've run into this issue myself when I needed to build an alert message or something from an ASP.NET back end, and stick it in a JavaScript alert on the front end. The issue was that developers could enter anything in the Page.Alert() method.</p>\n\n<p>What I did to solve this was as follows:</p>\n\n<pre><code>public void Alert(string message)\n{\n message = message.Replace(\"\\\\\", \"\\\\\\\\\")\n .Replace(\"\\r\\n\", \"\\n\")\n .Replace(\"\\n\", \"\\\\n\")\n .Replace(\"\\t\", \"\\\\t\")\n .Replace(\"\\\"\", \"\\\\\\\"\");\n\n // and now register my JavaScript with this safe string.\n}\n</code></pre>\n" }, { "answer_id": 284022, "author": "James Hughes", "author_id": 34671, "author_profile": "https://Stackoverflow.com/users/34671", "pm_score": 2, "selected": false, "text": "<p>I'll re-iterate what's been said before - verbatim strings aren't possible in javascript. It's actually easy to escape valid escape characters like <code>\\n \\\\ \\t</code> etc but the problem comes from escaping non-valid characters due to the way they are handled in the different functions they become incompatible. For example</p>\n\n<pre><code>\"\\a\".replace(\"\\a\",\"\\\\a\") // WORKS \\a\n\"aa\\a\".replace(\"\\a\", \"\\\\a\") // FAILS \\aaa\n</code></pre>\n\n<p>Also if you look at an array of illegal special characters eg <code>[\"\\a\"]</code> the character will just look like an <code>a</code>. This makes doing what you want essentially impossible.</p>\n\n<p>Hope that at least clears it up for you.</p>\n" }, { "answer_id": 284483, "author": "Mr. Muskrat", "author_id": 2657951, "author_profile": "https://Stackoverflow.com/users/2657951", "pm_score": 2, "selected": false, "text": "<p>Big kludge of a workaround...</p>\n\n<pre><code>&lt;html&gt;\n&lt;head&gt;\n&lt;script&gt;\nfunction foo() {\n var string = document.getElementById('foo').innerHTML;\n alert(string);\n}\nwindow.onload=foo;\n&lt;/script&gt;\n&lt;style&gt;\n#foo{\n display: none;\n}\n&lt;/style&gt;\n&lt;/head&gt;\n&lt;body&gt;\nCalling foo on page load.\n&lt;div id=\"foo\"&gt;\\\\server\\path\\to\\file.txt&lt;/div&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 35571428, "author": "John Leidegren", "author_id": 58961, "author_profile": "https://Stackoverflow.com/users/58961", "pm_score": 4, "selected": false, "text": "<p><strong>Template strings</strong> do support line breaks.</p>\n<pre><code>`so you can\ndo this if you want`\n</code></pre>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals\" rel=\"noreferrer\">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals</a></p>\n<p>It does not of course prevent expansion from occurring the in the text, and by extension, code execution but maybe that's a good thing?</p>\n<blockquote>\n<p><strong>Note:</strong> I don't think there's a way to take an existing string and run it through expression interpolation. This makes it impossible to inject code this way since the code has to originate in the source. I don't know of an API that can do expression interpolation on-demand.</p>\n<p><strong>Note 2:</strong> Template strings are a ES2015 / ES6 feature. Support in every browser except (wait for it...) IE! However, Edge does support template strings.</p>\n<p><strong>Note 3:</strong> Template strings expand escape sequences, if you have a string inside a string that string will expand its escape sequences.</p>\n<pre><code>`&quot;A\\nB&quot;`\n</code></pre>\n<p>...will result in:</p>\n<pre><code>&quot;A\nB&quot;\n</code></pre>\n<p>...which will not work with <code>JSON.parse</code> because there's now a new-line in the string literal. Might be good to know.</p>\n</blockquote>\n" }, { "answer_id": 35681749, "author": "estani", "author_id": 1182464, "author_profile": "https://Stackoverflow.com/users/1182464", "pm_score": 3, "selected": false, "text": "<p>This is a very old thread, but still here's a workaround:</p>\n\n<pre><code>function verbatim(fn){return fn.toString().match(/[^]*\\/\\*\\s*([^]*)\\s*\\*\\/\\}$/)[1]}\n</code></pre>\n\n<p>Which you will use as this:</p>\n\n<pre><code>var myText = verbatim(function(){/*This\n is a multiline \\a\\n\\0 verbatim line*/})\n</code></pre>\n\n<p>Basically what happens here is that js treats comments indeed as verbatim strings. Furthermore, these are store along with the function. So what happens here is that we create a function with some verbatim comments which we extract in the verbatim function.</p>\n" }, { "answer_id": 44212558, "author": "LitoMore", "author_id": 7819703, "author_profile": "https://Stackoverflow.com/users/7819703", "pm_score": 4, "selected": false, "text": "<p>Just use <code>String.raw()</code></p>\n\n<pre><code>String.raw`\\n`\n</code></pre>\n\n<p>will output</p>\n\n<pre><code>\\\\n\n</code></pre>\n\n<hr>\n\n<p>But I don't know how to solve the case:</p>\n\n<pre><code>String.raw`hello`hello` // It will throw an TypeError\nString.raw`hello\\`hello` // Output is 'hello\\\\`hello'\n</code></pre>\n\n<p>I don't know how to deal with <code>`</code> :(</p>\n" }, { "answer_id": 63055984, "author": "Numan Bin Tariq", "author_id": 9097483, "author_profile": "https://Stackoverflow.com/users/9097483", "pm_score": 2, "selected": false, "text": "<p>Yes, we can use static <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/raw\" rel=\"nofollow noreferrer\">String.raw()</a>.It was introduced in ECMAScript 6 (ES6). This is similar to the r prefix in Python, or the @ prefix in C# for string literals.</p>\n<p>This is used to get the raw string form of template strings (that is the original, uninterpreted text).</p>\n<p>Syntax:</p>\n<pre><code>String.raw(callSite, ...substitutions)\nor \nString.raw`template string`\n</code></pre>\n<p>Example:</p>\n<pre><code>const filePath_SimpleString = 'C:\\\\Development\\\\profile\\\\aboutme.html';\nconst filePath_RawString = String.raw`C:\\Development\\profile\\aboutme.html`;\n \nconsole.log(`The file was uploaded from: ${filePath}`);\nconsole.log(`The file was uploaded from: ${filePath}`);\n \n// expected output will be same: \n//&quot;The file was uploaded from: C:\\Development\\profile\\aboutme.html&quot;\n</code></pre>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16940/" ]
i get the following error when trying to run a flex application (which has been working fine!). I was playing around with some different setttings trying to optimize the compiled size. I've put these settings back to the defaults as much as I thought but still getting issues. I remember getting this error before but cant seem to remember how I fixed it - nor any useful information about how to fix it again! Anybody know? VerifyError: Error #1014: Class IAutomationObject could not be found. ``` at flash.display::MovieClip/nextFrame() at mx.managers::SystemManager/deferredNextFrame()[E:\dev\3.1.0\frameworks\projects\framework\src\mx\managers\SystemManager.as:299] at mx.managers::SystemManager/preloader_initProgressHandler()[E:\dev\3.1.0\frameworks\projects\framework\src\mx\managers\SystemManager.as:2225] at flash.events::EventDispatcher/dispatchEventFunction() at flash.events::EventDispatcher/dispatchEvent() at mx.preloaders::Preloader/timerHandler()[E:\dev\3.1.0\frameworks\projects\framework\src\mx\preloaders\Preloader.as:398] at flash.utils::Timer/_timerDispatch() at flash.utils::Timer/tick() ```
No, there isn't support for that in JavaScript. And that workaround seems very problematic as you now lose the ability to have forward slashes. I've run into this issue myself when I needed to build an alert message or something from an ASP.NET back end, and stick it in a JavaScript alert on the front end. The issue was that developers could enter anything in the Page.Alert() method. What I did to solve this was as follows: ``` public void Alert(string message) { message = message.Replace("\\", "\\\\") .Replace("\r\n", "\n") .Replace("\n", "\\n") .Replace("\t", "\\t") .Replace("\"", "\\\""); // and now register my JavaScript with this safe string. } ```
283,471
<p>I know you can do it file by file.</p> <p>Is there any way to do this in one step for all files in a project?</p>
[ { "answer_id": 283474, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 5, "selected": true, "text": "<p>Do you mean using statements? First, note that they generally do no harm other that take space.\nTools like <a href=\"http://www.jetbrains.com/resharper/\" rel=\"noreferrer\">ReSharper</a> offer automated tricks to do this, however: there was a <a href=\"http://blogs.msdn.com/djpark/archive/2008/08/16/organize-usings-across-your-entire-solution.aspx\" rel=\"noreferrer\">link in the VS feed</a> a little while ago; it boils down to:</p>\n\n<ul>\n<li>go to Tools -> Macros -> Macros IDE...</li>\n<li>in the Project Explorer, Add -> Add Module... (put in a name - I've used OrganiseUsings)</li>\n<li>paste over with the code below</li>\n<li>File -> Save MyMacros, exit</li>\n</ul>\n\n<p>Now if you right-click on the toolbar and Customize... - you should be able to find MyMacros.OrganiseUsings.RemoveAndSortAll - drag this somewhere handy (maybe the Tools menu; you might also want to change the name after placing it).</p>\n\n<p>You can now use this option to run the Remove and Sort command for an entire solution. A big time-saver.</p>\n\n<p>==== code ====</p>\n\n<pre><code>Imports System\nImports EnvDTE\nImports EnvDTE80\nImports EnvDTE90\nImports System.Diagnostics\n\nPublic Module OrganiseUsings\n\n Public Sub RemoveAndSortAll()\n On Error Resume Next\n Dim sol As Solution = DTE.Solution\n\n For i As Integer = 1 To sol.Projects.Count \n Dim proj As Project = sol.Projects.Item(i) \n For j As Integer = 1 To proj.ProjectItems.Count \n RemoveAndSortSome(proj.ProjectItems.Item(j)) \n Next \n Next \n End Sub \n\n Private Sub RemoveAndSortSome(ByVal projectItem As ProjectItem)\n On Error Resume Next\n If projectItem.Kind = Constants.vsProjectItemKindPhysicalFile Then \n If projectItem.Name.LastIndexOf(\".cs\") = projectItem.Name.Length - 3 Then\n Dim window As Window = projectItem.Open(Constants.vsViewKindCode)\n\n window.Activate()\n\n projectItem.Document.DTE.ExecuteCommand(\"Edit.RemoveAndSort\")\n\n window.Close(vsSaveChanges.vsSaveChangesYes)\n End If \n End If \n\n For i As Integer = 1 To projectItem.ProjectItems.Count \n RemoveAndSortSome(projectItem.ProjectItems.Item(i)) \n Next\n End Sub \n\nEnd Module\n</code></pre>\n" }, { "answer_id": 283482, "author": "Mesh", "author_id": 15710, "author_profile": "https://Stackoverflow.com/users/15710", "pm_score": 2, "selected": false, "text": "<p>If you do mean 'using' Power Commands contains this functionality + a boat load more.</p>\n\n<p><a href=\"http://code.msdn.microsoft.com/PowerCommands\" rel=\"nofollow noreferrer\">http://code.msdn.microsoft.com/PowerCommands</a></p>\n" }, { "answer_id": 5745105, "author": "vmachacek", "author_id": 210025, "author_profile": "https://Stackoverflow.com/users/210025", "pm_score": 3, "selected": false, "text": "<p>For Visual Studio 2010 you can download the \"Remove and Sort Using\"extension from the Visual Studio Gallery.</p>\n\n<p><a href=\"http://visualstudiogallery.msdn.microsoft.com/en-us/cb559aa8-d976-4cc2-9754-5a712f985d16\">http://visualstudiogallery.msdn.microsoft.com/en-us/cb559aa8-d976-4cc2-9754-5a712f985d16</a></p>\n\n<p>Works Well for me</p>\n" }, { "answer_id": 10531081, "author": "mghaoui", "author_id": 32824, "author_profile": "https://Stackoverflow.com/users/32824", "pm_score": 2, "selected": false, "text": "<p>Here's a small improvement on the script above for VB.NET. Make sure you have the <a href=\"http://visualstudiogallery.msdn.microsoft.com/d0d33361-18e2-46c0-8ff2-4adea1e34fef/\" rel=\"nofollow\">Productivity Power Tools</a> installed.</p>\n\n<pre><code> Private Sub RemoveAndSortSome(ByVal projectItem As ProjectItem)\n On Error Resume Next\n If projectItem.Kind = Constants.vsProjectItemKindPhysicalFile Then\n If projectItem.Name.LastIndexOf(\".cs\") = projectItem.Name.Length - 3 Then\n Dim window As Window = projectItem.Open(Constants.vsViewKindCode)\n\n window.Activate()\n\n projectItem.Document.DTE.ExecuteCommand(\"Edit.RemoveAndSort\")\n\n window.Close(vsSaveChanges.vsSaveChangesYes)\n\n ElseIf projectItem.Name.LastIndexOf(\".vb\") = projectItem.Name.Length - 3 Then\n Dim window As Window = projectItem.Open(Constants.vsViewKindCode)\n\n window.Activate()\n\n projectItem.Document.DTE.ExecuteCommand(\"EditorContextMenus.CodeWindow.OrganizeImports.RemoveandSortImports\")\n\n window.Close(vsSaveChanges.vsSaveChangesYes)\n End If\n End I\n</code></pre>\n" }, { "answer_id": 32033067, "author": "VivekDev", "author_id": 1977871, "author_profile": "https://Stackoverflow.com/users/1977871", "pm_score": 2, "selected": false, "text": "<p>Productivity Power tools is what you need.\n<a href=\"https://visualstudiogallery.msdn.microsoft.com/dbcb8670-889e-4a54-a226-a48a15e4cace\" rel=\"nofollow\">https://visualstudiogallery.msdn.microsoft.com/dbcb8670-889e-4a54-a226-a48a15e4cace</a></p>\n\n<p>Once you have that installed, you can find the “<strong>Remove and Sort Usings on Save” from the “Tools –> Options –> Productivity Power Tools –> PowerCommands –> Generals</strong>”. After you check that option, restart VS. Now save and you see the magic.</p>\n\n<p>For VS 2015, take a look at <a href=\"https://visualstudiogallery.msdn.microsoft.com/34ebc6a2-2777-421d-8914-e29c1dfa7f5d\" rel=\"nofollow\">this</a></p>\n" }, { "answer_id": 35619794, "author": "Mark Bell", "author_id": 43140, "author_profile": "https://Stackoverflow.com/users/43140", "pm_score": 6, "selected": false, "text": "<p>The other answers which refer to the Productivity Power Tools extensions don't go into any detail of how to actually do this, so here are some instructions for Visual Studio 2013, 2015, 2017 and 2019:</p>\n<p>First, open the <strong>Tools &gt; Extensions and Updates...</strong> dialog in Visual Studio, select <strong>Online</strong> in the left-hand bar and then search the Visual Studio Gallery for <strong>&quot;Productivity Power Tools&quot;</strong>. Install the extension and restart VS.</p>\n<p>Alternatively, you can manually download and install the extensions for your version of Visual Studio:</p>\n<p><a href=\"https://marketplace.visualstudio.com/items?itemName=VisualStudioProductTeam.ProductivityPowerTools2013\" rel=\"noreferrer\">Productivity Power Tools 2013</a><br />\n<a href=\"https://marketplace.visualstudio.com/items?itemName=VisualStudioProductTeam.ProductivityPowerTools2015\" rel=\"noreferrer\">Productivity Power Tools 2015</a><br />\n<a href=\"https://marketplace.visualstudio.com/items?itemName=VisualStudioProductTeam.ProductivityPowerPack2017\" rel=\"noreferrer\">Productivity Power Tools 2017/2019</a></p>\n<p>For VS2017 and VS2019, you can also download the Power Commands extension separately from the others in the Power Tools pack:</p>\n<p><a href=\"https://marketplace.visualstudio.com/items?itemName=VisualStudioProductTeam.PowerCommandsforVisualStudio\" rel=\"noreferrer\">Power Commands for Visual Studio</a></p>\n<p>Be aware that at the time of writing, the VS2017 version doesn't work with .Net Core projects/solutions.</p>\n<p>Once you have the extension installed, just right-click the solution in Solution Explorer, then select <strong>Power Commands &gt; Remove and Sort Usings</strong>.</p>\n<p>This can take a while, particularly on large solutions; it also doesn't keep modified files open (hence no undo), so <strong>make sure you commit everything in your VCS of choice <em>before</em> running it</strong>, so that you can revert the changes it makes if something goes wrong!</p>\n<h2>Update: Format All Files</h2>\n<p>Recently I've been using the <a href=\"https://marketplace.visualstudio.com/items?itemName=munyabe.FormatAllFiles\" rel=\"noreferrer\">Format All Files</a> extension, which allows you to execute <strong>Format Document</strong>, <strong>Remove and Sort Usings</strong> and one other custom command of your choice (all optionally, set in the VS preferences).</p>\n<p>It seems to work very well, but again, no undo, so <strong>make sure you commit everything in your VCS of choice <em>before</em> running it</strong>.</p>\n" }, { "answer_id": 42139488, "author": "Tim Pickin", "author_id": 2024842, "author_profile": "https://Stackoverflow.com/users/2024842", "pm_score": 0, "selected": false, "text": "<p>I am using Visual Studio 2015 and found a tool named BatchFormat:\n<a href=\"https://marketplace.visualstudio.com/items?itemName=vs-publisher-147549.BatchFormat\" rel=\"nofollow noreferrer\">https://marketplace.visualstudio.com/items?itemName=vs-publisher-147549.BatchFormat</a></p>\n\n<p>This did the job perfectly.</p>\n\n<p>Install the tool, then right click on your solution in the solution explorer, then at the top of the menu you see batch format:</p>\n\n<p><a href=\"https://i.stack.imgur.com/Rm3aZ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Rm3aZ.png\" alt=\"enter image description here\"></a></p>\n\n<p>Whatever you select is applied to every file in your solution, as you can see in the screenshot, there are other options, you can also format every document.</p>\n" }, { "answer_id": 43663796, "author": "Dave Thieben", "author_id": 218136, "author_profile": "https://Stackoverflow.com/users/218136", "pm_score": 2, "selected": false, "text": "<p>for a more recent version, including 2017, try the <a href=\"https://marketplace.visualstudio.com/items?itemName=munyabe.FormatAllFiles\" rel=\"nofollow noreferrer\">\"Format All Files\"</a> extension. it has been working really well for me.</p>\n\n<p><a href=\"https://i.stack.imgur.com/iU3V0.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/iU3V0.png\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 50632775, "author": "sotn", "author_id": 944592, "author_profile": "https://Stackoverflow.com/users/944592", "pm_score": 7, "selected": false, "text": "<p>There is no need for any plugins in VS 2017 or 2019. Click the bulb icon near any using statement and click <code>Solution</code> next to <code>Fix all occurrences in</code> part.</p>\n<p><a href=\"https://i.stack.imgur.com/bqi3C.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/bqi3C.png\" alt=\"Screenshot of solution\" /></a></p>\n" }, { "answer_id": 55683984, "author": "Sangeet Shah", "author_id": 3539870, "author_profile": "https://Stackoverflow.com/users/3539870", "pm_score": 0, "selected": false, "text": "<p>visual studio 2017 having inbuild feature to remove unnecessary name space from whole project.</p>\n\n<p><a href=\"https://i.stack.imgur.com/ICfte.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ICfte.png\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 65658984, "author": "Murat Can OĞUZHAN", "author_id": 8090964, "author_profile": "https://Stackoverflow.com/users/8090964", "pm_score": 3, "selected": false, "text": "<p>There is a built-in function under the analyze menu that is called as Code Cleanup.\nIf you click Profile 1, it'll do as remove and sortings functionality.</p>\n<p><a href=\"https://i.stack.imgur.com/PjTxz.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/PjTxz.png\" alt=\"enter image description here\" /></a></p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283471", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4653/" ]
I know you can do it file by file. Is there any way to do this in one step for all files in a project?
Do you mean using statements? First, note that they generally do no harm other that take space. Tools like [ReSharper](http://www.jetbrains.com/resharper/) offer automated tricks to do this, however: there was a [link in the VS feed](http://blogs.msdn.com/djpark/archive/2008/08/16/organize-usings-across-your-entire-solution.aspx) a little while ago; it boils down to: * go to Tools -> Macros -> Macros IDE... * in the Project Explorer, Add -> Add Module... (put in a name - I've used OrganiseUsings) * paste over with the code below * File -> Save MyMacros, exit Now if you right-click on the toolbar and Customize... - you should be able to find MyMacros.OrganiseUsings.RemoveAndSortAll - drag this somewhere handy (maybe the Tools menu; you might also want to change the name after placing it). You can now use this option to run the Remove and Sort command for an entire solution. A big time-saver. ==== code ==== ``` Imports System Imports EnvDTE Imports EnvDTE80 Imports EnvDTE90 Imports System.Diagnostics Public Module OrganiseUsings Public Sub RemoveAndSortAll() On Error Resume Next Dim sol As Solution = DTE.Solution For i As Integer = 1 To sol.Projects.Count Dim proj As Project = sol.Projects.Item(i) For j As Integer = 1 To proj.ProjectItems.Count RemoveAndSortSome(proj.ProjectItems.Item(j)) Next Next End Sub Private Sub RemoveAndSortSome(ByVal projectItem As ProjectItem) On Error Resume Next If projectItem.Kind = Constants.vsProjectItemKindPhysicalFile Then If projectItem.Name.LastIndexOf(".cs") = projectItem.Name.Length - 3 Then Dim window As Window = projectItem.Open(Constants.vsViewKindCode) window.Activate() projectItem.Document.DTE.ExecuteCommand("Edit.RemoveAndSort") window.Close(vsSaveChanges.vsSaveChangesYes) End If End If For i As Integer = 1 To projectItem.ProjectItems.Count RemoveAndSortSome(projectItem.ProjectItems.Item(i)) Next End Sub End Module ```
283,476
<p>I am wondering what is the "best practice" to break long strings in C# source code. Is this string </p> <pre><code>"string1"+ "string2"+ "string3" </code></pre> <p>concatenated during compiling or in run time?</p>
[ { "answer_id": 283488, "author": "Maxam", "author_id": 15310, "author_profile": "https://Stackoverflow.com/users/15310", "pm_score": 2, "selected": false, "text": "<p>The concatenation is done at compile time, so there is no runtime overhead.</p>\n" }, { "answer_id": 283491, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 7, "selected": true, "text": "<p>It's done at compile time. That's exactly equivalent to \"string1string2string3\".</p>\n\n<p>Suppose you have:</p>\n\n<pre><code>string x = \"string1string2string3\"\nstring y = \"string1\" + \"string2\" + \"string3\"\n</code></pre>\n\n<p>The compiler will perform appropriate interning such that x and y refer to the same objects.</p>\n\n<p>EDIT: There's a lot of talk about <code>StringBuilder</code> in the answers and comments. Many developers seem to believe that string concatenation should <em>always</em> be done with <code>StringBuilder</code>. That's an overgeneralisation - it's worth understanding <a href=\"http://pobox.com/~skeet/csharp/stringbuilder.html\" rel=\"noreferrer\">why <code>StringBuilder</code> is good in some situations, and not in others</a>.</p>\n" }, { "answer_id": 283494, "author": "Damien", "author_id": 35454, "author_profile": "https://Stackoverflow.com/users/35454", "pm_score": 0, "selected": false, "text": "<p>Can't you use a <code>StringBuilder</code>? </p>\n" }, { "answer_id": 283495, "author": "James Newton-King", "author_id": 11829, "author_profile": "https://Stackoverflow.com/users/11829", "pm_score": 3, "selected": false, "text": "<p>Your example will be concatenated at compile time. All inline strings and const string variables are concatenated at compile time.</p>\n\n<p>Something to keep in mind is that including any readonly strings will delay concatting to runtime. string.Empty and Environment.NewLine are both readonly string variables.</p>\n" }, { "answer_id": 283496, "author": "Tamir", "author_id": 30879, "author_profile": "https://Stackoverflow.com/users/30879", "pm_score": 1, "selected": false, "text": "<p>it really depends on what you need. Generally, if you need to concat strings, the best performance in runtime will be achieved by using StringBuilder.\nIf you're referring in source code something like var str = \"String1\"+\"String2\" it will be converter into string str = \"String1String2\" on compilation. In this case you have no concatenation overhead</p>\n" }, { "answer_id": 283505, "author": "Rune Grimstad", "author_id": 30366, "author_profile": "https://Stackoverflow.com/users/30366", "pm_score": 6, "selected": false, "text": "<p>If the whitespace isn't important then you can use the @ escape character to write multi-line strings in your code. \nThis is useful if you have a query in your code for example:</p>\n\n<pre><code>string query = @\"SELECT whatever\nFROM tableName\nWHERE column = 1\";\n</code></pre>\n\n<p>This will give you a string with line breaks and tabs, but for a query that doesn't matter.</p>\n" }, { "answer_id": 283507, "author": "Sani Singh Huttunen", "author_id": 26742, "author_profile": "https://Stackoverflow.com/users/26742", "pm_score": 1, "selected": false, "text": "<p>StringBuilder is a good way to go if\nyou have many (more than about four)\nstrings to concatenate. It's faster.</p>\n\n<p>Using String.Concat in you example above is done at compile time.\nSince they are literal strings they are optimized by the compiler.</p>\n\n<p>If you however use variables:</p>\n\n<pre><code>string a = \"string1\";\nstring b = \"string2\";\nstring c = a + b;\n</code></pre>\n\n<p>This is done at runtime.</p>\n" }, { "answer_id": 283529, "author": "naspinski", "author_id": 14777, "author_profile": "https://Stackoverflow.com/users/14777", "pm_score": -1, "selected": false, "text": "<p>StringBuilder will be your fastest approach if you are using any amount of strings.</p>\n\n<p><a href=\"http://dotnetperls.com/Content/StringBuilder-1.aspx\" rel=\"nofollow noreferrer\">http://dotnetperls.com/Content/StringBuilder-1.aspx</a></p>\n\n<p>If you are just doing a few string (5 or less is a good rule) the speed will not matter of what kind of concatenation you are using.</p>\n" }, { "answer_id": 743026, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>There´s any way to do it.\nMy favorete uses a string´s method´s from C#.\nSample One:</p>\n\n<p>string s=string.Format(\"{0} {1} {0}\",\"Hello\",\"By\");\nresult is s=\"Hello By Hello\";</p>\n" }, { "answer_id": 53973356, "author": "Felix K.", "author_id": 2477619, "author_profile": "https://Stackoverflow.com/users/2477619", "pm_score": 2, "selected": false, "text": "<p>How about the following <a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods\" rel=\"nofollow noreferrer\">extension method</a> (which is inspired by common-tags <a href=\"https://www.npmjs.com/package/common-tags#oneline\" rel=\"nofollow noreferrer\">oneLine</a> method)...</p>\n\n<pre><code>using System;\nusing System.Text.RegularExpressions;\nusing static System.Text.RegularExpressions.RegexOptions;\n\nnamespace My.Name.Space\n{\n public static class StringHelper\n {\n public static string AsOneLine(this string text, string separator = \" \")\n {\n return new Regex(@\"(?:\\n(?:\\s*))+\").Replace(text, separator).Trim();\n }\n }\n}\n</code></pre>\n\n<p>...in combination with the <a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/verbatim\" rel=\"nofollow noreferrer\">verbatim string literal</a> used as such:</p>\n\n<pre><code>var mySingleLineText = @\"\n If we wish to count lines of code, we should not regard them\n as 'lines produced' but as 'lines spent'.\n\".AsOneLine();\n</code></pre>\n\n<p>Note that spaces \"inside\" the string are kept intact, for example:</p>\n\n<pre><code>// foo bar hello world.\nvar mySingleLineText = @\"\n foo bar\n hello world.\n\".AsOneLine();\n</code></pre>\n\n<p>If you don't want newlines to be substituted with spaces, then pass <code>\"\"</code> as argument to the extension method:</p>\n\n<pre><code>// foobar\nvar mySingleLineText = @\"\n foo\n bar\n\".AsOneLine(\"\");\n</code></pre>\n\n<p><strong>Please note:</strong> This form of string concatenation is conducted at run time due to the helper-method involved (in contrast to concatenation via the <code>+</code> operator occurring at compile time, as also stated in the accepted answer). So if performance is an issue, go with the <code>+</code>. If you are dealing with long phrases and readability and \"ease of use\" is the focus, then the approach suggested above may be worth considering.</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283476", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11256/" ]
I am wondering what is the "best practice" to break long strings in C# source code. Is this string ``` "string1"+ "string2"+ "string3" ``` concatenated during compiling or in run time?
It's done at compile time. That's exactly equivalent to "string1string2string3". Suppose you have: ``` string x = "string1string2string3" string y = "string1" + "string2" + "string3" ``` The compiler will perform appropriate interning such that x and y refer to the same objects. EDIT: There's a lot of talk about `StringBuilder` in the answers and comments. Many developers seem to believe that string concatenation should *always* be done with `StringBuilder`. That's an overgeneralisation - it's worth understanding [why `StringBuilder` is good in some situations, and not in others](http://pobox.com/~skeet/csharp/stringbuilder.html).
283,477
<p>Suppose I have the following directory layout in a Maven project:</p> <pre><code>src/ |-- main | |-- bin | | |-- run.cmd | | `-- run.sh | |-- etc | | |-- common-spring.xml | | |-- log4j.xml | | `-- xml-spring.xml | `-- java | `-- com ... </code></pre> <p>I would like to build a zip file that, when unzipped, produces something like this:</p> <pre><code>assembly |-- bin | |-- run.cmd | `-- run.sh |-- etc | |-- common-spring.xml | |-- log4j.xml | `-- xml-spring.xml `-- lib |-- dependency1.jar |-- dependency2.jar ... </code></pre> <p>where `run.xx' are executable shell scripts that will call my main application and <em>put all dependencies on the classpath</em>.</p> <p>Is this possible with some of the `official' Maven plugins, e.g. maven-assembly-plugin?</p>
[ { "answer_id": 283564, "author": "jassuncao", "author_id": 1009, "author_profile": "https://Stackoverflow.com/users/1009", "pm_score": 5, "selected": true, "text": "<p>I use the <a href=\"http://mojo.codehaus.org/appassembler/appassembler-maven-plugin/\" rel=\"noreferrer\">AppAssembler plugin</a> to get something similar. Example:</p>\n\n<pre><code>...\n&lt;build&gt;\n&lt;plugins&gt;\n &lt;plugin&gt;\n &lt;groupId&gt;org.codehaus.mojo&lt;/groupId&gt;\n &lt;artifactId&gt;appassembler-maven-plugin&lt;/artifactId&gt;\n &lt;configuration&gt;\n &lt;programs&gt;\n &lt;program&gt;\n &lt;mainClass&gt;com.acme.MainClass&lt;/mainClass&gt;\n &lt;name&gt;app&lt;/name&gt;\n &lt;/program&gt;\n &lt;/programs&gt;\n &lt;/configuration&gt;\n &lt;/plugin&gt;\n&lt;/plugins&gt;\n</code></pre>\n\n<p></p>\n" }, { "answer_id": 285311, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>The appassembler generates the 'run.xx' files for you.</p>\n\n<p>If you have already created the shell scripts yourself you can use the maven-assembly-plugin to create the zip file.\nTo gather the dependencies you can use maven-dependency-plugin.</p>\n" }, { "answer_id": 287494, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>The maven-assembly-plugin can also copy the dependencies into your assembly, by including something like the below in your assembly descriptor file:</p>\n\n<pre><code>&lt;dependencySets&gt;\n &lt;!-- Copy dependency jar files to 'lib' --&gt;\n &lt;dependencySet&gt;\n &lt;outputDirectory&gt;lib&lt;/outputDirectory&gt;\n &lt;includes&gt;\n &lt;include&gt;*:jar:*&lt;/include&gt;\n &lt;/includes&gt;\n &lt;/dependencySet&gt;\n&lt;/dependencySets&gt;\n</code></pre>\n" }, { "answer_id": 301222, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>I've used the maven-assembly-plugin to acheive something similar in a project. I wanted a zip file to be built during the package phase, instead of manually calling assembly:assembly. Here's what I came up with:</p>\n\n<p>/src/assemble/distribution.xml:</p>\n\n<pre><code>&lt;assembly&gt;\n &lt;id&gt;distribution&lt;/id&gt;\n\n &lt;!-- specify the output formats --&gt;\n &lt;formats&gt;\n &lt;format&gt;zip&lt;/format&gt;\n &lt;/formats&gt;\n\n &lt;!-- include all runtime libraries in the /lib folder of the output file --&gt;\n &lt;dependencySets&gt;\n &lt;dependencySet&gt;\n &lt;outputDirectory&gt;/lib&lt;/outputDirectory&gt;\n &lt;scope&gt;runtime&lt;/scope&gt;\n &lt;/dependencySet&gt;\n &lt;/dependencySets&gt;\n\n &lt;fileSets&gt;\n &lt;!-- include all *.jar files in the target directory --&gt;\n &lt;fileSet&gt;\n &lt;directory&gt;target&lt;/directory&gt;\n &lt;outputDirectory&gt;&lt;/outputDirectory&gt;\n &lt;includes&gt;\n &lt;include&gt;*.jar&lt;/include&gt;\n &lt;/includes&gt;\n &lt;/fileSet&gt;\n\n &lt;!-- include all files in the /conf directory --&gt;\n &lt;fileSet&gt;\n &lt;outputDirectory&gt;&lt;/outputDirectory&gt;\n &lt;includes&gt;\n &lt;include&gt;conf/**&lt;/include&gt;\n &lt;/includes&gt;\n &lt;/fileSet&gt;\n &lt;/fileSets&gt;\n\n&lt;/assembly&gt;\n</code></pre>\n\n<p>/pom.xml</p>\n\n<p>...</p>\n\n<pre><code> &lt;plugin&gt;\n &lt;artifactId&gt;maven-assembly-plugin&lt;/artifactId&gt;\n\n &lt;configuration&gt;\n &lt;descriptors&gt;\n &lt;descriptor&gt;src/assemble/distribution.xml\n &lt;/descriptor&gt;\n &lt;/descriptors&gt;\n &lt;/configuration&gt;\n\n &lt;!-- append assembly:assembly to the package phase --&gt;\n &lt;executions&gt;\n &lt;execution&gt;\n &lt;phase&gt;package&lt;/phase&gt;\n &lt;goals&gt;\n &lt;goal&gt;assembly&lt;/goal&gt;\n &lt;/goals&gt;\n &lt;/execution&gt;\n &lt;/executions&gt;\n\n &lt;/plugin&gt;\n</code></pre>\n\n<p>...</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1428/" ]
Suppose I have the following directory layout in a Maven project: ``` src/ |-- main | |-- bin | | |-- run.cmd | | `-- run.sh | |-- etc | | |-- common-spring.xml | | |-- log4j.xml | | `-- xml-spring.xml | `-- java | `-- com ... ``` I would like to build a zip file that, when unzipped, produces something like this: ``` assembly |-- bin | |-- run.cmd | `-- run.sh |-- etc | |-- common-spring.xml | |-- log4j.xml | `-- xml-spring.xml `-- lib |-- dependency1.jar |-- dependency2.jar ... ``` where `run.xx' are executable shell scripts that will call my main application and *put all dependencies on the classpath*. Is this possible with some of the `official' Maven plugins, e.g. maven-assembly-plugin?
I use the [AppAssembler plugin](http://mojo.codehaus.org/appassembler/appassembler-maven-plugin/) to get something similar. Example: ``` ... <build> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>appassembler-maven-plugin</artifactId> <configuration> <programs> <program> <mainClass>com.acme.MainClass</mainClass> <name>app</name> </program> </programs> </configuration> </plugin> </plugins> ```
283,484
<p>Is there anything similar to getElementById in actionscript? </p> <p>I'm trying to make a prototype of a flash page wich gets it's data from a xhtml file. I want to have both an accessible html version (for search engines, textreaders and people without flash) and a flash version (because the customer insists to use flash even though a html-css-ajax solution would do quite nicely). </p> <p>What I need is a simple way of getting the text or attributes from the html with a certain id, like <code>&lt;h1 id="flashdataTitle"&gt;This is the title&lt;/h1&gt;</code> etc. I'm guessing a few ways it might be possible:</p> <ul> <li>Somehow use an ExternalInterface.call and do the DOM trickery in JavaScript (wich is probably what I will do, because I'm very familiar with JS and a complete newbie with flash/actionscript, unless you have a better solution)</li> <li>Load the xhtml with the Actionscript XML class, and manually traverse the XML looking for the correct id attribute (but this is probably very slow)</li> <li>Use XPath with the XML class in actionscript. (I'd like some hints on how to do this, if this is the reccomended way)</li> <li>There is actually an Actionscript equivalent to getElementById to use with the XML?</li> <li>Allthough my employer hope we don't have to do this: I could rewrite the server side code to output the relevant texts and image urls in a flash-friendly format.</li> </ul> <p>What is the most effective, easiest to implement, and robust-crossbrowser way of doing this? Any totally different ideas?</p> <p>Please post any ideas even if you think the question have been answered, I'd like to explore all the different possibilities, and allso what disadvantages the proposed solutions have.</p>
[ { "answer_id": 283552, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 2, "selected": true, "text": "<p>Since you said your input would be XHTML, you can do it with XPath:</p>\n\n<pre><code>import mx.xpath.XPathAPI;\n\nvar elementId:String = \"flashdataTitle\";\nvar elementPath:String = \"//h1[@id'\" + elementId + \"']\";\nfound_elements = XPathAPI.selectNodeList(xhtml.firstChild, elementPath);\n\nif (found_elements.length == 1) {\n trace(found_elements[0]);\n}\n</code></pre>\n\n<p>The code example is inspired from <a href=\"http://www.robgonda.com/blog/index.cfm/2005/7/10/Xpath-for-ActionScript\" rel=\"nofollow noreferrer\">here</a>, where you also can find some mode detail on XPath and ActionScript.</p>\n\n<p>AS3 has it's own <a href=\"http://code.google.com/p/xpath-as3/\" rel=\"nofollow noreferrer\">XPath Library</a>, the general approach would be the same.</p>\n" }, { "answer_id": 285278, "author": "Stein G. Strindhaug", "author_id": 26115, "author_profile": "https://Stackoverflow.com/users/26115", "pm_score": 0, "selected": false, "text": "<p>Is there anything like the prototype.js function <a href=\"http://www.prototypejs.org/api/object/inspect\" rel=\"nofollow noreferrer\">inspect()</a> in Actionscript? I've tried testing the xpath solution but it just won't work. I've tested that the xpath is correct using scetchpad (I think that's what it's called), so I beleave theres a problem with the XML object... It seems to contain the xhtml file when viewing it in the debugger, though it seems quite chaotic, but if I could \"inspect\" the variables and trace them it would help locating the problem. (Thanks Tomalak, I will upvote your answer as soon as my \"reputation\" is high enough.)</p>\n\n<p>BTW, I still want to hear other ideas.</p>\n" }, { "answer_id": 317036, "author": "Jonas", "author_id": 25194, "author_profile": "https://Stackoverflow.com/users/25194", "pm_score": 0, "selected": false, "text": "<p>Use XML.idMap (or XMLDocument.idMap in ActionScript 3.0) property if quering elements by id is enough. This method is probably fastest way to do this. While XPath gives you advanced quering capabilities it reduces performance. So if you need some elements having id attributes I recomend you use idMap.</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283484", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26115/" ]
Is there anything similar to getElementById in actionscript? I'm trying to make a prototype of a flash page wich gets it's data from a xhtml file. I want to have both an accessible html version (for search engines, textreaders and people without flash) and a flash version (because the customer insists to use flash even though a html-css-ajax solution would do quite nicely). What I need is a simple way of getting the text or attributes from the html with a certain id, like `<h1 id="flashdataTitle">This is the title</h1>` etc. I'm guessing a few ways it might be possible: * Somehow use an ExternalInterface.call and do the DOM trickery in JavaScript (wich is probably what I will do, because I'm very familiar with JS and a complete newbie with flash/actionscript, unless you have a better solution) * Load the xhtml with the Actionscript XML class, and manually traverse the XML looking for the correct id attribute (but this is probably very slow) * Use XPath with the XML class in actionscript. (I'd like some hints on how to do this, if this is the reccomended way) * There is actually an Actionscript equivalent to getElementById to use with the XML? * Allthough my employer hope we don't have to do this: I could rewrite the server side code to output the relevant texts and image urls in a flash-friendly format. What is the most effective, easiest to implement, and robust-crossbrowser way of doing this? Any totally different ideas? Please post any ideas even if you think the question have been answered, I'd like to explore all the different possibilities, and allso what disadvantages the proposed solutions have.
Since you said your input would be XHTML, you can do it with XPath: ``` import mx.xpath.XPathAPI; var elementId:String = "flashdataTitle"; var elementPath:String = "//h1[@id'" + elementId + "']"; found_elements = XPathAPI.selectNodeList(xhtml.firstChild, elementPath); if (found_elements.length == 1) { trace(found_elements[0]); } ``` The code example is inspired from [here](http://www.robgonda.com/blog/index.cfm/2005/7/10/Xpath-for-ActionScript), where you also can find some mode detail on XPath and ActionScript. AS3 has it's own [XPath Library](http://code.google.com/p/xpath-as3/), the general approach would be the same.
283,486
<p>We are experiencing a strange bug on our website which we think is related to the software installed on user's computers. We have an e-mail link on a lot of pages, which is created using Javascript (so spambots won't get it).</p> <p>It seems the link is "clicked" automatically on some user's machines. Some users then discard the window by clicking Send on the e-mail window that pops up, resulting in a ton of e-mails to us.</p> <p>When inspecting the Apache log, nothing weird can be seen in the browser string. Can this be a download accelerator/prefetcher gone haywire? Any other theories as to what this might be?</p> <p>The link in the HTML is written like this (it is autogenerated by Smarty):</p> <pre><code>&lt;script type="text/javascript" language="javascript"&gt; &lt;!-- {document.write(String.fromCharCode(60,97,32,104,114,101, 102,61,34,109,97,105,108,116,111,58,115,117,112,112,111,114, 116,64,112,114,111,118,101,46,110,111,63,115,117,98,106,101,99, 116,61,82,101,102,101,114,97,110,115,101,110,117,109,109,101,114, 37,50,48,49,53,48,48,34,32,62,83,101,110,100,32,115,112,38,111,115, 108,97,115,104,59,114,115,109,38,97,114,105,110,103,59,108,46,60,47,97,62))} //--&gt; &lt;/script&gt; </code></pre>
[ { "answer_id": 283874, "author": "Jeroen Heijmans", "author_id": 30748, "author_profile": "https://Stackoverflow.com/users/30748", "pm_score": 0, "selected": false, "text": "<p>My only suggestion would indeed be that some program (browser, extension, bot, indexer) reads the page and then opens the link and sends the mail, but I've never seen that before. </p>\n\n<p>Is there anything you can see from the mail messages you get? Recurring IP addresses or X-Mailer?</p>\n\n<p>Perhaps you can ask one of the users about their system setup - you have their e-mail address. </p>\n" }, { "answer_id": 284132, "author": "bart", "author_id": 19966, "author_profile": "https://Stackoverflow.com/users/19966", "pm_score": 2, "selected": false, "text": "<p>Could something in the browser be prefetching the links? For example, the Firefox extension <a href=\"http://fasterfox.mozdev.org/\" rel=\"nofollow noreferrer\">Fasterfox</a> does that (which is the reason why I don't use it). I seem to remember Google at one time also had brought out a browser accelerator using the same concept. And the AVG antivirus' Linkscanner is infamous for doing it too (all in the name of scanning for bad sites).</p>\n\n<p>In short: don't use links for something that changes a state, for example for logging out, deleting a record (gasp!) or sending email. Use a button instead. </p>\n" }, { "answer_id": 1361093, "author": "warren", "author_id": 4418, "author_profile": "https://Stackoverflow.com/users/4418", "pm_score": 0, "selected": false, "text": "<p>Personally, I'd try to solve this by changing from a <code>mailto:</code> link to a contact form - though that doesn't directly answer the question you asked.</p>\n\n<p>The other suggestions of link pre-fetchers seem the most probable.</p>\n\n<p>I suppose it <em>might</em> even be related to caching from an ISP, if it's trying to pre-spider a page so the linked-to pages load quicker?</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283486", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1606/" ]
We are experiencing a strange bug on our website which we think is related to the software installed on user's computers. We have an e-mail link on a lot of pages, which is created using Javascript (so spambots won't get it). It seems the link is "clicked" automatically on some user's machines. Some users then discard the window by clicking Send on the e-mail window that pops up, resulting in a ton of e-mails to us. When inspecting the Apache log, nothing weird can be seen in the browser string. Can this be a download accelerator/prefetcher gone haywire? Any other theories as to what this might be? The link in the HTML is written like this (it is autogenerated by Smarty): ``` <script type="text/javascript" language="javascript"> <!-- {document.write(String.fromCharCode(60,97,32,104,114,101, 102,61,34,109,97,105,108,116,111,58,115,117,112,112,111,114, 116,64,112,114,111,118,101,46,110,111,63,115,117,98,106,101,99, 116,61,82,101,102,101,114,97,110,115,101,110,117,109,109,101,114, 37,50,48,49,53,48,48,34,32,62,83,101,110,100,32,115,112,38,111,115, 108,97,115,104,59,114,115,109,38,97,114,105,110,103,59,108,46,60,47,97,62))} //--> </script> ```
Could something in the browser be prefetching the links? For example, the Firefox extension [Fasterfox](http://fasterfox.mozdev.org/) does that (which is the reason why I don't use it). I seem to remember Google at one time also had brought out a browser accelerator using the same concept. And the AVG antivirus' Linkscanner is infamous for doing it too (all in the name of scanning for bad sites). In short: don't use links for something that changes a state, for example for logging out, deleting a record (gasp!) or sending email. Use a button instead.
283,492
<p>I'm tring to build a library for simplifing late binding calls in C#, and I'm getting trouble tring with reference parameteres. I have the following method to add a parameter used in a method call</p> <pre><code> public IInvoker AddParameter(ref object value) { //List&lt;object&gt; _parameters = new List&lt;object&gt;(); _parameters.Add(value); //List&lt;bool&gt; _isRef = new List&lt;bool&gt;(); _isRef.Add(true); return this; } </code></pre> <p>And that doesn't work with value types, because they get boxed as an object, thus they are not modified. E.g:</p> <pre><code>int param1 = 2; object paramObj = param1; //MulFiveRef method multiplies the integer passed as a reference parameter by 5: //void MulFiveRef(ref int value) { value *= 5; } fi.Method("MulFiveRef").AddParameter(ref paramObj); </code></pre> <p>That doesn't work. The late binding call is successful, and the inner List which holds the parameteres (_parameters ) does get modified, but not the value outside the call.</p> <p>Does anyone knows a simple way to overcome this limitation? The AddParameter signature cannot be modified, as with late binding calls, you cannot know in advance the Type of the parameters (and either way you insert all the parameters for a call inside an object array prior to making the call)</p> <p>Thanks in advance.</p>
[ { "answer_id": 283499, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 1, "selected": false, "text": "<p>Your method isn't changing <code>value</code> anyway - why are you passing it by reference? It may make sense, but it's not really clear to me. Note that the sample code you've provided wouldn't compile anyway, as <code>ref</code> arguments have to be <em>exactly</em> the same type as the parameter.</p>\n\n<p>(Also, are you aware that C# 4.0 and .NET 4.0 will have built-in support for late-binding? Chances are that the language-integrated version will be easier to use than a library-only one. Are you sure it's worth spending time on the library at this point in time?)</p>\n\n<p>EDIT: The code you've provided really won't compile. You don't get boxing for <code>ref</code> parameters, precisely because the argument and parameter types have to be exactly the same. Here's some sample code to prove it:</p>\n\n<pre><code>public class Test\n{\n static void Main()\n {\n int i;\n Foo(ref i); // Won't compile - error CS1502/1503\n }\n\n static void Foo(ref object x)\n {\n }\n}\n</code></pre>\n\n<p>If your current code <em>is</em> compiling, then it's not the code you presented in the question. Perhaps you have another overload for <code>AddParameter</code> which accepts <code>ref int</code>?</p>\n" }, { "answer_id": 283500, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": true, "text": "<p>If the value is changing <em>inside the method</em>, you will need to declare a temp (<code>object</code>) variable to pass (<code>ref</code>) to the method, and unbox it yourself afterwards:</p>\n\n<pre><code> int i = 3;\n //...\n object obj = i;\n Foo(ref obj);\n i = (int)obj;\n</code></pre>\n\n<p>Note that this will not allow you to update the value after the event. Something like an event or callback might be an alternative way of passing changes back to the caller.</p>\n\n<p>Note also that C# 4.0 has some tricks to help with this <em>only</em> in the context of COM calls (where <code>ref object</code> is so common [plus of course <code>dynamic</code> for late binding, as Jon notes]).</p>\n" }, { "answer_id": 283769, "author": "Ricardo Amores", "author_id": 10136, "author_profile": "https://Stackoverflow.com/users/10136", "pm_score": 0, "selected": false, "text": "<p>Ok, thanks to Jon Skeet corrections and Mark Gravell code, i've come up with this interface:</p>\n\n<pre><code> //This will be created with a factory\n IOperationInvoker invoker = new OperationInvoker(Activator.CreateInstance&lt;MyLateBindingTestType&gt;());\n\n int param1 = 2;\n object paramObj = param1;\n\n invoker.AddParameter(ref paramObj).Invoke(\"MulFiveRef\");\n\n param1 = (int)invoker.Parameters[0];\n</code></pre>\n\n<p>Is not exactly as I've imagined, but is way more simply and readable that my previous interface:</p>\n\n<pre><code> IOperationInvoker invoker = new OperationInvoker(Activator.CreateInstance&lt;MyLateBindingTestType&gt;());\n int refValue = 10;\n object[] args = Args.Build(refValue);\n\n invoker.Call(\"MulFiveRef\", Args.ByRefIndexs(0), args);\n\n refValue = (int)args[0];\n</code></pre>\n\n<p>Thank you very much for your help people :)</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10136/" ]
I'm tring to build a library for simplifing late binding calls in C#, and I'm getting trouble tring with reference parameteres. I have the following method to add a parameter used in a method call ``` public IInvoker AddParameter(ref object value) { //List<object> _parameters = new List<object>(); _parameters.Add(value); //List<bool> _isRef = new List<bool>(); _isRef.Add(true); return this; } ``` And that doesn't work with value types, because they get boxed as an object, thus they are not modified. E.g: ``` int param1 = 2; object paramObj = param1; //MulFiveRef method multiplies the integer passed as a reference parameter by 5: //void MulFiveRef(ref int value) { value *= 5; } fi.Method("MulFiveRef").AddParameter(ref paramObj); ``` That doesn't work. The late binding call is successful, and the inner List which holds the parameteres (\_parameters ) does get modified, but not the value outside the call. Does anyone knows a simple way to overcome this limitation? The AddParameter signature cannot be modified, as with late binding calls, you cannot know in advance the Type of the parameters (and either way you insert all the parameters for a call inside an object array prior to making the call) Thanks in advance.
If the value is changing *inside the method*, you will need to declare a temp (`object`) variable to pass (`ref`) to the method, and unbox it yourself afterwards: ``` int i = 3; //... object obj = i; Foo(ref obj); i = (int)obj; ``` Note that this will not allow you to update the value after the event. Something like an event or callback might be an alternative way of passing changes back to the caller. Note also that C# 4.0 has some tricks to help with this *only* in the context of COM calls (where `ref object` is so common [plus of course `dynamic` for late binding, as Jon notes]).
283,513
<p>We just shifted from VB to C# and I am having some troubles..!</p> <p>Why can't I create a private static const void?? </p> <p>why is it not working?</p> <pre><code> private static const void MyVoid(void void) { try { this.void void = new void(void + void); return this.void; } catch (void) { Response.Write(void); } } </code></pre>
[ { "answer_id": 283517, "author": "Rob Cooper", "author_id": 832, "author_profile": "https://Stackoverflow.com/users/832", "pm_score": 2, "selected": false, "text": "<p><code>void</code> is the return type of <strong>\"there is no return type\"</strong>. It is not a type in itself (as in <code>int</code>, <code>bool</code> etc.), but rather specifies it returns nothing.</p>\n" }, { "answer_id": 283521, "author": "Tamir", "author_id": 30879, "author_profile": "https://Stackoverflow.com/users/30879", "pm_score": 1, "selected": false, "text": "<p>it's because void is actually nothingness :) If you want to send nothing to methods. Do it\nMyVoid()</p>\n\n<p>The same is for other lines in your method</p>\n" }, { "answer_id": 283526, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": false, "text": "<p>C# doesn't let you declare a method to be <code>const</code> whatever its return type is, so your method declaration is incorrect.</p>\n\n<p>You can't catch <code>void</code> either - you can only catch exception types.</p>\n\n<p>Ditto void parameters etc.</p>\n\n<p>Why do you think you need this?</p>\n" }, { "answer_id": 283527, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>void is a reserved keyword for \"return nothing\"</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/yah0tteb.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/yah0tteb.aspx</a></p>\n\n<p>here is the list of all reserved keywords \n<a href=\"http://msdn.microsoft.com/en-us/library/x53a06bb.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/x53a06bb.aspx</a></p>\n\n<p>think of Void like a Sub for C#</p>\n\n<p>In C# we only have methods - which return something (VB Functions) or return nothing ie void (VB Sub)</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36864/" ]
We just shifted from VB to C# and I am having some troubles..! Why can't I create a private static const void?? why is it not working? ``` private static const void MyVoid(void void) { try { this.void void = new void(void + void); return this.void; } catch (void) { Response.Write(void); } } ```
C# doesn't let you declare a method to be `const` whatever its return type is, so your method declaration is incorrect. You can't catch `void` either - you can only catch exception types. Ditto void parameters etc. Why do you think you need this?
283,523
<p>I have a C# application where i want to implement a logic for a programm which will open the word document and go to a certain place in the page and create a Table and put values in that. Can any one tell me how to implement this. I am using Visual studio 2005 </p>
[ { "answer_id": 283536, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "<p>Look up \"Word Automation\".</p>\n\n<p>For example, <a href=\"http://support.microsoft.com/kb/316384\" rel=\"nofollow noreferrer\">KB316384</a>, which covers:</p>\n\n<p>The sample code in this article demonstrates how to do the following:</p>\n\n<ul>\n<li>Insert paragraphs with text and formatting.</li>\n<li>Browse and modify various ranges within a document.</li>\n<li>Insert tables, format tables, and populate the tables with data.</li>\n<li>Add a chart.</li>\n</ul>\n" }, { "answer_id": 283631, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>If you don't want to use Word Automation, e.g. you don't have Word installed on the computer running your program, you should have a look at <a href=\"http://www.aspose.com/categories/file-format-components/aspose.words-for-.net-and-java/default.aspx\" rel=\"nofollow noreferrer\" title=\"Aspose.Words\">Aspose.Words</a>.</p>\n\n<p>The only problem is that it's not free.</p>\n" }, { "answer_id": 427800, "author": "Fionnuala", "author_id": 2548, "author_profile": "https://Stackoverflow.com/users/2548", "pm_score": 0, "selected": false, "text": "<p>Word will quite happily open a file in HTML with the extension .Doc. You can have all the formatting you want by using an internal style sheet. A very similar question came up here:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/282531/export-to-word-document-in-c\">Export to Word Document in C#</a></p>\n" }, { "answer_id": 10769658, "author": "Gary Kindel", "author_id": 44597, "author_profile": "https://Stackoverflow.com/users/44597", "pm_score": 3, "selected": false, "text": "<p>Here is code to copy datagridview to a word table:</p>\n\n<p>Reference is Microsoft.Office.Interop.Word \nC:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Visual Studio Tools for Office\\PIA\\Office12\\Microsoft.Office.Interop.Word.dll</p>\n\n<pre><code>using word = Microsoft.Office.Interop.Word; \npublic static void ExportToWord(DataGridView dgv)\n {\n SendMessage(\"Opening Word\");\n\n word.ApplicationClass word = null;\n\n\n\n word.Document doc = null;\n object oMissing = System.Reflection.Missing.Value;\n object oEndOfDoc = \"\\\\endofdoc\"; /* \\endofdoc is a predefined bookmark */ \n try\n {\n word = new word.ApplicationClass();\n word.Visible = true;\n doc = word.Documents.Add(ref oMissing, ref oMissing,ref oMissing, ref oMissing);\n }\n catch (Exception ex)\n {\n ErrorLog(ex);\n }\n finally\n {\n }\n if (word != null &amp;&amp; doc != null)\n {\n word.Table newTable;\n word.Range wrdRng = doc.Bookmarks.get_Item(ref oEndOfDoc).Range;\n newTable = doc.Tables.Add(wrdRng, 1, dgv.Columns.Count-1, ref oMissing, ref oMissing);\n newTable.Borders.InsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;\n newTable.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;\n newTable.AllowAutoFit = true;\n\n foreach (DataGridViewCell cell in dgv.Rows[0].Cells)\n {\n newTable.Cell(newTable.Rows.Count, cell.ColumnIndex).Range.Text = dgv.Columns[cell.ColumnIndex].Name;\n\n }\n newTable.Rows.Add();\n\n foreach (DataGridViewRow row in dgv.Rows)\n {\n foreach (DataGridViewCell cell in row.Cells)\n {\n newTable.Cell(newTable.Rows.Count, cell.ColumnIndex).Range.Text = cell.Value.ToString(); \n }\n newTable.Rows.Add();\n } \n }\n\n }\n</code></pre>\n" }, { "answer_id": 29876521, "author": "nassimlouchani", "author_id": 3261559, "author_profile": "https://Stackoverflow.com/users/3261559", "pm_score": 0, "selected": false, "text": "<p>You can try my method to export data to Word (*.docx) , it's easy to use and works 100% with any DataGridView , just add <strong>Microsoft.Office.Interop.Word</strong> reference and copy the following code :</p>\n\n<pre><code> using Word = Microsoft.Office.Interop.Word;\n\n public void Export_Data_To_Word(DataGridView DGV, string filename)\n {\n if (DGV.Rows.Count != 0)\n {\n int RowCount = DGV.Rows.Count;\n int ColumnCount = DGV.Columns.Count;\n Object[,] DataArray = new object[RowCount + 1, ColumnCount + 1];\n\n //add rows\n int r = 0;\n for (int c = 0; c &lt;= ColumnCount - 1; c++)\n {\n for (r = 0; r &lt;= RowCount - 1; r++)\n {\n DataArray[r, c] = DGV.Rows[r].Cells[c].Value;\n } //end row loop\n } //end column loop\n\n Word.Document oDoc = new Word.Document();\n oDoc.Application.Visible = true;\n\n //page orintation\n oDoc.PageSetup.Orientation = Word.WdOrientation.wdOrientLandscape;\n\n\n dynamic oRange = oDoc.Content.Application.Selection.Range;\n string oTemp = \"\";\n for (r = 0; r &lt;= RowCount - 1; r++)\n {\n for (int c = 0; c &lt;= ColumnCount - 1; c++)\n {\n oTemp = oTemp + DataArray[r, c] + \"\\t\";\n\n }\n }\n\n //table format\n oRange.Text = oTemp;\n\n object Separator = Word.WdTableFieldSeparator.wdSeparateByTabs;\n object ApplyBorders = true;\n object AutoFit = true;\n object AutoFitBehavior = Word.WdAutoFitBehavior.wdAutoFitContent;\n\n oRange.ConvertToTable(ref Separator, ref RowCount, ref ColumnCount,\n Type.Missing, Type.Missing, ref ApplyBorders,\n Type.Missing, Type.Missing, Type.Missing,\n Type.Missing, Type.Missing, Type.Missing,\n Type.Missing, ref AutoFit, ref AutoFitBehavior, Type.Missing);\n\n oRange.Select();\n\n oDoc.Application.Selection.Tables[1].Select();\n oDoc.Application.Selection.Tables[1].Rows.AllowBreakAcrossPages = 0;\n oDoc.Application.Selection.Tables[1].Rows.Alignment = 0;\n oDoc.Application.Selection.Tables[1].Rows[1].Select();\n oDoc.Application.Selection.InsertRowsAbove(1);\n oDoc.Application.Selection.Tables[1].Rows[1].Select();\n\n //header row style\n oDoc.Application.Selection.Tables[1].Rows[1].Range.Bold = 1;\n oDoc.Application.Selection.Tables[1].Rows[1].Range.Font.Name = \"Tahoma\";\n oDoc.Application.Selection.Tables[1].Rows[1].Range.Font.Size = 14;\n\n //add header row manually\n for (int c = 0; c &lt;= ColumnCount - 1; c++)\n {\n oDoc.Application.Selection.Tables[1].Cell(1, c + 1).Range.Text = DGV.Columns[c].HeaderText;\n }\n\n //table style \n oDoc.Application.Selection.Tables[1].set_Style(\"Grid Table 4 - Accent 5\");\n oDoc.Application.Selection.Tables[1].Rows[1].Select();\n oDoc.Application.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;\n\n //header text\n foreach (Word.Section section in oDoc.Application.ActiveDocument.Sections)\n {\n Word.Range headerRange = section.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;\n headerRange.Fields.Add(headerRange, Word.WdFieldType.wdFieldPage);\n headerRange.Text = \"your header text\";\n headerRange.Font.Size = 16;\n headerRange.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;\n }\n\n //save the file\n oDoc.SaveAs2(filename);\n\n //NASSIM LOUCHANI\n } \n }\n\n\n\n\n private void button_Click(object sender, EventArgs e)\n {\n SaveFileDialog sfd = new SaveFileDialog();\n\n sfd.Filter = \"Word Documents (*.docx)|*.docx\";\n\n sfd.FileName = \"export.docx\";\n\n if (sfd.ShowDialog() == DialogResult.OK)\n {\n\n Export_Data_To_Word(dataGridView1, sfd.FileName); \n }\n }\n</code></pre>\n\n<p>Thank you.</p>\n" }, { "answer_id": 59755161, "author": "Osiel López", "author_id": 12718905, "author_profile": "https://Stackoverflow.com/users/12718905", "pm_score": 0, "selected": false, "text": "<p>I have a code for insert table in to specific bookmark retreiving model in database, i hope helps community, i use mvc C#, microsoft office interop word for create a word file and add dynamic table from helper class</p>\n\n<pre><code>public void tableFromDatabase(Document doc, Application word, string risk, string bookmarkName, TableTemplate table) {\n Table newTable;//Create a new table\n Range wrdRng = doc.Bookmarks.get_Item(bookmarkName).Range;//Get a bookmark Range\n doc.Bookmarks[bookmarkName].Select();\n newTable = word.Selection.Tables.Add(wrdRng,1,1);//Add new table to selected bookmark by default set 1 row, 1 column (need set interval 1-63)\n newTable.Borders.InsideLineStyle = WdLineStyle.wdLineStyleSingle;\n newTable.Borders.OutsideLineStyle = WdLineStyle.wdLineStyleSingle;\n int a=0, b=0;//Set integer values for iterate in model arrays\n //Iterate model rows\n for (int i = 1; i &lt;= table.Rows.Count; i++)//Set in 1 the value because in word tables the begin is (1,1)\n {\n //Only add rows if is after first row\n if (i &gt; 1)\n {\n newTable.Rows.Add();\n }\n //Iterate model columns from rows\n for (int j = 1; j &lt;= table.Rows[a].Columns.Count; j++)\n {\n //Only Add rows if is after first\n if (j == 1 &amp;&amp; i == 1)\n {\n newTable.Cell(i, j).Range.Font.Name = table.Rows[a].Columns[b].cellFontName;\n newTable.Cell(i, j).Range.Font.Size = table.Rows[a].Columns[b].cellFontSize;\n newTable.Cell(i, j).Width = float.Parse(table.Rows[a].Columns[b].cellWidth);\n }\n else\n {\n //Add Cells to rows only if columns of the model is largen than table, this is for not exceed the interval\n if (newTable.Rows[i].Cells.Count &lt; table.Rows[a].Columns.Count)\n {\n newTable.Rows[i].Cells.Add();\n }\n //Set the values to new table\n //The width must be float type\n newTable.Cell(i, j).Range.Font.Name = table.Rows[a].Columns[b].cellFontName;\n newTable.Cell(i, j).Range.Font.Size = table.Rows[a].Columns[b].cellFontSize;\n newTable.Cell(i, j).Width = float.Parse(table.Rows[a].Columns[b].cellWidth);\n }\n b++;\n //Set 0 to reset cycle\n if (b == table.Rows[a].Columns.Count)\n {\n b = 0;\n }\n }\n a++;\n //Set 0 to reset cycle\n if (a == table.Rows.Count)\n {\n a = 0;\n }\n }\n newTable.Borders.InsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;\n newTable.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;\n newTable.AllowAutoFit = true;\n //Set gray color to borders\n newTable.Borders.InsideColor = (Microsoft.Office.Interop.Word.WdColor)12964311;\n newTable.Borders.OutsideColor = (Microsoft.Office.Interop.Word.WdColor)12964311;\n\n }\n</code></pre>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283523", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a C# application where i want to implement a logic for a programm which will open the word document and go to a certain place in the page and create a Table and put values in that. Can any one tell me how to implement this. I am using Visual studio 2005
Here is code to copy datagridview to a word table: Reference is Microsoft.Office.Interop.Word C:\Program Files (x86)\Microsoft Visual Studio 10.0\Visual Studio Tools for Office\PIA\Office12\Microsoft.Office.Interop.Word.dll ``` using word = Microsoft.Office.Interop.Word; public static void ExportToWord(DataGridView dgv) { SendMessage("Opening Word"); word.ApplicationClass word = null; word.Document doc = null; object oMissing = System.Reflection.Missing.Value; object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */ try { word = new word.ApplicationClass(); word.Visible = true; doc = word.Documents.Add(ref oMissing, ref oMissing,ref oMissing, ref oMissing); } catch (Exception ex) { ErrorLog(ex); } finally { } if (word != null && doc != null) { word.Table newTable; word.Range wrdRng = doc.Bookmarks.get_Item(ref oEndOfDoc).Range; newTable = doc.Tables.Add(wrdRng, 1, dgv.Columns.Count-1, ref oMissing, ref oMissing); newTable.Borders.InsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle; newTable.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle; newTable.AllowAutoFit = true; foreach (DataGridViewCell cell in dgv.Rows[0].Cells) { newTable.Cell(newTable.Rows.Count, cell.ColumnIndex).Range.Text = dgv.Columns[cell.ColumnIndex].Name; } newTable.Rows.Add(); foreach (DataGridViewRow row in dgv.Rows) { foreach (DataGridViewCell cell in row.Cells) { newTable.Cell(newTable.Rows.Count, cell.ColumnIndex).Range.Text = cell.Value.ToString(); } newTable.Rows.Add(); } } } ```
283,525
<p>This line:</p> <pre><code>strcat(query,*it); </code></pre> <p>(where <code>*it</code> is an iterator to a string)</p> <p>Keeps giving me this error:</p> <blockquote> <p>no matching function for call to ``strcat(char[200], const std::basic_string, std::allocator >&amp;)`' </p> </blockquote> <p>I guess it's because <code>strcat</code> takes in a <code>char*</code> while <code>*it</code> is a string. How do I convert it from a string to a <code>char*</code> to make it work with <code>strcat()</code> ?</p> <p>I've tried <code>strcat(query,(*it).c_str())</code> but that just gives me a runtime error.</p> <p>Edit: sorry, it should be converted to a <code>const char*</code></p>
[ { "answer_id": 283531, "author": "tragomaskhalos", "author_id": 31140, "author_profile": "https://Stackoverflow.com/users/31140", "pm_score": 3, "selected": false, "text": "<p><code>strcat(query,(*it).c_str())</code> should work. What's the runtime error? Are you sure that <code>query</code> is null-terminated before you make the call?</p>\n" }, { "answer_id": 283532, "author": "unwind", "author_id": 28169, "author_profile": "https://Stackoverflow.com/users/28169", "pm_score": 1, "selected": false, "text": "<p>You need to be more specific about which runtime error you get. Calling <code>c_str()</code> on the string should be the correct solution. As always with <code>strcat()</code> and other classic C string functions without bounds checking, you must be careful not to pass it too long of an input.</p>\n" }, { "answer_id": 283538, "author": "Stefan Rådström", "author_id": 19981, "author_profile": "https://Stackoverflow.com/users/19981", "pm_score": 0, "selected": false, "text": "<p>Try this (I assume that the runtime error is because of a NULL/invalid pointer):</p>\n\n<pre><code>for (...; it != str.end(); ++it)\n...\n if (!it-&gt;empty())\n {\n strcat(query, it-&gt;c_str());\n }\n</code></pre>\n\n<p>EDIT: Sorry, c_str() never returns NULL, which I temporarily forgot, so it is always safe. Unless the query buffer is not long enough to be able to contain all of the concatenated strings of course (or there is some other issue, like iterator beyond .end(), the container modified during the loop, or something similar).</p>\n" }, { "answer_id": 283699, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 2, "selected": false, "text": "<p>Buffer overflow?</p>\n\n<pre><code>char query[200] = {0}; // Make sure this array initialized before\n // you start concatenating strings onto it.\n\nfor (it = vec.begin();it != vec.end();++it)\n{\n if ((strlen(query) + it-&gt;length() + 1) &gt;= 200)\n {\n logError(\"Buffer oveflow detected.\";\n break;\n }\n strcat(query, it-&gt;c_str());\n}\n</code></pre>\n" }, { "answer_id": 284046, "author": "xtofl", "author_id": 6610, "author_profile": "https://Stackoverflow.com/users/6610", "pm_score": 1, "selected": false, "text": "<p>When you're sure about the length of the buffer you're <code>strcat</code>ting in (e.g. 200), better use <code>strncat</code>; this will rule out the Buffer Overflow mentioned by @Martin. Otherwies check for the total length before concatenating (<a href=\"http://www.cplusplus.com/reference/clibrary/cstring/strcat.html\" rel=\"nofollow noreferrer\">this is a precondition for its use</a>!)</p>\n\n<p>Queries typically become way longer than 200 characters, by the way. If you're not sure about the length of the resulting query, fall back on a dynamic string, like <code>std::string</code>.</p>\n" }, { "answer_id": 284143, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Is *it pointing at a valid string in all cases? Could it be pointing at end() in the last iteration? Or may be the container it points into got modified, invalidating *it.</p>\n" }, { "answer_id": 284395, "author": "Vinay", "author_id": 28641, "author_profile": "https://Stackoverflow.com/users/28641", "pm_score": 0, "selected": false, "text": "<p>If the application is in release mode, trace the application by putting the message boxes or by generating the interrupt 3. (_asm int 3;) in particular places. And if you have put the interrupt it exe will popup a debug message. Attach the process to Visual Studio to debug it.\nHope this way we can know the place of crash.</p>\n" }, { "answer_id": 284415, "author": "korona", "author_id": 25731, "author_profile": "https://Stackoverflow.com/users/25731", "pm_score": 2, "selected": false, "text": "<p>Use the debugger, Luke!</p>\n\n<p>(*it).c_str() Sure as hell should be a valid argument for strcat, assuming that your iterator is valid, and assuming that query is a null-terminated string, so should that. The quickest way to find out which of them are misbehaving is to watch it do so and inspect the values of it and query at runtime.</p>\n" }, { "answer_id": 285673, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 1, "selected": false, "text": "<p>Since you've ruled out that <code>query</code> is not null-terminated, it seems the consensus is that the problem is likely to be one of the following:</p>\n\n<ol>\n<li>buffer overflow - the buffer pointed to by <code>query</code> is\nnot large enough to have\n<code>(*it).c_str()</code> concatenated to it</li>\n<li><p>the itereator, <code>it</code>, is invalid. This can happen in several ways, including:</p>\n\n<ul>\n<li>not being properly initialized;</li>\n<li>has the value of someContainer.end();</li>\n<li>or the container has been modified in some way that invalidates an existing iterator</li>\n</ul></li>\n</ol>\n\n<p>You should be able to determine what's going on with a debugger. Also, I'm sure if you post more code, that shows how <code>query</code> and <code>it</code> are defined and used, you'll get a definitive answer here, too (how's that for remote debugging).</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283525", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28462/" ]
This line: ``` strcat(query,*it); ``` (where `*it` is an iterator to a string) Keeps giving me this error: > > no matching function for call to ``strcat(char[200], const std::basic\_string, std::allocator >&)`' > > > I guess it's because `strcat` takes in a `char*` while `*it` is a string. How do I convert it from a string to a `char*` to make it work with `strcat()` ? I've tried `strcat(query,(*it).c_str())` but that just gives me a runtime error. Edit: sorry, it should be converted to a `const char*`
`strcat(query,(*it).c_str())` should work. What's the runtime error? Are you sure that `query` is null-terminated before you make the call?
283,537
<p>Given a method signature:</p> <pre><code>public bool AreTheSame&lt;T&gt;(Expression&lt;Func&lt;T, object&gt;&gt; exp1, Expression&lt;Func&lt;T, object&gt;&gt; exp2) </code></pre> <p>What would be the most efficient way to say if the two expressions are the same? This only needs to work for simple expressions, by this I mean all that would be "supported" would be simple MemberExpressions, eg c => c.ID.</p> <p>An example call might be:</p> <pre><code>AreTheSame&lt;User&gt;(u1 =&gt; u1.ID, u2 =&gt; u2.ID); --&gt; would return true </code></pre>
[ { "answer_id": 283546, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 6, "selected": true, "text": "<p>Hmmm... I guess you'd have to parse the tree, checking the node-type and member of each. I'll knock up an example...</p>\n\n<pre><code>using System;\nusing System.Linq.Expressions;\nclass Test {\n public string Foo { get; set; }\n public string Bar { get; set; }\n static void Main()\n {\n bool test1 = FuncTest&lt;Test&gt;.FuncEqual(x =&gt; x.Bar, y =&gt; y.Bar),\n test2 = FuncTest&lt;Test&gt;.FuncEqual(x =&gt; x.Foo, y =&gt; y.Bar);\n }\n\n}\n// this only exists to make it easier to call, i.e. so that I can use FuncTest&lt;T&gt; with\n// generic-type-inference; if you use the doubly-generic method, you need to specify\n// both arguments, which is a pain...\nstatic class FuncTest&lt;TSource&gt;\n{\n public static bool FuncEqual&lt;TValue&gt;(\n Expression&lt;Func&lt;TSource, TValue&gt;&gt; x,\n Expression&lt;Func&lt;TSource, TValue&gt;&gt; y)\n {\n return FuncTest.FuncEqual&lt;TSource, TValue&gt;(x, y);\n }\n}\nstatic class FuncTest {\n public static bool FuncEqual&lt;TSource, TValue&gt;(\n Expression&lt;Func&lt;TSource,TValue&gt;&gt; x,\n Expression&lt;Func&lt;TSource,TValue&gt;&gt; y)\n {\n return ExpressionEqual(x, y);\n }\n private static bool ExpressionEqual(Expression x, Expression y)\n {\n // deal with the simple cases first...\n if (ReferenceEquals(x, y)) return true;\n if (x == null || y == null) return false;\n if ( x.NodeType != y.NodeType\n || x.Type != y.Type ) return false;\n\n switch (x.NodeType)\n {\n case ExpressionType.Lambda:\n return ExpressionEqual(((LambdaExpression)x).Body, ((LambdaExpression)y).Body);\n case ExpressionType.MemberAccess:\n MemberExpression mex = (MemberExpression)x, mey = (MemberExpression)y;\n return mex.Member == mey.Member; // should really test down-stream expression\n default:\n throw new NotImplementedException(x.NodeType.ToString());\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 24528357, "author": "neleus", "author_id": 2528649, "author_profile": "https://Stackoverflow.com/users/2528649", "pm_score": 6, "selected": false, "text": "<p><strong>UPDATE:</strong> Due to interest to my solution, I have updated the code so it supports arrays, new operators and other stuff and compares the ASTs in more elegant way.</p>\n\n<p>Here is an improved version of Marc's code and now <strong>it's available as a <a href=\"https://www.nuget.org/packages/Neleus.LambdaCompare/\" rel=\"noreferrer\">nuget package</a></strong>:</p>\n\n<pre><code>public static class LambdaCompare\n{\n public static bool Eq&lt;TSource, TValue&gt;(\n Expression&lt;Func&lt;TSource, TValue&gt;&gt; x,\n Expression&lt;Func&lt;TSource, TValue&gt;&gt; y)\n {\n return ExpressionsEqual(x, y, null, null);\n }\n\n public static bool Eq&lt;TSource1, TSource2, TValue&gt;(\n Expression&lt;Func&lt;TSource1, TSource2, TValue&gt;&gt; x,\n Expression&lt;Func&lt;TSource1, TSource2, TValue&gt;&gt; y)\n {\n return ExpressionsEqual(x, y, null, null);\n }\n\n public static Expression&lt;Func&lt;Expression&lt;Func&lt;TSource, TValue&gt;&gt;, bool&gt;&gt; Eq&lt;TSource, TValue&gt;(Expression&lt;Func&lt;TSource, TValue&gt;&gt; y)\n {\n return x =&gt; ExpressionsEqual(x, y, null, null);\n }\n\n private static bool ExpressionsEqual(Expression x, Expression y, LambdaExpression rootX, LambdaExpression rootY)\n {\n if (ReferenceEquals(x, y)) return true;\n if (x == null || y == null) return false;\n\n var valueX = TryCalculateConstant(x);\n var valueY = TryCalculateConstant(y);\n\n if (valueX.IsDefined &amp;&amp; valueY.IsDefined)\n return ValuesEqual(valueX.Value, valueY.Value);\n\n if (x.NodeType != y.NodeType\n || x.Type != y.Type)\n {\n if (IsAnonymousType(x.Type) &amp;&amp; IsAnonymousType(y.Type))\n throw new NotImplementedException(\"Comparison of Anonymous Types is not supported\");\n return false;\n }\n\n if (x is LambdaExpression)\n {\n var lx = (LambdaExpression)x;\n var ly = (LambdaExpression)y;\n var paramsX = lx.Parameters;\n var paramsY = ly.Parameters;\n return CollectionsEqual(paramsX, paramsY, lx, ly) &amp;&amp; ExpressionsEqual(lx.Body, ly.Body, lx, ly);\n }\n if (x is MemberExpression)\n {\n var mex = (MemberExpression)x;\n var mey = (MemberExpression)y;\n return Equals(mex.Member, mey.Member) &amp;&amp; ExpressionsEqual(mex.Expression, mey.Expression, rootX, rootY);\n }\n if (x is BinaryExpression)\n {\n var bx = (BinaryExpression)x;\n var by = (BinaryExpression)y;\n return bx.Method == @by.Method &amp;&amp; ExpressionsEqual(bx.Left, @by.Left, rootX, rootY) &amp;&amp;\n ExpressionsEqual(bx.Right, @by.Right, rootX, rootY);\n }\n if (x is UnaryExpression)\n {\n var ux = (UnaryExpression)x;\n var uy = (UnaryExpression)y;\n return ux.Method == uy.Method &amp;&amp; ExpressionsEqual(ux.Operand, uy.Operand, rootX, rootY);\n }\n if (x is ParameterExpression)\n {\n var px = (ParameterExpression)x;\n var py = (ParameterExpression)y;\n return rootX.Parameters.IndexOf(px) == rootY.Parameters.IndexOf(py);\n }\n if (x is MethodCallExpression)\n {\n var cx = (MethodCallExpression)x;\n var cy = (MethodCallExpression)y;\n return cx.Method == cy.Method\n &amp;&amp; ExpressionsEqual(cx.Object, cy.Object, rootX, rootY)\n &amp;&amp; CollectionsEqual(cx.Arguments, cy.Arguments, rootX, rootY);\n }\n if (x is MemberInitExpression)\n {\n var mix = (MemberInitExpression)x;\n var miy = (MemberInitExpression)y;\n return ExpressionsEqual(mix.NewExpression, miy.NewExpression, rootX, rootY)\n &amp;&amp; MemberInitsEqual(mix.Bindings, miy.Bindings, rootX, rootY);\n }\n if (x is NewArrayExpression)\n {\n var nx = (NewArrayExpression)x;\n var ny = (NewArrayExpression)y;\n return CollectionsEqual(nx.Expressions, ny.Expressions, rootX, rootY);\n }\n if (x is NewExpression)\n {\n var nx = (NewExpression)x;\n var ny = (NewExpression)y;\n return\n Equals(nx.Constructor, ny.Constructor)\n &amp;&amp; CollectionsEqual(nx.Arguments, ny.Arguments, rootX, rootY)\n &amp;&amp; (nx.Members == null &amp;&amp; ny.Members == null\n || nx.Members != null &amp;&amp; ny.Members != null &amp;&amp; CollectionsEqual(nx.Members, ny.Members));\n }\n if (x is ConditionalExpression)\n {\n var cx = (ConditionalExpression)x;\n var cy = (ConditionalExpression)y;\n return\n ExpressionsEqual(cx.Test, cy.Test, rootX, rootY)\n &amp;&amp; ExpressionsEqual(cx.IfFalse, cy.IfFalse, rootX, rootY)\n &amp;&amp; ExpressionsEqual(cx.IfTrue, cy.IfTrue, rootX, rootY);\n }\n\n throw new NotImplementedException(x.ToString());\n }\n\n private static Boolean IsAnonymousType(Type type)\n {\n Boolean hasCompilerGeneratedAttribute = type.GetCustomAttributes(typeof(CompilerGeneratedAttribute), false).Any();\n Boolean nameContainsAnonymousType = type.FullName.Contains(\"AnonymousType\");\n Boolean isAnonymousType = hasCompilerGeneratedAttribute &amp;&amp; nameContainsAnonymousType;\n\n return isAnonymousType;\n }\n\n private static bool MemberInitsEqual(ICollection&lt;MemberBinding&gt; bx, ICollection&lt;MemberBinding&gt; by, LambdaExpression rootX, LambdaExpression rootY)\n {\n if (bx.Count != by.Count)\n {\n return false;\n }\n\n if (bx.Concat(by).Any(b =&gt; b.BindingType != MemberBindingType.Assignment))\n throw new NotImplementedException(\"Only MemberBindingType.Assignment is supported\");\n\n return\n bx.Cast&lt;MemberAssignment&gt;().OrderBy(b =&gt; b.Member.Name).Select((b, i) =&gt; new { Expr = b.Expression, b.Member, Index = i })\n .Join(\n by.Cast&lt;MemberAssignment&gt;().OrderBy(b =&gt; b.Member.Name).Select((b, i) =&gt; new { Expr = b.Expression, b.Member, Index = i }),\n o =&gt; o.Index, o =&gt; o.Index, (xe, ye) =&gt; new { XExpr = xe.Expr, XMember = xe.Member, YExpr = ye.Expr, YMember = ye.Member })\n .All(o =&gt; Equals(o.XMember, o.YMember) &amp;&amp; ExpressionsEqual(o.XExpr, o.YExpr, rootX, rootY));\n }\n\n private static bool ValuesEqual(object x, object y)\n {\n if (ReferenceEquals(x, y))\n return true;\n if (x is ICollection &amp;&amp; y is ICollection)\n return CollectionsEqual((ICollection)x, (ICollection)y);\n\n return Equals(x, y);\n }\n\n private static ConstantValue TryCalculateConstant(Expression e)\n {\n if (e is ConstantExpression)\n return new ConstantValue(true, ((ConstantExpression)e).Value);\n if (e is MemberExpression)\n {\n var me = (MemberExpression)e;\n var parentValue = TryCalculateConstant(me.Expression);\n if (parentValue.IsDefined)\n {\n var result =\n me.Member is FieldInfo\n ? ((FieldInfo)me.Member).GetValue(parentValue.Value)\n : ((PropertyInfo)me.Member).GetValue(parentValue.Value);\n return new ConstantValue(true, result);\n }\n }\n if (e is NewArrayExpression)\n {\n var ae = ((NewArrayExpression)e);\n var result = ae.Expressions.Select(TryCalculateConstant);\n if (result.All(i =&gt; i.IsDefined))\n return new ConstantValue(true, result.Select(i =&gt; i.Value).ToArray());\n }\n if (e is ConditionalExpression)\n {\n var ce = (ConditionalExpression)e;\n var evaluatedTest = TryCalculateConstant(ce.Test);\n if (evaluatedTest.IsDefined)\n {\n return TryCalculateConstant(Equals(evaluatedTest.Value, true) ? ce.IfTrue : ce.IfFalse);\n }\n }\n\n return default(ConstantValue);\n }\n\n private static bool CollectionsEqual(IEnumerable&lt;Expression&gt; x, IEnumerable&lt;Expression&gt; y, LambdaExpression rootX, LambdaExpression rootY)\n {\n return x.Count() == y.Count()\n &amp;&amp; x.Select((e, i) =&gt; new { Expr = e, Index = i })\n .Join(y.Select((e, i) =&gt; new { Expr = e, Index = i }),\n o =&gt; o.Index, o =&gt; o.Index, (xe, ye) =&gt; new { X = xe.Expr, Y = ye.Expr })\n .All(o =&gt; ExpressionsEqual(o.X, o.Y, rootX, rootY));\n }\n\n private static bool CollectionsEqual(ICollection x, ICollection y)\n {\n return x.Count == y.Count\n &amp;&amp; x.Cast&lt;object&gt;().Select((e, i) =&gt; new { Expr = e, Index = i })\n .Join(y.Cast&lt;object&gt;().Select((e, i) =&gt; new { Expr = e, Index = i }),\n o =&gt; o.Index, o =&gt; o.Index, (xe, ye) =&gt; new { X = xe.Expr, Y = ye.Expr })\n .All(o =&gt; Equals(o.X, o.Y));\n }\n\n private struct ConstantValue\n {\n public ConstantValue(bool isDefined, object value)\n : this()\n {\n IsDefined = isDefined;\n Value = value;\n }\n\n public bool IsDefined { get; private set; }\n\n public object Value { get; private set; }\n }\n}\n</code></pre>\n\n<p>Note that it does not compare full AST. Instead, it collapses constant expressions and compares their values rather than their AST.\nIt is useful for mocks validation when the lambda has a reference to local variable. In his case the variable is compared by its value.</p>\n\n<p>Unit tests:</p>\n\n<pre><code>[TestClass]\npublic class Tests\n{\n [TestMethod]\n public void BasicConst()\n {\n var f1 = GetBasicExpr1();\n var f2 = GetBasicExpr2();\n Assert.IsTrue(LambdaCompare.Eq(f1, f2));\n }\n\n [TestMethod]\n public void PropAndMethodCall()\n {\n var f1 = GetPropAndMethodExpr1();\n var f2 = GetPropAndMethodExpr2();\n Assert.IsTrue(LambdaCompare.Eq(f1, f2));\n }\n\n [TestMethod]\n public void MemberInitWithConditional()\n {\n var f1 = GetMemberInitExpr1();\n var f2 = GetMemberInitExpr2();\n Assert.IsTrue(LambdaCompare.Eq(f1, f2));\n }\n\n [TestMethod]\n public void AnonymousType()\n {\n var f1 = GetAnonymousExpr1();\n var f2 = GetAnonymousExpr2();\n Assert.Inconclusive(\"Anonymous Types are not supported\");\n }\n\n private static Expression&lt;Func&lt;int, string, string&gt;&gt; GetBasicExpr2()\n {\n var const2 = \"some const value\";\n var const3 = \"{0}{1}{2}{3}\";\n return (i, s) =&gt;\n string.Format(const3, (i + 25).ToString(CultureInfo.InvariantCulture), i + s, const2.ToUpper(), 25);\n }\n\n private static Expression&lt;Func&lt;int, string, string&gt;&gt; GetBasicExpr1()\n {\n var const1 = 25;\n return (first, second) =&gt;\n string.Format(\"{0}{1}{2}{3}\", (first + const1).ToString(CultureInfo.InvariantCulture), first + second,\n \"some const value\".ToUpper(), const1);\n }\n\n private static Expression&lt;Func&lt;Uri, bool&gt;&gt; GetPropAndMethodExpr2()\n {\n return u =&gt; Uri.IsWellFormedUriString(u.ToString(), UriKind.Absolute);\n }\n\n private static Expression&lt;Func&lt;Uri, bool&gt;&gt; GetPropAndMethodExpr1()\n {\n return arg1 =&gt; Uri.IsWellFormedUriString(arg1.ToString(), UriKind.Absolute);\n }\n\n private static Expression&lt;Func&lt;Uri, UriBuilder&gt;&gt; GetMemberInitExpr2()\n {\n var isSecure = true;\n return u =&gt; new UriBuilder(u) { Host = string.IsNullOrEmpty(u.Host) ? \"abc\" : \"def\" , Port = isSecure ? 443 : 80 };\n }\n\n private static Expression&lt;Func&lt;Uri, UriBuilder&gt;&gt; GetMemberInitExpr1()\n {\n var port = 443;\n return x =&gt; new UriBuilder(x) { Port = port, Host = string.IsNullOrEmpty(x.Host) ? \"abc\" : \"def\" };\n }\n\n private static Expression&lt;Func&lt;Uri, object&gt;&gt; GetAnonymousExpr2()\n {\n return u =&gt; new { u.Host , Port = 443, Addr = u.AbsolutePath };\n }\n\n private static Expression&lt;Func&lt;Uri, object&gt;&gt; GetAnonymousExpr1()\n {\n return x =&gt; new { Port = 443, x.Host, Addr = x.AbsolutePath };\n }\n}\n</code></pre>\n" }, { "answer_id": 30875144, "author": "jnm2", "author_id": 521757, "author_profile": "https://Stackoverflow.com/users/521757", "pm_score": 2, "selected": false, "text": "<p>A canonical solution would be great. In the meantime, I created an <code>IEqualityComparer&lt;Expression&gt;</code> version.\nThis is rather a verbose implementation, so I <a href=\"https://gist.github.com/jnm2/83b36ad497b4cb1cbcac\" rel=\"nofollow\">created a gist for it</a>.</p>\n\n<p>It is intended to be a comprehensive abstract syntax tree comparer. To that end, it compares every expression type including expressions that aren't yet supported by C# like <code>Try</code> and <code>Switch</code> and <code>Block</code>. The only types it does not compare are <code>Goto</code>, <code>Label</code>, <code>Loop</code> and <code>DebugInfo</code> due to my limited knowledge of them.</p>\n\n<p>You can specify whether and how names of parameters and lambdas should be compared, as well as how to handle <code>ConstantExpression</code>.</p>\n\n<p>It tracks parameters positionally by context. Lambdas inside lambdas and catch block variable parameters are supported.</p>\n" }, { "answer_id": 37505702, "author": "Ryan.Bartsch", "author_id": 824434, "author_profile": "https://Stackoverflow.com/users/824434", "pm_score": 2, "selected": false, "text": "<p>I know this is an old question, but I rolled my own expression tree equality comparer - <a href=\"https://github.com/yesmarket/yesmarket.Linq.Expressions\" rel=\"nofollow\">https://github.com/yesmarket/yesmarket.Linq.Expressions</a></p>\n\n<p>The implementation makes heavy use of the ExpressionVisitor class to determine whether two expression trees are equal. As the nodes in the expression tree are traversed, individual nodes are compared for equality.</p>\n" }, { "answer_id": 61316588, "author": "Sebastian Xawery Wiśniowiecki", "author_id": 3099317, "author_profile": "https://Stackoverflow.com/users/3099317", "pm_score": 0, "selected": false, "text": "<p>I think most efficiency out of <code>Lambdas</code> you getting when you will use <em>lambda-efficient collection</em> - what I mean is <em>column-based collection</em> that can be enumerated by only one or more selected columns achieving this by implementing <code>IEnumerable</code> on each column separately - let's call it <strong>first step</strong> ;)</p>\n\n<p>That is only my idea that I want to do some day. I have no clues at the moment but I think many will agree with me that enumerating to check value through single variables list in compare to checking some property in list of objects is like proving itself. </p>\n\n<p>Next <strong>second step</strong> to get more from functional programming: use as a collections representing columns use <em>sorted-list</em>, <em>hash-table</em> or any other <em>search-efficient collection</em>.</p>\n\n<pre><code>class LambdaReadyColumn&lt;int&gt; : HashTable&lt;int&gt; \n</code></pre>\n\n<p>And another <strong>third step</strong> connect items between columns with some pointers so instead of keeping under-hood columns in: </p>\n\n<pre><code>class LambdaReadyColumn&lt;int&gt; : IEnumabrable&lt;int&gt; \n</code></pre>\n\n<p>keep data in something closer to:</p>\n\n<pre><code>class LambdaReadyColumn&lt;LambdaReadyColumnItem&lt;T, int&gt;&gt; : IEnumabrable&lt;int&gt; \n//with example constructor like: \npublic LambdaReadyColumn&lt;LambdaReadyColumnItem&lt;T, int&gt;&gt;(Hash, LambdaReadyColumnItem, LambdaReadyColumnItem, T, int); \n</code></pre>\n\n<p>where:</p>\n\n<ul>\n<li>CollectionItem - references to right and left column items of same T item</li>\n<li>Hash - to make search faster</li>\n<li>int - type representing column</li>\n<li>T - <strong>fourth step</strong> whole LambdaReadyCollection in column collection easily understanding simply to make <code>Select(T)</code> at the returning item descriptor faster but also avoiding traversing few references left/right for items with many properties.</li>\n</ul>\n\n<p>Finally with all the step we have collection with double data: row-based and collection based additionally lot of reference data.\nOf course row-based HashTable can keep data and column-based only references but than building every collection to return from the statement would use lot of referencing. </p>\n\n<p>To achieve it you need to use reflections, dynamic types or other advanced technique depending on the language.</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283537", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32855/" ]
Given a method signature: ``` public bool AreTheSame<T>(Expression<Func<T, object>> exp1, Expression<Func<T, object>> exp2) ``` What would be the most efficient way to say if the two expressions are the same? This only needs to work for simple expressions, by this I mean all that would be "supported" would be simple MemberExpressions, eg c => c.ID. An example call might be: ``` AreTheSame<User>(u1 => u1.ID, u2 => u2.ID); --> would return true ```
Hmmm... I guess you'd have to parse the tree, checking the node-type and member of each. I'll knock up an example... ``` using System; using System.Linq.Expressions; class Test { public string Foo { get; set; } public string Bar { get; set; } static void Main() { bool test1 = FuncTest<Test>.FuncEqual(x => x.Bar, y => y.Bar), test2 = FuncTest<Test>.FuncEqual(x => x.Foo, y => y.Bar); } } // this only exists to make it easier to call, i.e. so that I can use FuncTest<T> with // generic-type-inference; if you use the doubly-generic method, you need to specify // both arguments, which is a pain... static class FuncTest<TSource> { public static bool FuncEqual<TValue>( Expression<Func<TSource, TValue>> x, Expression<Func<TSource, TValue>> y) { return FuncTest.FuncEqual<TSource, TValue>(x, y); } } static class FuncTest { public static bool FuncEqual<TSource, TValue>( Expression<Func<TSource,TValue>> x, Expression<Func<TSource,TValue>> y) { return ExpressionEqual(x, y); } private static bool ExpressionEqual(Expression x, Expression y) { // deal with the simple cases first... if (ReferenceEquals(x, y)) return true; if (x == null || y == null) return false; if ( x.NodeType != y.NodeType || x.Type != y.Type ) return false; switch (x.NodeType) { case ExpressionType.Lambda: return ExpressionEqual(((LambdaExpression)x).Body, ((LambdaExpression)y).Body); case ExpressionType.MemberAccess: MemberExpression mex = (MemberExpression)x, mey = (MemberExpression)y; return mex.Member == mey.Member; // should really test down-stream expression default: throw new NotImplementedException(x.NodeType.ToString()); } } } ```
283,551
<p>I am struggling with a creating a query. It is related to a large and complicated database but for the sake of this post I have boiled the problem down to something simpler.</p> <p>I have three tables X, Y, Z defined as</p> <pre><code>CREATE TABLE [dbo].[X]( [ID] [bigint] NOT NULL ) CREATE TABLE [dbo].[Y]( [ID] [nchar](10) NOT NULL ) CREATE TABLE [dbo].[Z]( [IDX] [bigint] NOT NULL, [IDY] [nchar](10) NOT NULL ) </code></pre> <p>They contain the following data</p> <pre><code>Table X Table Y Table Z ID ID IDX IDY -- -- --- --- 1 A 1 A 2 B 1 B 3 C 1 A </code></pre> <p>I want to create a query that produces the following result</p> <pre><code>Count IDX IDY ===== === === 2 1 A 1 1 B 0 1 C 0 2 A 0 2 B 0 2 C 0 3 A 0 3 B 0 3 C </code></pre> <p>My initial thought was</p> <pre><code>SELECT COUNT(*), X.ID, Y.ID FROM X CROSS JOIN Y FULL OUTER JOIN Z ON X.ID = Z.IDX AND Y.ID = Z.IDY GROUP BY X.ID, Y.ID </code></pre> <p>but this turns out to be on the wrong road.</p> <p>Any ideas?</p>
[ { "answer_id": 283586, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 0, "selected": false, "text": "<pre><code>SELECT\n COUNT(z.idx) count,\n x.id idx,\n y.id idy\nFROM\n (x CROSS JOIN y)\n LEFT JOIN z ON z.idx = x.id AND z.idy = y.id\nGROUP BY\n x.id,\n y.id\nORDER BY\n COUNT(z.idx) DESC,\n x.id,\n y.id\n</code></pre>\n" }, { "answer_id": 283587, "author": "splattne", "author_id": 6461, "author_profile": "https://Stackoverflow.com/users/6461", "pm_score": 1, "selected": false, "text": "<p>This seems to work:</p>\n\n<pre><code>SELECT COUNT(*) AS CNT, IDX, IDY\nFROM Z\nGROUP BY IDX, IDY\nUNION\nSELECT 0, X.ID, Y.ID\nFROM X, Y\nWHERE NOT EXISTS (\n SELECT * FROM Z WHERE Z.IDX = X.ID AND Z.IDY = Y.ID\n)\nORDER BY CNT DESC\n</code></pre>\n" }, { "answer_id": 283604, "author": "Timothy Khouri", "author_id": 11917, "author_profile": "https://Stackoverflow.com/users/11917", "pm_score": 2, "selected": true, "text": "<pre><code>SELECT\n (SELECT COUNT(*) FROM Z WHERE IDX = X.ID AND IDY = Y.ID),\n X.ID,\n Y.ID\nFROM\n X,Y\n</code></pre>\n\n<p>That's your answer... why do you possibly want that query, no clue :)</p>\n" }, { "answer_id": 283641, "author": "Maxam", "author_id": 15310, "author_profile": "https://Stackoverflow.com/users/15310", "pm_score": 0, "selected": false, "text": "<pre><code>SELECT (SELECT(COUNT(*) FROM Z) AS COUNT, X.ID AS IDX, y.ID AS IDY\nFROM X CROSS JOIN Y \nORDER BY 1 DESC, 2, 3\n</code></pre>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283551", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am struggling with a creating a query. It is related to a large and complicated database but for the sake of this post I have boiled the problem down to something simpler. I have three tables X, Y, Z defined as ``` CREATE TABLE [dbo].[X]( [ID] [bigint] NOT NULL ) CREATE TABLE [dbo].[Y]( [ID] [nchar](10) NOT NULL ) CREATE TABLE [dbo].[Z]( [IDX] [bigint] NOT NULL, [IDY] [nchar](10) NOT NULL ) ``` They contain the following data ``` Table X Table Y Table Z ID ID IDX IDY -- -- --- --- 1 A 1 A 2 B 1 B 3 C 1 A ``` I want to create a query that produces the following result ``` Count IDX IDY ===== === === 2 1 A 1 1 B 0 1 C 0 2 A 0 2 B 0 2 C 0 3 A 0 3 B 0 3 C ``` My initial thought was ``` SELECT COUNT(*), X.ID, Y.ID FROM X CROSS JOIN Y FULL OUTER JOIN Z ON X.ID = Z.IDX AND Y.ID = Z.IDY GROUP BY X.ID, Y.ID ``` but this turns out to be on the wrong road. Any ideas?
``` SELECT (SELECT COUNT(*) FROM Z WHERE IDX = X.ID AND IDY = Y.ID), X.ID, Y.ID FROM X,Y ``` That's your answer... why do you possibly want that query, no clue :)
283,556
<p>I am trying to find the crc that works with the following results. The byte string consists of 2 bytes (ie. 0xCE1E) and the crc is an single byte (ie. 0x03)</p> <pre> byte crc CE1E 03 CE20 45 CE22 6F 0000 C0 0001 D4 FFFF 95 </pre> <p>Can anyone help?</p>
[ { "answer_id": 283643, "author": "The Archetypal Paul", "author_id": 21755, "author_profile": "https://Stackoverflow.com/users/21755", "pm_score": 2, "selected": false, "text": "<p>Assuming they are two byte (16 bit) values, I've tried a few on some online CRC generators without getting your results. So it looks like it's not a commonly used CRC algorithm.</p>\n\n<p>Do you have any clues about the likely algorithm? Or is this a homework assignment and you're supposed to reverse-engineer the CRC algorithm/parameters?</p>\n\n<p>Summary: more information needed.</p>\n" }, { "answer_id": 283684, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 2, "selected": false, "text": "<p>First, 4 hex digits aren't 4 bytes. Since all your examples show 4 hex digits -- 2 bytes -- I'll assume you mean 2 bytes.</p>\n\n<p>There are only 65,536 distinct hash values, here's what you do.</p>\n\n<p>Execute the hash function for all 65,536 values from 0000 to FFFF. Tabulate the results. That table <strong>is</strong> the function. It maps input value to output value.</p>\n\n<p>While lame, it's always correct, it's not terribly big (65K bytes), and it's really fast after you've done the calculation.</p>\n\n<p>You can't reverse engineer hash functions very easily. The good ones are sophisticated state machines that use all of the input bits in some \"fair\" way so that the output values are dramatically different for input values that differ by only a few bits.</p>\n\n<p>If you compare 0000 with 0001, 0002, 0004, 0008, 0010, 0020, 0040, 0080, 0100, 0200, 0400, 0800, 1000, 2000, 4000 and 8000, you might be able to figure out what each bit contributes to the hash. But I doubt it.</p>\n" }, { "answer_id": 283723, "author": "Svante", "author_id": 31615, "author_profile": "https://Stackoverflow.com/users/31615", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://www.geocities.com/SiliconValley/Pines/8659/crc.htm#r2\" rel=\"nofollow noreferrer\">http://www.geocities.com/SiliconValley/Pines/8659/crc.htm#r2</a></p>\n\n<p>It looks to my inexperienced eyes that you will have to implement a general crc algorithm and try it out with several polys (try the \"popular\" ones mentioned in that article first).</p>\n\n<p><em>edit</em>: after further reading, it seems that you have to take into account reverse polys too.</p>\n" }, { "answer_id": 848161, "author": "Eyal", "author_id": 4454, "author_profile": "https://Stackoverflow.com/users/4454", "pm_score": 2, "selected": false, "text": "<p>A CRC is simply division, just like you learn long-hand division in grade school except that add and subtract are replaced with XOR. So what you need to do is solve the following equations in GF(2):</p>\n\n<pre><code>CE1E % p = 03\nCE20 % p = 45\nCE22 % p = 6F\n0000 % p = C0\n0001 % p = D4\nFFFF % p = 95\n</code></pre>\n\n<p>There is no polynomial p for which 0000%p = c0. (0 modulo p is 0 for all values of p.) So maybe it's (x+input) % p = crc. In your case, x must be c0. If that's true, then (x+0001)%p must be c1. Looks like it isn't a CRC at all. If you're determined and you believe that the answer is linear, make a matrix of zeroes and ones that is invertible and solve the set of equations that arises from your matrix times input = output. You'll need more inputs, though.</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am trying to find the crc that works with the following results. The byte string consists of 2 bytes (ie. 0xCE1E) and the crc is an single byte (ie. 0x03) ``` byte crc CE1E 03 CE20 45 CE22 6F 0000 C0 0001 D4 FFFF 95 ``` Can anyone help?
Assuming they are two byte (16 bit) values, I've tried a few on some online CRC generators without getting your results. So it looks like it's not a commonly used CRC algorithm. Do you have any clues about the likely algorithm? Or is this a homework assignment and you're supposed to reverse-engineer the CRC algorithm/parameters? Summary: more information needed.
283,561
<p>Inspired by <a href="https://stackoverflow.com/questions/277106/looking-for-some-interesting-c-programming-problems">this question</a>, I wanted to try my hand at the latest <a href="http://domino.research.ibm.com/Comm/wwwr_ponder.nsf/Challenges/November2008.html" rel="nofollow noreferrer">ponder this challenge</a>, using F#</p> <p>My approach is probably completely off course, but in the course of solving this problem, I'm trying to get a list of all the permutations of the digits 0-9.</p> <p>I'm looking at solving it using a n-ary tree like so:</p> <pre><code>type Node = | Branch of (int * Node list) | Leaf of int </code></pre> <p>I'm quite pleased with myself, because I've managed to work out how to generate the tree that I want. </p> <p>My problem now is that I can't work out how to traverse this tree and extract the 'path' to each leaf as an int. Thing thing that is confusing me is that I need to match on individual Nodes, but my 'outer' function needs to take a Node list.</p> <p>My current attempt almost does the right thing, except that it returns me the sum of all the paths...</p> <pre><code>let test = Branch(3, [Branch(2, [Leaf(1)]);Branch(1, [Leaf(2)])]) let rec visitor lst acc = let inner n = match n with | Leaf(h) -&gt; acc * 10 + h | Branch(h, t) -&gt; visitor t (acc * 10 + h) List.map inner lst |&gt; List.sum visitor [test] 0 //-&gt; gives 633 (which is 321 + 312) </code></pre> <p>And I'm not even sure that this is tail-recursive.</p> <p>(You're quite welcome to propose another solution for finding permutations, but I'm still interested in the solution to this particular problem)</p> <p>EDIT: I've posted a generic permutations algorithm in F# <a href="https://stackoverflow.com/questions/286427/calculating-permutations-in-f">here</a>.</p>
[ { "answer_id": 283638, "author": "Tomas Petricek", "author_id": 33518, "author_profile": "https://Stackoverflow.com/users/33518", "pm_score": 4, "selected": true, "text": "<p>regarding your question about list traversal - you can start by writing a function that returns lists that represent the path - that's I think easier and it will be later easy to turn it into a function that returns a number.</p>\n\n<p>This one takes a list as the first argument (path so far) and a tree and returns a list> type - that is all the possible paths from the current branch.</p>\n\n<pre><code>let rec visitor lst tree = \n match tree with\n | Branch(n, sub) -&gt; List.collect (visitor (n::lst)) sub\n | Leaf(n) -&gt; [List.rev (n::lst)]\n\n// For example...\n&gt; let tr = Branch(1, [Leaf(3); Branch(2, [Leaf(4); Leaf(5)] )]);;\n&gt; visitor [] tr;;\nval it : int list list = [[1; 3]; [1; 2; 4]; [1; 2; 5]]\n</code></pre>\n\n<p>In the 'Leaf' case, we simply add the current number to the list and return the result as a list containing single list (we have to reverse it first, because we were adding numbers to the beginning).\nIn the 'Branch' case, we add 'n' to the list and recursively call the visitor to process all the sub-nodes of the current branch. This returns a bunch of lists and we use 'map_concat' to turn them into a single list that contains all posble paths from the current branch.</p>\n\n<p>Now, you can rewrite this to return a list of integers:</p>\n\n<pre><code>let rec visitor2 lst tree = \n match tree with\n | Branch(n, sub) -&gt; List.collect (visitor2 (lst * 10 + n)) sub\n | Leaf(n) -&gt; [lst * 10 + n]\n\n// For example... \n&gt; visitor2 0 tr;;\nval it : int list = [13; 124; 125] \n</code></pre>\n\n<p>Instead of concatenating lists, we now calculate the number.</p>\n" }, { "answer_id": 283736, "author": "Tomas Petricek", "author_id": 33518, "author_profile": "https://Stackoverflow.com/users/33518", "pm_score": 2, "selected": false, "text": "<p>Regarding laziness - \nYou can make this lazy by using F# \"seq\" type instead of \"list\" type. Here is an example:</p>\n\n<pre><code>let rec visitor2 lst tree =\n match tree with\n | Branch(n, sub) -&gt; Seq.map_concat (visitor2 (lst * 10 + n)) sub\n | Leaf(n) -&gt;\n seq { do printfn \"--yielding: %d\" (lst * 10 + n)\n yield lst * 10 + n };;\n</code></pre>\n\n<p>The \"seq\" thing is a sequence expression, which represents a lazy stream of values. I added \"printfn\" to the code, so we can track how things are executing:</p>\n\n<pre><code>&gt; visitor2 0 tr |&gt; Seq.take 2;;\n--yielding: 13\n--yielding: 124\nval it : seq&lt;int&gt; = seq [13; 124]\n</code></pre>\n\n<p>You can probably use something like Seq.first to find the first value which represents the result.</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11410/" ]
Inspired by [this question](https://stackoverflow.com/questions/277106/looking-for-some-interesting-c-programming-problems), I wanted to try my hand at the latest [ponder this challenge](http://domino.research.ibm.com/Comm/wwwr_ponder.nsf/Challenges/November2008.html), using F# My approach is probably completely off course, but in the course of solving this problem, I'm trying to get a list of all the permutations of the digits 0-9. I'm looking at solving it using a n-ary tree like so: ``` type Node = | Branch of (int * Node list) | Leaf of int ``` I'm quite pleased with myself, because I've managed to work out how to generate the tree that I want. My problem now is that I can't work out how to traverse this tree and extract the 'path' to each leaf as an int. Thing thing that is confusing me is that I need to match on individual Nodes, but my 'outer' function needs to take a Node list. My current attempt almost does the right thing, except that it returns me the sum of all the paths... ``` let test = Branch(3, [Branch(2, [Leaf(1)]);Branch(1, [Leaf(2)])]) let rec visitor lst acc = let inner n = match n with | Leaf(h) -> acc * 10 + h | Branch(h, t) -> visitor t (acc * 10 + h) List.map inner lst |> List.sum visitor [test] 0 //-> gives 633 (which is 321 + 312) ``` And I'm not even sure that this is tail-recursive. (You're quite welcome to propose another solution for finding permutations, but I'm still interested in the solution to this particular problem) EDIT: I've posted a generic permutations algorithm in F# [here](https://stackoverflow.com/questions/286427/calculating-permutations-in-f).
regarding your question about list traversal - you can start by writing a function that returns lists that represent the path - that's I think easier and it will be later easy to turn it into a function that returns a number. This one takes a list as the first argument (path so far) and a tree and returns a list> type - that is all the possible paths from the current branch. ``` let rec visitor lst tree = match tree with | Branch(n, sub) -> List.collect (visitor (n::lst)) sub | Leaf(n) -> [List.rev (n::lst)] // For example... > let tr = Branch(1, [Leaf(3); Branch(2, [Leaf(4); Leaf(5)] )]);; > visitor [] tr;; val it : int list list = [[1; 3]; [1; 2; 4]; [1; 2; 5]] ``` In the 'Leaf' case, we simply add the current number to the list and return the result as a list containing single list (we have to reverse it first, because we were adding numbers to the beginning). In the 'Branch' case, we add 'n' to the list and recursively call the visitor to process all the sub-nodes of the current branch. This returns a bunch of lists and we use 'map\_concat' to turn them into a single list that contains all posble paths from the current branch. Now, you can rewrite this to return a list of integers: ``` let rec visitor2 lst tree = match tree with | Branch(n, sub) -> List.collect (visitor2 (lst * 10 + n)) sub | Leaf(n) -> [lst * 10 + n] // For example... > visitor2 0 tr;; val it : int list = [13; 124; 125] ``` Instead of concatenating lists, we now calculate the number.
283,575
<p>I'm using the ReportViewer control to display a Report within a WebForm, i've also implemented the "Export to Excel" feature, by calling the Render method of the Server Report</p> <p>eg</p> <pre><code>ReportViewerControl.ServerReport.Render("Excel",etc,etc,etc); </code></pre> <p>My problem is that the exported report contains Hyperlinks that link to other reports, I wish these to appear in the webform but not appear hence be disabled in the Exported Spreadsheet (generated by the Code above).</p> <p>Does anyone have a way of achieving this?</p> <p>Thanks</p>
[ { "answer_id": 283638, "author": "Tomas Petricek", "author_id": 33518, "author_profile": "https://Stackoverflow.com/users/33518", "pm_score": 4, "selected": true, "text": "<p>regarding your question about list traversal - you can start by writing a function that returns lists that represent the path - that's I think easier and it will be later easy to turn it into a function that returns a number.</p>\n\n<p>This one takes a list as the first argument (path so far) and a tree and returns a list> type - that is all the possible paths from the current branch.</p>\n\n<pre><code>let rec visitor lst tree = \n match tree with\n | Branch(n, sub) -&gt; List.collect (visitor (n::lst)) sub\n | Leaf(n) -&gt; [List.rev (n::lst)]\n\n// For example...\n&gt; let tr = Branch(1, [Leaf(3); Branch(2, [Leaf(4); Leaf(5)] )]);;\n&gt; visitor [] tr;;\nval it : int list list = [[1; 3]; [1; 2; 4]; [1; 2; 5]]\n</code></pre>\n\n<p>In the 'Leaf' case, we simply add the current number to the list and return the result as a list containing single list (we have to reverse it first, because we were adding numbers to the beginning).\nIn the 'Branch' case, we add 'n' to the list and recursively call the visitor to process all the sub-nodes of the current branch. This returns a bunch of lists and we use 'map_concat' to turn them into a single list that contains all posble paths from the current branch.</p>\n\n<p>Now, you can rewrite this to return a list of integers:</p>\n\n<pre><code>let rec visitor2 lst tree = \n match tree with\n | Branch(n, sub) -&gt; List.collect (visitor2 (lst * 10 + n)) sub\n | Leaf(n) -&gt; [lst * 10 + n]\n\n// For example... \n&gt; visitor2 0 tr;;\nval it : int list = [13; 124; 125] \n</code></pre>\n\n<p>Instead of concatenating lists, we now calculate the number.</p>\n" }, { "answer_id": 283736, "author": "Tomas Petricek", "author_id": 33518, "author_profile": "https://Stackoverflow.com/users/33518", "pm_score": 2, "selected": false, "text": "<p>Regarding laziness - \nYou can make this lazy by using F# \"seq\" type instead of \"list\" type. Here is an example:</p>\n\n<pre><code>let rec visitor2 lst tree =\n match tree with\n | Branch(n, sub) -&gt; Seq.map_concat (visitor2 (lst * 10 + n)) sub\n | Leaf(n) -&gt;\n seq { do printfn \"--yielding: %d\" (lst * 10 + n)\n yield lst * 10 + n };;\n</code></pre>\n\n<p>The \"seq\" thing is a sequence expression, which represents a lazy stream of values. I added \"printfn\" to the code, so we can track how things are executing:</p>\n\n<pre><code>&gt; visitor2 0 tr |&gt; Seq.take 2;;\n--yielding: 13\n--yielding: 124\nval it : seq&lt;int&gt; = seq [13; 124]\n</code></pre>\n\n<p>You can probably use something like Seq.first to find the first value which represents the result.</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30861/" ]
I'm using the ReportViewer control to display a Report within a WebForm, i've also implemented the "Export to Excel" feature, by calling the Render method of the Server Report eg ``` ReportViewerControl.ServerReport.Render("Excel",etc,etc,etc); ``` My problem is that the exported report contains Hyperlinks that link to other reports, I wish these to appear in the webform but not appear hence be disabled in the Exported Spreadsheet (generated by the Code above). Does anyone have a way of achieving this? Thanks
regarding your question about list traversal - you can start by writing a function that returns lists that represent the path - that's I think easier and it will be later easy to turn it into a function that returns a number. This one takes a list as the first argument (path so far) and a tree and returns a list> type - that is all the possible paths from the current branch. ``` let rec visitor lst tree = match tree with | Branch(n, sub) -> List.collect (visitor (n::lst)) sub | Leaf(n) -> [List.rev (n::lst)] // For example... > let tr = Branch(1, [Leaf(3); Branch(2, [Leaf(4); Leaf(5)] )]);; > visitor [] tr;; val it : int list list = [[1; 3]; [1; 2; 4]; [1; 2; 5]] ``` In the 'Leaf' case, we simply add the current number to the list and return the result as a list containing single list (we have to reverse it first, because we were adding numbers to the beginning). In the 'Branch' case, we add 'n' to the list and recursively call the visitor to process all the sub-nodes of the current branch. This returns a bunch of lists and we use 'map\_concat' to turn them into a single list that contains all posble paths from the current branch. Now, you can rewrite this to return a list of integers: ``` let rec visitor2 lst tree = match tree with | Branch(n, sub) -> List.collect (visitor2 (lst * 10 + n)) sub | Leaf(n) -> [lst * 10 + n] // For example... > visitor2 0 tr;; val it : int list = [13; 124; 125] ``` Instead of concatenating lists, we now calculate the number.
283,589
<p>is there a way to change an oracle user's default schema?</p> <p>I found it in the FAQ that I can alter it in the session, but it's not what I want. E.G. the user at log on always sees another schema as default.</p> <p>Thanks in advance.</p>
[ { "answer_id": 283814, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 6, "selected": true, "text": "<p>I believe a logon trigger should work:</p>\n\n<pre><code>CREATE OR REPLACE TRIGGER db_logon\nAFTER logon ON DATABASE WHEN (USER = 'A')\nBEGIN\n execute immediate 'ALTER SESSION SET CURRENT_SCHEMA = B';\nEND;\n</code></pre>\n" }, { "answer_id": 809549, "author": "Ryan Cook", "author_id": 43029, "author_profile": "https://Stackoverflow.com/users/43029", "pm_score": 4, "selected": false, "text": "<p>For some reason Tony's trigger did not work for me. However, a slightly different trigger that I found on the web using the same concept did.</p>\n\n<pre><code>create or replace trigger set_default_schema\nafter logon on my_user.schema\nbegin\n execute immediate 'alter session set current_schema=NEW_SCHEMA';\nend;\n</code></pre>\n\n<p>I just wanted to throw it out there in case someone else has the same issue.</p>\n" }, { "answer_id": 12915088, "author": "Greg", "author_id": 1750074, "author_profile": "https://Stackoverflow.com/users/1750074", "pm_score": 1, "selected": false, "text": "<pre><code>create or replace trigger AFTER_LOGON_TSFREL\nAFTER LOGON ON \"TSFRELEASEAPP\".SCHEMA\nBEGIN\n EXECUTE IMMEDIATE 'ALTER SESSION SET current_schema=TSF_RELEASE';\nEND;\n</code></pre>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283589", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11621/" ]
is there a way to change an oracle user's default schema? I found it in the FAQ that I can alter it in the session, but it's not what I want. E.G. the user at log on always sees another schema as default. Thanks in advance.
I believe a logon trigger should work: ``` CREATE OR REPLACE TRIGGER db_logon AFTER logon ON DATABASE WHEN (USER = 'A') BEGIN execute immediate 'ALTER SESSION SET CURRENT_SCHEMA = B'; END; ```
283,594
<p>I am adding membership-related schemas to an existing database (lets call it myDatabase) following <a href="https://web.archive.org/web/20210506052241/http://aspnet.4guysfromrolla.com/articles/040506-1.aspx" rel="nofollow noreferrer">those instructions</a>.</p> <p>As a results the number of tables, views and stored procedures are being created in myDatabase.</p> <p>The next step is to modify web.config for the application to use CustomizedMembershipProvider</p> <pre><code>&lt;membership defaultProvider="CustomizedMembershipProvider"&gt; &lt;providers&gt; &lt;add name="CustomizedMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="MyDBConnectionString" /&gt; &lt;/providers&gt; &lt;/membership&gt; </code></pre> <p>Then we also need to specify the connection string like:</p> <pre><code>&lt;connectionStrings&gt; &lt;add name="MyDB" MyDBConnectionString ="..." /&gt; &lt;/connectionStrings&gt; </code></pre> <p><strong>Here is my question:</strong></p> <ol> <li>Should I use different connection string to the one the application uses? As is there a need to create a new user in the database with permissions related specifically to the membership objects?</li> <li>Once the connection string is specified with the User ID etc., do I need to grant permissions for that user for those newly created objects? Would that be for stored procedures only or also tables and views?</li> </ol> <p><strong>EDIT:</strong> I noticed that there was a set of roles created in the database along with the membership object. So it is a matter of assigning the user to the proper role(s). The roles are the likes of </p> <pre><code>aspnet_Membership_FullAccess aspnet_Personalization_FullAccess etc... </code></pre> <p>So the only the first part of the question remains in place. So is there a point in creating a new database user (so separate db connection)</p>
[ { "answer_id": 283682, "author": "Jonas Lincoln", "author_id": 17436, "author_profile": "https://Stackoverflow.com/users/17436", "pm_score": 0, "selected": false, "text": "<ol>\n<li>It's perfectly okay to use the same user/database as your application.</li>\n<li>I don't know, sorry. </li>\n</ol>\n" }, { "answer_id": 283700, "author": "John Lemp", "author_id": 12915, "author_profile": "https://Stackoverflow.com/users/12915", "pm_score": 0, "selected": false, "text": "<p>I would recommend using the same connection string for performance reasons. Using the same connection string as your application will allow more efficient connection pooling.</p>\n" }, { "answer_id": 283711, "author": "Robert Vuković", "author_id": 438025, "author_profile": "https://Stackoverflow.com/users/438025", "pm_score": 2, "selected": false, "text": "<p>Some good texts about Membership Provider:</p>\n\n<ul>\n<li><a href=\"https://web.archive.org/web/20210513220018/http://aspnet.4guysfromrolla.com/articles/120705-1.aspx\" rel=\"nofollow noreferrer\">Examining ASP.NET 2.0's Membership, Roles, and Profile</a></li>\n<li><a href=\"http://odetocode.com/Articles/427.aspx\" rel=\"nofollow noreferrer\">Membership and Role Providers in ASP.NET 2.0 Part</a></li>\n</ul>\n" }, { "answer_id": 283733, "author": "kristof", "author_id": 3241, "author_profile": "https://Stackoverflow.com/users/3241", "pm_score": 3, "selected": true, "text": "<p>I looked it up a bit, </p>\n\n<ol>\n<li>The standard connection can be used</li>\n<li>In terms of permissions it looks\nlike it is a matter of assigning the\ndatabase user to the\naspnet_Membership_FullAccess role (<a href=\"http://msdn.microsoft.com/en-us/library/ms164596(VS.80).aspx\" rel=\"nofollow noreferrer\">other roles if you require privileges related to them</a>)</li>\n</ol>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3241/" ]
I am adding membership-related schemas to an existing database (lets call it myDatabase) following [those instructions](https://web.archive.org/web/20210506052241/http://aspnet.4guysfromrolla.com/articles/040506-1.aspx). As a results the number of tables, views and stored procedures are being created in myDatabase. The next step is to modify web.config for the application to use CustomizedMembershipProvider ``` <membership defaultProvider="CustomizedMembershipProvider"> <providers> <add name="CustomizedMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="MyDBConnectionString" /> </providers> </membership> ``` Then we also need to specify the connection string like: ``` <connectionStrings> <add name="MyDB" MyDBConnectionString ="..." /> </connectionStrings> ``` **Here is my question:** 1. Should I use different connection string to the one the application uses? As is there a need to create a new user in the database with permissions related specifically to the membership objects? 2. Once the connection string is specified with the User ID etc., do I need to grant permissions for that user for those newly created objects? Would that be for stored procedures only or also tables and views? **EDIT:** I noticed that there was a set of roles created in the database along with the membership object. So it is a matter of assigning the user to the proper role(s). The roles are the likes of ``` aspnet_Membership_FullAccess aspnet_Personalization_FullAccess etc... ``` So the only the first part of the question remains in place. So is there a point in creating a new database user (so separate db connection)
I looked it up a bit, 1. The standard connection can be used 2. In terms of permissions it looks like it is a matter of assigning the database user to the aspnet\_Membership\_FullAccess role ([other roles if you require privileges related to them](http://msdn.microsoft.com/en-us/library/ms164596(VS.80).aspx))
283,608
<p>I have quite a large list of words in a txt file and I'm trying to do a regex find and replace in Notepad++. I need to add a string before each line and after each line.. So that:</p> <pre> wordone wordtwo wordthree </pre> <p>become</p> <pre> able:"wordone" able:"wordtwo" able:"wordthree" </pre> <p>How can I do this?</p>
[ { "answer_id": 283613, "author": "Jonathan Lonowski", "author_id": 15031, "author_profile": "https://Stackoverflow.com/users/15031", "pm_score": 9, "selected": true, "text": "<p>Assuming alphanumeric words, you can use:</p>\n\n<pre><code>Search = ^([A-Za-z0-9]+)$\nReplace = able:\"\\1\"\n</code></pre>\n\n<p>Or, if you just want to highlight the lines and use \"Replace All\" &amp; \"In Selection\" (with the same replace):</p>\n\n<pre><code>Search = ^(.+)$\n</code></pre>\n\n<p><code>^</code> points to the start of the line.<br>\n<code>$</code> points to the end of the line.</p>\n\n<p><code>\\1</code> will be the source match within the parentheses.</p>\n" }, { "answer_id": 283617, "author": "Rob Stevenson-Leggett", "author_id": 4950, "author_profile": "https://Stackoverflow.com/users/4950", "pm_score": 3, "selected": false, "text": "<p>Use a Macro.</p>\n\n<p>Macro>Start Recording</p>\n\n<p>Use the keyboard to make your changes in a repeatable manner e.g.</p>\n\n<p>home>type \"able\">end>down arrow>home</p>\n\n<p>Then go back to the menu and click stop recording then run a macro multiple times.</p>\n\n<p>That should do it and no regex based complications!</p>\n" }, { "answer_id": 5730261, "author": "Peter Perháč", "author_id": 81520, "author_profile": "https://Stackoverflow.com/users/81520", "pm_score": 5, "selected": false, "text": "<p>Why don't you use the Notepad++ multiline editing capabilities?</p>\n\n<p>Hold down Alt while selecting text (using your usual click-and-drag approach) to select text across multiple lines. This is sometimes also referred to as column editing.</p>\n\n<p>You could place the cursor at the beginning of the file, Press (and hold) Alt, Shift and then just keep pressing the down-arrow or PageDown to select the lines that you want to prepend with some text :-) Easy. Multiline editing is a very useful feature of Notepad++. It's also possible in Visual Studio, in the same manner, and also in Eclipse by switching to Block Selection Mode by pressing Alt+Shift+A and then use mouse to select text across lines.</p>\n" }, { "answer_id": 44923194, "author": "Mukul Aggarwal", "author_id": 4544947, "author_profile": "https://Stackoverflow.com/users/4544947", "pm_score": 5, "selected": false, "text": "<p>Regular Expression that can be used:</p>\n\n<pre><code>Find: \\w.+\nReplace: able:\"$&amp;\"\n</code></pre>\n\n<p>As, <code>$&amp;</code> will give you the string you search for.</p>\n\n<p>Refer: <a href=\"http://regexr.com/\" rel=\"noreferrer\">regexr</a></p>\n" }, { "answer_id": 66091220, "author": "luky", "author_id": 4870273, "author_profile": "https://Stackoverflow.com/users/4870273", "pm_score": 1, "selected": false, "text": "<p>In visual studio code i found that simple regex as ^ worked.</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26823/" ]
I have quite a large list of words in a txt file and I'm trying to do a regex find and replace in Notepad++. I need to add a string before each line and after each line.. So that: ``` wordone wordtwo wordthree ``` become ``` able:"wordone" able:"wordtwo" able:"wordthree" ``` How can I do this?
Assuming alphanumeric words, you can use: ``` Search = ^([A-Za-z0-9]+)$ Replace = able:"\1" ``` Or, if you just want to highlight the lines and use "Replace All" & "In Selection" (with the same replace): ``` Search = ^(.+)$ ``` `^` points to the start of the line. `$` points to the end of the line. `\1` will be the source match within the parentheses.
283,632
<p>I followed the commonly-linked tip for reducing an application to the system tray : <a href="http://www.developer.com/net/csharp/article.php/3336751" rel="noreferrer">http://www.developer.com/net/csharp/article.php/3336751</a> Now it works, but there is still a problem : my application is shown when it starts ; I want it to start directly in the systray. I tried to minimize and hide it in the Load event, but it does nothing.</p> <p>Edit : I could, as a poster suggested, modify the shortcut properties, but I'd rather use code : I don't have complete control over every computer the soft is installed on.</p> <p>I don't want to remove it completely from everywhere except the systray, I just want it to start minimized.</p> <p>Any ideas ?</p> <p>Thanks</p>
[ { "answer_id": 283640, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "<p>If you are using a <code>NotifyIcon</code>, try changing ShowInTaskbar to false.</p>\n\n<p>To remove it from the Alt+Tab screen, try changing your window border style; I believe some of the tool-window styles don't appear...</p>\n\n<p>something like:</p>\n\n<pre><code>using System;\nusing System.Windows.Forms;\nclass MyForm : Form\n{\n NotifyIcon sysTray;\n\n MyForm()\n {\n sysTray = new NotifyIcon();\n sysTray.Icon = System.Drawing.SystemIcons.Asterisk;\n sysTray.Visible = true;\n sysTray.Text = \"Hi there\";\n sysTray.MouseClick += delegate { MessageBox.Show(\"Boo!\"); };\n\n ShowInTaskbar = false;\n FormBorderStyle = FormBorderStyle.SizableToolWindow;\n Opacity = 0;\n WindowState = FormWindowState.Minimized;\n }\n\n [STAThread]\n static void Main()\n {\n Application.EnableVisualStyles();\n Application.Run(new MyForm());\n }\n}\n</code></pre>\n\n<p>If it still appears in the Alt+Tab, you can change the window styles through p/invoke (a bit hackier):</p>\n\n<pre><code>protected override void OnLoad(EventArgs e)\n{\n base.OnLoad(e);\n IntPtr handle = this.Handle;\n int currentStyle = GetWindowLong(handle, GWL_EXSTYLE);\n SetWindowLong(handle, GWL_EXSTYLE, currentStyle | WS_EX_TOOLWINDOW);\n}\nprivate const int GWL_EXSTYLE = -20, WS_EX_TOOLWINDOW = 0x00000080;\n[System.Runtime.InteropServices.DllImport(\"user32.dll\")]\nprivate static extern int SetWindowLong(IntPtr window, int index, int value);\n[System.Runtime.InteropServices.DllImport(\"user32.dll\")]\nprivate static extern int GetWindowLong(IntPtr window, int index);\n</code></pre>\n" }, { "answer_id": 283644, "author": "xan", "author_id": 15667, "author_profile": "https://Stackoverflow.com/users/15667", "pm_score": 2, "selected": false, "text": "<p>As a bit of a cludge, you could configure the shortcut that launches your app to \"run minimised\"? That might give you what you need!</p>\n\n<p>Like so: (image just an example from google)...</p>\n\n<p><a href=\"https://i.stack.imgur.com/MadYl.gif\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/MadYl.gif\" alt=\"Run Minimized\"></a><br>\n<sub>(source: <a href=\"http://www.unixwiz.net/images/ygpm-shortcut-4.gif\" rel=\"nofollow noreferrer\">unixwiz.net</a>)</sub> </p>\n" }, { "answer_id": 283649, "author": "lubos hasko", "author_id": 275, "author_profile": "https://Stackoverflow.com/users/275", "pm_score": 4, "selected": false, "text": "<p>this is how you do it</p>\n\n<pre><code>static class Program\n{\n [STAThread]\n static void Main()\n {\n NotifyIcon icon = new NotifyIcon();\n icon.Icon = System.Drawing.SystemIcons.Application;\n icon.Click += delegate { MessageBox.Show(\"Bye!\"); icon.Visible = false; Application.Exit(); };\n icon.Visible = true;\n Application.Run();\n }\n}\n</code></pre>\n" }, { "answer_id": 283683, "author": "Sunlight", "author_id": 33650, "author_profile": "https://Stackoverflow.com/users/33650", "pm_score": 6, "selected": true, "text": "<p>In your main program you probably have a line of the form:</p>\n\n<pre><code>Application.Run(new Form1());\n</code></pre>\n\n<p>This will force the form to be shown. You will need to create the form but <em>not</em> pass it to <code>Application.Run</code>:</p>\n\n<pre><code>Form1 form = new Form1();\nApplication.Run();\n</code></pre>\n\n<p>Note that the program will now not terminate until you call <code>Application.ExitThread()</code>. It's best to do this from a handler for the <code>FormClosed</code> event.</p>\n\n<pre><code>private void Form1_FormClosed(object sender, FormClosedEventArgs e)\n{\n Application.ExitThread();\n}\n</code></pre>\n" }, { "answer_id": 283855, "author": "rjrapson", "author_id": 1616, "author_profile": "https://Stackoverflow.com/users/1616", "pm_score": 1, "selected": false, "text": "<p>Since this was tagged with vb.net, here's what I did in a Windows Service and Controller app I just finished, Add a code module to the project, Setup the NotifyIcon and it's associated Context menu in Sub Main(), and then set the application's Startup Object to the Sub Main() instead of the Form. </p>\n\n<pre><code>Public mobNotifyIcon As NotifyIcon\nPublic WithEvents mobContextMenu As ContextMenu\n\nPublic Sub Main()\n\n mobContextMenu = New ContextMenu\n SetupMenu()\n mobNotifyIcon = New NotifyIcon()\n With mobNotifyIcon\n .Icon = My.Resources.NotifyIcon\n .ContextMenu = mobContextMenu\n .BalloonTipText = String.Concat(\"Monitor the EDS Transfer Service\", vbCrLf, \"Right click icon for menu\")\n .BalloonTipIcon = ToolTipIcon.Info\n .BalloonTipTitle = \"EDS Transfer Monitor\"\n .Text = \"EDS Transfer Service Monitor\"\n AddHandler .MouseClick, AddressOf showBalloon\n .Visible = True\n End With\n Application.Run()\nEnd Sub\n\nPrivate Sub SetupMenu()\n With mobContextMenu\n\n .MenuItems.Add(New MenuItem(\"Configure\", New EventHandler(AddressOf Config)))\n .MenuItems.Add(\"-\")\n .MenuItems.Add(New MenuItem(\"Start\", New EventHandler(AddressOf StartService)))\n .MenuItems.Add(New MenuItem(\"Stop\", New EventHandler(AddressOf StopService)))\n .MenuItems.Add(\"-\")\n .MenuItems.Add(New MenuItem(\"Exit\", New EventHandler(AddressOf ExitController)))\n End With\n GetServiceStatus()\nEnd Sub\n</code></pre>\n\n<p>In the Config(), I create an instance of my form and display it.</p>\n\n<pre><code>Private Sub Config(ByVal sender As Object, ByVal e As EventArgs)\n Using cs As New ConfigureService\n cs.Show()\n End Using\n\nEnd Sub\n</code></pre>\n" }, { "answer_id": 284446, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Here you go:</p>\n\n<p>Create 2 classes, 1 which inherits from ApplicationContext. The other only contains a Main routine. I've made an example that has a form and a notifyicon that when double clicked brings up the form and back again.</p>\n\n<p>Remember to set \"Sub Main\" as your startup object in My Project settings and point to a real *.ico file instead of f:\\TP.ico .. :)</p>\n\n<p>Code should of course be stuffed with proper error handling code. </p>\n\n<p>Class1:</p>\n\n<pre><code>Imports System.threading \nImports System.Runtime.InteropServices \nImports System.Windows.Forms\n\n\nPublic Class Class1\n\n &lt;System.STAThread()&gt; _\n Public Shared Sub Main()\n\n Try\n System.Windows.Forms.Application.EnableVisualStyles()\n System.Windows.Forms.Application.DoEvents()\n System.Windows.Forms.Application.Run(New Class2)\n Catch invEx As Exception\n\n Application.Exit()\n\n End Try\n\n\n End Sub 'Main End Class \n</code></pre>\n\n<p>Class2:</p>\n\n<pre><code>Imports System.Windows.Forms \nImports System.drawing\n\nPublic Class Class2\n Inherits System.Windows.Forms.ApplicationContext\n\n Private WithEvents f As New System.Windows.Forms.Form\n Private WithEvents nf As New System.Windows.Forms.NotifyIcon\n\n Public Sub New()\n\n f.Size = New Drawing.Size(50, 50)\n f.StartPosition = FormStartPosition.CenterScreen\n f.WindowState = Windows.Forms.FormWindowState.Minimized\n f.ShowInTaskbar = False\n nf.Visible = True\n nf.Icon = New Icon(\"f:\\TP.ico\")\n End Sub\n\n\n Private Sub nf_DoubleClick(ByVal sender As Object, ByVal e As EventArgs) Handles nf.DoubleClick\n If f.WindowState &lt;&gt; Windows.Forms.FormWindowState.Minimized Then\n f.WindowState = Windows.Forms.FormWindowState.Minimized\n f.Hide()\n Else\n f.WindowState = Windows.Forms.FormWindowState.Normal\n f.Show()\n End If\n End Sub\n\n Private Sub f_FormClosed(ByVal sender As Object, ByVal e As FormClosedEventArgs) Handles f.FormClosed\n Application.Exit()\n End Sub End Class\n</code></pre>\n" }, { "answer_id": 398039, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>This shows you how to control startup as minimized or normal as well as much more with NotifyIcon.</p>\n\n<p>More here: <a href=\"http://code.msdn.microsoft.com/TheNotifyIconExample\" rel=\"nofollow noreferrer\">http://code.msdn.microsoft.com/TheNotifyIconExample</a></p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6776/" ]
I followed the commonly-linked tip for reducing an application to the system tray : <http://www.developer.com/net/csharp/article.php/3336751> Now it works, but there is still a problem : my application is shown when it starts ; I want it to start directly in the systray. I tried to minimize and hide it in the Load event, but it does nothing. Edit : I could, as a poster suggested, modify the shortcut properties, but I'd rather use code : I don't have complete control over every computer the soft is installed on. I don't want to remove it completely from everywhere except the systray, I just want it to start minimized. Any ideas ? Thanks
In your main program you probably have a line of the form: ``` Application.Run(new Form1()); ``` This will force the form to be shown. You will need to create the form but *not* pass it to `Application.Run`: ``` Form1 form = new Form1(); Application.Run(); ``` Note that the program will now not terminate until you call `Application.ExitThread()`. It's best to do this from a handler for the `FormClosed` event. ``` private void Form1_FormClosed(object sender, FormClosedEventArgs e) { Application.ExitThread(); } ```
283,636
<p>We need to set up a secure certificate on an Apache reverse proxy. We've been advised that we need to use a virtual host directive.</p> <p>I've looked these up in the O'Reilly book bit can't find any examples that pick up https specifically.</p> <p>Does anyone have any examples of config snippets to do this?</p>
[ { "answer_id": 283663, "author": "f4nt", "author_id": 14838, "author_profile": "https://Stackoverflow.com/users/14838", "pm_score": 2, "selected": false, "text": "<p>Not sure if this is what you're after, but I used something like the following in the past:</p>\n\n<pre><code>&lt;IfModule mod_ssl.c&gt;\n SSLProxyEngine On\n ProxyPreserveHost On\n RewriteRule ^/whatever(.*)$ https://otherhost/whatever$1 [P]\n&lt;/IfModule&gt;\n</code></pre>\n\n<p>I needed to proxy secure content from another host, and that's what we ended up using. Works fine, and has for some time now. Does that sort of cover what you're looking for?</p>\n" }, { "answer_id": 283665, "author": "Till", "author_id": 2859, "author_profile": "https://Stackoverflow.com/users/2859", "pm_score": 3, "selected": true, "text": "<p>I'm not exactly sure what you are asking for, but there are multiple things you need. For example, you need to get a SSL certificate, then you need to install mod_ssl into your Apache. I suggest you install it using your system's package manager, etc..</p>\n\n<p>This is an example virtualhost:</p>\n\n<pre><code>&lt;VirtualHost IP.ADDRESS.HERE:443&gt;\n DocumentRoot /web/domain.com/www/htdocs\n\n ServerName www.domain.com\n ServerAdmin [email protected]\n\n SSLEngine on\n SSLCertificateFile /usr/local/etc/apache/ssl.crt/www.domain.com.crt\n SSLCertificateKeyFile /usr/local/etc/apache/ssl.key/www.domain.com.key\n\n ErrorLog \"/var/logs/domain.com/error_log\"\n CustomLog \"|/usr/local/sbin/cronolog /var/logs/domain.com/%Y/%m/access_log\" combined\n&lt;/VirtualHost&gt;\n</code></pre>\n\n<p>A proxy configuration inside the <code>&lt;VirtualHost /&gt;</code> can look different. This assumes that the domain points to a directory on your server, but what you do inside <code>&lt;VirtualHost /&gt;</code> is up to you.</p>\n\n<p>As I said, I also had to install ssl into Apache, to load the module I needed the following:</p>\n\n<pre><code>LoadModule ssl_module libexec/apache/libssl.so\n...\nAddModule mod_ssl.c\n</code></pre>\n\n<p>And that's basically it. Let me know if you need more pointers. In case, it also helps if you tell us if you run Apache 1.3 or 2.x.</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283636", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39447/" ]
We need to set up a secure certificate on an Apache reverse proxy. We've been advised that we need to use a virtual host directive. I've looked these up in the O'Reilly book bit can't find any examples that pick up https specifically. Does anyone have any examples of config snippets to do this?
I'm not exactly sure what you are asking for, but there are multiple things you need. For example, you need to get a SSL certificate, then you need to install mod\_ssl into your Apache. I suggest you install it using your system's package manager, etc.. This is an example virtualhost: ``` <VirtualHost IP.ADDRESS.HERE:443> DocumentRoot /web/domain.com/www/htdocs ServerName www.domain.com ServerAdmin [email protected] SSLEngine on SSLCertificateFile /usr/local/etc/apache/ssl.crt/www.domain.com.crt SSLCertificateKeyFile /usr/local/etc/apache/ssl.key/www.domain.com.key ErrorLog "/var/logs/domain.com/error_log" CustomLog "|/usr/local/sbin/cronolog /var/logs/domain.com/%Y/%m/access_log" combined </VirtualHost> ``` A proxy configuration inside the `<VirtualHost />` can look different. This assumes that the domain points to a directory on your server, but what you do inside `<VirtualHost />` is up to you. As I said, I also had to install ssl into Apache, to load the module I needed the following: ``` LoadModule ssl_module libexec/apache/libssl.so ... AddModule mod_ssl.c ``` And that's basically it. Let me know if you need more pointers. In case, it also helps if you tell us if you run Apache 1.3 or 2.x.
283,645
<p>I have a python list, say l</p> <pre><code>l = [1,5,8] </code></pre> <p>I want to write a sql query to get the data for all the elements of the list, say</p> <pre><code>select name from students where id = |IN THE LIST l| </code></pre> <p>How do I accomplish this?</p>
[ { "answer_id": 283706, "author": "gimel", "author_id": 6491, "author_profile": "https://Stackoverflow.com/users/6491", "pm_score": 4, "selected": false, "text": "<p><a href=\"http://docs.python.org/library/stdtypes.html#str.join\" rel=\"nofollow noreferrer\">string.join</a> the list values separated by commas, and use the <a href=\"http://docs.python.org/library/stdtypes.html#string-formatting\" rel=\"nofollow noreferrer\">format operator</a> to form a query string.</p>\n\n<pre><code>myquery = \"select name from studens where id in (%s)\" % \",\".join(map(str,mylist))\n</code></pre>\n\n<p>(Thanks, <a href=\"https://stackoverflow.com/users/1199/blair-conrad\">blair-conrad</a>)</p>\n" }, { "answer_id": 283713, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 5, "selected": false, "text": "<p>The SQL you want is</p>\n\n<pre><code>select name from studens where id in (1, 5, 8)\n</code></pre>\n\n<p>If you want to construct this from the python you could use</p>\n\n<pre><code>l = [1, 5, 8]\nsql_query = 'select name from studens where id in (' + ','.join(map(str, l)) + ')'\n</code></pre>\n\n<p>The <a href=\"http://docs.python.org/library/functions.html#map\" rel=\"noreferrer\">map</a> function will transform the list into a list of strings that can be glued together by commas using the <a href=\"http://docs.python.org/library/stdtypes.html#str.join\" rel=\"noreferrer\">str.join</a> method.</p>\n\n<p>Alternatively:</p>\n\n<pre><code>l = [1, 5, 8]\nsql_query = 'select name from studens where id in (' + ','.join((str(n) for n in l)) + ')'\n</code></pre>\n\n<p>if you prefer <a href=\"http://docs.python.org/glossary.html#term-generator-expression\" rel=\"noreferrer\">generator expressions</a> to the map function.</p>\n\n<p>UPDATE: <a href=\"https://stackoverflow.com/users/10661/slott\">S. Lott</a> mentions in the comments that the Python SQLite bindings don't support sequences. In that case, you might want</p>\n\n<pre><code>select name from studens where id = 1 or id = 5 or id = 8\n</code></pre>\n\n<p>Generated by </p>\n\n<pre><code>sql_query = 'select name from studens where ' + ' or '.join(('id = ' + str(n) for n in l))\n</code></pre>\n" }, { "answer_id": 283801, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 8, "selected": true, "text": "<p>Answers so far have been templating the values into a plain SQL string. That's absolutely fine for integers, but if we wanted to do it for strings we get the escaping issue.</p>\n<p>Here's a variant using a parameterised query that would work for both:</p>\n<pre class=\"lang-python prettyprint-override\"><code>placeholder= '?' # For SQLite. See DBAPI paramstyle.\nplaceholders= ', '.join(placeholder for unused in l)\nquery= 'SELECT name FROM students WHERE id IN (%s)' % placeholders\ncursor.execute(query, l)\n</code></pre>\n" }, { "answer_id": 4233213, "author": "jimhark", "author_id": 514485, "author_profile": "https://Stackoverflow.com/users/514485", "pm_score": 3, "selected": false, "text": "<p>I like bobince's answer:</p>\n\n<pre><code>placeholder= '?' # For SQLite. See DBAPI paramstyle.\nplaceholders= ', '.join(placeholder for unused in l)\nquery= 'SELECT name FROM students WHERE id IN (%s)' % placeholders\ncursor.execute(query, l)\n</code></pre>\n\n<p>But I noticed this:</p>\n\n<pre><code>placeholders= ', '.join(placeholder for unused in l)\n</code></pre>\n\n<p>Can be replaced with:</p>\n\n<pre><code>placeholders= ', '.join(placeholder*len(l))\n</code></pre>\n\n<p>I find this more direct if less clever and less general. Here <code>l</code> is required to have a length (i.e. refer to an object that defines a <code>__len__</code> method), which shouldn't be a problem. But placeholder must also be a single character. To support a multi-character placeholder use:</p>\n\n<pre><code>placeholders= ', '.join([placeholder]*len(l))\n</code></pre>\n" }, { "answer_id": 27145241, "author": "Ximix", "author_id": 2592043, "author_profile": "https://Stackoverflow.com/users/2592043", "pm_score": 2, "selected": false, "text": "<p>Solution for @umounted answer, because that broke with a one-element tuple, since (1,) is not valid SQL.:</p>\n\n<pre><code>&gt;&gt;&gt; random_ids = [1234,123,54,56,57,58,78,91]\n&gt;&gt;&gt; cursor.execute(\"create table test (id)\")\n&gt;&gt;&gt; for item in random_ids:\n cursor.execute(\"insert into test values (%d)\" % item)\n&gt;&gt;&gt; sublist = [56,57,58]\n&gt;&gt;&gt; cursor.execute(\"select id from test where id in %s\" % str(tuple(sublist)).replace(',)',')'))\n&gt;&gt;&gt; a = cursor.fetchall()\n&gt;&gt;&gt; a\n[(56,), (57,), (58,)]\n</code></pre>\n\n<p>Other solution for sql string:</p>\n\n<pre><code>cursor.execute(\"select id from test where id in (%s)\" % ('\"'+'\", \"'.join(l)+'\"'))\n</code></pre>\n" }, { "answer_id": 39024751, "author": "pgalilea", "author_id": 1510734, "author_profile": "https://Stackoverflow.com/users/1510734", "pm_score": 0, "selected": false, "text": "<p>For example, if you want the sql query:</p>\n\n<pre><code>select name from studens where id in (1, 5, 8)\n</code></pre>\n\n<p>What about:</p>\n\n<pre><code>my_list = [1, 5, 8]\ncur.execute(\"select name from studens where id in %s\" % repr(my_list).replace('[','(').replace(']',')') )\n</code></pre>\n" }, { "answer_id": 40737575, "author": "ALLSYED", "author_id": 5270699, "author_profile": "https://Stackoverflow.com/users/5270699", "pm_score": 5, "selected": false, "text": "<p>Dont complicate it, Solution for this is simple.</p>\n\n<pre><code>l = [1,5,8]\n\nl = tuple(l)\n\nparams = {'l': l}\n\ncursor.execute('SELECT * FROM table where id in %(l)s',params)\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/5Vbsg.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/5Vbsg.png\" alt=\"enter image description here\"></a></p>\n\n<p>I hope this helped !!!</p>\n" }, { "answer_id": 49679494, "author": "Amir Imani", "author_id": 6509765, "author_profile": "https://Stackoverflow.com/users/6509765", "pm_score": 7, "selected": false, "text": "<p>Easiest way is to turn the list to <code>tuple</code> first</p>\n\n<pre><code>t = tuple(l)\nquery = \"select name from studens where id IN {}\".format(t)\n</code></pre>\n" }, { "answer_id": 51091831, "author": "Roland Mechler", "author_id": 10008063, "author_profile": "https://Stackoverflow.com/users/10008063", "pm_score": 0, "selected": false, "text": "<p>This uses parameter substitution and takes care of the single value list case:</p>\n\n<pre><code>l = [1,5,8]\n\nget_operator = lambda x: '=' if len(x) == 1 else 'IN'\nget_value = lambda x: int(x[0]) if len(x) == 1 else x\n\nquery = 'SELECT * FROM table where id ' + get_operator(l) + ' %s'\n\ncursor.execute(query, (get_value(l),))\n</code></pre>\n" }, { "answer_id": 54646596, "author": "Rishabh Jain", "author_id": 6692436, "author_profile": "https://Stackoverflow.com/users/6692436", "pm_score": 2, "selected": false, "text": "<pre><code>placeholders= ', '.join(\"'{\"+str(i)+\"}'\" for i in range(len(l)))\nquery=\"select name from students where id (%s)\"%placeholders\nquery=query.format(*l)\ncursor.execute(query)\n</code></pre>\n\n<p>This should solve your problem.</p>\n" }, { "answer_id": 55802128, "author": "Omar Omeiri", "author_id": 11127541, "author_profile": "https://Stackoverflow.com/users/11127541", "pm_score": 2, "selected": false, "text": "<p>a simpler solution:</p>\n\n<pre><code>lst = [1,2,3,a,b,c]\n\nquery = f\"\"\"SELECT * FROM table WHERE IN {str(lst)[1:-1}\"\"\"\n</code></pre>\n" }, { "answer_id": 59399870, "author": "Sam Mason", "author_id": 1358308, "author_profile": "https://Stackoverflow.com/users/1358308", "pm_score": 2, "selected": false, "text": "<p>If you're using PostgreSQL with the Psycopg2 library you can let its <a href=\"http://initd.org/psycopg/docs/usage.html#tuples-adaptation\" rel=\"nofollow noreferrer\">tuple adaption</a> do all the escaping and string interpolation for you, e.g:</p>\n\n<pre><code>ids = [1,2,3]\ncur.execute(\n \"SELECT * FROM foo WHERE id IN %s\",\n [tuple(ids)])\n</code></pre>\n\n<p>i.e. just make sure that you're passing the <code>IN</code> parameter as a <code>tuple</code>. if it's a <code>list</code> you can use the <a href=\"https://www.postgresql.org/docs/10/functions-comparisons.html#id-1.5.8.28.16\" rel=\"nofollow noreferrer\"><code>= ANY</code> array syntax</a>:</p>\n\n<pre><code>cur.execute(\n \"SELECT * FROM foo WHERE id = ANY (%s)\",\n [list(ids)])\n</code></pre>\n\n<p>note that these both will get turned into the same query plan so you should just use whichever is easier. e.g. if your list comes in a tuple use the former, if they're stored in a list use the latter.</p>\n" }, { "answer_id": 62024363, "author": "user13476428", "author_id": 13476428, "author_profile": "https://Stackoverflow.com/users/13476428", "pm_score": 2, "selected": false, "text": "<pre><code>l = [1] # or [1,2,3]\n\nquery = \"SELECT * FROM table WHERE id IN :l\"\nparams = {'l' : tuple(l)}\ncursor.execute(query, params)\n</code></pre>\n\n<p>The <code>:var</code> notation seems simpler. (Python 3.7)</p>\n" }, { "answer_id": 63620667, "author": "raj", "author_id": 11040181, "author_profile": "https://Stackoverflow.com/users/11040181", "pm_score": 1, "selected": false, "text": "<p>This Will Work If Number of Values in List equals to 1 or greater than 1</p>\n<pre><code>t = str(tuple(l))\nif t[-2] == ',':\n t= t.replace(t[-2],&quot;&quot;)\nquery = &quot;select name from studens where id IN {}&quot;.format(t)\n</code></pre>\n" }, { "answer_id": 64024678, "author": "Greed Ruler", "author_id": 4830065, "author_profile": "https://Stackoverflow.com/users/4830065", "pm_score": 2, "selected": false, "text": "<p>Just use inline if operation with tuple function:</p>\n<pre><code>query = &quot;Select * from hr_employee WHERE id in &quot; % tuple(employee_ids) if len(employee_ids) != 1 else &quot;(&quot;+ str(employee_ids[0]) + &quot;)&quot;\n</code></pre>\n" }, { "answer_id": 64998540, "author": "citynorman", "author_id": 3140992, "author_profile": "https://Stackoverflow.com/users/3140992", "pm_score": 2, "selected": false, "text": "<p>To run a select from where field is in list of strings (instead of int), <a href=\"https://stackoverflow.com/questions/6741185/add-quotes-to-every-list-element\">as per this question</a> use <code>repr(tuple(map(str, l)))</code>. Full example:</p>\n<pre><code>l = ['a','b','c']\nsql = f'''\n\nselect name \nfrom students \nwhere id in {repr(tuple(map(str, l)))}\n'''\nprint(sql)\n</code></pre>\n<p>Returns:\n<code> select name from students where id in ('a', 'b', 'c')</code></p>\n<p>For a list of dates in Oracle, this worked</p>\n<pre><code>dates_str = ','.join([f'DATE {repr(s)}' for s in ['2020-11-24', '2020-12-28']])\ndates_str = f'({dates_str})'\n\nsql_cmd = f'''\nselect *\nfrom students \nwhere \nand date in {dates_str}\n'''\n</code></pre>\n<p>Returns:\n<code>select * from students where and date in (DATE '2020-11-24',DATE '2020-12-28')</code></p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283645", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2220518/" ]
I have a python list, say l ``` l = [1,5,8] ``` I want to write a sql query to get the data for all the elements of the list, say ``` select name from students where id = |IN THE LIST l| ``` How do I accomplish this?
Answers so far have been templating the values into a plain SQL string. That's absolutely fine for integers, but if we wanted to do it for strings we get the escaping issue. Here's a variant using a parameterised query that would work for both: ```python placeholder= '?' # For SQLite. See DBAPI paramstyle. placeholders= ', '.join(placeholder for unused in l) query= 'SELECT name FROM students WHERE id IN (%s)' % placeholders cursor.execute(query, l) ```
283,646
<p>I have just converted a project from Visual Studio 2003 to 2005 and although most of it 'converted' fine, I have a series of STL errors from the following line:</p> <pre><code>void SomeFn( std::vector&lt;CSomeObject*&gt;::iterator it, std::vector&lt;CSomeObject*&gt;::iterator itBegin = NULL, std::vector&lt;CSomeObject*&gt;::iterator itEnd = NULL ); </code></pre> <p>The Visual Studio error is as follows:</p> <pre><code>c:\&lt;path&gt;\Headerfile.h(20) : error C2440: 'default argument' : cannot convert from 'int' to 'std::_Vector_iterator&lt;_Ty,_Alloc&gt;' with [ _Ty=CObject *, _Alloc=std::allocator&lt;CObject *&gt; ] No constructor could take the source type, or constructor overload resolution was ambiguous </code></pre> <p>I can't see anything wrong with that code and it worked perfectly in VS 2003. Any ideas?</p>
[ { "answer_id": 283660, "author": "Sunlight", "author_id": 33650, "author_profile": "https://Stackoverflow.com/users/33650", "pm_score": 2, "selected": false, "text": "<p>In 2003, <code>std::vector&lt;T&gt;::iterator</code> is just <code>T *</code>. In 2005, at least in debug mode, it is a class, and hence you can't use <code>NULL</code> for its value (<code>NULL</code> resolves to <code>0</code>).</p>\n\n<p>You can use a default-constructed iterator instead:</p>\n\n<pre><code>std::vector&lt;CSomeObject*&gt;::iterator itBegin = std::vector&lt;CSomeObject*&gt;::iterator()\n</code></pre>\n" }, { "answer_id": 283693, "author": "PierreBdR", "author_id": 7136, "author_profile": "https://Stackoverflow.com/users/7136", "pm_score": 5, "selected": true, "text": "<p>Your program is incorrect as NULL cannot be converted as an iterator. I don't really know what you want these iterators to be initialized as. If you need an iterator guarantied not to be in a container but to be still \"valid\", you can use a default-constructor:</p>\n\n<pre><code>typedef std::vector&lt;CSomeObject*&gt; myvector_t;\nvoid SomeFn( myvector_t::iterator it,\n myvector_t::iterator itBegin = myvector_t::iterator(),\n myvector_t::iterator itEnd = myvector_t::iterator() );\n</code></pre>\n\n<p>Note, however, that if you do so, <code>it</code>, <code>itBegin</code> and <code>itEnd</code> won't be comparable in a meaningful way! Only iterators obtained from a given container are comparable meaningfully. In the end, I would recommend against using defaults values for <code>itBegin</code> and <code>itEnd</code>. If you really need to not have these, create another function without the arguments and do something meaningful. i.e.:</p>\n\n<pre><code>typedef std::vector&lt;CSomeObject*&gt; myvector_t;\nvoid SomeFn( myvector_t::iterator it,\n myvector_t::iterator itBegin,\n myvector_t::iterator itEnd );\nvoid SomeFn( myvector_t::iterator it ); // No begin/end arguments\n</code></pre>\n\n<p>Another problem of your program is the use of a vector to store pointers. This is really unsafe. Make sure you never erase elements from the vector without deleting the element first. You might also have problems with algorithms copying objects around. It is better to use smart pointers in vectors.</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283646", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18664/" ]
I have just converted a project from Visual Studio 2003 to 2005 and although most of it 'converted' fine, I have a series of STL errors from the following line: ``` void SomeFn( std::vector<CSomeObject*>::iterator it, std::vector<CSomeObject*>::iterator itBegin = NULL, std::vector<CSomeObject*>::iterator itEnd = NULL ); ``` The Visual Studio error is as follows: ``` c:\<path>\Headerfile.h(20) : error C2440: 'default argument' : cannot convert from 'int' to 'std::_Vector_iterator<_Ty,_Alloc>' with [ _Ty=CObject *, _Alloc=std::allocator<CObject *> ] No constructor could take the source type, or constructor overload resolution was ambiguous ``` I can't see anything wrong with that code and it worked perfectly in VS 2003. Any ideas?
Your program is incorrect as NULL cannot be converted as an iterator. I don't really know what you want these iterators to be initialized as. If you need an iterator guarantied not to be in a container but to be still "valid", you can use a default-constructor: ``` typedef std::vector<CSomeObject*> myvector_t; void SomeFn( myvector_t::iterator it, myvector_t::iterator itBegin = myvector_t::iterator(), myvector_t::iterator itEnd = myvector_t::iterator() ); ``` Note, however, that if you do so, `it`, `itBegin` and `itEnd` won't be comparable in a meaningful way! Only iterators obtained from a given container are comparable meaningfully. In the end, I would recommend against using defaults values for `itBegin` and `itEnd`. If you really need to not have these, create another function without the arguments and do something meaningful. i.e.: ``` typedef std::vector<CSomeObject*> myvector_t; void SomeFn( myvector_t::iterator it, myvector_t::iterator itBegin, myvector_t::iterator itEnd ); void SomeFn( myvector_t::iterator it ); // No begin/end arguments ``` Another problem of your program is the use of a vector to store pointers. This is really unsafe. Make sure you never erase elements from the vector without deleting the element first. You might also have problems with algorithms copying objects around. It is better to use smart pointers in vectors.
283,661
<p>Since a few days ago, MySQL server on my Windows machine was not successful on closing itself. I found multiple instance of these lines in the MySQL error log:</p> <pre><code>InnoDB: Operating system error number 32 in a file operation. InnoDB: The error means that another program is using InnoDB's files. InnoDB: This might be a backup or antivirus software or another instance InnoDB: of MySQL. Please close it to get rid of this error. </code></pre> <p>I have plenty of free spaces, the server is installed for months, the version is 5.1.22-rc-community-log on Windows XP SP3, and I have used only one Windows account to create and execute MySQL service.</p> <p>Following Greg's answer, I found through <code>ProcessExplorer</code> that there's another MySQL service running with a different name. I kill it and all run fine.</p>
[ { "answer_id": 283668, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 5, "selected": true, "text": "<p>If the file is in use by another program then <a href=\"http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx\" rel=\"noreferrer\">Process Explorer</a> could help you track down which one has it open. I assume you've checked you only have one copy of MySQL running.</p>\n" }, { "answer_id": 283673, "author": "Till", "author_id": 2859, "author_profile": "https://Stackoverflow.com/users/2859", "pm_score": 2, "selected": false, "text": "<p>Sounds like a conflict. Make sure to stop the mysqld service and then double-check if it's really not running anymore, then restart the service. Also, when it's back up, make sure to run checks on your tables and see if there is any damage.</p>\n\n<p>My assumption is based on the <a href=\"http://dev.mysql.com/doc/refman/5.0/en/operating-system-error-codes.html\" rel=\"nofollow noreferrer\">operating system error codes</a> in the MySQL docs.</p>\n" }, { "answer_id": 11202882, "author": "Anadi Kumar", "author_id": 1482004, "author_profile": "https://Stackoverflow.com/users/1482004", "pm_score": 2, "selected": false, "text": "<p>You can follow these steps:</p>\n\n<ol>\n<li>Open TaskManager </li>\n<li>Kill the <strong>mysqld.exe</strong> process.</li>\n<li><code>cd E:\\apps\\db\\mysql-5.5.25-win32\\bin</code></li>\n<li>Run: <code>mysqld --install MySQL</code></li>\n<li>Run: <code>mysqladmin -u root start</code></li>\n</ol>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8404/" ]
Since a few days ago, MySQL server on my Windows machine was not successful on closing itself. I found multiple instance of these lines in the MySQL error log: ``` InnoDB: Operating system error number 32 in a file operation. InnoDB: The error means that another program is using InnoDB's files. InnoDB: This might be a backup or antivirus software or another instance InnoDB: of MySQL. Please close it to get rid of this error. ``` I have plenty of free spaces, the server is installed for months, the version is 5.1.22-rc-community-log on Windows XP SP3, and I have used only one Windows account to create and execute MySQL service. Following Greg's answer, I found through `ProcessExplorer` that there's another MySQL service running with a different name. I kill it and all run fine.
If the file is in use by another program then [Process Explorer](http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx) could help you track down which one has it open. I assume you've checked you only have one copy of MySQL running.
283,672
<p>I have a user who gets an error from ajax calls on our site.</p> <p>The error is pasted below. </p> <p>They get the error in FF3 Windows, but not IE.</p> <p>Based on some searching it seems this issue is often caused by the client protocol squid (you'll notice at the end of the error, squid is mentioned).</p> <p>My ajax code is the same used here: <a href="http://www.w3schools.com/Ajax/ajax_browsers.asp" rel="nofollow noreferrer">http://www.w3schools.com/Ajax/ajax_browsers.asp</a></p> <p>Any ideas?</p> <pre><code>ERROR The requested URL could not be retrieved While trying to process the request: POST /library/cart/cart_ajax.php?action=refreshCartWidget&amp;qty=dontuse&amp; HTTP/1.1 Host: mydomain.com User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3 (.NET CLR 3.5.30729) Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-us,en;q=0.5 Accept-Encoding: identity,gzip,deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive: 300 Connection: Close Referer: http://mydomain.com/library Pragma: no-cache Cache-Control: no-cache The following error was encountered: Invalid Request Some aspect of the HTTP Request is invalid. Possible problems: Missing or unknown request method Missing URL Missing HTTP Identifier (HTTP/1.0) Request is too large Content-Length missing for POST or PUT requests Illegal character in hostname; underscores are not allowed Your cache administrator is webmaster. Generated Wed, 12 Nov 2008 09:28:58 GMT by ipwal3.osi-tech.com (squid/2.6.STABLE17) </code></pre>
[ { "answer_id": 283686, "author": "Till", "author_id": 2859, "author_profile": "https://Stackoverflow.com/users/2859", "pm_score": 2, "selected": false, "text": "<p>Save yourself some time and use <a href=\"http://jquery.com/\" rel=\"nofollow noreferrer\">jQuery</a>. It has an abstraction for ajax, which works in all browsers and not just Internet Explorer, and maybe FF. ;-) I am assuming that the code up there is old and didn't get an update in a long while.</p>\n\n<p>A simple ajax call in jQuery is as follows:</p>\n\n<pre><code>$.post(\n '/the/url/to/post/to',\n { some: data },\n function(data) { alert(data); }\n);\n</code></pre>\n\n<p>It also helps if you understand the basics of HTTP - for example, the request methods (<code>PUT</code>, <code>POST</code>, <code>GET</code>, <code>DELETE</code>, <code>HEAD</code>) and so on. The error you pasted means that the header <code>Content-Length</code> is missing with your request and most servers (if not all) expect it to be send when you issue <code>PUT</code> or <code>POST</code> because those are assumed to be \"data changing\" (e.g. create, update).</p>\n\n<p>Maybe IE adds the header for you, but Firefox apparently doesn't.</p>\n\n<p>jQuery takes care of all that. ;)</p>\n" }, { "answer_id": 283765, "author": "jishi", "author_id": 33663, "author_profile": "https://Stackoverflow.com/users/33663", "pm_score": 1, "selected": false, "text": "<p>You can use .setRequestHeader() on your XHR-object to set a content-length if FF doesn't do it for you.</p>\n\n<p>Since you're posting your data in the .send(content) method, just add a header before that with content.length.</p>\n" }, { "answer_id": 283826, "author": "mkoeller", "author_id": 33433, "author_profile": "https://Stackoverflow.com/users/33433", "pm_score": 0, "selected": false, "text": "<p>You should sit together with your user and put the <a href=\"http://www.fiddlertool.com/fiddler/\" rel=\"nofollow noreferrer\">Fiddler</a> HTTP tracing tool in between. Then you can easily compare the request being sent by IE and FF3.</p>\n\n<p>This way it should become visible where the differences are and why they're causing problems.</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283672", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a user who gets an error from ajax calls on our site. The error is pasted below. They get the error in FF3 Windows, but not IE. Based on some searching it seems this issue is often caused by the client protocol squid (you'll notice at the end of the error, squid is mentioned). My ajax code is the same used here: <http://www.w3schools.com/Ajax/ajax_browsers.asp> Any ideas? ``` ERROR The requested URL could not be retrieved While trying to process the request: POST /library/cart/cart_ajax.php?action=refreshCartWidget&qty=dontuse& HTTP/1.1 Host: mydomain.com User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3 (.NET CLR 3.5.30729) Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-us,en;q=0.5 Accept-Encoding: identity,gzip,deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive: 300 Connection: Close Referer: http://mydomain.com/library Pragma: no-cache Cache-Control: no-cache The following error was encountered: Invalid Request Some aspect of the HTTP Request is invalid. Possible problems: Missing or unknown request method Missing URL Missing HTTP Identifier (HTTP/1.0) Request is too large Content-Length missing for POST or PUT requests Illegal character in hostname; underscores are not allowed Your cache administrator is webmaster. Generated Wed, 12 Nov 2008 09:28:58 GMT by ipwal3.osi-tech.com (squid/2.6.STABLE17) ```
Save yourself some time and use [jQuery](http://jquery.com/). It has an abstraction for ajax, which works in all browsers and not just Internet Explorer, and maybe FF. ;-) I am assuming that the code up there is old and didn't get an update in a long while. A simple ajax call in jQuery is as follows: ``` $.post( '/the/url/to/post/to', { some: data }, function(data) { alert(data); } ); ``` It also helps if you understand the basics of HTTP - for example, the request methods (`PUT`, `POST`, `GET`, `DELETE`, `HEAD`) and so on. The error you pasted means that the header `Content-Length` is missing with your request and most servers (if not all) expect it to be send when you issue `PUT` or `POST` because those are assumed to be "data changing" (e.g. create, update). Maybe IE adds the header for you, but Firefox apparently doesn't. jQuery takes care of all that. ;)
283,701
<p>What are best practices with regards to C and C++ coding standards? Should developers be allowed to willy-nilly mix them together. Are there any complications when linking C and C++ object files.</p> <p>Should things like socket libraries that traditionally is written in C remain in C and kept in seperate source files? That is keeping c code in .c files and c++ code in .cpp files. When mixing c and C++ after being parsed with g++ will there be any performance penalties, since typesafe checks are not done in C? but are in C++. Would would be the best way to link C and C++ source code files.</p>
[ { "answer_id": 283716, "author": "Graeme Perrow", "author_id": 1821, "author_profile": "https://Stackoverflow.com/users/1821", "pm_score": 3, "selected": false, "text": "<p>The biggest issue is calling a C function from C++ code or vice versa. In that case, you want to make sure you mark the function as having \"C\" linkage using <code>extern \"C\"</code>. You can do this in the header file directly using:</p>\n\n<pre><code>#if defined( __cplusplus )\nextern \"C\" {\n#endif\n\nextern int myfunc( const char *param, int another_one );\n\n#if defined( __cplusplus )\n}\n#endif\n</code></pre>\n\n<p>You need the <code>#if</code>s because C code that includes it won't understand <code>extern \"C\"</code>.</p>\n\n<p>If you don't want to (or can't) change the header file, you can do it in the C++ code:</p>\n\n<pre><code>extern \"C\" {\n#include \"myfuncheader.h\"\n}\n</code></pre>\n\n<p>You can mark a C++ function as having C linkage the same way, and then you can call it from C code. You can't do this for overloaded functions or C++ classes.</p>\n\n<p>Other than that, there should be no problem mixing C and C++. We have a number of decades-old C functions that are still being used by our C++ code.</p>\n" }, { "answer_id": 283722, "author": "Sunlight", "author_id": 33650, "author_profile": "https://Stackoverflow.com/users/33650", "pm_score": 2, "selected": false, "text": "<p>C++ doesn't do 'typesafe checks' at run time unless you ask for them (by using <code>dynamic_cast</code>). C++ is highly compatible with C, so you may freely call C libraries as you wish and compile C code with a C++ compiler. C++ does not imply 'object-oriented', and you should get no performance penalty from using it.</p>\n\n<p>If you mix code compiled with gcc and with g++, see Graeme's answer.</p>\n" }, { "answer_id": 283806, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 0, "selected": false, "text": "<p>If you compile all your source with g++ then it is all compiled in C++ object files (i.e. with the appropriate name mangling and the C++ ABI).</p>\n\n<p>You will only need to use the extern \"C\" trick if you are building libraries that need to be used by explicitly C applications that need to use the C ABI.</p>\n\n<p>If everything is being compiled into a single executable then use g++ and treat everything as C++</p>\n" }, { "answer_id": 283810, "author": "CesarB", "author_id": 28258, "author_profile": "https://Stackoverflow.com/users/28258", "pm_score": 1, "selected": false, "text": "<p>If you have a function in C++ which calls a function in C which in turn calls another function in C++, and this later function throws an exception which should be caught by the first function, you can have problems unless you told the C compiler to enable generation of the exception handling tables.</p>\n\n<p>For gcc, this is the <a href=\"http://gcc.gnu.org/onlinedocs/gcc-4.3.2/gcc/Code-Gen-Options.html\" rel=\"nofollow noreferrer\"><code>-fexceptions</code></a> parameter, which is enabled by default for C++ but disabled by default for C.</p>\n" }, { "answer_id": 283841, "author": "David Allan Finch", "author_id": 27417, "author_profile": "https://Stackoverflow.com/users/27417", "pm_score": 1, "selected": false, "text": "<p>There are no good hard and fast rules here.</p>\n\n<p>If the end product will always be linked with a C++ main() then it does not really matter. As you can always create headers that will do the correct thing.</p>\n\n<p>If you are creating a library that needs to have a C and C++ interface but you can't assume the C++ linker then you will need to make sure you separated the C API from the C++ cleanly. At this point it is usually cleaner to do all the work in C and use C++ classes to proxy to the C.</p>\n\n<p>For example:</p>\n\n<pre><code>/* c header */\n\nstruct CData\n { /* stuff */ };\n\nvoid init( CData* data );\nvoid fini( CData* data );\nint getSomething( CData* data );\nvoid doSomething( CData* data, int val );\n\n// c++ header\n\nextern \"C\" {\n#include cdata.h\n};\n\nclass CppData : private CData\n {\n public:\n CppData() { ::init( (CData*)this ); }\n ~CppData() { ::fini( (CData*)this ); }\n int getSomething() { return ::getSomething( (CData*)this ); }\n void doSomething( int val ) { :: doSomething( (CData*)this, val ); }\n };\n</code></pre>\n\n<p>I hope this helps.</p>\n" }, { "answer_id": 285063, "author": "EvilTeach", "author_id": 7734, "author_profile": "https://Stackoverflow.com/users/7734", "pm_score": 2, "selected": false, "text": "<p>One should generally assume that c++ can throw exceptions, hence the c wrapper functions in your block, ought to catch them, and morph them into nice error codes that the c caller can digest.</p>\n\n<pre><code>extern \"c\"\n{\n int nice_c_function_interface\n (\n void\n )\n {\n int returnStatus;\n\n try\n {\n returnStatus = nice_cpp_function();\n }\n catch (NiceCppException&amp; that)\n {\n returnStatus = that.failure_code(); \n }\n catch (...)\n {\n cerr &lt;&lt; \"Oh Worse! an unexpected unknown exception\" &lt;&lt; endl;\n\n returnStatus = -1; // Horrible unknown failure\n }\n\n return returnStatus;\n }\n}\n</code></pre>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283701", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7362/" ]
What are best practices with regards to C and C++ coding standards? Should developers be allowed to willy-nilly mix them together. Are there any complications when linking C and C++ object files. Should things like socket libraries that traditionally is written in C remain in C and kept in seperate source files? That is keeping c code in .c files and c++ code in .cpp files. When mixing c and C++ after being parsed with g++ will there be any performance penalties, since typesafe checks are not done in C? but are in C++. Would would be the best way to link C and C++ source code files.
The biggest issue is calling a C function from C++ code or vice versa. In that case, you want to make sure you mark the function as having "C" linkage using `extern "C"`. You can do this in the header file directly using: ``` #if defined( __cplusplus ) extern "C" { #endif extern int myfunc( const char *param, int another_one ); #if defined( __cplusplus ) } #endif ``` You need the `#if`s because C code that includes it won't understand `extern "C"`. If you don't want to (or can't) change the header file, you can do it in the C++ code: ``` extern "C" { #include "myfuncheader.h" } ``` You can mark a C++ function as having C linkage the same way, and then you can call it from C code. You can't do this for overloaded functions or C++ classes. Other than that, there should be no problem mixing C and C++. We have a number of decades-old C functions that are still being used by our C++ code.
283,707
<p>Is there a way to find the size of a file object that is currently open?</p> <p>Specifically, I am working with the tarfile module to create tarfiles, but I don't want my tarfile to exceed a certain size. As far as I know, tarfile objects are file-like objects, so I imagine a generic solution would work.</p>
[ { "answer_id": 283718, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 3, "selected": false, "text": "<p>If you have the file descriptor, you can use <code>fstat</code> to find out the size, if any. A more generic solution is to seek to the end of the file, and read its location there.</p>\n" }, { "answer_id": 283719, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 8, "selected": true, "text": "<pre><code>$ ls -la chardet-1.0.1.tgz\n-rwxr-xr-x 1 vinko vinko 179218 2008-10-20 17:49 chardet-1.0.1.tgz\n$ python\nPython 2.5.1 (r251:54863, Jul 31 2008, 22:53:39)\n[GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2\nType &quot;help&quot;, &quot;copyright&quot;, &quot;credits&quot; or &quot;license&quot; for more information.\n&gt;&gt;&gt; f = open('chardet-1.0.1.tgz','rb')\n&gt;&gt;&gt; f.seek(0, os.SEEK_END)\n&gt;&gt;&gt; f.tell()\n179218L\n</code></pre>\n<p>Adding ChrisJY's idea to the example</p>\n<pre><code>&gt;&gt;&gt; import os\n&gt;&gt;&gt; os.fstat(f.fileno()).st_size\n179218L\n&gt;&gt;&gt; \n</code></pre>\n<p><strong>Note</strong>: Based on the comments, <code>f.seek(0, os.SEEK_END)</code> is must before calling <code>f.tell()</code>, without which it would return a size of 0. <a href=\"https://stackoverflow.com/questions/283707/size-of-an-open-file-object#comment53321883_283719\">The reason is that <code>f.seek(0, os.SEEK_END)</code> moves the file object's position to the end of the file.</a></p>\n" }, { "answer_id": 283725, "author": "PierreBdR", "author_id": 7136, "author_profile": "https://Stackoverflow.com/users/7136", "pm_score": 4, "selected": false, "text": "<p>Well, if the file object support the tell method, you can do:</p>\n\n<pre><code>current_size = f.tell()\n</code></pre>\n\n<p>That will tell you were it is currently writing. If you write in a sequential way this will be the size of the file.</p>\n\n<p>Otherwise, you can use the file system capabilities, i.e. <code>os.fstat</code> as suggested by others.</p>\n" }, { "answer_id": 38992375, "author": "vestronge", "author_id": 6725474, "author_profile": "https://Stackoverflow.com/users/6725474", "pm_score": 1, "selected": false, "text": "<p>Another solution is using StringIO \"if you are doing in-memory operations\".</p>\n\n<pre><code>with open(file_path, 'rb') as x:\n body = StringIO()\n body.write(x.read())\n body.seek(0, 0)\n</code></pre>\n\n<p>Now <code>body</code> behaves like a file object with various attributes like <code>body.read()</code>. </p>\n\n<p><code>body.len</code> gives the file size.</p>\n" }, { "answer_id": 73214956, "author": "darda", "author_id": 149506, "author_profile": "https://Stackoverflow.com/users/149506", "pm_score": 0, "selected": false, "text": "<p>I was curious about the performance implications of both, since once you open a file, the <code>name</code> attribute of the handle gives you the filename (so you can call <code>os.stat</code> on it).</p>\n<p>Here's a function for the seek/tell method:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import io\ndef seek_size(f):\n pos = f.tell()\n f.seek(0, io.SEEK_END)\n size = f.tell()\n f.seek(pos) # back to where we were\n return size\n</code></pre>\n<p>With a 65 MiB file on an SSD, Windows 10, this is some 6.5x faster than calling <code>os.stat(f.name)</code></p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36312/" ]
Is there a way to find the size of a file object that is currently open? Specifically, I am working with the tarfile module to create tarfiles, but I don't want my tarfile to exceed a certain size. As far as I know, tarfile objects are file-like objects, so I imagine a generic solution would work.
``` $ ls -la chardet-1.0.1.tgz -rwxr-xr-x 1 vinko vinko 179218 2008-10-20 17:49 chardet-1.0.1.tgz $ python Python 2.5.1 (r251:54863, Jul 31 2008, 22:53:39) [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> f = open('chardet-1.0.1.tgz','rb') >>> f.seek(0, os.SEEK_END) >>> f.tell() 179218L ``` Adding ChrisJY's idea to the example ``` >>> import os >>> os.fstat(f.fileno()).st_size 179218L >>> ``` **Note**: Based on the comments, `f.seek(0, os.SEEK_END)` is must before calling `f.tell()`, without which it would return a size of 0. [The reason is that `f.seek(0, os.SEEK_END)` moves the file object's position to the end of the file.](https://stackoverflow.com/questions/283707/size-of-an-open-file-object#comment53321883_283719)
283,727
<p>I've spent hours trying to get my code to work, its a rats nest of if/elses. Basically I want to check a country name against these two arrays:</p> <pre><code>//if its in this array add a 'THE' $keywords = array("bahamas","island","kingdom","republic","maldives","netherlands", "isle of man","ivory","philippines","seychelles","usa"); //if its in this array, take THE off! $exceptions = array("eire","hispaniola"); </code></pre> <p>and thats it. </p> <p>Its sending me batty, and to be honest I'm embarassed to show you my code. Lets just say it has 2 if statements, 2 else statements and 2 foreach loops. Its a blooming mess, and I was hoping someone can dumbfound me by showing me a good way of doing this? I expect there is a way using only 1 line of code, or something sickening like that. Thank you.</p>
[ { "answer_id": 283739, "author": "alxp", "author_id": 19513, "author_profile": "https://Stackoverflow.com/users/19513", "pm_score": 1, "selected": false, "text": "<p>The easiest would be to split it into two steps, ad the \"the\" for the countries that match the first list, and then just remove it if if matches the words in the second list.</p>\n" }, { "answer_id": 283742, "author": "Stefan Gehrig", "author_id": 11354, "author_profile": "https://Stackoverflow.com/users/11354", "pm_score": 2, "selected": false, "text": "<pre><code>$countryKey = strtolower($country);\nif (in_array($countryKey, $keywords)) {\n $country = 'The' . $country;\n} else if (in_array($countryKey, $exceptions) &amp;&amp; stripos($country, 'the ') === 0) {\n $country = substr($country, 4);\n}\n</code></pre>\n" }, { "answer_id": 283743, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 1, "selected": false, "text": "<p>Why you would simpy test if the country name is contained within the string (<a href=\"http://us.php.net/manual/en/function.strpos.php\" rel=\"nofollow noreferrer\">strpos</a>):</p>\n\n<pre><code>\",bahamas,island,kingdom,republic,maldives,netherlands,isle of man,ivory,philippines,seychelles,usa,\"\n</code></pre>\n\n<p>(Note the beginning and trailing ',')</p>\n\n<p>It is faster than a regexp: if your \",country name,\" is is that string, add 'THE', else remove it.</p>\n" }, { "answer_id": 283746, "author": "Can Berk Güder", "author_id": 2119, "author_profile": "https://Stackoverflow.com/users/2119", "pm_score": 1, "selected": false, "text": "<p>I believe you're looking for something like this:</p>\n\n<pre><code>if(in_array($country, $keywords)) {\n // add 'the'\n} elseif(in_array($country, $exceptions)) {\n // remove 'the'\n}\n</code></pre>\n" }, { "answer_id": 283772, "author": "jishi", "author_id": 33663, "author_profile": "https://Stackoverflow.com/users/33663", "pm_score": 1, "selected": false, "text": "<p>in_array() is your friend. No need to loop for it.</p>\n" }, { "answer_id": 283777, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 3, "selected": true, "text": "<p>This builds on @sgehrig's answer, but note the change in your exceptions:</p>\n\n<pre><code>//if its in this array add a 'THE' \n$keywords = array(\"bahamas\",\"island\",\"kingdom\",\"republic\",\"maldives\",\"netherlands\",\n \"isle of man\",\"ivory\",\"philippines\",\"seychelles\",\"usa\");\n//if its in this array, take THE off!\n$exceptions = array(\"the eire\",\"the hispaniola\");\n\n$countryKey = strtolower($country);\nif (in_array($countryKey, $keywords)) {\n $country = 'The ' . $country;\n} else if (in_array($countryKey, $exceptions)) {\n $country = substr($country, 4);\n}\n</code></pre>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283727", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26107/" ]
I've spent hours trying to get my code to work, its a rats nest of if/elses. Basically I want to check a country name against these two arrays: ``` //if its in this array add a 'THE' $keywords = array("bahamas","island","kingdom","republic","maldives","netherlands", "isle of man","ivory","philippines","seychelles","usa"); //if its in this array, take THE off! $exceptions = array("eire","hispaniola"); ``` and thats it. Its sending me batty, and to be honest I'm embarassed to show you my code. Lets just say it has 2 if statements, 2 else statements and 2 foreach loops. Its a blooming mess, and I was hoping someone can dumbfound me by showing me a good way of doing this? I expect there is a way using only 1 line of code, or something sickening like that. Thank you.
This builds on @sgehrig's answer, but note the change in your exceptions: ``` //if its in this array add a 'THE' $keywords = array("bahamas","island","kingdom","republic","maldives","netherlands", "isle of man","ivory","philippines","seychelles","usa"); //if its in this array, take THE off! $exceptions = array("the eire","the hispaniola"); $countryKey = strtolower($country); if (in_array($countryKey, $keywords)) { $country = 'The ' . $country; } else if (in_array($countryKey, $exceptions)) { $country = substr($country, 4); } ```
283,728
<p>I need to create a BAT file to run an application through telnet, but as far as I know there is no way to do this on DOS. Telnet does not allow any command to be sent to the remote machine at the very instant of the connection, and each subsequent command in the BAT file would only be executed after telnet stops. This hypothetical piece of code illustrates what I want to do:</p> <pre><code>telnet 100.99.98.1 "C:\Application\app.exe -a -b -c" </code></pre> <p>And that would run the app.exe on the machine 100.99.98.1 with three parameters. Despite my efforts, nothing worked. Is there a way to do that?</p> <p>Tks,</p> <p>Pedrin Batista</p>
[ { "answer_id": 283741, "author": "Frank Grimm", "author_id": 903, "author_profile": "https://Stackoverflow.com/users/903", "pm_score": 2, "selected": false, "text": "<p>Using telnet in the way you want to is imho not possible.</p>\n\n<p>You could you secure shell (ssh), but a ssh server has to run on the remote machine (100.99.98.1 in you case).</p>\n\n<p>EDIT:</p>\n\n<p>See <a href=\"http://sshwindows.sourceforge.net/\" rel=\"nofollow noreferrer\">http://sshwindows.sourceforge.net/</a> for a ssh client and server (based on cygwin) for Windows.</p>\n" }, { "answer_id": 283744, "author": "Adam Liss", "author_id": 29157, "author_profile": "https://Stackoverflow.com/users/29157", "pm_score": 0, "selected": false, "text": "<p>Does your telnet app need to run in a command window, or do you only need to <em>start</em> it from the command line? If you want to \"launch and forget,\" you might consider a scriptable terminal program such as the free TeraTerm. You can launch it from the command line with the <code>start</code> command and let it execute a script in the background.</p>\n" }, { "answer_id": 283747, "author": "Alnitak", "author_id": 6782, "author_profile": "https://Stackoverflow.com/users/6782", "pm_score": 3, "selected": false, "text": "<p>Have you tried:</p>\n\n<pre><code>echo \"c:\\application\\app.exe -a -b -c\" | telnet 100.99.98.1\n</code></pre>\n\n<p>this won't work if the remote telnet server requires a username and password, though.</p>\n" }, { "answer_id": 283750, "author": "Todd", "author_id": 31940, "author_profile": "https://Stackoverflow.com/users/31940", "pm_score": 2, "selected": false, "text": "<p>Due to your paths I'm assuming you are working on a windows platform. I'd suggest looking at <a href=\"http://technet.microsoft.com/en-us/sysinternals/bb897553.aspx\" rel=\"nofollow noreferrer\">PsExec</a> from Microsoft/SysInternals which allows you to execute a command on a remote machine. </p>\n\n<p><a href=\"http://technet.microsoft.com/en-us/sysinternals/bb897553.aspx\" rel=\"nofollow noreferrer\">PsExec</a> is part of the excellent free <a href=\"http://technet.microsoft.com/en-us/sysinternals/bb896649.aspx\" rel=\"nofollow noreferrer\">PsTools</a> package from Mark Russinovich. SysInternals was recently purchased by Microsoft, but the tools remain free.</p>\n\n<p>This does not, however, work over the internet. It uses windows networking port 445 and should only be used on local networks. If you need that I'd suggest using SSH.</p>\n" }, { "answer_id": 283753, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 2, "selected": false, "text": "<p>Have you tried the following?</p>\n\n<pre><code>telnet 100.99.98.1 &lt;someScript\n</code></pre>\n\n<p>Where someScipt has your command, e.g., <code>C:\\Application\\app.exe -a -b -c</code></p>\n\n<p>Have you looked at a <a href=\"http://sourceforge.net/projects/rshd/\" rel=\"nofollow noreferrer\">Remote Shell daemon</a> for windows? This is probably a lot better than telnet.</p>\n" }, { "answer_id": 283754, "author": "PW.", "author_id": 927, "author_profile": "https://Stackoverflow.com/users/927", "pm_score": 2, "selected": true, "text": "<p>give <a href=\"http://expect.nist.gov/#windows\" rel=\"nofollow noreferrer\">expect</a> a try</p>\n\n<p>from the webpage:</p>\n\n<blockquote>\n <p>Expect is a tool for automating\n interactive applications such as\n <strong>telnet</strong>, ftp, passwd, fsck, rlogin,\n tip, etc. Expect really makes this\n stuff trivial. Expect is also useful\n for testing these same applications.</p>\n</blockquote>\n" }, { "answer_id": 283811, "author": "joel.neely", "author_id": 3525, "author_profile": "https://Stackoverflow.com/users/3525", "pm_score": 0, "selected": false, "text": "<p>You might consider using <a href=\"http://www.cygwin.com/\" rel=\"nofollow noreferrer\">Cygwin</a> (which provides a Linux-/Unix-like command-line environment running on Windows). A wide range of standard tools, including shell scripting, is available as part of Cygwin.</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36183/" ]
I need to create a BAT file to run an application through telnet, but as far as I know there is no way to do this on DOS. Telnet does not allow any command to be sent to the remote machine at the very instant of the connection, and each subsequent command in the BAT file would only be executed after telnet stops. This hypothetical piece of code illustrates what I want to do: ``` telnet 100.99.98.1 "C:\Application\app.exe -a -b -c" ``` And that would run the app.exe on the machine 100.99.98.1 with three parameters. Despite my efforts, nothing worked. Is there a way to do that? Tks, Pedrin Batista
give [expect](http://expect.nist.gov/#windows) a try from the webpage: > > Expect is a tool for automating > interactive applications such as > **telnet**, ftp, passwd, fsck, rlogin, > tip, etc. Expect really makes this > stuff trivial. Expect is also useful > for testing these same applications. > > >
283,737
<p>I have an ASP.NET 1.1 application that uses the following code to write out a file in the response:</p> <pre><code>Dim objStream As Object objStream = Server.CreateObject("ADODB.Stream") objStream.open() objStream.type = 1 objStream.loadfromfile(localfile) Response.BinaryWrite(objStream.read) </code></pre> <p>This code is called by a pop up window that displays this file or gives a open/save dialog in Internet Explorer. The problem is, that it seems to work fine in IE6 but in IE7 the pop up opens and then closes without displaying the file. Any one know whats wrong?</p>
[ { "answer_id": 288829, "author": "Malik Daud Ahmad Khokhar", "author_id": 1688440, "author_profile": "https://Stackoverflow.com/users/1688440", "pm_score": -1, "selected": false, "text": "<p>So the images that are being served by Asp.Net are tiff files. And it says <a href=\"http://forums.asp.net/p/1113169/2332853.aspx#2332853\" rel=\"nofollow noreferrer\">here</a> that IE7 doesn't display files with 4 letter extensions for some reason. I think I'll try to change it to 3 letters and see what happens.</p>\n" }, { "answer_id": 1060550, "author": "pedrofernandes", "author_id": 127891, "author_profile": "https://Stackoverflow.com/users/127891", "pm_score": 0, "selected": false, "text": "<p>I have a code like this for download files from server:</p>\n\n<pre><code>strFilename = Server.MapPath(\"/App_Upload/\" &amp; strFilename) \n\nWith Response\n .AddHeader(\"Content-Type\", \"binary/octet-stream\")\n .AddHeader(\"Content-Disposition\", \"attachment; filename=\" &amp; strFilename &amp; \";\")\n .WriteFile(strFilename)\n .End()\nEnd With\n</code></pre>\n\n<p>Try if work in your case.</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1688440/" ]
I have an ASP.NET 1.1 application that uses the following code to write out a file in the response: ``` Dim objStream As Object objStream = Server.CreateObject("ADODB.Stream") objStream.open() objStream.type = 1 objStream.loadfromfile(localfile) Response.BinaryWrite(objStream.read) ``` This code is called by a pop up window that displays this file or gives a open/save dialog in Internet Explorer. The problem is, that it seems to work fine in IE6 but in IE7 the pop up opens and then closes without displaying the file. Any one know whats wrong?
I have a code like this for download files from server: ``` strFilename = Server.MapPath("/App_Upload/" & strFilename) With Response .AddHeader("Content-Type", "binary/octet-stream") .AddHeader("Content-Disposition", "attachment; filename=" & strFilename & ";") .WriteFile(strFilename) .End() End With ``` Try if work in your case.
283,740
<p>I am using the Zend Framework.</p> <p>I have a controller named 'UserController' that has a public function displayAction().</p> <p>I would like to know how I can get that action method to use a different viewer than the default display.phtml.</p> <p>Any help is appreciated.</p>
[ { "answer_id": 283784, "author": "Aron Rotteveel", "author_id": 11568, "author_profile": "https://Stackoverflow.com/users/11568", "pm_score": 5, "selected": true, "text": "<p>You can use </p>\n\n<pre><code>$this-&gt;render('actionName');\n</code></pre>\n\n<p>or, alternatively, you can call a view script directly by calling</p>\n\n<pre><code>$this-&gt;renderScript('path/to/viewscript.phtml');\n</code></pre>\n\n<p>For more information, you can take a look at <a href=\"http://framework.zend.com/manual/en/zend.controller.actionhelpers.html\" rel=\"noreferrer\">http://framework.zend.com/manual/en/zend.controller.actionhelpers.html</a>, specifically the parts about the <code>render()</code> and <code>renderScript()</code> methods.</p>\n" }, { "answer_id": 10469195, "author": "Brian Vanderbusch", "author_id": 1106939, "author_profile": "https://Stackoverflow.com/users/1106939", "pm_score": 1, "selected": false, "text": "<p>Lately, I've been getting errors with the method described above (using ZF 1.11.11). I've had success with this:</p>\n\n<pre><code>$this-&gt;_helper-&gt;viewRenderer('action');\n</code></pre>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283740", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15052/" ]
I am using the Zend Framework. I have a controller named 'UserController' that has a public function displayAction(). I would like to know how I can get that action method to use a different viewer than the default display.phtml. Any help is appreciated.
You can use ``` $this->render('actionName'); ``` or, alternatively, you can call a view script directly by calling ``` $this->renderScript('path/to/viewscript.phtml'); ``` For more information, you can take a look at <http://framework.zend.com/manual/en/zend.controller.actionhelpers.html>, specifically the parts about the `render()` and `renderScript()` methods.
283,749
<p>At work, I'm frequently working on projects where numerous properties of certain objects have to be set during their construction or early during their lifetime. For the sake of convenience and readability, I often use the <code>With</code> statement to set these properties. I find that</p> <pre><code>With Me.Elements .PropertyA = True .PropertyB = "Inactive" ' And so on for several more lines End With </code></pre> <p>Looks much better than</p> <pre><code>Me.Elements.PropertyA = True Me.Elements.PropertyB = "Inactive" ' And so on for several more lines </code></pre> <p>for very long statements that simply set properties.</p> <p>I've noticed that there are some issues with using <code>With</code> while debugging; however, <strong>I was wondering if there were any compelling reasons to avoid using <code>With</code> in practice</strong>? I've always assumed the code generated via the compiler for the above two cases is basically the same which is why I've always chosen to write what I feel to be more readable. </p>
[ { "answer_id": 283785, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": false, "text": "<p>Where it makes the code genuinely more readable, go for it. Where it makes it <em>less</em> readable, avoid it - in particular, I suggest you avoid nesting With statements.</p>\n\n<p>C# 3.0 has this feature solely for object initialization:</p>\n\n<pre><code>var x = new Whatever { PropertyA=true, PropertyB=\"Inactive\" };\n</code></pre>\n\n<p>This is not only pretty much required for LINQ, but it also makes sense in terms of where the syntax doesn't indicate a code smell. I usually find that when I'm performing many different operations on an object beyond its initial construction, those operations should be encapsulated as a single one on the object itself.</p>\n\n<p>One note about your example - do you really need the \"Me\" at all? Why not just write:</p>\n\n<pre><code>PropertyA = True\nPropertyB = \"Inactive\"\n</code></pre>\n\n<p>? Surely \"Me\" is implied in that case...</p>\n" }, { "answer_id": 283820, "author": "Stefan", "author_id": 19307, "author_profile": "https://Stackoverflow.com/users/19307", "pm_score": 7, "selected": true, "text": "<p>If you have long variablenames and would end up with:</p>\n\n<pre><code>UserHandler.GetUser.First.User.FirstName=\"Stefan\"\nUserHandler.GetUser.First.User.LastName=\"Karlsson\"\nUserHandler.GetUser.First.User.Age=\"39\"\nUserHandler.GetUser.First.User.Sex=\"Male\"\nUserHandler.GetUser.First.User.Occupation=\"Programmer\"\nUserHandler.GetUser.First.User.UserID=\"0\"\n....and so on\n</code></pre>\n\n<p>then I would use WITH to make it more readable:</p>\n\n<pre><code>With UserHandler.GetUser.First.User\n .FirstName=\"Stefan\"\n .LastName=\"Karlsson\"\n .Age=\"39\"\n .Sex=\"Male\"\n .Occupation=\"Programmer\"\n .UserID=\"0\"\nend with\n</code></pre>\n\n<p>In the later example there are even performance benefit over the first example because in the first example Im fetching the user every time I access a user property and in the WITH-case I only fetch the user one time.</p>\n\n<p>I can get the performance gain without using with, like this:</p>\n\n<pre><code>dim myuser as user =UserHandler.GetUser.First.User\nmyuser.FirstName=\"Stefan\"\nmyuser.LastName=\"Karlsson\"\nmyuser.Age=\"39\"\nmyuser.Sex=\"Male\"\nmyuser.Occupation=\"Programmer\"\nmyuser.UserID=\"0\"\n</code></pre>\n\n<p>But I would go for the WITH statement instead, it looks cleaner.</p>\n\n<p>And I just took this as an example so dont complain over a class with many keywords, another example could be like: WITH RefundDialog.RefundDatagridView.SelectedRows(0) </p>\n" }, { "answer_id": 283853, "author": "ljorquera", "author_id": 9132, "author_profile": "https://Stackoverflow.com/users/9132", "pm_score": 3, "selected": false, "text": "<p>I would be suspicious of code that uses a lot this keyword: if it is used to make easier to set lots of instance variables or properties I think this may indicate that your classes are too large ( <a href=\"http://en.wikipedia.org/wiki/Code_smell\" rel=\"noreferrer\">Large Class smell</a> ). If you use it to replace long chains of calls like this: </p>\n\n<pre><code>UserHandler.GetUser.First.User.FirstName=\"Stefan\"\nUserHandler.GetUser.First.User.LastName=\"Karlsson\"\nUserHandler.GetUser.First.User.Age=\"39\"\nUserHandler.GetUser.First.User.Sex=\"Male\"\nUserHandler.GetUser.First.User.Occupation=\"Programmer\"\nUserHandler.GetUser.First.User.UserID=\"0\"\n</code></pre>\n\n<p>then you are probably violating <a href=\"http://www.ccs.neu.edu/home/lieber/LoD.html\" rel=\"noreferrer\">Demeter Law</a> </p>\n" }, { "answer_id": 284041, "author": "bart", "author_id": 19966, "author_profile": "https://Stackoverflow.com/users/19966", "pm_score": 2, "selected": false, "text": "<p>I don't use VB.NET (I used to use plain VB) but...</p>\n\n<p>Is the leading dot mandatory? If so, then I don't see a problem. In Javascript, the result of using <code>with</code> is that a property of an object looks just the same as a plain variable, and <em>that</em> is very dangerous, as you don't see if you're accessing a property or a variable, and thus, <code>with</code> is something to avoid.</p>\n\n<p>Not only is its use easier on the eyes, but for repeated access to properties of an object, it's likely to be faster, as the object is fetched through the method chain only once, and not once for every property.</p>\n\n<p>I do agree with other replies that you ought to avoid nested use of <code>with</code>, for the same reason as why to avoid <code>with</code> altogether in Javascript: because you no longer see what object your property belongs to.</p>\n" }, { "answer_id": 284073, "author": "John Rudy", "author_id": 14048, "author_profile": "https://Stackoverflow.com/users/14048", "pm_score": 5, "selected": false, "text": "<p>In practice, there are no really compelling points against it. I'm not a fan, but that's a personal preference, there's no empirical data to suggest that the <code>With</code> construct is bad.</p>\n\n<p>In .NET, it compiles to exactly the same code as fully-qualifying the object name, so there is no performance penalty for this sugar. I ascertained this by compiling, then disassembling, the following VB .NET 2.0 class:</p>\n\n<pre><code>Imports System.Text\n\nPublic Class Class1\n Public Sub Foo()\n Dim sb As New StringBuilder\n With sb\n .Append(\"foo\")\n .Append(\"bar\")\n .Append(\"zap\")\n End With\n\n Dim sb2 As New StringBuilder\n sb2.Append(\"foo\")\n sb2.Append(\"bar\")\n sb2.Append(\"zap\")\n End Sub\nEnd Class\n</code></pre>\n\n<p>The disassembly is as follows -- note that the calls to <code>sb2</code>'s <code>Append</code> method look identical to the <code>With</code> statement calls for <code>sb</code>:</p>\n\n<pre><code>.method public instance void Foo() cil managed\n{\n // Code size 91 (0x5b)\n .maxstack 2\n .locals init ([0] class [mscorlib]System.Text.StringBuilder sb,\n [1] class [mscorlib]System.Text.StringBuilder sb2,\n [2] class [mscorlib]System.Text.StringBuilder VB$t_ref$L0)\n IL_0000: nop\n IL_0001: newobj instance void [mscorlib]System.Text.StringBuilder::.ctor()\n IL_0006: stloc.0\n IL_0007: ldloc.0\n IL_0008: stloc.2\n IL_0009: ldloc.2\n IL_000a: ldstr \"foo\"\n IL_000f: callvirt instance class [mscorlib]System.Text.StringBuilder [mscorlib]System.Text.StringBuilder::Append(string)\n IL_0014: pop\n IL_0015: ldloc.2\n IL_0016: ldstr \"bar\"\n IL_001b: callvirt instance class [mscorlib]System.Text.StringBuilder [mscorlib]System.Text.StringBuilder::Append(string)\n IL_0020: pop\n IL_0021: ldloc.2\n IL_0022: ldstr \"zap\"\n IL_0027: callvirt instance class [mscorlib]System.Text.StringBuilder [mscorlib]System.Text.StringBuilder::Append(string)\n IL_002c: pop\n IL_002d: ldnull\n IL_002e: stloc.2\n IL_002f: newobj instance void [mscorlib]System.Text.StringBuilder::.ctor()\n IL_0034: stloc.1\n IL_0035: ldloc.1\n IL_0036: ldstr \"foo\"\n IL_003b: callvirt instance class [mscorlib]System.Text.StringBuilder [mscorlib]System.Text.StringBuilder::Append(string)\n IL_0040: pop\n IL_0041: ldloc.1\n IL_0042: ldstr \"bar\"\n IL_0047: callvirt instance class [mscorlib]System.Text.StringBuilder [mscorlib]System.Text.StringBuilder::Append(string)\n IL_004c: pop\n IL_004d: ldloc.1\n IL_004e: ldstr \"zap\"\n IL_0053: callvirt instance class [mscorlib]System.Text.StringBuilder [mscorlib]System.Text.StringBuilder::Append(string)\n IL_0058: pop\n IL_0059: nop\n IL_005a: ret\n} // end of method Class1::Foo\n</code></pre>\n\n<p>So if you like it, and find it more readable, go for it; there's no compelling reason not to. </p>\n\n<p>(By the way, <a href=\"https://stackoverflow.com/users/20/tom\">Tom</a>, I'm interested in knowing what happened with the debugger -- I can't recall ever seeing any unusual behavior in the debugger based on a <code>With</code> statement, so I'm curious to know what behavior you did see.)</p>\n" }, { "answer_id": 1723065, "author": "soemirno", "author_id": 67219, "author_profile": "https://Stackoverflow.com/users/67219", "pm_score": 2, "selected": false, "text": "<p>The 'with' is basically the 'cascade' from Smalltalk. It is a pattern in Kent Beck's Smalltalk Best Practice Patterns book.</p>\n\n<p>A summary of the pattern: use it when it makes sense to group the messages sent to the object. Don't use it if it just happens to be some messages sent to the same object.</p>\n" }, { "answer_id": 10029239, "author": "phillihp", "author_id": 232271, "author_profile": "https://Stackoverflow.com/users/232271", "pm_score": 4, "selected": false, "text": "<p>It's all about readability. Like all syntactic sugar, it can be <strong>overused</strong>.</p>\n\n<p><strong>Embrace it IF</strong> you're setting several members of an object over a few lines</p>\n\n<pre><code>With myObject\n .Property1 = arg1\n .Property2 = arg2\n...\n</code></pre>\n\n<p><strong>Avoid</strong> doing anything else with \"With\"</p>\n\n<p>If you write a With block that spans 50-100 lines and involves lots of other variables it can make it REALLY difficult to remember what was declared at the top of the block. For obvious reasons, I won't provide an example of such messy code</p>\n" }, { "answer_id": 18288030, "author": "JohnRC", "author_id": 1992793, "author_profile": "https://Stackoverflow.com/users/1992793", "pm_score": 4, "selected": false, "text": "<p>There is a difference between using With and making repeating references to an object, which is subtle but should be borne in mind, I think.</p>\n\n<p>When a WITH statement is used, it creates a new local variable referencing the object. Subsequent references using .xx are references to properties of that local reference. If during the execution of the WITH statement, the original variable reference is changed, the object referenced by the WITH does not change. Consider:</p>\n\n<pre><code>Dim AA As AAClass = GetNextAAObject()\nWith AA\n AA = GetNextAAObject()\n\n '// Setting property of original AA instance, not later instance\n .SomeProperty = SomeValue\nEnd With\n</code></pre>\n\n<p>So, the WITH statement is not simply syntactical sugar, it is genuinely a different construct. Whilst you would be unlikely to code something explicit like the above, in some situations this might occur inadvertently so you should be aware of the issue. The most likely situation is where you may be traversing a structure such as a network of objects whose interconnections my be implicitly changed by setting properties.</p>\n" }, { "answer_id": 32765636, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p><strong>AVOID the <em>WITH Block</em> at all costs</strong> (even readability). Two reasons: </p>\n\n<ol>\n<li>the <a href=\"https://msdn.microsoft.com/en-us/library/wc500chb.aspx\" rel=\"nofollow\">Microsoft Documentation about With...End With</a> says that in some circumstances, it creates a copy of the data on the stack, so any changes that you make will be thrown away. </li>\n<li>If you use it for LINQ Queries, the lambda results DO NOT Chain and so each intermediate clause's result is thrown away. </li>\n</ol>\n\n<p>To describe this, we have a (broken) example from a Textbook that my co-worker had to ask the author about (it is indeed incorrect, the Names have been changed to protect... whatever): </p>\n\n<blockquote>\n <p>With dbcontext.Blahs<br>\n .OrderBy(Function(currentBlah) currentBlah.LastName)<br>\n .ThenBy(Function(currentBlah) currentBlah.FirstName)<br>\n .Load()<br>\n End With</p>\n</blockquote>\n\n<p>The OrderBy and ThenBy have <strong>No Effect</strong> at all. IF you reformat the code by ONLY dropping the With and End With, and adding line continuation characters at the end of the first three lines... it works (as shown <em>15 pages later</em> in the same textbook).</p>\n\n<p>We don't need any more reason to <em>search and destroy</em> WITH Blocks. They only had meaning in an <strong>Interpreted</strong> framework.</p>\n" }, { "answer_id": 45738157, "author": "George Birbilis", "author_id": 903783, "author_profile": "https://Stackoverflow.com/users/903783", "pm_score": 1, "selected": false, "text": "<p>There's a gotcha when using it with structures, aka you can't set their fields, since you're working on a local copy (made at time of entry in with block) of the \"with\" expression and not working with a (copy of an) object reference in that case:</p>\n\n<blockquote>\n <p>The data type of objectExpression can be any class or structure type\n or even a Visual Basic elementary type such as Integer. If\n objectExpression results in anything other than an object, you can\n only read the values of its members or invoke methods, and you get an\n error if you try to assign values to members of a structure used in a\n With...End With statement. This is the same error you would get if you\n invoked a method that returned a structure and immediately accessed\n and assigned a value to a member of the function’s result, such as\n GetAPoint().x = 1. The problem in both cases is that the structure\n exists only on the call stack, and there is no way a modified\n structure member in these situations can write to a location such that\n any other code in the program can observe the change.</p>\n \n <p>The objectExpression is evaluated once, upon entry into the block. You\n can't reassign the objectExpression from within the With block.</p>\n</blockquote>\n\n<p><a href=\"https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/with-end-with-statement\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/with-end-with-statement</a></p>\n\n<p>guess the compiler could have been a bit more clever if you pass to with statement a structure name instead of an expression that returns a structure, but seems it's not</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283749", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20/" ]
At work, I'm frequently working on projects where numerous properties of certain objects have to be set during their construction or early during their lifetime. For the sake of convenience and readability, I often use the `With` statement to set these properties. I find that ``` With Me.Elements .PropertyA = True .PropertyB = "Inactive" ' And so on for several more lines End With ``` Looks much better than ``` Me.Elements.PropertyA = True Me.Elements.PropertyB = "Inactive" ' And so on for several more lines ``` for very long statements that simply set properties. I've noticed that there are some issues with using `With` while debugging; however, **I was wondering if there were any compelling reasons to avoid using `With` in practice**? I've always assumed the code generated via the compiler for the above two cases is basically the same which is why I've always chosen to write what I feel to be more readable.
If you have long variablenames and would end up with: ``` UserHandler.GetUser.First.User.FirstName="Stefan" UserHandler.GetUser.First.User.LastName="Karlsson" UserHandler.GetUser.First.User.Age="39" UserHandler.GetUser.First.User.Sex="Male" UserHandler.GetUser.First.User.Occupation="Programmer" UserHandler.GetUser.First.User.UserID="0" ....and so on ``` then I would use WITH to make it more readable: ``` With UserHandler.GetUser.First.User .FirstName="Stefan" .LastName="Karlsson" .Age="39" .Sex="Male" .Occupation="Programmer" .UserID="0" end with ``` In the later example there are even performance benefit over the first example because in the first example Im fetching the user every time I access a user property and in the WITH-case I only fetch the user one time. I can get the performance gain without using with, like this: ``` dim myuser as user =UserHandler.GetUser.First.User myuser.FirstName="Stefan" myuser.LastName="Karlsson" myuser.Age="39" myuser.Sex="Male" myuser.Occupation="Programmer" myuser.UserID="0" ``` But I would go for the WITH statement instead, it looks cleaner. And I just took this as an example so dont complain over a class with many keywords, another example could be like: WITH RefundDialog.RefundDatagridView.SelectedRows(0)
283,751
<p>I have the problem, that PHP replaces all spaces with underscores in POST and GET variables.</p> <p>For example if I have the URL: <code>http://localhost/proxy.php?user name=Max</code> the browser will convert it to <code>http://localhost/proxy.php?user%20name=Max</code>.</p> <p>But if I give the $_GET parameters out, the key is not <code>user name</code> but <code>user_name</code> (note the underscore)!</p> <p>Is there any possibility to change this behaviour?</p>
[ { "answer_id": 283778, "author": "Fred", "author_id": 33630, "author_profile": "https://Stackoverflow.com/users/33630", "pm_score": 1, "selected": false, "text": "<p>As far as i can remember, i've never seen spaces in URL parameter names...</p>\n\n<p>I think, it would be better to convert all spaces of parameter names into \"_\".</p>\n" }, { "answer_id": 283781, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 6, "selected": true, "text": "<p>From the <a href=\"http://www.php.net/manual/en/language.variables.external.php\" rel=\"noreferrer\">PHP manual</a>:</p>\n\n<blockquote>\n <p>Dots in incoming variable names</p>\n \n <p>Typically, PHP does not alter the\n names of variables when they are\n passed into a script. However, it\n should be noted that the dot (period,\n full stop) is not a valid character in\n a PHP variable name. For the reason,\n look at it: </p>\n\n<pre><code>&lt;?php $varname.ext; /* invalid variable name */ ?&gt;\n</code></pre>\n \n <p>Now, what\n the parser sees is a variable named\n $varname, followed by the string\n concatenation operator, followed by\n the barestring (i.e. unquoted string\n which doesn't match any known key or\n reserved words) 'ext'. Obviously, this\n doesn't have the intended result.</p>\n \n <p>For this reason, it is important to\n note that PHP will automatically\n replace any dots in incoming variable\n names with underscores.</p>\n</blockquote>\n\n<p>And a comment on the page:</p>\n\n<blockquote>\n <p>The full list of field-name characters that PHP converts to _ (underscore) is the following (not just dot):</p>\n\n<pre><code>chr(32) ( ) (space)\nchr(46) (.) (dot)\nchr(91) ([) (open square bracket)\nchr(128) - chr(159) (various)\n</code></pre>\n \n <p>PHP irreversibly modifies field names containing these characters in an attempt to maintain compatibility with the deprecated register_globals feature.</p>\n</blockquote>\n" }, { "answer_id": 283786, "author": "Adam Byrtek", "author_id": 36656, "author_profile": "https://Stackoverflow.com/users/36656", "pm_score": 2, "selected": false, "text": "<p>In the old crazy times of register_globals query string was unpacked by PHP into global variables, but the format of variable identifiers is constrained, so obviously spaces couldn't work. This limitation remained, and honestly I believe it's a good idea to keep it this way.</p>\n\n<p>If you really cannot change spaces into underscores in your URLs, just mangle the $_GET array when you process the request and substitute every underscore by a space.</p>\n" }, { "answer_id": 689574, "author": "Rudi", "author_id": 83613, "author_profile": "https://Stackoverflow.com/users/83613", "pm_score": 3, "selected": false, "text": "<p>I think the only possibility to get the wanted parameters, is to parse them on your own using <code>$_SERVER['QUERY_STRING']</code>:</p>\n\n<pre><code>$a_pairs = explode('&amp;', $_SERVER['QUERY_STRING']);\nforeach($a_pairs AS $s_pair){\n $a_pair = explode('=', $s_pair);\n if(count($a_pair) == 1) $a_pair[1] = '';\n\n $a_pair[0] = urldecode($a_pair[0]);\n $a_pair[1] = urldecode($a_pair[1]);\n\n $GLOBALS['_GET'][$a_pair[0]] = $a_pair[1];\n $_GET[$a_pair[0]] = $a_pair[1];\n}\n</code></pre>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30724/" ]
I have the problem, that PHP replaces all spaces with underscores in POST and GET variables. For example if I have the URL: `http://localhost/proxy.php?user name=Max` the browser will convert it to `http://localhost/proxy.php?user%20name=Max`. But if I give the $\_GET parameters out, the key is not `user name` but `user_name` (note the underscore)! Is there any possibility to change this behaviour?
From the [PHP manual](http://www.php.net/manual/en/language.variables.external.php): > > Dots in incoming variable names > > > Typically, PHP does not alter the > names of variables when they are > passed into a script. However, it > should be noted that the dot (period, > full stop) is not a valid character in > a PHP variable name. For the reason, > look at it: > > > > ``` > <?php $varname.ext; /* invalid variable name */ ?> > > ``` > > Now, what > the parser sees is a variable named > $varname, followed by the string > concatenation operator, followed by > the barestring (i.e. unquoted string > which doesn't match any known key or > reserved words) 'ext'. Obviously, this > doesn't have the intended result. > > > For this reason, it is important to > note that PHP will automatically > replace any dots in incoming variable > names with underscores. > > > And a comment on the page: > > The full list of field-name characters that PHP converts to \_ (underscore) is the following (not just dot): > > > > ``` > chr(32) ( ) (space) > chr(46) (.) (dot) > chr(91) ([) (open square bracket) > chr(128) - chr(159) (various) > > ``` > > PHP irreversibly modifies field names containing these characters in an attempt to maintain compatibility with the deprecated register\_globals feature. > > >
283,752
<p>I'm automating a web application (the Mantis bug tracker) and I'm getting an interesting response header from it, called Refresh:</p> <pre><code>HTTP/1.x 200 OK ... Refresh: 0;url=my_view_page.php </code></pre> <p>It seems to be acting the same way that <a href="http://en.wikipedia.org/wiki/Meta_refresh" rel="noreferrer">meta refresh</a> does, and the meta refresh technique implies that it is an equivalent of a header in HTTP.</p> <p>Problem is, I can't find any mention of the Refresh header in the <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html" rel="noreferrer">HTTP standard</a> or any other definitive documentation on how it should be parsed and what the browser should do when it encounters it.</p> <p>What's going on here?</p>
[ { "answer_id": 283776, "author": "Loki", "author_id": 17324, "author_profile": "https://Stackoverflow.com/users/17324", "pm_score": 5, "selected": false, "text": "<p>from the W3C HTML 4.01 specification, quote:</p>\n<blockquote>\n<p>META and HTTP headers</p>\n<p>The http-equiv attribute can be used in place of the name attribute and has a special significance when documents are retrieved via the Hypertext Transfer Protocol (HTTP). HTTP servers may use the property name specified by the http-equiv attribute to create an [RFC822]-style header in the HTTP response. Please see the HTTP specification ([RFC2616]) for details on valid HTTP headers.</p>\n</blockquote>\n<p>What this means is that when you use the <code>&lt;meta http-equiv=&quot;refresh&quot; url=&quot;...&quot;/&gt;</code> tag, you are actually instructing the browser to act as if there were a <code>Refresh</code> header being sent.</p>\n<p>a good overview of the history of it can be found at <a href=\"http://www.securiteam.com/securityreviews/6Z00320HFQ.html\" rel=\"noreferrer\">http://www.securiteam.com/securityreviews/6Z00320HFQ.html</a></p>\n" }, { "answer_id": 283794, "author": "Alistair", "author_id": 11324, "author_profile": "https://Stackoverflow.com/users/11324", "pm_score": 7, "selected": true, "text": "<p>As far as I know, Refresh (along with Set-Cookie and possibly some other proprietary pseudo-headers) were created by Netscape in the very early days of the internet and have been basically (but not quite) standard since then. Because just about every browser supports it, Refresh is pretty safe to use -- and commonly is.</p>\n\n<p>I guess it never became part of the official standards because they already had provisions for that with the status codes.</p>\n" }, { "answer_id": 283797, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 4, "selected": false, "text": "<p>According to <a href=\"http://en.wikipedia.org/wiki/URL_redirection#Refresh_Meta_tag_and_HTTP_refresh_header\" rel=\"noreferrer\">Wikipedia: URL Redirection</a>:</p>\n\n<blockquote>\n <p>This is a proprietary/non-standard\n extension by Netscape. It is supported\n by most web browsers.</p>\n</blockquote>\n" }, { "answer_id": 283799, "author": "Alnitak", "author_id": 6782, "author_profile": "https://Stackoverflow.com/users/6782", "pm_score": 3, "selected": false, "text": "<p>I believe it was originally a Netscape extension, and was not standardised because it's deprecated by W3C:</p>\n\n<p><a href=\"http://www.w3.org/TR/WCAG10-HTML-TECHS/#meta-element\" rel=\"noreferrer\">http://www.w3.org/TR/WCAG10-HTML-TECHS/#meta-element</a></p>\n" }, { "answer_id": 59167331, "author": "Mike", "author_id": 920404, "author_profile": "https://Stackoverflow.com/users/920404", "pm_score": 3, "selected": false, "text": "<p>The \"Refresh\" HTTP response header has been standardized (for web browsers,\nanyway) in HTML:</p>\n\n<p><a href=\"https://html.spec.whatwg.org/multipage/browsing-the-web.html#navigating-across-documents%3Ashared-declarative-refresh-steps\" rel=\"noreferrer\">https://html.spec.whatwg.org/multipage/browsing-the-web.html#navigating-across-documents%3Ashared-declarative-refresh-steps</a></p>\n\n<p>That URL doesn't look so stable, so here are the relevant steps as of\n2019-12-03:</p>\n\n<blockquote>\n <ol start=\"13\">\n <li>If <em>response</em> has a <code>Refresh</code> header, then:\n \n <ol>\n <li>Let <em>value</em> be the isomorphic decoding of the value of the header.</li>\n <li>Run the shared declarative refresh steps with <em>document</em> and <em>value</em>.</li>\n </ol></li>\n </ol>\n</blockquote>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15109/" ]
I'm automating a web application (the Mantis bug tracker) and I'm getting an interesting response header from it, called Refresh: ``` HTTP/1.x 200 OK ... Refresh: 0;url=my_view_page.php ``` It seems to be acting the same way that [meta refresh](http://en.wikipedia.org/wiki/Meta_refresh) does, and the meta refresh technique implies that it is an equivalent of a header in HTTP. Problem is, I can't find any mention of the Refresh header in the [HTTP standard](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html) or any other definitive documentation on how it should be parsed and what the browser should do when it encounters it. What's going on here?
As far as I know, Refresh (along with Set-Cookie and possibly some other proprietary pseudo-headers) were created by Netscape in the very early days of the internet and have been basically (but not quite) standard since then. Because just about every browser supports it, Refresh is pretty safe to use -- and commonly is. I guess it never became part of the official standards because they already had provisions for that with the status codes.
283,759
<p>I'm converting my applications to Delphi 2009 and faced an intriguing issue with some calls that need to convert a string (wide) to AnsiString.</p> <p>Here's an example to demonstrate the issue I'm having:</p> <pre><code>var s: PAnsiChar; ... s := PAnsiChar(Application.ExeName); </code></pre> <p>With Delphi 2007 and previous versions, s := PChar(Application.ExeName) would return the application exe path.</p> <p>with Delphi 2009, s := PAnsiChar(Application.ExeName) returns only 'E'.</p> <p>My guess is that's because I'm converting a unicode string to an ansi string but how can I convert it so that a PAnsiChar gets the full string?</p>
[ { "answer_id": 283773, "author": "Toon Krijthe", "author_id": 18061, "author_profile": "https://Stackoverflow.com/users/18061", "pm_score": 6, "selected": true, "text": "<p>I have no Delphi 2009 here, so I can't check it. But maybe you have to try:</p>\n\n<pre><code>s := PAnsiChar(AnsiString(Application.ExeName));\n</code></pre>\n\n<p>As gabr already pointed, this is not a very good practice, and you will only use it if you are 100% sure. The string only contains characters that have a direct mapping to the ANSI range.</p>\n\n<p>That's why you should get a warning because you are converting Unicode to ANSI.</p>\n" }, { "answer_id": 283817, "author": "Jamie", "author_id": 922, "author_profile": "https://Stackoverflow.com/users/922", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/ms776420%5C(VS.85%5C).aspx\" rel=\"nofollow noreferrer\">WideCharToMultiByte</a> could help you.</p>\n" }, { "answer_id": 283885, "author": "smartins", "author_id": 36544, "author_profile": "https://Stackoverflow.com/users/36544", "pm_score": 1, "selected": false, "text": "<p>Gamecat explicit conversion works. I'm explaining the problem in more detail below so that perhaps someone can point to a better solution.</p>\n\n<p>I'm using the following function to retrieve the application compilation date:</p>\n\n<pre><code>function LinkerTimeStamp(const FileName: string): TDateTime;\nvar\n LI: TLoadedImage;\nbegin\n {$IFDEF UNICODE}\n Win32Check(MapAndLoad(PAnsiChar(AnsiString(FileName)), nil, @LI, False, True));\n {$ELSE}\n Win32Check(MapAndLoad(PChar(FileName), nil, @LI, False, True));\n {$ENDIF}\n Result := LI.FileHeader.FileHeader.TimeDateStamp / SecsPerDay + UnixDateDelta;\n UnMapAndLoad(@LI);\nend;\n</code></pre>\n\n<p>MapAndLoad requires a PAnsiChar for the ImageName Parameter so I need to convert the unicode string. Is there any other alternative as to explicitly convert to AnsiString first?</p>\n" }, { "answer_id": 614720, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I had the exact same problem. The <code>PAnsiChar</code> only points to the first character. I wrote the following function to handle the old functionality.</p>\n\n<pre><code>// This function converts a string to a PAnsiChar\n// If the output is not the same, an exception is raised\n// Author: [email protected]\n\nfunction StringToPAnsiChar(stringVar : string) : PAnsiChar;\nVar\n AnsString : AnsiString;\n InternalError : Boolean;\nbegin\n InternalError := false;\n Result := '';\n try\n if stringVar &lt;&gt; '' Then\n begin\n AnsString := AnsiString(StringVar);\n Result := PAnsiChar(PAnsiString(AnsString));\n end;\n Except\n InternalError := true;\n end;\n if InternalError or (String(Result) &lt;&gt; stringVar) then\n begin\n Raise Exception.Create('Conversion from string to PAnsiChar failed!');\n end;\nend;\n</code></pre>\n" }, { "answer_id": 767896, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>I think You are a bit off.\nEvery Win32 API function has a unicode counterpart, if it is expecting a string.\nTry <strong>MapAndLoadW</strong> instead of <strong>MapAndLoad</strong>...</p>\n" }, { "answer_id": 2337315, "author": "Meka", "author_id": 281567, "author_profile": "https://Stackoverflow.com/users/281567", "pm_score": 3, "selected": false, "text": "<p>Instead of using type <code>String</code>, use <code>RawByteString</code>:</p>\n\n<pre><code>s: RawByteString;\n\ns := LoadSomeRegularString(usually a string type);\n\nPAnsiChar(s) &lt;&lt;&lt; all fine.\n</code></pre>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36544/" ]
I'm converting my applications to Delphi 2009 and faced an intriguing issue with some calls that need to convert a string (wide) to AnsiString. Here's an example to demonstrate the issue I'm having: ``` var s: PAnsiChar; ... s := PAnsiChar(Application.ExeName); ``` With Delphi 2007 and previous versions, s := PChar(Application.ExeName) would return the application exe path. with Delphi 2009, s := PAnsiChar(Application.ExeName) returns only 'E'. My guess is that's because I'm converting a unicode string to an ansi string but how can I convert it so that a PAnsiChar gets the full string?
I have no Delphi 2009 here, so I can't check it. But maybe you have to try: ``` s := PAnsiChar(AnsiString(Application.ExeName)); ``` As gabr already pointed, this is not a very good practice, and you will only use it if you are 100% sure. The string only contains characters that have a direct mapping to the ANSI range. That's why you should get a warning because you are converting Unicode to ANSI.
283,763
<p>I am reading a .csv file and returning its lines in string array. One of the members is manufacturer, for which I have Toyota, Ford, etc.</p> <p>I want to sort an array (Can be another collection) of the rows, by the value in manufacturer and alphabetical order.</p> <p>So I'd have:</p> <pre><code>28437 Ford Fiesta 328 Honda Civic 34949 Toyota Yaris </code></pre> <p>and so forth...</p> <p>What would be the best way to do this using C# and no database? I say no database because I could insert the csv into a table in a sql server database, and then query it and return the data. But this data is going into a html table built on the fly, which would make the database approach a little long winded.</p>
[ { "answer_id": 283771, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 2, "selected": false, "text": "<p>What version of .NET are you using? If you're using 3.5 - or can use C# 3.0 and <a href=\"http://www.albahari.com/nutshell/linqbridge.aspx\" rel=\"nofollow noreferrer\">LINQBridge</a> - then I'd definitely go with LINQ. First transform each line into some appropriate object, and then use OrderBy:</p>\n\n<pre><code>var cars = lines.Select(line =&gt; Car.ParseLine(line))\n .OrderBy(car =&gt; car.Manufacturer);\n</code></pre>\n" }, { "answer_id": 283842, "author": "TToni", "author_id": 20703, "author_profile": "https://Stackoverflow.com/users/20703", "pm_score": 1, "selected": false, "text": "<p>If you just have a bunch of strings in an Array, use</p>\n\n<pre><code>Array.Sort(myArray)\n</code></pre>\n\n<p>That will put the strings in \"myArray\" in alphabetical order (case sensitive).</p>\n\n<p>If you want to to different comparisons (like case-insensitive for example), you can define an own ICcomparer or use Linq-Extensions, preferrably with a lambda expression like</p>\n\n<pre><code> string [] sArray = new string[] { \"fsdhj\", \"FA\", \"FX\", \"fxx\", \"Äbc\" };\n sArray = sArray.OrderBy(s =&gt; s.ToLowerInvariant()).ToArray();\n</code></pre>\n\n<p>There's a whole bunch of other sorting methods, but these are the most basic. I could give you a more detailed answer to your problem, if I understood better what your input-object looks like. As long as it's just an array of strings, you should be fine with the above.</p>\n\n<p>In response to the first two comments below I should also note that the invariant string-sorting method given above is not the best one for that particular job (see comments).</p>\n\n<p>However it <strong>does</strong> illustrate the use of extension methods with lambda expressions, which come in very handy in situations where you don't have predefined IComparer-classes.</p>\n" }, { "answer_id": 283845, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 1, "selected": false, "text": "<p>Without trying to second guess Jon, I believe he is suggesting that you would create a class Car (\"some appropriate object\") with the necessary properties, and the ability to populate a Car from a line:</p>\n\n<pre><code>public class Car\n{\n public int Id {get;set;}\n public string Manufacturer {get;set;}\n public string Model {get;set;}\n\n public static Car ParseLine(string line)\n {\n string[] parts = line.Split(DELIMITER);\n return new Car\n {\n Id = int.Parse(parts[0]),\n Manufacturer = parts[1],\n Model = parts[2]\n };\n }\n}\n</code></pre>\n\n<p>i.e. treating the lines as objects. Then with LINQ things become quite simple:</p>\n\n<pre><code> var query = from line in lines\n let car = Car.ParseLine(line)\n orderby car.Manufacturer\n select car;\n\n var arr = query.ToArray();\n</code></pre>\n\n<p>Note that you can do this without LINQ too, for example (using a <code>Car[]</code> array) - an in-place array sort:</p>\n\n<pre><code> Array.Sort(arr, (x, y) =&gt; string.Compare(x.Manufacturer, y.Manufacturer));\n</code></pre>\n\n<p>or the same with <code>List&lt;Car&gt;</code>:</p>\n\n<pre><code> list.Sort((x, y) =&gt; string.Compare(x.Manufacturer, y.Manufacturer));\n</code></pre>\n" }, { "answer_id": 283849, "author": "Todd", "author_id": 31940, "author_profile": "https://Stackoverflow.com/users/31940", "pm_score": 1, "selected": false, "text": "<p>In Jon's post he is parsing the line into objects first, then sorting. You could also just sort an IEnumerable list of strings based on part of the string. Here is an example that is sorting the list on a substring (first 10 characters starting at position 6):</p>\n\n<pre><code>List&lt;string&gt; lines = new List&lt;string&gt;\n {\n \"34949 Toyota Yaris\",\n \"328 Honda Civic\",\n \"28437 Ford Fiesta\"\n };\n\nvar sortedLines = lines.OrderBy(line =&gt; line.Substring(6, 10));\n// Or make it case insensitive\n// var sortedLines = lines.OrderBy(line =&gt; line.Substring(6, 10), StringComparer.InvariantCultureIgnoreCase);\n\nforeach (var line in sortedLines)\n{\n Console.WriteLine(line);\n}\n</code></pre>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283763", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32484/" ]
I am reading a .csv file and returning its lines in string array. One of the members is manufacturer, for which I have Toyota, Ford, etc. I want to sort an array (Can be another collection) of the rows, by the value in manufacturer and alphabetical order. So I'd have: ``` 28437 Ford Fiesta 328 Honda Civic 34949 Toyota Yaris ``` and so forth... What would be the best way to do this using C# and no database? I say no database because I could insert the csv into a table in a sql server database, and then query it and return the data. But this data is going into a html table built on the fly, which would make the database approach a little long winded.
What version of .NET are you using? If you're using 3.5 - or can use C# 3.0 and [LINQBridge](http://www.albahari.com/nutshell/linqbridge.aspx) - then I'd definitely go with LINQ. First transform each line into some appropriate object, and then use OrderBy: ``` var cars = lines.Select(line => Car.ParseLine(line)) .OrderBy(car => car.Manufacturer); ```
283,764
<p>In a SQL Server database, I record people's date of birth. Is there an straight-forward method of working out the person's age on a given date using SQL only? </p> <p>Using <strong>DATEDIFF(YEAR, DateOfBirth, GETDATE())</strong> does not work as this only looks at the year part of the date. For example <strong>DATEDIFF(YEAR, '31 December 2007', '01 January 2008')</strong> returns 1.</p>
[ { "answer_id": 283780, "author": "scable", "author_id": 8942, "author_profile": "https://Stackoverflow.com/users/8942", "pm_score": 6, "selected": true, "text": "<p>Check out this article: <a href=\"http://www.kodyaz.com/articles/calculate-age-sql-code.aspx\" rel=\"noreferrer\">How to calculate age of a person using SQL codes</a></p>\n\n<p>Here is the code from the article:</p>\n\n<pre><code>DECLARE @BirthDate DATETIME\nDECLARE @CurrentDate DATETIME\n\nSELECT @CurrentDate = '20070210', @BirthDate = '19790519'\n\nSELECT DATEDIFF(YY, @BirthDate, @CurrentDate) - CASE WHEN( (MONTH(@BirthDate)*100 + DAY(@BirthDate)) &gt; (MONTH(@CurrentDate)*100 + DAY(@CurrentDate)) ) THEN 1 ELSE 0 END \n</code></pre>\n" }, { "answer_id": 656799, "author": "Mark Brittingham", "author_id": 15592, "author_profile": "https://Stackoverflow.com/users/15592", "pm_score": 3, "selected": false, "text": "<p>There is another way that is a bit simpler:</p>\n\n<pre><code>Select CAST(DATEDIFF(hh, [birthdate], GETDATE()) / 8766 AS int) AS Age\n</code></pre>\n\n<p>Because the rounding here is very granular, this is <em>almost</em> perfectly accurate. The exceptions are so convoluted that they are almost humorous: every fourth year the age returned will be one year too young if we A) ask for the age before 6:00 AM, B) on the person's birthday and C) their birthday is after February 28th. In my setting, this is a perfectly acceptable compromise.</p>\n" }, { "answer_id": 9085213, "author": "John Pick", "author_id": 251034, "author_profile": "https://Stackoverflow.com/users/251034", "pm_score": 2, "selected": false, "text": "<p>FWIW, Age can be computed in a straightforward manner without resorting to hacks (not that there's anything wrong with hacks!):</p>\n\n<pre><code>CREATE FUNCTION Age (@BirthDate DATETIME)\nRETURNS INT\nAS\nBEGIN\n DECLARE @AgeOnBirthdayThisYear INT\n DECLARE @BirthdayThisYear DATETIME\n SET @AgeOnBirthdayThisYear = DATEDIFF(year, @BirthDate, GETDATE())\n SET @BirthdayThisYear = DATEADD(year, @AgeOnBirthdayThisYear, @BirthDate)\n RETURN\n @AgeOnBirthdayThisYear\n - CASE WHEN @BirthdayThisYear &gt; GETDATE() THEN 1 ELSE 0 END\nEND\n</code></pre>\n" }, { "answer_id": 12776316, "author": "Paul", "author_id": 61335, "author_profile": "https://Stackoverflow.com/users/61335", "pm_score": 1, "selected": false, "text": "<p>This solution show how in one query without variables</p>\n\n<pre><code>SELECT DATEDIFF(YY, birthdate, GETDATE()) - CASE WHEN( (MONTH(birthdate)*100 + DAY(birthdate)) &gt; (MONTH(GETDATE())*100 + DAY(GETDATE())) ) THEN 1 ELSE 0 END\n</code></pre>\n" }, { "answer_id": 13035623, "author": "brianary", "author_id": 54323, "author_profile": "https://Stackoverflow.com/users/54323", "pm_score": 1, "selected": false, "text": "<p>This is more concise and a bit faster than the answers provided, and completely accurate:</p>\n\n<pre><code>datediff(year,DateOfBirth,getdate()-datepart(dy,DateOfBirth)+1)\n</code></pre>\n" }, { "answer_id": 21468800, "author": "user3255222", "author_id": 3255222, "author_profile": "https://Stackoverflow.com/users/3255222", "pm_score": 0, "selected": false, "text": "<p>I hope this one is perfect provided you accept the algorithm that a leap-baby turns a year older on successive February 29th's, or March 1's on non-leap years. @DOB must contain a date within a few centuries of now, @AsOf must contain a similar date >= @DOB:</p>\n\n<pre><code>SET @Age = YEAR(@AsOf) - YEAR(@DOB) - 1\nIF MONTH(@AsOf) * 100 + DAY(@AsOf) &gt;= MONTH(@DOB) * 100 + DAY(@DOB)\n SET @Age = @Age + 1\n</code></pre>\n\n<p>I'd REALLY REALLY appreciate any testing and comments as I haven't found a way yet to break it... yet.</p>\n\n<p>Added - 1/31/2014: This one seems to work perfectly too even though at first glance it looks too crude:</p>\n\n<pre><code>SET @Age = FLOOR(DATEDIFF(dd,@DOB,@CompareDate)/365.25)\n</code></pre>\n\n<p>Pop these in a function and here's a test script:</p>\n\n<pre><code> SELECT dbo.fnGetAge('2/27/2008', '2/27/2012')\n SELECT dbo.fnGetAge('2/27/2008', '2/28/2012')\n SELECT dbo.fnGetAge('2/27/2008', '2/29/2012')\n SELECT dbo.fnGetAge('2/27/2008', '3/1/2012')\n -- 4 4 4 4\n SELECT dbo.fnGetAge('2/28/2008', '2/27/2012')\n SELECT dbo.fnGetAge('2/28/2008', '2/28/2012')\n SELECT dbo.fnGetAge('2/28/2008', '2/29/2012')\n SELECT dbo.fnGetAge('2/28/2008', '3/1/2012')\n -- 3 4 4 4\n SELECT dbo.fnGetAge('2/29/2008', '2/27/2012')\n SELECT dbo.fnGetAge('2/29/2008', '2/28/2012')\n SELECT dbo.fnGetAge('2/29/2008', '2/29/2012')\n SELECT dbo.fnGetAge('2/29/2008', '3/1/2012')\n -- 3 3 4 4\n SELECT dbo.fnGetAge('3/1/2008', '2/27/2012')\n SELECT dbo.fnGetAge('3/1/2008', '2/28/2012')\n SELECT dbo.fnGetAge('3/1/2008', '2/29/2012')\n SELECT dbo.fnGetAge('3/1/2008', '3/1/2012')\n -- 3 3 3 4\n SELECT dbo.fnGetAge('3/1/2007', '2/27/2012')\n SELECT dbo.fnGetAge('3/1/2007', '2/28/2012')\n SELECT dbo.fnGetAge('3/1/2007', '2/29/2012')\n SELECT dbo.fnGetAge('3/1/2007', '3/1/2012')\n -- 4 4 4 5\n SELECT dbo.fnGetAge('3/1/2007', '2/27/2013')\n SELECT dbo.fnGetAge('3/1/2007', '2/28/2013')\n SELECT dbo.fnGetAge('3/1/2007', '3/1/2013')\n SELECT dbo.fnGetAge('2/27/2007', '2/28/2013')\n SELECT dbo.fnGetAge('2/28/2007', '2/28/2014')\n -- 5 5 6 6 7\n</code></pre>\n\n<p>Cheers</p>\n\n<p>PS: You can probably tweak the February 29 decision to being a day earlier if that floats your boat.</p>\n" }, { "answer_id": 34756768, "author": "Bony Bathini", "author_id": 5780328, "author_profile": "https://Stackoverflow.com/users/5780328", "pm_score": 0, "selected": false, "text": "<pre><code>SELECT Pname, DOB, DATEDIFF(YEAR, DOB, GETDATE()) AS Age\nFROM tablename\n</code></pre>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7585/" ]
In a SQL Server database, I record people's date of birth. Is there an straight-forward method of working out the person's age on a given date using SQL only? Using **DATEDIFF(YEAR, DateOfBirth, GETDATE())** does not work as this only looks at the year part of the date. For example **DATEDIFF(YEAR, '31 December 2007', '01 January 2008')** returns 1.
Check out this article: [How to calculate age of a person using SQL codes](http://www.kodyaz.com/articles/calculate-age-sql-code.aspx) Here is the code from the article: ``` DECLARE @BirthDate DATETIME DECLARE @CurrentDate DATETIME SELECT @CurrentDate = '20070210', @BirthDate = '19790519' SELECT DATEDIFF(YY, @BirthDate, @CurrentDate) - CASE WHEN( (MONTH(@BirthDate)*100 + DAY(@BirthDate)) > (MONTH(@CurrentDate)*100 + DAY(@CurrentDate)) ) THEN 1 ELSE 0 END ```
283,766
<p>I have an application that imports data from a pickled file. It works just fine in Windows but Mac and Linux behaviour is odd.</p> <p>In OS X, the pickled file (file extension ".char") is unavailable as a selection unless I set the file type to *.*. Then, if I select a file that has the .char extension, it won't load, giving the error</p> <blockquote> <pre><code>unpickle_file = cPickle.load(char_file) </code></pre> <p>ValueError: could not convert string to float</p> </blockquote> <p>However, if I create a file that doesn't have the .char extension, that file will load up just fine.</p> <p>In Linux, when I use the "file open" dialog, my pickled files aren't visible, whether or not they have a file extension. However, I can see them under Nautilus or Dolphin. They simply don't exist to my application though.</p> <hr> <p><strong>Edit</strong> Here's the save code:</p> <pre><code>def createSaveFile(self): """Create the data files to be saved and save them. Creates a tuple comprised of a dictionary of general character information and the character's skills dictionary.""" if self.file_name: self.save_data = ({'Name':self.charAttribs.name, &lt;snip&gt; self.charAttribs.char_skills_dict) self.file = open(self.file_name, 'w') cPickle.dump(self.save_data, self.file) self.file.close() </code></pre> <p>Here's the open code:</p> <pre><code> def getCharFile(self, event): # wxGlade: CharSheet.&lt;event_handler&gt; """Retrieve pickled character file from disk.""" wildcard = "Character files (*.char) | *.char | All files (*.*) | *.*" openDialog = wx.FileDialog(None, "Choose a character file", os.getcwd(), "", wildcard, wx.OPEN | wx.CHANGE_DIR) if openDialog.ShowModal() == wx.ID_OK: self.path = openDialog.GetPath() try: char_file = open(self.path, "r") unpickle_file = cPickle.load(char_file) char_data, char_skills = unpickle_file self.displayCharacter(char_data, char_skills) except IOError: self.importError = wx.MessageDialog(self, "The character file is not available!", "Character Import Error", wx.OK | wx.ICON_ERROR) self.importError.ShowModal() self.importError.Destroy() openDialog.Destroy() </code></pre>
[ { "answer_id": 283802, "author": "Adam Byrtek", "author_id": 36656, "author_profile": "https://Stackoverflow.com/users/36656", "pm_score": 4, "selected": true, "text": "<p>Probably you didn't open the file in binary mode when writing and/or reading the pickled data. In this case newline format conversion will occur, which can break the binary data.</p>\n\n<p>To open a file in binary mode you have to provide \"b\" as part of the mode string:</p>\n\n<pre><code>char_file = open('pickle.char', 'rb')\n</code></pre>\n" }, { "answer_id": 283854, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 3, "selected": false, "text": "<p>As mentioned by <a href=\"https://stackoverflow.com/questions/283766/pickled-file-wont-load-on-maclinux#283802\">Adam</a>, the problem is likely to be the newline format of the pickle file.</p>\n\n<p>Unfortunately, the real problem is actually caused on <em>save</em> rather than load. This may be recoverable if you're using text mode pickles, rather than binary. Try opening the file in universal newline mode, which will cause python to guess what the right line-endings are ie:</p>\n\n<pre><code>char_file=open('filename.char','rU')\n</code></pre>\n\n<p>However, if you're using a binary format (cPickle.dump(file, 1)) you may have an unrecoverably corrupted pickle (even when loading in Windows) - if you're lucky and no \\r\\n characters show up then it may work, but as soon as this occurs you could end up with corrupted data, as there's no way to distinguish between a \"real\" \\r\\n code and one windows has inserted on seeing just \\n.</p>\n\n<p>The best way to handle things to be loaded in multiple platforms is to always save in binary mode. On your windows machine, when saving the pickle use:</p>\n\n<pre><code>char_file = open('filename.char','wb')\ncPickle.dumps(data, char_file)\n</code></pre>\n" }, { "answer_id": 284357, "author": "John Montgomery", "author_id": 5868, "author_profile": "https://Stackoverflow.com/users/5868", "pm_score": 2, "selected": false, "text": "<pre><code>self.file = open(self.file_name, 'w')</code></pre>\n\n<p>Should be:</p>\n\n<pre><code>self.file = open(self.file_name, 'wb')</code></pre>\n\n<p>In your <code>createSaveFile</code> function, to save the file in binary mode (rather than text mode). You should also make sure you open the file in binary mode as well (rb).</p>\n\n<p>If you don't use binary mode then Windows will convert all new-lines to \\r\\n and will effectively corrupt the file (at least as far as other OS's are concerned).</p>\n" }, { "answer_id": 9357720, "author": "jkellydresser", "author_id": 1220465, "author_profile": "https://Stackoverflow.com/users/1220465", "pm_score": 2, "selected": false, "text": "<p>Another way to get this error is to forget to close the output file after pickling. This can leave an incomplete file that fails in random ways during subsequent unpickling.</p>\n" }, { "answer_id": 24923596, "author": "Hadi", "author_id": 433261, "author_profile": "https://Stackoverflow.com/users/433261", "pm_score": 0, "selected": false, "text": "<p>Use dos2unix tool</p>\n\n<pre><code>dos2unix pickle.char\n</code></pre>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18676/" ]
I have an application that imports data from a pickled file. It works just fine in Windows but Mac and Linux behaviour is odd. In OS X, the pickled file (file extension ".char") is unavailable as a selection unless I set the file type to \*.\*. Then, if I select a file that has the .char extension, it won't load, giving the error > > > ``` > unpickle_file = cPickle.load(char_file) > > ``` > > ValueError: could not convert string to float > > > However, if I create a file that doesn't have the .char extension, that file will load up just fine. In Linux, when I use the "file open" dialog, my pickled files aren't visible, whether or not they have a file extension. However, I can see them under Nautilus or Dolphin. They simply don't exist to my application though. --- **Edit** Here's the save code: ``` def createSaveFile(self): """Create the data files to be saved and save them. Creates a tuple comprised of a dictionary of general character information and the character's skills dictionary.""" if self.file_name: self.save_data = ({'Name':self.charAttribs.name, <snip> self.charAttribs.char_skills_dict) self.file = open(self.file_name, 'w') cPickle.dump(self.save_data, self.file) self.file.close() ``` Here's the open code: ``` def getCharFile(self, event): # wxGlade: CharSheet.<event_handler> """Retrieve pickled character file from disk.""" wildcard = "Character files (*.char) | *.char | All files (*.*) | *.*" openDialog = wx.FileDialog(None, "Choose a character file", os.getcwd(), "", wildcard, wx.OPEN | wx.CHANGE_DIR) if openDialog.ShowModal() == wx.ID_OK: self.path = openDialog.GetPath() try: char_file = open(self.path, "r") unpickle_file = cPickle.load(char_file) char_data, char_skills = unpickle_file self.displayCharacter(char_data, char_skills) except IOError: self.importError = wx.MessageDialog(self, "The character file is not available!", "Character Import Error", wx.OK | wx.ICON_ERROR) self.importError.ShowModal() self.importError.Destroy() openDialog.Destroy() ```
Probably you didn't open the file in binary mode when writing and/or reading the pickled data. In this case newline format conversion will occur, which can break the binary data. To open a file in binary mode you have to provide "b" as part of the mode string: ``` char_file = open('pickle.char', 'rb') ```
283,816
<p>I'm working now together with others in a grails project. I have to write some Java-classes. But I need access to an searchable object created with groovy. It seems, that this object has to be placed in the default-package. </p> <p>My question is: <strong>Is there a way to access this object in the default-package from a Java-class in a named package?</strong></p>
[ { "answer_id": 283828, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 8, "selected": true, "text": "<p><a href=\"http://mindprod.com/jgloss/import.html\" rel=\"noreferrer\">You can’t use</a> classes in the default package from a named package.<br />\n(<em>Technically</em> you can, as shown in Sharique Abdullah's <a href=\"https://stackoverflow.com/a/561183/6309\">answer</a> through reflection API, <em>but</em> classes from the unnamed namespace are <strong>not in scope</strong> in an <strong>import declaration</strong>)</p>\n<p>Prior to J2SE 1.4 you could import classes from the default package using a syntax like this:</p>\n<pre><code>import Unfinished;\n</code></pre>\n<p>That's <a href=\"http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4989710\" rel=\"noreferrer\">no longer allowed</a>. So to access a default package class from within a packaged class requires moving the default package class into a package of its own.</p>\n<p>If you have access to the source generated by groovy, some post-processing is needed to move the file into a dedicated package and add this &quot;package&quot; directive at its beginning.</p>\n<hr />\n<p>Update 2014: <a href=\"https://bugs.openjdk.java.net/browse/JDK-6975015\" rel=\"noreferrer\">bug 6975015</a>, for JDK7 and JDK8, describe an even <em>stricter</em> prohibition against import from unnamed package.</p>\n<blockquote>\n<p>The <code>TypeName</code> must be the canonical name of a class type, interface type, enum type, or annotation type.<br />\nThe type must be either a member of a <strong>named package</strong>, or a member of a type whose outermost lexically enclosing type is a member of a <strong>named package</strong>, <strong>or a compile-time error occurs</strong>.</p>\n</blockquote>\n<hr />\n<p><a href=\"https://stackoverflow.com/users/5221149/andreas\">Andreas</a> points out <a href=\"https://stackoverflow.com/questions/283816/how-to-access-java-classes-in-the-default-package/283828#comment98446842_283828\">in the comments</a>:</p>\n<blockquote>\n<blockquote>\n<p>&quot;why is [the default package] there in the first place? design error?&quot;</p>\n</blockquote>\n<p>No, it's deliberate.<br />\n<a href=\"https://docs.oracle.com/javase/specs/jls/se8/html/jls-7.html#jls-7.4.2\" rel=\"noreferrer\">JLS 7.4.2. Unnamed Packages</a> says: &quot;Unnamed packages are provided by the Java SE platform principally for convenience when developing small or temporary applications or when just beginning development&quot;.</p>\n</blockquote>\n" }, { "answer_id": 284047, "author": "Ken Gentle", "author_id": 8709, "author_profile": "https://Stackoverflow.com/users/8709", "pm_score": 2, "selected": false, "text": "<p>You can use packages in the <code>Groovy</code> code, and things will work just fine. </p>\n\n<p>It may mean a minor reorganization of code under <code>grails-app</code> and a little bit of a pain at first, but on a large grails project, it just make sense to organize things in packages. We use the Java standard package naming convention <code>com.foo.&lt;app&gt;.&lt;package&gt;</code>.</p>\n\n<p>Having everything in the default package becomes a hindrance to integration, as you're finding.</p>\n\n<p>Controllers seem to be the one Grails artifact (or artefact) that resists being put in a Java package. Probably I just haven't figured out the <code>Convention</code> for that yet. ;-)</p>\n" }, { "answer_id": 561183, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "<p>In fact, you can. </p>\n\n<p>Using reflections API you can access any class so far. At least I was able to :)</p>\n\n<pre><code>Class fooClass = Class.forName(\"FooBar\");\nMethod fooMethod = fooClass.getMethod(\"fooMethod\", String.class);\n\nString fooReturned = (String)fooMethod.invoke(fooClass.newInstance(), \"I did it\");\n</code></pre>\n" }, { "answer_id": 22368012, "author": "Sean", "author_id": 3127264, "author_profile": "https://Stackoverflow.com/users/3127264", "pm_score": 3, "selected": false, "text": "<p>Use <a href=\"https://code.google.com/p/jarjar/\">jarjar</a> to repackage the jar file with the following rule:</p>\n\n<pre><code>rule * &lt;target package name&gt;.@1\n</code></pre>\n\n<p>All classes in the default package of the source jar file will move to the target package, thus are able to access.</p>\n" }, { "answer_id": 61437652, "author": "Java", "author_id": 11042460, "author_profile": "https://Stackoverflow.com/users/11042460", "pm_score": 1, "selected": false, "text": "<p><em>just to complete the idea:</em></p>\n\n<p><strong>From inside</strong> default-package you can access objects resided in named packages.</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21005/" ]
I'm working now together with others in a grails project. I have to write some Java-classes. But I need access to an searchable object created with groovy. It seems, that this object has to be placed in the default-package. My question is: **Is there a way to access this object in the default-package from a Java-class in a named package?**
[You can’t use](http://mindprod.com/jgloss/import.html) classes in the default package from a named package. (*Technically* you can, as shown in Sharique Abdullah's [answer](https://stackoverflow.com/a/561183/6309) through reflection API, *but* classes from the unnamed namespace are **not in scope** in an **import declaration**) Prior to J2SE 1.4 you could import classes from the default package using a syntax like this: ``` import Unfinished; ``` That's [no longer allowed](http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4989710). So to access a default package class from within a packaged class requires moving the default package class into a package of its own. If you have access to the source generated by groovy, some post-processing is needed to move the file into a dedicated package and add this "package" directive at its beginning. --- Update 2014: [bug 6975015](https://bugs.openjdk.java.net/browse/JDK-6975015), for JDK7 and JDK8, describe an even *stricter* prohibition against import from unnamed package. > > The `TypeName` must be the canonical name of a class type, interface type, enum type, or annotation type. > > The type must be either a member of a **named package**, or a member of a type whose outermost lexically enclosing type is a member of a **named package**, **or a compile-time error occurs**. > > > --- [Andreas](https://stackoverflow.com/users/5221149/andreas) points out [in the comments](https://stackoverflow.com/questions/283816/how-to-access-java-classes-in-the-default-package/283828#comment98446842_283828): > > > > > > "why is [the default package] there in the first place? design error?" > > > > > > > > > No, it's deliberate. > > [JLS 7.4.2. Unnamed Packages](https://docs.oracle.com/javase/specs/jls/se8/html/jls-7.html#jls-7.4.2) says: "Unnamed packages are provided by the Java SE platform principally for convenience when developing small or temporary applications or when just beginning development". > > >
283,821
<p>Does anyone know if there is an implementation of <code>javax.jms.QueueConnectionFactory</code> for WebSphere MQ and where to get it? I Googled it and searched IBM website but couldn't find anything. I don't want to retrieve the connection or factory from Websphere MQ via JNDI, I need my own connection factory.</p>
[ { "answer_id": 283839, "author": "Stroboskop", "author_id": 23428, "author_profile": "https://Stackoverflow.com/users/23428", "pm_score": 4, "selected": true, "text": "<p>I think you need three jars</p>\n\n<pre><code>com.ibm.mq.jar\ncom.ibm.mqbind.jar\ncom.ibm.mqjms.jar\n</code></pre>\n\n<p>You instantiate a <em>MQQueueConnectionFactory</em> and i hope you can take it from there.</p>\n\n<p>And here's more info:\n<a href=\"http://www.ibm.com/developerworks/websphere/techjournal/0502_woolf/0502_woolf.html\" rel=\"noreferrer\">IBMs HOWTO</a></p>\n\n<p>Oh, and MQ can do \"real\" JMS instead of MQ - only the JMS implementation seemed to have problems closing the Channel properly - at least in our environment.</p>\n" }, { "answer_id": 1773151, "author": "T.Rob", "author_id": 214668, "author_profile": "https://Stackoverflow.com/users/214668", "pm_score": 2, "selected": false, "text": "<p>Although Bobby's article referenced in the other response is good, I would want to use a more current version of the JMS classes than from 2005! Most of the development has been in enhancing JMS function and performance. The classes have been simplified and repackaged into fewer jars as well so it's easier to deploy.</p>\n\n<p>I'd recommend going to the WMQ Infocenter for the version of JMS classes you have (6.0 or 7.0) and looking for the Using Java manual. Inside there is a section on environment variables. Make sure you have the jars listed in the CLASSPATH for your specific version. The infocenter is linked from the <a href=\"http://www-01.ibm.com/software/integration/wmq/library/\" rel=\"nofollow noreferrer\">WMQ Library</a> page.</p>\n\n<p>If you can use the latest version, download the <a href=\"http://www-01.ibm.com/support/docview.wss?rs=171&amp;uid=swg24019253&amp;loc=en_US&amp;cs=utf-8&amp;lang=en\" rel=\"nofollow noreferrer\">MQC7 SupportPac</a>. This is the WMQ client code and includes the latest jars.</p>\n\n<p>Once you get the client installed, the sample code can be found in C:\\Program Files\\IBM\\WebSphere MQ\\tools\\jms\\samples\\simple</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283821", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4688/" ]
Does anyone know if there is an implementation of `javax.jms.QueueConnectionFactory` for WebSphere MQ and where to get it? I Googled it and searched IBM website but couldn't find anything. I don't want to retrieve the connection or factory from Websphere MQ via JNDI, I need my own connection factory.
I think you need three jars ``` com.ibm.mq.jar com.ibm.mqbind.jar com.ibm.mqjms.jar ``` You instantiate a *MQQueueConnectionFactory* and i hope you can take it from there. And here's more info: [IBMs HOWTO](http://www.ibm.com/developerworks/websphere/techjournal/0502_woolf/0502_woolf.html) Oh, and MQ can do "real" JMS instead of MQ - only the JMS implementation seemed to have problems closing the Channel properly - at least in our environment.
283,824
<p>I can't figure out why the following wont work, any ideas?? public interface IFieldSimpleItem { }</p> <pre><code>public interface IFieldNormalItem : IFieldSimpleItem { } public class Person { public virtual T Create&lt;T&gt;() where T : IFieldSimpleItem { return default(T); } } public class Bose : Person { public override T Create&lt;T&gt;() where T : IFieldNormalItem //This is where the error is { return default(T); } } </code></pre> <p>The reason why I am doing this is due to the fact that if a developer inherits from Bose, Bose relies on the instance being creating being at least of IFieldNormalItem. Whereas the below only relies on it being IFieldSimpleItem but the above should force it to be at least IFieldNormalItem.</p> <pre><code>public class Person { public virtual IFieldSimpleItem Create() { return null; } } public class Bose : Person { public override IFieldSimpleItem Create() { return null; } } </code></pre> <p>Cheers Anthony</p>
[ { "answer_id": 283837, "author": "Grzenio", "author_id": 5363, "author_profile": "https://Stackoverflow.com/users/5363", "pm_score": 1, "selected": false, "text": "<p>I think the problem is that you override a previously defined method. So effectively you try to change the definition of the method, which is not permitted. Your only choice is to either create a new method, e.g.</p>\n\n<pre><code>public class Bose : Person\n{\n public virtual T CreateNormal&lt;T&gt;()\n where T : IFieldNormalItem //This is where the error is\n {\n return default(T);\n } \n}\n</code></pre>\n\n<p>or require a normal field on the Person class, or do the validation dynamically.</p>\n" }, { "answer_id": 283848, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 0, "selected": false, "text": "<p>What about this:</p>\n\n<pre><code>public interface IFieldNormalItem : IFieldSimpleItem\n{ }\n\npublic class Person&lt;T&gt; where T : IFieldSimpleItem\n{\n public virtual T Create()\n {\n return default(T);\n }\n}\n</code></pre>\n\n<p>Now you can have <code>Person&lt;IFieldSimpleItem&gt;</code> (corresponds to <code>Person</code>) or <code>Person&lt;IFieldNormalItem&gt;</code> (corresponds to <code>Bose</code>).</p>\n" }, { "answer_id": 283850, "author": "Ali Ersöz", "author_id": 4215, "author_profile": "https://Stackoverflow.com/users/4215", "pm_score": 0, "selected": false, "text": "<p>The code below is enough to override. The type T is already indicated as need to be implemented by IFieldSimpleItem in base class Person.</p>\n\n<pre><code>public class Bose : Person\n{\n public override T Create&lt;T&gt;()\n // where T : IFieldNormalItem // You don't need this line.\n {\n return default(T);\n } \n}\n</code></pre>\n\n<p>EDIT : \nI totally got the question wrong so the code above won't solve this case. The only thing you have to do is; not to override the Create method by \"override\" but \"virtual\".</p>\n\n<pre><code>public class Bose : Person\n{\n public virtual T Create&lt;T&gt;()\n where T : IFieldNormalItem\n {\n return default(T);\n } \n}\n</code></pre>\n" }, { "answer_id": 283862, "author": "bruno conde", "author_id": 31136, "author_profile": "https://Stackoverflow.com/users/31136", "pm_score": 1, "selected": false, "text": "<p>It seems you can not change the method's definition but can you make your classes generic instead of the Create Method?</p>\n\n<pre><code>public class Person&lt;T&gt; where T : IFieldSimpleItem\n{\n public virtual T Create()\n {\n return default(T);\n }\n}\n\npublic class Bose&lt;T&gt; : Person&lt;T&gt; where T : IFieldNormalItem\n{\n public override T Create()\n {\n return default(T);\n } \n}\n</code></pre>\n" }, { "answer_id": 283886, "author": "Brent Rockwood", "author_id": 31253, "author_profile": "https://Stackoverflow.com/users/31253", "pm_score": 0, "selected": false, "text": "<p>The simplest example is that this breaks polymorphism. If you had a collection of Person, where one or more of those items is of the type Bose, this would crash as soon as it hits a Bose.</p>\n\n<pre><code>Person[] people;\n[...initialize this somewhere...]\n\nforeach(Person p in people)\n p.Create&lt;IFieldSimpleItem&gt;();\n</code></pre>\n" }, { "answer_id": 286288, "author": "Robert Paulson", "author_id": 14033, "author_profile": "https://Stackoverflow.com/users/14033", "pm_score": 3, "selected": true, "text": "<p>I'm pretty sure you're out of luck as far as using the compiler and generics to save you some runtime checks. You can't override something that doesn't already exist, and you can't have different return types to the same methods. </p>\n\n<p>I can't say I completely understand your motivation, but it has technical merit.</p>\n\n<p>My first attempt was using the base class having a Non-Virtual public interface, and then having another protected virtual method <code>CheckCreatedType</code> that would allow anything in the chain to inspect the type before the base class Create was called.</p>\n\n<pre><code>public class A\n{\n public IFieldSimpleItem Create()\n {\n IFieldSimpleItem created = InternalCreate();\n CheckCreatedType(created);\n return created;\n }\n\n protected virtual IFieldSimpleItem InternalCreate()\n {\n return new SimpleImpl();\n }\n protected virtual void CheckCreatedType(IFieldSimpleItem item)\n { \n // base class doesn't care. compiler guarantees IFieldSimpleItem\n }\n}\npublic class B : A\n{\n protected override IFieldSimpleItem InternalCreate()\n {\n // does not call base class.\n return new NormalImpl();\n }\n protected override void CheckCreatedType(IFieldSimpleItem item)\n {\n base.CheckCreatedType(item);\n if (!(item is IFieldNormalItem))\n throw new Exception(\"I need a normal item.\");\n\n }\n}\n</code></pre>\n\n<p>The following sticks in runtime checking at the base class. The unresolvable issue is you still have to rely on the base class method being called. A misbehaving subclass can break all checks by not calling <code>base.CheckCreatedType(item)</code>.</p>\n\n<p>The alternatives are you hardcode all the checks for all subclasses inside the base class (bad), or otherwise externalize the checking. </p>\n\n<p>Attempt 2: (Sub)Classes register the checks they need.</p>\n\n<pre><code>public class A\n{\n public IFieldSimpleItem Create()\n {\n IFieldSimpleItem created = InternalCreate();\n CheckCreatedType(created);\n return created;\n }\n\n protected virtual IFieldSimpleItem InternalCreate()\n {\n return new SimpleImpl();\n }\n\n private void CheckCreatedType(IFieldSimpleItem item)\n {\n Type inspect = this.GetType();\n bool keepgoing = true;\n while (keepgoing)\n {\n string name = inspect.FullName;\n if (CheckDelegateMethods.ContainsKey(name))\n {\n var checkDelegate = CheckDelegateMethods[name];\n if (!checkDelegate(item))\n throw new Exception(\"failed check\");\n }\n if (inspect == typeof(A))\n {\n keepgoing = false;\n }\n else\n {\n inspect = inspect.BaseType;\n }\n }\n }\n\n private static Dictionary&lt;string,Func&lt;IFieldSimpleItem,bool&gt;&gt; CheckDelegateMethods = new Dictionary&lt;string,Func&lt;IFieldSimpleItem,bool&gt;&gt;();\n protected static void RegisterCheckOnType(string name, Func&lt;IFieldSimpleItem,bool&gt; checkMethod )\n {\n CheckDelegateMethods.Add(name, checkMethod);\n }\n}\npublic class B : A\n{\n static B()\n {\n RegisterCheckOnType(typeof(B).FullName, o =&gt; o is IFieldNormalItem);\n }\n\n protected override IFieldSimpleItem InternalCreate()\n {\n // does not call base class.\n return new NormalImpl();\n }\n}\n</code></pre>\n\n<p>The check is done by the subclass registering a delegate to invoke in base class, but without the base class knowing all the rules upfront. Notice too that it's still the Non-Virtual public interface which allows the base class to check the results before returning them.</p>\n\n<p>I'm assuming that it's a developer error that you're trying to catch. If it's applicable, you can adorn the runtime check method with <code>System.Diagnostics.Conditional(\"DEBUG\")]</code>, allowing the Release version to skip the checks.</p>\n\n<p>My knowledge of generics isn't perfect, so maybe this is unnecessary. However the checks here don't have to be for type alone: this could be adapted for other uses. e.g. the delegate passed in <code>Register..</code> doesn't have to just check the reference is a specific type'</p>\n\n<p>* Note that it's probably not good to create the dictionary on the type name as written above; this working is a little simplistic in order to illustrate the mechanism used.</p>\n" }, { "answer_id": 286348, "author": "Andrew Kennan", "author_id": 22506, "author_profile": "https://Stackoverflow.com/users/22506", "pm_score": 1, "selected": false, "text": "<p>Changing the generic constraint changes the method signature which is not allowed if you're overriding a virtual.</p>\n\n<p>I think you may need to split the Create method into a separate class:</p>\n\n<pre><code>public interface IFieldSimpleItem { }\n\npublic interface IFieldNormalItem : IFieldSimpleItem{ }\n\npublic interface IFieldCreator&lt;TField, TPerson&gt; where TField : IFieldSimpleItem where TPerson : Person\n{\n TField Create(TPerson person);\n}\n\npublic class Person\n{\n}\n\npublic class Bose : Person\n{\n}\n\npublic class PersonFieldCreator : IFieldCreator&lt;IFieldSimpleItem, Person&gt; \n{\n public IFieldSimpleItem Create(Person person) { return null; }\n}\n\npublic class BoseFieldCreator : IFieldCreator&lt;IFieldNormalItem, Bose&gt;\n{\n public IFieldNormalItem Create(Bose person) { return null; }\n}\n</code></pre>\n" }, { "answer_id": 286789, "author": "Buu", "author_id": 17815, "author_profile": "https://Stackoverflow.com/users/17815", "pm_score": 2, "selected": false, "text": "<p>That's not allowed because it violates Liskov Substitution Principle. </p>\n\n<p>Let's say you have another interface:</p>\n\n<pre><code>public interface IFieldSuperItem : IFieldSimpleItem\n</code></pre>\n\n<p>You then might do this </p>\n\n<pre><code>Person p = new Boss();\np.Create&lt;IFieldSuperItem&gt;();\n</code></pre>\n\n<p>The call in second line, while compatible with the definition of Create in Person but obviously not compatible to that defined in Boss (which only work with IFieldNormalItem and its subclass). </p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30572/" ]
I can't figure out why the following wont work, any ideas?? public interface IFieldSimpleItem { } ``` public interface IFieldNormalItem : IFieldSimpleItem { } public class Person { public virtual T Create<T>() where T : IFieldSimpleItem { return default(T); } } public class Bose : Person { public override T Create<T>() where T : IFieldNormalItem //This is where the error is { return default(T); } } ``` The reason why I am doing this is due to the fact that if a developer inherits from Bose, Bose relies on the instance being creating being at least of IFieldNormalItem. Whereas the below only relies on it being IFieldSimpleItem but the above should force it to be at least IFieldNormalItem. ``` public class Person { public virtual IFieldSimpleItem Create() { return null; } } public class Bose : Person { public override IFieldSimpleItem Create() { return null; } } ``` Cheers Anthony
I'm pretty sure you're out of luck as far as using the compiler and generics to save you some runtime checks. You can't override something that doesn't already exist, and you can't have different return types to the same methods. I can't say I completely understand your motivation, but it has technical merit. My first attempt was using the base class having a Non-Virtual public interface, and then having another protected virtual method `CheckCreatedType` that would allow anything in the chain to inspect the type before the base class Create was called. ``` public class A { public IFieldSimpleItem Create() { IFieldSimpleItem created = InternalCreate(); CheckCreatedType(created); return created; } protected virtual IFieldSimpleItem InternalCreate() { return new SimpleImpl(); } protected virtual void CheckCreatedType(IFieldSimpleItem item) { // base class doesn't care. compiler guarantees IFieldSimpleItem } } public class B : A { protected override IFieldSimpleItem InternalCreate() { // does not call base class. return new NormalImpl(); } protected override void CheckCreatedType(IFieldSimpleItem item) { base.CheckCreatedType(item); if (!(item is IFieldNormalItem)) throw new Exception("I need a normal item."); } } ``` The following sticks in runtime checking at the base class. The unresolvable issue is you still have to rely on the base class method being called. A misbehaving subclass can break all checks by not calling `base.CheckCreatedType(item)`. The alternatives are you hardcode all the checks for all subclasses inside the base class (bad), or otherwise externalize the checking. Attempt 2: (Sub)Classes register the checks they need. ``` public class A { public IFieldSimpleItem Create() { IFieldSimpleItem created = InternalCreate(); CheckCreatedType(created); return created; } protected virtual IFieldSimpleItem InternalCreate() { return new SimpleImpl(); } private void CheckCreatedType(IFieldSimpleItem item) { Type inspect = this.GetType(); bool keepgoing = true; while (keepgoing) { string name = inspect.FullName; if (CheckDelegateMethods.ContainsKey(name)) { var checkDelegate = CheckDelegateMethods[name]; if (!checkDelegate(item)) throw new Exception("failed check"); } if (inspect == typeof(A)) { keepgoing = false; } else { inspect = inspect.BaseType; } } } private static Dictionary<string,Func<IFieldSimpleItem,bool>> CheckDelegateMethods = new Dictionary<string,Func<IFieldSimpleItem,bool>>(); protected static void RegisterCheckOnType(string name, Func<IFieldSimpleItem,bool> checkMethod ) { CheckDelegateMethods.Add(name, checkMethod); } } public class B : A { static B() { RegisterCheckOnType(typeof(B).FullName, o => o is IFieldNormalItem); } protected override IFieldSimpleItem InternalCreate() { // does not call base class. return new NormalImpl(); } } ``` The check is done by the subclass registering a delegate to invoke in base class, but without the base class knowing all the rules upfront. Notice too that it's still the Non-Virtual public interface which allows the base class to check the results before returning them. I'm assuming that it's a developer error that you're trying to catch. If it's applicable, you can adorn the runtime check method with `System.Diagnostics.Conditional("DEBUG")]`, allowing the Release version to skip the checks. My knowledge of generics isn't perfect, so maybe this is unnecessary. However the checks here don't have to be for type alone: this could be adapted for other uses. e.g. the delegate passed in `Register..` doesn't have to just check the reference is a specific type' \* Note that it's probably not good to create the dictionary on the type name as written above; this working is a little simplistic in order to illustrate the mechanism used.
283,835
<p>I am trying to establish a basic .NET Remoting communication between 2x 64bit windows machines. If Machine1 is acting as client and Machine2 as server, then everything works fine. The other way around the following exception occurs:</p> <p>System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it 172.16.7.44:6666</p> <p>The server code:</p> <pre><code>TcpChannel channel = new TcpChannel(6666); ChannelServices.RegisterChannel(channel); RemotingConfiguration.RegisterWellKnownServiceType( typeof(MyRemotableObject),"HelloWorld",WellKnownObjectMode.Singleton); </code></pre> <p>The client code:</p> <pre><code>TcpChannel chan = new TcpChannel(); ChannelServices.RegisterChannel(chan); // Create an instance of the remote object remoteObject = (MyRemotableObject)Activator.GetObject( typeof(MyRemotableObject), "tcp://172.16.7.44:6666/HelloWorld"); </code></pre> <p>Any idea whats wrong with my code?</p>
[ { "answer_id": 283843, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 4, "selected": false, "text": "<p>Windows Firewall? (Question author says this is not it.)</p>\n\n<p>To track down connection issues the standard approach applies (apply in any order):</p>\n\n<ul>\n<li>ping the machine</li>\n<li>double check if some process really is listening in port 6666 (<code>netstat -an</code>)</li>\n<li>telnet the machine on port 6666</li>\n<li>try to use a different service on the machine.</li>\n<li>check if some configuration upsets the server process listening on 6666 and causes it to refuse you. (don't know if that is possible with .NET remoting)</li>\n<li>watch communication with the machine using a packet sniffer (Packetyzer, for example) to find out what's going on at the TCP/IP level.</li>\n<li>maybe active network infrastructure components between server and client (layer-3 switches, firewalls, NAT-routers, whatever) are interfering</li>\n</ul>\n" }, { "answer_id": 283861, "author": "stephbu", "author_id": 12702, "author_profile": "https://Stackoverflow.com/users/12702", "pm_score": 4, "selected": true, "text": "<p>Assuming that the same binaries/configs work one-way but not the other would tell me something amiss in the networking side of the house to start with. </p>\n\n<ul>\n<li>You're using IP addresses - double check the bound addresses on target machine against config/code with IPCONFIG /ALL. </li>\n<li>Does the \"server\" machine have multiple NICs? Is the service bound to one NIC not both for example?</li>\n<li>pinging the server will tell you that ICMP is routable between machines - can you create session orient requests e.g. opening UNC paths on the server from the client. </li>\n</ul>\n\n<p>Beyond Firewall, the only other connection refused experiences I've had have been:</p>\n\n<ul>\n<li>Name Resolution - preexisting host entry was wrong. Shouldn't be an issue here though.</li>\n<li>IPSEC oriented - different policies between machines prevented one from accepting inbound connections from the other. Possible if you work in a corporate secured environment. If you do work in an IPSec environment check for simple stuff like clocks, valid machine certs. All of these can prevent IPSec sessions from being established.</li>\n<li>stress issue - IP stack exhausted free TCP control blocks through misconfiguration of a server. Equally sounds like you can't get any connection going - probably not the issue.</li>\n</ul>\n\n<p>I'd start with Firewall 1st - either by setting policy to exempt inbound requests on that socket, trust all sockets from the source IP, or by disabling it all-together. (personally the latter is quick and dirty as a test, but I would do the former in a production environment)</p>\n\n<p>Beyond that event logs, audit trail if you do have firewall enabled but punched through. Netmon etc. all become your friends.</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283835", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35061/" ]
I am trying to establish a basic .NET Remoting communication between 2x 64bit windows machines. If Machine1 is acting as client and Machine2 as server, then everything works fine. The other way around the following exception occurs: System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it 172.16.7.44:6666 The server code: ``` TcpChannel channel = new TcpChannel(6666); ChannelServices.RegisterChannel(channel); RemotingConfiguration.RegisterWellKnownServiceType( typeof(MyRemotableObject),"HelloWorld",WellKnownObjectMode.Singleton); ``` The client code: ``` TcpChannel chan = new TcpChannel(); ChannelServices.RegisterChannel(chan); // Create an instance of the remote object remoteObject = (MyRemotableObject)Activator.GetObject( typeof(MyRemotableObject), "tcp://172.16.7.44:6666/HelloWorld"); ``` Any idea whats wrong with my code?
Assuming that the same binaries/configs work one-way but not the other would tell me something amiss in the networking side of the house to start with. * You're using IP addresses - double check the bound addresses on target machine against config/code with IPCONFIG /ALL. * Does the "server" machine have multiple NICs? Is the service bound to one NIC not both for example? * pinging the server will tell you that ICMP is routable between machines - can you create session orient requests e.g. opening UNC paths on the server from the client. Beyond Firewall, the only other connection refused experiences I've had have been: * Name Resolution - preexisting host entry was wrong. Shouldn't be an issue here though. * IPSEC oriented - different policies between machines prevented one from accepting inbound connections from the other. Possible if you work in a corporate secured environment. If you do work in an IPSec environment check for simple stuff like clocks, valid machine certs. All of these can prevent IPSec sessions from being established. * stress issue - IP stack exhausted free TCP control blocks through misconfiguration of a server. Equally sounds like you can't get any connection going - probably not the issue. I'd start with Firewall 1st - either by setting policy to exempt inbound requests on that socket, trust all sockets from the source IP, or by disabling it all-together. (personally the latter is quick and dirty as a test, but I would do the former in a production environment) Beyond that event logs, audit trail if you do have firewall enabled but punched through. Netmon etc. all become your friends.
283,858
<p>I have an XML input file and I'm trying to output the result of a call like: </p> <pre><code>&lt;xsl:value-of select="Some/Value"/&gt; </code></pre> <p>into an attribute. </p> <pre><code>&lt;Output Attribute="Value should be put here"/&gt; </code></pre> <p>My problem is, since I'm outputting XML, the XSL processor won't allow me to write: </p> <pre><code>&lt;Output Attribute="&lt;xsl:value-of select="Some/Value"/&gt;"&gt; </code></pre> <p>How do you accomplish this?</p>
[ { "answer_id": 283868, "author": "Phil Ross", "author_id": 5981, "author_profile": "https://Stackoverflow.com/users/5981", "pm_score": 5, "selected": false, "text": "<p>You can use an xsl:attribute element:</p>\n\n<pre><code>&lt;Output&gt;\n &lt;xsl:attribute name=\"Attribute\"&gt;\n &lt;xsl:value-of select=\"Some/Value\"/&gt;\n &lt;/xsl:attribute&gt;\n&lt;/Output&gt;\n</code></pre>\n" }, { "answer_id": 283877, "author": "Danko Durbić", "author_id": 19241, "author_profile": "https://Stackoverflow.com/users/19241", "pm_score": 7, "selected": true, "text": "<p>The easiest way is to use <a href=\"http://www.w3.org/TR/xslt.html#dt-attribute-value-template\" rel=\"noreferrer\">attribute value templates</a>, like this:</p>\n\n<pre><code>&lt;Output Attribute=\"{Some/Value}\"/&gt;\n</code></pre>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/143/" ]
I have an XML input file and I'm trying to output the result of a call like: ``` <xsl:value-of select="Some/Value"/> ``` into an attribute. ``` <Output Attribute="Value should be put here"/> ``` My problem is, since I'm outputting XML, the XSL processor won't allow me to write: ``` <Output Attribute="<xsl:value-of select="Some/Value"/>"> ``` How do you accomplish this?
The easiest way is to use [attribute value templates](http://www.w3.org/TR/xslt.html#dt-attribute-value-template), like this: ``` <Output Attribute="{Some/Value}"/> ```
283,869
<p>I'm trying to add a new node to an jQuery <a href="http://news.kg/wp-content/uploads/tree/" rel="nofollow noreferrer">SimpleTree</a>, but all I seem to be able to get is "sTC.addNode is not a function"... </p> <pre><code>var simpleTreeCollection = $('.simpleTree').simpleTree({ animate:true, drag:false, autoclose: false, afterClick:function(node){}, afterDblClick:function(node){}, beforeMove:function (destination, source, pos){}, afterMove:function(destination, source, pos){}, afterAjax:function() {}, afterContextMenu:function(node){} }); simpleTreeCollection.addNode('test', 'test'); </code></pre> <p>Any suggestions what I might be doing wrong? Is there even the possibility to add a node?</p>
[ { "answer_id": 283914, "author": "redsquare", "author_id": 6440, "author_profile": "https://Stackoverflow.com/users/6440", "pm_score": 1, "selected": false, "text": "<p>hmm tricky one this and I have to say I dont like the plugin as it uses numerics as id's and w3c states \"The attribute's value must begin with a letter in the range A-Z or a-z and may be followed by letters.......\"</p>\n\n<p>However to get you working u need to select one of the nodes first in order to add to it like this</p>\n\n<pre><code> //Select first child node in tree\n $('#2').click();\n //Add new node to selected node\n simpleTreeCollection.get(0).addNode(1,'A New Node')\n</code></pre>\n" }, { "answer_id": 286442, "author": "redsquare", "author_id": 6440, "author_profile": "https://Stackoverflow.com/users/6440", "pm_score": 0, "selected": false, "text": "<p>FYI the above code works in the firebug console on their demo page. On your tree ake sure you use a correct selector to highlight the node</p>\n" }, { "answer_id": 289739, "author": "redsquare", "author_id": 6440, "author_profile": "https://Stackoverflow.com/users/6440", "pm_score": 2, "selected": true, "text": "<p>Maybe take a look at <a href=\"http://www.jstree.com/jsTree/examples/\" rel=\"nofollow noreferrer\">jsTree</a> </p>\n" }, { "answer_id": 970974, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I have solved it by editing the addNode funcion. I commented the temp_node.remove(); and added dragNode_destination.after(dragNode_source);</p>\n\n<p>Just like that:</p>\n\n<pre><code> TREE.addNode = function(id, text, callback)\n {\n var temp_node = $('&lt;li&gt;&lt;ul&gt;&lt;li id=\"'+id+'\"&gt;&lt;span&gt;'+text+'&lt;/span&gt;&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;');\n TREE.setTreeNodes(temp_node);\n dragNode_destination = TREE.getSelected();\n dragNode_source = $('.doc-last',temp_node);\n TREE.moveNodeToFolder(dragNode_destination);\n// temp_node.remove();\n dragNode_destination.after(dragNode_source);\n if(typeof(callback) == 'function')\n {\n callback(dragNode_destination, dragNode_source);\n }\n };\n</code></pre>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283869", "https://Stackoverflow.com", "https://Stackoverflow.com/users/999/" ]
I'm trying to add a new node to an jQuery [SimpleTree](http://news.kg/wp-content/uploads/tree/), but all I seem to be able to get is "sTC.addNode is not a function"... ``` var simpleTreeCollection = $('.simpleTree').simpleTree({ animate:true, drag:false, autoclose: false, afterClick:function(node){}, afterDblClick:function(node){}, beforeMove:function (destination, source, pos){}, afterMove:function(destination, source, pos){}, afterAjax:function() {}, afterContextMenu:function(node){} }); simpleTreeCollection.addNode('test', 'test'); ``` Any suggestions what I might be doing wrong? Is there even the possibility to add a node?
Maybe take a look at [jsTree](http://www.jstree.com/jsTree/examples/)
283,891
<p>How can I access the WCF Service through JavaScript? My problem is, I have to access the operation contracts through the JavaScript (my website is not Ajax enabled).<br> Previously for calling .asmx web services, I am using the following code snippet</p> <pre><code>var xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); xmlHttp.open("POST", URL, false); xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xmlHttp.send(payload); xmlData = xmlHttp.responseXML; </code></pre> <p>where url is my webservice location.</p> <p>Now if I am trying to consume the wcf service in the same manner, I am not able to. Many techies are explaining through AJAX approach, I need an approach without AJAX.</p>
[ { "answer_id": 283921, "author": "user32415", "author_id": 32415, "author_profile": "https://Stackoverflow.com/users/32415", "pm_score": 2, "selected": false, "text": "<p>By using XMLHTTP you ARE using ajax.</p>\n\n<p>There's a full example here:</p>\n\n<p><a href=\"http://www.west-wind.com/weblog/posts/324917.aspx\" rel=\"nofollow noreferrer\">jQuery AJAX calls to a WCF REST Service</a></p>\n" }, { "answer_id": 284409, "author": "user32415", "author_id": 32415, "author_profile": "https://Stackoverflow.com/users/32415", "pm_score": 0, "selected": false, "text": "<p>Look at the code on the link that I have sent before. Sure U can implement it yourself but it well be a huge effort duplication.</p>\n\n<p>First, your WCF service must have:</p>\n\n<pre><code>[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]\n</code></pre>\n\n<p>Then, on the javascript side, change the </p>\n\n<pre><code>\"Content-Type\", \"application/x-www-form-urlencoded\"\n</code></pre>\n\n<p>To</p>\n\n<pre><code>\"Content-Type\", \"application/json\"\n</code></pre>\n\n<p>Remember that the response will be json formated, so having a parser could be useful.</p>\n\n<p>Why you don't want to use external libs?</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How can I access the WCF Service through JavaScript? My problem is, I have to access the operation contracts through the JavaScript (my website is not Ajax enabled). Previously for calling .asmx web services, I am using the following code snippet ``` var xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); xmlHttp.open("POST", URL, false); xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xmlHttp.send(payload); xmlData = xmlHttp.responseXML; ``` where url is my webservice location. Now if I am trying to consume the wcf service in the same manner, I am not able to. Many techies are explaining through AJAX approach, I need an approach without AJAX.
By using XMLHTTP you ARE using ajax. There's a full example here: [jQuery AJAX calls to a WCF REST Service](http://www.west-wind.com/weblog/posts/324917.aspx)
283,893
<p>To support multiple platforms in C/C++, one would use the preprocessor to enable conditional compiles. E.g.,</p> <pre><code>#ifdef _WIN32 #include &lt;windows.h&gt; #endif </code></pre> <p>How can you do this in Ada? Does Ada have a preprocessor?</p>
[ { "answer_id": 283920, "author": "David Allan Finch", "author_id": 27417, "author_profile": "https://Stackoverflow.com/users/27417", "pm_score": 2, "selected": false, "text": "<p>No but the CPP preprocessor or m4 can be called on any file on the command line or using a building tool like make or ant. I suggest calling your .ada file something else. I have done this for some time on java files. I call the java file .m4 and use a make rule to create the .java and then build it in the normal way.</p>\n\n<p>I hope that helps.</p>\n" }, { "answer_id": 300192, "author": "Marc C", "author_id": 38706, "author_profile": "https://Stackoverflow.com/users/38706", "pm_score": 3, "selected": false, "text": "<p>AdaCore provides the <a href=\"https://gcc.gnu.org/onlinedocs/gnat_ugn/Preprocessing-with-gnatprep.html\" rel=\"nofollow noreferrer\">gnatprep</a> preprocessor, which is specialized for Ada. They state that gnatprep \"does not depend on any special GNAT features\", so it sounds as though it should work with non-GNAT Ada compilers. Their User Guide also provides some conditional compilation <a href=\"https://gcc.gnu.org/onlinedocs/gnat_ugn/Conditional-Compilation.html#Conditional-Compilation\" rel=\"nofollow noreferrer\">advice</a>.</p>\n\n<p>I have been on a project where m4 was used as well, with the Ada spec and body files suffixed as \".m4s\" and \".m4b\", respectively.</p>\n\n<p>My preference is really to avoid preprocessing altogether, and just use specialized bodies, setting up CM and the build process to manage them.</p>\n" }, { "answer_id": 305371, "author": "Louis Brandy", "author_id": 2089740, "author_profile": "https://Stackoverflow.com/users/2089740", "pm_score": 4, "selected": true, "text": "<p>The answer to your question is no, Ada does not have a pre-processor that is built into the language. That means each compiler may or may not have one and there is not \"uniform\" syntax for pre-processing and things like conditional compilation. This was intentional: it's considered \"harmful\" to the Ada ethos.</p>\n\n<p>There are almost always ways around a lack of a preprocessor but often times the solution can be a little cumbersome. For example, you can declare the platform specific functions as 'separate' and then use build-tools to compile the correct one (either a project system, using pragma body replacement, or a very simple directory system... put all the windows files in /windows/ and all the linux files in /linux/ and include the appropriate directory for the platform).</p>\n\n<p>All that being said, GNAT realized that sometimes you need a preprocessor and has created gnatprep. It should work regardless of the compiler (but you will need to insert it into your build process). Similarly, for simple things (like conditional compilation) you can probably just use the c pre-processor or even roll your own very simple one.</p>\n" }, { "answer_id": 305426, "author": "T.E.D.", "author_id": 29639, "author_profile": "https://Stackoverflow.com/users/29639", "pm_score": 0, "selected": false, "text": "<p>No, it does not. </p>\n\n<p>If you really want one, there are ways to get one (Use C's, use a stand-alone one, etc.) However I'd argue against it. It was a purposeful design decision to not have one. The whole idea of a preprocessor is very un-Ada.</p>\n\n<p>Most of what C's preprocessor is used for can be accomplished in Ada in other more reliable ways. The only major exception is in making minor changes to a source file for cross-platform support. Given how much this gets abused in a typical cross-platform C program, I'm still happy there's no support for it in Ada. Very few C/C++ developers can control themselves enough to keep the changes \"minor\". The result may work, but is often nearly impossible for a human to read. </p>\n\n<p>The typical Ada way to accomplish this would be to put the different code in different files and use your build system to somehow choose between them at compile time. Make is plenty powerful enough to help you do this.</p>\n" }, { "answer_id": 2613634, "author": "Daniel Miller", "author_id": 313487, "author_profile": "https://Stackoverflow.com/users/313487", "pm_score": 2, "selected": false, "text": "<p>Some old Ada1983-era compilers have a package called a.app that utilized a #-prefixed subset of Ada (interpreted at build-time) as a preprocessing language for generating Ada (to be then translated to machine code at compile-time). Rational's Verdix Ada Development System (VADS) appears to be the progenitor of a.app among several Ada compilers. Sun Microsystems, for example, derived the Ada SPARCompiler from VADS and thus also had a.app. This is not unlike the use of PL/I as the preprocessor of PL/I, which IBM did.</p>\n\n<p>Chapter 2 is some documentation of what a.app looks like: <a href=\"http://dlc.sun.com/pdf/802-3641/802-3641.pdf\" rel=\"nofollow noreferrer\">http://dlc.sun.com/pdf/802-3641/802-3641.pdf</a></p>\n" }, { "answer_id": 8264429, "author": "Rego", "author_id": 1005540, "author_profile": "https://Stackoverflow.com/users/1005540", "pm_score": 2, "selected": false, "text": "<p>Yes, it has. </p>\n\n<p>If you are using GNAT compiler, you can use <code>gnatprep</code> for doing the preprocessing, or if you use GNAT Programming Studio you can configure your project file to define some conditional compilation switches like</p>\n\n<pre><code>#if SOMESWITCH then\n-- Your code here is executed only if the switch SOMESWITCH is active in your build configuration\n#end if;\n</code></pre>\n\n<p>In this case you can use <code>gnatmake</code> or <code>gprbuild</code> so you don't have to run <code>gnatprep</code> by hand. </p>\n\n<p>That's very useful, for example, when you need to compile the same code for several different OS's using even different cross-compilers.</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283893", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14069/" ]
To support multiple platforms in C/C++, one would use the preprocessor to enable conditional compiles. E.g., ``` #ifdef _WIN32 #include <windows.h> #endif ``` How can you do this in Ada? Does Ada have a preprocessor?
The answer to your question is no, Ada does not have a pre-processor that is built into the language. That means each compiler may or may not have one and there is not "uniform" syntax for pre-processing and things like conditional compilation. This was intentional: it's considered "harmful" to the Ada ethos. There are almost always ways around a lack of a preprocessor but often times the solution can be a little cumbersome. For example, you can declare the platform specific functions as 'separate' and then use build-tools to compile the correct one (either a project system, using pragma body replacement, or a very simple directory system... put all the windows files in /windows/ and all the linux files in /linux/ and include the appropriate directory for the platform). All that being said, GNAT realized that sometimes you need a preprocessor and has created gnatprep. It should work regardless of the compiler (but you will need to insert it into your build process). Similarly, for simple things (like conditional compilation) you can probably just use the c pre-processor or even roll your own very simple one.
283,894
<p>Have you ever tried this feedback calling an external zip.py script to work? My CGITB does not show any error messages. It simply did not invoke external .py script to work. It simply skipped over to gush. I should be grateful if you can assist me in making this zip.py callable in feedback.py. </p> <p>Regards. David </p> <pre><code>#********************************************************************** # Description: # Zips the contents of a folder. # Parameters: # 0 - Input folder. # 1 - Output zip file. It is assumed that the user added the .zip # extension. #********************************************************************** # Import modules and create the geoprocessor # import sys, zipfile, arcgisscripting, os, traceback gp = arcgisscripting.create() # Function for zipping files. If keep is true, the folder, along with # all its contents, will be written to the zip file. If false, only # the contents of the input folder will be written to the zip file - # the input folder name will not appear in the zip file. # def zipws(path, zip, keep): path = os.path.normpath(path) # os.walk visits every subdirectory, returning a 3-tuple # of directory name, subdirectories in it, and filenames # in it. # for (dirpath, dirnames, filenames) in os.walk(path): # Iterate over every filename # for file in filenames: # Ignore .lock files # if not file.endswith('.lock'): gp.AddMessage("Adding %s..." % os.path.join(path, dirpath, file)) try: if keep: zip.write(os.path.join(dirpath, file), os.path.join(os.path.basename(path), os.path.join(dirpath, file)[len(path)+len(os.sep):])) else: zip.write(os.path.join(dirpath, file), os.path.join(dirpath[len(path):], file)) except Exception, e: gp.AddWarning(" Error adding %s: %s" % (file, e)) return None if __name__ == '__main__': try: # Get the tool parameter values # infolder = gp.GetParameterAsText(0) outfile = gp.GetParameterAsText(1) # Create the zip file for writing compressed data. In some rare # instances, the ZIP_DEFLATED constant may be unavailable and # the ZIP_STORED constant is used instead. When ZIP_STORED is # used, the zip file does not contain compressed data, resulting # in large zip files. # try: zip = zipfile.ZipFile(outfile, 'w', zipfile.ZIP_DEFLATED) zipws(infolder, zip, True) zip.close() except RuntimeError: # Delete zip file if exists # if os.path.exists(outfile): os.unlink(outfile) zip = zipfile.ZipFile(outfile, 'w', zipfile.ZIP_STORED) zipws(infolder, zip, True) zip.close() gp.AddWarning(" Unable to compress zip file contents.") gp.AddMessage("Zip file created successfully") except: # Return any python specific errors as well as any errors from the geoprocessor # tb = sys.exc_info()[2] tbinfo = traceback.format_tb(tb)[0] pymsg = "PYTHON ERRORS:\nTraceback Info:\n" + tbinfo + "\nError Info:\n " + str(sys.exc_type) + ": " + str(sys.exc_value) + "\n" gp.AddError(pymsg) msgs = "GP ERRORS:\n" + gp.GetMessages(2) + "\n" gp.AddError(msgs) </code></pre>
[ { "answer_id": 284199, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 1, "selected": false, "text": "<ul>\n<li><p><code>zip()</code> is a built-in function in Python. Therefore it is a bad practice to use <code>zip</code> as a variable name. <code>zip_</code> can be used instead of.</p></li>\n<li><p><code>execfile()</code> function reads and executes a Python script.</p></li>\n<li><p>It is probably that you actually need just <code>import zip_</code> in feedback.py instead of <code>execfile()</code>.</p></li>\n</ul>\n" }, { "answer_id": 284448, "author": "UberJumper", "author_id": 34395, "author_profile": "https://Stackoverflow.com/users/34395", "pm_score": 0, "selected": false, "text": "<p>Yay ArcGIS.</p>\n\n<p>Just to clarify how are you trying to call this script using popen, can you post some code?</p>\n\n<p>If your invoking this script via another script in the ArcGIS environment, then the thing is, when you use Popen the script wont be invoked within the ArcGIS environment, instead it will be invoked within windows. So you will loose all real control over it.</p>\n\n<p>Also just another ArcGIS comment you never initalize a license for the geoprocessor.</p>\n\n<p>My suggestion refactor your code, into a module function that simply attempts to zip the files, if it fails print the message out to ArcGIS.</p>\n\n<p>If you want post how you are calling it, and how this is being run.</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283894", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36900/" ]
Have you ever tried this feedback calling an external zip.py script to work? My CGITB does not show any error messages. It simply did not invoke external .py script to work. It simply skipped over to gush. I should be grateful if you can assist me in making this zip.py callable in feedback.py. Regards. David ``` #********************************************************************** # Description: # Zips the contents of a folder. # Parameters: # 0 - Input folder. # 1 - Output zip file. It is assumed that the user added the .zip # extension. #********************************************************************** # Import modules and create the geoprocessor # import sys, zipfile, arcgisscripting, os, traceback gp = arcgisscripting.create() # Function for zipping files. If keep is true, the folder, along with # all its contents, will be written to the zip file. If false, only # the contents of the input folder will be written to the zip file - # the input folder name will not appear in the zip file. # def zipws(path, zip, keep): path = os.path.normpath(path) # os.walk visits every subdirectory, returning a 3-tuple # of directory name, subdirectories in it, and filenames # in it. # for (dirpath, dirnames, filenames) in os.walk(path): # Iterate over every filename # for file in filenames: # Ignore .lock files # if not file.endswith('.lock'): gp.AddMessage("Adding %s..." % os.path.join(path, dirpath, file)) try: if keep: zip.write(os.path.join(dirpath, file), os.path.join(os.path.basename(path), os.path.join(dirpath, file)[len(path)+len(os.sep):])) else: zip.write(os.path.join(dirpath, file), os.path.join(dirpath[len(path):], file)) except Exception, e: gp.AddWarning(" Error adding %s: %s" % (file, e)) return None if __name__ == '__main__': try: # Get the tool parameter values # infolder = gp.GetParameterAsText(0) outfile = gp.GetParameterAsText(1) # Create the zip file for writing compressed data. In some rare # instances, the ZIP_DEFLATED constant may be unavailable and # the ZIP_STORED constant is used instead. When ZIP_STORED is # used, the zip file does not contain compressed data, resulting # in large zip files. # try: zip = zipfile.ZipFile(outfile, 'w', zipfile.ZIP_DEFLATED) zipws(infolder, zip, True) zip.close() except RuntimeError: # Delete zip file if exists # if os.path.exists(outfile): os.unlink(outfile) zip = zipfile.ZipFile(outfile, 'w', zipfile.ZIP_STORED) zipws(infolder, zip, True) zip.close() gp.AddWarning(" Unable to compress zip file contents.") gp.AddMessage("Zip file created successfully") except: # Return any python specific errors as well as any errors from the geoprocessor # tb = sys.exc_info()[2] tbinfo = traceback.format_tb(tb)[0] pymsg = "PYTHON ERRORS:\nTraceback Info:\n" + tbinfo + "\nError Info:\n " + str(sys.exc_type) + ": " + str(sys.exc_value) + "\n" gp.AddError(pymsg) msgs = "GP ERRORS:\n" + gp.GetMessages(2) + "\n" gp.AddError(msgs) ```
* `zip()` is a built-in function in Python. Therefore it is a bad practice to use `zip` as a variable name. `zip_` can be used instead of. * `execfile()` function reads and executes a Python script. * It is probably that you actually need just `import zip_` in feedback.py instead of `execfile()`.
283,925
<p>Ok so I have an abstract base class called Product, a KitItem class that inherits Product and a PackageKitItem class that inherits KitItem. ie.</p> <pre><code>Product KitItem : Product PackageKitItem : KitItem </code></pre> <p>I have my KitItems loaded and I need to load up a collection of PackageKitItems which are, effectively, shallow copies of KitItems.</p> <p>Currently we are doing what feels to me a hacky shallow copy in the Product constructor like so:</p> <pre><code>public Product(Product product) { FieldInfo[] fields = product.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); // copy each value over to 'this' foreach (FieldInfo fi in fields) fi.SetValue(this, fi.GetValue(product)); } </code></pre> <p>I've tried setting up a copy on KitItem like so:</p> <pre><code>public KitItem ShallowCopy() { return (KitItem)this.MemberwiseClone(); } </code></pre> <p>and calling it thus:</p> <pre><code>PackageKitItem tempPackKitItem = (PackageKitItem)packKitItem.ShallowCopy(); </code></pre> <p>but I get an invalid cast. I'm looking for ideas for the best way to accomplish this.</p>
[ { "answer_id": 284021, "author": "Leonardo Herrera", "author_id": 7841, "author_profile": "https://Stackoverflow.com/users/7841", "pm_score": 0, "selected": false, "text": "<p>In your Product constructor you are already doing some form of shallow copy, aren't you? If you haven't overwritten your constructor, then you should be able to just create a new PackageKitItem that receives a KitItem as its parameter.</p>\n\n<pre><code>PackageKitItem tempPackKitItem = new tempPackKitItem(kitItem);\n</code></pre>\n\n<p>Maybe I just misunderstood your question.</p>\n" }, { "answer_id": 284034, "author": "RS Conley", "author_id": 7890, "author_profile": "https://Stackoverflow.com/users/7890", "pm_score": 1, "selected": false, "text": "<p>Strangely I didn't get an error doing this on Visual Studio 2008. I am posting the code so you can see what I am missing or what I am assuming wrong. My guess is that the problem is in one of the class members that you didn't post. </p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Data;\nusing System.Drawing;\nusing System.Linq;\nusing System.Text;\nusing System.Windows.Forms;\nusing System.Reflection;\n\nnamespace WindowsFormsApplication1\n{\n public partial class Form1 : Form\n {\n public Form1()\n {\n InitializeComponent();\n }\n\n private void button1_Click(object sender, EventArgs e)\n {\n PackageKitItem PKI = new PackageKitItem();\n PKI.ID = 1;\n PKI.KitName = \"2\";\n PKI.Name = \"3\";\n PKI.Package = 4;\n\n PackageKitItem tempPackKitItem = (PackageKitItem)PKI.ShallowCopy();\n\n }\n }\n\n}\n\npublic class Product\n{\n public int ID;\n public string Name;\n\n public Product()\n {\n }\n\n public Product(Product product)\n {\n FieldInfo[] fields = product.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);\n\n // copy each value over to 'this'\n foreach (FieldInfo fi in fields)\n fi.SetValue(this, fi.GetValue(product));\n }\n\n\n}\n\npublic class KitItem:Product\n{\n public string KitName;\n public KitItem ShallowCopy()\n {\n return (KitItem)this.MemberwiseClone();\n }\n\n}\n\npublic class PackageKitItem : KitItem\n{\n public int Package;\n\n}\n</code></pre>\n" }, { "answer_id": 292973, "author": "TAG", "author_id": 36400, "author_profile": "https://Stackoverflow.com/users/36400", "pm_score": 3, "selected": true, "text": "<p>The problem you have is that since ShallowCopy() is a member of KitItem, MemberwiseClone() is just copying the KitItem fields and returning a KitItem even if the original object is a PackageKitItem.</p>\n\n<p>I think what you have to do in this circumstance add to KitItem:</p>\n\n<pre><code>public virtual KitItem ShallowCopy() \n{ \n return (KitItem) this.MemberwiseClone(); \n}\n</code></pre>\n\n<p>and in PackageKitItem:</p>\n\n<pre><code>public override KitItem ShallowCopy() \n{ \n return (PackageKitItem) this.MemberwiseClone(); \n}\n</code></pre>\n\n<p>Thus you will get the proper MemberwiseClone() call done depending on the object you are trying to ShallowCopy(). </p>\n\n<p>If you wanted to go further, you could define a ShallowCopy() in Product (returning a Product) and then have overridden versions in KitItem and PackageKitItem each returning their respective shallow copy.</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283925", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12862/" ]
Ok so I have an abstract base class called Product, a KitItem class that inherits Product and a PackageKitItem class that inherits KitItem. ie. ``` Product KitItem : Product PackageKitItem : KitItem ``` I have my KitItems loaded and I need to load up a collection of PackageKitItems which are, effectively, shallow copies of KitItems. Currently we are doing what feels to me a hacky shallow copy in the Product constructor like so: ``` public Product(Product product) { FieldInfo[] fields = product.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); // copy each value over to 'this' foreach (FieldInfo fi in fields) fi.SetValue(this, fi.GetValue(product)); } ``` I've tried setting up a copy on KitItem like so: ``` public KitItem ShallowCopy() { return (KitItem)this.MemberwiseClone(); } ``` and calling it thus: ``` PackageKitItem tempPackKitItem = (PackageKitItem)packKitItem.ShallowCopy(); ``` but I get an invalid cast. I'm looking for ideas for the best way to accomplish this.
The problem you have is that since ShallowCopy() is a member of KitItem, MemberwiseClone() is just copying the KitItem fields and returning a KitItem even if the original object is a PackageKitItem. I think what you have to do in this circumstance add to KitItem: ``` public virtual KitItem ShallowCopy() { return (KitItem) this.MemberwiseClone(); } ``` and in PackageKitItem: ``` public override KitItem ShallowCopy() { return (PackageKitItem) this.MemberwiseClone(); } ``` Thus you will get the proper MemberwiseClone() call done depending on the object you are trying to ShallowCopy(). If you wanted to go further, you could define a ShallowCopy() in Product (returning a Product) and then have overridden versions in KitItem and PackageKitItem each returning their respective shallow copy.
283,931
<p>Could somebody please explain to me what happens here?<br> I am creating a binding in code. </p> <p>The target object is a UserControl<br> The target property is a boolean DependencyProperty<br> The source object is a FrameworkElement and implements INotifyPropertyChanged<br> The source property is of type ObservableCollection </p> <p>What happens:</p> <ul> <li><p>The binding is created in code, the result BindingExpressionBase looks fine, the mode is OneWay, the target value gets set correctly (at this time)</p> <p>Binding b = new Binding();<br> b.Path = "SourceProperty";<br> b.Source = SourceObject;<br> BindingExpressionBase e = this.SetBinding(TargetProperty, b); </p></li> <li><p>The source property then gets changed as a result of another databinding. The UserControl tries to fire the PropertyChanged event.</p></li> <li><p>....but nobody is listening. PropertyChanged is null.</p></li> </ul> <p>I am sure that nothing else is assigned to the target property, so it should still be bound. Why is the binding not listening for the PropertyChanged event?</p>
[ { "answer_id": 284303, "author": "jarda", "author_id": 6601, "author_profile": "https://Stackoverflow.com/users/6601", "pm_score": 3, "selected": true, "text": "<p>Alright, I found the answer myself. This is a bug in Silverlight..</p>\n\n<p>The code that does the following </p>\n\n<pre><code>if (PropertyChanged != null) \n{ \n PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); \n} \n</code></pre>\n\n<p>must be directly on the class that you bind to, not on its ancestor. I had it inside a FirePropertyChanged() method on a base class and moving it to the derived class made the difference.</p>\n" }, { "answer_id": 17070447, "author": "Alex", "author_id": 1860652, "author_profile": "https://Stackoverflow.com/users/1860652", "pm_score": 0, "selected": false, "text": "<p>For anyone else who is experiencing this: <strong>make sure you are implementing INotifyPropertyChanged on your ViewModel</strong>!</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283931", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6601/" ]
Could somebody please explain to me what happens here? I am creating a binding in code. The target object is a UserControl The target property is a boolean DependencyProperty The source object is a FrameworkElement and implements INotifyPropertyChanged The source property is of type ObservableCollection What happens: * The binding is created in code, the result BindingExpressionBase looks fine, the mode is OneWay, the target value gets set correctly (at this time) Binding b = new Binding(); b.Path = "SourceProperty"; b.Source = SourceObject; BindingExpressionBase e = this.SetBinding(TargetProperty, b); * The source property then gets changed as a result of another databinding. The UserControl tries to fire the PropertyChanged event. * ....but nobody is listening. PropertyChanged is null. I am sure that nothing else is assigned to the target property, so it should still be bound. Why is the binding not listening for the PropertyChanged event?
Alright, I found the answer myself. This is a bug in Silverlight.. The code that does the following ``` if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } ``` must be directly on the class that you bind to, not on its ancestor. I had it inside a FirePropertyChanged() method on a base class and moving it to the derived class made the difference.
283,943
<p>I have a list of strings displayed by a Silverlight ItemsControl. The DataTemplate is a Border control with a TextBlock as its child. How can I access the border control corresponding to an item? For example, I might want to do this to change the background color.</p>
[ { "answer_id": 283972, "author": "jarda", "author_id": 6601, "author_profile": "https://Stackoverflow.com/users/6601", "pm_score": 0, "selected": false, "text": "<p>You can override the ItemsControl.GetContainerForItemOverride method and save the object-container pairs in a dictionary.</p>\n" }, { "answer_id": 285017, "author": "Bryant", "author_id": 10893, "author_profile": "https://Stackoverflow.com/users/10893", "pm_score": 2, "selected": false, "text": "<p>An easier way to do this is to grab the Parent of the textblock and cast it as a Border. Here is a quick example of this:</p>\n\n<p>Xaml</p>\n\n<pre><code>&lt;Grid&gt;\n &lt;ItemsControl x:Name=\"items\"&gt;\n &lt;ItemsControl.ItemTemplate&gt;\n &lt;DataTemplate&gt;\n &lt;Border&gt;\n &lt;TextBlock MouseEnter=\"TextBlock_MouseEnter\" MouseLeave=\"TextBlock_MouseLeave\" Text=\"{Binding}\" /&gt;\n &lt;/Border&gt;\n &lt;/DataTemplate&gt;\n &lt;/ItemsControl.ItemTemplate&gt;\n &lt;/ItemsControl&gt;\n&lt;/Grid&gt;\n</code></pre>\n\n<p>Code behind</p>\n\n<pre><code>public Page()\n{\n InitializeComponent();\n\n items.ItemsSource = new string[] { \"This\", \"Is\", \"A\", \"Test\" };\n}\n\nprivate void TextBlock_MouseEnter(object sender, MouseEventArgs e)\n{\n var tx = sender as TextBlock;\n var bd = tx.Parent as Border;\n bd.Background = new SolidColorBrush(Colors.Yellow);\n}\n\nprivate void TextBlock_MouseLeave(object sender, MouseEventArgs e)\n{\n var tx = sender as TextBlock;\n var bd = tx.Parent as Border;\n bd.Background = new SolidColorBrush(Colors.White);\n}\n</code></pre>\n\n<p>The example sets the background on the border by grabbing the parent of the textbox. </p>\n" }, { "answer_id": 2829615, "author": "morpheus", "author_id": 147530, "author_profile": "https://Stackoverflow.com/users/147530", "pm_score": 0, "selected": false, "text": "<p>see this: <a href=\"http://msdn.microsoft.com/en-us/library/bb613579.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/bb613579.aspx</a> and this: <a href=\"http://blogs.msdn.com/wpfsdk/archive/2007/04/16/how-do-i-programmatically-interact-with-template-generated-elements-part-ii.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/wpfsdk/archive/2007/04/16/how-do-i-programmatically-interact-with-template-generated-elements-part-ii.aspx</a>. Unfortunately, it won't work in SL because SL DataTemplate class doesn't have the FindName method.</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283943", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a list of strings displayed by a Silverlight ItemsControl. The DataTemplate is a Border control with a TextBlock as its child. How can I access the border control corresponding to an item? For example, I might want to do this to change the background color.
An easier way to do this is to grab the Parent of the textblock and cast it as a Border. Here is a quick example of this: Xaml ``` <Grid> <ItemsControl x:Name="items"> <ItemsControl.ItemTemplate> <DataTemplate> <Border> <TextBlock MouseEnter="TextBlock_MouseEnter" MouseLeave="TextBlock_MouseLeave" Text="{Binding}" /> </Border> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> </Grid> ``` Code behind ``` public Page() { InitializeComponent(); items.ItemsSource = new string[] { "This", "Is", "A", "Test" }; } private void TextBlock_MouseEnter(object sender, MouseEventArgs e) { var tx = sender as TextBlock; var bd = tx.Parent as Border; bd.Background = new SolidColorBrush(Colors.Yellow); } private void TextBlock_MouseLeave(object sender, MouseEventArgs e) { var tx = sender as TextBlock; var bd = tx.Parent as Border; bd.Background = new SolidColorBrush(Colors.White); } ``` The example sets the background on the border by grabbing the parent of the textbox.
283,950
<p>When looking at C# code, I often see patterns like this:</p> <pre><code>DataType[] items = GetSomeItems(); OtherDataType[] itemProps = new OtherDataType[items.Length]; int i = 0; foreach (DataType item in items) { // Do some stuff with item, then finally itemProps[i] = item.Prop; i++; } </code></pre> <p>The for-loop iterates over the objects in <code>items</code>, but also keeping a counter (<code>i</code>) for iterating over <code>itemProps</code> as well. I personally don't like this extra <code>i</code> hanging around, and instead would probably do something like:</p> <pre><code>DataType[] items = GetSomeItems(); OtherDataType[] itemProps = new OtherDataType[items.Length]; for (int i = 0; i &lt; items.Length; i++) { // Do some stuff with items[i], then finally itemProps[i] = items[i].Prop; } </code></pre> <p>Is there perhaps some benfit to the first approach I'm not aware of? Is this a result of everybody trying to use that fancy <code>foreach (...)</code> syntax? I'm interested in your opinions on this.</p>
[ { "answer_id": 283966, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 2, "selected": false, "text": "<p>In this case, I don't think so. Sometimes, though, the collection doesn't implement <code>this[int index]</code> but it does implement GetEnumerator(). In the latter case, you don't have much choice.</p>\n" }, { "answer_id": 283969, "author": "DilbertDave", "author_id": 31580, "author_profile": "https://Stackoverflow.com/users/31580", "pm_score": 2, "selected": false, "text": "<p>With i being outside the array then if would be available after the completion of the loop. If you wanted to count the number of items and the collection didn't provide a .Count or .UBound property then this could be useful.</p>\n\n<p>Like you I would normally use the second method, looks much cleaner to me.</p>\n" }, { "answer_id": 283971, "author": "Ali Ersöz", "author_id": 4215, "author_profile": "https://Stackoverflow.com/users/4215", "pm_score": 3, "selected": false, "text": "<p>If you are using C# 3.0 that will be better;</p>\n\n<pre><code>OtherDataType[] itemProps = items.Select(i=&gt;i.Prop).ToArray();\n</code></pre>\n" }, { "answer_id": 283980, "author": "Nicolas Repiquet", "author_id": 36896, "author_profile": "https://Stackoverflow.com/users/36896", "pm_score": 1, "selected": false, "text": "<p>Some data structures are not well suited for random access but can be iterated over very fast ( Trees, linked lists, etc ). So if you need to iterate over one of these but need a count for some reason, your doomed to go the ugly way...</p>\n" }, { "answer_id": 284023, "author": "philsquared", "author_id": 32136, "author_profile": "https://Stackoverflow.com/users/32136", "pm_score": 1, "selected": false, "text": "<p>Semantically they may be equivalent, but in fact using foreach over an enumerator gives the compiler more scope to optimise. </p>\n\n<p>I don't remember all the arguments off the top of my head,but they are well covered in <em>Effective C#</em>, which is recommended reading.</p>\n" }, { "answer_id": 284126, "author": "user35978", "author_id": 35978, "author_profile": "https://Stackoverflow.com/users/35978", "pm_score": 1, "selected": false, "text": "<p>foreach (DataType item in items)\nThis foreach loop makes it crystal clear that you're iterating over all the DataType item of, well yes, items. Maybe it makes the code a little longer, but it's not a \"bad\" code. For the other for-loop, you need to check inside the brackets to have an idea for what this loop is used. </p>\n\n<p>The problem with this example lies in the fact that you're iterating over two different arrays in the same time which we don't do that often.. so we are stuck between two strategies.. either we \"hack a bit\" the fancy-foreach as you call it or we get back on the old-not-so-loved for(int i = 0; i ...). (There are other ways than those 2, of course)</p>\n\n<p>So, I think it's the Vim vs Emacs things coming back in your question with the For vs Foreach loop :) People who like the for(), will say this foreach is useless, might cause performance issues and is just big. People who prefere foreach will say something like, we don't care if there's two extra line if we can read the code and maintenance it easily.</p>\n\n<p>Finally, the i is outside the scope first the first example and inside for the second.. reasons to that?! Because if you use the i outside of your foreach, I would have called differently. And, for my opinion, I prefer the foreach ways because you see immediately what is happening. You also don't have to think about if it's &lt; or =. You know immediately that you are iterating over all the list, However, sadly, people will forget about the i++ at the end :D So, I say Vim!</p>\n" }, { "answer_id": 284261, "author": "ADB", "author_id": 3610, "author_profile": "https://Stackoverflow.com/users/3610", "pm_score": 1, "selected": false, "text": "<p>Lets not forget that some collections do not implement a direct access operator[] and that you have to iterate using the IEnumerable interface which is most easily accessed with foreach().</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2576/" ]
When looking at C# code, I often see patterns like this: ``` DataType[] items = GetSomeItems(); OtherDataType[] itemProps = new OtherDataType[items.Length]; int i = 0; foreach (DataType item in items) { // Do some stuff with item, then finally itemProps[i] = item.Prop; i++; } ``` The for-loop iterates over the objects in `items`, but also keeping a counter (`i`) for iterating over `itemProps` as well. I personally don't like this extra `i` hanging around, and instead would probably do something like: ``` DataType[] items = GetSomeItems(); OtherDataType[] itemProps = new OtherDataType[items.Length]; for (int i = 0; i < items.Length; i++) { // Do some stuff with items[i], then finally itemProps[i] = items[i].Prop; } ``` Is there perhaps some benfit to the first approach I'm not aware of? Is this a result of everybody trying to use that fancy `foreach (...)` syntax? I'm interested in your opinions on this.
If you are using C# 3.0 that will be better; ``` OtherDataType[] itemProps = items.Select(i=>i.Prop).ToArray(); ```
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": "<p>I'm just assuming by filepath, you actually mean url (or uri, I forget which one is partial).</p>\n\n<p>Without the ~, the first example should work. <code>&lt;script type=\"text/javascript\" src=\"/jQueryScripts/jquery.js\"&gt;&lt;/script&gt;</code> would cause the browser to request <a href=\"http://www.example.com/jQueryScripts/jquery.js\" rel=\"nofollow noreferrer\">http://www.example.com/jQueryScripts/jquery.js</a> (where www.example.com is your domain).</p>\n" }, { "answer_id": 284005, "author": "DOK", "author_id": 27637, "author_profile": "https://Stackoverflow.com/users/27637", "pm_score": 1, "selected": false, "text": "<p>I believe you need to have <code>runat=server</code> in the <code>&lt;head&gt;</code> tag of the <code>MasterPage</code> for this URL rebasing to work.</p>\n\n<pre><code>&lt;head runat=\"server\"&gt;\n</code></pre>\n" }, { "answer_id": 284037, "author": "Jeff Sheldon", "author_id": 33910, "author_profile": "https://Stackoverflow.com/users/33910", "pm_score": 1, "selected": false, "text": "<p>First off the tilde in front is a asp.net thing for use in server controls and won't work in basic HTML.</p>\n\n<p>Without getting into detailed explanations you could just use a slash (/) in front, and include the web app name if its not the root site.</p>\n\n<p>Or you could put code in your master page for dynamically including scripts, and let it handle the pathing. Like:</p>\n\n<pre><code> 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</code></pre>\n\n<p>The above code also appends the assembly version. I use this mostly for development so my javascript files get updated whenever I build.</p>\n" }, { "answer_id": 284070, "author": "kristian", "author_id": 20377, "author_profile": "https://Stackoverflow.com/users/20377", "pm_score": 1, "selected": false, "text": "<p>You could use the <strong>Page.ResolveUrl</strong> method to get around this</p>\n\n<p>for example:</p>\n\n<pre><code>&lt;script type=\"text/javascript\" src=\"&lt;%=Page.ResolveUrl(\"~/jQueryScripts/jquery.js\")%&gt;\"&gt;&lt;/script&gt;\n</code></pre>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283951", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35454/" ]
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. To fix this I need to get the filepath from the root but I can't seem to get it working. I tried: ``` <script type="text/javascript" src="~/jQueryScripts/jquery.js"></script> ``` and ``` <script type="text/javascript" src="../jQueryScripts/jquery.js"></script> ``` No luck on either! Any ideas on how I can tell it to get the filepath from the root?
I'm just assuming by filepath, you actually mean url (or uri, I forget which one is partial). Without the ~, the first example should work. `<script type="text/javascript" src="/jQueryScripts/jquery.js"></script>` would cause the browser to request <http://www.example.com/jQueryScripts/jquery.js> (where www.example.com is your domain).
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": "<p>According to <a href=\"https://www.rfc-editor.org/rfc/rfc2397\" rel=\"nofollow noreferrer\">RFC 2397</a>, no, there isn't.</p>\n<p><strike>Nor does there appear to be any <a href=\"http://www.w3schools.com/tags/tag_a.asp\" rel=\"nofollow noreferrer\">attribute</a> of the <code>&lt;a&gt;</code> element that you can use either.</strike></p>\n<p>However HTML5 has subsequently introduced the <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#Attributes\" rel=\"nofollow noreferrer\"><code>download</code></a> attribute on the <code>&lt;a&gt;</code> element, although at the time of writing support is not universal (no MSIE support, for example)</p>\n" }, { "answer_id": 6171260, "author": "Lightness Races in Orbit", "author_id": 560648, "author_profile": "https://Stackoverflow.com/users/560648", "pm_score": 4, "selected": false, "text": "<p>No.</p>\n\n<p>The entire purpose is that it's a datastream, not a file. The data source should not have any knowledge of the user agent handling it as a file... and it doesn't.</p>\n" }, { "answer_id": 6171309, "author": "ninjagecko", "author_id": 711085, "author_profile": "https://Stackoverflow.com/users/711085", "pm_score": 2, "selected": false, "text": "<p>(This answer has been made deprecated by newer technology, but will be kept here for historical interest.)</p>\n<p><strike>It's kind of hackish, but I've been in the same situation before. I was dynamically generating a text file in javascript and wanted to provide it for download by encoding it with the data-URI.</p>\n<p>This is possible with <strike>minor</strike>major user intervention. Generate a link <code>&lt;a href=&quot;data:...&quot;&gt;right-click me and select &quot;Save Link As...&quot; and save as &quot;example.txt&quot;&lt;/a&gt;</code>. As I said, this is inelegant, but it works if you do not need a professional solution.</p>\n<p>This could be made less painful by using flash to copy the name into the clipboard first. Of course if you let yourself use Flash or Java (now with less and less browser support I think?), you could probably find a another way to do this.</strike></p>\n" }, { "answer_id": 6171323, "author": "silex", "author_id": 748779, "author_profile": "https://Stackoverflow.com/users/748779", "pm_score": 3, "selected": false, "text": "<p>Look at this link:\n<a href=\"http://lists.w3.org/Archives/Public/uri/2010Feb/0069.html\" rel=\"noreferrer\">http://lists.w3.org/Archives/Public/uri/2010Feb/0069.html</a></p>\n\n<p>Quote:</p>\n\n<blockquote>\n <p>It even works (as in, doesn't cause a problem) with ;base64 at the end<br>\n like this (in Opera at least):</p>\n \n <p><strong>data:text/plain;charset=utf-8;headers=Content-Disposition%3A%20attachment%3B%20filename%3D%22with%20spaces.txt%22%0D%0AContent-Language%3A%20en;base64,4oiaDQo%3D</strong></p>\n</blockquote>\n\n<p>Also there is some info in the rest messages of the discussion.</p>\n" }, { "answer_id": 6240528, "author": "sherpya", "author_id": 764426, "author_profile": "https://Stackoverflow.com/users/764426", "pm_score": 4, "selected": false, "text": "<p>I've looked a bit in firefox sources in netwerk/protocol/data/nsDataHandler.cpp</p>\n\n<p>data handler only parses content/type and charset, and looks if there is \";base64\"\nin the string</p>\n\n<p>the rfc specifices no filename and at least firefox handles no filename for it,\nthe code generates a random name plus \".part\"</p>\n\n<p>I've also checked firefox log</p>\n\n\n\n<pre class=\"lang-none prettyprint-override\"><code>[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</code></pre>\n\n<p>interesting files if you want to look at mozilla sources:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>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</code></pre>\n\n<p>I think you can stop searching a solution for now, because I suspect there is none :)</p>\n\n<p>as noticed in this thread html5 has <code>download</code> attribute, it works also on firefox 20 <a href=\"http://www.whatwg.org/specs/web-apps/current-work/multipage/links.html#attr-hyperlink-download\" rel=\"nofollow\">http://www.whatwg.org/specs/web-apps/current-work/multipage/links.html#attr-hyperlink-download</a></p>\n" }, { "answer_id": 6943481, "author": "Dan Fabulich", "author_id": 54829, "author_profile": "https://Stackoverflow.com/users/54829", "pm_score": 8, "selected": false, "text": "<p>Use the <code>download</code> attribute:</p>\n<pre><code>&lt;a download='FileName' href='your_url'&gt;\n</code></pre>\n<p><a href=\"http://caniuse.com/#search=download\" rel=\"noreferrer\">The <code>download</code> attribute works on</a> Chrome, Firefox, Edge, Opera, desktop Safari 10+, iOS Safari 13+, and not IE11.</p>\n" }, { "answer_id": 8827700, "author": "Fabian B.", "author_id": 1144274, "author_profile": "https://Stackoverflow.com/users/1144274", "pm_score": 2, "selected": false, "text": "<p>There is a tiny workaround script on Google Code that worked for me: </p>\n\n<p><a href=\"http://code.google.com/p/download-data-uri/\" rel=\"nofollow\">http://code.google.com/p/download-data-uri/</a></p>\n\n<p>It adds a form with the data in it, submits it and then removes the form again. Hacky, but it did the job for me. Requires jQuery. </p>\n\n<p>This thread showed up in Google before the Google Code page and I thought it might be helpful to have the link in here, too.</p>\n" }, { "answer_id": 12409154, "author": "cuixiping", "author_id": 988089, "author_profile": "https://Stackoverflow.com/users/988089", "pm_score": 3, "selected": false, "text": "<p>you can add a download attribute to the anchor element. </p>\n\n<p>sample:</p>\n\n<pre><code>&lt;a download=\"abcd.cer\"\n href=\"data:application/stream;base64,MIIDhTC......\"&gt;down&lt;/a&gt;\n</code></pre>\n" }, { "answer_id": 15832569, "author": "owencm", "author_id": 842506, "author_profile": "https://Stackoverflow.com/users/842506", "pm_score": 4, "selected": false, "text": "<p>The following Javascript snippet works in Chrome by using the new 'download' attribute of links and simulating a click.</p>\n\n<pre><code>function downloadWithName(uri, name) {\n var link = document.createElement(\"a\");\n link.download = name;\n link.href = uri;\n link.click();\n}\n</code></pre>\n\n<p>And the following example shows it's use:</p>\n\n<pre><code>downloadWithName(\"data:,Hello%2C%20World!\", \"helloWorld.txt\")\n</code></pre>\n" }, { "answer_id": 16523173, "author": "Holf", "author_id": 169334, "author_profile": "https://Stackoverflow.com/users/169334", "pm_score": 6, "selected": false, "text": "<p>Chrome makes this very simple these days:</p>\n\n<pre><code>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</code></pre>\n" }, { "answer_id": 21915171, "author": "kgividen", "author_id": 1402620, "author_profile": "https://Stackoverflow.com/users/1402620", "pm_score": 2, "selected": false, "text": "<p>Here is a jQuery version based off of Holf's version and works with Chrome and Firefox whereas his version seems to only work with Chrome. It's a little strange to add something to the body to do this but if someone has a better option I'm all for it.</p>\n\n<pre><code>var exportFileName = \"export-\" + filename;\n$('&lt;a&gt;&lt;/a&gt;', {\n \"download\": exportFileName,\n \"href\": \"data:,\" + JSON.stringify(exportData, null,5),\n \"id\": \"exportDataID\"\n}).appendTo(\"body\")[0].click().remove();\n</code></pre>\n" }, { "answer_id": 25715985, "author": "fregante", "author_id": 288906, "author_profile": "https://Stackoverflow.com/users/288906", "pm_score": 6, "selected": false, "text": "<p><strong>HTML only:</strong> use the <code>download</code> attribute:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;a download=\"logo.gif\" href=\"data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7\"&gt;Download transparent png&lt;/a&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<hr>\n\n<p><strong>Javascript only:</strong> you can save any data URI with this code:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function saveAs(uri, filename) {\r\n var link = document.createElement('a');\r\n if (typeof link.download === 'string') {\r\n link.href = uri;\r\n link.download = filename;\r\n\r\n //Firefox requires the link to be in the body\r\n document.body.appendChild(link);\r\n \r\n //simulate click\r\n link.click();\r\n\r\n //remove the link when done\r\n document.body.removeChild(link);\r\n } else {\r\n window.open(uri);\r\n }\r\n}\r\n\r\nvar file = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'\r\nsaveAs(file, 'logo.gif');</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p><strong>Chrome, Firefox, and Edge 13+</strong> will use the specified filename.</p>\n\n<p><strong>IE11, Edge 12, and Safari 9</strong> (which <a href=\"http://caniuse.com/#feat=download\" rel=\"noreferrer\">don't support the <code>download</code> attribute</a>) will download the file with their default name <strong>or they will simply display it</strong> in a new tab, if it's of a supported file type: images, videos, audio files, …</p>\n" }, { "answer_id": 28124736, "author": "Adria", "author_id": 1090770, "author_profile": "https://Stackoverflow.com/users/1090770", "pm_score": 3, "selected": false, "text": "<p>Using <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker_API/Using_Service_Workers\" rel=\"noreferrer\">service workers</a>, this is finally possible in the truest sense.</p>\n\n<ol>\n<li>Create a fake URL. For example /saveAs/myPrettyName.jpg</li>\n<li>Use URL in <code>&lt;a href, &lt;img src</code>, window.open( url ), absolutely anything that can be done with a \"real\" URL. </li>\n<li>Inside the worker, catch the fetch event, and respond with the correct data.</li>\n</ol>\n\n<p>The browser will now suggest myPrettyName.jpg even if the user opens the file in a new tab, and tries to save it there. It will be exactly as if the file had come from the server.</p>\n\n<pre><code>// 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</code></pre>\n" }, { "answer_id": 33917332, "author": "Sushama Pradhan", "author_id": 5143142, "author_profile": "https://Stackoverflow.com/users/5143142", "pm_score": -1, "selected": false, "text": "<pre><code>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</code></pre>\n" }, { "answer_id": 34569480, "author": "NeutronenStern", "author_id": 5381025, "author_profile": "https://Stackoverflow.com/users/5381025", "pm_score": 2, "selected": false, "text": "<p>This one works with Firefox 43.0 (older not tested):</p>\n\n<p><strong>dl.js:</strong></p>\n\n<pre><code>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</code></pre>\n\n<p><strong>dl.html</strong></p>\n\n<pre><code>&lt;html lang=\"en\" xmlns=\"http://www.w3.org/1999/xhtml\"&gt;\n\n&lt;head&gt;\n &lt;meta charset=\"utf-8\"/&gt;\n &lt;title&gt;Test&lt;/title&gt;\n &lt;script type=\"text/javascript\" src=\"dl.js\"&gt;&lt;/script&gt;\n&lt;/head&gt;\n\n&lt;body&gt;\n&lt;button id=\"create\" type=\"button\" onclick=\"download();\"&gt;Download&lt;/button&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>If button is clicked it offered a file named <em>hello.bin</em> for download. Trick is to use <em>File</em> instead of <em>Blob</em>.</p>\n\n<p>reference: <a href=\"https://developer.mozilla.org/de/docs/Web/API/File\" rel=\"nofollow\">https://developer.mozilla.org/de/docs/Web/API/File</a></p>\n" }, { "answer_id": 40819952, "author": "Chad Scira", "author_id": 103696, "author_profile": "https://Stackoverflow.com/users/103696", "pm_score": -1, "selected": false, "text": "<p>You actually can achieve this, in Chrome and FireFox.</p>\n\n<p>Try the following url, it will download the code that was used.</p>\n\n<pre><code>data:text/html;base64,PGEgaHJlZj0iZGF0YTp0ZXh0L2h0bWw7YmFzZTY0LFBHRWdhSEpsWmowaVVGVlVYMFJCVkVGZlZWSkpYMGhGVWtVaUlHUnZkMjVzYjJGa1BTSjBaWE4wTG1oMGJXd2lQZ284YzJOeWFYQjBQZ3BrYjJOMWJXVnVkQzV4ZFdWeWVWTmxiR1ZqZEc5eUtDZGhKeWt1WTJ4cFkyc29LVHNLUEM5elkzSnBjSFErIiBkb3dubG9hZD0idGVzdC5odG1sIj4KPHNjcmlwdD4KZG9jdW1lbnQucXVlcnlTZWxlY3RvcignYScpLmNsaWNrKCk7Cjwvc2NyaXB0Pg==\n</code></pre>\n" }, { "answer_id": 66157662, "author": "Micha", "author_id": 15191770, "author_profile": "https://Stackoverflow.com/users/15191770", "pm_score": 0, "selected": false, "text": "<p><code>&lt;a href=.. download=.. &gt;</code> works for left-click and right-click -&gt; save link as..,</p>\n<p>but <code>&lt;img src=.. download=.. &gt;</code> doesn't work for right-click -&gt; save image as.. , &quot;Download.jped&quot; is suggested.</p>\n<p>If you combine both:<code>&lt;a href=.. download=..&gt;&lt;img src=..&gt;&lt;/a&gt;</code></p>\n<p>it works for left-click, right-click -&gt; save link as.., right-click -&gt; save image as..</p>\n<p>You have to write the data-uri twice (href and src), so for large image files it is better to copy the uri with javascript.</p>\n<p><em>tested with Chrome/Edge 88</em></p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283956", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
If for example you follow the link: `data:application/octet-stream;base64,SGVsbG8=` 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?
Use the `download` attribute: ``` <a download='FileName' href='your_url'> ``` [The `download` attribute works on](http://caniuse.com/#search=download) Chrome, Firefox, Edge, Opera, desktop Safari 10+, iOS Safari 13+, and not IE11.
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": "<p>add this css to your product_container class</p>\n\n<pre><code> margin: 0px auto;\n padding: 0px;\n border:0;\n width: 700px;\n</code></pre>\n" }, { "answer_id": 283985, "author": "Adam Bellaire", "author_id": 21632, "author_profile": "https://Stackoverflow.com/users/21632", "pm_score": 2, "selected": false, "text": "<p>By default, <code>div</code> elements are displayed as block elements, so they have 100% width, making centering them meaningless. As suggested by Arief, you must specify a <code>width</code> and you can then use <code>auto</code> when specifying <code>margin</code> in order to center a <code>div</code>.</p>\n\n<p>Alternatively, you could also force <code>display: inline</code>, but then you'd have something that pretty much behaves like a <code>span</code> instead of a <code>div</code>, so that doesn't make a lot of sense.</p>\n" }, { "answer_id": 283988, "author": "Kon", "author_id": 22303, "author_profile": "https://Stackoverflow.com/users/22303", "pm_score": 0, "selected": false, "text": "<p>I'm afraid the only way to do this without explicitly specifying the width is to use (gasp) tables.</p>\n" }, { "answer_id": 284064, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 7, "selected": false, "text": "<p>An element with ‘display: block’ (as div is by default) has a width determined by the width of its container. You can't make a block's width dependent on the width of its contents (shrink-to-fit).</p>\n\n<p>(Except for blocks that are ‘float: left/right’ in CSS 2.1, but that's no use for centering.)</p>\n\n<p>You could set the ‘display’ property to ‘inline-block’ to turn a block into a shrink-to-fit object that can be controlled by its parent's text-align property, but browser support is spotty. You can mostly get away with it by using hacks (eg. see -moz-inline-stack) if you want to go that way.</p>\n\n<p>The other way to go is tables. This can be necessary when you have columns whose width really can't be known in advance. I can't really tell what you're trying to do from the example code — there's nothing obvious in there that would <em>need</em> a shrink-to-fit block — but a list of products could possibly be considered tabular.</p>\n\n<p>[PS. never use ‘pt’ for font sizes on the web. ‘px’ is more reliable if you really need fixed size text, otherwise relative units like ‘%’ are better. And “clear: ccc both” — a typo?]</p>\n\n<pre><code>.center{\n text-align:center; \n}\n\n.center &gt; div{ /* N.B. child combinators don't work in IE6 or less */\n display:inline-block;\n}\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/ajr4Lhhr/1/\" rel=\"noreferrer\">JSFiddle</a></p>\n" }, { "answer_id": 2522640, "author": "Lionel", "author_id": 302448, "author_profile": "https://Stackoverflow.com/users/302448", "pm_score": 0, "selected": false, "text": "<p>Crappy fix, but it does work...</p>\n\n<p>CSS:</p>\n\n<pre><code>#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</code></pre>\n\n<p>HTML:</p>\n\n<pre><code>&lt;center&gt;\n&lt;table border=\"0\" cellspacing=\"0\"&gt;\n &lt;tr&gt;\n &lt;td&gt;\n&lt;div id=\"mainContent\"&gt;\n1&lt;br/&gt;\n&lt;br/&gt;\n123&lt;br/&gt;\n123&lt;br/&gt;\n123&lt;br/&gt;\n&lt;/div&gt;&lt;div id=\"sidebar\"&gt;&lt;br/&gt;\n&lt;/div&gt;&lt;/td&gt;\n&lt;/tr&gt;\n&lt;/table&gt;\n&lt;/center&gt;\n</code></pre>\n" }, { "answer_id": 6353345, "author": "Mike M. Lin", "author_id": 266536, "author_profile": "https://Stackoverflow.com/users/266536", "pm_score": 8, "selected": false, "text": "<p><strong>Update 27 Feb 2015:</strong> My original answer keeps getting voted up, but now I normally use @bobince's approach instead.</p>\n\n<pre><code>.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</code></pre>\n\n<p><strong>My original post for historical purposes:</strong></p>\n\n<p>You might want to try this approach.</p>\n\n<pre><code>&lt;div class=\"product_container\"&gt;\n &lt;div class=\"outer-center\"&gt;\n &lt;div class=\"product inner-center\"&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;div class=\"clear\"/&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>Here's the matching style:</p>\n\n<pre><code>.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</code></pre>\n\n<p><a href=\"http://jsfiddle.net/6350btvd/3/\">JSFiddle</a></p>\n\n<p>The idea here is that you contain the content you want to center in two divs, an outer one and an inner one. You float both divs so that their widths automatically shrink to fit your content. Next, you relatively position the outer div with it's right edge in the center of the container. Lastly, you relatively position the inner div the opposite direction by half of its own width (actually the outer div's width, but they are the same). Ultimately that centers the content in whatever container it's in.</p>\n\n<p>You <em>may</em> need that empty div at the end if you depend on your \"product\" content to size the height for the \"product_container\".</p>\n" }, { "answer_id": 6544658, "author": "JavierIEH", "author_id": 232588, "author_profile": "https://Stackoverflow.com/users/232588", "pm_score": 4, "selected": false, "text": "<p>I found a more elegant solution, combining \"inline-block\" to avoid using float and the hacky clear:both. It still requires nested divs tho, which isnt very semantic but it just works...</p>\n\n<pre><code>div.outer{\n display:inline-block;\n position:relative;\n left:50%;\n}\n\ndiv.inner{\n position:relative;\n left:-50%;\n}\n</code></pre>\n\n<p>Hope it helps!</p>\n" }, { "answer_id": 8319494, "author": "Alexander Pogrebnyak", "author_id": 185722, "author_profile": "https://Stackoverflow.com/users/185722", "pm_score": 1, "selected": false, "text": "<p>Slight variation on <a href=\"https://stackoverflow.com/a/6353345/185722\">Mike M. Lin's answer</a></p>\n\n<p>If you add <code>overflow: auto;</code> ( or <code>hidden</code> ) to <code>div.product_container</code>, then you don't need <code>div.clear</code>.</p>\n\n<p>This is derived from this article -> <a href=\"http://www.quirksmode.org/css/clearing.html\" rel=\"nofollow noreferrer\">http://www.quirksmode.org/css/clearing.html</a></p>\n\n<p>Here is modified HTML:</p>\n\n<pre><code>&lt;div class=\"product_container\"&gt;\n &lt;div class=\"outer-center\"&gt;\n &lt;div class=\"product inner-center\"&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>And here is modified CSS:</p>\n\n<pre><code>.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</code></pre>\n\n<p>The reason, why it's better without <code>div.clear</code> (apart that it feels wrong to have an empty element) is Firefox'es overzealous margin assignment.</p>\n\n<p>If, for example, you have this html:</p>\n\n<pre><code>&lt;div class=\"product_container\"&gt;\n &lt;div class=\"outer-center\"&gt;\n &lt;div class=\"product inner-center\"&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;div style=\"clear: both;\"&gt;&lt;/div&gt;\n&lt;/div&gt;\n&lt;p style=\"margin-top: 11px;\"&gt;Some text&lt;/p&gt;\n</code></pre>\n\n<p>then, in Firefox (8.0 at the point of writing), you will see <code>11px</code> margin <strong>before</strong> <code>product_container</code>. What's worse, is that you will get a vertical scroll bar for the whole page, even if the content fits nicely into the screen dimensions.</p>\n" }, { "answer_id": 10647574, "author": "Shinov T", "author_id": 1402636, "author_profile": "https://Stackoverflow.com/users/1402636", "pm_score": 1, "selected": false, "text": "<p>Try this new css and markup</p>\n\n<p>Here is modified HTML:</p>\n\n<pre><code>&lt;div class=\"product_container\"&gt;\n&lt;div class=\"products\" id=\"products\"&gt;\n &lt;div id=\"product_15\" class=\"products_box\"&gt;\n &lt;img src=\"/images/ecommerce/card_default.png\"&gt;\n &lt;div class=\"price\"&gt;R$ 0,01&lt;/div&gt;\n &lt;/div&gt;\n &lt;div id=\"product_15\" class=\"products_box\"&gt;\n &lt;img src=\"/images/ecommerce/card_default.png\"&gt;\n &lt;div class=\"price\"&gt;R$ 0,01&lt;/div&gt;\n &lt;/div&gt; \n &lt;div id=\"product_15\" class=\"products_box\"&gt;\n &lt;img src=\"/images/ecommerce/card_default.png\"&gt;\n &lt;div class=\"price\"&gt;R$ 0,01&lt;/div&gt;\n &lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p></p>\n\n<p>And here is modified CSS:</p>\n\n<pre><code>&lt;pre&gt;\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</code></pre>\n\n<p></p>\n" }, { "answer_id": 11791282, "author": "Craigo", "author_id": 418057, "author_profile": "https://Stackoverflow.com/users/418057", "pm_score": 0, "selected": false, "text": "<p>Simple fix that works in old browsers (but does use tables, and requires a height to be set):</p>\n\n<pre><code>&lt;div style=\"width:100%;height:40px;position:absolute;top:50%;margin-top:-20px;\"&gt;\n &lt;table style=\"width:100%\"&gt;&lt;tr&gt;&lt;td align=\"center\"&gt;\n In the middle\n &lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;\n&lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 11899243, "author": "johndoe", "author_id": 1574023, "author_profile": "https://Stackoverflow.com/users/1574023", "pm_score": 1, "selected": false, "text": "<pre><code>&lt;div class=\"product_container\"&gt;\n&lt;div class=\"outer-center\"&gt;\n&lt;div class=\"product inner-center\"&gt;\n &lt;/div&gt;\n&lt;/div&gt;\n&lt;div class=\"clear\"&gt;&lt;/div&gt;\n&lt;/div&gt;\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</code></pre>\n\n<p>If you dont provide \"overflow:hidden\" for \".product_container\" the \"outer-center\" div will overlap other nearby contents to the right of it. Any links or buttons to the right of \"outer-center\" wont work. Try background color for \"outer-center\" to understand the need of \"overflow :hidden\" </p>\n" }, { "answer_id": 13413240, "author": "Greg Benner", "author_id": 1151520, "author_profile": "https://Stackoverflow.com/users/1151520", "pm_score": 2, "selected": false, "text": "<p>This will center an element such as an Ordered List, or Unordered List, or any element.\nJust wrap it with a Div with the class of outerElement and give the inner element the class of innerElement. </p>\n\n<p>The outerelement class accounts for IE, old Mozilla, and most newer browsers. </p>\n\n<pre><code> .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</code></pre>\n" }, { "answer_id": 16132736, "author": "somebody", "author_id": 2304644, "author_profile": "https://Stackoverflow.com/users/2304644", "pm_score": 0, "selected": false, "text": "<pre><code>&lt;style type=\"text/css\"&gt;\n.container_box{\n text-align:center\n}\n.content{\n padding:10px;\n background:#ff0000;\n color:#ffffff;\n</code></pre>\n\n<p>}\n </p>\n\n<p>use span istead of the inner divs</p>\n\n<pre><code>&lt;div class=\"container_box\"&gt;\n &lt;span class=\"content\"&gt;Hello&lt;/span&gt;\n&lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 16928805, "author": "Nikola", "author_id": 585786, "author_profile": "https://Stackoverflow.com/users/585786", "pm_score": 1, "selected": false, "text": "<p>I found interesting solution, I was making slider and had to center slide controls and I did this and works fine. You can also add relative position to parent and move child position vertical. Take a look <a href=\"http://jsfiddle.net/bergb/6DvJz/\" rel=\"nofollow\">http://jsfiddle.net/bergb/6DvJz/</a></p>\n\n<p>CSS:</p>\n\n<pre><code>#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</code></pre>\n\n<p>HTML:</p>\n\n<pre><code>&lt;div id=\"parent\"&gt;\n &lt;div id=\"child\"&gt;voila&lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 21320716, "author": "Maxime Rossini", "author_id": 547733, "author_profile": "https://Stackoverflow.com/users/547733", "pm_score": 7, "selected": false, "text": "<p>Most browsers support the <code>display: table;</code> CSS rule. This is a good trick to center a div in a container without adding extra HTML nor applying constraining styles to the container (like <code>text-align: center;</code> which would center all other inline content in the container), while keeping dynamic width for the contained div:</p>\n\n<p>HTML:</p>\n\n<pre><code>&lt;div class=\"container\"&gt;\n &lt;div class=\"centered\"&gt;This content is centered&lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>CSS:</p>\n\n<pre><code>.centered { display: table; margin: 0 auto; }\n</code></pre>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.container {\r\n background-color: green;\r\n}\r\n.centered {\r\n display: table;\r\n margin: 0 auto;\r\n background-color: red;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div class=\"container\"&gt;\r\n &lt;div class=\"centered\"&gt;This content is centered&lt;/div&gt;\r\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<hr>\n\n<p><strong>Update (2015-03-09):</strong></p>\n\n<p>The proper way to do this today is actually to use flexbox rules. Browser support is a little bit more restricted (<a href=\"http://caniuse.com/#feat=css-table\" rel=\"noreferrer\">CSS table support</a> vs <a href=\"http://caniuse.com/#feat=flexbox\" rel=\"noreferrer\">flexbox support</a>) but this method also allows many other things, and is a dedicated CSS rule for this type of behavior:</p>\n\n<p>HTML:</p>\n\n<pre><code>&lt;div class=\"container\"&gt;\n &lt;div class=\"centered\"&gt;This content is centered&lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>CSS:</p>\n\n<pre><code>.container {\n display: flex;\n flex-direction: column; /* put this if you want to stack elements vertically */\n}\n.centered { margin: 0 auto; }\n</code></pre>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.container {\r\n display: flex;\r\n flex-direction: column; /* put this if you want to stack elements vertically */\r\n background-color: green;\r\n}\r\n.centered {\r\n margin: 0 auto;\r\n background-color: red;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div class=\"container\"&gt;\r\n &lt;div class=\"centered\"&gt;This content is centered&lt;/div&gt;\r\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 25047040, "author": "Wray Bowling", "author_id": 1281267, "author_profile": "https://Stackoverflow.com/users/1281267", "pm_score": 0, "selected": false, "text": "<p>I know this question is old, but I'm taking a crack at it. Very similar to bobince's answer but with working code example. </p>\n\n<p>Make each product an inline-block. Center the contents of the container. Done.</p>\n\n<p><a href=\"http://jsfiddle.net/rgbk/6Z2Re/\" rel=\"nofollow noreferrer\">http://jsfiddle.net/rgbk/6Z2Re/</a></p>\n\n<pre><code>&lt;style&gt;\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&lt;/style&gt;\n\n\n&lt;div class=\"products\"&gt;\n &lt;div class=\"product\"&gt;\n &lt;div class=\"price\"&gt;R$ 0,01&lt;/div&gt;\n &lt;/div&gt;\n &lt;div class=\"product\"&gt;\n &lt;div class=\"price\"&gt;R$ 0,01&lt;/div&gt;\n &lt;/div&gt;\n &lt;div class=\"product\"&gt;\n &lt;div class=\"price\"&gt;R$ 0,01&lt;/div&gt;\n &lt;/div&gt;\n &lt;div class=\"product\"&gt;\n &lt;div class=\"price\"&gt;R$ 0,01&lt;/div&gt;\n &lt;/div&gt;\n &lt;div class=\"product\"&gt;\n &lt;div class=\"price\"&gt;R$ 0,01&lt;/div&gt;\n &lt;/div&gt;\n &lt;div class=\"product\"&gt;\n &lt;div class=\"price\"&gt;R$ 0,01&lt;/div&gt;\n &lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>See also: <a href=\"https://stackoverflow.com/questions/9245755/center-inline-blocks-with-dynamic-width-in-css\">Center inline-blocks with dynamic width in CSS</a></p>\n" }, { "answer_id": 26650821, "author": "hahaha", "author_id": 3522714, "author_profile": "https://Stackoverflow.com/users/3522714", "pm_score": 1, "selected": false, "text": "<p>Do <code>display:table;</code> and set <code>margin</code> to <code>auto</code></p>\n\n<p>Important bit of code:</p>\n\n<pre><code>.relatedProducts {\n display: table;\n margin-left: auto;\n margin-right: auto;\n}\n</code></pre>\n\n<p>No matter how many elements you got now it will auto align in center</p>\n\n<p>Example in code snippet:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.relatedProducts {\r\n display: table;\r\n margin-left: auto;\r\n margin-right: auto;\r\n}\r\na {\r\n text-decoration:none;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div class=\"row relatedProducts\"&gt;\r\n&lt;div class=\"homeContentTitle\" style=\"margin: 100px auto 35px; width: 250px\"&gt;Similar Products&lt;/div&gt;\r\n \r\n&lt;a href=\"#\"&gt;test1 &lt;/a&gt;\r\n&lt;a href=\"#\"&gt;test2 &lt;/a&gt;\r\n&lt;a href=\"#\"&gt;test3 &lt;/a&gt;\r\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 32085351, "author": "West1", "author_id": 3919052, "author_profile": "https://Stackoverflow.com/users/3919052", "pm_score": 3, "selected": false, "text": "<pre><code>&lt;div class=\"outer\"&gt;\n &lt;div class=\"target\"&gt;\n &lt;div class=\"filler\"&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n&lt;/div&gt;\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</code></pre>\n\n<p>If the target element is absolutely positioned, you can center it by moving it 50% in one direction (<code>left: 50%</code>) and then transforming it 50% in the opposition direction (<code>transform:translateX(-50%)</code>). This works without defining the target element's width (or with <code>width:auto</code>). The parent element's position can be static, absolute, relative, or fixed.</p>\n" }, { "answer_id": 33843063, "author": "zloctb", "author_id": 1673376, "author_profile": "https://Stackoverflow.com/users/1673376", "pm_score": 2, "selected": false, "text": "<p>use css3 flexbox with justify-content:center;</p>\n\n<pre><code> &lt;div class=\"row\"&gt;\n &lt;div class=\"col\" style=\"background:red;\"&gt;content1&lt;/div&gt;\n &lt;div class=\"col\" style=\"\"&gt;content2&lt;/div&gt;\n &lt;/div&gt;\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</code></pre>\n" }, { "answer_id": 44135688, "author": "Frank N", "author_id": 444255, "author_profile": "https://Stackoverflow.com/users/444255", "pm_score": 5, "selected": false, "text": "<h1>six ways to skin that cat:</h1>\n\n<p><a href=\"https://i.stack.imgur.com/76Vpf.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/76Vpf.png\" alt=\"\"></a></p>\n\n<p><strong>Button one:</strong> anything of type <code>display: block</code> will assume the full parents width. (unless combined with <code>float</code> or a <code>display: flex</code> parent). True. Bad example.</p>\n\n<p><strong>Button 2:</strong> going for <code>display: inline-block</code> will lead to automatic (rather than full) width. You can then center using <code>text-align: center</code> <em>on the wrapping block</em>. <strong>Probably the easiest, and most widely compatible, even with ‘vintage’ browsers...</strong></p>\n\n<pre><code>.wrapTwo\n text-align: center;\n.two\n display: inline-block; // instantly shrinks width\n</code></pre>\n\n<p><strong>Button 3:</strong>\nNo need to put anything on the wrap. So perhaps this is the most elegant solution. Also works vertically. (Browser support for transtlate is <a href=\"https://caniuse.com/#search=transform\" rel=\"noreferrer\">good enough (≥IE9)</a> these days...).</p>\n\n<pre><code>position: relative;\ndisplay: inline-block; // instantly shrinks width\nleft: 50%;\ntransform: translateX(-50%);\n</code></pre>\n\n<p>Btw: Also a great way for vertically centering blocks of unknown height (in connection with absolute positioning).</p>\n\n<p><strong>Button 4:</strong>\nAbsolute positioning. Just make sure to reserve enough height in the wrapper, since noone else will (neither clearfix nor implicit...)</p>\n\n<pre><code>.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</code></pre>\n\n<p><strong>Button 5:</strong>\nfloat (which brings also block-level elements to dynamic width) and a relative shift. Although I've <em>never</em> seen this in the wild. Perhaps there are disadvantages...</p>\n\n<pre><code>.wrapFive\n &amp;: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</code></pre>\n\n<p><strong>Update:</strong> <strong>Button 6:</strong>\nAnd nowadays, you could also use flex-box. Note, that styles apply to the wrapper of the centered object.</p>\n\n<pre><code>.wrapSix\n display: flex\n justify-content: center\n</code></pre>\n\n<h2><a href=\"https://codepen.io/fnocke/pen/NjeVgg?editors=1100\" rel=\"noreferrer\">→ full source code (stylus syntax)</a></h2>\n" }, { "answer_id": 45145288, "author": "Byron", "author_id": 5311089, "author_profile": "https://Stackoverflow.com/users/5311089", "pm_score": -1, "selected": false, "text": "<p>my solution was:</p>\n\n<pre><code>.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</code></pre>\n" }, { "answer_id": 58773545, "author": "Shirley Ashby", "author_id": 4937353, "author_profile": "https://Stackoverflow.com/users/4937353", "pm_score": 0, "selected": false, "text": "<p>This is one way to center anything within a div not know the inner width of the elements.</p>\n\n<pre><code>#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</code></pre>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
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? 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. ```css .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; } ``` ```html <div class="product_container"> <div class="products" id="products"> <div id="product_15"> <img src="/images/ecommerce/card_default.png"> <div class="price">R$ 0,01</div> </div> <div id="product_15"> <img src="/images/ecommerce/card_default.png"> <div class="price">R$ 0,01</div> </div> <div id="product_15"> <img src="/images/ecommerce/card_default.png"> <div class="price">R$ 0,01</div> </div> </div> </div> ```
**Update 27 Feb 2015:** My original answer keeps getting voted up, but now I normally use @bobince's approach instead. ``` .child { /* This is the item to center... */ display: inline-block; } .parent { /* ...and this is its parent container. */ text-align: center; } ``` **My original post for historical purposes:** You might want to try this approach. ``` <div class="product_container"> <div class="outer-center"> <div class="product inner-center"> </div> </div> <div class="clear"/> </div> ``` Here's the matching style: ``` .outer-center { float: right; right: 50%; position: relative; } .inner-center { float: right; right: -50%; position: relative; } .clear { clear: both; } ``` [JSFiddle](http://jsfiddle.net/6350btvd/3/) The idea here is that you contain the content you want to center in two divs, an outer one and an inner one. You float both divs so that their widths automatically shrink to fit your content. Next, you relatively position the outer div with it's right edge in the center of the container. Lastly, you relatively position the inner div the opposite direction by half of its own width (actually the outer div's width, but they are the same). Ultimately that centers the content in whatever container it's in. You *may* need that empty div at the end if you depend on your "product" content to size the height for the "product\_container".
283,973
<p>I'm looking for a table or list of standard time estimations for developments in ABAP, something customizable in some variables according to the development team, complexity of project, etc...</p> <p>Something similar to:</p> <pre><code>Simple Module Pool -&gt; 10 hours Complex Module Pool -&gt; 30 hours Definition of Dictionary -&gt; (0,4 * number_of_tables * average_fields ) hours ALV Report -&gt; (2 * number_of_parameters) hours </code></pre> <p>I've searched but haven't found anything yet. I found AboveSoft Adaptive Estimator, what looks like a software tool to do what I need, but I prefer something... manual, an official or standard table.</p> <p>Do you know anything like that?</p> <p>Thank you in advance.</p> <p>Updated, as requested in comments by Rob S., to provide more information for future similar questions:</p> <p>What I'm looking for is a bunch of formulas, any metric system that can be applicable to (or even created for) time estimations on SAP development.</p> <p>I'm looking for a technic/tool/method to estimate SAP work, duration, cost, something similar to COCOMO II, FP, ESTIMACS or SLIM for SAP development.</p>
[ { "answer_id": 284175, "author": "epochwolf", "author_id": 16204, "author_profile": "https://Stackoverflow.com/users/16204", "pm_score": 4, "selected": true, "text": "<p>If I am reading this right, you are looking for a something to estimate how long it would take someone to program an application. I would doubt an official table actually exists. </p>\n\n<p>Development time is highly variable. Programmer experience, complexity of requirements, clarity of requirements, and dozens of other factors affect how much time development takes. So even if an official table exists, it may not be accurate. </p>\n" }, { "answer_id": 284207, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 1, "selected": false, "text": "<p>Let me guess... you're a project manager?</p>\n\n<p>There is no \"one way\" in programming, especially not in the highly specialized world of ABAP.</p>\n" }, { "answer_id": 284232, "author": "fmsf", "author_id": 26004, "author_profile": "https://Stackoverflow.com/users/26004", "pm_score": 1, "selected": false, "text": "<p>You can use Excel, Numbers, Gant charts, to do it manualy but you won't be able to find <strong>ANY</strong> automated thing for that, you'll have to do it yourself!</p>\n" }, { "answer_id": 284430, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 3, "selected": false, "text": "<p>the formulas you made up for illustration purposes in your question are as good as any others - in other words, you are asking for something that is pointless.</p>\n\n<p>the reason is that no formula can account for the truly important variables:</p>\n\n<ul>\n<li>your team</li>\n<li>your customer</li>\n<li>your environment</li>\n<li>your standards and best practices</li>\n</ul>\n\n<p>all of which will have a much larger drag coefficient than any other terms</p>\n\n<p>if you want accurate estimates, <em>ask your developers, and track their accuracy</em></p>\n\n<p>if you truly think that this sort of thing can be reduced to formulas, <strong>please resign as a project manager immediately</strong></p>\n" }, { "answer_id": 284465, "author": "ARemesal", "author_id": 36599, "author_profile": "https://Stackoverflow.com/users/36599", "pm_score": 2, "selected": false, "text": "<p>I'm not a project manager, I'm only an internship into a SAP team. Due to my experience in other languages I DO know that there are so many variables that it's impossible to automate a estimation of development time.</p>\n\n<p>But I've received the work of search for a \"standard table of estimated times\" for SAP/ABAP developments and, being a newbie in SAP, I imagined that will could exist any metric standarization.</p>\n\n<p>I think i've suffer a rough joke from my manager...</p>\n\n<p>Sorry for the inconvenience of my question.</p>\n" }, { "answer_id": 511217, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>HI, I understand your need...\nI'm project manager and estimation specialist, and what you're looking for is a table for estimate effort, por develop ABAP components...\nYou need a tabulate table, where based on complexity of the component and complexity of the change, yo can get an estimate effort. (this is based in one estimation method called Object Points <a href=\"http://yunus.hacettepe.edu.tr/~sencer/objectp.html\" rel=\"nofollow noreferrer\">http://yunus.hacettepe.edu.tr/~sencer/objectp.html</a>)</p>\n\n<p>This effor is only for Codding &amp; Unit Testing, you as project manager (or your project manager!) must to take this estimation as input, but you need to estimate another project factors to get the complete \"project estimation\"...</p>\n\n<p>I didn't find this table, or some estandar table for bencharmak, so I'm working in a project withing my software factory to build our own table...</p>\n\n<p>I hope this will be helpful for you..\nRegards,</p>\n" }, { "answer_id": 1120102, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>this simply doesn't exist. General metrics are so general that are useless. Project Managers should find other ways to make their life easier, like resign, but not try to quantify developments as if peeling potatoes.</p>\n" }, { "answer_id": 3919449, "author": "Dave", "author_id": 473885, "author_profile": "https://Stackoverflow.com/users/473885", "pm_score": 1, "selected": false, "text": "<p>Try AboveSoft's new tool, named AboveSoft Predictor. You can download it here www.abovesoft.com</p>\n\n<p>It connects to an SAP system and you can easily (graphically) generate your own estimation templates which are saved in SAP.</p>\n\n<p>Dave.</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283973", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36599/" ]
I'm looking for a table or list of standard time estimations for developments in ABAP, something customizable in some variables according to the development team, complexity of project, etc... Something similar to: ``` Simple Module Pool -> 10 hours Complex Module Pool -> 30 hours Definition of Dictionary -> (0,4 * number_of_tables * average_fields ) hours ALV Report -> (2 * number_of_parameters) hours ``` I've searched but haven't found anything yet. I found AboveSoft Adaptive Estimator, what looks like a software tool to do what I need, but I prefer something... manual, an official or standard table. Do you know anything like that? Thank you in advance. Updated, as requested in comments by Rob S., to provide more information for future similar questions: What I'm looking for is a bunch of formulas, any metric system that can be applicable to (or even created for) time estimations on SAP development. I'm looking for a technic/tool/method to estimate SAP work, duration, cost, something similar to COCOMO II, FP, ESTIMACS or SLIM for SAP development.
If I am reading this right, you are looking for a something to estimate how long it would take someone to program an application. I would doubt an official table actually exists. Development time is highly variable. Programmer experience, complexity of requirements, clarity of requirements, and dozens of other factors affect how much time development takes. So even if an official table exists, it may not be accurate.
283,977
<p>Does the C++ STL set data structure have a set difference operator?</p>
[ { "answer_id": 283984, "author": "Mr Fooz", "author_id": 25050, "author_profile": "https://Stackoverflow.com/users/25050", "pm_score": 4, "selected": false, "text": "<p>Yes, there is a <a href=\"http://www.sgi.com/tech/stl/set_difference.html\" rel=\"noreferrer\">set_difference</a> function in the algorithms header.</p>\n\n<p><strong>Edits:</strong></p>\n\n<p>FYI, the set data structure is able to efficiently use that algorithm, as stated in its <a href=\"http://www.sgi.com/tech/stl/set.html\" rel=\"noreferrer\">documentation</a>. The algorithm also works not just on sets but on any pair of iterators over sorted collections.</p>\n\n<p>As others have mentioned, this is an external algorithm, not a method. Presumably that's fine for your application.</p>\n" }, { "answer_id": 283989, "author": "Ian G", "author_id": 5764, "author_profile": "https://Stackoverflow.com/users/5764", "pm_score": 1, "selected": false, "text": "<p>Not as a method but there's the external algorithm function set_difference</p>\n\n<pre><code>template &lt;class InputIterator1, class InputIterator2, class OutputIterator&gt;\nOutputIterator set_difference(InputIterator1 first1, InputIterator1 last1,\n InputIterator2 first2, InputIterator2 last2,\n OutputIterator result);\n</code></pre>\n\n<p><a href=\"http://www.sgi.com/tech/stl/set_difference.html\" rel=\"nofollow noreferrer\">http://www.sgi.com/tech/stl/set_difference.html</a></p>\n" }, { "answer_id": 283991, "author": "LeppyR64", "author_id": 16592, "author_profile": "https://Stackoverflow.com/users/16592", "pm_score": 1, "selected": false, "text": "<p>Apparently, it does.</p>\n\n<p><a href=\"http://www.sgi.com/tech/stl/set_difference.html\" rel=\"nofollow noreferrer\">SGI - set_difference</a></p>\n" }, { "answer_id": 283996, "author": "philsquared", "author_id": 32136, "author_profile": "https://Stackoverflow.com/users/32136", "pm_score": 2, "selected": false, "text": "<p>Not an \"operator\" in the language sense, but there is the set_difference algorithm in the standard library:</p>\n\n<p><a href=\"http://www.cplusplus.com/reference/algorithm/set_difference.html\" rel=\"nofollow noreferrer\">http://www.cplusplus.com/reference/algorithm/set_difference.html</a></p>\n\n<p>Of course, the other basic set operations are present too - (union etc), as suggested by the \"See also\" section at the end of the linked article.</p>\n" }, { "answer_id": 284004, "author": "PierreBdR", "author_id": 7136, "author_profile": "https://Stackoverflow.com/users/7136", "pm_score": 7, "selected": false, "text": "<p>Yes there is, it is in <code>&lt;algorithm&gt;</code> and is called: <a href=\"http://en.cppreference.com/w/cpp/algorithm/set_difference\" rel=\"noreferrer\"><code>std::set_difference</code></a>. The usage is:</p>\n\n<pre><code>#include &lt;algorithm&gt;\n#include &lt;set&gt;\n#include &lt;iterator&gt;\n// ...\nstd::set&lt;int&gt; s1, s2;\n// Fill in s1 and s2 with values\nstd::set&lt;int&gt; result;\nstd::set_difference(s1.begin(), s1.end(), s2.begin(), s2.end(),\n std::inserter(result, result.end()));\n</code></pre>\n\n<p>In the end, the set <code>result</code> will contain the <code>s1-s2</code>.</p>\n" }, { "answer_id": 1236413, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>The chosen answer is correct, but has some syntax errors.</p>\n\n<p>Instead of </p>\n\n<pre><code>#include &lt;algorithms&gt;\n</code></pre>\n\n<p>use</p>\n\n<pre><code>#include &lt;algorithm&gt;\n</code></pre>\n\n<p>Instead of</p>\n\n<pre><code>std::insert_iterator(result, result.end()));\n</code></pre>\n\n<p>use</p>\n\n<pre><code>std::insert_iterator&lt;set&lt;int&gt; &gt;(result, result.end()));\n</code></pre>\n" }, { "answer_id": 14148344, "author": "user1830108", "author_id": 1830108, "author_profile": "https://Stackoverflow.com/users/1830108", "pm_score": -1, "selected": false, "text": "<p>can we just use</p>\n\n<pre><code> set_difference(set1.begin(), set1.end(), set2.begin(). set2,end(),std::back_inserter(result)).\n</code></pre>\n" }, { "answer_id": 19168776, "author": "strickli", "author_id": 1612703, "author_profile": "https://Stackoverflow.com/users/1612703", "pm_score": 2, "selected": false, "text": "<p>Once again, boost to the rescue:</p>\n\n<pre><code>#include &lt;string&gt;\n#include &lt;set&gt;\n#include &lt;boost/range/algorithm/set_algorithm.hpp&gt;\n\nstd::set&lt;std::string&gt; set0, set1, setDifference;\nboost::set_difference(set0, set1, std::inserter(setDifference, setDifference.begin());\n</code></pre>\n\n<p>setDifference will contain set0-set1.</p>\n" }, { "answer_id": 48995121, "author": "astraujums", "author_id": 841390, "author_profile": "https://Stackoverflow.com/users/841390", "pm_score": 2, "selected": false, "text": "<p>C++ does not define a set difference operator but you can define your own (using code given in other responses):</p>\n\n<pre><code>template&lt;class T&gt;\nset&lt;T&gt; operator -(set&lt;T&gt; reference, set&lt;T&gt; items_to_remove)\n{\n set&lt;T&gt; 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</code></pre>\n" }, { "answer_id": 49281192, "author": "Ben", "author_id": 874660, "author_profile": "https://Stackoverflow.com/users/874660", "pm_score": 1, "selected": false, "text": "<p>All of the answers I see here are O(n). Wouldn't this be better?:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>template &lt;class Key, class Compare, class Allocator&gt; \nstd::set&lt;Key, Compare, Allocator&gt; \nset_subtract(std::set&lt;Key, Compare, Allocator&gt;&amp;&amp; lhs,\n const std::set&lt;Key, Compare, Allocator&gt;&amp; 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</code></pre>\n\n<p>That seems to do the right thing. I'm not sure how to deal with the case that <code>Compare</code>'s type doesn't fully specify its behavior, as in if <code>Compare</code> is a <code>std::function&lt;bool(int,int)&gt;</code>, but aside from that, this seems to work right and should be like O((num overlapping) • log(<code>lhs.size()</code>)).</p>\n\n<p>In the case that <code>lhs</code> doesn't contain <code>*i</code>, it's probably possible to optimize further by doing an O(log(<code>rhs.size()</code>)) search for the next element of <code>rhs</code> that's >= the next element of <code>lhs</code>. That would optimize the case that <code>lhs = {0, 1000}</code> and <code>rhs = {1, 2, ..., 999}</code> to do the subtraction in log time.</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/283977", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28462/" ]
Does the C++ STL set data structure have a set difference operator?
Yes there is, it is in `<algorithm>` and is called: [`std::set_difference`](http://en.cppreference.com/w/cpp/algorithm/set_difference). The usage is: ``` #include <algorithm> #include <set> #include <iterator> // ... std::set<int> s1, s2; // Fill in s1 and s2 with values std::set<int> result; std::set_difference(s1.begin(), s1.end(), s2.begin(), s2.end(), std::inserter(result, result.end())); ``` In the end, the set `result` will contain the `s1-s2`.
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": "<p>This will copy an array of characters into an array of ints:</p>\n\n<pre><code>#include &lt;algorithm&gt;\nchar foo[9] = \"asdfasdf\";\nint bar[9];\nstd::copy(foo, foo+9, bar);\n</code></pre>\n\n<p><a href=\"http://www.cppreference.com/wiki/stl/algorithm/copy\" rel=\"nofollow noreferrer\">std::copy</a></p>\n\n<p>This assigns the values of a null terminated character array {'a', 's', 'd', 'f', 'a', 's', 'd', 'f', '\\0'} to an integer array, yielding {97, 115, 100, 102, 97, 115, 100, 102, 0}. Note that this includes the null termination of the original string.</p>\n\n<hr>\n\n<p>This will parse an array of strings, and put their integer values into an array of ints:</p>\n\n<pre><code>#include &lt;algorithm&gt;\n#include &lt;sstream&gt;\n#include &lt;string&gt;\n\ntemplate &lt;class T&gt;\nT parse(const std::string&amp; str)\n{\n T temp;\n std::istringstream iss(str);\n iss &gt;&gt; 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&lt;int&gt;);\n</code></pre>\n\n<p><a href=\"http://www.cppreference.com/wiki/stl/algorithm/transform\" rel=\"nofollow noreferrer\">std::transform</a></p>\n\n<p>This will transform each of the strings in the array foo into ints, and place them in the array of ints, bar.</p>\n" }, { "answer_id": 284087, "author": "jalf", "author_id": 33213, "author_profile": "https://Stackoverflow.com/users/33213", "pm_score": 3, "selected": false, "text": "<pre><code>#include &lt;algorithm&gt;\n\nstd::string foo[9];\nint bar[9];\n\nstd::transform(foo, foo+9, bar, MyMagicStringToIntFunction);\n</code></pre>\n\n<p>Where MyMagicStringToIntFunction is whichever function you wish to use to convert your strings to integers. Since you didn't specify how you wanted that to be done, I can't answer that part.</p>\n\n<p>That's my guess at what you want to do, but some more information would be helpful. (By \"string array do you mean an array of std::strings? And how would you like to perform the conversion?\"</p>\n\n<p>In any case, std::transform is my best best, but you'll have to fill in the gaps yourself.</p>\n" }, { "answer_id": 284102, "author": "Shadow2531", "author_id": 1697, "author_profile": "https://Stackoverflow.com/users/1697", "pm_score": 0, "selected": false, "text": "<p>If you want to use vectors instead of arrays, this might give you some ideas.</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;string&gt;\n#include &lt;vector&gt;\n#include &lt;iterator&gt;\n#include &lt;ostream&gt;\n#include &lt;algorithm&gt;\n#include &lt;sstream&gt;\nusing namespace std;\n\nint int_from_string(const string&amp; s) {\n istringstream ss(s);\n int i;\n ss &gt;&gt; i;\n return i;\n}\n\nvector&lt;int&gt; int_vec_from_string_vec(const vector&lt;string&gt;&amp; vstr) {\n vector&lt;int&gt; v(vstr.size());\n transform(vstr.begin(), vstr.end(), v.begin(), int_from_string);\n return v;\n}\n\nint main() {\n const vector&lt;string&gt; vstr(3, \"45\");\n const vector&lt;int&gt; vint = int_vec_from_string_vec(vstr);\n copy(vint.begin(), vint.end(), ostream_iterator&lt;int&gt;(cout, \"\\n\"));\n}\n</code></pre>\n" }, { "answer_id": 284105, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 2, "selected": false, "text": "<h3>string array -> int array</h3>\n\n<p>Loop over the string array, and convert each string successively into the corresponging integer using <code>std::istringstream</code></p>\n\n<pre><code>std::size_t const N = 3;\nstd::string a[N] = { \"10\", \"-2\", \"5\" };\nint b[N];\n\nfor(std::size_t i = 0; i &lt; N; i++) {\n std::istringstream sstream(a[i]);\n sstream &gt;&gt; b[i];\n}\n</code></pre>\n\n<p>If you have many values, the constant recreation of the stringstream can introduce substantial overhead. You can take it out of the loop.</p>\n\n<pre><code>std::stringstream sstream;\nfor(std::size_t i = 0; i &lt; N; i++) {\n sstream &lt;&lt; a[i];\n sstream &gt;&gt; b[i];\n sstream.clear(); \n sstream.seekp(0); sstream.seekg(0);\n}\n</code></pre>\n\n<h3>char array -> int array</h3>\n\n<p>If you want to convert a char array <code>a</code> into an int array <code>b</code>, you can do it like this:</p>\n\n<pre><code>std::size_t const N = 15;\nchar a[N] = { \"this is a test\" };\nint b[N];\n\nfor(std::size_t i = 0; i &lt; N; i++)\n b[i] = (int)(unsigned char) a[i];\n</code></pre>\n\n<p>The cast to <code>unsigned char</code> makes the values of the int array positive (useful if you want to convert extended 8 bit characters which will be represented in a signed 8bit char type as a negative number and would otherwise be negative integers too). If you don't want this behaivor, you can just omit that cast safely.</p>\n" }, { "answer_id": 284156, "author": "Jonathan Adelson", "author_id": 8092, "author_profile": "https://Stackoverflow.com/users/8092", "pm_score": 0, "selected": false, "text": "<p>If you want to explode a byte array to an integer array, you can just do it char by char:</p>\n\n<pre><code>char foo[10];\nint bar[10];\n\nfor(int i = 0; i &lt; 10; ++i) {\n bar[i] = (int)foo[i];\n}\n</code></pre>\n\n<p>But I'm guessing this isn't what you're looking for...</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
What is the best way to convert a fixed length string array to a fixed lengh integer array in C++ ?
This will copy an array of characters into an array of ints: ``` #include <algorithm> char foo[9] = "asdfasdf"; int bar[9]; std::copy(foo, foo+9, bar); ``` [std::copy](http://www.cppreference.com/wiki/stl/algorithm/copy) This assigns the values of a null terminated character array {'a', 's', 'd', 'f', 'a', 's', 'd', 'f', '\0'} to an integer array, yielding {97, 115, 100, 102, 97, 115, 100, 102, 0}. Note that this includes the null termination of the original string. --- This will parse an array of strings, and put their integer values into an array of ints: ``` #include <algorithm> #include <sstream> #include <string> template <class T> T parse(const std::string& str) { T temp; std::istringstream iss(str); iss >> temp; if(iss.bad() || iss.fail()) { // handle conversion failure } return temp; } ... std::string foo[3]; int bar[3]; foo[0] = "67"; foo[1] = "11"; foo[2] = "42"; std::transform(foo, foo+3, bar, parse<int>); ``` [std::transform](http://www.cppreference.com/wiki/stl/algorithm/transform) This will transform each of the strings in the array foo into ints, and place them in the array of ints, bar.
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": "<p>In your project definition there should be a <code>&lt;triggers&gt;</code> section. For our nightly builds we use the following:</p>\n\n<pre><code> &lt;triggers&gt;\n &lt;scheduleTrigger time=\"00:30\" buildCondition=\"IfModificationExists\"/&gt;\n &lt;/triggers&gt;\n</code></pre>\n\n<p>This tells CCNet to build at 0030 hours only if changes have been checked in since the last build. The important part here is the <code>buildCondition=\"IfModificationExists\"</code>, which can be used on any trigger type.</p>\n" }, { "answer_id": 284772, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>So scott you mean you have different definitions for nightly and normal builds or different triggers? </p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284029", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
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 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.... ``` <sourcecontrol type="vault" autoGetSource="true" applyLabel="true"> <executable>c:\program files\sourcegear\vault client\vault.exe</executable> <username>john</username> <password>password</password> <host>server</host> <repository>Default Repository</repository> <folder>$/Projects/xxx/xxx/xxx/source/xxx/xxx/xxx/xx.source</folder> <ssl>false</ssl> <timeout units="minutes">10</timeout> **<useWorkingDirectory>false</useWorkingDirectory>** <workingDirectory>C:\CCNET\build\xx\xx\</workingDirectory> </sourcecontrol> ``` The thing is that I don't want labels for build where there are no changes to code. Any help is appreciated.
In your project definition there should be a `<triggers>` section. For our nightly builds we use the following: ``` <triggers> <scheduleTrigger time="00:30" buildCondition="IfModificationExists"/> </triggers> ``` This tells CCNet to build at 0030 hours only if changes have been checked in since the last build. The important part here is the `buildCondition="IfModificationExists"`, which can be used on any trigger type.
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": "<p>Sounds to me like it's some kind of problem with UIBean referencing an out-of-date version of ConnectionBean. This is one problem with JSF - if you re-create a bean, JSF will not update the references in all your other beans.</p>\n\n<p>You could try getting a 'fresh' copy of the ConnectionBean each time. The following method will retrieve a backing bean by name:</p>\n\n<pre><code>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</code></pre>\n\n<p>Without knowing the specifics of your code and how you're using the beans it's difficult to be more specific!</p>\n" }, { "answer_id": 934097, "author": "Martlark", "author_id": 72668, "author_profile": "https://Stackoverflow.com/users/72668", "pm_score": 1, "selected": false, "text": "<p>@Phill Sacre \ngetApplication().createValueBinding is now deprecated. Use this function instead for JSF 1.2. To get a fresh copy of the bean.</p>\n\n<pre><code>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</code></pre>\n" }, { "answer_id": 9295181, "author": "Ondrej Bozek", "author_id": 668417, "author_profile": "https://Stackoverflow.com/users/668417", "pm_score": 0, "selected": false, "text": "<p>Define constant and static method in first session bean:</p>\n\n<pre><code>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</code></pre>\n\n<p>than use in second session bean like this:</p>\n\n<pre><code>... \nFirstBean firstBean = FirstBean.getCurrentInstance(); \n...\n</code></pre>\n\n<p>Better approach would be to use some <strong>Dependency Injection</strong> framework like JSF 2 or Spring.</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am currently modifying some jsf application. I have two beans. * connectionBean * UIBean 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. However when I try to set the connection parameters in the same session. My UIBean will still use the previous connectionBean information. It only will use after I invalidate the whole httpSession. Is there anyway I can make one session bean update another session bean?
Sounds to me like it's some kind of problem with UIBean referencing an out-of-date version of ConnectionBean. This is one problem with JSF - if you re-create a bean, JSF will not update the references in all your other beans. You could try getting a 'fresh' copy of the ConnectionBean each time. The following method will retrieve a backing bean by name: ``` protected Object getBackingBean( String name ) { FacesContext context = FacesContext.getCurrentInstance(); return context .getApplication().createValueBinding( String.format( "#{%s}", name ) ).getValue( context ); } ``` Without knowing the specifics of your code and how you're using the beans it's difficult to be more specific!
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": "<p>You can use simple print statements, or any other way of writing to standard output. You can also invoke the Python debugger anywhere in your tests.</p>\n<p>If you use <em><a href=\"https://web.archive.org/web/20081120065052/http://www.somethingaboutorange.com/mrl/projects/nose\" rel=\"nofollow noreferrer\">nose</a></em> to run your tests (which I recommend), it will collect the standard output for each test and only show it to you if the test failed, so you don't have to live with the cluttered output when the tests pass.</p>\n<p><em>nose</em> also has switches to automatically show variables mentioned in asserts, or to invoke the debugger on failed tests. For example, <code>-s</code> (<code>--nocapture</code>) prevents the capture of standard output.</p>\n" }, { "answer_id": 284192, "author": "monkut", "author_id": 24718, "author_profile": "https://Stackoverflow.com/users/24718", "pm_score": 4, "selected": false, "text": "<p>I don't think this is quite what you're looking for. There's no way to display variable values that don't fail, but this may help you get closer to outputting the results the way you want.</p>\n<p>You can use the <strong><a href=\"http://docs.python.org/library/unittest.html#id3\" rel=\"nofollow noreferrer\">TestResult object</a></strong> returned by the <strong>TestRunner.run()</strong> for results analysis and processing. Particularly, TestResult.errors and TestResult.failures</p>\n<p>About the TestResults Object:</p>\n<p><a href=\"http://docs.python.org/library/unittest.html#id3\" rel=\"nofollow noreferrer\">http://docs.python.org/library/unittest.html#id3</a></p>\n<p>And some code to point you in the right direction:</p>\n<pre><code>&gt;&gt;&gt; import random\n&gt;&gt;&gt; import unittest\n&gt;&gt;&gt;\n&gt;&gt;&gt; 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&gt;&gt;&gt; suite = unittest.TestLoader().loadTestsFromTestCase(TestSequenceFunctions)\n&gt;&gt;&gt; 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 &quot;&lt;stdin&gt;&quot;, 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 &quot;&lt;stdin&gt;&quot;, 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&gt;&gt;&gt;\n&gt;&gt;&gt; testResult.errors\n[(&lt;__main__.TestSequenceFunctions testMethod=testchoice&gt;, 'Traceback (most recent call last):\\n File &quot;&lt;stdin&gt;&quot;\n, line 11, in testchoice\\nZeroDivisionError: integer division or modulo by zero\\n')]\n&gt;&gt;&gt;\n&gt;&gt;&gt; testResult.failures\n[(&lt;__main__.TestSequenceFunctions testMethod=testshuffle&gt;, 'Traceback (most recent call last):\\n File &quot;&lt;stdin&gt;\n&quot;, line 8, in testshuffle\\nAssertionError: [0, 1, 2, 3, 4] != [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\\n')]\n&gt;&gt;&gt;\n</code></pre>\n" }, { "answer_id": 284283, "author": "Sam Corder", "author_id": 2351, "author_profile": "https://Stackoverflow.com/users/2351", "pm_score": 0, "selected": false, "text": "<p>Catch the exception that gets generated from the assertion failure. In your catch block you could output the data however you wanted to wherever. Then when you were done you could rethrow the exception. The test runner probably wouldn't know the difference.</p>\n<p>Disclaimer: I haven't tried this with Python's unit test framework, but I have with other unit test frameworks.</p>\n" }, { "answer_id": 284326, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 6, "selected": false, "text": "<p>We use the logging module for this.</p>\n<p>For example:</p>\n<pre><code>import logging\nclass SomeTest( unittest.TestCase ):\n def testSomething( self ):\n log= logging.getLogger( &quot;SomeTest.testSomething&quot; )\n log.debug( &quot;this= %r&quot;, self.this )\n log.debug( &quot;that= %r&quot;, self.that )\n self.assertEqual( 3.14, pi )\n\nif __name__ == &quot;__main__&quot;:\n logging.basicConfig( stream=sys.stderr )\n logging.getLogger( &quot;SomeTest.testSomething&quot; ).setLevel( logging.DEBUG )\n unittest.main()\n</code></pre>\n<p>That allows us to turn on debugging for specific tests which we know are failing and for which we want additional debugging information.</p>\n<p>My preferred method, however, isn't to spend a lot of time on debugging, but spend it writing more fine-grained tests to expose the problem.</p>\n" }, { "answer_id": 284706, "author": "Silverfish", "author_id": 27415, "author_profile": "https://Stackoverflow.com/users/27415", "pm_score": 2, "selected": false, "text": "<p>I think I might have been overthinking this. One way I've come up with that does the job, is simply to have a global variable that accumulates the diagnostic data.</p>\n<p>Something like this:</p>\n<pre><code>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(&quot;TestBar.runTest&quot;) = (f, t1, t2)\n self.fail(&quot;f.bar(t2) != 2&quot;)\n</code></pre>\n" }, { "answer_id": 288568, "author": "orip", "author_id": 37020, "author_profile": "https://Stackoverflow.com/users/37020", "pm_score": 3, "selected": false, "text": "<p>Another option - start a debugger where the test fails.</p>\n<p>Try running your tests with Testoob (it will run your unit test suite without changes), and you can use the '--debug' command line switch to open a debugger when a test fails.</p>\n<p>Here's a terminal session on Windows:</p>\n<pre class=\"lang-none prettyprint-override\"><code>C:\\work&gt; testoob tests.py --debug\nF\nDebugging for failure in test: test_foo (tests.MyTests.test_foo)\n&gt; c:\\python25\\lib\\unittest.py(334)failUnlessEqual()\n-&gt; (msg or '%r != %r' % (first, second))\n(Pdb) up\n&gt; c:\\work\\tests.py(6)test_foo()\n-&gt; 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 -&gt; self.assertEqual(x, y)\n[EOF]\n(Pdb)\n</code></pre>\n" }, { "answer_id": 13688397, "author": "Facundo Casco", "author_id": 181337, "author_profile": "https://Stackoverflow.com/users/181337", "pm_score": 6, "selected": false, "text": "<p>In Python 2.7 you could use an additional parameter, <code>msg</code>, to add information to the error message like this:</p>\n<pre><code>self.assertEqual(f.bar(t2), 2, msg='{0}, {1}'.format(t1, t2))\n</code></pre>\n<p>The official documentation is <a href=\"http://docs.python.org/2/library/unittest.html#unittest.TestCase.assertEqual\" rel=\"noreferrer\">here</a>.</p>\n" }, { "answer_id": 18791576, "author": "Max Murphy", "author_id": 2480661, "author_profile": "https://Stackoverflow.com/users/2480661", "pm_score": 1, "selected": false, "text": "<p>inspect.trace will let you get local variables after an exception has been thrown. You can then wrap the unit tests with a decorator like the following one to save off those local variables for examination during the post mortem.</p>\n<pre><code>import random\nimport unittest\nimport inspect\n\n\ndef store_result(f):\n &quot;&quot;&quot;\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 &quot;&quot;&quot;\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 &quot;&quot;&quot;\n Get all the results from a test suite\n &quot;&quot;&quot;\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</code></pre>\n<p>The last line will print the returned values where the test succeeded and the local variables, in this case x, when it fails:</p>\n<pre><code>{'test_choice': {'result': {7: 2}, 'success': True},\n 'test_sample': {'locals': {'self': &lt;__main__.TestSequenceFunctions testMethod=test_sample&gt;,\n 'x': 799},\n 'success': False},\n 'test_shuffle': {'result': {1: 2}, 'success': True}}\n</code></pre>\n" }, { "answer_id": 19538362, "author": "georgepsarakis", "author_id": 920374, "author_profile": "https://Stackoverflow.com/users/920374", "pm_score": -1, "selected": false, "text": "<p>Expanding on <a href=\"https://stackoverflow.com/questions/284043/outputting-data-from-unit-test-in-python/13688397#13688397\">Facundo Casco's answer</a>, this works quite well for me:</p>\n<pre><code>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 &quot;\\nMESSENGER OUTPUT: %s&quot; % str(e),\n</code></pre>\n" }, { "answer_id": 22187982, "author": "Orane", "author_id": 3305148, "author_profile": "https://Stackoverflow.com/users/3305148", "pm_score": 3, "selected": false, "text": "<p>The method I use is really simple. I just log it as a warning so it will actually show up.\n</p>\n\n<pre><code>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</code></pre>\n" }, { "answer_id": 28546167, "author": "not-a-user", "author_id": 2965738, "author_profile": "https://Stackoverflow.com/users/2965738", "pm_score": 2, "selected": false, "text": "<p>Use logging:</p>\n\n<pre><code>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</code></pre>\n\n<p>Usage:</p>\n\n<pre><code># 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</code></pre>\n\n<p>If you do not set <code>LOG_FILE</code>, logging will got to <code>stderr</code>.</p>\n" }, { "answer_id": 30038630, "author": "kenorb", "author_id": 55075, "author_profile": "https://Stackoverflow.com/users/55075", "pm_score": 2, "selected": false, "text": "<p>You can use <code>logging</code> module for that.</p>\n\n<p>So in the unit test code, use:</p>\n\n<pre><code>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</code></pre>\n\n<p>By default warnings and errors are outputted to <code>/dev/stderr</code>, so they should be visible on the console.</p>\n\n<p>To customize logs (such as formatting), try the following sample:</p>\n\n<pre><code># 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</code></pre>\n" }, { "answer_id": 36178137, "author": "fedorqui", "author_id": 1983854, "author_profile": "https://Stackoverflow.com/users/1983854", "pm_score": 3, "selected": false, "text": "<p>In these cases I use a <code>log.debug()</code> with some messages in my application. Since the default logging level is <code>WARNING</code>, such messages don't show in the normal execution.</p>\n<p>Then, in the unit test I change the logging level to <code>DEBUG</code>, so that such messages are shown while running them.</p>\n<pre><code>import logging\n\nlog.debug(&quot;Some messages to be shown just when debugging or unit testing&quot;)\n</code></pre>\n<p>In the unit tests:</p>\n<pre><code># Set log level\nloglevel = logging.DEBUG\nlogging.basicConfig(level=loglevel)\n</code></pre>\n<hr />\n<hr />\n<hr />\n<p>See a full example:</p>\n<p>This is <code>daikiri.py</code>, a basic class that implements a <em><a href=\"https://www.etymonline.com/word/daiquiri\" rel=\"nofollow noreferrer\">daikiri</a></em> with its name and price. There is method <code>make_discount()</code> that returns the price of that specific daikiri after applying a given discount:</p>\n<pre><code>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(&quot;Deducting discount...&quot;) # I want to see this message\n return self.price * percentage\n</code></pre>\n<p>Then, I create a unit test, <code>test_daikiri.py</code>, that checks its usage:</p>\n<pre><code>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(&quot;cuban&quot;, 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__ == &quot;__main__&quot;:\n unittest.main()\n</code></pre>\n<p>So when I execute it I get the <code>log.debug</code> messages:</p>\n<pre><code>$ python -m test_daikiri\nDEBUG:daikiri:Deducting discount...\n.\n----------------------------------------------------------------------\nRan 1 test in 0.000s\n\nOK\n</code></pre>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27415/" ]
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? 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. For example, suppose you had a class Foo, and were testing a method bar, using data from a list called testdata: ``` class TestBar(unittest.TestCase): def runTest(self): for t1, t2 in testdata: f = Foo(t1) self.assertEqual(f.bar(t2), 2) ``` 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.
We use the logging module for this. For example: ``` import logging class SomeTest( unittest.TestCase ): def testSomething( self ): log= logging.getLogger( "SomeTest.testSomething" ) log.debug( "this= %r", self.this ) log.debug( "that= %r", self.that ) self.assertEqual( 3.14, pi ) if __name__ == "__main__": logging.basicConfig( stream=sys.stderr ) logging.getLogger( "SomeTest.testSomething" ).setLevel( logging.DEBUG ) unittest.main() ``` That allows us to turn on debugging for specific tests which we know are failing and for which we want additional debugging information. My preferred method, however, isn't to spend a lot of time on debugging, but spend it writing more fine-grained tests to expose the problem.
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": "<p>You could try this:</p>\n\n<pre><code>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</code></pre>\n" }, { "answer_id": 284147, "author": "Todd", "author_id": 31940, "author_profile": "https://Stackoverflow.com/users/31940", "pm_score": 3, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);\n</code></pre>\n" }, { "answer_id": 19788063, "author": "user2956093", "author_id": 2956093, "author_profile": "https://Stackoverflow.com/users/2956093", "pm_score": -1, "selected": false, "text": "<p>Public Shared Sub WriteDBStatus(ByVal strString As String)</p>\n\n<pre><code> 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</code></pre>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284049", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7024/" ]
How do you get the current directory where your app is running?
You could try this: ``` using System.IO; using System.Reflection; namespace Utilities { static public class DirectoryHelper { static public string GetCurrentDirectory () { return Path.GetDirectoryName (Assembly.GetExecutingAssembly ().GetName ().CodeBase); } } } ```
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": 284062, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 0, "selected": false, "text": "<p>The only thing similar I can think of is in ASP.NET's register script block functions. They all have an overload that takes a bool for whether script tags should be added or not.</p>\n\n<p>Here's a link to the docs for one:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/bahh2fef.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/bahh2fef.aspx</a></p>\n" }, { "answer_id": 284130, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 1, "selected": false, "text": "<p>I'm adding my own answer here, so its more obvious what I'm trying to find out. The current idea I have settled on would perform as follows:</p>\n\n<pre><code>my $html=&lt;&lt;'EOF'\n&lt;script&gt;\n//&lt;!--&lt;![CDATA[\nfoo\n//]]&gt;--&gt;\n&lt;/script&gt;\nEOF\n#/# this line is here for the syntax highlighter\nmy $obj = parse($html); \nprint $obj-&gt;text(); \n# foo\n$obj-&gt;text(\"bar\");\nprint $obj-&gt;text(); \n# bar\nprint $obj-&gt;html(); \n# &lt;script&gt;\n# //&lt;!--&lt;![CDATA[\n# bar\n# //]]&gt;--&gt;\n# &lt;/script&gt;\n</code></pre>\n\n<p>Important points being: </p>\n\n<ol>\n<li>The xml/html/legacybrowser/bot protection mechanisms are removed for the internal code view. </li>\n<li>Inline code can thus be manipulated as if they were not there. </li>\n<li>Re-exporting modified code puts the protection mechanisms back on. </li>\n</ol>\n\n<p>if there was </p>\n\n<ol>\n<li>No Protection mechanisms</li>\n<li>Different ( ie: no // , or no <code>&lt;!-</code>, or no <code>&lt;!</code> ) parts</li>\n</ol>\n\n<p>the existing protections would be stripped and replaced with the bog-standard specified above. </p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284052", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15614/" ]
Imagine the following. 1. Html is parsed into a dom tree 2. Dom Nodes become available programmatically 3. Dom Nodes may-or-may-not be augmented programmatically 4. Augmented nodes are reserialised to html. I have primarily a question on how one would want the **"script"** tag to behave. ``` my $tree = someparser( $source ); .... print $somenode->text(); $somenode->text('arbitraryjavascript'); .... print $tree->serialize(); ``` Or to that effect. 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. What I'm wanting to do myself is this: ``` $somenode->text("verbatim"); ``` --> ``` <script> // <!-- <![CDATA[ verbatim // ]]> --> </script> ``` So that what i produce is both somewhat safe, and validation friendly. 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. 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. 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. 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. Its possible my entire reasoning is flawed here and the text contents should go totally unprocessed unless wanted to be processed. What behaviour do **you** look for in such a tool? Please point out anything in reasoning I may have overlooked. --- **TLDR Summary:** How should i programmatically handle the **escaping** mechanism in these scripts, namely the '`//<`!--<![CDATA[``' safey padding at either end, with respect to input/output
I'm adding my own answer here, so its more obvious what I'm trying to find out. The current idea I have settled on would perform as follows: ``` my $html=<<'EOF' <script> //<!--<![CDATA[ foo //]]>--> </script> EOF #/# this line is here for the syntax highlighter my $obj = parse($html); print $obj->text(); # foo $obj->text("bar"); print $obj->text(); # bar print $obj->html(); # <script> # //<!--<![CDATA[ # bar # //]]>--> # </script> ``` Important points being: 1. The xml/html/legacybrowser/bot protection mechanisms are removed for the internal code view. 2. Inline code can thus be manipulated as if they were not there. 3. Re-exporting modified code puts the protection mechanisms back on. if there was 1. No Protection mechanisms 2. Different ( ie: no // , or no `<!-`, or no `<!` ) parts the existing protections would be stripped and replaced with the bog-standard specified above.
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": 284062, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 0, "selected": false, "text": "<p>The only thing similar I can think of is in ASP.NET's register script block functions. They all have an overload that takes a bool for whether script tags should be added or not.</p>\n\n<p>Here's a link to the docs for one:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/bahh2fef.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/bahh2fef.aspx</a></p>\n" }, { "answer_id": 284130, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 1, "selected": false, "text": "<p>I'm adding my own answer here, so its more obvious what I'm trying to find out. The current idea I have settled on would perform as follows:</p>\n\n<pre><code>my $html=&lt;&lt;'EOF'\n&lt;script&gt;\n//&lt;!--&lt;![CDATA[\nfoo\n//]]&gt;--&gt;\n&lt;/script&gt;\nEOF\n#/# this line is here for the syntax highlighter\nmy $obj = parse($html); \nprint $obj-&gt;text(); \n# foo\n$obj-&gt;text(\"bar\");\nprint $obj-&gt;text(); \n# bar\nprint $obj-&gt;html(); \n# &lt;script&gt;\n# //&lt;!--&lt;![CDATA[\n# bar\n# //]]&gt;--&gt;\n# &lt;/script&gt;\n</code></pre>\n\n<p>Important points being: </p>\n\n<ol>\n<li>The xml/html/legacybrowser/bot protection mechanisms are removed for the internal code view. </li>\n<li>Inline code can thus be manipulated as if they were not there. </li>\n<li>Re-exporting modified code puts the protection mechanisms back on. </li>\n</ol>\n\n<p>if there was </p>\n\n<ol>\n<li>No Protection mechanisms</li>\n<li>Different ( ie: no // , or no <code>&lt;!-</code>, or no <code>&lt;!</code> ) parts</li>\n</ol>\n\n<p>the existing protections would be stripped and replaced with the bog-standard specified above. </p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284060", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11568/" ]
I am using a simple [Zend\_Auth](http://framework.zend.com/manual/en/zend.auth.html) setup to authenticate users for one of my applications, using a check in the preDispatch() method in a [controller plugin](http://framework.zend.com/manual/en/zend.controller.plugins.html). When anonymous users navigate to ``` /users/view/id/6 ``` for example, they should be redirected to the above URI after authentication. What is the best way to do this? I'd prefer not to store `$_SERVER['REQUEST_URI']` 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. Any thoughts?
I'm adding my own answer here, so its more obvious what I'm trying to find out. The current idea I have settled on would perform as follows: ``` my $html=<<'EOF' <script> //<!--<![CDATA[ foo //]]>--> </script> EOF #/# this line is here for the syntax highlighter my $obj = parse($html); print $obj->text(); # foo $obj->text("bar"); print $obj->text(); # bar print $obj->html(); # <script> # //<!--<![CDATA[ # bar # //]]>--> # </script> ``` Important points being: 1. The xml/html/legacybrowser/bot protection mechanisms are removed for the internal code view. 2. Inline code can thus be manipulated as if they were not there. 3. Re-exporting modified code puts the protection mechanisms back on. if there was 1. No Protection mechanisms 2. Different ( ie: no // , or no `<!-`, or no `<!` ) parts the existing protections would be stripped and replaced with the bog-standard specified above.
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": "<p>As far as I know, there is no built-in functionality that will allow this type of path resolution. Your best option is to dynamically determine the applications executing directory and concatenate to it your images path. You don't want to use <code>Environment.CurrentDirectory</code> specifically for the reasons you mention - the current directory may not always be correct for this situation.</p>\n\n<p>The safest code I've found to find the executing assembly location is this:</p>\n\n<pre><code>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</code></pre>\n" }, { "answer_id": 284088, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 0, "selected": false, "text": "<p>2 options:</p>\n\n<ul>\n<li>The code that uses the setting can resolve the setting against the directory of the current executing assembly.</li>\n<li>You can create your own type that serializes as a string relative to the executing assembly, and has an accessor for the full path that will resolve against the directory of the current executing assembly.</li>\n</ul>\n\n<p>Code sample:</p>\n\n<pre><code>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</code></pre>\n\n<p>The nice thing about this code is that it allows a fully qualified path, or a relative path, in your settings. If you need the path to be relative to a different assembly, you can change which assembly's location you use - <code>GetExecutingAssembly()</code> will give you the location of the assembly with the code you're running, and <code>GetCallingAssembly()</code> would be good if you go with option 2.</p>\n" }, { "answer_id": 284089, "author": "Harper Shelby", "author_id": 21196, "author_profile": "https://Stackoverflow.com/users/21196", "pm_score": 1, "selected": false, "text": "<p>Are you looking for Application.ExecutablePath ? That should tell you where the application's executable is, remove the executable name, and then append your path to it.</p>\n" }, { "answer_id": 487464, "author": "Sire", "author_id": 2440, "author_profile": "https://Stackoverflow.com/users/2440", "pm_score": 0, "selected": false, "text": "<p>This seem to work in both WinForms and ASP.NET (gives the path to the <strong>config file</strong>):</p>\n\n<pre><code>new System.IO.FileInfo(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile).Directory;\n</code></pre>\n\n<p>For Windows and Console applications, the obvious way is by using:</p>\n\n<pre><code>Application.StartupPath\n</code></pre>\n" }, { "answer_id": 1516760, "author": "Graviton", "author_id": 3834, "author_profile": "https://Stackoverflow.com/users/3834", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://itscommonsensestupid.blogspot.com/2008/05/how-to-get-file-path-of-executing.html\" rel=\"nofollow noreferrer\">I suggest you</a> to use Assembly.CodeBase, as shown below:</p>\n\n<pre><code>public static string RealAssemblyFilePath()\n{\n string dllPath=Assembly.GetExecutingAssembly().CodeBase.Substring(8);\n return dllPath;\n}\n</code></pre>\n\n<p>You can try <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.application.executablepath.aspx\" rel=\"nofollow noreferrer\">Application.ExecutablePath</a>. But you need to make reference to System.Windows.Forms. This may not be a good idea if you want your class library to steer clear of forms and UI stuff.</p>\n\n<p>You can try the <a href=\"http://msdn.microsoft.com/en-us/library/system.reflection.assembly.location%28VS.71%29.aspx\" rel=\"nofollow noreferrer\">Assembly.GetExecutingAssembly().Location</a>. But if, somehow, you do a \"Shadow Copy\" before you run your application (like the default NUnit behavior), then this property will return you the shadow copy location, not the real, physical location.</p>\n\n<p>The best way is to implement a function that calls the CodeBase property of Assembly object and chop off the irrelevant portion of the string. </p>\n" }, { "answer_id": 6281022, "author": "Eamon Nerbonne", "author_id": 42921, "author_profile": "https://Stackoverflow.com/users/42921", "pm_score": 0, "selected": false, "text": "<p>I use the following two methods to help with that:</p>\n\n<pre><code>public static IEnumerable&lt;DirectoryInfo&gt; 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 =&gt; Path.Combine(dir.FullName + @\"\\\", relpath))\n .Where(Directory.Exists)\n .Select(path =&gt; new DirectoryInfo(path))\n .FirstOrDefault();\n}\n</code></pre>\n\n<p>The reason to look at parent dirs to to be easier in use during development when various build scripts end up sticking things in directories like <code>bin\\x64\\Release\\NonsensePath\\</code>.</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284061", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20489/" ]
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.
As far as I know, there is no built-in functionality that will allow this type of path resolution. Your best option is to dynamically determine the applications executing directory and concatenate to it your images path. You don't want to use `Environment.CurrentDirectory` specifically for the reasons you mention - the current directory may not always be correct for this situation. The safest code I've found to find the executing assembly location is this: ``` public string ExecutingAssemblyPath() { Assembly actualAssembly = Assembly.GetEntryAssembly(); if (this.actualAssembly == null) { actualAssembly = Assembly.GetCallingAssembly(); } return actualAssembly.Location; } ```
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": "<p>Write an extension method.</p>\n\n<pre><code>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</code></pre>\n" }, { "answer_id": 284081, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 2, "selected": false, "text": "<p>I'd use an alternative implementation <code>TryParse</code> which returns an <code>int?</code>:</p>\n\n<pre><code>public static int? TryParseInt32(string x)\n{\n int value;\n return int.TryParse(x, out value) ? value : (int?) null;\n}\n</code></pre>\n\n<p>Then you can write:</p>\n\n<pre><code>var p = new Person { RecordID = Helpers.TryParseInt32(row[\"ContactID\"].ToString()) ?? 0 };\n</code></pre>\n\n<p>(Or use a different default value, if you want - either way it'll be visible in your code.)</p>\n" }, { "answer_id": 284097, "author": "Ali Ersöz", "author_id": 4215, "author_profile": "https://Stackoverflow.com/users/4215", "pm_score": 0, "selected": false, "text": "<p>I suggest separate the TryParse part from initializer. It will be more readable.</p>\n\n<pre><code>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</code></pre>\n" }, { "answer_id": 54084299, "author": "alanthinker", "author_id": 10881894, "author_profile": "https://Stackoverflow.com/users/10881894", "pm_score": 0, "selected": false, "text": "<pre><code>private static void TryToDecimal(string str, Action&lt;decimal&gt; 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) =&gt; { st.LastTradePrice = x; });\nTryToDecimal(strList[3], (x) =&gt; { st.LastClosedPrice = x; });\nTryToDecimal(strList[6], (x) =&gt; { st.TopPrice = x; });\nTryToDecimal(strList[7], (x) =&gt; { st.BottomPrice = x; });\nTryToDecimal(strList[10], (x) =&gt; { st.PriceChange = x; });\n</code></pre>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17692/" ]
I'm currently refactoring code to replace Convert.To's to TryParse. I've come across the following bit of code which is creating and assigning a property to an object. ``` List<Person> list = new List<Person>(); foreach (DataRow row in dt.Rows) { var p = new Person{ RecordID = Convert.ToInt32(row["ContactID"]) }; list.Add(p); } ``` What I've come up with as a replacement is: ``` var p = new Person { RecordID = Int32.TryParse(row["ContactID"].ToString(), out RecordID) ? RecordID : RecordID }; ``` Any thoughts, opinions, alternatives to what I've done?
Write an extension method. ``` public static Int32? ParseInt32(this string str) { Int32 k; if(Int32.TryParse(str, out k)) return k; return null; } ```
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": "<p>If you really want to use ReadOnlyCollection&lt;T&gt;, the issue is that the constructor of ReadOnlyCollection&lt;T&gt; takes an IList&lt;T&gt;, while the KeyCollection of the Dictionary is only a ICollection&lt;T&gt;.</p>\n\n<p>So if you want to wrap the KeyCollection in a ReadOnlyCollection, you'll have to create an adapter (or wrapper) type, implementing IList&lt;T&gt;, wrapping the KeyCollection. So it would look like:</p>\n\n<pre><code>var dictionary = ...;\nvar readonly_keys = new ReadOnlyCollection&lt;T&gt; (new CollectionListWrapper&lt;T&gt; (dictionary.Keys)\n);\n</code></pre>\n\n<p>Not very elegant though, especially as the KeyCollection is already a readonly collection, and that you could simply pass it around as an ICollection&lt;T&gt; :)</p>\n" }, { "answer_id": 284159, "author": "Phil Jenkins", "author_id": 35496, "author_profile": "https://Stackoverflow.com/users/35496", "pm_score": 0, "selected": false, "text": "<p>It's ugly, but this will do it</p>\n\n<pre><code>Dictionary&lt;int,string&gt; dict = new Dictionary&lt;int, string&gt;();\n...\nReadOnlyCollection&lt;int&gt; roc = new ReadOnlyCollection&lt;int&gt;((new List&lt;int&gt;((IEnumerable&lt;int&gt;)dict.Keys)));\n</code></pre>\n" }, { "answer_id": 284169, "author": "Winston Smith", "author_id": 35086, "author_profile": "https://Stackoverflow.com/users/35086", "pm_score": 1, "selected": false, "text": "<p>Assuming you are using C# 3.0 and you have:</p>\n\n<p>Dictionary&lt; T,S > d;</p>\n\n<p>Then</p>\n\n<p>ReadOnlyCollection&lt; T > r = new ReadOnlyCollection&lt; T >( d.Keys.ToList() );</p>\n\n<p>You will also need to import the System.Linq namespace. </p>\n" }, { "answer_id": 284218, "author": "Tamas Czinege", "author_id": 8954, "author_profile": "https://Stackoverflow.com/users/8954", "pm_score": 1, "selected": false, "text": "<p>Unfortunately you cannot to that direcly as far as I know as <code>KeyCollection&lt;T&gt;</code> does not expose anything that would allow you to do this easily.</p>\n\n<p>You could, however, subclass <code>ReadOnlyCollection&lt;T&gt;</code> so that its constructor receives the dictionary itself and override the appropriate methods so that it exposes the Dictionary's items as if they were its own items.</p>\n" }, { "answer_id": 284488, "author": "bruno conde", "author_id": 31136, "author_profile": "https://Stackoverflow.com/users/31136", "pm_score": 3, "selected": false, "text": "<p>DrJokepu said that it might be difficult to implement a wrapper for Keys Collection. But, in this particular case, I think the implementation is not so difficult because, as we know, this is a read-only wrapper. </p>\n\n<p>This allows us to ignore some methods that, in other case, would be hard to implement.</p>\n\n<p>Here's a quick implementation of the wrapper for Dictionary.KeyCollection :</p>\n\n<pre><code>class MyListWrapper&lt;T, TValue&gt; : IList&lt;T&gt;\n{\n private Dictionary&lt;T, TValue&gt;.KeyCollection keys;\n\n public MyListWrapper(Dictionary&lt;T, TValue&gt;.KeyCollection keys)\n {\n this.keys = keys;\n }\n\n #region IList&lt;T&gt; Members\n\n public int IndexOf(T item)\n {\n if (item == null)\n throw new ArgumentNullException();\n IEnumerator&lt;T&gt; 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&lt;T&gt; e = keys.GetEnumerator();\n if (index &lt; 0 || index &gt; keys.Count)\n throw new IndexOutOfRangeException();\n int i = 0;\n while (e.MoveNext() &amp;&amp; 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&lt;T&gt; 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&lt;T&gt; Members\n\n public IEnumerator&lt;T&gt; 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</code></pre>\n\n<p>This might not be the best implementation for these methods :) but it was just for proving that this might be done.</p>\n" }, { "answer_id": 37572467, "author": "Mark Sowul", "author_id": 155892, "author_profile": "https://Stackoverflow.com/users/155892", "pm_score": 1, "selected": false, "text": "<p>For the record, in .NET 4.6, the <code>KeyCollection&lt;T&gt;</code> implements <code>IReadOnlyCollection&lt;T&gt;</code>, so if you use that interface, you can still reflect changes to the dictionary, still get O(1) contains*, and because the interface is covariant, you can return <code>IReadOnlyCollection&lt;some base type&gt;</code></p>\n<p>*<code>Enumerable.Contains&lt;T&gt;</code> does an <code>as</code> cast on the <code>IEnumerable</code> to forward it to <code>ICollection&lt;T&gt;.Contains</code> if available. See &quot;remarks&quot; on Enumerable.Contains: <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.contains#system-linq-enumerable-contains-1(system-collections-generic-ienumerable((-0))-0)\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.contains#system-linq-enumerable-contains-1(system-collections-generic-ienumerable((-0))-0)</a>. <code>Dictionary.KeyCollection</code> also implements <code>ICollection&lt;T&gt;</code></p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6091/" ]
My class contains a `Dictionary<T, S> dict`, and I want to expose a `ReadOnlyCollection<T>` of the keys. How can I do this without copying the `Dictionary<T, S>.KeyCollection dict.Keys` to an array and then exposing the array as a `ReadOnlyCollection`? I want the `ReadOnlyCollection` 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! Edit: I'm using C# 2.0, so don't have extension methods such as .ToList (easily) available.
If you really want to use ReadOnlyCollection<T>, the issue is that the constructor of ReadOnlyCollection<T> takes an IList<T>, while the KeyCollection of the Dictionary is only a ICollection<T>. So if you want to wrap the KeyCollection in a ReadOnlyCollection, you'll have to create an adapter (or wrapper) type, implementing IList<T>, wrapping the KeyCollection. So it would look like: ``` var dictionary = ...; var readonly_keys = new ReadOnlyCollection<T> (new CollectionListWrapper<T> (dictionary.Keys) ); ``` Not very elegant though, especially as the KeyCollection is already a readonly collection, and that you could simply pass it around as an ICollection<T> :)
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": "<p>You don't store hexadecimal values in strings. </p>\n\n<p>You can, but it would just be that, a string, and would have to be cast to an integer or a byte to actually read its value.</p>\n\n<p>You can assign a hexadecimal value as a literal to an int or a byte though:</p>\n\n<pre><code>Byte value = 0x0FF;\nint value = 0x1B;\n</code></pre>\n\n<p>So, its easily possible to pass an hexadecimal literal into your string: </p>\n\n<pre><code>string foo = String.Format(\"{0} hex test\", 0x0BB);\n</code></pre>\n\n<p>Which would create this string \"126 hex test\". </p>\n\n<p>But I don't think that's what you wanted?</p>\n" }, { "answer_id": 284243, "author": "Nicolas Repiquet", "author_id": 36896, "author_profile": "https://Stackoverflow.com/users/36896", "pm_score": 3, "selected": false, "text": "<p>There's an '\\u' escape code for hexadecimal <strong>16 bits</strong> unicode character codes.</p>\n\n<pre><code>Console.WriteLine( \"Look, I'm so happy : \\u263A\" );\n</code></pre>\n" }, { "answer_id": 284374, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 5, "selected": false, "text": "<p>Please try to avoid the <code>\\x</code> escape sequence. It's difficult to read because where it stops depends on the data. For instance, how much difference is there at a glance between these two strings?</p>\n\n<pre><code>\"\\x9Good compiler\"\n\"\\x9Bad compiler\"\n</code></pre>\n\n<p>In the former, the \"\\x9\" is tab - the escape sequence stops there because 'G' is not a valid hex character. In the second string, \"\\x9Bad\" is all an escape sequence, leaving you with some random Unicode character and \" compiler\".</p>\n\n<p>I suggest you use the \\u escape sequence instead:</p>\n\n<pre><code>\"\\u0009Good compiler\"\n\"\\u0009Bad compiler\"\n</code></pre>\n\n<p>(Of course for tab you'd use <code>\\t</code> but I hope you see what I mean...)</p>\n\n<p>This is somewhat aside from the original question of course, but that's been answered already :)</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36922/" ]
How do I build an escape sequence string in hexadecimal notation. Example: ``` string s = "\x1A"; // this will create the hex-value 1A or dec-value 26 ``` I want to be able to build strings with hex-values between 00 to FF like this (in this example 1B) ``` string s = "\x" + "1B"; // Unrecognized escape sequence ``` Maybe there's another way of making hexadecimal strings...
You don't store hexadecimal values in strings. You can, but it would just be that, a string, and would have to be cast to an integer or a byte to actually read its value. You can assign a hexadecimal value as a literal to an int or a byte though: ``` Byte value = 0x0FF; int value = 0x1B; ``` So, its easily possible to pass an hexadecimal literal into your string: ``` string foo = String.Format("{0} hex test", 0x0BB); ``` Which would create this string "126 hex test". But I don't think that's what you wanted?
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": "<p>If you don't care about the namespace, you can use the XPath `local-name()' function:</p>\n\n<pre><code>&lt;xsl:for-each select=\"//*[local-name() = 'Row']\"&gt;\n &lt;xsl:copy-of select=\".\"/&gt;\n&lt;/xsl:for-each&gt;\n</code></pre>\n\n<p>Alternatively the same same thing can be expressed like this. I'm not certain if this is standard XPath and if all XPath implementations support it (ColdFusion does, so probably Java does as well). Maybe someone knows if this conforms to any standard.</p>\n\n<pre><code>&lt;xsl:for-each select=\"//:Row\"&gt;\n &lt;xsl:copy-of select=\".\"/&gt;\n&lt;/xsl:for-each&gt;\n</code></pre>\n" }, { "answer_id": 284145, "author": "ckarras", "author_id": 5688, "author_profile": "https://Stackoverflow.com/users/5688", "pm_score": 6, "selected": true, "text": "<p>Declare a namespace prefix for the namespace in your XSLT and then <code>select</code> using that prefix:</p>\n\n<pre><code>&lt;xsl:stylesheet ... xmlns:os=\"urn:schemas-microsoft-com:office:spreadsheet\"&gt;\n ... \n &lt;xsl:for-each select=\"//os:Row\"&gt;\n ...\n &lt;/xsl:for-each&gt;\n ...\n&lt;/xsl:stylesheet&gt;\n</code></pre>\n\n<p>This usually results in XPaths that are easy to read. However, XSLT/XPath tools generate the following, equivalent code:</p>\n\n<pre><code>&lt;xsl:for-each select=\"//*[local-name()='Row' = and namespace-uri()='urn:schemas-microsoft-com:office:spreadsheet']\"&gt;\n ...\n&lt;/xsl:for-each&gt;\n</code></pre>\n" }, { "answer_id": 284231, "author": "ChuckB", "author_id": 28605, "author_profile": "https://Stackoverflow.com/users/28605", "pm_score": 3, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/users/18771/tomalak\">Tomalek</a> and <a href=\"https://stackoverflow.com/users/5688/ckarras\">ckarras</a> give good answers, but I want to clarify the reasons behind them.</p>\n\n<p>The elements you aren't matching are in the default namespace of the scope in which they occur in the doc, that is, they are in the namespace declared for that scope without a prefix (e.g.</p>\n\n<pre><code>xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"\n</code></pre>\n\n<p>on the <code>Workbook</code> element). Even though the tagnames lack a namespace prefix, they are in a namespace.</p>\n\n<p>However, XPath requires that all names of elements in a namespace be qualified with a prefix, or that the namespace be specified explicitly with <code>namespace-uri()</code> in a predicate. Hence, you must either use the <code>local-name()</code> function in a predicate to match the element name (and use the <code>namespace-uri()</code> function as well if there is a danger of name collisions across namespaces), or you must declare each namespace in which you wish to match elements in XPaths with a prefix, and qualify the element names with their namespace prefixes in the XPath expressions.</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284094", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2017/" ]
I have an XML document something like ::: ``` <?xml version="1.0" encoding="utf-8"?> <?mso-application progid="Excel.Sheet"?> <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"> <Worksheet ss:Name="Worksheet1"> <Table> <Column ss:Width="100"></Column> <Row> <Cell ss:Index="1" ss:StyleID="headerStyle"> <Data ss:Type="String">Submitted By</Data> </Cell> </Row> <Row> <Cell ss:Index="1" ss:StyleID="alternatingItemStyle"> <Data ss:Type="String">Value1-0</Data> </Cell> </Row> </Table> <AutoFilter xmlns="urn:schemas-microsoft-com:office:excel" x:Range="R1C1:R1C5"></AutoFilter> </Worksheet> </Workbook> ``` The problem is when trying to select Rows with ``` <xsl:for-each select="//Row"> <xsl:copy-of select="."/> </xsl:for-each> ``` 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?
Declare a namespace prefix for the namespace in your XSLT and then `select` using that prefix: ``` <xsl:stylesheet ... xmlns:os="urn:schemas-microsoft-com:office:spreadsheet"> ... <xsl:for-each select="//os:Row"> ... </xsl:for-each> ... </xsl:stylesheet> ``` This usually results in XPaths that are easy to read. However, XSLT/XPath tools generate the following, equivalent code: ``` <xsl:for-each select="//*[local-name()='Row' = and namespace-uri()='urn:schemas-microsoft-com:office:spreadsheet']"> ... </xsl:for-each> ```
284,149
<p>Here is my problem. I am hitting a web service (hosted on a Java based server) that will only accept text encoded Requests, but it returns MTOM Responses. What I've found is that if I set the web service to RequireMtom, it sends an Mtom request! Unfortunately, the server chokes on an Mtom request and returns a 500 error. However, if I set it to Text message encoding, the response comes back correctly with a multipart MIME (MTOM) response that errors out the Microsoft Web Service API (sample error below). It's expecting a text encoded response because the request was text encoded. I would like to RequireMtom on the response only. Can anyone help me here?</p> <p><em>As you can see in the error below (which occurs with the standard web services API, WCF or WSE3), when I send the request with text encoding, the response comes back correctly with all the data in a multipart/related response, but the .net framework chokes!</em></p> <p><strong>ERROR MESSAGE WITH WSE:</strong></p> <pre><code>Client found response content type of 'multipart/related; type="text/xml"; start="&lt;1AE0B46A85B0186B5D136D12E1EE286E&gt;"; boundary="----=_Part_209564_1891070135.1226526701833"', but expected 'text/xml'. The request failed with the error message: at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall) at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters) at TestWseService.AdesaJasperWse.ManagementServiceService.runReport(String requestXmlString) in C:\Documents and Settings\xxx\My Documents\Visual Studio 2005\Projects\TestWseService\Web References\AdesaJasperWse\Reference.cs:line 229 at TestWseService.Form1.buttonRunService_Click(Object sender, EventArgs e) in C:\Documents and Settings\xxx\My Documents\Visual Studio 2005\Projects\TestWseService\Form1.cs:line 42 </code></pre> <p><strong>ERROR MESSAGE WITH WCF</strong></p> <pre><code>The content type multipart/related; type="text/xml"; start="&lt;30ED8FE3004CDA67723CC7164A6CFEEC&gt;"; boundary="----=_Part_209545_389093169.1226526546805" of the response message does not match the content type of the binding (text/xml; charset=utf-8). If using a custom encoder, be sure that the IsContentTypeSupported method is implemented properly. The first 1024 bytes of the response were: Server stack trace: at System.ServiceModel.Channels.HttpChannelUtilities.ValidateRequestReplyResponse(HttpWebRequest request, HttpWebResponse response, HttpChannelFactory factory, WebException responseException) at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout) at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout) at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout) at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout) at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs) at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation) at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message) </code></pre> <p><strong>Request (with Text Message Encoding):</strong></p> <pre><code>POST /jasperserver-pro/services/repository HTTP/1.1 Content-Type: text/xml; charset=utf-8 VsDebuggerCausalityData: uIDPo7V2+runH+xGudbec7ueUU8AAAAA7H9vL3stlkCBofMgLa5DWkQOHHpBdy1Ek6P6nXx7FpsACQAA SOAPAction: "" Authorization: Basic amFzcGVyYWRtaW46akBzcDNyQGRtJW4= Host: reports.dev.xxx.com Content-Length: 789 Expect: 100-continue &lt;s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"&gt;&lt;s:Body s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;&lt;q1:runReport xmlns:q1="http://axis2.ws.jasperserver.jaspersoft.com"&gt;&lt;requestXmlString xsi:type="xsd:string"&gt;&amp;lt;request operationName="runReport" locale="en"&amp;gt;&amp;#xD; &amp;lt;argument name="RUN_OUTPUT_FORMAT"&amp;gt;HTML&amp;lt;/argument&amp;gt;&amp;#xD; &amp;lt;resourceDescriptor name="" wsType="" uriString="/BusinessIntelligence/MOS/Reports/dotnettest" isNew="false"&amp;gt;&amp;#xD; &amp;lt;label&amp;gt;null&amp;lt;/label&amp;gt;&amp;#xD; &amp;lt;parameter name="testparam"&amp;gt;1&amp;lt;/parameter&amp;gt;&amp;#xD; &amp;lt;/resourceDescriptor&amp;gt;&amp;#xD; &amp;lt;/request&amp;gt;&lt;/requestXmlString&gt;&lt;/q1:runReport&gt;&lt;/s:Body&gt;&lt;/s:Envelope&gt; </code></pre> <p><strong>Response (with Text Message Encoding):</strong></p> <pre><code>HTTP/1.1 200 OK Date: Wed, 12 Nov 2008 21:49:04 GMT Server: IBM_HTTP_Server Surrogate-Control: no-store Set-Cookie: JSESSIONID=0000z5pH1xEMyulueASctjru2qe:13kftunf6; Path=/ Expires: Thu, 01 Dec 1994 16:00:00 GMT Cache-Control: no-cache="set-cookie, set-cookie2" Content-Length: 2580 Content-Type: multipart/related; type="text/xml"; start="&lt;30ED8FE3004CDA67723CC7164A6CFEEC&gt;"; boundary="----=_Part_209545_389093169.1226526546805" Content-Language: en-US ------=_Part_209545_389093169.1226526546805 Content-Type: text/xml; charset=UTF-8 Content-Transfer-Encoding: binary Content-Id: &lt;30ED8FE3004CDA67723CC7164A6CFEEC&gt; &lt;?xml version="1.0" encoding="utf-8"?&gt;&lt;soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&gt;&lt;soapenv:Body&gt;&lt;ns1:runReportResponse soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:ns1="http://axis2.ws.jasperserver.jaspersoft.com"&gt;&lt;runReportReturn xsi:type="xsd:string"&gt;&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;UTF-8&amp;quot;?&amp;gt; &amp;lt;operationResult version=&amp;quot;2.0.1&amp;quot;&amp;gt; &amp;lt;returnCode&amp;gt;&amp;lt;![CDATA[0]]&amp;gt;&amp;lt;/returnCode&amp;gt; &amp;lt;/operationResult&amp;gt; &lt;/runReportReturn&gt;&lt;/ns1:runReportResponse&gt;&lt;/soapenv:Body&gt;&lt;/soapenv:Envelope&gt; ------=_Part_209545_389093169.1226526546805 Content-Type: text/html Content-Transfer-Encoding: binary Content-Id: &lt;report&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;&lt;/title&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/&gt; &lt;style type="text/css"&gt; a {text-decoration: none} &lt;/style&gt; &lt;/head&gt; &lt;body text="#000000" link="#000000" alink="#000000" vlink="#000000"&gt; &lt;table width="100%" cellpadding="0" cellspacing="0" border="0"&gt; &lt;tr&gt;&lt;td width="50%"&gt;&amp;nbsp;&lt;/td&gt;&lt;td align="center"&gt; &lt;a name="JR_PAGE_ANCHOR_0_1"/&gt; &lt;table style="width: 595px" cellpadding="0" cellspacing="0" border="0" bgcolor="white"&gt; &lt;tr&gt; &lt;td&gt;&lt;img alt="" src="images/px" style="width: 35px; height: 1px;"/&gt;&lt;/td&gt; &lt;td&gt;&lt;img alt="" src="images/px" style="width: 189px; height: 1px;"/&gt;&lt;/td&gt; &lt;td&gt;&lt;img alt="" src="images/px" style="width: 253px; height: 1px;"/&gt;&lt;/td&gt; &lt;td&gt;&lt;img alt="" src="images/px" style="width: 118px; height: 1px;"/&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr valign="top"&gt; &lt;td colspan="4"&gt;&lt;img alt="" src="images/px" style="width: 595px; height: 20px;"/&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr valign="top"&gt; &lt;td&gt;&lt;img alt="" src="images/px" style="width: 35px; height: 30px;"/&gt;&lt;/td&gt; &lt;td valign="middle"&gt;&lt;span style="font-family: Arial; font-size: 12.0px; font-weight: bold;"&gt;The value of the parameter is:&lt;/span&gt;&lt;/td&gt; &lt;td valign="middle"&gt;&lt;span style="font-family: Arial; background-color: #FFFFFF; font-size: 12.0px; font-weight: bold;"&gt;1&lt;/span&gt;&lt;/td&gt; &lt;td&gt;&lt;img alt="" src="images/px" style="width: 118px; height: 30px;"/&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr valign="top"&gt; &lt;td colspan="4"&gt;&lt;img alt="" src="images/px" style="width: 595px; height: 20px;"/&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/td&gt;&lt;td width="50%"&gt;&amp;nbsp;&lt;/td&gt;&lt;/tr&gt; &lt;/table&gt; &lt;/body&gt; &lt;/html&gt; ------=_Part_209545_389093169.1226526546805-- </code></pre> <p><strong>Request (with Mtom Message Encoding):</strong></p> <pre><code>POST /jasperserver-pro/services/repository HTTP/1.1 MIME-Version: 1.0 Content-Type: multipart/related; type="application/xop+xml";start="&lt;http://tempuri.org/0&gt;";boundary="uuid:fafcdca7-94f7-4884-a8d4-5c6d50dbe8ef+id=1";start-info="text/xml" VsDebuggerCausalityData: uIDPo+cN2kKX2odFuUVaER0j60gAAAAAmfYaGH7Ow0WQOcwhebh5pqmDl29omcVOtwVGa10IWewACQAA SOAPAction: "" Authorization: Basic amFzcGVyYWRtaW46akBzcDNyQGRtJW4= Host: reports.dev.xxx.com Content-Length: 1031 Expect: 100-continue --uuid:fafcdca7-94f7-4884-a8d4-5c6d50dbe8ef+id=1 Content-ID: &lt;http://tempuri.org/0&gt; Content-Transfer-Encoding: 8bit Content-Type: application/xop+xml;charset=utf-8;type="text/xml" &lt;s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"&gt;&lt;s:Body s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;&lt;q1:runReport xmlns:q1="http://axis2.ws.jasperserver.jaspersoft.com"&gt;&lt;requestXmlString xsi:type="xsd:string"&gt;&amp;lt;request operationName="runReport" locale="en"&amp;gt;&amp;#xD; &amp;lt;argument name="RUN_OUTPUT_FORMAT"&amp;gt;HTML&amp;lt;/argument&amp;gt;&amp;#xD; &amp;lt;resourceDescriptor name="" wsType="" uriString="/BusinessIntelligence/MOS/Reports/dotnettest" isNew="false"&amp;gt;&amp;#xD; &amp;lt;label&amp;gt;null&amp;lt;/label&amp;gt;&amp;#xD; &amp;lt;parameter name="testparam"&amp;gt;1&amp;lt;/parameter&amp;gt;&amp;#xD; &amp;lt;/resourceDescriptor&amp;gt;&amp;#xD; &amp;lt;/request&amp;gt;&lt;/requestXmlString&gt;&lt;/q1:runReport&gt;&lt;/s:Body&gt;&lt;/s:Envelope&gt; --uuid:fafcdca7-94f7-4884-a8d4-5c6d50dbe8ef+id=1-- </code></pre> <p><strong>Response (with Mtom Message Encoding):</strong></p> <pre><code>HTTP/1.1 500 Internal Server Error Date: Wed, 12 Nov 2008 21:47:42 GMT Server: IBM_HTTP_Server Surrogate-Control: no-store $WSEP: Set-Cookie: JSESSIONID=0000_iMrdp-TnK9FG3jZFzjx_hA:13kftunf6; Path=/ Expires: Thu, 01 Dec 1994 16:00:00 GMT Cache-Control: no-cache="set-cookie, set-cookie2" Content-Length: 12 Connection: close Content-Type: text/html;charset=UTF-8 Content-Language: en-US Error 500: </code></pre> <p>Here is a link that supports the theory that Microsoft does not support mixed encodings:</p> <p><a href="http://social.msdn.microsoft.com/Forums/en-US/asmxandxml/thread/9270913a-ab9f-4097-beef-51d4d69563d7/" rel="noreferrer" title="WSE 3.0: MTOM response mandatory for MTOM request?">WSE 3.0: MTOM response mandatory for MTOM request?</a></p> <p>UHG!</p>
[ { "answer_id": 297892, "author": "komma8.komma1", "author_id": 13355, "author_profile": "https://Stackoverflow.com/users/13355", "pm_score": 1, "selected": false, "text": "<p>Here is a reply I got on another forum. it basically says that the problem is with Axis2 on the Java side. Unfortunately, that is not under my control in this case.</p>\n\n<blockquote>\n <p>cherry111 - Posted on Saturday,\n November 15, 2008 12:52:08 AM</p>\n \n <p>You need change the configuration on\n your AXIS2 web service. You may know\n you can enable MTOM at two places. One\n is in service.xml and the other is in\n the axis.xml. Java recommends you set\n it in service.xml, but .net wse3.0\n client does not like it. If you enable\n MTOM in axis.xml, it should work.</p>\n</blockquote>\n" }, { "answer_id": 304715, "author": "Wagner Silveira", "author_id": 33352, "author_profile": "https://Stackoverflow.com/users/33352", "pm_score": 2, "selected": false, "text": "<p>I researched a bit about this and the bad news is that from WCF point of view the request and response MUST use the same enconding. So yeah, the answer above is quite correct. You have to organize with service provider to enable MTOM on both request and response. The MTOM request will not have any impact on his application, apart from changing the SOAP mime-type, as far as I know.</p>\n" }, { "answer_id": 1799425, "author": "Eric Schlosser", "author_id": 196823, "author_profile": "https://Stackoverflow.com/users/196823", "pm_score": 4, "selected": true, "text": "<p>Yes you can send a text message and get an mtom reply(or vise versa)with WCF.</p>\n\n<p>see...</p>\n\n<p><a href=\"http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/480f1bc4-1fc4-40e9-a2ed-efcf3009d6ef\" rel=\"nofollow noreferrer\">http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/480f1bc4-1fc4-40e9-a2ed-efcf3009d6ef</a></p>\n" }, { "answer_id": 2408332, "author": "Siddharth Sawe", "author_id": 289559, "author_profile": "https://Stackoverflow.com/users/289559", "pm_score": 1, "selected": false, "text": "<p>Yes WCF has that mandated requirement and NO, because you can work around it like i did.</p>\n\n<p>I wrote a MultiContentTypeMessageEncoder that encapsulates 3 different encoders text, mtom and fi. I also plan to encapsulate a gpb encoder if possible and if there is a good reason to do so, in the future</p>\n" }, { "answer_id": 32965413, "author": "Zayani Chiheb", "author_id": 5343405, "author_profile": "https://Stackoverflow.com/users/5343405", "pm_score": 0, "selected": false, "text": "<p>[WSE 3.0]\nYou can define a new class that inherits from your WSE3 proxy object with a single override method GetWebResponse.</p>\n\n<p>In GetWebResponse method, you can simply choose if you want to use the mtom encoding according to the response's content-type.</p>\n\n<p>After that, you have to use this proxy class instead of the generated one.</p>\n\n<p>PS: The WSE3 proxy class have to be generated using wsewsdl3 as a WebClient (add this option /type:webClient to the commend line).</p>\n\n<p>Reference:\n<a href=\"http://www.codeproject.com/Tips/46257/Solution-to-WSE-error-for-WSE-clients-needing\" rel=\"nofollow\">http://www.codeproject.com/Tips/46257/Solution-to-WSE-error-for-WSE-clients-needing</a>.</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13355/" ]
Here is my problem. I am hitting a web service (hosted on a Java based server) that will only accept text encoded Requests, but it returns MTOM Responses. What I've found is that if I set the web service to RequireMtom, it sends an Mtom request! Unfortunately, the server chokes on an Mtom request and returns a 500 error. However, if I set it to Text message encoding, the response comes back correctly with a multipart MIME (MTOM) response that errors out the Microsoft Web Service API (sample error below). It's expecting a text encoded response because the request was text encoded. I would like to RequireMtom on the response only. Can anyone help me here? *As you can see in the error below (which occurs with the standard web services API, WCF or WSE3), when I send the request with text encoding, the response comes back correctly with all the data in a multipart/related response, but the .net framework chokes!* **ERROR MESSAGE WITH WSE:** ``` Client found response content type of 'multipart/related; type="text/xml"; start="<1AE0B46A85B0186B5D136D12E1EE286E>"; boundary="----=_Part_209564_1891070135.1226526701833"', but expected 'text/xml'. The request failed with the error message: at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall) at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters) at TestWseService.AdesaJasperWse.ManagementServiceService.runReport(String requestXmlString) in C:\Documents and Settings\xxx\My Documents\Visual Studio 2005\Projects\TestWseService\Web References\AdesaJasperWse\Reference.cs:line 229 at TestWseService.Form1.buttonRunService_Click(Object sender, EventArgs e) in C:\Documents and Settings\xxx\My Documents\Visual Studio 2005\Projects\TestWseService\Form1.cs:line 42 ``` **ERROR MESSAGE WITH WCF** ``` The content type multipart/related; type="text/xml"; start="<30ED8FE3004CDA67723CC7164A6CFEEC>"; boundary="----=_Part_209545_389093169.1226526546805" of the response message does not match the content type of the binding (text/xml; charset=utf-8). If using a custom encoder, be sure that the IsContentTypeSupported method is implemented properly. The first 1024 bytes of the response were: Server stack trace: at System.ServiceModel.Channels.HttpChannelUtilities.ValidateRequestReplyResponse(HttpWebRequest request, HttpWebResponse response, HttpChannelFactory factory, WebException responseException) at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout) at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout) at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout) at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout) at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs) at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation) at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message) ``` **Request (with Text Message Encoding):** ``` POST /jasperserver-pro/services/repository HTTP/1.1 Content-Type: text/xml; charset=utf-8 VsDebuggerCausalityData: uIDPo7V2+runH+xGudbec7ueUU8AAAAA7H9vL3stlkCBofMgLa5DWkQOHHpBdy1Ek6P6nXx7FpsACQAA SOAPAction: "" Authorization: Basic amFzcGVyYWRtaW46akBzcDNyQGRtJW4= Host: reports.dev.xxx.com Content-Length: 789 Expect: 100-continue <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"><s:Body s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><q1:runReport xmlns:q1="http://axis2.ws.jasperserver.jaspersoft.com"><requestXmlString xsi:type="xsd:string">&lt;request operationName="runReport" locale="en"&gt;&#xD; &lt;argument name="RUN_OUTPUT_FORMAT"&gt;HTML&lt;/argument&gt;&#xD; &lt;resourceDescriptor name="" wsType="" uriString="/BusinessIntelligence/MOS/Reports/dotnettest" isNew="false"&gt;&#xD; &lt;label&gt;null&lt;/label&gt;&#xD; &lt;parameter name="testparam"&gt;1&lt;/parameter&gt;&#xD; &lt;/resourceDescriptor&gt;&#xD; &lt;/request&gt;</requestXmlString></q1:runReport></s:Body></s:Envelope> ``` **Response (with Text Message Encoding):** ``` HTTP/1.1 200 OK Date: Wed, 12 Nov 2008 21:49:04 GMT Server: IBM_HTTP_Server Surrogate-Control: no-store Set-Cookie: JSESSIONID=0000z5pH1xEMyulueASctjru2qe:13kftunf6; Path=/ Expires: Thu, 01 Dec 1994 16:00:00 GMT Cache-Control: no-cache="set-cookie, set-cookie2" Content-Length: 2580 Content-Type: multipart/related; type="text/xml"; start="<30ED8FE3004CDA67723CC7164A6CFEEC>"; boundary="----=_Part_209545_389093169.1226526546805" Content-Language: en-US ------=_Part_209545_389093169.1226526546805 Content-Type: text/xml; charset=UTF-8 Content-Transfer-Encoding: binary Content-Id: <30ED8FE3004CDA67723CC7164A6CFEEC> <?xml version="1.0" encoding="utf-8"?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><soapenv:Body><ns1:runReportResponse soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:ns1="http://axis2.ws.jasperserver.jaspersoft.com"><runReportReturn xsi:type="xsd:string">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; &lt;operationResult version=&quot;2.0.1&quot;&gt; &lt;returnCode&gt;&lt;![CDATA[0]]&gt;&lt;/returnCode&gt; &lt;/operationResult&gt; </runReportReturn></ns1:runReportResponse></soapenv:Body></soapenv:Envelope> ------=_Part_209545_389093169.1226526546805 Content-Type: text/html Content-Transfer-Encoding: binary Content-Id: <report> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <style type="text/css"> a {text-decoration: none} </style> </head> <body text="#000000" link="#000000" alink="#000000" vlink="#000000"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr><td width="50%">&nbsp;</td><td align="center"> <a name="JR_PAGE_ANCHOR_0_1"/> <table style="width: 595px" cellpadding="0" cellspacing="0" border="0" bgcolor="white"> <tr> <td><img alt="" src="images/px" style="width: 35px; height: 1px;"/></td> <td><img alt="" src="images/px" style="width: 189px; height: 1px;"/></td> <td><img alt="" src="images/px" style="width: 253px; height: 1px;"/></td> <td><img alt="" src="images/px" style="width: 118px; height: 1px;"/></td> </tr> <tr valign="top"> <td colspan="4"><img alt="" src="images/px" style="width: 595px; height: 20px;"/></td> </tr> <tr valign="top"> <td><img alt="" src="images/px" style="width: 35px; height: 30px;"/></td> <td valign="middle"><span style="font-family: Arial; font-size: 12.0px; font-weight: bold;">The value of the parameter is:</span></td> <td valign="middle"><span style="font-family: Arial; background-color: #FFFFFF; font-size: 12.0px; font-weight: bold;">1</span></td> <td><img alt="" src="images/px" style="width: 118px; height: 30px;"/></td> </tr> <tr valign="top"> <td colspan="4"><img alt="" src="images/px" style="width: 595px; height: 20px;"/></td> </tr> </table> </td><td width="50%">&nbsp;</td></tr> </table> </body> </html> ------=_Part_209545_389093169.1226526546805-- ``` **Request (with Mtom Message Encoding):** ``` POST /jasperserver-pro/services/repository HTTP/1.1 MIME-Version: 1.0 Content-Type: multipart/related; type="application/xop+xml";start="<http://tempuri.org/0>";boundary="uuid:fafcdca7-94f7-4884-a8d4-5c6d50dbe8ef+id=1";start-info="text/xml" VsDebuggerCausalityData: uIDPo+cN2kKX2odFuUVaER0j60gAAAAAmfYaGH7Ow0WQOcwhebh5pqmDl29omcVOtwVGa10IWewACQAA SOAPAction: "" Authorization: Basic amFzcGVyYWRtaW46akBzcDNyQGRtJW4= Host: reports.dev.xxx.com Content-Length: 1031 Expect: 100-continue --uuid:fafcdca7-94f7-4884-a8d4-5c6d50dbe8ef+id=1 Content-ID: <http://tempuri.org/0> Content-Transfer-Encoding: 8bit Content-Type: application/xop+xml;charset=utf-8;type="text/xml" <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"><s:Body s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><q1:runReport xmlns:q1="http://axis2.ws.jasperserver.jaspersoft.com"><requestXmlString xsi:type="xsd:string">&lt;request operationName="runReport" locale="en"&gt;&#xD; &lt;argument name="RUN_OUTPUT_FORMAT"&gt;HTML&lt;/argument&gt;&#xD; &lt;resourceDescriptor name="" wsType="" uriString="/BusinessIntelligence/MOS/Reports/dotnettest" isNew="false"&gt;&#xD; &lt;label&gt;null&lt;/label&gt;&#xD; &lt;parameter name="testparam"&gt;1&lt;/parameter&gt;&#xD; &lt;/resourceDescriptor&gt;&#xD; &lt;/request&gt;</requestXmlString></q1:runReport></s:Body></s:Envelope> --uuid:fafcdca7-94f7-4884-a8d4-5c6d50dbe8ef+id=1-- ``` **Response (with Mtom Message Encoding):** ``` HTTP/1.1 500 Internal Server Error Date: Wed, 12 Nov 2008 21:47:42 GMT Server: IBM_HTTP_Server Surrogate-Control: no-store $WSEP: Set-Cookie: JSESSIONID=0000_iMrdp-TnK9FG3jZFzjx_hA:13kftunf6; Path=/ Expires: Thu, 01 Dec 1994 16:00:00 GMT Cache-Control: no-cache="set-cookie, set-cookie2" Content-Length: 12 Connection: close Content-Type: text/html;charset=UTF-8 Content-Language: en-US Error 500: ``` Here is a link that supports the theory that Microsoft does not support mixed encodings: [WSE 3.0: MTOM response mandatory for MTOM request?](http://social.msdn.microsoft.com/Forums/en-US/asmxandxml/thread/9270913a-ab9f-4097-beef-51d4d69563d7/ "WSE 3.0: MTOM response mandatory for MTOM request?") UHG!
Yes you can send a text message and get an mtom reply(or vise versa)with WCF. see... <http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/480f1bc4-1fc4-40e9-a2ed-efcf3009d6ef>
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": 284590, "author": "Alex", "author_id": 32392, "author_profile": "https://Stackoverflow.com/users/32392", "pm_score": 1, "selected": false, "text": "<p>I did it using this function:</p>\n\n<pre>function fieldNumericSorter(field:String):Function {\n return function (obj1:Object, obj2:Object):int {\n return sign( int(obj1[field]) - int(obj2[field]) );\n }\n}</pre>\n\n<p>and for each column that needed sorting set </p>\n\n<pre>colToBeSorted.sortCompareFunction = fieldNumericSorter(\"fieldname\");</pre>\n" }, { "answer_id": 722563, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>If you are using a DataGrid with an XML dataProvider, this worked for me (modified from Alex's answer):</p>\n\n<pre><code>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 &gt; 0) ? 1 : ((num &lt; 0) ? -1 : 0);\n }\n\n}\n</code></pre>\n\n<p>and </p>\n\n<pre><code>dataGridColumn.sortCompareFunction = xmlDataGridNumericSorter(xmlAttribute.name().toString());\n</code></pre>\n\n<p>A very nice solution, considering how common a procedure this probably is..</p>\n\n<p>Thanks Alex, hope this helps people further.</p>\n" }, { "answer_id": 1780330, "author": "crazy horse", "author_id": 204312, "author_profile": "https://Stackoverflow.com/users/204312", "pm_score": 0, "selected": false, "text": "<p>I did not use a numeric function to sort - instead did the following:</p>\n\n<p>arrayCollObject.addItem({Col1: rowData[0], Col2: parseFloat(rowData[1])});</p>\n\n<p>This seems to do the sorting correctly.</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32392/" ]
I am using a Flex dataGrid, and need to sort some of my columns numerically. 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. 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.
I did it using this function: ``` function fieldNumericSorter(field:String):Function { return function (obj1:Object, obj2:Object):int { return sign( int(obj1[field]) - int(obj2[field]) ); } } ``` and for each column that needed sorting set ``` colToBeSorted.sortCompareFunction = fieldNumericSorter("fieldname"); ```
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": 284213, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 2, "selected": false, "text": "<p>Add a scheduled task that runs the script with your credentials. Remind yourself that you need to update the credentials on the task every time you change your password. It be a good idea to have the script \"phone home\" via email or something every time it is run so that you can tell if it is being executed.</p>\n\n<p>It might also be a good idea to set up a separate service id for these sorts of activities. You may not need to change the password on the service id as frequently.</p>\n" }, { "answer_id": 284277, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 2, "selected": false, "text": "<p>You can add a scheduled task and enter no credentials or password for it. This will cause it to run under LOCAL SYSTEM (which normally is the context the Task Scheduler service uses).</p>\n\n<p>Be aware that this is a backdoor vulnerability scenario: Anyone allowed to edit your script file could misuse it to do undesirable things on the machine that runs the task. Put proper permission on the script file to prevent that. On the other hand - a task running as LOCAL SYSTEM cannot wreck havoc over the network.</p>\n\n<p>I propose you condense your script file a little:</p>\n\n<pre>\nSet WshShell = WScript.CreateObject(\"WScript.Shell\") \n\nRun \"cmd.exe\" \nSendKeys \"telnet 10.20.70.254{ENTER}\" \nSendKeys \"netscreen\" \nSendKeys \"{ENTER}\" \nSendKeys \"netscreen\" \nSendKeys \"{ENTER}\" \nSendKeys \"save conf to tftp 10.10.40.139 test.cfg{ENTER}\"\nSendKeys \"exit{ENTER}\" 'close telnet session' \n\nRun \"cmd.exe\" \nSendKeys \"telnet 10.20.70.254{ENTER}\" \nSendKeys \"netscreen\" \nSendKeys \"{ENTER}\" \nSendKeys \"netscreen\" \nSendKeys \"{ENTER}\" \nSendKeys \"save conf to tftp 10.10.40.139 palsg140.cfg{ENTER}\" 'repeat as needed \nSendKeys \"exit{ENTER}\" 'close telnet session' \nSendKeys \"{ENTER}\" 'get command prompt back \nSendKeys \"exit{ENTER}\" 'close cmd.exe\nSendKeys \"{ENTER}\" 'get command prompt back \nSendKeys \"exit{ENTER}\" 'close cmd.exe\n\nSub SendKeys(s)\n WshShell.SendKeys s\n WScript.Sleep 300\nEnd Sub\n\nSub Run(command)\n WshShell.Run command\n WScript.Sleep 100 \n WshShell.AppActivate command \n WScript.Sleep 300 \nEnd Sub\n\n</pre>\n" }, { "answer_id": 284727, "author": "aphoria", "author_id": 2441, "author_profile": "https://Stackoverflow.com/users/2441", "pm_score": 1, "selected": false, "text": "<p>I'm pretty sure SendKeys will not work if the desktop is locked or no user is logged in.</p>\n" }, { "answer_id": 295640, "author": "Michael Galos", "author_id": 29820, "author_profile": "https://Stackoverflow.com/users/29820", "pm_score": 1, "selected": false, "text": "<p>I'm pretty SendKeys will not work if you aren't logged in.\nIt's unreliable in my experience anyway.\nYou might be better off using a DOS batch file.</p>\n\n<p>getftpconf.bat:</p>\n\n<pre><code>telnet 10.10.40.139\nnetscreen\nnetscreen\nsave conf to tftp 10.10.40.139 palsg140.cf\nexit\n</code></pre>\n\n<p>Something like that.</p>\n\n<p>If there is output in the command prompt that you need to record, you can put a \" >> output.txt\" at the end of the command line shortcut.</p>\n\n<p>You could then call another batch file which sends that output.txt via ftp to where ever you need.</p>\n\n<p>You can easily setup this batch file to run as a scheduled task in windows.</p>\n" }, { "answer_id": 1004035, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Batch files don't work in Windows with Telnet (works fine in UNIX -- again, way to go Microsoft). As already mentioned here, sendkeys does not work in vba when not logged on.</p>\n\n<p>Sorry I don't have the \"this does work\" solution for you....I'm stuck on the same problem</p>\n" }, { "answer_id": 1004088, "author": "scottm", "author_id": 53007, "author_profile": "https://Stackoverflow.com/users/53007", "pm_score": 1, "selected": false, "text": "<p>just make a batch file that contains this:</p>\n\n<pre><code>cscript.exe myscript.vbs\n</code></pre>\n\n<p>save it as something like myscript.bat.</p>\n\n<p>Use schedule tasks to schedule the .bat file. After you create the scheduled task, you may have to check it's properties to make sure it's has appropriate user rights. </p>\n\n<p>There are <a href=\"http://technet.microsoft.com/en-us/library/bb490816.aspx\" rel=\"nofollow noreferrer\">some options</a> you can use with cscript so it doesn't show the logo, etc. </p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284201", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a [VBScript](http://en.wikipedia.org/wiki/VBScript) script that starts a cmd prompt, telnets into a device and [TFTP](http://en.wikipedia.org/wiki/Trivial_File_Transfer_Protocol)'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 [Task Scheduler](http://en.wikipedia.org/wiki/Task_Scheduler). Any assistance would be appreciated, here is the VBScript script: ``` 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 ```
Add a scheduled task that runs the script with your credentials. Remind yourself that you need to update the credentials on the task every time you change your password. It be a good idea to have the script "phone home" via email or something every time it is run so that you can tell if it is being executed. It might also be a good idea to set up a separate service id for these sorts of activities. You may not need to change the password on the service id as frequently.
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": "<pre><code>foreach( object element in myList ) {\n Item itm = element as Item;\n if ( null == itm ) { continue; }\n Guid test = itm.ItemGuid;\n}\n</code></pre>\n" }, { "answer_id": 284236, "author": "user34292", "author_id": 34292, "author_profile": "https://Stackoverflow.com/users/34292", "pm_score": 1, "selected": false, "text": "<p>Your list should be declared like this:</p>\n\n<pre><code>List&lt;V&gt; myList = someMethod;\n</code></pre>\n\n<p>Where V is the type item.</p>\n\n<p>and then your iteration was correct:</p>\n\n<pre><code>foreach(V element in myList)\n{\n Guid test = element.IetmGuid;\n}\n</code></pre>\n" }, { "answer_id": 284263, "author": "Daniel M", "author_id": 36559, "author_profile": "https://Stackoverflow.com/users/36559", "pm_score": 2, "selected": false, "text": "<p>Try declaring your list like this:</p>\n\n<pre><code>List&lt;Item&gt; myList = someMethod;\n</code></pre>\n" }, { "answer_id": 284266, "author": "akmad", "author_id": 1314, "author_profile": "https://Stackoverflow.com/users/1314", "pm_score": 3, "selected": false, "text": "<p>Are you putting a constraint on the generic type V? You'll need to tell the runtime that V can be any type that is a subtype of your <code>Item</code> type.</p>\n\n<pre><code>public class MyGenericClass&lt;V&gt;\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&lt;V&gt; 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</code></pre>\n\n<p>Note, it only makes sense to use a generic class in this manner if you need to support multiple kinds of Items (represented by subtypes of Item).</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284220", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
``` 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; } } } ``` The above is my custom object. I have a list: ``` List<V> myList = someMethod; ``` where V is of type Item, my object. I want to iterate and get the properties as such ``` foreach(V element in mylist) { Guid test = element.IetmGuid; } ``` When I debug and look at the 'element' object I can see all the properties in the 'Quickwatch' but I cannot do element.IetmGuid.
Are you putting a constraint on the generic type V? You'll need to tell the runtime that V can be any type that is a subtype of your `Item` type. ``` public class MyGenericClass<V> where V : Item //This is a constraint that requires type V to be an Item (or subtype) { public void DoSomething() { List<V> myList = someMethod(); foreach (V element in myList) { //This will now work because you've constrained the generic type V Guid test = element.IetmGuid; } } } ``` Note, it only makes sense to use a generic class in this manner if you need to support multiple kinds of Items (represented by subtypes of Item).
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": 284396, "author": "sep332", "author_id": 13652, "author_profile": "https://Stackoverflow.com/users/13652", "pm_score": 0, "selected": false, "text": "<p>\"Or is it simply the case that anyone who needs more powerful windowing components has to use wxPython?\"<br>\nShort answer: yes.</p>\n\n<p>Long answer:\nIt may take some practice for your wxPython code to feel \"clean,\" but it is nicer and much more powerful than Tkinter. You will also get better support, since more people use it these days.</p>\n" }, { "answer_id": 284695, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 6, "selected": true, "text": "<p>On recent Python (> 2.7) versions, you can use the <a href=\"https://docs.python.org/2/library/ttk.html\" rel=\"noreferrer\"><code>ttk</code></a> module, which provides access to the <em>Tk themed widget</em> set, which has been introduced in <code>Tk 8.5</code>.</p>\n\n<p>Here's how you import <code>ttk</code> in Python 2:</p>\n\n<pre><code>import ttk\n\nhelp(ttk.Notebook)\n</code></pre>\n\n<p>In Python 3, the <a href=\"https://docs.python.org/3.4/library/tkinter.ttk.html?highlight=ttk#module-tkinter.ttk\" rel=\"noreferrer\"><code>ttk</code></a> module comes with the standard distributions as a submodule of <a href=\"https://docs.python.org/3.4/library/tkinter.html\" rel=\"noreferrer\"><code>tkinter</code></a>. </p>\n\n<p>Here's a simple working example based on an example from the <a href=\"http://www.tkdocs.com/tutorial/complex.html\" rel=\"noreferrer\"><code>TkDocs</code></a> website:</p>\n\n<pre><code>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</code></pre>\n\n<p>Another alternative is to use the <code>NoteBook</code> widget from the <a href=\"https://docs.python.org/3/library/tkinter.tix.html\" rel=\"noreferrer\"><code>tkinter.tix</code></a> library. To use <code>tkinter.tix</code>, you must have the <code>Tix</code> widgets installed, usually alongside your installation of the <code>Tk</code> widgets. To test your installation, try the following:</p>\n\n<pre><code>from tkinter import tix\nroot = tix.Tk()\nroot.tk.eval('package require Tix')\n</code></pre>\n\n<p>For more info, check out this <a href=\"https://docs.python.org/3/library/tkinter.tix.html\" rel=\"noreferrer\">webpage</a> on the PSF website.</p>\n\n<p>Note that <code>tix</code> is pretty old and not well-supported, so your best choice might be to go for <code>ttk.Notebook</code>.</p>\n" }, { "answer_id": 285642, "author": "John Fouhy", "author_id": 15154, "author_profile": "https://Stackoverflow.com/users/15154", "pm_score": 0, "selected": false, "text": "<p>What problems did you have with pmw? It's old, yes, but it's pure python so it should work.</p>\n\n<p>Note that Tix doesn't work with py2exe, if that is an issue for you.</p>\n" }, { "answer_id": 288151, "author": "Bryan Oakley", "author_id": 7432, "author_profile": "https://Stackoverflow.com/users/7432", "pm_score": 2, "selected": false, "text": "<p>While it may not help you at the moment, tk 8.5 comes with an extended set of widgets. This extended set is available with tk 8.4 by way of an extension known as \"tile\". Included in the extended set of widgets is a notebook widget. Unfortunately, at this time Tkinter by default uses a fairly old version of Tk that doesn't come with these widgets.</p>\n\n<p>There have been efforts to make tile available to Tkinter. Check out <a href=\"http://tkinter.unpythonic.net/wiki/TileWrapper\" rel=\"nofollow noreferrer\">http://tkinter.unpythonic.net/wiki/TileWrapper</a>. For another similar effort see <a href=\"http://pypi.python.org/pypi/pyttk\" rel=\"nofollow noreferrer\">http://pypi.python.org/pypi/pyttk</a>. Also, for a taste of how these widgets look (in Ruby, Perl and Tcl) see <a href=\"http://www.tkdocs.com/\" rel=\"nofollow noreferrer\">http://www.tkdocs.com/</a>. </p>\n\n<p>Tk 8.5 is a <em>huge</em> improvement over stock Tk. It introduces several new widgets, native widgets, and a theming engine. Hopefully it will be available by default in Tkinter some day soon. Too bad the Python world is lagging behind other languages.</p>\n\n<p><em>update: The latest versions of Python now include support for the themed widgets out of the box. _</em></p>\n" }, { "answer_id": 18922125, "author": "sPaz", "author_id": 1762092, "author_profile": "https://Stackoverflow.com/users/1762092", "pm_score": 3, "selected": false, "text": "<p>If anyone still looking, I have got this working as Tab in tkinter. Play around with the code to make it function the way you want (for example, you can add button to add a new tab):</p>\n\n<pre><code>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 &lt; 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)&gt;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</code></pre>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284234", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1694/" ]
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). A little Googling on the subject offers a few suggestions. There's [a cookbook entry](http://code.activestate.com/recipes/188537/) with a class allowing you to use tabs, but it's very primitive. There's also [Python megawidgets](http://pmw.sourceforge.net/) on SourceForge, although this seems very old and gave me errors during installation. 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?
On recent Python (> 2.7) versions, you can use the [`ttk`](https://docs.python.org/2/library/ttk.html) module, which provides access to the *Tk themed widget* set, which has been introduced in `Tk 8.5`. Here's how you import `ttk` in Python 2: ``` import ttk help(ttk.Notebook) ``` In Python 3, the [`ttk`](https://docs.python.org/3.4/library/tkinter.ttk.html?highlight=ttk#module-tkinter.ttk) module comes with the standard distributions as a submodule of [`tkinter`](https://docs.python.org/3.4/library/tkinter.html). Here's a simple working example based on an example from the [`TkDocs`](http://www.tkdocs.com/tutorial/complex.html) website: ``` from tkinter import ttk import tkinter as tk from tkinter.scrolledtext import ScrolledText def demo(): root = tk.Tk() root.title("ttk.Notebook") nb = ttk.Notebook(root) # adding Frames as pages for the ttk.Notebook # first page, which would get widgets gridded into it page1 = ttk.Frame(nb) # second page page2 = ttk.Frame(nb) text = ScrolledText(page2) text.pack(expand=1, fill="both") nb.add(page1, text='One') nb.add(page2, text='Two') nb.pack(expand=1, fill="both") root.mainloop() if __name__ == "__main__": demo() ``` Another alternative is to use the `NoteBook` widget from the [`tkinter.tix`](https://docs.python.org/3/library/tkinter.tix.html) library. To use `tkinter.tix`, you must have the `Tix` widgets installed, usually alongside your installation of the `Tk` widgets. To test your installation, try the following: ``` from tkinter import tix root = tix.Tk() root.tk.eval('package require Tix') ``` For more info, check out this [webpage](https://docs.python.org/3/library/tkinter.tix.html) on the PSF website. Note that `tix` is pretty old and not well-supported, so your best choice might be to go for `ttk.Notebook`.
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": "<p>So my understanding of your problem is that <code>side_bar_html</code> is set during the <code>onreadystatechange</code> function call, but you're not seeing it being set unless you alert it.</p>\n\n<p>Here's what's probably happening: the Ajax request takes some time to happen. When you call <code>req.send(null)</code> then that kicks off the request, but your <code>onreadystatechange</code> function won't get called until sometime later, after your web browser has made the request and gotten back a response.</p>\n\n<p>So when you immediately try to use the <code>side_bar_html</code> value, it doesn't work because the response hasn't come back yet. However, when you alert the value, the time it takes to perform the alert gives the browser time to get a response and set the <code>side_bar_html</code> value appropriately.</p>\n\n<p>Your underlying problem is that Ajax is asynchronous (which is there the A comes from) and you're trying to use it synchronously (meaning that you assume that things will always happen in a particular order). Your best bet is to put the code that uses <code>side_bar_html</code> in your <code>onreadystatechange</code> function, so that it doesn't get used before it's set.</p>\n" }, { "answer_id": 284284, "author": "Jared", "author_id": 1980, "author_profile": "https://Stackoverflow.com/users/1980", "pm_score": 0, "selected": false, "text": "<p>add the code below to the end of your onreadystatechange function (within the if statement checking for a value of 4). e.g:</p>\n\n<pre><code>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 &lt; 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 &lt; 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 &lt; polygons.length; k++) {\n polygons[k].hide();\n }\n\n for(var l = 0; l &lt; polygonsToShow.length; l++){ \n polygons[polygonsToShow[l]].show();\n }\n\n 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});\n map.addControl(searchResults, new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(20, 70)));\n}\n</code></pre>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284246", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36939/" ]
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 `side_bar_html` variable will not output if I do not alert the data first. Here is my searchMap function. The variable is declared as such: `var side_bar_html = "";` ``` 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 < 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 < 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 < polygons.length; k++) { polygons[k].hide(); } for(var l = 0; l < 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('<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}); map.addControl(searchResults, new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(20, 70))); } ``` And the function to create a search marker: ``` function createSearchMarker(point, id, pname, letIcon) { var marker = new GMarker(point,letIcon); GEvent.addListener(marker, "click", function() { marker.openInfoWindowHtml('<a href="#" onclick=\'tb_show("' + pname + '","admin/get_info.php?b=' + id + '&KeepThis=true&TB_iframe=true&height=400&width=600",false); return false;\'>' + pname + '</a>'); }); side_bar_html = side_bar_html + '<a href="javascript:clickSearch(' + searchCount + ')">' + String.fromCharCode("A".charCodeAt(0) + searchCount) + ': ' + pname + '</a><br>'; marker.vt_id = id; searchMarkers.push(marker); searchCount++; return marker; } ``` 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!
So my understanding of your problem is that `side_bar_html` is set during the `onreadystatechange` function call, but you're not seeing it being set unless you alert it. Here's what's probably happening: the Ajax request takes some time to happen. When you call `req.send(null)` then that kicks off the request, but your `onreadystatechange` function won't get called until sometime later, after your web browser has made the request and gotten back a response. So when you immediately try to use the `side_bar_html` value, it doesn't work because the response hasn't come back yet. However, when you alert the value, the time it takes to perform the alert gives the browser time to get a response and set the `side_bar_html` value appropriately. Your underlying problem is that Ajax is asynchronous (which is there the A comes from) and you're trying to use it synchronously (meaning that you assume that things will always happen in a particular order). Your best bet is to put the code that uses `side_bar_html` in your `onreadystatechange` function, so that it doesn't get used before it's set.
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": "<p>Not tested, but how about via an <code>XmlDocument</code>:</p>\n\n<pre><code> XmlDocument doc = new XmlDocument();\n doc.Load(reader);\n XmlElement el = doc.DocumentElement;\n</code></pre>\n\n<p>Alternatively (from the cmoment), something like:</p>\n\n<pre><code> doc.LoadXml(reader.ReadOuterXml());\n</code></pre>\n\n<p>But actually I'm not a fan of that... it forces an additional xml-parse step (one of the more CPU-expensive operations) for no good reason. If the original is being glitchy, then perhaps consider a sub-reader:</p>\n\n<pre><code> using (XmlReader subReader = reader.ReadSubtree())\n {\n XmlDocument doc = new XmlDocument();\n doc.Load(subReader);\n XmlElement el = doc.DocumentElement;\n }\n</code></pre>\n" }, { "answer_id": 284580, "author": "Sunny Milenov", "author_id": 8220, "author_profile": "https://Stackoverflow.com/users/8220", "pm_score": 2, "selected": false, "text": "<p>Assuming that you have XmlDocument, where you need to attach the newly created XmlElement:</p>\n\n<pre><code>XmlElement myElement;\nmyXmlReader.Read();\nif (myXmlReader.NodeType == XmlNodeType.Element)\n{\n myElement = doc.CreateElement(myXmlReader.Name);\n myElement.InnerXml = myXmlReader.InnerXml;\n}\n</code></pre>\n\n<p>From the <a href=\"http://msdn.microsoft.com/en-us/library/system.xml.xmlelement.xmlelement.aspx\" rel=\"nofollow noreferrer\">docs</a>: Do not instantiate an XmlElement directly; instead, use methods such as CreateElement.</p>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1946/" ]
If I have an xmlreader instance how can I use it to read its current node and end up with a xmlElement instance?
Not tested, but how about via an `XmlDocument`: ``` XmlDocument doc = new XmlDocument(); doc.Load(reader); XmlElement el = doc.DocumentElement; ``` Alternatively (from the cmoment), something like: ``` doc.LoadXml(reader.ReadOuterXml()); ``` But actually I'm not a fan of that... it forces an additional xml-parse step (one of the more CPU-expensive operations) for no good reason. If the original is being glitchy, then perhaps consider a sub-reader: ``` using (XmlReader subReader = reader.ReadSubtree()) { XmlDocument doc = new XmlDocument(); doc.Load(subReader); XmlElement el = doc.DocumentElement; } ```
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": "<p>It depends on the scenario. <code>XmlSerializer</code> is certainly one way and has the advantage of mapping directly to an object model. In .NET 3.5, <code>XDocument</code>, etc. are also very friendly. If the size is very large, then <code>XmlWriter</code> is your friend.</p>\n\n<p>For an <code>XDocument</code> example:</p>\n\n<pre><code>Console.WriteLine(\n new XElement(\"Foo\",\n new XAttribute(\"Bar\", \"some &amp; value\"),\n new XElement(\"Nested\", \"data\")));\n</code></pre>\n\n<p>Or the same with <code>XmlDocument</code>:</p>\n\n<pre><code>XmlDocument doc = new XmlDocument();\nXmlElement el = (XmlElement)doc.AppendChild(doc.CreateElement(\"Foo\"));\nel.SetAttribute(\"Bar\", \"some &amp; value\");\nel.AppendChild(doc.CreateElement(\"Nested\")).InnerText = \"data\";\nConsole.WriteLine(doc.OuterXml);\n</code></pre>\n\n<p>If you are writing a <strong>large</strong> stream of data, then any of the DOM approaches (such as <code>XmlDocument</code>/<code>XDocument</code>, etc.) will quickly take a lot of memory. So if you are writing a 100&nbsp;MB XML file from <a href=\"http://en.wikipedia.org/wiki/Comma-separated_values\" rel=\"noreferrer\">CSV</a>, you might consider <code>XmlWriter</code>; this is more primitive (a write-once firehose), but very efficient (imagine a big loop here):</p>\n\n<pre><code>XmlWriter writer = XmlWriter.Create(Console.Out);\nwriter.WriteStartElement(\"Foo\");\nwriter.WriteAttributeString(\"Bar\", \"Some &amp; value\");\nwriter.WriteElementString(\"Nested\", \"data\");\nwriter.WriteEndElement();\n</code></pre>\n\n<p>Finally, via <code>XmlSerializer</code>:</p>\n\n<pre><code>[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 &amp; value\",\n Nested = \"data\"\n};\nnew XmlSerializer(typeof(Foo)).Serialize(Console.Out, foo);\n</code></pre>\n\n<p>This is a nice model for mapping to classes, etc.; however, it might be overkill if you are doing something simple (or if the desired XML doesn't really have a direct correlation to the object model). Another issue with <code>XmlSerializer</code> is that it doesn't like to serialize immutable types : everything must have a public getter <em>and</em> setter (unless you do it all yourself by implementing <code>IXmlSerializable</code>, in which case you haven't gained much by using <code>XmlSerializer</code>).</p>\n" }, { "answer_id": 284348, "author": "Mikael Söderström", "author_id": 36944, "author_profile": "https://Stackoverflow.com/users/36944", "pm_score": 3, "selected": false, "text": "<p>XmlWriter is the fastest way to write good XML. XDocument, XMLDocument and some others works good aswell, but are not optimized for writing XML. If you want to write the XML as fast as possible, you should definitely use XmlWriter.</p>\n" }, { "answer_id": 284351, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 1, "selected": false, "text": "<p>For simple things, I just use the XmlDocument/XmlNode/XmlAttribute classes and XmlDocument DOM found in System.XML.</p>\n\n<p>It generates the XML for me, I just need to link a few items together.</p>\n\n<p>However, on larger things, I use XML serialization.</p>\n" }, { "answer_id": 284369, "author": "Todd", "author_id": 31940, "author_profile": "https://Stackoverflow.com/users/31940", "pm_score": 1, "selected": false, "text": "<p>For simple cases, I would also suggest looking at <a href=\"http://www.improve.dk/blog/2008/08/10/updating-xmloutput\" rel=\"nofollow noreferrer\">XmlOutput</a> a fluent interface for building Xml.</p>\n\n<p>XmlOutput is great for simple Xml creation with readable and maintainable code, while generating valid Xml. The <a href=\"http://www.improve.dk/blog/2007/10/20/xmldocument-fluent-interface\" rel=\"nofollow noreferrer\">orginal post</a> has some great examples.</p>\n" }, { "answer_id": 284371, "author": "Bob", "author_id": 45, "author_profile": "https://Stackoverflow.com/users/45", "pm_score": 2, "selected": false, "text": "<p>In the past I have created my XML Schema, then used a tool to generate C# classes which will serialize to that schema. The XML Schema Definition Tool is one example</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/x6c1kb0s(VS.71).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/x6c1kb0s(VS.71).aspx</a></p>\n" }, { "answer_id": 285381, "author": "GurdeepS", "author_id": 32484, "author_profile": "https://Stackoverflow.com/users/32484", "pm_score": -1, "selected": false, "text": "<p>As above.</p>\n\n<p>I use stringbuilder.append().</p>\n\n<p>Very straightforward, and you can then do xmldocument.load(strinbuilder object as parameter).</p>\n\n<p>You will probably find yourself using string.concat within the append parameter, but this is a very straightforward approach.</p>\n" }, { "answer_id": 1365017, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "<p>The best thing hands down that I have tried is <a href=\"http://linqtoxsd.codeplex.com/\" rel=\"noreferrer\">LINQ to XSD</a> (which is unknown to most developers). You give it an XSD Schema and it generates a perfectly mapped complete strongly-typed object model (based on LINQ to XML) for you in the background, which is really easy to work with - and it updates and validates your object model and XML in real-time. While it's still \"Preview\", I have not encountered any bugs with it.</p>\n\n<p>If you have an XSD Schema that looks like this:</p>\n\n<pre><code> &lt;xs:element name=\"RootElement\"&gt;\n &lt;xs:complexType&gt;\n &lt;xs:sequence&gt;\n &lt;xs:element name=\"Element1\" type=\"xs:string\" /&gt;\n &lt;xs:element name=\"Element2\" type=\"xs:string\" /&gt;\n &lt;/xs:sequence&gt;\n &lt;xs:attribute name=\"Attribute1\" type=\"xs:integer\" use=\"optional\" /&gt;\n &lt;xs:attribute name=\"Attribute2\" type=\"xs:boolean\" use=\"required\" /&gt;\n &lt;/xs:complexType&gt;\n &lt;/xs:element&gt;\n</code></pre>\n\n<p>Then you can simply build XML like this:</p>\n\n<pre><code>RootElement rootElement = new RootElement;\nrootElement.Element1 = \"Element1\";\nrootElement.Element2 = \"Element2\";\nrootElement.Attribute1 = 5;\nrootElement.Attribute2 = true;\n</code></pre>\n\n<p>Or simply load an XML from file like this:</p>\n\n<pre><code>RootElement rootElement = RootElement.Load(filePath);\n</code></pre>\n\n<p>Or save it like this:</p>\n\n<pre><code>rootElement.Save(string);\nrootElement.Save(textWriter);\nrootElement.Save(xmlWriter);\n</code></pre>\n\n<p><code>rootElement.Untyped</code> also yields the element in form of a XElement (from LINQ to XML).</p>\n" }, { "answer_id": 1767005, "author": "Vincent", "author_id": 215034, "author_profile": "https://Stackoverflow.com/users/215034", "pm_score": 5, "selected": false, "text": "<pre><code>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</code></pre>\n" }, { "answer_id": 4409887, "author": "swdev", "author_id": 427793, "author_profile": "https://Stackoverflow.com/users/427793", "pm_score": 2, "selected": false, "text": "<p>I think this resource should suffice for a moderate XML save/load: <a href=\"http://www.java2s.com/Code/CSharp/XML/ReadandWriteXMLWithoutLoadinganEntireDocumentintoMemory.htm\" rel=\"nofollow\">Read/Write XML using C#</a>.</p>\n\n<p>My task was to store musical notation. I choose XML, because I guess <a href=\"http://en.wikipedia.org/wiki/.NET_Framework\" rel=\"nofollow\">.NET</a> has matured enough to allow easy solution for the task. I was right :)</p>\n\n<p>This is my song file prototype:</p>\n\n<pre><code>&lt;music judul=\"Kupu-Kupu yang Lucu\" pengarang=\"Ibu Sud\" tempo=\"120\" birama=\"4/4\" nadadasar=\"1=F\" biramapembilang=\"4\" biramapenyebut=\"4\"&gt;\n &lt;not angka=\"1\" oktaf=\"0\" naikturun=\"\" nilai=\"1\"/&gt;\n &lt;not angka=\"2\" oktaf=\"0\" naikturun=\"\" nilai=\"0.5\"/&gt;\n &lt;not angka=\"5\" oktaf=\"1\" naikturun=\"/\" nilai=\"0.25\"/&gt;\n &lt;not angka=\"2\" oktaf=\"0\" naikturun=\"\\\" nilai=\"0.125\"/&gt;\n &lt;not angka=\"1\" oktaf=\"0\" naikturun=\"\" nilai=\"0.0625\"/&gt;\n&lt;/music&gt;\n</code></pre>\n\n<p>That can be solved quite easily:</p>\n\n<p>For Save to File:</p>\n\n<pre><code> 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 &lt; 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</code></pre>\n\n<p>For load file:</p>\n\n<pre><code>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</code></pre>\n" } ]
2008/11/12
[ "https://Stackoverflow.com/questions/284324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19020/" ]
How can I generate valid XML in C#?
It depends on the scenario. `XmlSerializer` is certainly one way and has the advantage of mapping directly to an object model. In .NET 3.5, `XDocument`, etc. are also very friendly. If the size is very large, then `XmlWriter` is your friend. For an `XDocument` example: ``` Console.WriteLine( new XElement("Foo", new XAttribute("Bar", "some & value"), new XElement("Nested", "data"))); ``` Or the same with `XmlDocument`: ``` XmlDocument doc = new XmlDocument(); XmlElement el = (XmlElement)doc.AppendChild(doc.CreateElement("Foo")); el.SetAttribute("Bar", "some & value"); el.AppendChild(doc.CreateElement("Nested")).InnerText = "data"; Console.WriteLine(doc.OuterXml); ``` If you are writing a **large** stream of data, then any of the DOM approaches (such as `XmlDocument`/`XDocument`, etc.) will quickly take a lot of memory. So if you are writing a 100 MB XML file from [CSV](http://en.wikipedia.org/wiki/Comma-separated_values), you might consider `XmlWriter`; this is more primitive (a write-once firehose), but very efficient (imagine a big loop here): ``` XmlWriter writer = XmlWriter.Create(Console.Out); writer.WriteStartElement("Foo"); writer.WriteAttributeString("Bar", "Some & value"); writer.WriteElementString("Nested", "data"); writer.WriteEndElement(); ``` Finally, via `XmlSerializer`: ``` [Serializable] public class Foo { [XmlAttribute] public string Bar { get; set; } public string Nested { get; set; } } ... Foo foo = new Foo { Bar = "some & value", Nested = "data" }; new XmlSerializer(typeof(Foo)).Serialize(Console.Out, foo); ``` This is a nice model for mapping to classes, etc.; however, it might be overkill if you are doing something simple (or if the desired XML doesn't really have a direct correlation to the object model). Another issue with `XmlSerializer` is that it doesn't like to serialize immutable types : everything must have a public getter *and* setter (unless you do it all yourself by implementing `IXmlSerializable`, in which case you haven't gained much by using `XmlSerializer`).