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
162,571
<p>I've executed a JDBC query to obtain a resultset. Before iterating over it, I'd like to quickly find out how many rows were returned. How can I do this with high performance?</p> <p>I'm using Java 6, Oracle 11g, and the latest Oracle JDBC drivers.</p>
[ { "answer_id": 162581, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 4, "selected": false, "text": "<p>Short answer: you can't.</p>\n\n<p>Long answer: you can't, partly because the database may be lazily evaluating the query, only returning rows as you ask for them.</p>\n\n<p>EDIT: Using a scrollable ResultSet you can :)</p>\n\n<p>Indeed, I asked this very question in the Java databases newsgroup a long time ago (back in 2001!) and had some <a href=\"http://groups.google.com/group/comp.lang.java.databases/browse_frm/thread/f5142687a3d492fd/cda88f3b14649c8e\" rel=\"noreferrer\">helpful responses</a>.</p>\n" }, { "answer_id": 162597, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 2, "selected": false, "text": "<p>If your driver supports it(!), you can call <code>ResultSet.afterLast()</code> <code>ResultSet.getRow()</code> <code>ResultSet.beforeFirst()</code>. Performance may or may not be good.</p>\n\n<p>A better solution would be to rewrite your algorithm not to require the size up front.</p>\n" }, { "answer_id": 162629, "author": "cletus", "author_id": 18393, "author_profile": "https://Stackoverflow.com/users/18393", "pm_score": 6, "selected": true, "text": "<p>You're going to have to do this as a separate query, for example:</p>\n\n<pre><code>SELECT COUNT(1) FROM table_name\n</code></pre>\n\n<p>Some JDBC drivers might tell you but this is optional behaviour and, more to the point, the driver may not know yet. This can be due to how the query is optimised eg two example execution strategies in Oracle are to get all rows as quickly as possible or to get the first row as quickly as possible.</p>\n\n<p>If you do two separate queries (one a count and the other the query) then you'll need to do them within the same transaction. This will work well on Oracle but can be problematic on other databases (eg SQL Server will either show you uncommitted data or block on an external uncommitted update depending on your isolation level whereas Oracle supports an isolation level that gives you a transactionally consistent view of the data without blocking on external updates).</p>\n\n<p>Normally though it doesn't really matter how many rows there are. Typically this sort of query is either batch processed or paged and either way you have progress information in the form of rows loaded/processed and you can detect the end of the result set (obviously).</p>\n" }, { "answer_id": 10139221, "author": "thezar", "author_id": 978036, "author_profile": "https://Stackoverflow.com/users/978036", "pm_score": 5, "selected": false, "text": "<pre><code>ResultSet rs = stmt.executeQuery(sql);\nint rowCount = rs.last() ? rs.getRow() : 0; // Number of rows in result set. Don't forget to set cyrsor to beforeFirst() row! :)\n</code></pre>\n" }, { "answer_id": 16268359, "author": "MindBrain", "author_id": 1118559, "author_profile": "https://Stackoverflow.com/users/1118559", "pm_score": 0, "selected": false, "text": "<p>Code:</p>\n\n<pre><code>//Create a Statement class to execute the SQL statement\nStatement stmt = con.createStatement();\n\nResultSet rs = stmt.executeQuery(\"SELECT COUNT(*) AS COUNT FROM\nTABLENAME\");\n\n while(rs.next()) {\n System.out.println(\"The count is \" + rs.getInt(\"COUNT\"));\n }\n\n //Closing the connection\n con.close();\n</code></pre>\n" }, { "answer_id": 17718051, "author": "user2594537", "author_id": 2594537, "author_profile": "https://Stackoverflow.com/users/2594537", "pm_score": 4, "selected": false, "text": "<p>To get the number of rows from JDBC:</p>\n\n<pre><code>ResultSet rs = st.executeQuery(\"select count(*) from TABLE_NAME\");\nrs.next();\nint count = rs.getInt(1);\n</code></pre>\n" }, { "answer_id": 51537403, "author": "v8-E", "author_id": 8064000, "author_profile": "https://Stackoverflow.com/users/8064000", "pm_score": 2, "selected": false, "text": "<p><strong>Without ternary operator</strong> </p>\n\n<pre><code>rs.last(); // Moves the cursor to the last row in this ResultSet object.\nint rowCount = rs.getRow(); //Retrieves the current row number.\nrs.beforeFirst(); //Moves the cursor to the front of this ResultSet object,just before the first row.\n</code></pre>\n\n<p><strong>With ternary operator one line</strong> </p>\n\n<pre><code>int rowCount = rs.last() ? rs.getRow() : 0; \nrs.beforeFirst();\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162571", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2959/" ]
I've executed a JDBC query to obtain a resultset. Before iterating over it, I'd like to quickly find out how many rows were returned. How can I do this with high performance? I'm using Java 6, Oracle 11g, and the latest Oracle JDBC drivers.
You're going to have to do this as a separate query, for example: ``` SELECT COUNT(1) FROM table_name ``` Some JDBC drivers might tell you but this is optional behaviour and, more to the point, the driver may not know yet. This can be due to how the query is optimised eg two example execution strategies in Oracle are to get all rows as quickly as possible or to get the first row as quickly as possible. If you do two separate queries (one a count and the other the query) then you'll need to do them within the same transaction. This will work well on Oracle but can be problematic on other databases (eg SQL Server will either show you uncommitted data or block on an external uncommitted update depending on your isolation level whereas Oracle supports an isolation level that gives you a transactionally consistent view of the data without blocking on external updates). Normally though it doesn't really matter how many rows there are. Typically this sort of query is either batch processed or paged and either way you have progress information in the form of rows loaded/processed and you can detect the end of the result set (obviously).
162,576
<p>I've been battling PHP's email reading functions for the better part of two days. I'm writing a script to read emails from a mailbox and save any attachments onto the server. If you've ever done something similar, you might understand my pain: <strong>PHP doesn't play well with email!</strong></p> <p>I've connected to the POP3 server and I can iterate the files. Here's a rough outline of the code:</p> <pre><code>if (!$mbox = imap_open ("{myserver.com:110/pop3/notls}INBOX", "u", "p")) die ('Cannot connect/check mail! Exiting'); if ($hdr = imap_check($mbox)) $msgCount = $hdr-&gt;Nmsgs; else die ("Failed to get mail"); foreach ($overview as $message) { $msgStruct = imap_fetchstructure($mbox, $message-&gt;msgno); // if it has parts, there are attachments that need reading if ($msgStruct-&gt;parts) { foreach ($msgStruct-&gt;parts as $key =&gt; $part) { switch (strtoupper($part-&gt;subtype)) { case 'GIF': case 'JPEG':case 'PNG': //do something - but what?! break; } } } } </code></pre> <p>I've marked where I'm stuck. I can use <code>imap_fetchbody($mbox, $message-&gt;msgno, $key+1)</code> but that gets me a bunch of data like this:</p> <pre><code>/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAUDBAQEAwUEBAQFBQUGBwwIBwcHBw8LCwkMEQ8S EhEPERETFhwXExQaFRERGCEYGh0dHx8fExciJCIeJBweHx7/2wBDAQUFBQcGBw4ICA4eFBEU Hh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh7/wAAR CAHiAi0DASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAA AgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkK FhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWG h4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl 5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREA ... </code></pre> <p>I'm lead to believe that this is MIME data. I need it as an image! I've seen several classes bombing around the internet that claim to do the required wizardry. I can't get any of them to work. I don't understand why I'm finding this so hard!</p> <p><strong>In short</strong>, I'm looking for something that can turn a raw MIME string into real data.</p>
[ { "answer_id": 162589, "author": "Ben", "author_id": 11522, "author_profile": "https://Stackoverflow.com/users/11522", "pm_score": 1, "selected": false, "text": "<p>MIME data is base-64 encoded, so I think you should be able to decode it using base64_decode</p>\n" }, { "answer_id": 162611, "author": "kender", "author_id": 4172, "author_profile": "https://Stackoverflow.com/users/4172", "pm_score": 3, "selected": true, "text": "<p>I found a quick guide how to treat emails with PHP: <a href=\"http://www.linuxscope.net/articles/mailAttachmentsPHP.html\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>At the bottom of that page there's a attachment-body <code>echo</code>:</p>\n\n<pre><code>if (substr($ContentType,0,4) == \"text\") {\necho imap_qprint($fileContent);\n} else {\necho imap_base64($fileContent);\n}\n</code></pre>\n\n<p>I guess this is what you might need... </p>\n\n<p>(edit: in your case if it's image always you can skip the <code>if</code> part. And of course, save the file instead of echoing it:)</p>\n" }, { "answer_id": 162637, "author": "Cetra", "author_id": 15087, "author_profile": "https://Stackoverflow.com/users/15087", "pm_score": 1, "selected": false, "text": "<p>you can use the <a href=\"http://php.net/manual/en/function.imap-base64.php\" rel=\"nofollow noreferrer\"> <code>imap_base64</code> </a> function and just output that to a file, or use <a href=\"http://php.net/manual/en/function.imap-savebody.php\" rel=\"nofollow noreferrer\"> <code>imap_savebody</code> </a></p>\n" }, { "answer_id": 162638, "author": "Joeri Sebrechts", "author_id": 20980, "author_profile": "https://Stackoverflow.com/users/20980", "pm_score": 1, "selected": false, "text": "<p>Zend framework contains Zend_Mail, which should make reading mail messages much easier, and Zend_Mime, which I believe can parse a multipart mime message into a sensible data structure.</p>\n\n<p><a href=\"http://framework.zend.com/manual/en/zend.mail.read.html\" rel=\"nofollow noreferrer\">http://framework.zend.com/manual/en/zend.mail.read.html</a></p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12870/" ]
I've been battling PHP's email reading functions for the better part of two days. I'm writing a script to read emails from a mailbox and save any attachments onto the server. If you've ever done something similar, you might understand my pain: **PHP doesn't play well with email!** I've connected to the POP3 server and I can iterate the files. Here's a rough outline of the code: ``` if (!$mbox = imap_open ("{myserver.com:110/pop3/notls}INBOX", "u", "p")) die ('Cannot connect/check mail! Exiting'); if ($hdr = imap_check($mbox)) $msgCount = $hdr->Nmsgs; else die ("Failed to get mail"); foreach ($overview as $message) { $msgStruct = imap_fetchstructure($mbox, $message->msgno); // if it has parts, there are attachments that need reading if ($msgStruct->parts) { foreach ($msgStruct->parts as $key => $part) { switch (strtoupper($part->subtype)) { case 'GIF': case 'JPEG':case 'PNG': //do something - but what?! break; } } } } ``` I've marked where I'm stuck. I can use `imap_fetchbody($mbox, $message->msgno, $key+1)` but that gets me a bunch of data like this: ``` /9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAUDBAQEAwUEBAQFBQUGBwwIBwcHBw8LCwkMEQ8S EhEPERETFhwXExQaFRERGCEYGh0dHx8fExciJCIeJBweHx7/2wBDAQUFBQcGBw4ICA4eFBEU Hh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh7/wAAR CAHiAi0DASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAA AgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkK FhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWG h4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl 5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREA ... ``` I'm lead to believe that this is MIME data. I need it as an image! I've seen several classes bombing around the internet that claim to do the required wizardry. I can't get any of them to work. I don't understand why I'm finding this so hard! **In short**, I'm looking for something that can turn a raw MIME string into real data.
I found a quick guide how to treat emails with PHP: [here](http://www.linuxscope.net/articles/mailAttachmentsPHP.html). At the bottom of that page there's a attachment-body `echo`: ``` if (substr($ContentType,0,4) == "text") { echo imap_qprint($fileContent); } else { echo imap_base64($fileContent); } ``` I guess this is what you might need... (edit: in your case if it's image always you can skip the `if` part. And of course, save the file instead of echoing it:)
162,617
<p>When creating a new file with vim, I would like to automatically add some skeleton code.</p> <p>For example, when creating a new xml file, I would like to add the first line:</p> <pre><code> &lt;?xml version="1.0"?&gt; </code></pre> <p>Or when creating an html file, I would like to add:</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "answer_id": 162654, "author": "Oli", "author_id": 22035, "author_profile": "https://Stackoverflow.com/users/22035", "pm_score": 1, "selected": false, "text": "<p>Here are two examples using python scripting.</p>\n\n<p>Add something like this in your .vimrc or another file sourced by your .vimrc:</p>\n\n<pre><code>augroup Xml\n au BufNewFile *.xml :python import vim\n au BufNewFile *.xml :python vim.current.buffer[0:0] = ['&lt;?xml version=\"1.0\"?&gt;']\n au BufNewFile *.xml :python del vim\naugroup END\n\nfu s:InsertHtmlSkeleton()\n python import vim\n python vim.current.buffer[0:0] = ['&lt;!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\"&gt;', \"&lt;html&gt;\", \"&lt;head&gt;\", \" &lt;title&gt;&lt;/title&gt;\", \"&lt;/head&gt;\", \"&lt;body&gt;\", \"\", \"&lt;/body&gt;\", \"&lt;/html&gt;\"]\n python del vim\nendfu\n\naugroup Html\n au BufNewFile *.html call &lt;SID&gt;InsertHtmlSkeleton()\naugroup END\n</code></pre>\n" }, { "answer_id": 162662, "author": "davetron5000", "author_id": 3029, "author_profile": "https://Stackoverflow.com/users/3029", "pm_score": 1, "selected": false, "text": "<p>You can add various hooks when files are read or created. to</p>\n\n<pre><code>:help event\n</code></pre>\n\n<p>and read what's there. What you want is</p>\n\n<pre><code>:help BufNewFile\n</code></pre>\n" }, { "answer_id": 162671, "author": "kender", "author_id": 4172, "author_profile": "https://Stackoverflow.com/users/4172", "pm_score": 5, "selected": false, "text": "<p>I got something like this in my .vimrc:</p>\n\n<pre><code>au BufNewFile *.xml 0r ~/.vim/xml.skel | let IndentStyle = \"xml\"\nau BufNewFile *.html 0r ~/.vim/html.skel | let IndentStyle = \"html\"\n</code></pre>\n\n<p>And so on, whatever you'll need.</p>\n" }, { "answer_id": 162704, "author": "erichui", "author_id": 6034, "author_profile": "https://Stackoverflow.com/users/6034", "pm_score": 4, "selected": false, "text": "<p>You can save your skeleton/template to a file, for example ~/vim/skeleton.xml</p>\n\n<p>Then add the following to your .vimrc</p>\n\n<pre><code>augroup Xml\n au BufNewFile *.xml 0r ~/vim/skeleton.xml\naugroup end\n</code></pre>\n" }, { "answer_id": 162811, "author": "Luc Hermitte", "author_id": 15934, "author_profile": "https://Stackoverflow.com/users/15934", "pm_score": 4, "selected": true, "text": "<p>If you want to adapt your skeleton to the context, or to the user choices, have a look at the template-expander plugins listed on <a href=\"http://vim.wikia.com/wiki/Category:Automated_Text_Insertion\" rel=\"nofollow noreferrer\">vim.wikia</a></p>\n" }, { "answer_id": 7264817, "author": "orftz", "author_id": 603891, "author_profile": "https://Stackoverflow.com/users/603891", "pm_score": 3, "selected": false, "text": "<p>Sorry for the lateness, but I feel the way <a href=\"https://github.com/astrails/dotvim\" rel=\"nofollow noreferrer\">I do it</a> might be useful to some. It uses the file's filetype, making it shorter and more dynamic than more conventional methods. It was tested only on Vim 7.3.</p>\n\n<pre><code>if has(\"win32\") || has ('win64')\n let $VIMHOME = $HOME.\"/vimfiles/\"\nelse\n let $VIMHOME = $HOME.\"/.vim/\"\nendif\n\n\" add templates in templates/ using filetype as file name\nau BufNewFile * :silent! exec \":0r \".$VIMHOME.\"templates/\".&amp;ft\n</code></pre>\n" }, { "answer_id": 26910252, "author": "ibizaman", "author_id": 1013628, "author_profile": "https://Stackoverflow.com/users/1013628", "pm_score": 0, "selected": false, "text": "<p>It can work with snipmate too:</p>\n\n<pre class=\"lang-bash prettyprint-override\"><code>augroup documentation\n au!\n au BufNewFile *.py :call ExecuteSnippet('docs')\naugroup END\n\nfunction! ExecuteSnippet(name)\n execute \"normal! i\" . a:name . \"\\&lt;c-r&gt;=TriggerSnippet()\\&lt;cr&gt;\"\nendfunction\n</code></pre>\n\n<p>with \"docs\" the snippet to trigger.</p>\n\n<p>It works with multi-snippets but then the :messages window appears and it's cumbersome.</p>\n" }, { "answer_id": 30012516, "author": "linuscl", "author_id": 3297638, "author_profile": "https://Stackoverflow.com/users/3297638", "pm_score": 0, "selected": false, "text": "<p>I wrote a plugin for html:</p>\n\n<p>On vim scripts: <a href=\"http://www.vim.org/scripts/script.php?script_id=4845\" rel=\"nofollow\">http://www.vim.org/scripts/script.php?script_id=4845</a></p>\n\n<p>On Github: <a href=\"https://github.com/linuscl/vim-htmltemplate\" rel=\"nofollow\">https://github.com/linuscl/vim-htmltemplate</a></p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24076/" ]
When creating a new file with vim, I would like to automatically add some skeleton code. For example, when creating a new xml file, I would like to add the first line: ``` <?xml version="1.0"?> ``` Or when creating an html file, I would like to add: ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html> <head> <title></title> </head> <body> </body> </html> ```
If you want to adapt your skeleton to the context, or to the user choices, have a look at the template-expander plugins listed on [vim.wikia](http://vim.wikia.com/wiki/Category:Automated_Text_Insertion)
162,651
<p>What is the difference between these two pieces of code</p> <pre><code>type IInterface1 = interface procedure Proc1; end; IInterface2 = interface procedure Proc2; end; TMyClass = class(TInterfacedObject, IInterface1, IInterface2) protected procedure Proc1; procedure Proc2; end; </code></pre> <p>And the following :</p> <pre><code>type IInterface1 = interface procedure Proc1; end; IInterface2 = interface(Interface1) procedure Proc2; end; TMyClass = class(TInterfacedObject, IInterface2) protected procedure Proc1; procedure Proc2; end; </code></pre> <p>If they are one and the same, are there any advantages, or readability issues with either.</p> <p>I guess the second means you cannot write a class that implements IInterface2 without implementing IInterface1, whilst with the first you can.</p>
[ { "answer_id": 162682, "author": "Joe Skora", "author_id": 14057, "author_profile": "https://Stackoverflow.com/users/14057", "pm_score": 1, "selected": false, "text": "<p>Assuming you meant</p>\n\n<pre><code>...\nIInterface2 = interface(Interface1)\n...\n</code></pre>\n\n<p>I interpret it the same as you, <strong>the second form requires a class implementing Interface2 to implement Interface1 as well</strong>, while the first form does not.</p>\n" }, { "answer_id": 162702, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>I guess the second means you cannot write a class that implements IInterface2 without implementing IInterface1, whilst with the first you can.</p>\n</blockquote>\n\n<p>That would be the technical difference.</p>\n\n<p>Which one is better depends very much on what the interfaces actually are. Does it ever make sense for an IInterface2 to exist without it also being an IInterface1?</p>\n\n<p>If IInterface1 is \"displayable\" and IInterface2 is \"storable,\" then the first option probably makes more sense. If IInterface1 is \"vehicle\" and IInterface2 is \"truck,\" then the second option probably makes much more sense.</p>\n" }, { "answer_id": 162706, "author": "Dave Sherohman", "author_id": 18914, "author_profile": "https://Stackoverflow.com/users/18914", "pm_score": 3, "selected": true, "text": "<p>First off, I'm assuming that the second example's declaration for IInterface2 is a typo and should be</p>\n\n<pre><code>IInterface2 = interface(Interface1)\n</code></pre>\n\n<p>because inheriting from itself is nonsensical (even if the compiler accepted it).</p>\n\n<p>And \"inheriting\" is the key word there for answering your question. In example 1 the two interfaces are completely independent and you can implement one, the other, or both without problems. In example 2, you are correct that you can't implement interface2 without also implementing interface1, but the reason why that's so is because it makes interface1 <em>a part of</em> interface2.</p>\n\n<p>The difference, then, is primarily structural and organizational, not just readability.</p>\n" }, { "answer_id": 164141, "author": "Barry Kelly", "author_id": 3712, "author_profile": "https://Stackoverflow.com/users/3712", "pm_score": 3, "selected": false, "text": "<p>The two snippets of code have very different effects, and are in almost no way equivalent, if we are talking about Delphi for Win32 (Delphi for .NET has different rules).</p>\n\n<ol>\n<li>A class that implements its interface must implement all the members of that interface's ancestors, but it does <strong>not</strong> implicitly implement the ancestors. Thus, attempts to assign instances of type TMyClass to locations of type IInterface1 will fail for the second case.</li>\n<li>Related to the previous point, if IInterface1 and IInterface2 both had GUIDs, dynamic casts (using <code>Supports</code> or '<code>as</code>') of interface references with a target type of IInterface1 would fail on instances of TMyClass in the second case.</li>\n<li>The interface IInterface2 has an extra method in the second case, which it does not in the first.</li>\n<li>Values of type IInterface2 in the second case are assignable to locations of type IInterface1; this is not true for the first case.</li>\n</ol>\n\n<p>See for yourself in this example:</p>\n\n<pre><code> type\n A_I1 = interface\n end;\n\n A_I2 = interface(A_I1)\n end;\n\n A_Class = class(TInterfacedObject, A_I2)\n end;\n\n procedure TestA;\n var\n a: A_Class;\n x: A_I1;\n begin\n a := A_Class.Create;\n x := a; // fails!\n end;\n\n type\n B_I1 = interface\n end;\n\n B_I2 = interface\n end;\n\n B_Class = class(TInterfacedObject, B_I1, B_I2)\n end;\n\n procedure TestB;\n var\n a: B_Class;\n x: B_I1;\n begin\n a := B_Class.Create;\n x := a; // succeeds!\n end;\n\n begin\n TestA;\n TestB;\n end.\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22712/" ]
What is the difference between these two pieces of code ``` type IInterface1 = interface procedure Proc1; end; IInterface2 = interface procedure Proc2; end; TMyClass = class(TInterfacedObject, IInterface1, IInterface2) protected procedure Proc1; procedure Proc2; end; ``` And the following : ``` type IInterface1 = interface procedure Proc1; end; IInterface2 = interface(Interface1) procedure Proc2; end; TMyClass = class(TInterfacedObject, IInterface2) protected procedure Proc1; procedure Proc2; end; ``` If they are one and the same, are there any advantages, or readability issues with either. I guess the second means you cannot write a class that implements IInterface2 without implementing IInterface1, whilst with the first you can.
First off, I'm assuming that the second example's declaration for IInterface2 is a typo and should be ``` IInterface2 = interface(Interface1) ``` because inheriting from itself is nonsensical (even if the compiler accepted it). And "inheriting" is the key word there for answering your question. In example 1 the two interfaces are completely independent and you can implement one, the other, or both without problems. In example 2, you are correct that you can't implement interface2 without also implementing interface1, but the reason why that's so is because it makes interface1 *a part of* interface2. The difference, then, is primarily structural and organizational, not just readability.
162,674
<p>When using tooltips to show a detailed description of a TreeNode, the tooltip is drawn on top of the node, as if it was completing the node's text. Also, if the text is long, the tooltip is positioned in a way that the <strong>text exceeds the screen</strong>. </p> <p>But what I need is the tooltip to show right below the mouse pointer and not on top of the TreeNode.</p> <p>Any idea how to do this?</p> <hr> <p>Show, don't tell:</p> <p>How it is: </p> <p><a href="https://i.stack.imgur.com/aqDww.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aqDww.png" alt="how it is"></a> </p> <p>How I want: </p> <p><a href="https://i.stack.imgur.com/buIrV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/buIrV.png" alt="how I want"></a> </p>
[ { "answer_id": 162769, "author": "Vivek", "author_id": 7418, "author_profile": "https://Stackoverflow.com/users/7418", "pm_score": 2, "selected": false, "text": "<p>You need to define a ToolTip and write an MouseOverEventHandler for the TreeView. In the MouseOverEventHandler calculate the node above which mouse is positioned, then show the description ToolTip. Also make sure you are not setting the tooltip description more than once, otherwise the behavior is quite ugly.</p>\n\n<p>A better way is to show the description in the StatusStrip - bottom left of the Form.</p>\n\n<p><strong>Update:</strong></p>\n\n<p>OK since you have clarified your question. You can use <code>ToolTip.Show</code> method where you can specify coordinates:</p>\n\n<pre><code>public void Show(\n string text,\n IWin32Window window,\n int x,\n int y,\n int duration\n)\n</code></pre>\n\n<p>Obviously, you'll have to add offset to x and y.</p>\n" }, { "answer_id": 309457, "author": "Jonas", "author_id": 10833, "author_profile": "https://Stackoverflow.com/users/10833", "pm_score": 3, "selected": false, "text": "<p>I didn't find the answer I was looking for, but I somehow made it work the way I wanted.</p>\n\n<p>Before, I was trying to set up the tooltip as follows:</p>\n\n<pre><code> private void treeView1_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)\n {\n TreeNode node = treeView1.GetNodeAt(e.X, e.Y);\n if (node != null)\n {\n string text = GetNodeTooltip(node);\n string currentText = toolTip1.GetToolTip(treeView1);\n\n if (text.Equals(currentText) == false)\n {\n toolTip1.SetToolTip(treeView1, text);\n }\n }\n else\n {\n toolTip1.SetToolTip(tree, string.Empty);\n }\n }\n else\n {\n toolTip1.SetToolTip(tree, string.Empty);\n }\n }\n</code></pre>\n\n<p>Now, I just make <code>treeView1.ShowNodeToolTips=true</code> and when I create every node, I just set its <code>TreeNode.ToolTipText</code> value with the desired text.</p>\n" }, { "answer_id": 3541601, "author": "Boris Kalandarov", "author_id": 427631, "author_profile": "https://Stackoverflow.com/users/427631", "pm_score": 2, "selected": false, "text": "<pre><code>private ToolTip toolTipController = new ToolTip() { UseFading = false,UseAnimation = false};\n\nprotected override void OnMouseMove(MouseEventArgs e)\n{\n var node = GetNodeAt(e.X, e.Y);\n if (node != null)\n {\n var text = node.Text;\n\n if (!text.Equals(toolTipController.GetToolTip(this)))\n {\n toolTipController.Show(text, this, e.Location, 2000);\n }\n }\n else\n {\n toolTipController.RemoveAll();\n }\n}\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10833/" ]
When using tooltips to show a detailed description of a TreeNode, the tooltip is drawn on top of the node, as if it was completing the node's text. Also, if the text is long, the tooltip is positioned in a way that the **text exceeds the screen**. But what I need is the tooltip to show right below the mouse pointer and not on top of the TreeNode. Any idea how to do this? --- Show, don't tell: How it is: [![how it is](https://i.stack.imgur.com/aqDww.png)](https://i.stack.imgur.com/aqDww.png) How I want: [![how I want](https://i.stack.imgur.com/buIrV.png)](https://i.stack.imgur.com/buIrV.png)
I didn't find the answer I was looking for, but I somehow made it work the way I wanted. Before, I was trying to set up the tooltip as follows: ``` private void treeView1_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e) { TreeNode node = treeView1.GetNodeAt(e.X, e.Y); if (node != null) { string text = GetNodeTooltip(node); string currentText = toolTip1.GetToolTip(treeView1); if (text.Equals(currentText) == false) { toolTip1.SetToolTip(treeView1, text); } } else { toolTip1.SetToolTip(tree, string.Empty); } } else { toolTip1.SetToolTip(tree, string.Empty); } } ``` Now, I just make `treeView1.ShowNodeToolTips=true` and when I create every node, I just set its `TreeNode.ToolTipText` value with the desired text.
162,677
<p>How would I write a Perl CGI script that receives a file via a HTTP post and saves that to the file system?</p>
[ { "answer_id": 162724, "author": "kender", "author_id": 4172, "author_profile": "https://Stackoverflow.com/users/4172", "pm_score": 4, "selected": true, "text": "<p>Just a note: however you will write it, <strong>don't</strong> save it in a place accessible from your web-server.</p>\n\n<p>And now to the point: below is a script which I was using for some time for photo-uploading. It might need some tweaking, but should show you the way.</p>\n\n<p>As the image isnt uploaded to web-accesible directory, we then have separate process checking it, resizing, putting a watermark and placing it where it can be accessed.</p>\n\n<pre><code> #!/usr/bin/perl -wT\n\nuse strict;\nuse CGI;\nuse CGI::Carp qw ( fatalsToBrowser );\nuse File::Basename;\n\n$CGI::POST_MAX = 1024 * 5000;\nmy $safe_filename_characters = \"a-zA-Z0-9_.-\";\nmy $upload_dir = \"/home/www/upload\";\n\nmy $query = new CGI;\nmy $filename = $query-&gt;param(\"photo\");\nmy $email_address = $query-&gt;param(\"email_address\");\n\nif ( !$filename )\n{\n print $query-&gt;header ( );\n print \"There was a problem uploading your photo (try a smaller file).\";\n exit;\n}\n\nmy ( $name, $path, $extension ) = fileparse ( $filename, '\\..*' );\n$filename = $name . $extension;\n$filename =~ tr/ /_/;\n$filename =~ s/[^$safe_filename_characters]//g;\n\nif ( $filename =~ /^([$safe_filename_characters]+)$/ )\n{\n $filename = $1;\n}\nelse\n{\n die \"Filename contains invalid characters\";\n}\n\nmy $upload_filehandle = $query-&gt;upload(\"photo\");\n\nopen ( UPLOADFILE, \"&gt;$upload_dir/$filename\" ) or die \"$!\";\nbinmode UPLOADFILE;\n\nwhile ( &lt;$upload_filehandle&gt; )\n{\n print UPLOADFILE;\n}\n\nclose UPLOADFILE;\n\nprint $query-&gt;header ( );\nprint &lt;&lt;END_HTML;\n&lt;!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"DTD/xhtml1-strict.dtd\"&gt;\n&lt;html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\"&gt;\n &lt;head&gt;\n &lt;meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /&gt;\n &lt;title&gt;Thanks!&lt;/title&gt;\n &lt;/head&gt;\n &lt;body&gt;\n &lt;p&gt;Thanks for uploading your photo!&lt;/p&gt;\n &lt;/body&gt;\n&lt;/html&gt;\nEND_HTML\n</code></pre>\n" }, { "answer_id": 162740, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 3, "selected": false, "text": "<p>See <a href=\"http://search.cpan.org/~lds/CGI.pm/CGI.pm#CREATING_A_FILE_UPLOAD_FIELD\" rel=\"nofollow noreferrer\">the CGI.pm documentation for file uploads</a>.</p>\n" }, { "answer_id": 162751, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 3, "selected": false, "text": "<p>Use the <a href=\"http://search.cpan.org/~lds/CGI.pm-3.42/CGI.pm#CREATING_A_FILE_UPLOAD_FIELD\" rel=\"nofollow noreferrer\">CGI module</a>.</p>\n\n<pre><code>my $fh = $query-&gt;upload('upload_field');\nwhile(&lt;$fh&gt;) {\n print SAVE_FILE $_;\n}\n</code></pre>\n" }, { "answer_id": 162895, "author": "runrig", "author_id": 10415, "author_profile": "https://Stackoverflow.com/users/10415", "pm_score": 2, "selected": false, "text": "<p>I'd start by using <a href=\"http://search.cpan.org/dist/CGI\" rel=\"nofollow noreferrer\">CGI</a> and reading <a href=\"http://search.cpan.org/perldoc/CGI#CREATING_A_FILE_UPLOAD_FIELD\" rel=\"nofollow noreferrer\">CREATING A FILE UPLOAD FIELD</a>, and using <a href=\"http://perldoc.perl.org/functions/open.html\" rel=\"nofollow noreferrer\">open</a> to create a file and <a href=\"http://perldoc.perl.org/functions/print.html\" rel=\"nofollow noreferrer\">print</a> to write to it. (and then <a href=\"http://perldoc.perl.org/functions/close.html\" rel=\"nofollow noreferrer\">close</a> to close it).</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6701/" ]
How would I write a Perl CGI script that receives a file via a HTTP post and saves that to the file system?
Just a note: however you will write it, **don't** save it in a place accessible from your web-server. And now to the point: below is a script which I was using for some time for photo-uploading. It might need some tweaking, but should show you the way. As the image isnt uploaded to web-accesible directory, we then have separate process checking it, resizing, putting a watermark and placing it where it can be accessed. ``` #!/usr/bin/perl -wT use strict; use CGI; use CGI::Carp qw ( fatalsToBrowser ); use File::Basename; $CGI::POST_MAX = 1024 * 5000; my $safe_filename_characters = "a-zA-Z0-9_.-"; my $upload_dir = "/home/www/upload"; my $query = new CGI; my $filename = $query->param("photo"); my $email_address = $query->param("email_address"); if ( !$filename ) { print $query->header ( ); print "There was a problem uploading your photo (try a smaller file)."; exit; } my ( $name, $path, $extension ) = fileparse ( $filename, '\..*' ); $filename = $name . $extension; $filename =~ tr/ /_/; $filename =~ s/[^$safe_filename_characters]//g; if ( $filename =~ /^([$safe_filename_characters]+)$/ ) { $filename = $1; } else { die "Filename contains invalid characters"; } my $upload_filehandle = $query->upload("photo"); open ( UPLOADFILE, ">$upload_dir/$filename" ) or die "$!"; binmode UPLOADFILE; while ( <$upload_filehandle> ) { print UPLOADFILE; } close UPLOADFILE; print $query->header ( ); print <<END_HTML; <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Thanks!</title> </head> <body> <p>Thanks for uploading your photo!</p> </body> </html> END_HTML ```
162,681
<p>Given the email address: "Jim" &lt;[email protected]&gt;</p> <p>If I try to pass this to MailAddress I get the exception:</p> <blockquote> <p>The specified string is not in the form required for an e-mail address.</p> </blockquote> <p>How do I parse this address into a display name (Jim) and email address ([email protected]) in C#?</p> <p>EDIT: I'm looking for C# code to parse it.</p> <p>EDIT2: I found that the exception was being thrown by MailAddress because I had a space at the start of the email address string. </p>
[ { "answer_id": 162700, "author": "Codewerks", "author_id": 17729, "author_profile": "https://Stackoverflow.com/users/17729", "pm_score": 2, "selected": false, "text": "<p>Try:</p>\n\n<pre><code>\"Jimbo &lt;[email protected]&gt;\"\n</code></pre>\n" }, { "answer_id": 162701, "author": "Wayne", "author_id": 8236, "author_profile": "https://Stackoverflow.com/users/8236", "pm_score": 0, "selected": false, "text": "<pre><code>new MailAddress(\"[email protected]\", \"Jimbo\");\n</code></pre>\n\n<p>to parse out the string you gave:</p>\n\n<pre><code>string input = \"\\\"Jimbo\\\" [email protected]\";\nstring[] pieces = input.Split(' ');\nMailAddress ma = new MailAddress(pieces[1].Replace(\"&lt;\", string.Empty).Replace(\"&gt;\",string.Empty), pieces[0].Replace(\"\\\"\", string.Empty));\n</code></pre>\n" }, { "answer_id": 162703, "author": "Sekhat", "author_id": 1610, "author_profile": "https://Stackoverflow.com/users/1610", "pm_score": 0, "selected": false, "text": "<p>try: \"Jim\" &lt;[email protected]&gt;\nnot sure if it'll work, but that's how I generally see it in e-mail clients.</p>\n" }, { "answer_id": 162709, "author": "Vivek", "author_id": 7418, "author_profile": "https://Stackoverflow.com/users/7418", "pm_score": 0, "selected": false, "text": "<pre><code>string inputEmailString = \"\\\"Jimbo\\\" &lt;[email protected]&gt;\";\nstring[] strSet = inputEmailString.Split('\\\"','&lt;','&gt;'); \n\nMailAddress mAddress = new MailAddress(strSet[0], strSet[2]);\n</code></pre>\n" }, { "answer_id": 162723, "author": "Carlton Jenke", "author_id": 1215, "author_profile": "https://Stackoverflow.com/users/1215", "pm_score": 0, "selected": false, "text": "<p>if you make the assumption there is always a space between the 2, you could just use String.Split(' ') to split it on the spaces. That would give you an array with the parts split. </p>\n\n<p>so maybe like this:</p>\n\n<pre><code>string str = \"\\\"Jimbo\\\" [email protected]\"\nstring[] parts = str.Trim().Replace(\"\\\"\",\"\").Split(' ')\n</code></pre>\n\n<p>An issue with this to check for is that if the display name has a space in it, it will be split into 2 or more items in your array itself, but the email would always be last.</p>\n\n<p>Edit - you might also need to edit out the brackets, just add replaces with those. </p>\n" }, { "answer_id": 162731, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 0, "selected": false, "text": "<p>I just wrote this up, it grabs the first well formed e-mail address out of a string. That way you don't have to assume where the e-mail address is in the string</p>\n\n<p>Lots of room for improvement, but I need to leave for work :)</p>\n\n<pre><code>class Program\n{\n static void Main(string[] args)\n {\n string email = \"\\\"Jimbo\\\" &lt;[email protected]&gt;\";\n Console.WriteLine(parseEmail(email));\n }\n\n private static string parseEmail(string inputString)\n {\n Regex r = \n new Regex(@\"^((?:(?:(?:[a-zA-Z0-9][\\.\\-\\+_]?)*)[a-zA-Z0-9])+)\\@((?:(?:(?:[a-zA-Z0-9][\\.\\-_]?){0,62})[a-zA-Z0-9])+)\\.([a-zA-Z0-9]{2,6})$\");\n\n string[] tokens = inputString.Split(' ');\n\n foreach (string s in tokens)\n {\n string temp = s;\n temp = temp.TrimStart('&lt;'); temp = temp.TrimEnd('&gt;');\n\n if (r.Match(temp).Success)\n return temp;\n }\n\n throw new ArgumentException(\"Not an e-mail address\");\n }\n}\n</code></pre>\n" }, { "answer_id": 162744, "author": "Rob", "author_id": 7872, "author_profile": "https://Stackoverflow.com/users/7872", "pm_score": 0, "selected": false, "text": "<p>It's a bit \"rough and ready\" but will work for the example you've given:</p>\n\n<pre><code> string emailAddress, displayname;\n string unparsedText = \"\\\"Jimbo\\\" &lt;[email protected]&gt;\";\n string[] emailParts = unparsedText.Split(new char[] { '&lt;' });\n\n if (emailParts.Length == 2)\n {\n displayname = emailParts[0].Trim(new char[] { ' ', '\\\"' });\n emailAddress = emailParts[1].TrimEnd('&gt;');\n }\n</code></pre>\n" }, { "answer_id": 163075, "author": "Brannon", "author_id": 5745, "author_profile": "https://Stackoverflow.com/users/5745", "pm_score": 5, "selected": true, "text": "<p>If you are looking to parse the email address manually, you want to read RFC2822 (<a href=\"https://www.rfc-editor.org/rfc/rfc822.html#section-3.4\" rel=\"nofollow noreferrer\">https://www.rfc-editor.org/rfc/rfc822.html#section-3.4</a>). Section 3.4 talks about the address format.</p>\n<p>But parsing email addresses correctly is not easy and <code>MailAddress</code> should be able to handle most scenarios.</p>\n<p>According to the MSDN documentation for <code>MailAddress</code>:</p>\n<p><a href=\"http://msdn.microsoft.com/en-us/library/591bk9e8.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/591bk9e8.aspx</a></p>\n<p>It should be able to parse an address with a display name. They give <code>&quot;Tom Smith &lt;[email protected]&gt;&quot;</code> as an example. Maybe the quotes are the issue? If so, just strip the quotes out and use MailAddress to parse the rest.</p>\n<pre><code>string emailAddress = &quot;\\&quot;Jim\\&quot; &lt;[email protected]&gt;&quot;;\n\nMailAddress address = new MailAddress(emailAddress.Replace(&quot;\\&quot;&quot;, &quot;&quot;));\n</code></pre>\n<p>Manually parsing RFC2822 isn't worth the trouble if you can avoid it.</p>\n" }, { "answer_id": 163216, "author": "b w", "author_id": 4126, "author_profile": "https://Stackoverflow.com/users/4126", "pm_score": 0, "selected": false, "text": "<p>To handle embedded spaces, split on the brackets, as follows:</p>\n\n<pre><code>string addrin = \"\\\"Jim Smith\\\" &lt;[email protected]&gt;\";\nchar[] bracks = {'&lt;','&gt;'};\nstring[] pieces = addrin.Split(bracks);\npieces[0] = pieces[0]\n .Substring(0, pieces[0].Length - 1)\n .Replace(\"\\\"\", string.Empty);\nMailAddress ma = new MailAddress(pieces[1], pieces[0]);\n</code></pre>\n" }, { "answer_id": 163301, "author": "Dylan", "author_id": 4580, "author_profile": "https://Stackoverflow.com/users/4580", "pm_score": 0, "selected": false, "text": "<p>So, this is what I have done. It's a little quick and dirty, but seems to work.</p>\n\n<pre><code>string emailTo = \"\\\"Jim\\\" &lt;[email protected]&gt;\";\nstring emailRegex = @\"(?:[a-z0-9!#$%&amp;'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&amp;'*+/=?^_`{|}~-]+)*|\"\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\"\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])\";\nstring emailAddress = Regex.Match(emailTo.ToLower(), emailRegex).Value;\nstring displayName = null;\n\ntry\n{\n displayName = emailTo.Substring(0, emailTo.ToLower().IndexOf(emailAddress) - 1);\n}\ncatch \n{\n // No display name \n}\n\nMailAddress addr = new MailAddress(emailAddress, displayName);\n</code></pre>\n\n<p>Comments?</p>\n" }, { "answer_id": 163372, "author": "benc", "author_id": 2910, "author_profile": "https://Stackoverflow.com/users/2910", "pm_score": 0, "selected": false, "text": "<p>I don't code in this language, but I see two issues you might want to check:</p>\n\n<p>1- You don't know exactly why it was rejected. On immediate possibility was that it has a blacklist for example.com.</p>\n\n<p>2- The real solution you want is to probably implement a strict validator. Stack Overflow is probably a good place to develop this, because there are lots of people with practical experience.</p>\n\n<p>Here are a couple things you need:</p>\n\n<ol>\n<li>trim whitespace and obviously cruft.</li>\n<li>parse into individual parts (display name, left-hand-side of address, right-hand side of address).</li>\n<li>validate each of these with a data structure specific validator. For example, the right-hand side needs to be a valid FQDN (or unqualified hostname if you are on a liberal mail system).</li>\n</ol>\n\n<p>That's the best long-term approach to solving this problem.</p>\n" }, { "answer_id": 163499, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 3, "selected": false, "text": "<p>Works for me:</p>\n\n<pre><code>string s = \"\\\"Jim\\\" &lt;[email protected]&gt;\";\nSystem.Net.Mail.MailAddress a = new System.Net.Mail.MailAddress(s);\nDebug.WriteLine(\"DisplayName: \" + a.DisplayName);\nDebug.WriteLine(\"Address: \" + a.Address);\n</code></pre>\n\n<p>The MailAddress class has a private method that parses an email address. Don't know how good it is, but I'd tend to use it rather than writing my own.</p>\n" }, { "answer_id": 45333332, "author": "CSharpCoder", "author_id": 8357566, "author_profile": "https://Stackoverflow.com/users/8357566", "pm_score": 0, "selected": false, "text": "<p>I can suggest my regex-based solution for decoding email address field values (\"From\", \"To\") and field value \"Subject\"</p>\n\n<p><a href=\"https://www.codeproject.com/Tips/1198601/Parsing-and-Decoding-Values-of-Some-Email-Message\" rel=\"nofollow noreferrer\">https://www.codeproject.com/Tips/1198601/Parsing-and-Decoding-Values-of-Some-Email-Message</a></p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162681", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4580/" ]
Given the email address: "Jim" <[email protected]> If I try to pass this to MailAddress I get the exception: > > The specified string is not in the form required for an e-mail address. > > > How do I parse this address into a display name (Jim) and email address ([email protected]) in C#? EDIT: I'm looking for C# code to parse it. EDIT2: I found that the exception was being thrown by MailAddress because I had a space at the start of the email address string.
If you are looking to parse the email address manually, you want to read RFC2822 (<https://www.rfc-editor.org/rfc/rfc822.html#section-3.4>). Section 3.4 talks about the address format. But parsing email addresses correctly is not easy and `MailAddress` should be able to handle most scenarios. According to the MSDN documentation for `MailAddress`: <http://msdn.microsoft.com/en-us/library/591bk9e8.aspx> It should be able to parse an address with a display name. They give `"Tom Smith <[email protected]>"` as an example. Maybe the quotes are the issue? If so, just strip the quotes out and use MailAddress to parse the rest. ``` string emailAddress = "\"Jim\" <[email protected]>"; MailAddress address = new MailAddress(emailAddress.Replace("\"", "")); ``` Manually parsing RFC2822 isn't worth the trouble if you can avoid it.
162,696
<p>A few years ago, I read a book that described how you could override the default event 'dispatcher' implementation in .NET with your own processor.</p> <pre><code> class foo { public event EventHandler myEvent; ... } ... myFoo.myEvent += myBar1.EventHandler; myFoo.myEvent += myBar2.EventHandler; </code></pre> <p>Whenever the event fires, both myBar1 and myBar2 handlers will be called.</p> <p>As I recall, the default implementation of this loop uses a linked list and simply iterates over the list and calls the EventHandler delegates in order.</p> <p>My question is two fold: </p> <ol> <li>Does someone know which book I was reading?</li> <li>Why would you want to override the default implementation (which might be answered in the book)?</li> </ol> <p>Edit: The book I was referring to was indeed Jeffrey Richter's CLR via C#</p>
[ { "answer_id": 162745, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I seem to remember something similar in Jeffrey Richter's CLR via C#. <strong>Edit:</strong> I definitely do remember that he goes into detail about it.</p>\n\n<p>There are a few different reasons for taking control of event registration. One of them is to reduce code bloat when you've got TONS of events. I think Jeffrey went into this in detail within the book...</p>\n" }, { "answer_id": 162749, "author": "arul", "author_id": 15409, "author_profile": "https://Stackoverflow.com/users/15409", "pm_score": 1, "selected": false, "text": "<ol>\n<li>No</li>\n<li>You might, for example, need to break the call chain based on the result of one of the handlers. Say your CustomEventArgs object has a property 'Blocked', which when set to true suppresses all further event handler invocations.</li>\n</ol>\n" }, { "answer_id": 162750, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 4, "selected": true, "text": "<p>It could have been one of many books or web articles.</p>\n\n<p>There are various reasons why you might want to change how events are subscribed/unsubscribed:</p>\n\n<ul>\n<li>If you have many events, many of which may well not be subscribed to, you may want to use <a href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.eventhandlerlist.aspx\" rel=\"noreferrer\">EventHandlerList</a> to lower your memory usage</li>\n<li>You may wish to log subscription/unsubscription</li>\n<li>You may wish to use a weak reference to avoid the subscriber's lifetime from being tied to yours</li>\n<li>You may wish to change the locking associated with subscription/unsubscription</li>\n</ul>\n\n<p>I'm sure there are more - those are off the top of my head :)</p>\n\n<p>EDIT: Also note that there's a difference between having a custom way of handling subscription/unsubscription and having a custom way of raising the event (which may call GetInvocationList and guarantee that all handlers are called, regardless of exceptions, for example).</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162696", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10703/" ]
A few years ago, I read a book that described how you could override the default event 'dispatcher' implementation in .NET with your own processor. ``` class foo { public event EventHandler myEvent; ... } ... myFoo.myEvent += myBar1.EventHandler; myFoo.myEvent += myBar2.EventHandler; ``` Whenever the event fires, both myBar1 and myBar2 handlers will be called. As I recall, the default implementation of this loop uses a linked list and simply iterates over the list and calls the EventHandler delegates in order. My question is two fold: 1. Does someone know which book I was reading? 2. Why would you want to override the default implementation (which might be answered in the book)? Edit: The book I was referring to was indeed Jeffrey Richter's CLR via C#
It could have been one of many books or web articles. There are various reasons why you might want to change how events are subscribed/unsubscribed: * If you have many events, many of which may well not be subscribed to, you may want to use [EventHandlerList](http://msdn.microsoft.com/en-us/library/system.componentmodel.eventhandlerlist.aspx) to lower your memory usage * You may wish to log subscription/unsubscription * You may wish to use a weak reference to avoid the subscriber's lifetime from being tied to yours * You may wish to change the locking associated with subscription/unsubscription I'm sure there are more - those are off the top of my head :) EDIT: Also note that there's a difference between having a custom way of handling subscription/unsubscription and having a custom way of raising the event (which may call GetInvocationList and guarantee that all handlers are called, regardless of exceptions, for example).
162,727
<p>I've got a text file full of records where each field in each record is a fixed width. My first approach would be to parse each record simply using string.Substring(). Is there a better way? </p> <p>For example, the format could be described as:</p> <pre><code>&lt;Field1(8)&gt;&lt;Field2(16)&gt;&lt;Field3(12)&gt; </code></pre> <p>And an example file with two records could look like:</p> <pre><code>SomeData0000000000123456SomeMoreData Data2 0000000000555555MoreData </code></pre> <p>I just want to make sure I'm not overlooking a more elegant way than Substring().</p> <hr> <p><strong>Update:</strong> I ultimately went with a regex like Killersponge suggested:</p> <pre><code>private readonly Regex reLot = new Regex(REGEX_LOT, RegexOptions.Compiled); const string REGEX_LOT = "^(?&lt;Field1&gt;.{6})" + "(?&lt;Field2&gt;.{16})" + "(?&lt;Field3&gt;.{12})"; </code></pre> <p>I then use the following to access the fields:</p> <pre><code>Match match = reLot.Match(record); string field1 = match.Groups["Field1"].Value; </code></pre>
[ { "answer_id": 162772, "author": "Will Hartung", "author_id": 13663, "author_profile": "https://Stackoverflow.com/users/13663", "pm_score": 0, "selected": false, "text": "<p>Nope, Substring is fine. That's what it's for.</p>\n" }, { "answer_id": 162774, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 4, "selected": true, "text": "<p>Substring sounds good to me. The only downside I can immediately think of is that it means copying the data each time, but I wouldn't worry about that until you prove it's a bottleneck. Substring is simple :)</p>\n\n<p>You <em>could</em> use a regex to match a whole record at a time and capture the fields, but I think that would be overkill.</p>\n" }, { "answer_id": 162809, "author": "Sekhat", "author_id": 1610, "author_profile": "https://Stackoverflow.com/users/1610", "pm_score": 2, "selected": false, "text": "<p>You may have to watch out, if the end of the lines aren't padded out with spaces to fill the field, your substring won't work without a bit of fiddling to work out how much more of the line there is to read. This of course only applies to the last field :)</p>\n" }, { "answer_id": 162909, "author": "Leandro Oliveira", "author_id": 16610, "author_profile": "https://Stackoverflow.com/users/16610", "pm_score": 5, "selected": false, "text": "<p>Use <a href=\"http://www.filehelpers.net/\" rel=\"noreferrer\">FileHelpers</a>.</p>\n\n<p>Example:</p>\n\n<pre><code>[FixedLengthRecord()] \npublic class MyData\n{ \n [FieldFixedLength(8)] \n public string someData; \n\n [FieldFixedLength(16)] \n public int SomeNumber; \n\n [FieldFixedLength(12)] \n [FieldTrim(TrimMode.Right)]\n public string someMoreData;\n}\n</code></pre>\n\n<p>Then, it's as simple as this:</p>\n\n<pre><code>var engine = new FileHelperEngine&lt;MyData&gt;(); \n\n// To Read Use: \nvar res = engine.ReadFile(\"FileIn.txt\"); \n\n// To Write Use: \nengine.WriteFile(\"FileOut.txt\", res); \n</code></pre>\n" }, { "answer_id": 162929, "author": "Jon Limjap", "author_id": 372, "author_profile": "https://Stackoverflow.com/users/372", "pm_score": 1, "selected": false, "text": "<p>Unfortunately out of the box the CLR only provides Substring for this.</p>\n\n<p><a href=\"http://www.codeproject.com/KB/cs/FixedFlatFileHandling.aspx\" rel=\"nofollow noreferrer\">Someone over at CodeProject made a custom parser using attributes to define fields</a>, you might wanna look at that.</p>\n" }, { "answer_id": 164117, "author": "Soraz", "author_id": 24610, "author_profile": "https://Stackoverflow.com/users/24610", "pm_score": 0, "selected": false, "text": "<p>You could set up an ODBC data source for the fixed format file, and then access it as any other database table.\nThis has the added advantage that specific knowledge of the file format is not compiled into your code for that fateful day that someone decides to stick an extra field in the middle.</p>\n" }, { "answer_id": 12549829, "author": "Colonel Panic", "author_id": 284795, "author_profile": "https://Stackoverflow.com/users/284795", "pm_score": 3, "selected": false, "text": "<p>Why reinvent the wheel? Use .NET's <a href=\"http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.fileio.textfieldparser.aspx\" rel=\"nofollow noreferrer\">TextFieldParser</a> class per this how-to for Visual Basic: <a href=\"http://msdn.microsoft.com/en-us/library/zezabash.aspx\" rel=\"nofollow noreferrer\"><em>How to read from fixed-width text files</em></a>.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162727", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2773/" ]
I've got a text file full of records where each field in each record is a fixed width. My first approach would be to parse each record simply using string.Substring(). Is there a better way? For example, the format could be described as: ``` <Field1(8)><Field2(16)><Field3(12)> ``` And an example file with two records could look like: ``` SomeData0000000000123456SomeMoreData Data2 0000000000555555MoreData ``` I just want to make sure I'm not overlooking a more elegant way than Substring(). --- **Update:** I ultimately went with a regex like Killersponge suggested: ``` private readonly Regex reLot = new Regex(REGEX_LOT, RegexOptions.Compiled); const string REGEX_LOT = "^(?<Field1>.{6})" + "(?<Field2>.{16})" + "(?<Field3>.{12})"; ``` I then use the following to access the fields: ``` Match match = reLot.Match(record); string field1 = match.Groups["Field1"].Value; ```
Substring sounds good to me. The only downside I can immediately think of is that it means copying the data each time, but I wouldn't worry about that until you prove it's a bottleneck. Substring is simple :) You *could* use a regex to match a whole record at a time and capture the fields, but I think that would be overkill.
162,730
<p>I have a table column that needs to be limited to a certain width - say 100 pixels. At times the text in that column is wider than this and contains no spaces. For example:</p> <pre><code>a_really_long_string_of_text_like_this_with_no_line_breaks_makes_the_table_unhappy </code></pre> <p>I would like to calculate the width of text server-side and add an ellipsis after the correct number of characters. The problem is that I don't have data about the rendered size of the text.</p> <p>For example, assuming the browser was Firefox 3 and the font was 12px Arial. What would be the width of the letter "a", the width of the letter "b", etc.?</p> <p>Do you have data showing the pixel width of each character? Or a program to generate it?</p> <p>I think a clever one-time javascript script could do the trick. But I don't want to spend time re-inventing the wheel if someone else has already done this. I am surely not the first person to come up against this problem.</p>
[ { "answer_id": 162746, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 1, "selected": false, "text": "<p>Very very hard to do server-side. You can never know what fonts users have installed, and there are many things that affect the display of text.</p>\n\n<p>Try this instead:</p>\n\n<pre><code>table-layout: fixed;\n</code></pre>\n\n<p>That'll make sure the table is never larger than the size you specified.</p>\n" }, { "answer_id": 162754, "author": "NotMe", "author_id": 2424, "author_profile": "https://Stackoverflow.com/users/2424", "pm_score": 2, "selected": false, "text": "<p>How about overflow: scroll?</p>\n" }, { "answer_id": 162771, "author": "Dave Van den Eynde", "author_id": 455874, "author_profile": "https://Stackoverflow.com/users/455874", "pm_score": 3, "selected": true, "text": "<p>This would not only be impossible to do server-side, it would also not make sense. You don't what browser your client will be using, and you don't know what font settings on the client side will override whatever styling information you assign to a piece of HTML. You might think that you're using absolute positioning pixels in your style properties, but the client could simply be ignoring those or using some plugin to zoom everything because the client uses a high-dpi screen.</p>\n\n<p>Using fixed widths is generally a bad idea.</p>\n" }, { "answer_id": 162784, "author": "Neall", "author_id": 619, "author_profile": "https://Stackoverflow.com/users/619", "pm_score": 0, "selected": false, "text": "<p>This is essentially impossible to do on the server side. In addition to the problem of people having different fonts installed, you also have kerning (the letter \"f\" will take up a different amount of space depending on what is next to it) and font rendering options (is cleartype on? \"large fonts\"?).</p>\n" }, { "answer_id": 162785, "author": "roenving", "author_id": 23142, "author_profile": "https://Stackoverflow.com/users/23142", "pm_score": 0, "selected": false, "text": "<p>You could put the text into an invisible span and read that spans width, but basicly this looks like someone trying to sabotage your site, and therefore I would recommend banning posts with words longer than a certain lenth, for example 30 characters without spaces (allowing links to be longer !-)</p>\n\n<p>-- but the simple approach is to put a block-element inside the table-cell:</p>\n\n<pre><code>&lt;td&gt;&lt;div style=\"width:100px;overflow:hidden\"&gt;a_really_long_string_of_text_like_this_with_no_line_breaks_makes_the_ta ... &lt;/div&gt;&lt;/td&gt;\n</code></pre>\n\n<p>This will effectively stop the table-cluttering !o]</p>\n" }, { "answer_id": 162803, "author": "sk.", "author_id": 16399, "author_profile": "https://Stackoverflow.com/users/16399", "pm_score": 0, "selected": false, "text": "<p>There's nothing you can do server-side to calculate it. All you have to work with is the browser identification string, which may or may not tell you the user's operating system and browser accurately. You can also \"ask\" (via a font tag or CSS) for a certain font to be used to display the text but there's no guarantee that the user has that font installed. Beyond that the user could have a different DPI setting at the operating system level, or could have made the text bigger or smaller with the browser zoom function, or could be using their own stylesheet altogether.</p>\n" }, { "answer_id": 163337, "author": "neonski", "author_id": 17112, "author_profile": "https://Stackoverflow.com/users/17112", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://extjs.com\" rel=\"nofollow noreferrer\">Ext JS</a> has a module to do just that</p>\n\n<blockquote>\n <p><a href=\"http://extjs.com/deploy/dev/docs/?class=Ext.util.TextMetrics\" rel=\"nofollow noreferrer\">TextMetrics</a>\n Provides precise pixel measurements\n for blocks of text so that you can\n determine exactly how high and wide,\n in pixels, a given block of text will\n be. </p>\n</blockquote>\n\n<p>I am sure that there are other libraries available out there that do it as well.</p>\n" }, { "answer_id": 164513, "author": "Devon", "author_id": 13850, "author_profile": "https://Stackoverflow.com/users/13850", "pm_score": 1, "selected": false, "text": "<p>Here is my client-side solution that I came up with. It is pretty specific to my application but I am sharing it here in case someone else comes across the same problem.</p>\n\n<p>It works a bit more quickly than I had expected. And it assumes the contents of the cells are text only - any HTML will formatting will be erased in the shortening process.</p>\n\n<p>It requires jQuery.</p>\n\n<pre><code>function fixFatColumns() {\n $('table#MyTable td').each(function() {\n var defined_width = $(this).attr('width');\n if (defined_width) {\n var actual_width = $(this).width();\n var contents = $(this).html();\n if (contents.length) {\n var working_div = $('#ATempDiv');\n if (working_div.is('*')) {\n working_div.html(contents);\n } else {\n $('body').append('&lt;div id=\"ATempDiv\" style=\"position:absolute;top:-100px;left:-500px;font-size:13px;font-family:Arial\"&gt;'+contents+'&lt;/div&gt;');\n working_div = $('#ATempDiv');\n }\n\n if (working_div.width() &gt; defined_width) {\n contents = working_div.text();\n working_div.text(contents);\n while (working_div.width() + 8 &gt; defined_width) {\n // shorten the contents of the columns\n var working_text = working_div.text();\n if (working_text.length &gt; 1) working_text = working_text.substr(0,working_text.length-1);\n working_div.text(working_text);\n }\n $(this).html(working_text+'...')\n }\n\n working_div.empty();\n }\n\n }\n });\n\n}\n</code></pre>\n" }, { "answer_id": 451852, "author": "sunflowerpower", "author_id": 55992, "author_profile": "https://Stackoverflow.com/users/55992", "pm_score": 0, "selected": false, "text": "<p>If you're ok with this not working for FireFox, why not just use CSS? Have the table with table-layout:fixed, have the column in question have overflow:hidden;text-overflow:ellipsis; white-space:nowrap.</p>\n" }, { "answer_id": 451873, "author": "Georg Schölly", "author_id": 24587, "author_profile": "https://Stackoverflow.com/users/24587", "pm_score": 0, "selected": false, "text": "<pre><code>http://www.css3.info/preview/text-overflow/\n</code></pre>\n\n<p>This is a new function of css3.</p>\n" }, { "answer_id": 451880, "author": "Diodeus - James MacFarlane", "author_id": 12579, "author_profile": "https://Stackoverflow.com/users/12579", "pm_score": 0, "selected": false, "text": "<p>Some users have larger or smaller default font settings. You can't do this on the server. You can only measure it once the browser has rendered the page.</p>\n" }, { "answer_id": 451881, "author": "Soviut", "author_id": 46914, "author_profile": "https://Stackoverflow.com/users/46914", "pm_score": 0, "selected": false, "text": "<p>Since font size can be easily changed on the browser side, your server-side calculation is made invalid very easily.</p>\n\n<p>A quick client side fix would be to style your cells with an overflow attribute:</p>\n\n<pre><code>td\n{\n overflow: scroll; /* or overflow: hidden; etc. */\n}\n</code></pre>\n\n<p>A better alternative is to truncate your strings server side and provide a simple javascript tooltip that can display the longer version. An \"expand\" button may also help that could display the result in an overlay div.</p>\n" }, { "answer_id": 4028265, "author": "Dustin", "author_id": 1311049, "author_profile": "https://Stackoverflow.com/users/1311049", "pm_score": 0, "selected": false, "text": "<p>What you want is the &lt;wbr&gt; tag. This is a special HTML tag that tells the browser that it is acceptable to break a word here if a wrap is necessary. I would not inject the into the text for persistent storage because then you are coupling your data with where/how you will display that data. However, it is perfectly acceptable to inject the tags server side in code that is view-centric (like with a JSP tag or possibly in the controller). That's how I would do it. Just use some regular expression to find words that are longer than X characters and inject this tag every X characters into such words.</p>\n\n<p>Update: I was doing some looking around and it looks like wbr is not supported on all browsers. Most notably, IE8. I haven't tested this myself though. Perhaps you could use overflow:hidden as a backup or something like that.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13850/" ]
I have a table column that needs to be limited to a certain width - say 100 pixels. At times the text in that column is wider than this and contains no spaces. For example: ``` a_really_long_string_of_text_like_this_with_no_line_breaks_makes_the_table_unhappy ``` I would like to calculate the width of text server-side and add an ellipsis after the correct number of characters. The problem is that I don't have data about the rendered size of the text. For example, assuming the browser was Firefox 3 and the font was 12px Arial. What would be the width of the letter "a", the width of the letter "b", etc.? Do you have data showing the pixel width of each character? Or a program to generate it? I think a clever one-time javascript script could do the trick. But I don't want to spend time re-inventing the wheel if someone else has already done this. I am surely not the first person to come up against this problem.
This would not only be impossible to do server-side, it would also not make sense. You don't what browser your client will be using, and you don't know what font settings on the client side will override whatever styling information you assign to a piece of HTML. You might think that you're using absolute positioning pixels in your style properties, but the client could simply be ignoring those or using some plugin to zoom everything because the client uses a high-dpi screen. Using fixed widths is generally a bad idea.
162,752
<p>I am looking for an algorithm to calculate the next set of operations in a sequence. Here is the simple definition of the sequence.</p> <ol> <li>Task 1A will be done every 500 hours</li> <li>Task 2A will be done every 1000 hours</li> <li>Task 3A will be done every 1500 hours</li> </ol> <p>So at t=500, do 1A. At t=1000, do both 1A and 2A, at t=1500 do 1A and 3A, but not 2A as 1500 is not a multiple of 1000. You get the idea.</p> <p>It would be quite easy if I had the actual time, but I don't. What I have is the history of tasks (eg last time a [1A+2A] was done). </p> <p>Knowing last time (eg [1A+2A]) is not enough to decide:</p> <ul> <li>[1A+2A] could be at t=1000: next is [1A+3A] at t=1500</li> <li>[1A+2A] could be at t=5000: next is [1A] at t=5500</li> </ul> <p>Is there an algorithm for this? It looks like a familiar problem (some sort of sieve?) but I can't seem to find a solution.</p> <p>Also it must "scale" as I actually have more than 3 tasks.</p>
[ { "answer_id": 162806, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 2, "selected": false, "text": "<p>If you have enough history to get the last two times each task was done you could reconstruct the original task sequence definitions. When they coincide is incidental.</p>\n" }, { "answer_id": 162825, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 2, "selected": false, "text": "<p>The sequence must repeat. For the example given, the sequence would be 1A, 1A+2A, 1A+3A, 1A+2A, 1A, 1A+2A+3A. In this situation, you could see how far back the last 1A+2A+3A is and use that distance as an index into an array. In the general case, for a cycle of length N, you could always do it by testing the last N events against all rotations of the cycle, but I suspect that there will usually be some kind of shortcut available, like how many events back the last \"do everything\" event happened, or how long ago the last \"do everything\" event happened.</p>\n" }, { "answer_id": 162831, "author": "dacracot", "author_id": 13930, "author_profile": "https://Stackoverflow.com/users/13930", "pm_score": 1, "selected": false, "text": "<p>Seems like a greatest common denominator problem.</p>\n" }, { "answer_id": 162923, "author": "6eorge Jetson", "author_id": 23422, "author_profile": "https://Stackoverflow.com/users/23422", "pm_score": 1, "selected": false, "text": "<p><b>Edit:</b></p>\n\n<p>Ah, you have to go the other way. In that case, as someone mentioned, you can calculate an effective @TimeLastJob using the least common multiple of the three</p>\n\n<blockquote>\n--Note: uses some SQL Server 2005 SQL extentions, \n<br/>--&nbsp; &nbsp; &nbsp; but can still serve as a psuedocode specification of the algorithm\n<br/>DECLARE @constEvaluationPeriodLength int\n<br/>DECLARE @constCycleTimeJob1A int\n<br/>DECLARE @constCycleTimeJob2A int\n<br/>DECLARE @constCycleTimeJob3A int\n<br/>\n<br/>SET @constEvaluationPeriodLength = 500\n<br/>SET @constCycleTimeJob1A = 500\n<br/>SET @constCycleTimeJob2A = 1000\n<br/>SET @constCycleTimeJob3A = 1500\n<br/>\n<br/>DECLARE @Indicator1ARunAtLastCyclePoint int\n<br/>DECLARE @Indicator2ARunAtLastCyclePoint int\n<br/>DECLARE @Indicator3ARunAtLastCyclePoint int\n<br/>\n<br/>SET @Indicator1ARunAtLastCyclePoint = 1\n<br/>SET @Indicator2ARunAtLastCyclePoint = 0\n<br/>SET @Indicator3ARunAtLastCyclePoint = 1\n<br/>\n<br/>DECLARE @tblPrimeFactors TABLE(\n<br/>&nbsp; &nbsp; TaskId int\n<br/>&nbsp; &nbsp; CycleTimePrimeFactor int\n<br/>)\n<br/>\n<br/>--Capture the prime factors for each TaskId\n<br/>IF (@Indicator1ARunAtLastCyclePoint = 1)\n<br/>&nbsp; BEGIN\n<br/>&nbsp; INSERT @tblPrimeFactors\n<br/>&nbsp; SELECT \n<br/>&nbsp; &nbsp; &nbsp; TaskId = 1\n<br/>&nbsp; &nbsp; &nbsp;,PrimeFactor \n<br/>&nbsp; FROM dbo.tvfGetPrimeFactors(@constCycleTimeJob1A) --Table-valued function left for the reader\n<br/>&nbsp; END\n<br/>IF (@Indicator2ARunAtLastCyclePoint = 1)\n<br/>&nbsp; BEGIN\n<br/>&nbsp; INSERT @tblPrimeFactors\n<br/>&nbsp; SELECT \n<br/>&nbsp; &nbsp; &nbsp; TaskId = 2\n<br/>&nbsp; &nbsp; &nbsp;,PrimeFactor \n<br/>&nbsp; FROM dbo.tvfGetPrimeFactors(@constCycleTimeJob2A) --Table-valued function left for the reader\n<br/>&nbsp; END\n<br/>IF (@Indicator3ARunAtLastCyclePoint = 1)\n<br/>&nbsp; BEGIN\n<br/>&nbsp; INSERT @tblPrimeFactors\n<br/>&nbsp; SELECT \n<br/>&nbsp; &nbsp; &nbsp; TaskId = 3\n<br/>&nbsp; &nbsp; &nbsp;,PrimeFactor \n<br/>&nbsp; FROM dbo.tvfGetPrimeFactors(@constCycleTimeJob3A) --Table-valued function left for the reader\n<br/>&nbsp; END\n<br/>\n<br/>\n<br/>--Calculate the LCM, which can serve as an effective time\n<br/>--Utilizes SQL Server dynamic table capability\n<br/>--(Inner select statements w/in parenthesis and given the alias names t0 & t1 below)\n<br/>DECLARE @LCM int\n<br/>\n<br/>SELECT\n<br/>&nbsp; &nbsp; --Fun w/ logs/powers to effect a product aggregate function\n<br/>&nbsp; &nbsp; @LCM = Power(sum(log10(power(PrimeFactor,Frequency))),10)\n<br/>FROM\n<br/>&nbsp; &nbsp; (\n<br/>&nbsp; &nbsp; &nbsp; &nbsp; SELECT\n<br/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; PrimeFactor\n<br/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;,Frequency = max(Frequency)\n<br/>&nbsp; &nbsp; &nbsp; &nbsp; FROM\n<br/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; (\n<br/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; SELECT\n<br/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; PrimeFactor\n<br/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;,Frequency = count(*)\n<br/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; FROM @tblPrimeFactors\n<br/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; GROUP BY\n<br/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; TaskId\n<br/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;,PrimeFactor\n<br/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ) t0\n<br/>&nbsp; &nbsp; ) t1\n<br/>\n<br/>DECLARE @TimeLastJob int\n<br/>DECLARE @TimeNextJob int\n<br/>SET @TimeLastJob = @LCM\n<br/>SET @TimeNextJob = @TimeLastJob + @constEvaluationPeriodLength\n<br/>\n<br/>SELECT\n<br/>&nbsp; &nbsp; Indicator1A = 1 - SIGN(@TimeNextJob % @constCycleTimeJob1A)\n<br/>&nbsp; &nbsp;,Indicator2A = 1 - SIGN(@TimeNextJob % @constCycleTimeJob2A)\n<br/>&nbsp; &nbsp;,Indicator3A = 1 - SIGN(@TimeNextJob % @constCycleTimeJob3A)\n</blockquote>\n\n<hr>\n\n<p><b>Original:</b></p>\n\n<p>The modulus operataor % should do the trick</p>\n\n<p>If I'm reading this correctly, you do have the time of the last task</p>\n\n<ul>\n<li>t=1000 or</li>\n<li>t=5000</li>\n</ul>\n\n<p>and frequency of task selection evaluation is every 500 hours.</p>\n\n<p>Try varying @TimeLastJob to see if the script below provides you w/ what you need</p>\n\n<blockquote>\nDECLARE @constEvaluationPeriodLength int\n<br/>DECLARE @constCycleTimeJob1A int\n<br/>DECLARE @constCycleTimeJob2A int\n<br/>DECLARE @constCycleTimeJob3A int\n<br/>\n<br/>SET @constEvaluationPeriodLength = 500\n<br/>SET @constCycleTimeJob1A = 500\n<br/>SET @constCycleTimeJob2A = 1000\n<br/>SET @constCycleTimeJob3A = 1500\n<br/>\n<br/>DECLARE @TimeLastJob int\n<br/>DECLARE @TimeNextJob int\n<br/>--SET @TimeLastJob = 1000\n<br/>SET @TimeLastJob =5000\n<br/>SET @TimeNextJob = @TimeLastJob + @constEvaluationPeriodLength\n<br/>\n<br/>SELECT\n<br/>&nbsp; &nbsp; Indicator1A = 1 - SIGN(@TimeNextJob % @constCycleTimeJob1A)\n<br/>&nbsp; &nbsp;,Indicator2A = 1 - SIGN(@TimeNextJob % @constCycleTimeJob2A)\n<br/>&nbsp; &nbsp;,Indicator3A = 1 - SIGN(@TimeNextJob % @constCycleTimeJob3A)\n</blockquote>\n" }, { "answer_id": 195813, "author": "HUAGHAGUAH", "author_id": 27233, "author_profile": "https://Stackoverflow.com/users/27233", "pm_score": 0, "selected": false, "text": "<p>Prerequisites:</p>\n\n<ol>\n<li>Calculate the LCM of the tasks' time; this is the period of a full cycle.</li>\n<li>Compute the event timeline for the full cycle.</li>\n</ol>\n\n<p>As each task / group of tasks is started, move an index through the timeline.</p>\n" }, { "answer_id": 195931, "author": "Simon Lehmann", "author_id": 27011, "author_profile": "https://Stackoverflow.com/users/27011", "pm_score": 2, "selected": true, "text": "<p>Bill the Lizard is right. Here is how to determine the task intervals from the history (in Python):</p>\n\n<pre><code>history = [list of tuples like (timestamp, (A, B, ...)), ordered by timestamp]\nlastTaskTime = {}\ntaskIntervals = {}\n\nfor timestamp, tasks in history:\n for task in tasks:\n if task not in lastTaskTime:\n lastTaskTime[task] = timestamp\n else:\n lastTimestamp = lastTaskTime[task]\n interval = abs(timestamp - lastTimestamp)\n if task not in taskIntervals or interval &lt; taskIntervals[task]:\n taskIntervals[task] = interval # Found a shorter interval\n\n # Always remember the last timestamp\n lastTaskTime[task] = timestamp\n\n# taskIntervals contains the shortest time intervals of each tasks executed at least twice in the past\n# lastTaskTime contains the last time each task was executed\n</code></pre>\n\n<p>To get the set of tasks, which will be executed next:</p>\n\n<pre><code>nextTime = None\nnextTasks = []\n\nfor task in lastTaskTime:\n lastTime = lastTaskTime[task]\n interval = taskIntervals[task]\n\n if not nextTime or lastTime + interval &lt; nextTime:\n nextTime = lastTime + interval\n nextTasks = [task]\n elif lastTime + interval == nextTime:\n nextTasks.append(task)\n\n# nextTime contains the time when the next set of tasks will be executed\n# nextTasks contains the set of tasks to be executed\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/341/" ]
I am looking for an algorithm to calculate the next set of operations in a sequence. Here is the simple definition of the sequence. 1. Task 1A will be done every 500 hours 2. Task 2A will be done every 1000 hours 3. Task 3A will be done every 1500 hours So at t=500, do 1A. At t=1000, do both 1A and 2A, at t=1500 do 1A and 3A, but not 2A as 1500 is not a multiple of 1000. You get the idea. It would be quite easy if I had the actual time, but I don't. What I have is the history of tasks (eg last time a [1A+2A] was done). Knowing last time (eg [1A+2A]) is not enough to decide: * [1A+2A] could be at t=1000: next is [1A+3A] at t=1500 * [1A+2A] could be at t=5000: next is [1A] at t=5500 Is there an algorithm for this? It looks like a familiar problem (some sort of sieve?) but I can't seem to find a solution. Also it must "scale" as I actually have more than 3 tasks.
Bill the Lizard is right. Here is how to determine the task intervals from the history (in Python): ``` history = [list of tuples like (timestamp, (A, B, ...)), ordered by timestamp] lastTaskTime = {} taskIntervals = {} for timestamp, tasks in history: for task in tasks: if task not in lastTaskTime: lastTaskTime[task] = timestamp else: lastTimestamp = lastTaskTime[task] interval = abs(timestamp - lastTimestamp) if task not in taskIntervals or interval < taskIntervals[task]: taskIntervals[task] = interval # Found a shorter interval # Always remember the last timestamp lastTaskTime[task] = timestamp # taskIntervals contains the shortest time intervals of each tasks executed at least twice in the past # lastTaskTime contains the last time each task was executed ``` To get the set of tasks, which will be executed next: ``` nextTime = None nextTasks = [] for task in lastTaskTime: lastTime = lastTaskTime[task] interval = taskIntervals[task] if not nextTime or lastTime + interval < nextTime: nextTime = lastTime + interval nextTasks = [task] elif lastTime + interval == nextTime: nextTasks.append(task) # nextTime contains the time when the next set of tasks will be executed # nextTasks contains the set of tasks to be executed ```
162,753
<p>I am using a multi-dimensional dynamic array in delphi and am trying to figure this out:</p> <p>I have 2 seperate values for the first index and second index that are totally seperate of each other.</p> <p>As new values come I want to grow the array if that new value is outside of either bound.</p> <p>For new values x, y</p> <p>I check:</p> <pre><code>if Length(List) &lt; (x + 1) then SetLength(List, x + 1); if Length(List[0]) &lt; (y + 1) then SetLength(List, Length(List), y + 1); </code></pre> <p>Is this the correct way to do this or is there a better way to grow the array as needed?</p>
[ { "answer_id": 162783, "author": "gabr", "author_id": 4997, "author_profile": "https://Stackoverflow.com/users/4997", "pm_score": 2, "selected": false, "text": "<p>It looks fine to me - if you change the last line to</p>\n\n<pre><code>SetLength(List, Length(List), y + 1);\n</code></pre>\n" }, { "answer_id": 165847, "author": "PatrickvL", "author_id": 12170, "author_profile": "https://Stackoverflow.com/users/12170", "pm_score": 3, "selected": true, "text": "<p>I think you forgot to use the second index on the second dimension;</p>\n\n<p>Your code should probably read like this :</p>\n\n<pre><code>if Length(List) &lt; (x + 1) then\n SetLength(List, x + 1);\nif Length(List[x]) &lt; (y + 1) then\n SetLength(List[x], y + 1);\n</code></pre>\n\n<p>Note the use of 'x' as the first dimension index when growing the second dimension.</p>\n\n<p>One caution though :</p>\n\n<p>You should be aware of the fact that Delphi uses reference-counting on dynamic arrays too (just like how it's done with AnsiString).\nBecause of this, growing the array like above will work, but any other reference to it will still have the <em>old</em> copy of it!</p>\n\n<p>The only way around this, is keeping track of these array's with one extra level of indirection - ie. : Use a pointer to the dynamic array (which is also a pointer in itself, but that's okay).</p>\n\n<p>Also note that any of those 'external' pointers should be updated in any situation that the address of the dynamic array could change, as when growing/shrinking it using SetLength().</p>\n" }, { "answer_id": 166614, "author": "gabr", "author_id": 4997, "author_profile": "https://Stackoverflow.com/users/4997", "pm_score": 1, "selected": false, "text": "<p><del>@PatrickvL:\nSorry, but that is just plain wrong. Your code does not even compile because it tries to set two dimensions for the single-dimensional element List[x].</del> <em>(PatrickvL updated his code so this part of the answer is no longer valid.)</em></p>\n\n<p>The following code demonstrates multidimensional array resizing.</p>\n\n<p>program TestDimensions;</p>\n\n<pre><code>{$APPTYPE CONSOLE}\n\nuses\n SysUtils;\n\nvar\n List: array of array of integer;\n\nbegin\n //set both dimensions\n SetLength(List, 3, 2);\n Writeln('X = ', Length(List), ', Y = ', Length(List[0])); //X = 3, Y = 2\n //set main dimension to 4, keep subdimension untouched\n SetLength(List, 4);\n Writeln('X = ', Length(List), ', Y = ', Length(List[0])); //X = 4, Y = 2\n //set subdimension to 3, keep main dimenstion untouched\n SetLength(List, Length(List), 3);\n Writeln('X = ', Length(List), ', Y = ', Length(List[0])); //X = 4, Y = 3\n //all List[0]..List[3] have 3 elements\n Writeln(Length(List[0]), Length(List[1]), Length(List[2]), Length(List[3])); //3333\n //you can change subdimension for each List[] vector\n SetLength(List[0], 1);\n SetLength(List[3], 7);\n //List is now a ragged array\n Writeln(Length(List[0]), Length(List[1]), Length(List[2]), Length(List[3])); //1337\n //this does not even compile because it tries to set dimension that does not exist!\n// SetLength(List[0], Length(List[0]), 12);\n Readln;\nend.\n</code></pre>\n\n<p>The Delphi help also explains this quite nicely (Structured Types, Arrays).</p>\n\n<blockquote>\n <p>Multidimensional Dynamic Arrays\n To declare multidimensional dynamic arrays, use iterated array of ... constructions. For example, </p>\n \n <p>type TMessageGrid = array of array of string;<br>\n var Msgs: TMessageGrid;</p>\n \n <p>declares a two-dimensional array of strings. To instantiate this array, call SetLength with two integer arguments. For example, if I \n and J are integer-valued variables, </p>\n \n <p>SetLength(Msgs,I,J); </p>\n \n <p>allocates an I-by-J array, and Msgs[0,0] denotes an element of that array. </p>\n \n <p>You can create multidimensional dynamic arrays that are not rectangular. The first step is to call SetLength, passing it parameters for the first n dimensions of the array. For example, </p>\n \n <p>var Ints: array of array of Integer;<br>\n SetLength(Ints,10); </p>\n \n <p>allocates ten rows for Ints but no columns. Later, you can allocate the columns one at a time (giving them different lengths); for example </p>\n \n <p>SetLength(Ints[2], 5); </p>\n \n <p>makes the third column of Ints five integers long. At this point (even if the other columns haven't been allocated) you can assign values to the third column - for example, Ints[2,4] := 6. </p>\n \n <p>The following example uses dynamic arrays (and the IntToStr function declared in the SysUtils unit) to create a triangular matrix of strings. </p>\n \n <p>var<br>\n A : array of array of string;<br>\n I, J : Integer;<br>\n begin<br>\n SetLength(A, 10);<br>\n for I := Low(A) to High(A) do<br>\n begin<br>\n SetLength(A[I], I);<br>\n for J := Low(A[I]) to High(A[I]) do<br>\n A[I,J] := IntToStr(I) + ',' + IntToStr(J) + ' ';<br>\n end;<br>\n end; </p>\n</blockquote>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162753", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16059/" ]
I am using a multi-dimensional dynamic array in delphi and am trying to figure this out: I have 2 seperate values for the first index and second index that are totally seperate of each other. As new values come I want to grow the array if that new value is outside of either bound. For new values x, y I check: ``` if Length(List) < (x + 1) then SetLength(List, x + 1); if Length(List[0]) < (y + 1) then SetLength(List, Length(List), y + 1); ``` Is this the correct way to do this or is there a better way to grow the array as needed?
I think you forgot to use the second index on the second dimension; Your code should probably read like this : ``` if Length(List) < (x + 1) then SetLength(List, x + 1); if Length(List[x]) < (y + 1) then SetLength(List[x], y + 1); ``` Note the use of 'x' as the first dimension index when growing the second dimension. One caution though : You should be aware of the fact that Delphi uses reference-counting on dynamic arrays too (just like how it's done with AnsiString). Because of this, growing the array like above will work, but any other reference to it will still have the *old* copy of it! The only way around this, is keeping track of these array's with one extra level of indirection - ie. : Use a pointer to the dynamic array (which is also a pointer in itself, but that's okay). Also note that any of those 'external' pointers should be updated in any situation that the address of the dynamic array could change, as when growing/shrinking it using SetLength().
162,762
<p>I recently deploy one web application in one of my development servers. I'm using oracle, asp.net and c#. When I run the application in the server everything works fine, but when I try to run the application outside of the server (using my pc, for example) i get this error:</p> <pre><code>ORA-12154: TNS:could not resolve the connect identifier specified </code></pre> <p>If i run the application in my pc with visual studio it works fine.</p> <p>Oracle is installed in Server "A" and the application is in server "B". Server "A" is in one domain and server "B" is in other domain.My pc is in the same domain has Server "A".</p> <p>In my pc I can find the file tnsname.ora in C:\oracle\product\10.2.0\client_1\NETWORK\ADMIN, but in Server "B" i can´t find it anywhere</p> <p>any idea? Thanks for the help.</p>
[ { "answer_id": 162796, "author": "warren", "author_id": 4418, "author_profile": "https://Stackoverflow.com/users/4418", "pm_score": 2, "selected": false, "text": "<p>Have you tried this yet? (from <a href=\"http://ora-12154.ora-code.com/\" rel=\"nofollow noreferrer\">http://ora-12154.ora-code.com/</a>)</p>\n\n<p>ORA-12154: TNS:could not resolve the connect identifier specified<br>\nCause: A connection to a database or other service was requested using a connect identifier, and the connect identifier specified could not be resolved into a connect descriptor using one of the naming methods configured. For example, if the type of connect identifier used was a net service name then the net service name could not be found in a naming method repository, or the repository could not be located or reached.<br>\nAction: \n- If you are using local naming (TNSNAMES.ORA file):</p>\n\n<ul>\n<li><p>Make sure that \"TNSNAMES\" is listed as one of the values of the NAMES.DIRECTORY_PATH parameter in the Oracle Net profile (SQLNET.ORA)</p></li>\n<li><p>Verify that a TNSNAMES.ORA file exists and is in the proper directory and is accessible.</p></li>\n<li><p>Check that the net service name used as the connect identifier exists in the TNSNAMES.ORA file.</p></li>\n<li><p>Make sure there are no syntax errors anywhere in the TNSNAMES.ORA file. Look for unmatched parentheses or stray characters. Errors in a TNSNAMES.ORA file may make it unusable.</p></li>\n<li><p>If you are using directory naming:</p></li>\n<li><p>Verify that \"LDAP\" is listed as one of the values of the NAMES.DIRETORY_PATH parameter in the Oracle Net profile (SQLNET.ORA).</p></li>\n<li><p>Verify that the LDAP directory server is up and that it is accessible.</p></li>\n<li><p>Verify that the net service name or database name used as the connect identifier is configured in the directory.</p></li>\n<li><p>Verify that the default context being used is correct by specifying a fully qualified net service name or a full LDAP DN as the connect identifier</p></li>\n<li><p>If you are using easy connect naming:</p></li>\n<li><p>Verify that \"EZCONNECT\" is listed as one of the values of the NAMES.DIRETORY_PATH parameter in the Oracle Net profile (SQLNET.ORA).</p></li>\n<li><p>Make sure the host, port and service name specified are correct.</p></li>\n<li><p>Try enclosing the connect identifier in quote marks. See the Oracle Net Services Administrators Guide or the Oracle operating system specific guide for more information on naming.</p></li>\n</ul>\n" }, { "answer_id": 162801, "author": "George Mauer", "author_id": 5056, "author_profile": "https://Stackoverflow.com/users/5056", "pm_score": 1, "selected": true, "text": "<p>Guess: An oracle client is not installed on Server B.</p>\n\n<p>If you do have an oracle client installed then you can still put a tnsnames file in any location (Such as a directory on a network share). In order to do this, set a TNS_ADMIN system variable (System Properties->Advanced->Environment Variables on XP) to the directory containing your tnsnames files.</p>\n\n<p>For me for example I have a system variable: TNS_ADMIN - C:\\oracle\\ora92\\network\\ADMIN</p>\n" }, { "answer_id": 162807, "author": "dacracot", "author_id": 13930, "author_profile": "https://Stackoverflow.com/users/13930", "pm_score": 0, "selected": false, "text": "<p>Is ORACLE_HOME set on server B?</p>\n" }, { "answer_id": 162812, "author": "Moshe", "author_id": 9941, "author_profile": "https://Stackoverflow.com/users/9941", "pm_score": 0, "selected": false, "text": "<p>It seems you need to install Oracle Client on \"Server B\" (the application server), and configure it's TNSNAMES.ORA file. This is required since otherwise, the running code will have no idea where to look for the database you use in the application (probably you're configured a data source in web.config or hard-coded something).\nRemember - you cannot access Oracle (easily) without Oracle Client.</p>\n" }, { "answer_id": 162912, "author": "Thomas Jones-Low", "author_id": 23030, "author_profile": "https://Stackoverflow.com/users/23030", "pm_score": 2, "selected": false, "text": "<p>Resolving TNS errors can be a real pain. A few things to keep in mind. </p>\n\n<p>Most development environments (like visual studio) keep their own copy of the TNS connection information, and do not use the TNSNAMES.ora file. The file where this information is kept does not have to be called TNSNAMES.ora, that's just the default name. Which may be the reason you can't find it on Server B. </p>\n\n<p>If you have the oracle client software (or an oracle database) you can use <strong>tnsping</strong> to check if your TNSNAMES.ora file is configured correctly. </p>\n\n<p>The most frequent problems with a TNSNAMES.ora file configuration are using the wrong service name and/or using the wrong host name. You may need to change the \"ODB_A\" to \"ODB_A.WORLD\" or vice versa, depending upon the SQL<em>NET settings. For Oracle 10, the latter is the default SQL</em>NET setting. For the latter, you need to use <strong>ping</strong> to see server \"A\", and know if you need to use \"SERVERA\" or \"SERVERA.DOMIN.COM\" or an IP address. </p>\n" }, { "answer_id": 13007218, "author": "Stikut", "author_id": 1167129, "author_profile": "https://Stackoverflow.com/users/1167129", "pm_score": 0, "selected": false, "text": "<p>Had the same problem. Turns out the TNSNAMES.ORA in out deployment environment had a different ADDRESS_NAME and SID/SERVICE_NAME ,and the application was configured to use the SID - which caused the problem.</p>\n\n<p><strong>Your connection string must contain the ADDRESS_NAME and not the SID</strong></p>\n" }, { "answer_id": 20754163, "author": "Vivek Vermani", "author_id": 2789764, "author_profile": "https://Stackoverflow.com/users/2789764", "pm_score": 0, "selected": false, "text": "<p>Possible Resolutions - </p>\n\n<p>Verify that the TNSNAMES.ORA exists and is accessible.</p>\n\n<p>Make sure that there are no syntax errors in TNSNAMES.ORA.</p>\n\n<p>Verify that the connection string is correct.</p>\n\n<p>Verify if there are any DNS issues.</p>\n\n<p>If the problem is while connect to server using PL sql developer client.try to install SQL developer within Program File instead of Program Files(x86)'s</p>\n" }, { "answer_id": 20966307, "author": "Rohit Hans", "author_id": 3168126, "author_profile": "https://Stackoverflow.com/users/3168126", "pm_score": 0, "selected": false, "text": "<p>Add the environment:</p>\n\n<pre><code>Variable Name: TNS_ADMIN\n\nVariable Value: (YourDrive):\\app\\(UserName)\\product\\11.2.0\\dbhome_1\\NETWORK\\ADMIN\n</code></pre>\n" }, { "answer_id": 39546535, "author": "Sarath Subramanian", "author_id": 3312636, "author_profile": "https://Stackoverflow.com/users/3312636", "pm_score": 0, "selected": false, "text": "<p>I had faced the similar issue. The below code was working in my system but was not working in another server even though I had added a tns entry in tnsnames.ora file.</p>\n\n<pre><code>con = new OracleConnection();\ncon.ConnectionString = \"User Id=username;Password=password;Data Source=uit45\";\ncon.Open(); // throws error here\n</code></pre>\n\n<p>After digging and digging, I found out the solution for this. We need to ignore the entry in tns file and can be given tns entry as connection string, which worked fine for me. Try the below code.</p>\n\n<pre><code>con = new OracleConnection(\"Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=db-uit45.xxx)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SID=uit45)));User Id=username;Password=password\");\ncon.Open();\n</code></pre>\n\n<p>Note that you need to give the associated values, especially for <code>HOST,PORT,SID,User Id</code> and <code>Password</code>.</p>\n" }, { "answer_id": 71452067, "author": "Shinjini", "author_id": 18448818, "author_profile": "https://Stackoverflow.com/users/18448818", "pm_score": 1, "selected": false, "text": "<p>Do not put @ in the password you are setting or remove it from the password.\nI was also getting the error and after changing it, the error got resolved.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24521/" ]
I recently deploy one web application in one of my development servers. I'm using oracle, asp.net and c#. When I run the application in the server everything works fine, but when I try to run the application outside of the server (using my pc, for example) i get this error: ``` ORA-12154: TNS:could not resolve the connect identifier specified ``` If i run the application in my pc with visual studio it works fine. Oracle is installed in Server "A" and the application is in server "B". Server "A" is in one domain and server "B" is in other domain.My pc is in the same domain has Server "A". In my pc I can find the file tnsname.ora in C:\oracle\product\10.2.0\client\_1\NETWORK\ADMIN, but in Server "B" i can´t find it anywhere any idea? Thanks for the help.
Guess: An oracle client is not installed on Server B. If you do have an oracle client installed then you can still put a tnsnames file in any location (Such as a directory on a network share). In order to do this, set a TNS\_ADMIN system variable (System Properties->Advanced->Environment Variables on XP) to the directory containing your tnsnames files. For me for example I have a system variable: TNS\_ADMIN - C:\oracle\ora92\network\ADMIN
162,798
<p>One of the really nice things about python is the simplicity with which you can name variables that have the same name as the accessor:</p> <pre><code>self.__value = 1 def value(): return self.__value </code></pre> <p>Is there a simple way of providing access to the private members of a class that I wish to subclass? Often I wish to simply work with the raw data objects inside of a class without having to use accessors and mutators all the time.</p> <p>I know this seems to go against the general idea of private and public, but usually the class I am trying to subclass is one of my own which I am quite happy to expose the members from to a subclass but not to an instance of that class. Is there a clean way of providing this distinction?</p>
[ { "answer_id": 162854, "author": "Thomas Wouters", "author_id": 17624, "author_profile": "https://Stackoverflow.com/users/17624", "pm_score": 4, "selected": true, "text": "<p>Not conveniently, without further breaking encapsulation. The double-underscore attribute is name-mangled by prepending '_ClassName' for the class it is being accessed in. So, if you have a 'ContainerThing' class that has a '__value' attribute, the attribute is actually being stored as '<code>_ContainerThing__value</code>'. Changing the class name (or refactoring where the attribute is assigned to) would mean breaking all subclasses that try to access that attribute.</p>\n\n<p>This is exactly why the double-underscore name-mangling (which is not really \"private\", just \"inconvenient\") is a bad idea to use. Just use a <em>single</em> leading underscore. Everyone will know not to touch your 'private' attribute and you will still be able to access it in subclasses and other situations where it's darned handy. The name-mangling of double-underscore attributes is useful only to avoid name-clashes for attributes that are truly specific to a particular class, which is extremely rare. It provides no extra 'security' since even the name-mangled attributes are trivially accessible.</p>\n\n<p>For the record, '<code>__value</code>' and '<code>value</code>' (and '<code>_value</code>') are not the same name. The underscores are part of the name.</p>\n" }, { "answer_id": 163571, "author": "Jeremy Brown", "author_id": 21776, "author_profile": "https://Stackoverflow.com/users/21776", "pm_score": 1, "selected": false, "text": "<p>Not sure of where to cite it from, but the following statement in regard to access protection is Pythonic canon: \"We're all consenting adults here\".</p>\n\n<p>Just as Thomas Wouters has stated, a single leading underscore is the idiomatic way of marking an attribute as being a part of the object's internal state. Two underscores just provides name mangling to prevent easy access to the attribute.</p>\n\n<p>After that, you should just expect that the client of your library won't go and shoot themselves in the foot by meddling with the \"private\" attributes.</p>\n" }, { "answer_id": 164691, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 2, "selected": false, "text": "<p>\"I know this seems to go against the general idea of private and public\" Not really \"against\", just different from C++ and Java.</p>\n\n<p>Private -- as implemented in C++ and Java is not a very useful concept. It helps, sometimes, to isolate implementation details. But it is way overused.</p>\n\n<p>Python names beginning with two <code>__</code> are special and you should not, as a normal thing, be defining attributes with names like this. Names with <code>__</code> are special and part of the implementation. And exposed for your use.</p>\n\n<p>Names beginning with one <code>_</code> are \"private\". Sometimes they are concealed, a little. Most of the time, the \"consenting adults\" rule applies -- don't use them foolishly, they're subject to change without notice. </p>\n\n<p>We put \"private\" in quotes because it's just an agreement between you and your users. You've marked things with <code>_</code>. Your users (and yourself) should honor that.</p>\n\n<p>Often, we have method function names with a leading <code>_</code> to indicate that we consider them to be \"private\" and subject to change without notice.</p>\n\n<p>The endless getters and setters that Java requires aren't as often used in Python. Python introspection is more flexible, you have access to an object's internal dictionary of attribute values, and you have first class <a href=\"http://docs.python.org/lib/built-in-funcs.html\" rel=\"nofollow noreferrer\">functions</a> like <code>getattr()</code> and <code>setattr()</code>.</p>\n\n<p>Further, you have the <code>property()</code> function which is often used to bind getters and setters to a single name that behaves like a simple attribute, but is actually well-defined method function calls.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162798", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18909/" ]
One of the really nice things about python is the simplicity with which you can name variables that have the same name as the accessor: ``` self.__value = 1 def value(): return self.__value ``` Is there a simple way of providing access to the private members of a class that I wish to subclass? Often I wish to simply work with the raw data objects inside of a class without having to use accessors and mutators all the time. I know this seems to go against the general idea of private and public, but usually the class I am trying to subclass is one of my own which I am quite happy to expose the members from to a subclass but not to an instance of that class. Is there a clean way of providing this distinction?
Not conveniently, without further breaking encapsulation. The double-underscore attribute is name-mangled by prepending '\_ClassName' for the class it is being accessed in. So, if you have a 'ContainerThing' class that has a '\_\_value' attribute, the attribute is actually being stored as '`_ContainerThing__value`'. Changing the class name (or refactoring where the attribute is assigned to) would mean breaking all subclasses that try to access that attribute. This is exactly why the double-underscore name-mangling (which is not really "private", just "inconvenient") is a bad idea to use. Just use a *single* leading underscore. Everyone will know not to touch your 'private' attribute and you will still be able to access it in subclasses and other situations where it's darned handy. The name-mangling of double-underscore attributes is useful only to avoid name-clashes for attributes that are truly specific to a particular class, which is extremely rare. It provides no extra 'security' since even the name-mangled attributes are trivially accessible. For the record, '`__value`' and '`value`' (and '`_value`') are not the same name. The underscores are part of the name.
162,804
<p>I have a char array in a C application that I have to split into parts of 250 so that I can send it along to another application that doesn't accept more at one time. </p> <p>How would I do that? Platform: win32. </p>
[ { "answer_id": 162837, "author": "jvasak", "author_id": 5840, "author_profile": "https://Stackoverflow.com/users/5840", "pm_score": 3, "selected": true, "text": "<p>From the MSDN documentation:</p>\n\n<blockquote>\n <p>The strncpy function copies the initial count characters of strSource to strDest and returns strDest. If count is less than or equal to the length of strSource, a null character is not appended automatically to the copied string. If count is greater than the length of strSource, the destination string is padded with null characters up to length count. The behavior of strncpy is undefined if the source and destination strings overlap. </p>\n</blockquote>\n\n<p>Note that <code>strncpy</code> doesn't check for valid destination space; that is left to the programmer. Prototype:</p>\n\n<p><code>char *strncpy(\n char *strDest,\n const char *strSource,\n size_t count \n);\n</code></p>\n\n<p>Extended example:</p>\n\n<pre><code>void send250(char *inMsg, int msgLen)\n{\n char block[250];\n while (msgLen &gt; 0)\n {\n int len = (msgLen&gt;250) ? 250 : msgLen;\n strncpy(block, inMsg, 250);\n\n // send block to other entity\n\n msgLen -= len;\n inMsg += len;\n }\n}\n</code></pre>\n" }, { "answer_id": 162849, "author": "warren", "author_id": 4418, "author_profile": "https://Stackoverflow.com/users/4418", "pm_score": 1, "selected": false, "text": "<p>I can think of something along the lines of the following:</p>\n\n<pre><code>char *somehugearray;\nchar chunk[251] ={0};\nint k;\nint l;\nfor(l=0;;){\n for(k=0; k&lt;250 &amp;&amp; somehugearray[l]!=0; k++){\n chunk[k] = somehugearray[l];\n l++;\n }\n chunk[k] = '\\0';\n dohandoff(chunk);\n}\n</code></pre>\n" }, { "answer_id": 162928, "author": "Ates Goral", "author_id": 23501, "author_profile": "https://Stackoverflow.com/users/23501", "pm_score": 1, "selected": false, "text": "<p>If you strive for performance and you're allowed to touch the string a bit (i.e. the buffer is not const, no thread safety issues etc.), you could momentarily null-terminate the string at intervals of 250 characters and send it in chunks, directly from the original string:</p>\n\n<pre><code>char *str_end = str + strlen(str);\nchar *chunk_start = str;\n\nwhile (true) {\n char *chunk_end = chunk_start + 250;\n\n if (chunk_end &gt;= str_end) {\n transmit(chunk_start);\n break;\n }\n\n char hijacked = *chunk_end;\n *chunk_end = '\\0';\n transmit(chunk_start);\n *chunk_end = hijacked;\n\n chunk_start = chunk_end;\n}\n</code></pre>\n" }, { "answer_id": 165602, "author": "Mike Thompson", "author_id": 2754, "author_profile": "https://Stackoverflow.com/users/2754", "pm_score": 0, "selected": false, "text": "<p>jvasaks's answer is basically correct, except that he hasn't null terminated 'block'. The code should be this:</p>\n\n<pre><code>void send250(char *inMsg, int msgLen)\n{\n char block[250];\n while (msgLen &gt; 0)\n {\n int len = (msgLen&gt;249) ? 249 : msgLen;\n strncpy(block, inMsg, 249);\n block[249] = 0;\n\n // send block to other entity\n\n msgLen -= len;\n inMsg += len;\n }\n</code></pre>\n\n<p>}</p>\n\n<p>So, now the block is 250 characters including the terminating null. strncpy will null terminate the last block if there are less than 249 characters remaining.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162804", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10010/" ]
I have a char array in a C application that I have to split into parts of 250 so that I can send it along to another application that doesn't accept more at one time. How would I do that? Platform: win32.
From the MSDN documentation: > > The strncpy function copies the initial count characters of strSource to strDest and returns strDest. If count is less than or equal to the length of strSource, a null character is not appended automatically to the copied string. If count is greater than the length of strSource, the destination string is padded with null characters up to length count. The behavior of strncpy is undefined if the source and destination strings overlap. > > > Note that `strncpy` doesn't check for valid destination space; that is left to the programmer. Prototype: `char *strncpy( char *strDest, const char *strSource, size_t count );` Extended example: ``` void send250(char *inMsg, int msgLen) { char block[250]; while (msgLen > 0) { int len = (msgLen>250) ? 250 : msgLen; strncpy(block, inMsg, 250); // send block to other entity msgLen -= len; inMsg += len; } } ```
162,810
<p>I am using Log4Net with the AdoNetAppender to log messages from a simple systray application into a SQL Server 2005 database.</p> <p>I want to log the machine name along with the log message because this application will be running on multiple machines and I need to know on which one the message originated.</p> <p>But, I cannot find a way to expose this information via the log4net.Layout.PatternLayout that I am using with the appender.</p> <p>Is there a way to log the machine name via log4net in this manner?</p>
[ { "answer_id": 162979, "author": "Thad", "author_id": 24500, "author_profile": "https://Stackoverflow.com/users/24500", "pm_score": 4, "selected": false, "text": "<p>you can create a parameter similar to the following:</p>\n\n<pre><code>&lt;parameter&gt;\n &lt;parameterName value=\"@machine\" /&gt;\n &lt;dbType value=\"String\" /&gt;\n &lt;size value=\"255\" /&gt;\n &lt;layout type=\"log4net.Layout.PatternLayout\"&gt;\n &lt;conversionPattern value=\"%X{machine}\" /&gt;\n &lt;/layout&gt;\n&lt;/parameter&gt;\n</code></pre>\n\n<p>Then add this line before writing to the log: <code>MDC.Set(\"machine\", Environment.MachineName);</code></p>\n" }, { "answer_id": 163362, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 7, "selected": true, "text": "<p>You can use the pre-populated property <code>log4net:HostName</code>, for example:</p>\n\n<pre><code>&lt;conversionPattern value=\"%property{log4net:HostName}\" /&gt;\n</code></pre>\n\n<p>This way you don't need to populate the MDC.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2834/" ]
I am using Log4Net with the AdoNetAppender to log messages from a simple systray application into a SQL Server 2005 database. I want to log the machine name along with the log message because this application will be running on multiple machines and I need to know on which one the message originated. But, I cannot find a way to expose this information via the log4net.Layout.PatternLayout that I am using with the appender. Is there a way to log the machine name via log4net in this manner?
You can use the pre-populated property `log4net:HostName`, for example: ``` <conversionPattern value="%property{log4net:HostName}" /> ``` This way you don't need to populate the MDC.
162,871
<p>I'm quite new to NHibernate and starting to find my way around.</p> <p>I have a domain model that is somewhat like a tree.</p> <p>Funds have Periods have Selections have Audits<br> Now I would like to get all Audits for a specific Fund</p> <p>Would look like this if I made it in SQL</p> <p>SELECT A.*<br> FROM Audit A<br> JOIN Selection S ON A.fkSelectionID = S.pkID<br> JOIN Period P ON S.fkPeriodID = P.pkID<br> JOIN Fund F ON P.fkFundID = F.pkID<br> WHERE F.pkID = 1</p> <p>All input appreciated!</p>
[ { "answer_id": 162966, "author": "Jasper", "author_id": 18702, "author_profile": "https://Stackoverflow.com/users/18702", "pm_score": 1, "selected": false, "text": "<p>Try this </p>\n\n<pre><code>select elements(s.Audits)\nfrom Fund as f inner join Period as p inner join Selection as s \nwhere f = myFundInstance \n</code></pre>\n" }, { "answer_id": 214286, "author": "kͩeͣmͮpͥ ͩ", "author_id": 26479, "author_profile": "https://Stackoverflow.com/users/26479", "pm_score": 1, "selected": false, "text": "<pre><code>session.CreateCriteria ( typeof(Audit) )\n .CreateCriteria(\"Selection\")\n .CreateCriteria(\"Period\")\n .CreateCriteria(\"Fund\")\n .Add(Restrinction.IdEq(fundId))\n</code></pre>\n" }, { "answer_id": 243332, "author": "penderi", "author_id": 32027, "author_profile": "https://Stackoverflow.com/users/32027", "pm_score": 0, "selected": false, "text": "<p>using LINQ ....</p>\n\n<p>(from var p in Fund.Periods\nlet fundPeriodSelections = p.Selections\nfrom var selection in fundPeriodSelections \nselect selection.Audit).ToList()</p>\n\n<p>... but it does depend on those many-to-many / one-to-many relations being 2-way. Also, I was thinking you may need a mapping table / class in bewteen the Period / Fund table.. but I guess you've already considered it.</p>\n\n<p>Hope the LINQ statemanet above works ... it depends on those mentioend properties, but it's an apraoch we've used on our project that's really cleaned up the code. </p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11434/" ]
I'm quite new to NHibernate and starting to find my way around. I have a domain model that is somewhat like a tree. Funds have Periods have Selections have Audits Now I would like to get all Audits for a specific Fund Would look like this if I made it in SQL SELECT A.\* FROM Audit A JOIN Selection S ON A.fkSelectionID = S.pkID JOIN Period P ON S.fkPeriodID = P.pkID JOIN Fund F ON P.fkFundID = F.pkID WHERE F.pkID = 1 All input appreciated!
Try this ``` select elements(s.Audits) from Fund as f inner join Period as p inner join Selection as s where f = myFundInstance ```
162,873
<p>How do you include a file that is more than 2 directories back. I know you can use <code>../index.php</code> to include a file that is 2 directories back, but how do you do it for 3 directories back? Does this make sense? I tried <code>.../index.php</code> but it isn't working.</p> <p>I have a file in <code>/game/forum/files/index.php</code> and it uses PHP include to include a file. Which is located in <code>/includes/boot.inc.php</code>; <code>/</code> being the root directory.</p>
[ { "answer_id": 162881, "author": "bdukes", "author_id": 2688, "author_profile": "https://Stackoverflow.com/users/2688", "pm_score": 4, "selected": false, "text": "<pre><code>../../index.php \n</code></pre>\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</p>\n" }, { "answer_id": 162882, "author": "Ólafur Waage", "author_id": 22459, "author_profile": "https://Stackoverflow.com/users/22459", "pm_score": 3, "selected": false, "text": "<p>You can do <code>../../directory/file.txt</code> - This goes two directories back.</p>\n\n<p><code>../../../</code> - this goes three. etc</p>\n" }, { "answer_id": 162883, "author": "HAXEN", "author_id": 11434, "author_profile": "https://Stackoverflow.com/users/11434", "pm_score": 3, "selected": false, "text": "<pre><code>../../../includes/boot.inc.php\n</code></pre>\n" }, { "answer_id": 162884, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 8, "selected": false, "text": "<p><code>..</code> selects the parent directory from the current. Of course, this can be chained:</p>\n\n<pre><code>../../index.php\n</code></pre>\n\n<p>This would be two directories up.</p>\n" }, { "answer_id": 162887, "author": "MazarD", "author_id": 22672, "author_profile": "https://Stackoverflow.com/users/22672", "pm_score": 3, "selected": false, "text": "<pre><code>../../../index.php\n</code></pre>\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</p>\n" }, { "answer_id": 162888, "author": "leek", "author_id": 3765, "author_profile": "https://Stackoverflow.com/users/3765", "pm_score": 4, "selected": false, "text": "<pre><code>../../../includes/boot.inc.php\n</code></pre>\n\n<p>Each instance of <code>../</code> means up/back one directory.</p>\n" }, { "answer_id": 162891, "author": "Joe Skora", "author_id": 14057, "author_profile": "https://Stackoverflow.com/users/14057", "pm_score": 5, "selected": false, "text": "<pre><code>. = current directory\n.. = parent directory\n</code></pre>\n\n<p><strong>So <code>../</code> gets you <em>one directory back not two</em></strong>. </p>\n\n<p>Chain <code>../</code> as many times as necessary to go up 2 or more levels.</p>\n" }, { "answer_id": 162899, "author": "ZombieSheep", "author_id": 377, "author_profile": "https://Stackoverflow.com/users/377", "pm_score": 3, "selected": false, "text": "<p>But be <strong><em>VERY</em></strong> careful about letting a user select the file. You don't really want to allow them to get a file called, for example,</p>\n\n<pre><code>../../../../../../../../../../etc/passwd\n</code></pre>\n\n<p>or other sensitive system files.</p>\n\n<p>(Sorry, it's been a while since I was a linux sysadmin, and I <em>think</em> this is a sensitive file, from what I remember)</p>\n" }, { "answer_id": 162905, "author": "Dan Hulton", "author_id": 8327, "author_profile": "https://Stackoverflow.com/users/8327", "pm_score": 6, "selected": false, "text": "<p>To include a file one directory back, use <code>'../file'</code>.\nFor two directories back, use <code>'../../file'</code>.\nAnd so on. </p>\n\n<p>Although, realistically you shouldn't be performing includes relative to the current directory. What if you wanted to move that file? All of the links would break. A way to ensure that you can still link to other files, while retaining those links if you move your file, is: </p>\n\n<pre><code>require_once($_SERVER['DOCUMENT_ROOT'] . 'directory/directory/file');\n</code></pre>\n\n<p><code>DOCUMENT_ROOT</code> is a server variable that represents the base directory that your code is located within.</p>\n" }, { "answer_id": 162918, "author": "Mauro", "author_id": 2208, "author_profile": "https://Stackoverflow.com/users/2208", "pm_score": 2, "selected": false, "text": "<p>if you include the <code>/</code> at the start of the include, the include will be taken as the path from the root of the site.</p>\n\n<p>if your site is <a href=\"http://www.example.com/game/forum/files/index.php\" rel=\"nofollow noreferrer\">http://www.example.com/game/forum/files/index.php</a> you can add an include to /includes/boot.inc.php which would resolve to <a href=\"http://www.example.com/includes/boot.inc.php\" rel=\"nofollow noreferrer\">http://www.example.com/includes/boot.inc.php</a> . </p>\n\n<p>You have to be careful with <code>..</code> traversal as some web servers have it disabled; it also causes problems when you want to move your site to a new machine/host and the structure is a little different.</p>\n" }, { "answer_id": 11953884, "author": "im_brian_d", "author_id": 1342440, "author_profile": "https://Stackoverflow.com/users/1342440", "pm_score": 4, "selected": false, "text": "<p><code>../</code> is one directory, Repeat for two directories <code>../../</code> or even three: <code>../../../</code> and so on. </p>\n\n<p>Defining constants may reduce confusion because you will drill forward into directories verses backwards</p>\n\n<p>You could define some constants like so:</p>\n\n<pre><code>define('BD', '/home/user/public_html/example/');\n\ndefine('HTMLBD', 'http://example.com/');\n</code></pre>\n\n<p>When using 'BD' or my 'base directory' it looks like so:</p>\n\n<pre><code>file(BD.'location/of/file.php');\n</code></pre>\n\n<p><a href=\"http://php.net/manual/en/function.define.php\" rel=\"noreferrer\">define(); reference</a> </p>\n" }, { "answer_id": 12095160, "author": "gaborous", "author_id": 1121352, "author_profile": "https://Stackoverflow.com/users/1121352", "pm_score": 5, "selected": false, "text": "<pre><code>include dirname(__FILE__).'/../../index.php';\n</code></pre>\n\n<p>is your best bet here, and it will avoid most of the relative path bugs you can encounter with other solutions.</p>\n\n<p>Indeed, it will force the include to always be <strong>relative to the position of the current script</strong> where this code is placed (which location is most likely stable, since you define the architecture of your application). This is different from just doing <code>include '../../index.php'</code> <a href=\"http://php.net/manual/en/function.include.php\">which will include relatively to the executing (also named \"calling\") script and then relatively to the current working directory</a>, which will point to the parent script that includes your script, instead of resolving from your included script's path.</p>\n\n<p>From the PHP documentation:</p>\n\n<blockquote>\n <p>Files are included based on the file path given or, if none is given,\n the include_path specified. If the file isn't found in the\n include_path, include will finally check in the calling script's own\n directory and the current working directory before failing.</p>\n</blockquote>\n\n<p>And the oldest post I've found citing this trick <a href=\"http://php.net/manual/en/function.dirname.php#21138\">dates back to 2003, by Tapken</a>.</p>\n\n<p>You can test with the following setup:</p>\n\n<p>Create a layout like this:</p>\n\n<pre><code>htdocs\n¦ parent.php\n¦ goal.php\n¦\n+---sub\n ¦ included.php\n ¦ goal.php\n</code></pre>\n\n<p>In <code>parent.php</code>, put:</p>\n\n<pre><code>&lt;?php\ninclude dirname(__FILE__).'/sub/included.php';\n?&gt;\n</code></pre>\n\n<p>In <code>sub/included.php</code>, put:</p>\n\n<pre><code>&lt;?php\nprint(\"WRONG : \" . realpath('goal.php'));\nprint(\"GOOD : \" . realpath(dirname(__FILE__).'/goal.php'));\n?&gt;\n</code></pre>\n\n<p>Result when accessing <code>parent.php</code>:</p>\n\n<pre><code>WRONG : X:\\htdocs\\goal.php\nGOOD : X:\\htdocs\\sub\\goal.php\n</code></pre>\n\n<p>As we can see, in the first case, the path is resolved from the calling script <code>parent.php</code>, while by using the <code>dirname(__FILE__).'/path'</code> trick, the include is done from the script <code>included.php</code> where the code is placed in.</p>\n\n<p>Beware, the following NOT equivalent to the trick above contrary to what can be read elsewhere:</p>\n\n<pre><code>include '/../../index.php';\n</code></pre>\n\n<p>Indeed, prepending <code>/</code> will work, but it will resolve just like <code>include ../../index.php</code> from the calling script (the difference is that <code>include_path</code> won't be looked afterwards if it fails). <a href=\"http://php.net/manual/en/function.include.php\">From PHP doc</a>:</p>\n\n<blockquote>\n <p>If a path is defined — whether absolute (starting with a drive letter\n or \\ on Windows, or / on Unix/Linux systems) or relative to the\n current directory (starting with . or ..) — the include_path will be\n ignored altogether.</p>\n</blockquote>\n" }, { "answer_id": 12289657, "author": "Bronek", "author_id": 769465, "author_profile": "https://Stackoverflow.com/users/769465", "pm_score": 1, "selected": false, "text": "<p>I saw your answers and I used include path with syntax</p>\n\n<pre><code>require_once '../file.php'; // server internal error 500\n</code></pre>\n\n<p>and http server (Apache 2.4.3) returned internal error 500.</p>\n\n<p>When I changed the path to</p>\n\n<pre><code>require_once '/../file.php'; // OK\n</code></pre>\n\n<p>everything is fine.</p>\n" }, { "answer_id": 12437609, "author": "khan", "author_id": 1673412, "author_profile": "https://Stackoverflow.com/users/1673412", "pm_score": 2, "selected": false, "text": "<p>Try <code>../../</code>. You can modify it accordingly as it will take you up back two directories. First reach to root directory then access the required directory.</p>\n\n<p>E.g. You are in <code>root/inc/usr/ap</code> and there is another directory <code>root/2nd/path</code>. You can access the <code>path</code> directory from <code>ap</code> like this: \n<code>../../2nd/path</code> first go to root than desired directory. If not working please share.</p>\n" }, { "answer_id": 19946346, "author": "user2951753", "author_id": 2951753, "author_profile": "https://Stackoverflow.com/users/2951753", "pm_score": 3, "selected": false, "text": "<p>following are ways to access your different directories:-</p>\n\n<pre><code>./ = Your current directory\n../ = One directory lower\n../../ = Two directories lower\n../../../ = Three directories lower\n</code></pre>\n" }, { "answer_id": 22999028, "author": "allenn", "author_id": 3521287, "author_profile": "https://Stackoverflow.com/users/3521287", "pm_score": 2, "selected": false, "text": "<p>including over directories can be processed by proxy file</p>\n\n<ul>\n<li>root</li>\n<li>.....|__web</li>\n<li>.....|.........|_requiredDbSettings.php</li>\n<li>.....|</li>\n<li>.....|___db</li>\n<li>.....|.........|_dbsettings.php</li>\n<li>.....|</li>\n<li><p>.....|_proxy.php</p>\n\n<pre><code>dbsettings.php:\n$host='localhost';\n$user='username':\n$pass='pass';\n\nproxy.php:\ninclude_once 'db/dbsettings.php\n\nrequiredDbSettings.php:\ninclude_once './../proxy.php';\n</code></pre></li>\n</ul>\n" }, { "answer_id": 40989202, "author": "ron", "author_id": 2672617, "author_profile": "https://Stackoverflow.com/users/2672617", "pm_score": 3, "selected": false, "text": "<p>if you are using php7 you can use dirname function with level parameter of 2, for example :</p>\n\n<pre><code>dirname(\"/usr/local/lib\", 2);\n</code></pre>\n\n<p>the second parameter \"2\" indicate how many level up </p>\n\n<p><a href=\"http://php.net/manual/en/function.dirname.php\" rel=\"noreferrer\">dirname referance</a></p>\n" }, { "answer_id": 43917676, "author": "LF00", "author_id": 6521116, "author_profile": "https://Stackoverflow.com/users/6521116", "pm_score": 3, "selected": false, "text": "<p>I recomend to use <code>__DIR__</code> to specify <a href=\"https://stackoverflow.com/a/5398508/6521116\">current php file directory</a>. Check <a href=\"https://stackoverflow.com/q/43917238/6521116\">here</a> for the reason.</p>\n\n<pre><code>__DIR__ . /../../index.php\n</code></pre>\n" }, { "answer_id": 55488815, "author": "rajpoot rehan", "author_id": 6687325, "author_profile": "https://Stackoverflow.com/users/6687325", "pm_score": 4, "selected": false, "text": "<p><strong><em>Try This</em></strong></p>\n\n<p><strong>this example is one directory back</strong></p>\n\n<pre><code>require_once('../images/yourimg.png');\n</code></pre>\n\n<p><strong>this example is two directory back</strong></p>\n\n<pre><code>require_once('../../images/yourimg.png');\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162873", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How do you include a file that is more than 2 directories back. I know you can use `../index.php` to include a file that is 2 directories back, but how do you do it for 3 directories back? Does this make sense? I tried `.../index.php` but it isn't working. I have a file in `/game/forum/files/index.php` and it uses PHP include to include a file. Which is located in `/includes/boot.inc.php`; `/` being the root directory.
`..` selects the parent directory from the current. Of course, this can be chained: ``` ../../index.php ``` This would be two directories up.
162,874
<p>I'm using <a href="http://enunciate.codehaus.org" rel="nofollow noreferrer">Enunciate</a> to build a prototype REST api and need to include a jar containing custom code as a library.</p> <p>My Ant Script looks like this:</p> <p></p> <pre><code>&lt;!--include all jars--&gt; &lt;path id="en.classpath"&gt; &lt;fileset dir="${lib}"&gt; &lt;include name="**/*.jar" /&gt; &lt;/fileset&gt; &lt;/path&gt; &lt;!--define the task--&gt; &lt;taskdef name="enunciate" classname="org.codehaus.enunciate.main.EnunciateTask"&gt; &lt;classpath refid="en.classpath" /&gt; &lt;/taskdef&gt; &lt;mkdir dir="${dist}" /&gt; &lt;enunciate dir="${src}" configFile="${basedir}/enunciate.xml"&gt; &lt;include name="**/*.java" /&gt; &lt;classpath refid="en.classpath"/&gt; &lt;export artifactId="spring.war.file" destination="${dist}/${war.name}" /&gt; &lt;/enunciate&gt; </code></pre> <p></p> <p>The problem is that my custom jar is being excluded from the WAR file. It is necessary to compile the enunciate annotated classes so the jar is obviously on the classpath at compile time but enunciate is failing to include it in the distribution. I have also noticed that several of the jars needed by enunciate are not being included in the WAR file.</p> <p>Why are they being excluded and how do I fix it?</p>
[ { "answer_id": 221420, "author": "Miguel Ping", "author_id": 22992, "author_profile": "https://Stackoverflow.com/users/22992", "pm_score": 2, "selected": false, "text": "<p>I never used enunciate, but as a quick hack you can add the jars to the war:</p>\n\n<pre><code>&lt;jar jarfile=\"${dist}/${war.name}\" update=\"true\"&gt;\n &lt;fileset dir=\"${lib}\"&gt;\n &lt;include name=\"**/*.jar\" /&gt;\n &lt;/fileset&gt;\n&lt;/jar&gt;\n</code></pre>\n\n<p>Note: you probably want to add the jars to the <strong>WEB-INF/lib</strong> directory, instead of the root directory.</p>\n\n<p>I'm guessing that enunciate does the mininum to interfere with your own build process, since you know best what to put within your jar file.</p>\n" }, { "answer_id": 1058310, "author": "Randyaa", "author_id": 9518, "author_profile": "https://Stackoverflow.com/users/9518", "pm_score": 2, "selected": true, "text": "<p>As it turns out one of the jars we're attempting to include has a dependency listed in it's Manifest file of a jar that Enunciate depends on (freemarker). Enunciate automatically excludes freemarker and at first glance it seems as though it automatically excludes anything that depends on freemarker as well. If we remove freemarker from the list of dependent jars in our code's manifest file it works just fine.</p>\n\n<p>However; I've spoken with the main developer of Enunciate (Ryan Heaten) and he assures me this isn't what's happening. Including his response below:</p>\n\n<blockquote>\n <p>Really?!</p>\n \n <p>Wow. Interesting. I can't explain\n it; Enunciate doesn't look at what's\n in the Manifest in order to determine\n what to include in the war, so I'm\n kind of stumped here. It could also\n be some weird Ant behavior (not\n including that jar in the\n \"en.classpath\" reference for some\n reason).</p>\n \n <p>~Ryan</p>\n</blockquote>\n" }, { "answer_id": 32510845, "author": "Amber", "author_id": 1324406, "author_profile": "https://Stackoverflow.com/users/1324406", "pm_score": 0, "selected": false, "text": "<p>In enunciate.xml I tell it not to copy any libs itself:</p>\n\n<pre><code>&lt;webapp doLibCopy=\"false\"&gt;\n</code></pre>\n\n<p>Then in the ant build file at the end of the enunciate task I update the war (you can do this to update the included/excluded jars whether or not you have Enunciate copy the jars for you in the step above):</p>\n\n<pre><code>&lt;war destfile=\"build-output/{mywar}\" update=\"true\"&gt;\n &lt;lib dir=\"WebContent/WEB-INF/lib\"&gt;\n &lt;include name=\"**/*.jar\" /&gt;\n &lt;/lib&gt;\n &lt;lib dir=\"build-output\"&gt;\n &lt;include name=\"some_other.jar\" /&gt;\n &lt;/lib&gt;\n&lt;/war&gt;\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162874", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9518/" ]
I'm using [Enunciate](http://enunciate.codehaus.org) to build a prototype REST api and need to include a jar containing custom code as a library. My Ant Script looks like this: ``` <!--include all jars--> <path id="en.classpath"> <fileset dir="${lib}"> <include name="**/*.jar" /> </fileset> </path> <!--define the task--> <taskdef name="enunciate" classname="org.codehaus.enunciate.main.EnunciateTask"> <classpath refid="en.classpath" /> </taskdef> <mkdir dir="${dist}" /> <enunciate dir="${src}" configFile="${basedir}/enunciate.xml"> <include name="**/*.java" /> <classpath refid="en.classpath"/> <export artifactId="spring.war.file" destination="${dist}/${war.name}" /> </enunciate> ``` The problem is that my custom jar is being excluded from the WAR file. It is necessary to compile the enunciate annotated classes so the jar is obviously on the classpath at compile time but enunciate is failing to include it in the distribution. I have also noticed that several of the jars needed by enunciate are not being included in the WAR file. Why are they being excluded and how do I fix it?
As it turns out one of the jars we're attempting to include has a dependency listed in it's Manifest file of a jar that Enunciate depends on (freemarker). Enunciate automatically excludes freemarker and at first glance it seems as though it automatically excludes anything that depends on freemarker as well. If we remove freemarker from the list of dependent jars in our code's manifest file it works just fine. However; I've spoken with the main developer of Enunciate (Ryan Heaten) and he assures me this isn't what's happening. Including his response below: > > Really?! > > > Wow. Interesting. I can't explain > it; Enunciate doesn't look at what's > in the Manifest in order to determine > what to include in the war, so I'm > kind of stumped here. It could also > be some weird Ant behavior (not > including that jar in the > "en.classpath" reference for some > reason). > > > ~Ryan > > >
162,879
<p>Let's say you have a class with a Uri property. Is there any way to get that property to accept both a string value and a Uri? How would you build it?</p> <p>I'd like to be able to do something like one of the following, but neither are supported (using VB, since it lets you specify type in the Set declaration for the 2nd one):</p> <pre class="lang-vb prettyprint-override"><code>Class MyClass Private _link As Uri 'Option 1: overloaded property Public Property Link1 As Uri Get return _link End Get Set(ByVal value As Uri) _link = value End Set End Property Public Property link1 As String Get return _link.ToString() End Get Set(Byval value As String) _link = new Uri(value) End Set End Property ' Option 2: Overloaded setter Public Property link2 As Uri Get return _link End Get Set(Byval value As Uri) _link = value End Set Set(Byval value As String) _link = new Uri(value) End Set End Class </code></pre> <p>Given that those probably won't be supported any time soon, how else would you handle this? I'm looking for something a little nicer than just providing an additional <code>.SetLink(string value)</code> method, and I'm still on .Net2.0 (though if later versions have a nice feature for this, I'd like to hear about it).</p> <p>I can think of other scenarios where you might want to provide this kind of overload: a class with an SqlConnection member that lets you set either a new connection or a new connection string, for example.</p>
[ { "answer_id": 162890, "author": "bdukes", "author_id": 2688, "author_profile": "https://Stackoverflow.com/users/2688", "pm_score": 2, "selected": false, "text": "<p>I think you just need to provide an accompanying </p>\n\n<pre><code>Public Sub SetLink(ByVal value as String)\n _link = new Uri(value)\nEnd Sub\n</code></pre>\n\n<p>Nothing nicer is available, AFAIK.</p>\n" }, { "answer_id": 162893, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>Let's say you have a class with a Uri property. Is there any way to get that property to accept both a string value and a Uri?</p>\n</blockquote>\n\n<p>No because this would mean having two getters that vary only in their return type and this isn't allowed in .NET.</p>\n\n<p>I would use the <code>Uri</code> method exclusively and perhaps create a convenienec method to set the <code>URI</code> property, given a string. However, since the conversion from <code>String</code> to <code>URI</code> is straightforward, even this might be unnecessary.</p>\n" }, { "answer_id": 162900, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 1, "selected": false, "text": "<p>You can't have one property like that, but you could create two properties which both manipulated the same underlying field - just like Height/Width/Size in Windows Forms.</p>\n" }, { "answer_id": 162913, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 3, "selected": true, "text": "<p>Alternatively, you can of course forego overloading and just name the properties appropriately:</p>\n\n<pre><code>Public WriteOnly Property UriString() As String\n Set(ByVal value As String)\n m_Uri = new Uri(value)\n End Set\nEnd Property\n</code></pre>\n\n<p>Of course you don't have to make this <code>WriteOnly</code> but it seems appropriate.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3043/" ]
Let's say you have a class with a Uri property. Is there any way to get that property to accept both a string value and a Uri? How would you build it? I'd like to be able to do something like one of the following, but neither are supported (using VB, since it lets you specify type in the Set declaration for the 2nd one): ```vb Class MyClass Private _link As Uri 'Option 1: overloaded property Public Property Link1 As Uri Get return _link End Get Set(ByVal value As Uri) _link = value End Set End Property Public Property link1 As String Get return _link.ToString() End Get Set(Byval value As String) _link = new Uri(value) End Set End Property ' Option 2: Overloaded setter Public Property link2 As Uri Get return _link End Get Set(Byval value As Uri) _link = value End Set Set(Byval value As String) _link = new Uri(value) End Set End Class ``` Given that those probably won't be supported any time soon, how else would you handle this? I'm looking for something a little nicer than just providing an additional `.SetLink(string value)` method, and I'm still on .Net2.0 (though if later versions have a nice feature for this, I'd like to hear about it). I can think of other scenarios where you might want to provide this kind of overload: a class with an SqlConnection member that lets you set either a new connection or a new connection string, for example.
Alternatively, you can of course forego overloading and just name the properties appropriately: ``` Public WriteOnly Property UriString() As String Set(ByVal value As String) m_Uri = new Uri(value) End Set End Property ``` Of course you don't have to make this `WriteOnly` but it seems appropriate.
162,897
<p>Given the following C function in a DLL:</p> <pre><code>char * GetDir(char* path ); </code></pre> <p>How would you P/Invoke this function into C# and marshal the char * properly. .NET seems to know how to do LPCTSTR but when I can't figure out any marshaling that doesn't cause a NotSupportedException to fire when calling this function.</p>
[ { "answer_id": 162922, "author": "OregonGhost", "author_id": 20363, "author_profile": "https://Stackoverflow.com/users/20363", "pm_score": 4, "selected": false, "text": "<p>Try</p>\n\n<pre><code>[DllImport(\"your.dll\", CharSet = CharSet.Ansi)]\nstring GetDir(StringBuilder path);\n</code></pre>\n\n<p>string is automatically marshalled to a zero-terminated string, and with the CharSet property, you tell the Marshaller that it should use ANSI rather than Unicode.\nNote: Use string (or System.String) for a const char*, but StringBuilder for a char*.</p>\n\n<p>You can also try MarshalAs, as in <a href=\"http://www.pinvoke.net/default.aspx/kernel32.GetShortPathName\" rel=\"noreferrer\">this example</a>.</p>\n" }, { "answer_id": 163573, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 6, "selected": true, "text": "<p>OregonGhost's answer is only correct if the char* returned from GetDir is either allocated in HGlobal or LocalAlloc. I can't remember which one but the CLR will assume that any string return type from a PInvoke function was allocated with one or the other. </p>\n\n<p>A more robust way is to type the return of GetDir to be IntPtr. Then you can use any of the Marshal.PtrToStringAnsi functions in order to get out a string type. It also gives you th flexibility of freeing the string in the manner of your choosing. </p>\n\n<pre><code>\n[DllImport(\"your.dll\", CharSet = CharSet.Ansi)]\nIntPtr GetDir(StringBuilder path);\n</code></pre>\n\n<p>Can you give us any other hints as to the behavior of GetDir? Does it modify the input string? How is the value which is returned allocated? If you can provide that I can give a much better answer. </p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162897", "https://Stackoverflow.com", "https://Stackoverflow.com/users/194/" ]
Given the following C function in a DLL: ``` char * GetDir(char* path ); ``` How would you P/Invoke this function into C# and marshal the char \* properly. .NET seems to know how to do LPCTSTR but when I can't figure out any marshaling that doesn't cause a NotSupportedException to fire when calling this function.
OregonGhost's answer is only correct if the char\* returned from GetDir is either allocated in HGlobal or LocalAlloc. I can't remember which one but the CLR will assume that any string return type from a PInvoke function was allocated with one or the other. A more robust way is to type the return of GetDir to be IntPtr. Then you can use any of the Marshal.PtrToStringAnsi functions in order to get out a string type. It also gives you th flexibility of freeing the string in the manner of your choosing. ``` [DllImport("your.dll", CharSet = CharSet.Ansi)] IntPtr GetDir(StringBuilder path); ``` Can you give us any other hints as to the behavior of GetDir? Does it modify the input string? How is the value which is returned allocated? If you can provide that I can give a much better answer.
162,911
<p>If I can do this, how do I call Java code (methods for instance) from within JavaScript code, in Wicket. </p>
[ { "answer_id": 163024, "author": "Quentin", "author_id": 19068, "author_profile": "https://Stackoverflow.com/users/19068", "pm_score": 0, "selected": false, "text": "<p>Assuming you mean JavaScript running on the client - you cause an HTTP redirect to be made to the server, and have your servlet react to the request for the given URL.</p>\n\n<p>This is known as <a href=\"http://www.jibbering.com/2002/4/httprequest.html\" rel=\"nofollow noreferrer\">Ajax</a>, and there are a <a href=\"http://developer.yahoo.com/yui/connection/\" rel=\"nofollow noreferrer\">number</a> of <a href=\"http://docs.jquery.com/Ajax\" rel=\"nofollow noreferrer\">libraries</a> that help you do it..</p>\n" }, { "answer_id": 163187, "author": "Paul Whelan", "author_id": 3050, "author_profile": "https://Stackoverflow.com/users/3050", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://www.wicket-library.com/wicket-examples-6.0.x/index.html/\" rel=\"nofollow noreferrer\">http://www.wicket-library.com/wicket-examples-6.0.x/index.html/</a> has plenty of examples to get you going.</p>\n\n<p>Or have a Have a look at DWR</p>\n\n<p><a href=\"http://directwebremoting.org/\" rel=\"nofollow noreferrer\">http://directwebremoting.org/</a></p>\n\n<p>DWR allows Javascript in a browser to interact with Java on a server and helps you manipulate web pages with the results. </p>\n\n<p>As Dorward mentioned this is done via AJAX</p>\n" }, { "answer_id": 1146921, "author": "Antony Stubbs", "author_id": 105741, "author_profile": "https://Stackoverflow.com/users/105741", "pm_score": 5, "selected": true, "text": "<p>erk. The correct answer would be ajax call backs. You can either manually code the js to hook into the wicket js, or you can setup the callbacks from wicket components in java.\nFor example, from AjaxLazyLoadPanel:</p>\n\n<pre><code> component.add( new AbstractDefaultAjaxBehavior() {\n\n @Override\n protected void respond(AjaxRequestTarget target) {\n // your code here\n }\n\n @Override\n public void renderHead(IHeaderResponse response) {\n super.renderHead( response );\n response.renderOnDomReadyJavascript( getCallbackScript().toString() );\n }\n\n }\n</code></pre>\n\n<p>This example shows how to add call back code to any Component in Wicket. After the OnDomReady event fires in your browser, when loading a page, Wicket will cause it's js enging, to call back into your code, using Ajax, to the 'respond' method shown above, at which point you can execute Java code on the server, and potentially add components to the ajax target to be re-rendered.</p>\n\n<p>To do it manually, from js, you can hook into wicket's system by printing out getCallbackScript().toString() to a attribute on a wicket component, which you'll then be able to access from js. Calling this url from js manually with wicket's wicketAjaxGet from wicket-ajax.js.</p>\n\n<p>Check out the mailing list for lot's of conversation on this topic:\n<a href=\"http://www.nabble.com/Wicket-and-javascript-ts24336438.html#a24336438\" rel=\"noreferrer\">http://www.nabble.com/Wicket-and-javascript-ts24336438.html#a24336438</a></p>\n" }, { "answer_id": 3572162, "author": "tetsuo", "author_id": 176897, "author_profile": "https://Stackoverflow.com/users/176897", "pm_score": 3, "selected": false, "text": "<p>Excerpt from <a href=\"https://cwiki.apache.org/WICKET/calling-wicket-from-javascript.html\" rel=\"noreferrer\">https://cwiki.apache.org/WICKET/calling-wicket-from-javascript.html</a></p>\n\n<p>If you add any class that extends AbstractDefaultAjaxBehavior to your page, wicket-ajax.js will be added to the header ofyour web page. wicket-ajax.js provides you with two basic methods to call your component:</p>\n\n<pre><code>function wicketAjaxGet(url, successHandler, failureHandler, precondition, channel)\n</code></pre>\n\n<p>and</p>\n\n<pre><code>function wicketAjaxPost(url, body, successHandler, failureHandler, precondition, channel)\n</code></pre>\n\n<p>Here is an example:</p>\n\n<p>JavaScript</p>\n\n<pre><code>function callWicket() {\n var wcall = wicketAjaxGet('$url$' + '$args$', function() { }, function() { });\n}\n</code></pre>\n\n<p><code>$url$</code> is obtained from the method <code>abstractDefaultAjaxBehavior.getCallbackUrl()</code>. If you paste the String returned from that method into your browser, you'll invoke the respond method, the same applies for the javascript method.</p>\n\n<p>You can optionally add arguments by appending these to the URL string. They take the form <code>&amp;foo=bar</code>.</p>\n\n<p>you get the optional arguments in the Java response method like this:</p>\n\n<pre><code>Map map = ((WebRequestCycle) RequestCycle.get()).getRequest().getParameterMap();\n</code></pre>\n\n<p>or this:</p>\n\n<pre><code>String paramFoo = RequestCycle.get().getRequest().getParameter(\"foo\");\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23486/" ]
If I can do this, how do I call Java code (methods for instance) from within JavaScript code, in Wicket.
erk. The correct answer would be ajax call backs. You can either manually code the js to hook into the wicket js, or you can setup the callbacks from wicket components in java. For example, from AjaxLazyLoadPanel: ``` component.add( new AbstractDefaultAjaxBehavior() { @Override protected void respond(AjaxRequestTarget target) { // your code here } @Override public void renderHead(IHeaderResponse response) { super.renderHead( response ); response.renderOnDomReadyJavascript( getCallbackScript().toString() ); } } ``` This example shows how to add call back code to any Component in Wicket. After the OnDomReady event fires in your browser, when loading a page, Wicket will cause it's js enging, to call back into your code, using Ajax, to the 'respond' method shown above, at which point you can execute Java code on the server, and potentially add components to the ajax target to be re-rendered. To do it manually, from js, you can hook into wicket's system by printing out getCallbackScript().toString() to a attribute on a wicket component, which you'll then be able to access from js. Calling this url from js manually with wicket's wicketAjaxGet from wicket-ajax.js. Check out the mailing list for lot's of conversation on this topic: <http://www.nabble.com/Wicket-and-javascript-ts24336438.html#a24336438>
162,931
<p>I'm trying to create a Crystal Reports formula field (to calculate the percentage change in a price) that will return "N/A" if a particular report field is null, but return a number to two decimal places using accounting format (negative numbers surrounded by parentheses) if it is not.</p> <p>The closest I have been able to manage is this:</p> <pre><code>If IsNull({ValuationReport.YestPrice}) Then 'N/A' Else ToText({@Price}/{ValuationReport.YestPrice}*100-100, '###.00', 2) </code></pre> <p>However this represents negative numbers using a negative sign, not parentheses. </p> <p>I tried format strings like '###.00;(###.00)' and '(###.00)' but these were rejected as invalid. How can I achieve my goal?</p>
[ { "answer_id": 163019, "author": "Pyroglass", "author_id": 21760, "author_profile": "https://Stackoverflow.com/users/21760", "pm_score": 4, "selected": true, "text": "<p>I think you are looking for <code>ToText(CCur(@Price}/{ValuationReport.YestPrice}*100-100))</code></p>\n\n<p>You can use <code>CCur</code> to convert numbers or string to Curency formats. <code>CCur(number)</code> or <code>CCur(string)</code></p>\n\n<hr>\n\n<p>I think this may be what you are looking for,</p>\n\n<p><code>Replace (ToText(CCur({field})),\"$\" , \"\")</code> that will give the parentheses for negative numbers</p>\n\n<p>It is a little hacky, but I'm not sure CR is very kind in the ways of formatting</p>\n" }, { "answer_id": 792254, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<pre><code>if(isnull({uspRptMonthlyGasRevenueByGas;1.YearTotal})) = true then\n \"nd\"\nelse\n totext({uspRptMonthlyGasRevenueByGas;1.YearTotal},'###.00')\n</code></pre>\n\n<p>The above logic should be what you are looking for.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162931", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3012/" ]
I'm trying to create a Crystal Reports formula field (to calculate the percentage change in a price) that will return "N/A" if a particular report field is null, but return a number to two decimal places using accounting format (negative numbers surrounded by parentheses) if it is not. The closest I have been able to manage is this: ``` If IsNull({ValuationReport.YestPrice}) Then 'N/A' Else ToText({@Price}/{ValuationReport.YestPrice}*100-100, '###.00', 2) ``` However this represents negative numbers using a negative sign, not parentheses. I tried format strings like '###.00;(###.00)' and '(###.00)' but these were rejected as invalid. How can I achieve my goal?
I think you are looking for `ToText(CCur(@Price}/{ValuationReport.YestPrice}*100-100))` You can use `CCur` to convert numbers or string to Curency formats. `CCur(number)` or `CCur(string)` --- I think this may be what you are looking for, `Replace (ToText(CCur({field})),"$" , "")` that will give the parentheses for negative numbers It is a little hacky, but I'm not sure CR is very kind in the ways of formatting
162,941
<p>I know this is a really basic question, but I've just started with some basic C++ programming after coding a few projects with high-level languages. </p> <p>Basically I have three questions:</p> <ol> <li>Why use pointers over normal variables?</li> <li>When and where should I use pointers?</li> <li>How do you use pointers with arrays?</li> </ol>
[ { "answer_id": 162971, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 5, "selected": false, "text": "<p>Pointers are one way of getting an indirect reference to another variable. Instead of holding the <em>value</em> of a variable, they tell you its <em>address</em>. This is particularly useful when dealing with arrays, since using a pointer to the first element in an array (its address) you can quickly find the next element by incrementing the pointer (to the next address location).</p>\n\n<p>The best explanation of pointers and pointer arithmetic that I've read is in K &amp; R's <a href=\"https://rads.stackoverflow.com/amzn/click/com/0131103628\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">The C Programming Language</a>. A good book for beginning learning C++ is <a href=\"https://rads.stackoverflow.com/amzn/click/com/0201824701\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">C++ Primer</a>.</p>\n" }, { "answer_id": 162974, "author": "warren", "author_id": 4418, "author_profile": "https://Stackoverflow.com/users/4418", "pm_score": 4, "selected": false, "text": "<p>In large part, pointers are arrays (in C/C++) - they are addresses in memory, and can be accessed like an array if desired (in \"normal\" cases).</p>\n\n<p>Since they're the address of an item, they're small: they take up only the space of an address. Since they're small, sending them to a function is cheap. And then they allow that function to work on the actual item rather than a copy.</p>\n\n<p>If you want to do dynamic storage allocation (such as for a linked-list), you must use pointers, because they're the only way to grab memory from the heap.</p>\n" }, { "answer_id": 162975, "author": "nobody", "author_id": 19405, "author_profile": "https://Stackoverflow.com/users/19405", "pm_score": 3, "selected": false, "text": "<p>Because copying big objects all over the places wastes time and memory.</p>\n" }, { "answer_id": 162988, "author": "Kyle Cronin", "author_id": 658, "author_profile": "https://Stackoverflow.com/users/658", "pm_score": 6, "selected": false, "text": "<ol>\n<li>Pointers allow you to refer to the same space in memory from multiple locations. This means that you can update memory in one location and the change can be seen from another location in your program. You will also save space by being able to share components in your data structures.</li>\n<li>You should use pointers any place where you need to obtain and pass around the address to a specific spot in memory. You can also use pointers to navigate arrays:</li>\n<li>An array is a block of contiguous memory that has been allocated with a specific type. The name of the array contains the value of the starting spot of the array. When you add 1, that takes you to the second spot. This allows you to write loops that increment a pointer that slides down the array without having an explicit counter for use in accessing the array.</li>\n</ol>\n\n<p>Here is an example in C:</p>\n\n<pre><code>char hello[] = \"hello\";\n\nchar *p = hello;\n\nwhile (*p)\n{\n *p += 1; // increase the character by one\n\n p += 1; // move to the next spot\n}\n\nprintf(hello);\n</code></pre>\n\n<p>prints</p>\n\n<pre><code>ifmmp\n</code></pre>\n\n<p>because it takes the value for each character and increments it by one.</p>\n" }, { "answer_id": 163103, "author": "trshiv", "author_id": 21647, "author_profile": "https://Stackoverflow.com/users/21647", "pm_score": 6, "selected": false, "text": "<p>One reason to use pointers is so that a variable or an object can be modified in a called function.</p>\n\n<p>In C++ it is a better practice to use references than pointers. Though references are essentially pointers, C++ to some extent hides the fact and makes it seem as if you are passing by value. This makes it easy to change the way the calling function receives the value without having to modify the semantics of passing it.</p>\n\n<p>Consider the following examples:</p>\n\n<p>Using references:</p>\n\n<pre><code>public void doSomething()\n{\n int i = 10;\n doSomethingElse(i); // passes i by references since doSomethingElse() receives it\n // by reference, but the syntax makes it appear as if i is passed\n // by value\n}\n\npublic void doSomethingElse(int&amp; i) // receives i as a reference\n{\n cout &lt;&lt; i &lt;&lt; endl;\n}\n</code></pre>\n\n<p>Using pointers:</p>\n\n<pre><code>public void doSomething()\n{\n int i = 10;\n doSomethingElse(&amp;i);\n}\n\npublic void doSomethingElse(int* i)\n{\n cout &lt;&lt; *i &lt;&lt; endl;\n}\n</code></pre>\n" }, { "answer_id": 163112, "author": "Ash", "author_id": 5023, "author_profile": "https://Stackoverflow.com/users/5023", "pm_score": 3, "selected": false, "text": "<p>Pointers are important in many data structures whose design requires the ability to link or chain one \"node\" to another efficiently. You would not \"choose\" a pointer over say a normal data type like float, they simply have different purposes.</p>\n\n<p>Pointers are useful where you require high performance and/or compact memory footprint.</p>\n\n<p>The address of the first element in your array can be assigned to a pointer. This then allows you to access the underlying allocated bytes directly. The whole point of an array is to avoid you needing to do this though.</p>\n" }, { "answer_id": 163138, "author": "Dan Lenski", "author_id": 20789, "author_profile": "https://Stackoverflow.com/users/20789", "pm_score": 4, "selected": false, "text": "<p>Here's a slightly different, but insightful take on why many features of C make sense: <a href=\"http://steve.yegge.googlepages.com/tour-de-babel#C\" rel=\"noreferrer\">http://steve.yegge.googlepages.com/tour-de-babel#C</a></p>\n\n<p>Basically, the standard CPU architecture is a Von Neumann architecture, and it's tremendously useful to be able to refer to the location of a data item in memory, and do arithmetic with it, on such a machine. If you know any variant of assembly language, you will quickly see how crucial this is at the low level.</p>\n\n<p>C++ makes pointers a bit confusing, since it sometimes manages them for you and hides their effect in the form of \"references.\" If you use straight C, the need for pointers is much more obvious: there's no other way to do call-by-reference, it's the best way to store a string, it's the best way to iterate through an array, etc.</p>\n" }, { "answer_id": 163304, "author": "Zebra North", "author_id": 17440, "author_profile": "https://Stackoverflow.com/users/17440", "pm_score": 4, "selected": false, "text": "<p>One use of pointers (I won't mention things already covered in other people's posts) is to access memory that you haven't allocated. This isn't useful much for PC programming, but it's used in embedded programming to access memory mapped hardware devices.</p>\n\n<p>Back in the old days of DOS, you used to be able to access the video card's video memory directly by declaring a pointer to:</p>\n\n<pre><code>unsigned char *pVideoMemory = (unsigned char *)0xA0000000;\n</code></pre>\n\n<p>Many embedded devices still use this technique.</p>\n" }, { "answer_id": 163544, "author": "Tooony", "author_id": 23864, "author_profile": "https://Stackoverflow.com/users/23864", "pm_score": 8, "selected": false, "text": "<ul>\n<li>Why use pointers over normal variables? </li>\n</ul>\n\n<p>Short answer is: Don't. ;-) Pointers are to be used where you can't use anything else. It is either because the lack of appropriate functionality, missing data types or for pure perfomance. More below...</p>\n\n<ul>\n<li>When and where should I use pointers? </li>\n</ul>\n\n<p>Short answer here is: Where you cannot use anything else. In C you don't have any support for complex datatypes such as a string. There are also no way of passing a variable \"by reference\" to a function. That's where you have to use pointers. Also you can have them to point at virtually anything, linked lists, members of structs and so on. But let's not go into that here.</p>\n\n<ul>\n<li>How do you use pointers with arrays? </li>\n</ul>\n\n<p>With little effort and much confusion. ;-) If we talk about simple data types such as int and char there is little difference between an array and a pointer.\nThese declarations are very similar (but not the same - e.g., <code>sizeof</code> will return different values):</p>\n\n<pre><code>char* a = \"Hello\";\nchar a[] = \"Hello\";\n</code></pre>\n\n<p>You can reach any element in the array like this</p>\n\n<pre><code>printf(\"Second char is: %c\", a[1]);\n</code></pre>\n\n<p>Index 1 since the array starts with element 0. :-)</p>\n\n<p>Or you could equally do this</p>\n\n<pre><code>printf(\"Second char is: %c\", *(a+1));\n</code></pre>\n\n<p>The pointer operator (the *) is needed since we are telling printf that we want to print a character. Without the *, the character representation of the memory address itself would be printed. Now we are using the character itself instead. If we had used %s instead of %c, we would have asked printf to print the content of the memory address pointed to by 'a' plus one (in this example above), and we wouldn't have had to put the * in front:</p>\n\n<pre><code>printf(\"Second char is: %s\", (a+1)); /* WRONG */\n</code></pre>\n\n<p>But this would not have just printed the second character, but instead all characters in the next memory addresses, until a null character (\\0) were found. And this is where things start to get dangerous. What if you accidentally try and print a variable of the type integer instead of a char pointer with the %s formatter?</p>\n\n<pre><code>char* a = \"Hello\";\nint b = 120;\nprintf(\"Second char is: %s\", b);\n</code></pre>\n\n<p>This would print whatever is found on memory address 120 and go on printing until a null character was found. It is wrong and illegal to perform this printf statement, but it would probably work anyway, since a pointer actually is of the type int in many environments. Imagine the problems you might cause if you were to use sprintf() instead and assign this way too long \"char array\" to another variable, that only got a certain limited space allocated. You would most likely end up writing over something else in the memory and cause your program to crash (if you are lucky).</p>\n\n<p>Oh, and if you don't assign a string value to the char array / pointer when you declare it, you MUST allocate sufficient amount of memory to it before giving it a value. Using malloc, calloc or similar. This since you only declared one element in your array / one single memory address to point at. So here's a few examples:</p>\n\n<pre><code>char* x;\n/* Allocate 6 bytes of memory for me and point x to the first of them. */\nx = (char*) malloc(6);\nx[0] = 'H';\nx[1] = 'e';\nx[2] = 'l';\nx[3] = 'l';\nx[4] = 'o';\nx[5] = '\\0';\nprintf(\"String \\\"%s\\\" at address: %d\\n\", x, x);\n/* Delete the allocation (reservation) of the memory. */\n/* The char pointer x is still pointing to this address in memory though! */\nfree(x);\n/* Same as malloc but here the allocated space is filled with null characters!*/\nx = (char *) calloc(6, sizeof(x));\nx[0] = 'H';\nx[1] = 'e';\nx[2] = 'l';\nx[3] = 'l';\nx[4] = 'o';\nx[5] = '\\0';\nprintf(\"String \\\"%s\\\" at address: %d\\n\", x, x);\n/* And delete the allocation again... */\nfree(x);\n/* We can set the size at declaration time as well */\nchar xx[6];\nxx[0] = 'H';\nxx[1] = 'e';\nxx[2] = 'l';\nxx[3] = 'l';\nxx[4] = 'o';\nxx[5] = '\\0';\nprintf(\"String \\\"%s\\\" at address: %d\\n\", xx, xx);\n</code></pre>\n\n<p>Do note that you can still use the variable x after you have performed a free() of the allocated memory, but you do not know what is in there. Also do notice that the two printf() might give you different addresses, since there is no guarantee that the second allocation of memory is performed in the same space as the first one.</p>\n" }, { "answer_id": 163721, "author": "Marioh", "author_id": 24293, "author_profile": "https://Stackoverflow.com/users/24293", "pm_score": 2, "selected": false, "text": "<p>In java and C# all the object references are pointers, the thing with c++ is that you have more control on where you pointer points. Remember With great power comes grand responsibility.</p>\n" }, { "answer_id": 10379509, "author": "Jason", "author_id": 1365190, "author_profile": "https://Stackoverflow.com/users/1365190", "pm_score": 3, "selected": false, "text": "<p>One way to use pointers over variables is to eliminate duplicate memory required. For example, if you have some large complex object, you can use a pointer to point to that variable for each reference you make. With a variable, you need to duplicate the memory for each copy.</p>\n" }, { "answer_id": 10379758, "author": "Jim Michaels", "author_id": 591668, "author_profile": "https://Stackoverflow.com/users/591668", "pm_score": 2, "selected": false, "text": "<ul>\n<li>In some cases, function pointers are required to use functions that are in a shared library (.DLL or .so). This includes performing stuff across languages, where oftentimes a DLL interface is provided.</li>\n<li>Making compilers</li>\n<li>Making scientific calculators, where you have an array or vector or string map of function pointers?</li>\n<li>Trying to modify video memory directly - making your own graphics package</li>\n<li>Making an API!</li>\n<li>Data structures - node link pointers for special trees you are making</li>\n</ul>\n\n<p>There are Lots of reasons for pointers. Having C name mangling especially is important in DLLs if you want to maintain cross-language compatibility.</p>\n" }, { "answer_id": 11076615, "author": "Jeremy Hahn", "author_id": 1462662, "author_profile": "https://Stackoverflow.com/users/1462662", "pm_score": 3, "selected": false, "text": "<p>Here's my anwser, and I won't promse to be an expert, but I've found pointers to be great in one of my libraries I'm trying to write. In this library (It's a graphics API with OpenGL:-)) you can create a triangle with vertex objects passed into them. The draw method takes these triangle objects, and well.. draws them based on the vertex objects i created. Well, its ok. </p>\n\n<p>But, what if i change a vertex coordinate? Move it or something with moveX() in the vertex class? Well, ok, now i have to update the triangle, adding more methods and performance is being wasted because i have to update the triangle every time a vertex moves. Still not a big deal, but it's not that great. </p>\n\n<p>Now, what if i have a mesh with tons of vertices and tons of triangles, and the mesh is rotateing, and moveing, and such. I'll have to update every triangle that uses these vertices, and probably every triangle in the scene because i wouldn't know which ones use which vertices. That's hugely computer intensive, and if I have several meshes ontop of a landscape, oh god! I'm in trouble, because im updateing every triangle almost every frame because these vertices are changing al the time!</p>\n\n<p>With pointers, you don't have to update the triangles.</p>\n\n<p>If I had three *Vertex objects per triangle class, not only am i saving room because a zillion triangles don't have three vertex objects which are large themselves, but also these pointers will always point to the Vertices they are meant to, no matter how often the vertices change. Since the pointers still point to the same vertex, the triangles don't change, and the update process is easier to handle. If I confused you, I wouldn't doubt it, I don't pretend to be an expert, just throwing my two cents into the discussion. </p>\n" }, { "answer_id": 14916998, "author": "vaibhav kumar", "author_id": 1866301, "author_profile": "https://Stackoverflow.com/users/1866301", "pm_score": 3, "selected": false, "text": "<p>The need for pointers in C language is described <a href=\"http://duramecho.com/ComputerInformation/WhyCPointers.html\" rel=\"nofollow noreferrer\">here</a></p>\n<p>The basic idea is that many limitations in the language (like using arrays, strings and modifying multiple variables in functions) could be removed by manipulating with the memory location of the data. To overcome these limitations, pointers were introduced in C.</p>\n<p>Further, it is also seen that using pointers, you can run your code faster and save memory in cases where you are passing big data types (like a structure with many fields) to a function. Making a copy of such data types before passing would take time and would consume memory. This is another reason why programmers prefer pointers for big data types.</p>\n<p>PS: Please refer the <a href=\"http://duramecho.com/ComputerInformation/WhyCPointers.html\" rel=\"nofollow noreferrer\">link provided</a> for detailed explanation with sample code.</p>\n" }, { "answer_id": 16843974, "author": "Sildoreth", "author_id": 2065237, "author_profile": "https://Stackoverflow.com/users/2065237", "pm_score": 3, "selected": false, "text": "<p>In C++, if you want to use subtype <a href=\"http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming\" rel=\"nofollow noreferrer\">polymorphism</a>, you <strong><em>have</em></strong> to use pointers. See this post: <a href=\"https://stackoverflow.com/q/7223613/2065237\">C++ Polymorphism without pointers</a>.</p>\n\n<p>Really, when you think about it, this makes sense. When you use subtype polymorphism, ultimately, you don't know ahead of time which class's or subclass's implementation of the method will be invoked because you don't know what the actual class is.</p>\n\n<p>This idea of having a variable that holds an object of an unknown class is incompatible with C++'s default (non-pointer) mode of storing objects on the stack, where the amount of space allocated directly corresponds to the class. Note: if a class has 5 instance fields versus 3, more space will need to be allocated.</p>\n\n<p><hr />\nNote that if you are using '&amp;' to pass arguments by reference, indirection (i.e., pointers) is still involved behind the scenes. The '&amp;' is just syntactic sugar that (1) saves you the trouble of using pointer syntax and (2) allows the compiler to be more strict (such as prohibiting null pointers).</p>\n" }, { "answer_id": 16846043, "author": "Radu Chivu", "author_id": 358409, "author_profile": "https://Stackoverflow.com/users/358409", "pm_score": 2, "selected": false, "text": "<p>Regarding your second question, generally you don't need to use pointers while programming, however there is one exception to this and that is when you make a public API.</p>\n\n<p>The problem with C++ constructs that people generally use to replace pointers are very dependent on the toolset that you use which is fine when you have all the control you need over the source code, however if you compile a static library with visual studio 2008 for instance and try to use it in a visual studio 2010 you will get a ton of linker errors because the new project is linked with a newer version of STL which is not backwards compatible. Things get even nastier if you compile a DLL and give an import library that people use in a different toolset because in that case your program will crash sooner or later for no apparent reason. </p>\n\n<p>So for the purpose of moving large data sets from one library to another you could consider giving a pointer to an array to the function that is supposed to copy the data if you don't want to force others to use the same tools that you use. The good part about this is that it doesn't even have to be a C-style array, you can use a std::vector and give the pointer by giving the address of the first element &amp;vector[0] for instance, and use the std::vector to manage the array internally. </p>\n\n<p>Another good reason to use pointers in C++ again relates to libraries, consider having a dll that cannot be loaded when your program runs, so if you use an import library then the dependency isn't satisfied and the program crashes. This is the case for instance when you give a public api in a dll alongside your application and you want to access it from other applications. In this case in order to use the API you need to load the dll from its' location (usually it's in a registry key) and then you need to use a function pointer to be able to call functions inside the DLL. Sometimes the people that make the API are nice enough to give you a .h file that contain helper functions to automate this process and give you all the function pointers that you need, but if not you can use LoadLibrary and GetProcAddress on windows and dlopen and dlsym on unix to get them (considering that you know the entire signature of the function).</p>\n" }, { "answer_id": 16846059, "author": "Carl", "author_id": 13760, "author_profile": "https://Stackoverflow.com/users/13760", "pm_score": 5, "selected": false, "text": "<p>Let me try and answer this too. </p>\n\n<p>Pointers are similar to references. In other words, they're not copies, but rather a way to refer to the original value. </p>\n\n<p>Before anything else, one place where <strong>you will typically have to use pointers</strong> a lot is when you're dealing <strong>with embedded hardware</strong>. Maybe you need to toggle the state of a digital IO pin. Maybe you're processing an interrupt and need to store a value at a specific location. You get the picture. However, if you're not dealing with hardware directly and are just wondering about which types to use, read on.</p>\n\n<p>Why use pointers as opposed to normal variables? The answer becomes clearer when you're dealing with complex types, like classes, structures and arrays. If you were to use a normal variable, you might end up making a copy (compilers are smart enough to prevent this in some situations and C++11 helps too, but we'll stay away from that discussion for now). </p>\n\n<p>Now what happens if you want to modify the original value? You could use something like this:</p>\n\n<pre><code>MyType a; //let's ignore what MyType actually is right now.\na = modify(a); \n</code></pre>\n\n<p>That will work just fine and if you don't know exactly why you're using pointers, you shouldn't use them. Beware of the \"they're probably faster\" reason. Run your own tests and if they actually are faster, then use them.</p>\n\n<p>However, let's say you're solving a problem where you need to allocate memory. When you allocate memory, you need to deallocate it. The memory allocation may or may not be successful. This is where <strong>pointers</strong> come in useful - they <strong>allow you to test for the existence of the object</strong> you've allocated and they allow you to access the object the memory was allocated for by de-referencing the pointer.</p>\n\n<pre><code>MyType *p = NULL; //empty pointer\nif(p)\n{\n //we never reach here, because the pointer points to nothing\n}\n//now, let's allocate some memory\np = new MyType[50000];\nif(p) //if the memory was allocated, this test will pass\n{\n //we can do something with our allocated array\n for(size_t i=0; i!=50000; i++)\n {\n MyType &amp;v = *(p+i); //get a reference to the ith object\n //do something with it\n //...\n }\n delete[] p; //we're done. de-allocate the memory\n}\n</code></pre>\n\n<p>This is the key to why you would use pointers - <strong>references assume the element you're referencing exists already</strong>. A pointer does not. </p>\n\n<p>The other reason why you would use pointers (or at least end up having to deal with them) is because they're a data type that existed before references. Therefore, if you end up using libraries to do the things that you know they're better at, you will find that a lot of these libraries use pointers all over the place, simply because of how long they've been around (a lot of them were written before C++). </p>\n\n<p>If you didn't use any libraries, you could design your code in such a way that you could stay away from pointers, but given that pointers are one of the basic types of the language, the faster you get comfortable using them, the more portable your C++ skills would be.</p>\n\n<p>From a maintainability point of view, I should also mention that when you do use pointers, you either have to test for their validity and handle the case when they're not valid, or, just assume they are valid and accept the fact that your program will crash or worse WHEN that assumption is broken. Put another way, <strong>your choice with pointers is to either introduce code complexity or more maintenance effort when something breaks</strong> and you're trying to track down a bug that belongs to a whole class of errors that pointers introduce, like memory corruption. </p>\n\n<p>So if you control all of your code, stay away from pointers and instead use references, keeping them const when you can. This will force you to think about the life times of your objects and will end up keeping your code easier to understand. </p>\n\n<p>Just remember this difference: <strong>A reference is essentially a valid pointer. A pointer is not always valid.</strong></p>\n\n<p>So am I saying that its impossible to create an invalid reference? No. Its totally possible, because C++ lets you do almost anything. It's just harder to do unintentionally and you will be amazed at how many bugs are unintentional :)</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I know this is a really basic question, but I've just started with some basic C++ programming after coding a few projects with high-level languages. Basically I have three questions: 1. Why use pointers over normal variables? 2. When and where should I use pointers? 3. How do you use pointers with arrays?
* Why use pointers over normal variables? Short answer is: Don't. ;-) Pointers are to be used where you can't use anything else. It is either because the lack of appropriate functionality, missing data types or for pure perfomance. More below... * When and where should I use pointers? Short answer here is: Where you cannot use anything else. In C you don't have any support for complex datatypes such as a string. There are also no way of passing a variable "by reference" to a function. That's where you have to use pointers. Also you can have them to point at virtually anything, linked lists, members of structs and so on. But let's not go into that here. * How do you use pointers with arrays? With little effort and much confusion. ;-) If we talk about simple data types such as int and char there is little difference between an array and a pointer. These declarations are very similar (but not the same - e.g., `sizeof` will return different values): ``` char* a = "Hello"; char a[] = "Hello"; ``` You can reach any element in the array like this ``` printf("Second char is: %c", a[1]); ``` Index 1 since the array starts with element 0. :-) Or you could equally do this ``` printf("Second char is: %c", *(a+1)); ``` The pointer operator (the \*) is needed since we are telling printf that we want to print a character. Without the \*, the character representation of the memory address itself would be printed. Now we are using the character itself instead. If we had used %s instead of %c, we would have asked printf to print the content of the memory address pointed to by 'a' plus one (in this example above), and we wouldn't have had to put the \* in front: ``` printf("Second char is: %s", (a+1)); /* WRONG */ ``` But this would not have just printed the second character, but instead all characters in the next memory addresses, until a null character (\0) were found. And this is where things start to get dangerous. What if you accidentally try and print a variable of the type integer instead of a char pointer with the %s formatter? ``` char* a = "Hello"; int b = 120; printf("Second char is: %s", b); ``` This would print whatever is found on memory address 120 and go on printing until a null character was found. It is wrong and illegal to perform this printf statement, but it would probably work anyway, since a pointer actually is of the type int in many environments. Imagine the problems you might cause if you were to use sprintf() instead and assign this way too long "char array" to another variable, that only got a certain limited space allocated. You would most likely end up writing over something else in the memory and cause your program to crash (if you are lucky). Oh, and if you don't assign a string value to the char array / pointer when you declare it, you MUST allocate sufficient amount of memory to it before giving it a value. Using malloc, calloc or similar. This since you only declared one element in your array / one single memory address to point at. So here's a few examples: ``` char* x; /* Allocate 6 bytes of memory for me and point x to the first of them. */ x = (char*) malloc(6); x[0] = 'H'; x[1] = 'e'; x[2] = 'l'; x[3] = 'l'; x[4] = 'o'; x[5] = '\0'; printf("String \"%s\" at address: %d\n", x, x); /* Delete the allocation (reservation) of the memory. */ /* The char pointer x is still pointing to this address in memory though! */ free(x); /* Same as malloc but here the allocated space is filled with null characters!*/ x = (char *) calloc(6, sizeof(x)); x[0] = 'H'; x[1] = 'e'; x[2] = 'l'; x[3] = 'l'; x[4] = 'o'; x[5] = '\0'; printf("String \"%s\" at address: %d\n", x, x); /* And delete the allocation again... */ free(x); /* We can set the size at declaration time as well */ char xx[6]; xx[0] = 'H'; xx[1] = 'e'; xx[2] = 'l'; xx[3] = 'l'; xx[4] = 'o'; xx[5] = '\0'; printf("String \"%s\" at address: %d\n", xx, xx); ``` Do note that you can still use the variable x after you have performed a free() of the allocated memory, but you do not know what is in there. Also do notice that the two printf() might give you different addresses, since there is no guarantee that the second allocation of memory is performed in the same space as the first one.
162,960
<p>So, I've been living with my cvs repositories for some time. Though there is a thing I miss - if i rename a file that is already in repository, I need to delete the one with old name from there and add the new one. Hence, I loose all my change-history. And sometimes there's a need to rename a file in alredy existing project.</p> <p>From what I saw, cvs/svn can't handle something like this, or am I wrong? If not, what other source control system would you recommend, that allows the renaming of files? </p>
[ { "answer_id": 162970, "author": "Matthias Winkelmann", "author_id": 4494, "author_profile": "https://Stackoverflow.com/users/4494", "pm_score": 5, "selected": true, "text": "<p>Subversion can do this, but you have to do it with </p>\n\n<pre><code>svn move &lt;oldfile&gt; &lt;newfile&gt;\n</code></pre>\n\n<p>Edit: And in this decade, we do <code>git mv &lt;oldfile&gt; &lt;newfile&gt;</code>, or just use <code>mv</code> and git usually figures it out on its own.</p>\n" }, { "answer_id": 162977, "author": "Carlton Jenke", "author_id": 1215, "author_profile": "https://Stackoverflow.com/users/1215", "pm_score": -1, "selected": false, "text": "<p>Subversion has rename capability.</p>\n" }, { "answer_id": 162996, "author": "Matt Dillard", "author_id": 863, "author_profile": "https://Stackoverflow.com/users/863", "pm_score": 2, "selected": false, "text": "<p>Pretty much any modern version control system will allow this (Subversion, Perforce, Vault, git, Mercurial, TFS, etc.).</p>\n\n<p>The only ones I can think of that won't (or that have major caveats) are CVS and VSS.</p>\n" }, { "answer_id": 162998, "author": "ColinYounger", "author_id": 1223, "author_profile": "https://Stackoverflow.com/users/1223", "pm_score": 3, "selected": false, "text": "<p>The <a href=\"http://www.cvsnt.org/manual/html/Moving-files.html\" rel=\"nofollow noreferrer\">online CVS manual</a> has some detail on how to do this:</p>\n\n<blockquote>\n <p>The normal way to move a file is to issue a cvs rename command.</p>\n\n<pre><code>$ cvs rename old new\n$ cvs commit -m \"Renamed old to new\"\n</code></pre>\n \n <p>This is the simplest way to move a file. It is not error prone, and it preserves the history of what was done. CVSNT clients can retrieve the original name by checking out an older version of the repository.</p>\n</blockquote>\n\n<p>This feature is only supported on CVSNT servers 2.0.55 and later.</p>\n" }, { "answer_id": 163001, "author": "bart", "author_id": 19966, "author_profile": "https://Stackoverflow.com/users/19966", "pm_score": 2, "selected": false, "text": "<p>In svn, use svn mv.</p>\n\n<p>See also: <a href=\"http://subversion.tigris.org/faq.html#case-change\" rel=\"nofollow noreferrer\">http://subversion.tigris.org/faq.html#case-change</a> in the FAQ.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162960", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4172/" ]
So, I've been living with my cvs repositories for some time. Though there is a thing I miss - if i rename a file that is already in repository, I need to delete the one with old name from there and add the new one. Hence, I loose all my change-history. And sometimes there's a need to rename a file in alredy existing project. From what I saw, cvs/svn can't handle something like this, or am I wrong? If not, what other source control system would you recommend, that allows the renaming of files?
Subversion can do this, but you have to do it with ``` svn move <oldfile> <newfile> ``` Edit: And in this decade, we do `git mv <oldfile> <newfile>`, or just use `mv` and git usually figures it out on its own.
162,986
<p>I have a class that looks like this</p> <pre><code>public class SomeClass { public SomeChildClass[] childArray; } </code></pre> <p>which will output XML from the XMLSerializer like this:</p> <pre><code>&lt;SomeClass&gt; &lt;SomeChildClass&gt; ... &lt;/SomeChildClass&gt; &lt;SomeChildClass&gt; ... &lt;/SomeChildClass&gt; &lt;/SomeClass&gt; </code></pre> <p>But I want the XML to look like this:</p> <pre><code>&lt;SomeClass&gt; &lt;SomeChildClass index=1&gt; ... &lt;/SomeChildClass&gt; &lt;SomeChildClass index=2&gt; ... &lt;/SomeChildClass&gt; &lt;/SomeClass&gt; </code></pre> <p>Where the index attribute is equal to the items position in the array.</p> <p>I could add an index property to SomeChildClass with the "XMLAttribute" attribute but then I would have to remember to loop through the array and set that value before I serialize my object.</p> <p>Is there some attribute i can add or some other way to automatically generate the index attribute for me?</p>
[ { "answer_id": 163047, "author": "Craig Eddy", "author_id": 5557, "author_profile": "https://Stackoverflow.com/users/5557", "pm_score": 0, "selected": false, "text": "<p>You may need to look into implementing System.Xml.Serialization.IXmlSerializable to accomplish this.</p>\n" }, { "answer_id": 163076, "author": "Sunny Milenov", "author_id": 8220, "author_profile": "https://Stackoverflow.com/users/8220", "pm_score": 0, "selected": false, "text": "<p>You can check XmlAttributeOverrides Class.</p>\n" }, { "answer_id": 163134, "author": "Micah", "author_id": 17744, "author_profile": "https://Stackoverflow.com/users/17744", "pm_score": 3, "selected": true, "text": "<p>The best approach would be to do what you said and add a property to the \"SomeChildClass\" like this</p>\n\n<pre><code>[XmlAttribute(\"Index\")]\npublic int Order\n{ { get; set; } }\n</code></pre>\n\n<p>Then however you are adding these items to your array, make sure that this property get's set. Then when you serialize....Presto!</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162986", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3543/" ]
I have a class that looks like this ``` public class SomeClass { public SomeChildClass[] childArray; } ``` which will output XML from the XMLSerializer like this: ``` <SomeClass> <SomeChildClass> ... </SomeChildClass> <SomeChildClass> ... </SomeChildClass> </SomeClass> ``` But I want the XML to look like this: ``` <SomeClass> <SomeChildClass index=1> ... </SomeChildClass> <SomeChildClass index=2> ... </SomeChildClass> </SomeClass> ``` Where the index attribute is equal to the items position in the array. I could add an index property to SomeChildClass with the "XMLAttribute" attribute but then I would have to remember to loop through the array and set that value before I serialize my object. Is there some attribute i can add or some other way to automatically generate the index attribute for me?
The best approach would be to do what you said and add a property to the "SomeChildClass" like this ``` [XmlAttribute("Index")] public int Order { { get; set; } } ``` Then however you are adding these items to your array, make sure that this property get's set. Then when you serialize....Presto!
162,989
<p>How does one dynamically load a new report from an embedded resource? I have created a reporting project that contains a report as an embedded resource. I added a second report file and use the following code to switch reports:</p> <pre><code>this.reportViewer1.LocalReport.ReportEmbeddedResource = "ReportsApplication2.Report2.rdlc"; this.reportViewer1.LocalReport.Refresh(); this.reportViewer1.RefreshReport(); </code></pre> <p>When this code executes, the original report remains visible in the report viewer.</p> <p>I have also tried using</p> <pre><code>LocalReport.LoadReportDefinition </code></pre> <p>but had the same result.</p>
[ { "answer_id": 167132, "author": "Craig Eddy", "author_id": 5557, "author_profile": "https://Stackoverflow.com/users/5557", "pm_score": 4, "selected": true, "text": "<p>The answer: you have to call </p>\n\n<pre><code>&lt;ReportViewer&gt;.Reset();\n</code></pre>\n\n<p>prior to changing the value of ReportEmbeddedResource or calling LoadReportDefinition.</p>\n\n<p>After you do so, you'll also have to call </p>\n\n<pre><code>&lt;ReportViewer&gt;.LocalReport.DataSources.Add( ... );\n</code></pre>\n\n<p>to re-establish the data sources.</p>\n" }, { "answer_id": 71563048, "author": "Mousa Abdulmaxod", "author_id": 11836637, "author_profile": "https://Stackoverflow.com/users/11836637", "pm_score": 0, "selected": false, "text": "<p>a better way to reference your reports is by using the default value of ReportEmbeddedResource, <strong>don't hard code</strong> it just change the name of the report.</p>\n<pre><code>//choose which report to load\n string reportEmbeddedResource = this.orderReportViewer.LocalReport.ReportEmbeddedResource;\n //remove the extention .rdlc\n reportEmbeddedResource = reportEmbeddedResource.Remove(reportEmbeddedResource.LastIndexOf('.'));\n //remove name of current report ex: .invoice.rdlc\n reportEmbeddedResource = reportEmbeddedResource.Remove(reportEmbeddedResource.LastIndexOf('.'));\n //clear current reportEmbeddedResource\n this.orderReportViewer.Reset();\n if (_retailReceip)\n {\n this.orderReportViewer.LocalReport.ReportEmbeddedResource = reportEmbeddedResource + &quot;.PrintReceipt.rdlc&quot;;\n }\n else\n {\n this.orderReportViewer.LocalReport.ReportEmbeddedResource = reportEmbeddedResource + &quot;.PrintOrder.rdlc&quot;;\n }\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162989", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5557/" ]
How does one dynamically load a new report from an embedded resource? I have created a reporting project that contains a report as an embedded resource. I added a second report file and use the following code to switch reports: ``` this.reportViewer1.LocalReport.ReportEmbeddedResource = "ReportsApplication2.Report2.rdlc"; this.reportViewer1.LocalReport.Refresh(); this.reportViewer1.RefreshReport(); ``` When this code executes, the original report remains visible in the report viewer. I have also tried using ``` LocalReport.LoadReportDefinition ``` but had the same result.
The answer: you have to call ``` <ReportViewer>.Reset(); ``` prior to changing the value of ReportEmbeddedResource or calling LoadReportDefinition. After you do so, you'll also have to call ``` <ReportViewer>.LocalReport.DataSources.Add( ... ); ``` to re-establish the data sources.
162,993
<p>I am creating a decoupled WMI provider in a class library. Everything I have read points towards including something along these lines:</p> <pre><code>[System.ComponentModel.RunInstaller(true)] public class MyApplicationManagementInstaller : DefaultManagementInstaller { } </code></pre> <p>I gather the purpose of this installation is because the Windows WMI infrastructure needs to be aware of the structure of my WMI provider before it is used.</p> <p>My question is - when is this "installer" ran? MSDN says that the installer will be invoked "during installation of an assembly", but I am not sure what that means or when it would happen in the context of a class library containing a WMI provider.</p> <p>I was under the impression that this was an automated replacement for manually running <strong>InstallUtil.exe</strong> against the assembly containing the WMI provider, but changes I make to the provider are not recognised by the Windows WMI infrastructure unless I manually run InstallUtil from the command prompt. I can do this on my own machine during development, but if an application using the provider is deployed to other machines - what then?</p> <p>It seems that this RunInstaller / DefaultManagementInstaller combination is not working properly - correct?</p>
[ { "answer_id": 164690, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": true, "text": "<p>As I understand, DefaultManagementInstaller is ran by installutil.exe - if you don't include it, the class is not installed in WMI. Maybe it is possible to create a 'setup project' or 'installer project' that runs it, but I'm not sure because I don't use Visual Studio.</p>\n\n<p>[edit]</p>\n\n<p>for remote instalation, an option could be to use Installutil with /MOF option to generate MOF for the assembly and use mofcomp to move it to WMI.</p>\n" }, { "answer_id": 171146, "author": "xyz", "author_id": 82, "author_profile": "https://Stackoverflow.com/users/82", "pm_score": 0, "selected": false, "text": "<p>Thanks Uros. It does look like all that RunInstaller and DefaultManagementInstaller do is enable you to run InstallUtil successfully against the assembly. This is strange because I'm almost certain that I didn't know about InstallUtil at the point where I'd compiled and played with my first WMI provider.</p>\n\n<p>I will look in to using the MOF file and for my own use I can just run the InstallUtil command line as a post build event in VS.</p>\n" }, { "answer_id": 373748, "author": "David Gardiner", "author_id": 25702, "author_profile": "https://Stackoverflow.com/users/25702", "pm_score": 1, "selected": false, "text": "<p>I use something like this to call InstallUtil programmatically:</p>\n\n<pre><code> public static void Run( Type type )\n {\n // Register WMI stuff\n var installArgs = new[]\n {\n string.Format( \"//logfile={0}\", @\"c:\\Temp\\sample.InstallLog\" ), \"//LogToConsole=false\", \"//ShowCallStack\",\n type.Assembly.Location,\n };\n\n ManagedInstallerClass.InstallHelper( installArgs );\n }\n</code></pre>\n\n<p>Call this from your Main() method.</p>\n\n<p>-dave</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/162993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/82/" ]
I am creating a decoupled WMI provider in a class library. Everything I have read points towards including something along these lines: ``` [System.ComponentModel.RunInstaller(true)] public class MyApplicationManagementInstaller : DefaultManagementInstaller { } ``` I gather the purpose of this installation is because the Windows WMI infrastructure needs to be aware of the structure of my WMI provider before it is used. My question is - when is this "installer" ran? MSDN says that the installer will be invoked "during installation of an assembly", but I am not sure what that means or when it would happen in the context of a class library containing a WMI provider. I was under the impression that this was an automated replacement for manually running **InstallUtil.exe** against the assembly containing the WMI provider, but changes I make to the provider are not recognised by the Windows WMI infrastructure unless I manually run InstallUtil from the command prompt. I can do this on my own machine during development, but if an application using the provider is deployed to other machines - what then? It seems that this RunInstaller / DefaultManagementInstaller combination is not working properly - correct?
As I understand, DefaultManagementInstaller is ran by installutil.exe - if you don't include it, the class is not installed in WMI. Maybe it is possible to create a 'setup project' or 'installer project' that runs it, but I'm not sure because I don't use Visual Studio. [edit] for remote instalation, an option could be to use Installutil with /MOF option to generate MOF for the assembly and use mofcomp to move it to WMI.
163,004
<p>Say I have two tables I want to join. Categories:</p> <pre><code>id name ---------- 1 Cars 2 Games 3 Pencils </code></pre> <p>And items:</p> <pre><code>id categoryid itemname --------------------------- 1 1 Ford 2 1 BMW 3 1 VW 4 2 Tetris 5 2 Pong 6 3 Foobar Pencil Factory </code></pre> <p>I want a query that returns the category and the first (and only the first) itemname:</p> <pre><code>category.id category.name item.id item.itemname ------------------------------------------------- 1 Cars 1 Ford 2 Games 4 Tetris 3 Pencils 6 Foobar Pencil Factory </code></pre> <p>And is there a way I could get random results like:</p> <pre><code>category.id category.name item.id item.itemname ------------------------------------------------- 1 Cars 3 VW 2 Games 5 Pong 3 Pencils 6 Foobar Pencil Factory </code></pre> <p>Thanks!</p>
[ { "answer_id": 163051, "author": "GSerg", "author_id": 11683, "author_profile": "https://Stackoverflow.com/users/11683", "pm_score": 0, "selected": false, "text": "<p>Mysql lets you to have columns not included in grouping or aggregate, in which case they've got random values:</p>\n\n<pre><code> select category.id, category.name, itemid, itemname\n inner join \n (select item.categoryid, item.id as itemid, item.name as itemname\n from item group by categoryid)\n on category.id = categoryid\n</code></pre>\n\n<p>Or, for minimums,</p>\n\n<pre><code>select category.id, category.name, itemid, itemname\ninner join \n (select item.categoryid, min(item.id) as itemid, item.name as itemname\n from items\n group by item.categoryid)\non category.id = categoryid\n</code></pre>\n" }, { "answer_id": 163087, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": true, "text": "<p>Just done a quick test. This seems to work:</p>\n\n<pre><code>mysql&gt; select * from categories c, items i\n -&gt; where i.categoryid = c.id\n -&gt; group by c.id;\n+------+---------+------+------------+----------------+\n| id | name | id | categoryid | name |\n+------+---------+------+------------+----------------+\n| 1 | Cars | 1 | 1 | Ford |\n| 2 | Games | 4 | 2 | Tetris |\n| 3 | Pencils | 6 | 3 | Pencil Factory |\n+------+---------+------+------------+----------------+\n3 rows in set (0.00 sec)\n</code></pre>\n\n<p>I think this would fulfil your first question. Not sure about the second one - I think that needs an inner query with order by random() or something like that!</p>\n" }, { "answer_id": 222707, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Mysql does let include non aggregate columns and there is no guarantee of determinism, but in my experience I nearly always get the first values. </p>\n\n<p>So usually (but not guaranteed) this will give you the first</p>\n\n<pre><code>select * \nfrom categories c, items i\nwhere i.categoryid = c.id\ngroup by c.id;\n</code></pre>\n\n<p>If you want guaranteed you will need to do something like</p>\n\n<pre><code>select categories.id, categories.name, items.id, items.name\nfrom categories inner join\n items on items.categoryid = categories.id and \n items.id = (select min(items2.id) from items as items2 where items2.categoryid = category.id)\n</code></pre>\n\n<p>If you want random answers you will have to change the subquery a little bit</p>\n\n<pre><code> select categories.id, categories.name, items.id, items.name\n from categories inner join\n items on items.categoryid = categories.id and \n items.id = (select items2.id from items as items2 where items2.categoryid = category.id order by rand() limit 1)\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15214/" ]
Say I have two tables I want to join. Categories: ``` id name ---------- 1 Cars 2 Games 3 Pencils ``` And items: ``` id categoryid itemname --------------------------- 1 1 Ford 2 1 BMW 3 1 VW 4 2 Tetris 5 2 Pong 6 3 Foobar Pencil Factory ``` I want a query that returns the category and the first (and only the first) itemname: ``` category.id category.name item.id item.itemname ------------------------------------------------- 1 Cars 1 Ford 2 Games 4 Tetris 3 Pencils 6 Foobar Pencil Factory ``` And is there a way I could get random results like: ``` category.id category.name item.id item.itemname ------------------------------------------------- 1 Cars 3 VW 2 Games 5 Pong 3 Pencils 6 Foobar Pencil Factory ``` Thanks!
Just done a quick test. This seems to work: ``` mysql> select * from categories c, items i -> where i.categoryid = c.id -> group by c.id; +------+---------+------+------------+----------------+ | id | name | id | categoryid | name | +------+---------+------+------------+----------------+ | 1 | Cars | 1 | 1 | Ford | | 2 | Games | 4 | 2 | Tetris | | 3 | Pencils | 6 | 3 | Pencil Factory | +------+---------+------+------------+----------------+ 3 rows in set (0.00 sec) ``` I think this would fulfil your first question. Not sure about the second one - I think that needs an inner query with order by random() or something like that!
163,009
<p>If I open a file using urllib2, like so:</p> <pre><code>remotefile = urllib2.urlopen('http://example.com/somefile.zip') </code></pre> <p>Is there an easy way to get the file name other then parsing the original URL?</p> <p>EDIT: changed openfile to urlopen... not sure how that happened.</p> <p>EDIT2: I ended up using:</p> <pre><code>filename = url.split('/')[-1].split('#')[0].split('?')[0] </code></pre> <p>Unless I'm mistaken, this should strip out all potential queries as well.</p>
[ { "answer_id": 163093, "author": "Dan Lenski", "author_id": 20789, "author_profile": "https://Stackoverflow.com/users/20789", "pm_score": 2, "selected": false, "text": "<p>Do you mean <code>urllib2.urlopen</code>? There is no function called <code>openfile</code> in the <code>urllib2</code> module.</p>\n\n<p>Anyway, use the <code>urllib2.urlparse</code> functions:</p>\n\n<pre><code>&gt;&gt;&gt; from urllib2 import urlparse\n&gt;&gt;&gt; print urlparse.urlsplit('http://example.com/somefile.zip')\n('http', 'example.com', '/somefile.zip', '', '')\n</code></pre>\n\n<p>Voila.</p>\n" }, { "answer_id": 163094, "author": "Rafał Dowgird", "author_id": 12166, "author_profile": "https://Stackoverflow.com/users/12166", "pm_score": 3, "selected": false, "text": "<p>I think that \"the file name\" isn't a very well defined concept when it comes to http transfers. The server might (but is not required to) provide one as \"content-disposition\" header, you can try to get that with <code>remotefile.headers['Content-Disposition']</code>. If this fails, you probably have to parse the URI yourself.</p>\n" }, { "answer_id": 163095, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 7, "selected": true, "text": "<p>Did you mean <a href=\"http://www.python.org/doc/2.5.2/lib/module-urllib2.html#l2h-3928\" rel=\"noreferrer\">urllib2.urlopen</a>?</p>\n\n<p>You could potentially lift the <em>intended</em> filename <em>if</em> the server was sending a Content-Disposition header by checking <code>remotefile.info()['Content-Disposition']</code>, but as it is I think you'll just have to parse the url.</p>\n\n<p>You could use <code>urlparse.urlsplit</code>, but if you have any URLs like at the second example, you'll end up having to pull the file name out yourself anyway:</p>\n\n<pre><code>&gt;&gt;&gt; urlparse.urlsplit('http://example.com/somefile.zip')\n('http', 'example.com', '/somefile.zip', '', '')\n&gt;&gt;&gt; urlparse.urlsplit('http://example.com/somedir/somefile.zip')\n('http', 'example.com', '/somedir/somefile.zip', '', '')\n</code></pre>\n\n<p>Might as well just do this:</p>\n\n<pre><code>&gt;&gt;&gt; 'http://example.com/somefile.zip'.split('/')[-1]\n'somefile.zip'\n&gt;&gt;&gt; 'http://example.com/somedir/somefile.zip'.split('/')[-1]\n'somefile.zip'\n</code></pre>\n" }, { "answer_id": 163107, "author": "miracle2k", "author_id": 15677, "author_profile": "https://Stackoverflow.com/users/15677", "pm_score": 1, "selected": false, "text": "<p>I guess it depends what you mean by parsing. There is no way to get the filename without parsing the URL, i.e. the remote server doesn't give you a filename. However, you don't have to do much yourself, there's the <code>urlparse</code> module:</p>\n\n<pre><code>In [9]: urlparse.urlparse('http://example.com/somefile.zip')\nOut[9]: ('http', 'example.com', '/somefile.zip', '', '', '')\n</code></pre>\n" }, { "answer_id": 163108, "author": "user15453", "author_id": 15453, "author_profile": "https://Stackoverflow.com/users/15453", "pm_score": 0, "selected": false, "text": "<pre><code>import os,urllib2\nresp = urllib2.urlopen('http://www.example.com/index.html')\nmy_url = resp.geturl()\n\nos.path.split(my_url)[1]\n\n# 'index.html'\n</code></pre>\n\n<p>This is not openfile, but maybe still helps :)</p>\n" }, { "answer_id": 163111, "author": "Corey Goldberg", "author_id": 16148, "author_profile": "https://Stackoverflow.com/users/16148", "pm_score": 1, "selected": false, "text": "<p>not that I know of.</p>\n\n<p>but you can parse it easy enough like this:</p>\n\n<p><code><pre>\n<code>url = 'http://example.com/somefile.zip'\n</code>print url.split('/')[-1]\n</pre></code></p>\n" }, { "answer_id": 163202, "author": "Jay", "author_id": 20840, "author_profile": "https://Stackoverflow.com/users/20840", "pm_score": 4, "selected": false, "text": "<p>If you only want the file name itself, assuming that there's no query variables at the end like <a href=\"http://example.com/somedir/somefile.zip?foo=bar\" rel=\"noreferrer\">http://example.com/somedir/somefile.zip?foo=bar</a> then you can use os.path.basename for this: </p>\n\n<pre><code>[user@host]$ python\nPython 2.5.1 (r251:54869, Apr 18 2007, 22:08:04) \nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n&gt;&gt;&gt; import os\n&gt;&gt;&gt; os.path.basename(\"http://example.com/somefile.zip\")\n'somefile.zip'\n&gt;&gt;&gt; os.path.basename(\"http://example.com/somedir/somefile.zip\")\n'somefile.zip'\n&gt;&gt;&gt; os.path.basename(\"http://example.com/somedir/somefile.zip?foo=bar\")\n'somefile.zip?foo=bar'\n</code></pre>\n\n<p>Some other posters mentioned using urlparse, which will work, but you'd still need to strip the leading directory from the file name. If you use os.path.basename() then you don't have to worry about that, since it returns only the final part of the URL or file path.</p>\n" }, { "answer_id": 15733928, "author": "Filipe Correia", "author_id": 684253, "author_profile": "https://Stackoverflow.com/users/684253", "pm_score": 2, "selected": false, "text": "<p>Using <code>urlsplit</code> is the safest option:</p>\n\n<pre><code>url = 'http://example.com/somefile.zip'\nurlparse.urlsplit(url).path.split('/')[-1]\n</code></pre>\n" }, { "answer_id": 22053032, "author": "DoomedRaven", "author_id": 1294762, "author_profile": "https://Stackoverflow.com/users/1294762", "pm_score": 0, "selected": false, "text": "<p>using requests, but you can do it easy with urllib(2)</p>\n\n<pre><code>import requests\nfrom urllib import unquote\nfrom urlparse import urlparse\n\nsample = requests.get(url)\n\nif sample.status_code == 200:\n #has_key not work here, and this help avoid problem with names\n\n if filename == False:\n\n if 'content-disposition' in sample.headers.keys():\n filename = sample.headers['content-disposition'].split('filename=')[-1].replace('\"','').replace(';','')\n\n else:\n\n filename = urlparse(sample.url).query.split('/')[-1].split('=')[-1].split('&amp;')[-1]\n\n if not filename:\n\n if url.split('/')[-1] != '':\n filename = sample.url.split('/')[-1].split('=')[-1].split('&amp;')[-1]\n filename = unquote(filename)\n</code></pre>\n" }, { "answer_id": 29173617, "author": "TMF Wolfman", "author_id": 4695284, "author_profile": "https://Stackoverflow.com/users/4695284", "pm_score": 3, "selected": false, "text": "<p>Just saw this I normally do..</p>\n\n<pre><code>filename = url.split(\"?\")[0].split(\"/\")[-1]\n</code></pre>\n" }, { "answer_id": 30160719, "author": "Régis B.", "author_id": 356528, "author_profile": "https://Stackoverflow.com/users/356528", "pm_score": 2, "selected": false, "text": "<p>The <code>os.path.basename</code> function works not only for file paths, but also for urls, so you don't have to manually parse the URL yourself. Also, it's important to note that you should use <code>result.url</code> instead of the original url in order to follow redirect responses:</p>\n\n<pre><code>import os\nimport urllib2\nresult = urllib2.urlopen(url)\nreal_url = urllib2.urlparse.urlparse(result.url)\nfilename = os.path.basename(real_url.path)\n</code></pre>\n" }, { "answer_id": 32512647, "author": "Vovan Kuznetsov", "author_id": 4619036, "author_profile": "https://Stackoverflow.com/users/4619036", "pm_score": 0, "selected": false, "text": "<p>You probably can use simple regular expression here. Something like:</p>\n\n<pre><code>In [26]: import re\nIn [27]: pat = re.compile('.+[\\/\\?#=]([\\w-]+\\.[\\w-]+(?:\\.[\\w-]+)?$)')\nIn [28]: test_set \n\n['http://www.google.com/a341.tar.gz',\n 'http://www.google.com/a341.gz',\n 'http://www.google.com/asdasd/aadssd.gz',\n 'http://www.google.com/asdasd?aadssd.gz',\n 'http://www.google.com/asdasd#blah.gz',\n 'http://www.google.com/asdasd?filename=xxxbl.gz']\n\nIn [30]: for url in test_set:\n ....: match = pat.match(url)\n ....: if match and match.groups():\n ....: print(match.groups()[0])\n ....: \n\na341.tar.gz\na341.gz\naadssd.gz\naadssd.gz\nblah.gz\nxxxbl.gz\n</code></pre>\n" }, { "answer_id": 36557581, "author": "Adam Nelson", "author_id": 26235, "author_profile": "https://Stackoverflow.com/users/26235", "pm_score": 0, "selected": false, "text": "<p>Using <a href=\"https://docs.python.org/3/library/pathlib.html#pathlib.PurePosixPath\" rel=\"nofollow\">PurePosixPath</a> which is not operating system—dependent and handles urls gracefully is the pythonic solution:</p>\n\n<pre><code>&gt;&gt;&gt; from pathlib import PurePosixPath\n&gt;&gt;&gt; path = PurePosixPath('http://example.com/somefile.zip')\n&gt;&gt;&gt; path.name\n'somefile.zip'\n&gt;&gt;&gt; path = PurePosixPath('http://example.com/nested/somefile.zip')\n&gt;&gt;&gt; path.name\n'somefile.zip'\n</code></pre>\n\n<p>Notice how there is no network traffic here or anything (i.e. those urls don't go anywhere) - just using standard parsing rules.</p>\n" }, { "answer_id": 36917997, "author": "Yth", "author_id": 6077892, "author_profile": "https://Stackoverflow.com/users/6077892", "pm_score": 2, "selected": false, "text": "<p>You could also combine both of the two best-rated answers :\nUsing urllib2.urlparse.urlsplit() to get the path part of the URL, and then os.path.basename for the actual file name.</p>\n\n<p>Full code would be :</p>\n\n<pre><code>&gt;&gt;&gt; remotefile=urllib2.urlopen(url)\n&gt;&gt;&gt; try:\n&gt;&gt;&gt; filename=remotefile.info()['Content-Disposition']\n&gt;&gt;&gt; except KeyError:\n&gt;&gt;&gt; filename=os.path.basename(urllib2.urlparse.urlsplit(url).path)\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6007/" ]
If I open a file using urllib2, like so: ``` remotefile = urllib2.urlopen('http://example.com/somefile.zip') ``` Is there an easy way to get the file name other then parsing the original URL? EDIT: changed openfile to urlopen... not sure how that happened. EDIT2: I ended up using: ``` filename = url.split('/')[-1].split('#')[0].split('?')[0] ``` Unless I'm mistaken, this should strip out all potential queries as well.
Did you mean [urllib2.urlopen](http://www.python.org/doc/2.5.2/lib/module-urllib2.html#l2h-3928)? You could potentially lift the *intended* filename *if* the server was sending a Content-Disposition header by checking `remotefile.info()['Content-Disposition']`, but as it is I think you'll just have to parse the url. You could use `urlparse.urlsplit`, but if you have any URLs like at the second example, you'll end up having to pull the file name out yourself anyway: ``` >>> urlparse.urlsplit('http://example.com/somefile.zip') ('http', 'example.com', '/somefile.zip', '', '') >>> urlparse.urlsplit('http://example.com/somedir/somefile.zip') ('http', 'example.com', '/somedir/somefile.zip', '', '') ``` Might as well just do this: ``` >>> 'http://example.com/somefile.zip'.split('/')[-1] 'somefile.zip' >>> 'http://example.com/somedir/somefile.zip'.split('/')[-1] 'somefile.zip' ```
163,022
<p>I'd like to do some basic profiling of my code, but found that the DateTime.Now in C# only have a resolution of about 16 ms. There must be better time keeping constructs that I haven't yet found.</p>
[ { "answer_id": 163030, "author": "MagicKat", "author_id": 8505, "author_profile": "https://Stackoverflow.com/users/8505", "pm_score": 4, "selected": false, "text": "<p>The System.Diagnostics.StopWatch class is awesome for profiling.</p>\n\n<p>Here is a link to <a href=\"http://blogs.msdn.com/vancem/archive/2006/09/21/765648.aspx\" rel=\"noreferrer\">Vance Morrison's Code Timer Blog</a> if you don't want to write your own measurement functions.</p>\n" }, { "answer_id": 163089, "author": "ChronoPositron", "author_id": 19127, "author_profile": "https://Stackoverflow.com/users/19127", "pm_score": 1, "selected": false, "text": "<p>You could call down to the high-resolution performance counter in Windows. The function name is QueryPerformanceCounter in kernel32.dll.</p>\n\n<p>Syntax for importing into C#:</p>\n\n<pre><code>[DllImport(\"Kernel32.dll\")]\nprivate static extern bool QueryPerformanceCounter(out long lpPerformanceCount);\n</code></pre>\n\n<p>Syntax for Windows call:</p>\n\n<pre><code>BOOL QueryPerformanceCounter( \n LARGE_INTEGER *lpPerformanceCount\n);\n</code></pre>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms644904.aspx\" rel=\"nofollow noreferrer\">QueryPerformanceCounter @ MSDN</a></p>\n" }, { "answer_id": 163096, "author": "quickcel", "author_id": 9129, "author_profile": "https://Stackoverflow.com/users/9129", "pm_score": 7, "selected": true, "text": "<p>Here is a sample bit of code to time an operation:</p>\n\n<pre><code>Dim sw As New Stopwatch()\nsw.Start()\n//Insert Code To Time\nsw.Stop()\nDim ms As Long = sw.ElapsedMilliseconds\nConsole.WriteLine(\"Total Seconds Elapsed: \" &amp; ms / 1000)\n</code></pre>\n\n<p>EDIT:</p>\n\n<p>And the neat thing is that it can resume as well.</p>\n\n<pre><code>Stopwatch sw = new Stopwatch();\nforeach(MyStuff stuff in _listOfMyStuff)\n{\n sw.Start();\n stuff.DoCoolCalculation();\n sw.Stop();\n}\nConsole.WriteLine(\"Total calculation time: {0}\", sw.Elapsed);\n</code></pre>\n\n<p>The <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx\" rel=\"noreferrer\">System.Diagnostics.Stopwatch</a> class will use a high-resolution counter if one is available on your system.</p>\n" }, { "answer_id": 163125, "author": "Wolfwyrd", "author_id": 15570, "author_profile": "https://Stackoverflow.com/users/15570", "pm_score": 3, "selected": false, "text": "<p>For highest resolution performance counters you can use the underlying win32 performance counters.</p>\n\n<p>Add the following P/Invoke sigs:</p>\n\n<pre><code>[System.Runtime.InteropServices.DllImport(\"Kernel32.dll\")]\npublic static extern bool QueryPerformanceCounter(out long perfcount);\n\n[System.Runtime.InteropServices.DllImport(\"Kernel32.dll\")]\npublic static extern bool QueryPerformanceFrequency(out long freq);\n</code></pre>\n\n<p>And call them using:</p>\n\n<pre><code>#region Query Performance Counter\n/// &lt;summary&gt;\n/// Gets the current 'Ticks' on the performance counter\n/// &lt;/summary&gt;\n/// &lt;returns&gt;Long indicating the number of ticks on the performance counter&lt;/returns&gt;\npublic static long QueryPerformanceCounter()\n{\n long perfcount;\n QueryPerformanceCounter(out perfcount);\n return perfcount;\n}\n#endregion\n\n#region Query Performance Frequency\n/// &lt;summary&gt;\n/// Gets the number of performance counter ticks that occur every second\n/// &lt;/summary&gt;\n/// &lt;returns&gt;The number of performance counter ticks that occur every second&lt;/returns&gt;\npublic static long QueryPerformanceFrequency()\n{\n long freq;\n QueryPerformanceFrequency(out freq);\n return freq;\n}\n#endregion\n</code></pre>\n\n<p>Dump it all into a simple class and you're ready to go. Example (assuming a class name of PerformanceCounters):</p>\n\n<pre><code>long startCount = PerformanceCounter.QueryPerformanceCounter();\n// DoStuff();\nlong stopCount = PerformanceCounter.QueryPerformanceCounter();\nlong elapsedCount = stopCount - startCount;\ndouble elapsedSeconds = (double)elapsedCount / PerformanceCounter.QueryPerformanceFrequency();\nMessageBox.Show(String.Format(\"Took {0} Seconds\", Math.Round(elapsedSeconds, 6).ToString()));\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163022", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2973/" ]
I'd like to do some basic profiling of my code, but found that the DateTime.Now in C# only have a resolution of about 16 ms. There must be better time keeping constructs that I haven't yet found.
Here is a sample bit of code to time an operation: ``` Dim sw As New Stopwatch() sw.Start() //Insert Code To Time sw.Stop() Dim ms As Long = sw.ElapsedMilliseconds Console.WriteLine("Total Seconds Elapsed: " & ms / 1000) ``` EDIT: And the neat thing is that it can resume as well. ``` Stopwatch sw = new Stopwatch(); foreach(MyStuff stuff in _listOfMyStuff) { sw.Start(); stuff.DoCoolCalculation(); sw.Stop(); } Console.WriteLine("Total calculation time: {0}", sw.Elapsed); ``` The [System.Diagnostics.Stopwatch](http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx) class will use a high-resolution counter if one is available on your system.
163,092
<p>In Ruby you can easily set a default value for a variable </p> <pre><code>x ||= "default" </code></pre> <p>The above statement will set the value of x to "default" if x is nil or false</p> <p>Is there a similar shortcut in PHP or do I have to use the longer form:</p> <pre><code>$x = (isset($x))? $x : "default"; </code></pre> <p>Are there any easier ways to handle this in PHP?</p>
[ { "answer_id": 163115, "author": "jochil", "author_id": 23794, "author_profile": "https://Stackoverflow.com/users/23794", "pm_score": 0, "selected": false, "text": "<p>I think your longer form is already the shortcut for php... and I wouldn't use it, because it is not good to read</p>\n\n<p>Some notice:\nIn the symfony framework most of the \"get\"-Methods have a second parameter to define a default value...</p>\n" }, { "answer_id": 163123, "author": "Michał Niedźwiedzki", "author_id": 2169, "author_profile": "https://Stackoverflow.com/users/2169", "pm_score": 3, "selected": false, "text": "<pre><code>isset($x) or $x = 'default';\n</code></pre>\n" }, { "answer_id": 163901, "author": "SeanDowney", "author_id": 5261, "author_profile": "https://Stackoverflow.com/users/5261", "pm_score": 2, "selected": false, "text": "<p>I wrap it in a function:</p>\n\n<pre><code>function default($value, $default) {\n return $value ? $value : $default;\n}\n// then use it like:\n$x=default($x, 'default');\n</code></pre>\n\n<p>Some people may not like it, but it keeps your code cleaner if you're doing a crazy function call.</p>\n" }, { "answer_id": 4886395, "author": "igorw", "author_id": 289985, "author_profile": "https://Stackoverflow.com/users/289985", "pm_score": 6, "selected": false, "text": "<p>As of PHP 5.3 you can use the ternary operator while omitting the middle argument:</p>\n\n<pre><code>$x = $x ?: 'default';\n</code></pre>\n" }, { "answer_id": 51987885, "author": "Machavity", "author_id": 2370483, "author_profile": "https://Stackoverflow.com/users/2370483", "pm_score": 4, "selected": false, "text": "<p>As of PHP 7.0, you can also use the <a href=\"http://php.net/manual/en/migration70.new-features.php#migration70.new-features.null-coalesce-op\" rel=\"noreferrer\">null coalesce operator</a></p>\n\n<pre><code>// PHP version &lt; 7.0, using a standard ternary\n$x = (isset($_GET['y'])) ? $_GET['y'] : 'not set';\n// PHP version &gt;= 7.0\n$x = $_GET['y'] ?? 'not set';\n</code></pre>\n" }, { "answer_id": 72278101, "author": "Roman", "author_id": 913761, "author_profile": "https://Stackoverflow.com/users/913761", "pm_score": 2, "selected": false, "text": "<p>As of PHP 7.4 you can write:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$x ??= &quot;default&quot;;\n</code></pre>\n<p>This works as long as <code>$x</code> is <code>null</code>. Other &quot;falsy&quot; values don't count as &quot;not set&quot;.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/796/" ]
In Ruby you can easily set a default value for a variable ``` x ||= "default" ``` The above statement will set the value of x to "default" if x is nil or false Is there a similar shortcut in PHP or do I have to use the longer form: ``` $x = (isset($x))? $x : "default"; ``` Are there any easier ways to handle this in PHP?
As of PHP 5.3 you can use the ternary operator while omitting the middle argument: ``` $x = $x ?: 'default'; ```
163,098
<p>I have several databases where the transaction log (.LDF) is many times larger than the database file (.MDF).</p> <p>What can I do to automatically shrink these or keep them from getting so large?</p>
[ { "answer_id": 163114, "author": "Forgotten Semicolon", "author_id": 1960, "author_profile": "https://Stackoverflow.com/users/1960", "pm_score": 2, "selected": false, "text": "<p>DBCC SHRINKFILE.</p>\n\n<p><a href=\"http://support.microsoft.com/kb/907511\" rel=\"nofollow noreferrer\">Here for 2005.</a>\n<a href=\"http://support.microsoft.com/kb/907511\" rel=\"nofollow noreferrer\">Here for 2000.</a></p>\n" }, { "answer_id": 163116, "author": "Dana", "author_id": 7856, "author_profile": "https://Stackoverflow.com/users/7856", "pm_score": 2, "selected": false, "text": "<p>Right click on the database in Enterprise Manager > All Tasks > Shrink Database.</p>\n" }, { "answer_id": 163117, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 2, "selected": false, "text": "<p>Backup transaction log and shrink it.</p>\n\n<p>If the DB is being backed up regularly and truncated on checkpoint, it shouldn't grow out of control, however, if you are doing a large number (size) of transactions between those intervals, it will grow until the next checkpoint.</p>\n" }, { "answer_id": 163121, "author": "schudel", "author_id": 18877, "author_profile": "https://Stackoverflow.com/users/18877", "pm_score": -1, "selected": false, "text": "<p>try sp_force_shrink_log which you can find here\n<a href=\"http://www.rectanglered.com/sqlserver.php\" rel=\"nofollow noreferrer\">http://www.rectanglered.com/sqlserver.php</a></p>\n" }, { "answer_id": 163156, "author": "Fry", "author_id": 23553, "author_profile": "https://Stackoverflow.com/users/23553", "pm_score": 0, "selected": false, "text": "<p>Another thing you can try is to set the recovery mode to simple (if they are not already) for the database, which will keep the log files from growing as rapidly. We had this problem recently where our transaction log filled up and we were not permitted anymore transactions.</p>\n\n<p>A combination of the shrink file which is in multiple answers and simple recovery mode made sure our log file stayed a reasonable size.</p>\n" }, { "answer_id": 163193, "author": "jdecuyper", "author_id": 296, "author_profile": "https://Stackoverflow.com/users/296", "pm_score": 0, "selected": false, "text": "<p>Using Query Analyser:</p>\n\n<pre><code>USE yourdabatase\nSELECT * FROM sysfiles\n</code></pre>\n\n<p>You should find something similar to:<br /></p>\n\n<pre><code>FileID … \n1 1 24264 -1 1280 1048578 0 yourdabatase_Data D:\\MSSQL_Services\\Data\\yourdabatase_Data.MDF\n2 0 128 -1 1280 66 0 yourdabatase_Log D:\\MSSQL_Services\\Data\\yourdabatase_Log.LDF\n</code></pre>\n\n<p>Check the file ID of the log file (its 2 most of the time).\nExecute 2 or 3 times the checkpoint command to write every page to the hard-drive. </p>\n\n<pre><code>Checkpoint\nGO\nCheckpoint\nGO\n</code></pre>\n\n<p>Execute the following transactional command to trunk the log file to 1 MB</p>\n\n<pre><code>DUMP TRAN yourdabatase WITH no_log \nDBCC SHRINKFILE(2,1) /*(FileID , the new size = 1 Mb)*/\n</code></pre>\n" }, { "answer_id": 163218, "author": "kristof", "author_id": 3241, "author_profile": "https://Stackoverflow.com/users/3241", "pm_score": 4, "selected": true, "text": "<p>That should do the job</p>\n\n<pre><code>use master\ngo\ndump transaction &lt;YourDBName&gt; with no_log\ngo\nuse &lt;YourDBName&gt;\ngo\nDBCC SHRINKFILE (&lt;YourDBNameLogFileName&gt;, 100) -- where 100 is the size you may want to shrink it to in MB, change it to your needs\ngo\n-- then you can call to check that all went fine\ndbcc checkdb(&lt;YourDBName&gt;)\n</code></pre>\n\n<p><strong>A word of warning</strong></p>\n\n<p>You would only really use it on a test/development database where you do not need a proper backup strategy as dumping the log will result in losing transactions history. In live systems you should use solution sugested by <a href=\"https://stackoverflow.com/questions/163098/how-do-i-shrink-the-transaction-log-on-ms-sql-2000-databases/163117#163117\">Cade Roux</a></p>\n" }, { "answer_id": 163340, "author": "spinner_den_g", "author_id": 2605028, "author_profile": "https://Stackoverflow.com/users/2605028", "pm_score": 0, "selected": false, "text": "<p>Here is what I have been Using</p>\n\n<pre><code>BACKUP LOG &lt;CatalogName&gt; with TRUNCATE_ONLY\nDBCC SHRINKDATABASE (&lt;CatalogName&gt;, 1)\nuse &lt;CatalogName&gt;\ngo\nDBCC SHRINKFILE(&lt;CatalogName_logName&gt;,1)\n</code></pre>\n" }, { "answer_id": 167313, "author": "Mladen", "author_id": 21404, "author_profile": "https://Stackoverflow.com/users/21404", "pm_score": 1, "selected": false, "text": "<p>No one here said it, so I will: NEVER EVER shrink the transaction log. It is a bad idea from the SQL Server point of view.</p>\n\n<p>Keep the transaction log small by doing daily db backups and hourly (or less) transaction log backups. The transaction log backup interval depends on how busy your db is.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163098", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2926/" ]
I have several databases where the transaction log (.LDF) is many times larger than the database file (.MDF). What can I do to automatically shrink these or keep them from getting so large?
That should do the job ``` use master go dump transaction <YourDBName> with no_log go use <YourDBName> go DBCC SHRINKFILE (<YourDBNameLogFileName>, 100) -- where 100 is the size you may want to shrink it to in MB, change it to your needs go -- then you can call to check that all went fine dbcc checkdb(<YourDBName>) ``` **A word of warning** You would only really use it on a test/development database where you do not need a proper backup strategy as dumping the log will result in losing transactions history. In live systems you should use solution sugested by [Cade Roux](https://stackoverflow.com/questions/163098/how-do-i-shrink-the-transaction-log-on-ms-sql-2000-databases/163117#163117)
163,162
<p>I am trying to use the <code>Directory.GetFiles()</code> method to retrieve a list of files of multiple types, such as <code>mp3</code>'s and <code>jpg</code>'s. I have tried both of the following with no luck:</p> <pre><code>Directory.GetFiles("C:\\path", "*.mp3|*.jpg", SearchOption.AllDirectories); Directory.GetFiles("C:\\path", "*.mp3;*.jpg", SearchOption.AllDirectories); </code></pre> <p>Is there a way to do this in one call?</p>
[ { "answer_id": 163203, "author": "NotMe", "author_id": 2424, "author_profile": "https://Stackoverflow.com/users/2424", "pm_score": 3, "selected": false, "text": "<p>Nope. Try the following:</p>\n\n<pre><code>List&lt;string&gt; _searchPatternList = new List&lt;string&gt;();\n ...\n List&lt;string&gt; fileList = new List&lt;string&gt;();\n foreach ( string ext in _searchPatternList )\n {\n foreach ( string subFile in Directory.GetFiles( folderName, ext )\n {\n fileList.Add( subFile );\n }\n }\n\n // Sort alpabetically\n fileList.Sort();\n\n // Add files to the file browser control \n foreach ( string fileName in fileList )\n {\n ...;\n }\n</code></pre>\n\n<p>Taken from: <a href=\"http://blogs.msdn.com/markda/archive/2006/04/20/580075.aspx\" rel=\"noreferrer\">http://blogs.msdn.com/markda/archive/2006/04/20/580075.aspx</a></p>\n" }, { "answer_id": 163219, "author": "sebagomez", "author_id": 23893, "author_profile": "https://Stackoverflow.com/users/23893", "pm_score": 2, "selected": false, "text": "<p>Nop... I believe you have to make as many calls as the file types you want. </p>\n\n<p>I would create a function myself taking an array on strings with the extensions I need and then iterate on that array making all the necessary calls. That function would return a generic list of the files matching the extensions I'd sent.</p>\n\n<p>Hope it helps.</p>\n" }, { "answer_id": 163220, "author": "Christoffer Lette", "author_id": 11808, "author_profile": "https://Stackoverflow.com/users/11808", "pm_score": 10, "selected": true, "text": "<p>For .NET 4.0 and later, </p>\n\n<pre><code>var files = Directory.EnumerateFiles(\"C:\\\\path\", \"*.*\", SearchOption.AllDirectories)\n .Where(s =&gt; s.EndsWith(\".mp3\") || s.EndsWith(\".jpg\"));\n</code></pre>\n\n<p>For earlier versions of .NET,</p>\n\n<pre><code>var files = Directory.GetFiles(\"C:\\\\path\", \"*.*\", SearchOption.AllDirectories)\n .Where(s =&gt; s.EndsWith(\".mp3\") || s.EndsWith(\".jpg\"));\n</code></pre>\n\n<p><strong>edit:</strong> <em>Please read the comments. The improvement that <a href=\"https://stackoverflow.com/users/97516/paul-farry\">Paul Farry</a> suggests, and the memory/performance issue that <a href=\"https://stackoverflow.com/users/21567/christian-k\">Christian.K</a> points out are both very important.</em></p>\n" }, { "answer_id": 163505, "author": "Jason Z", "author_id": 2470, "author_profile": "https://Stackoverflow.com/users/2470", "pm_score": 2, "selected": false, "text": "<p>Just found an another way to do it. Still not one operation, but throwing it out to see what other people think about it.</p>\n\n<pre><code>private void getFiles(string path)\n{\n foreach (string s in Array.FindAll(Directory.GetFiles(path, \"*\", SearchOption.AllDirectories), predicate_FileMatch))\n {\n Debug.Print(s);\n }\n}\n\nprivate bool predicate_FileMatch(string fileName)\n{\n if (fileName.EndsWith(\".mp3\"))\n return true;\n if (fileName.EndsWith(\".jpg\"))\n return true;\n return false;\n}\n</code></pre>\n" }, { "answer_id": 2945136, "author": "Alexander Popov", "author_id": 246473, "author_profile": "https://Stackoverflow.com/users/246473", "pm_score": 2, "selected": false, "text": "<p>The following function searches on multiple patterns, separated by commas. You can also specify an exclusion, eg: \"!web.config\" will search for all files and exclude \"web.config\". Patterns can be mixed.</p>\n\n<pre><code>private string[] FindFiles(string directory, string filters, SearchOption searchOption)\n{\n if (!Directory.Exists(directory)) return new string[] { };\n\n var include = (from filter in filters.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries) where !string.IsNullOrEmpty(filter.Trim()) select filter.Trim());\n var exclude = (from filter in include where filter.Contains(@\"!\") select filter);\n\n include = include.Except(exclude);\n\n if (include.Count() == 0) include = new string[] { \"*\" };\n\n var rxfilters = from filter in exclude select string.Format(\"^{0}$\", filter.Replace(\"!\", \"\").Replace(\".\", @\"\\.\").Replace(\"*\", \".*\").Replace(\"?\", \".\"));\n Regex regex = new Regex(string.Join(\"|\", rxfilters.ToArray()));\n\n List&lt;Thread&gt; workers = new List&lt;Thread&gt;();\n List&lt;string&gt; files = new List&lt;string&gt;();\n\n foreach (string filter in include)\n {\n Thread worker = new Thread(\n new ThreadStart(\n delegate\n {\n string[] allfiles = Directory.GetFiles(directory, filter, searchOption);\n if (exclude.Count() &gt; 0)\n {\n lock (files)\n files.AddRange(allfiles.Where(p =&gt; !regex.Match(p).Success));\n }\n else\n {\n lock (files)\n files.AddRange(allfiles);\n }\n }\n ));\n\n workers.Add(worker);\n\n worker.Start();\n }\n\n foreach (Thread worker in workers)\n {\n worker.Join();\n }\n\n return files.ToArray();\n\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>foreach (string file in FindFiles(@\"D:\\628.2.11\", @\"!*.config, !*.js\", SearchOption.AllDirectories))\n {\n Console.WriteLine(file);\n }\n</code></pre>\n" }, { "answer_id": 3707149, "author": "abatishchev", "author_id": 41956, "author_profile": "https://Stackoverflow.com/users/41956", "pm_score": 3, "selected": false, "text": "<p>Let</p>\n\n<pre><code>var set = new HashSet&lt;string&gt; { \".mp3\", \".jpg\" };\n</code></pre>\n\n<p>Then</p>\n\n<pre><code>Directory.GetFiles(path, \"*.*\", SearchOption.AllDirectories)\n .Where(f =&gt; set.Contains(\n new FileInfo(f).Extension,\n StringComparer.OrdinalIgnoreCase));\n</code></pre>\n\n<p>or</p>\n\n<pre><code>from file in Directory.GetFiles(path, \"*.*\", SearchOption.AllDirectories)\nfrom ext in set\nwhere String.Equals(ext, new FileInfo(file).Extension, StringComparison.OrdinalIgnoreCase)\nselect file;\n</code></pre>\n" }, { "answer_id": 3740401, "author": "Rajeesh Kuthuparakkal", "author_id": 451211, "author_profile": "https://Stackoverflow.com/users/451211", "pm_score": 3, "selected": false, "text": "<pre><code>List&lt;string&gt; FileList = new List&lt;string&gt;();\nDirectoryInfo di = new DirectoryInfo(\"C:\\\\DirName\");\n\nIEnumerable&lt;FileInfo&gt; fileList = di.GetFiles(\"*.*\");\n\n//Create the query\nIEnumerable&lt;FileInfo&gt; fileQuery = from file in fileList\n where (file.Extension.ToLower() == \".jpg\" || file.Extension.ToLower() == \".png\")\n orderby file.LastWriteTime\n select file;\n\nforeach (System.IO.FileInfo fi in fileQuery)\n{\n fi.Attributes = FileAttributes.Normal;\n FileList.Add(fi.FullName);\n}\n</code></pre>\n" }, { "answer_id": 4617227, "author": "jnoreiga", "author_id": 516492, "author_profile": "https://Stackoverflow.com/users/516492", "pm_score": 5, "selected": false, "text": "<p>If you have a large list of extensions to check you can use the following. I didn't want to create a lot of OR statements so i modified what lette wrote.</p>\n\n<pre><code>string supportedExtensions = \"*.jpg,*.gif,*.png,*.bmp,*.jpe,*.jpeg,*.wmf,*.emf,*.xbm,*.ico,*.eps,*.tif,*.tiff,*.g01,*.g02,*.g03,*.g04,*.g05,*.g06,*.g07,*.g08\";\nforeach (string imageFile in Directory.GetFiles(_tempDirectory, \"*.*\", SearchOption.AllDirectories).Where(s =&gt; supportedExtensions.Contains(Path.GetExtension(s).ToLower())))\n{\n //do work here\n}\n</code></pre>\n" }, { "answer_id": 8280070, "author": "eduardomozart", "author_id": 1031340, "author_profile": "https://Stackoverflow.com/users/1031340", "pm_score": 3, "selected": false, "text": "<p>I can't use <code>.Where</code> method because I'm programming in .NET Framework 2.0 (Linq is only supported in .NET Framework 3.5+). </p>\n\n<p>Code below is not case sensitive (so <code>.CaB</code> or <code>.cab</code> will be listed too).</p>\n\n<pre><code>string[] ext = new string[2] { \"*.CAB\", \"*.MSU\" };\n\nforeach (string found in ext)\n{\n string[] extracted = Directory.GetFiles(\"C:\\\\test\", found, System.IO.SearchOption.AllDirectories);\n\n foreach (string file in extracted)\n {\n Console.WriteLine(file);\n }\n}\n</code></pre>\n" }, { "answer_id": 8363526, "author": "Dave Rael", "author_id": 490500, "author_profile": "https://Stackoverflow.com/users/490500", "pm_score": 4, "selected": false, "text": "<p>Another way to use Linq, but without having to return everything and filter on that in memory.</p>\n\n<pre><code>var files = Directory.GetFiles(\"C:\\\\path\", \"*.mp3\", SearchOption.AllDirectories).Union(Directory.GetFiles(\"C:\\\\path\", \"*.jpg\", SearchOption.AllDirectories));\n</code></pre>\n\n<p>It's actually 2 calls to <code>GetFiles()</code>, but I think it's consistent with the spirit of the question and returns them in one enumerable.</p>\n" }, { "answer_id": 8466982, "author": "Albert", "author_id": 182888, "author_profile": "https://Stackoverflow.com/users/182888", "pm_score": 6, "selected": false, "text": "<p>How about this:</p>\n\n<pre><code>private static string[] GetFiles(string sourceFolder, string filters, System.IO.SearchOption searchOption)\n{\n return filters.Split('|').SelectMany(filter =&gt; System.IO.Directory.GetFiles(sourceFolder, filter, searchOption)).ToArray();\n}\n</code></pre>\n\n<p>I found it here (in the comments): <a href=\"http://msdn.microsoft.com/en-us/library/wz42302f.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/wz42302f.aspx</a></p>\n" }, { "answer_id": 8516496, "author": "A.Ramazani", "author_id": 1099337, "author_profile": "https://Stackoverflow.com/users/1099337", "pm_score": 2, "selected": false, "text": "<pre><code>/// &lt;summary&gt;\n/// Returns the names of files in a specified directories that match the specified patterns using LINQ\n/// &lt;/summary&gt;\n/// &lt;param name=\"srcDirs\"&gt;The directories to seach&lt;/param&gt;\n/// &lt;param name=\"searchPatterns\"&gt;the list of search patterns&lt;/param&gt;\n/// &lt;param name=\"searchOption\"&gt;&lt;/param&gt;\n/// &lt;returns&gt;The list of files that match the specified pattern&lt;/returns&gt;\npublic static string[] GetFilesUsingLINQ(string[] srcDirs,\n string[] searchPatterns,\n SearchOption searchOption = SearchOption.AllDirectories)\n{\n var r = from dir in srcDirs\n from searchPattern in searchPatterns\n from f in Directory.GetFiles(dir, searchPattern, searchOption)\n select f;\n\n return r.ToArray();\n}\n</code></pre>\n" }, { "answer_id": 9984667, "author": "Evado", "author_id": 1309151, "author_profile": "https://Stackoverflow.com/users/1309151", "pm_score": 2, "selected": false, "text": "<p>Make the extensions you want one string i.e \".mp3.jpg.wma.wmf\" and then check if each file contains the extension you want.\nThis works with .net 2.0 as it does not use LINQ.</p>\n\n<pre><code>string myExtensions=\".jpg.mp3\";\n\nstring[] files=System.IO.Directory.GetFiles(\"C:\\myfolder\");\n\nforeach(string file in files)\n{\n if(myExtensions.ToLower().contains(System.IO.Path.GetExtension(s).ToLower()))\n {\n //this file has passed, do something with this file\n\n }\n}\n</code></pre>\n\n<p>The advantage with this approach is you can add or remove extensions without editing the code i.e to add png images, just write myExtensions=\".jpg.mp3.png\".</p>\n" }, { "answer_id": 12927028, "author": "Icehunter", "author_id": 1751967, "author_profile": "https://Stackoverflow.com/users/1751967", "pm_score": 4, "selected": false, "text": "<p>I know it's old question but LINQ: (.NET40+)</p>\n\n<pre><code>var files = Directory.GetFiles(\"path_to_files\").Where(file =&gt; Regex.IsMatch(file, @\"^.+\\.(wav|mp3|txt)$\"));\n</code></pre>\n" }, { "answer_id": 13719160, "author": "Quispie", "author_id": 1758886, "author_profile": "https://Stackoverflow.com/users/1758886", "pm_score": 2, "selected": false, "text": "<p>I had the same problem and couldn't find the right solution so I wrote a function called GetFiles:</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Get all files with a specific extension\n/// &lt;/summary&gt;\n/// &lt;param name=\"extensionsToCompare\"&gt;string list of all the extensions&lt;/param&gt;\n/// &lt;param name=\"Location\"&gt;string of the location&lt;/param&gt;\n/// &lt;returns&gt;array of all the files with the specific extensions&lt;/returns&gt;\npublic string[] GetFiles(List&lt;string&gt; extensionsToCompare, string Location)\n{\n List&lt;string&gt; files = new List&lt;string&gt;();\n foreach (string file in Directory.GetFiles(Location))\n {\n if (extensionsToCompare.Contains(file.Substring(file.IndexOf('.')+1).ToLower())) files.Add(file);\n }\n files.Sort();\n return files.ToArray();\n}\n</code></pre>\n\n<p>This function will call <code>Directory.Getfiles()</code> only one time.</p>\n\n<p>For example call the function like this:</p>\n\n<pre><code>string[] images = GetFiles(new List&lt;string&gt;{\"jpg\", \"png\", \"gif\"}, \"imageFolder\");\n</code></pre>\n\n<p>EDIT: To get one file with multiple extensions use this one:</p>\n\n<pre><code>/// &lt;summary&gt;\n /// Get the file with a specific name and extension\n /// &lt;/summary&gt;\n /// &lt;param name=\"filename\"&gt;the name of the file to find&lt;/param&gt;\n /// &lt;param name=\"extensionsToCompare\"&gt;string list of all the extensions&lt;/param&gt;\n /// &lt;param name=\"Location\"&gt;string of the location&lt;/param&gt;\n /// &lt;returns&gt;file with the requested filename&lt;/returns&gt;\n public string GetFile( string filename, List&lt;string&gt; extensionsToCompare, string Location)\n {\n foreach (string file in Directory.GetFiles(Location))\n {\n if (extensionsToCompare.Contains(file.Substring(file.IndexOf('.') + 1).ToLower()) &amp;&amp;&amp; file.Substring(Location.Length + 1, (file.IndexOf('.') - (Location.Length + 1))).ToLower() == filename) \n return file;\n }\n return \"\";\n }\n</code></pre>\n\n<p>For example call the function like this:</p>\n\n<pre><code>string image = GetFile(\"imagename\", new List&lt;string&gt;{\"jpg\", \"png\", \"gif\"}, \"imageFolder\");\n</code></pre>\n" }, { "answer_id": 15571040, "author": "Bas1l", "author_id": 2029962, "author_profile": "https://Stackoverflow.com/users/2029962", "pm_score": 4, "selected": false, "text": "<p>There is also a descent solution which seems not to have any memory or performance overhead and be quite elegant:</p>\n\n<pre><code>string[] filters = new[]{\"*.jpg\", \"*.png\", \"*.gif\"};\nstring[] filePaths = filters.SelectMany(f =&gt; Directory.GetFiles(basePath, f)).ToArray();\n</code></pre>\n" }, { "answer_id": 15768160, "author": "Janis", "author_id": 2199074, "author_profile": "https://Stackoverflow.com/users/2199074", "pm_score": 2, "selected": false, "text": "<p>I wonder why there are so many \"solutions\" posted?</p>\n\n<p>If my rookie-understanding on how GetFiles works is right, there are only two options and any of the solutions above can be brought down to these:</p>\n\n<ol>\n<li><p>GetFiles, then filter: Fast, but a memory killer due to storing overhead untill the filters are applied</p></li>\n<li><p>Filter while GetFiles: Slower the more filters are set, but low memory usage as no overhead is stored.<br><em>This is explained in one of the above posts with an impressive benchmark: Each filter option causes a seperate GetFile-operation so the same part of the harddrive gets read several times.</em></p></li>\n</ol>\n\n<p>In my opinion Option 1) is better, but using the SearchOption.AllDirectories on folders like C:\\ would use huge amounts of memory.<br>\nTherefor i would just make a recursive sub-method that goes through all subfolders using option 1)</p>\n\n<p>This should cause only 1 GetFiles-operation on each folder and therefor be fast (Option 1), but use only a small amount of memory as the filters are applied afters each subfolders' reading -> overhead is deleted after each subfolder.</p>\n\n<p>Please correct me if I am wrong. I am as i said quite new to programming but want to gain deeper understanding of things to eventually become good at this :)</p>\n" }, { "answer_id": 16101684, "author": "Nilesh Padhiyar", "author_id": 2298661, "author_profile": "https://Stackoverflow.com/users/2298661", "pm_score": 3, "selected": false, "text": "<pre><code>DirectoryInfo directory = new DirectoryInfo(Server.MapPath(\"~/Contents/\"));\n\n//Using Union\n\nFileInfo[] files = directory.GetFiles(\"*.xlsx\")\n .Union(directory\n .GetFiles(\"*.csv\"))\n .ToArray();\n</code></pre>\n" }, { "answer_id": 19961761, "author": "drzaus", "author_id": 1037948, "author_profile": "https://Stackoverflow.com/users/1037948", "pm_score": 5, "selected": false, "text": "<p>for</p>\n\n<pre><code>var exts = new[] { \"mp3\", \"jpg\" };\n</code></pre>\n\n<p>You could:</p>\n\n<pre><code>public IEnumerable&lt;string&gt; FilterFiles(string path, params string[] exts) {\n return\n Directory\n .EnumerateFiles(path, \"*.*\")\n .Where(file =&gt; exts.Any(x =&gt; file.EndsWith(x, StringComparison.OrdinalIgnoreCase)));\n}\n</code></pre>\n\n<ul>\n<li>Don't forget the new .NET4 <code>Directory.EnumerateFiles</code> for a performance boost (<a href=\"https://stackoverflow.com/questions/5669617/what-is-the-difference-between-directory-enumeratefiles-vs-directory-getfiles\">What is the difference between Directory.EnumerateFiles vs Directory.GetFiles?</a>)</li>\n<li>\"IgnoreCase\" should be faster than \"ToLower\" (<code>.EndsWith(\"aspx\", StringComparison.OrdinalIgnoreCase)</code> rather than <code>.ToLower().EndsWith(\"aspx\")</code>)</li>\n</ul>\n\n<p>But the real benefit of <code>EnumerateFiles</code> shows up when you split up the filters and merge the results:</p>\n\n<pre><code>public IEnumerable&lt;string&gt; FilterFiles(string path, params string[] exts) {\n return \n exts.Select(x =&gt; \"*.\" + x) // turn into globs\n .SelectMany(x =&gt; \n Directory.EnumerateFiles(path, x)\n );\n}\n</code></pre>\n\n<p>It gets a bit faster if you don't have to turn them into globs (i.e. <code>exts = new[] {\"*.mp3\", \"*.jpg\"}</code> already).</p>\n\n<p>Performance evaluation based on the following LinqPad test (note: <code>Perf</code> just repeats the delegate 10000 times)\n<a href=\"https://gist.github.com/zaus/7454021\" rel=\"noreferrer\">https://gist.github.com/zaus/7454021</a></p>\n\n<p><em>( reposted and extended from 'duplicate' since that question specifically requested no LINQ: <a href=\"https://stackoverflow.com/questions/7039580/multiple-file-extensions-searchpattern-for-system-io-directory-getfiles/19933502#19933502\">Multiple file-extensions searchPattern for System.IO.Directory.GetFiles</a> )</em></p>\n" }, { "answer_id": 22947900, "author": "user3512661", "author_id": 3512661, "author_profile": "https://Stackoverflow.com/users/3512661", "pm_score": 1, "selected": false, "text": "<p>Or you can just convert the string of extensions to String^</p>\n\n<pre><code>vector &lt;string&gt; extensions = { \"*.mp4\", \"*.avi\", \"*.flv\" };\nfor (int i = 0; i &lt; extensions.size(); ++i)\n{\n String^ ext = gcnew String(extensions[i].c_str());;\n String^ path = \"C:\\\\Users\\\\Eric\\\\Videos\";\n array&lt;String^&gt;^files = Directory::GetFiles(path,ext);\n Console::WriteLine(ext);\n cout &lt;&lt; \" \" &lt;&lt; (files-&gt;Length) &lt;&lt; endl;\n}\n</code></pre>\n" }, { "answer_id": 25643193, "author": "Stefan Steiger", "author_id": 155077, "author_profile": "https://Stackoverflow.com/users/155077", "pm_score": 3, "selected": false, "text": "<p>in .NET 2.0 (no Linq):</p>\n\n<pre><code>public static List&lt;string&gt; GetFilez(string path, System.IO.SearchOption opt, params string[] patterns)\n{\n List&lt;string&gt; filez = new List&lt;string&gt;();\n foreach (string pattern in patterns)\n {\n filez.AddRange(\n System.IO.Directory.GetFiles(path, pattern, opt)\n );\n }\n\n\n // filez.Sort(); // Optional\n return filez; // Optional: .ToArray()\n}\n</code></pre>\n\n<p>Then use it:</p>\n\n<pre><code>foreach (string fn in GetFilez(path\n , System.IO.SearchOption.AllDirectories\n , \"*.xml\", \"*.xml.rels\", \"*.rels\"))\n{}\n</code></pre>\n" }, { "answer_id": 30381302, "author": "MattyMerrix", "author_id": 3416222, "author_profile": "https://Stackoverflow.com/users/3416222", "pm_score": 2, "selected": false, "text": "<p>What about</p>\n\n<pre><code>string[] filesPNG = Directory.GetFiles(path, \"*.png\");\nstring[] filesJPG = Directory.GetFiles(path, \"*.jpg\");\nstring[] filesJPEG = Directory.GetFiles(path, \"*.jpeg\");\n\nint totalArraySizeAll = filesPNG.Length + filesJPG.Length + filesJPEG.Length;\nList&lt;string&gt; filesAll = new List&lt;string&gt;(totalArraySizeAll);\nfilesAll.AddRange(filesPNG);\nfilesAll.AddRange(filesJPG);\nfilesAll.AddRange(filesJPEG);\n</code></pre>\n" }, { "answer_id": 45012513, "author": "elle0087", "author_id": 3061212, "author_profile": "https://Stackoverflow.com/users/3061212", "pm_score": 1, "selected": false, "text": "<p>i don t know what solution is better, but i use this:</p>\n\n<pre><code>String[] ext = \"*.ext1|*.ext2\".Split('|');\n\n List&lt;String&gt; files = new List&lt;String&gt;();\n foreach (String tmp in ext)\n {\n files.AddRange(Directory.GetFiles(dir, tmp, SearchOption.AllDirectories));\n }\n</code></pre>\n" }, { "answer_id": 48805134, "author": "Crusha K. Rool", "author_id": 7024019, "author_profile": "https://Stackoverflow.com/users/7024019", "pm_score": 3, "selected": false, "text": "<p>If you are using VB.NET (or imported the dependency into your C# project), there actually exists a convenience method that allows to filter for multiple extensions:</p>\n\n<pre><code>Microsoft.VisualBasic.FileIO.FileSystem.GetFiles(\"C:\\\\path\", Microsoft.VisualBasic.FileIO.SearchOption.SearchAllSubDirectories, new string[] {\"*.mp3\", \"*.jpg\"});\n</code></pre>\n\n<p>In VB.NET this can be accessed through the My-namespace:</p>\n\n<pre><code>My.Computer.FileSystem.GetFiles(\"C:\\path\", FileIO.SearchOption.SearchAllSubDirectories, {\"*.mp3\", \"*.jpg\"})\n</code></pre>\n\n<p>Unfortunately, these convenience methods don't support a lazily evaluated variant like <code>Directory.EnumerateFiles()</code> does.</p>\n" }, { "answer_id": 53171094, "author": "WillyS", "author_id": 10612853, "author_profile": "https://Stackoverflow.com/users/10612853", "pm_score": 2, "selected": false, "text": "<p>Using GetFiles search pattern for filtering the extension is not safe!!\nFor instance you have two file Test1.xls and Test2.xlsx and you want to filter out xls file using search pattern *.xls, but GetFiles return both Test1.xls and Test2.xlsx \nI was not aware of this and got error in production environment when some temporary files suddenly was handled as right files. Search pattern was *.txt and temp files was named *.txt20181028_100753898\nSo search pattern can not be trusted, you have to add extra check on filenames as well.</p>\n" }, { "answer_id": 62342701, "author": "JohnnBlade", "author_id": 588189, "author_profile": "https://Stackoverflow.com/users/588189", "pm_score": 2, "selected": false, "text": "<p>Here is a simple and elegant way of getting filtered files</p>\n\n<pre><code>var allowedFileExtensions = \".csv,.txt\";\n\n\nvar files = Directory.EnumerateFiles(@\"C:\\MyFolder\", \"*.*\", SearchOption.TopDirectoryOnly)\n .Where(s =&gt; allowedFileExtensions.IndexOf(Path.GetExtension(s)) &gt; -1).ToArray(); \n</code></pre>\n" }, { "answer_id": 72497345, "author": "hossein sedighian", "author_id": 10143546, "author_profile": "https://Stackoverflow.com/users/10143546", "pm_score": 0, "selected": false, "text": "<p>you can add this to your project</p>\n<pre><code>public static class Collectables {\n public static List&lt;System.IO.FileInfo&gt; FilesViaPattern(this System.IO.DirectoryInfo fldr, string pattern) {\n var filter = pattern.Split(&quot; &quot;);\n return fldr.GetFiles( &quot;*.*&quot;, System.IO.SearchOption.AllDirectories)\n .Where(l =&gt; filter.Any(k =&gt; l.Name.EndsWith(k))).ToList();\n }\n}\n</code></pre>\n<p>then use it anywhere like this</p>\n<pre><code>new System.IO.DirectoryInfo(&quot;c:\\\\test&quot;).FilesViaPattern(&quot;txt doc any.extension&quot;);\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163162", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2470/" ]
I am trying to use the `Directory.GetFiles()` method to retrieve a list of files of multiple types, such as `mp3`'s and `jpg`'s. I have tried both of the following with no luck: ``` Directory.GetFiles("C:\\path", "*.mp3|*.jpg", SearchOption.AllDirectories); Directory.GetFiles("C:\\path", "*.mp3;*.jpg", SearchOption.AllDirectories); ``` Is there a way to do this in one call?
For .NET 4.0 and later, ``` var files = Directory.EnumerateFiles("C:\\path", "*.*", SearchOption.AllDirectories) .Where(s => s.EndsWith(".mp3") || s.EndsWith(".jpg")); ``` For earlier versions of .NET, ``` var files = Directory.GetFiles("C:\\path", "*.*", SearchOption.AllDirectories) .Where(s => s.EndsWith(".mp3") || s.EndsWith(".jpg")); ``` **edit:** *Please read the comments. The improvement that [Paul Farry](https://stackoverflow.com/users/97516/paul-farry) suggests, and the memory/performance issue that [Christian.K](https://stackoverflow.com/users/21567/christian-k) points out are both very important.*
163,183
<p>I'm encountering some peculiarities with LINQ to SQL.</p> <p>With a relatively simple query, I want to select some fields, but have the date fields formatted as strings, which I first achieved like this:</p> <pre><code> var list = dataContext.MyLists.Single(x =&gt; x.ID == myId); var items = from i in list.MyItems select new { i.ID, i.Sector, i.Description, CompleteDate = i.CompleteDate.HasValue ? i.CompleteDate.Value.ToShortDateString() : "", DueDate = i.DueDate.HasValue ? i.DueDate.Value.ToShortDateString() : "" }; </code></pre> <p>Later on I tried the following query, which is exactly the same, except I'm querying straight from my dataContext, rather than an element in my first query:</p> <pre><code> var items = from i in dataContext.MyLists select new { i.ID, i.Sector, i.Description, CompleteDate = i.CompleteDate.HasValue ? i.CompleteDate.Value.ToShortDateString() : "", DueDate = i.DueDate.HasValue ? i.DueDate.Value.ToShortDateString() : "" }; </code></pre> <p>The first one runs fine, yet the second query yields a: </p> <p><em>Could not translate expression '...' into SQL and could not treat it as a local expression.</em></p> <p>If I remove the lines that Format the date, it works fine. If I remove the .HasValue check it also works fine, until there are null values.</p> <p>Any ideas?</p> <p>Anthony</p>
[ { "answer_id": 163248, "author": "Paul Nearney", "author_id": 24071, "author_profile": "https://Stackoverflow.com/users/24071", "pm_score": 3, "selected": false, "text": "<p>In the first query, you have already got the data back from the database by the time the second line runs (var items = ...). This means that the 2nd line runs at the client, where ToShortDateString can run quite happily.</p>\n\n<p>In the second query, because the select runs directly on an IQueryable collection (dataContext.MyLists), it attempts to translate the select into SQL for processing at the server, where ToShortDateString is not understood - hence the \"Could Not Translate..\" exception.</p>\n\n<p>To understand this a bit better, you really need to understand the difference between IQueryable and IEnumerable, and at which point a Linq To Sql query stops being IQueryable and becomes IEnumerable. There is plenty of stuff on the web about this.</p>\n\n<p>Hope this helps,</p>\n\n<p>Paul</p>\n" }, { "answer_id": 163261, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 5, "selected": true, "text": "<p>I'd do the SQL part without doing the formatting, then do the formatting on the client side:</p>\n\n<pre><code>var items = list.MyItems.Select(item =&gt; new { item.ID, item.Sector, item.Description, \n item.CompleteDate, item.DueDate })\n .AsEnumerable() // Don't do the next bit in the DB\n .Select(item =&gt; new { item.ID, item.Sector, item.Description,\n CompleteDate = FormatDate(CompleteDate),\n DueDate = FormatDate(DueDate) });\n\n\nstatic string FormatDate(DateTime? date)\n{\n return date.HasValue ? date.Value.ToShortDateString() : \"\"\n}\n</code></pre>\n" }, { "answer_id": 163265, "author": "Carlton Jenke", "author_id": 1215, "author_profile": "https://Stackoverflow.com/users/1215", "pm_score": 3, "selected": false, "text": "<p>Just like the error message tells you, the difference is due to what can be done locally verses remotely while connecting to SQL.</p>\n\n<p>The Linq code has to be converted by Linq to SQL into a SQL command for the remote data pulls - anything that has to be done locally cannot be included.</p>\n\n<p>Once you pulled it into a local object (in the first example), it is not using Linq to SQL anymore, just plain Linq. At that point you are free to do local manipulations on it.</p>\n" }, { "answer_id": 163502, "author": "Chris Ammerman", "author_id": 2729, "author_profile": "https://Stackoverflow.com/users/2729", "pm_score": 2, "selected": false, "text": "<p>Maybe there was a copy and paste error or just a typo in your sample. But if not, this might be the problem...</p>\n\n<p>In the second query you are querying a collection of lists, whereas in the first query you were querying the items within a list. But you haven't adjusted the query to account for this difference.</p>\n\n<p>What you need might be this. Note the commented lines which did not appear in your second sample.</p>\n\n<pre><code> var items = from aList in dataContext.MyLists\n from i in aList.MyItems // Access the items in a list\n where aList.ID == myId // Use only the single desired list\n select\n new\n {\n i.ID,\n i.Sector,\n i.Description,\n CompleteDate = i.CompleteDate.HasValue ? i.CompleteDate.Value.ToShortDateString() : \"\",\n DueDate = i.DueDate.HasValue ? i.DueDate.Value.ToShortDateString() : \"\"\n };\n</code></pre>\n" }, { "answer_id": 2208024, "author": "rotary_engine", "author_id": 248869, "author_profile": "https://Stackoverflow.com/users/248869", "pm_score": 1, "selected": false, "text": "<p><code>ToShortDateString()</code> is not supported by Linq to SQL <a href=\"http://msdn.microsoft.com/en-us/library/bb882657.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/bb882657.aspx</a></p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163183", "https://Stackoverflow.com", "https://Stackoverflow.com/users/366/" ]
I'm encountering some peculiarities with LINQ to SQL. With a relatively simple query, I want to select some fields, but have the date fields formatted as strings, which I first achieved like this: ``` var list = dataContext.MyLists.Single(x => x.ID == myId); var items = from i in list.MyItems select new { i.ID, i.Sector, i.Description, CompleteDate = i.CompleteDate.HasValue ? i.CompleteDate.Value.ToShortDateString() : "", DueDate = i.DueDate.HasValue ? i.DueDate.Value.ToShortDateString() : "" }; ``` Later on I tried the following query, which is exactly the same, except I'm querying straight from my dataContext, rather than an element in my first query: ``` var items = from i in dataContext.MyLists select new { i.ID, i.Sector, i.Description, CompleteDate = i.CompleteDate.HasValue ? i.CompleteDate.Value.ToShortDateString() : "", DueDate = i.DueDate.HasValue ? i.DueDate.Value.ToShortDateString() : "" }; ``` The first one runs fine, yet the second query yields a: *Could not translate expression '...' into SQL and could not treat it as a local expression.* If I remove the lines that Format the date, it works fine. If I remove the .HasValue check it also works fine, until there are null values. Any ideas? Anthony
I'd do the SQL part without doing the formatting, then do the formatting on the client side: ``` var items = list.MyItems.Select(item => new { item.ID, item.Sector, item.Description, item.CompleteDate, item.DueDate }) .AsEnumerable() // Don't do the next bit in the DB .Select(item => new { item.ID, item.Sector, item.Description, CompleteDate = FormatDate(CompleteDate), DueDate = FormatDate(DueDate) }); static string FormatDate(DateTime? date) { return date.HasValue ? date.Value.ToShortDateString() : "" } ```
163,184
<p>I need to convert inline css style attributes to their HTML tag equivelants. The solution I have works but runs VERY slowly using the Microsoft .Net Regex namespace and long documents (~40 pages of html). I've tried several variations but with no useful results. I've done a little wrapping around executing the expressions but in the end it's just the built-in regex Replace method that gets called.</p> <p>I'm sure I'm abusing the greediness of the regex but I'm not sure of a way around it to achieve what I want using a single regex.</p> <p>I want to be able to run the following unit tests:</p> <pre><code>[Test] public void TestCleanReplacesFontWeightWithB() { string html = "&lt;font style=\"font-weight:bold\"&gt;Bold Text&lt;/font&gt;"; html = Q4.PrWorkflow.Helper.CleanFormatting(html); Assert.AreEqual("&lt;b&gt;Bold Text&lt;/b&gt;", html); } [Test] public void TestCleanReplacesMultipleAttributesFontWeightWithB() { string html = "&lt;font style=\"font-weight:bold; color: blue; \"&gt;Bold Text&lt;/font&gt;"; html = Q4.PrWorkflow.Helper.CleanFormatting(html); Assert.AreEqual("&lt;b&gt;Bold Text&lt;/b&gt;", html); } [Test] public void TestCleanReplaceAttributesBoldAndUnderlineWithHtml() { string html = "&lt;span style=\"font-weight:bold; color: blue; text-decoration: underline; \"&gt;Bold Text&lt;/span&gt;"; html = Q4.PrWorkflow.Helper.CleanFormatting(html); Assert.AreEqual("&lt;u&gt;&lt;b&gt;Bold Text&lt;/b&gt;&lt;/u&gt;", html); } [Test] public void TestCleanReplaceAttributesBoldUnderlineAndItalicWithHtml() { string html = "&lt;span style=\"font-weight:bold; color: blue; font-style: italic; text-decoration: underline; \"&gt;Bold Text&lt;/span&gt;"; html = Q4.PrWorkflow.Helper.CleanFormatting(html); Assert.AreEqual("&lt;u&gt;&lt;b&gt;&lt;i&gt;Bold Text&lt;/i&gt;&lt;/b&gt;&lt;/u&gt;", html); } [Test] public void TestCleanReplacesFontWeightWithSpaceWithB() { string html = "&lt;font size=\"10\" style=\"font-weight: bold\"&gt;Bold Text&lt;/font&gt;"; html = Q4.PrWorkflow.Helper.CleanFormatting(html); Assert.AreEqual("&lt;b&gt;Bold Text&lt;/b&gt;", html); } </code></pre> <p>The regular expresion I am using to achieve this logic works but is VERY slow. The regex in the c# code looks like this:</p> <pre><code>public static IReplacePattern IncludeInlineItalicToITag(ICleanUpHtmlFactory factory) { return factory.CreateReplacePattern("(&lt;(span|font) .*?style=\".*?font-style:\\s*italic[^&gt;]*&gt;)(.*?)&lt;/\\2&gt;", "$1&lt;i&gt;$3&lt;/i&gt;&lt;/$2&gt;"); } public static IReplacePattern IncludeInlineBoldToBTag(ICleanUpHtmlFactory factory) { return factory.CreateReplacePattern("(&lt;(span|font) .*?style=\".*?font-weight:\\s*bold[^&gt;]*&gt;)(.*?)&lt;/\\2&gt;", "$1&lt;b&gt;$3&lt;/b&gt;&lt;/$2&gt;"); } public static IReplacePattern IncludeInlineUnderlineToUTag(ICleanUpHtmlFactory factory) { return factory.CreateReplacePattern("(&lt;(span|font) .*?style=\".*?text-decoration:\\s*underline[^&gt;]*&gt;)(.*?)&lt;/\\2&gt;", "$1&lt;u&gt;$3&lt;/u&gt;&lt;/$2&gt;"); } </code></pre>
[ { "answer_id": 163211, "author": "Santiago Palladino", "author_id": 12791, "author_profile": "https://Stackoverflow.com/users/12791", "pm_score": 3, "selected": false, "text": "<p>I believe the problem is that if it finds a <code>span</code>|<code>font</code> tag, which has no style attribute defined, it will continue looking for it until the end of the document because of the <code>.\\*?</code>. I haven't tested it, but changing it to <code>[^&gt;]\\*?</code> might improve performance.</p>\n\n<p>Make sure you apply that change for all <code>.\\*?</code> you have; even the one capturing the content between tags (use <code>[^&lt;]\\*?</code> there), because if a file is not well-formed, it will capture up to the next closing tag.</p>\n" }, { "answer_id": 163316, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 0, "selected": false, "text": "<p><s>.NET regular expressions does not support recursive constructs.</s> PCRE does, but that doesn't matter here.</p>\n\n<p>Concider</p>\n\n<pre><code>&lt;font style=\"font-weight: bold;\"&gt; text1 &lt;font color=\"blue\"&gt; text2 &lt;/font&gt; text3 &lt;/font&gt;\n</code></pre>\n\n<p>It would get converted into</p>\n\n<pre><code>&lt;b&gt; text1 &lt;font color=\"blue\"&gt; text2 &lt;/b&gt; text3 &lt;/font&gt;\n</code></pre>\n\n<p>My suggestion would be to use a proper markup parser, and maybe use regexp on the values of the style-tags.</p>\n\n<p><strong>Edit:</strong> Scratch that. It seems .NET has a construct for balanced, recursive patterns. But not as powerful as those in PCRE/perl.</p>\n\n<pre><code>(?&lt;N&gt;content) would push N onto a stack if content matches\n(?&lt;-N&gt;content) would pop N from the stack, if content matches.\n(?(N)yes|no) would match \"yes\" if N is on the stack, otherwise \"no\".\n</code></pre>\n\n<p>See <a href=\"http://weblogs.asp.net/whaggard/archive/2005/02/20/377025.aspx\" rel=\"nofollow noreferrer\">http://weblogs.asp.net/whaggard/archive/2005/02/20/377025.aspx</a> for details.</p>\n" }, { "answer_id": 179920, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 0, "selected": false, "text": "<p>Wild guess: I believe the cost comes from the alternative and the corresponding match.\nYou might want to try to replace:</p>\n\n<pre><code>\"(&lt;(span|font) .*?style=\\\".*?font-style:\\\\s*italic[^&gt;]*&gt;)(.*?)&lt;/\\\\2&gt;\", \"$1&lt;i&gt;$3&lt;/i&gt;&lt;/$2&gt;\"\n</code></pre>\n\n<p>with two separate expressions:</p>\n\n<pre><code>\"(&lt;span .*?style=\\\".*?font-style:\\\\s*italic[^&gt;]*&gt;)(.*?)&lt;/span&gt;\", \"$1&lt;i&gt;$2&lt;/i&gt;&lt;/span&gt;\"\n\"(&lt;font .*?style=\\\".*?font-style:\\\\s*italic[^&gt;]*&gt;)(.*?)&lt;/font&gt;\", \"$1&lt;i&gt;$2&lt;/i&gt;&lt;/font&gt;\"\n</code></pre>\n\n<p>Granted, that double the parsing of the file, but the regex being simpler, with less trackbacks, it might be faster in practice. It is not very nice (repetition of code) but as long as it works...</p>\n\n<p>Funnily, I did something similar (I don't have the code at hand) to clean up HTML generated by a tool, simplifying it so that JavaHelp can understand it... It is one case where regexes against HTML is OK, because it is not a human making mistakes or changing little things which creates the HTML, but a process with well defined patterns.</p>\n" }, { "answer_id": 1237993, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>During testing i found strange behavior. When run regexp in separate thread it runs a lot faster.\nI have sql script that i was spliting to sections from Go to Go using regexp.\nWhen working on this script without using separate thread it last for about 2 minutes. But when using multithreading it last only few secounds.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I need to convert inline css style attributes to their HTML tag equivelants. The solution I have works but runs VERY slowly using the Microsoft .Net Regex namespace and long documents (~40 pages of html). I've tried several variations but with no useful results. I've done a little wrapping around executing the expressions but in the end it's just the built-in regex Replace method that gets called. I'm sure I'm abusing the greediness of the regex but I'm not sure of a way around it to achieve what I want using a single regex. I want to be able to run the following unit tests: ``` [Test] public void TestCleanReplacesFontWeightWithB() { string html = "<font style=\"font-weight:bold\">Bold Text</font>"; html = Q4.PrWorkflow.Helper.CleanFormatting(html); Assert.AreEqual("<b>Bold Text</b>", html); } [Test] public void TestCleanReplacesMultipleAttributesFontWeightWithB() { string html = "<font style=\"font-weight:bold; color: blue; \">Bold Text</font>"; html = Q4.PrWorkflow.Helper.CleanFormatting(html); Assert.AreEqual("<b>Bold Text</b>", html); } [Test] public void TestCleanReplaceAttributesBoldAndUnderlineWithHtml() { string html = "<span style=\"font-weight:bold; color: blue; text-decoration: underline; \">Bold Text</span>"; html = Q4.PrWorkflow.Helper.CleanFormatting(html); Assert.AreEqual("<u><b>Bold Text</b></u>", html); } [Test] public void TestCleanReplaceAttributesBoldUnderlineAndItalicWithHtml() { string html = "<span style=\"font-weight:bold; color: blue; font-style: italic; text-decoration: underline; \">Bold Text</span>"; html = Q4.PrWorkflow.Helper.CleanFormatting(html); Assert.AreEqual("<u><b><i>Bold Text</i></b></u>", html); } [Test] public void TestCleanReplacesFontWeightWithSpaceWithB() { string html = "<font size=\"10\" style=\"font-weight: bold\">Bold Text</font>"; html = Q4.PrWorkflow.Helper.CleanFormatting(html); Assert.AreEqual("<b>Bold Text</b>", html); } ``` The regular expresion I am using to achieve this logic works but is VERY slow. The regex in the c# code looks like this: ``` public static IReplacePattern IncludeInlineItalicToITag(ICleanUpHtmlFactory factory) { return factory.CreateReplacePattern("(<(span|font) .*?style=\".*?font-style:\\s*italic[^>]*>)(.*?)</\\2>", "$1<i>$3</i></$2>"); } public static IReplacePattern IncludeInlineBoldToBTag(ICleanUpHtmlFactory factory) { return factory.CreateReplacePattern("(<(span|font) .*?style=\".*?font-weight:\\s*bold[^>]*>)(.*?)</\\2>", "$1<b>$3</b></$2>"); } public static IReplacePattern IncludeInlineUnderlineToUTag(ICleanUpHtmlFactory factory) { return factory.CreateReplacePattern("(<(span|font) .*?style=\".*?text-decoration:\\s*underline[^>]*>)(.*?)</\\2>", "$1<u>$3</u></$2>"); } ```
I believe the problem is that if it finds a `span`|`font` tag, which has no style attribute defined, it will continue looking for it until the end of the document because of the `.\*?`. I haven't tested it, but changing it to `[^>]\*?` might improve performance. Make sure you apply that change for all `.\*?` you have; even the one capturing the content between tags (use `[^<]\*?` there), because if a file is not well-formed, it will capture up to the next closing tag.
163,207
<p>I need to call a method that accepts a stream argument. The method loads text into the stream, which would normally be a file. I'd like to simply populate a string with the contents of the stream, instead of writing it to a file. How do I do this?</p>
[ { "answer_id": 163217, "author": "user8032", "author_id": 8032, "author_profile": "https://Stackoverflow.com/users/8032", "pm_score": 2, "selected": false, "text": "<p>Look up MemoryStream class</p>\n" }, { "answer_id": 163226, "author": "Wolfwyrd", "author_id": 15570, "author_profile": "https://Stackoverflow.com/users/15570", "pm_score": 3, "selected": false, "text": "<p>Use the StringWriter to act as a stream onto a string:</p>\n\n<pre><code>StringBuilder sb = new StringBuilder();\nStringWriter sw = new StringWriter(sb);\nCallYourMethodWhichWritesToYourStream(sw);\nreturn sb.ToString();\n</code></pre>\n" }, { "answer_id": 163233, "author": "Bryant", "author_id": 10893, "author_profile": "https://Stackoverflow.com/users/10893", "pm_score": 4, "selected": true, "text": "<p>Use a MemoryStream with a StreamReader. Something like:</p>\n\n<pre><code>using (MemoryStream ms = new MemoryStream())\nusing (StreamReader sr = new StreamReader(ms))\n{\n // pass the memory stream to method\n ms.Seek(0, SeekOrigin.Begin); // added from itsmatt\n string s = sr.ReadToEnd();\n}\n</code></pre>\n" }, { "answer_id": 163249, "author": "Tom", "author_id": 24227, "author_profile": "https://Stackoverflow.com/users/24227", "pm_score": 0, "selected": false, "text": "<p>you can do something like:</p>\n\n<pre><code>string s = \"Wahoo!\";\nint n = 452;\n\nusing( Stream stream = new MemoryStream() ) {\n // Write to the stream\n\n byte[] bytes1 = UnicodeEncoding.Unicode.GetBytes(s);\n byte[] bytes2 = BitConverter.GetBytes(n);\n stream.Write(bytes1, 0, bytes1.Length);\n stream.Write(bytes2, 0, bytes2.Length);\n</code></pre>\n" }, { "answer_id": 163329, "author": "itsmatt", "author_id": 7862, "author_profile": "https://Stackoverflow.com/users/7862", "pm_score": 2, "selected": false, "text": "<pre><code>MemoryStream ms = new MemoryStream();\nYourFunc(ms);\nms.Seek(0, SeekOrigin.Begin);\nStreamReader sr = new StreamReader(ms);\nstring mystring = sr.ReadToEnd();\n</code></pre>\n\n<p>is one way to do it.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20625/" ]
I need to call a method that accepts a stream argument. The method loads text into the stream, which would normally be a file. I'd like to simply populate a string with the contents of the stream, instead of writing it to a file. How do I do this?
Use a MemoryStream with a StreamReader. Something like: ``` using (MemoryStream ms = new MemoryStream()) using (StreamReader sr = new StreamReader(ms)) { // pass the memory stream to method ms.Seek(0, SeekOrigin.Begin); // added from itsmatt string s = sr.ReadToEnd(); } ```
163,246
<p>In Oracle, I can re-create a view with a single statement, as shown here:</p> <pre><code>CREATE OR REPLACE VIEW MY_VIEW AS SELECT SOME_FIELD FROM SOME_TABLE WHERE SOME_CONDITIONS </code></pre> <p>As the syntax implies, this will drop the old view and re-create it with whatever definition I've given.</p> <p>Is there an equivalent in MSSQL (SQL Server 2005 or later) that will do the same thing?</p>
[ { "answer_id": 163260, "author": "DaveK", "author_id": 4244, "author_profile": "https://Stackoverflow.com/users/4244", "pm_score": 6, "selected": false, "text": "<p>You can use 'IF EXISTS' to check if the view exists and drop if it does.</p>\n\n<pre>\nIF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.VIEWS\n WHERE TABLE_NAME = 'MyView')\n DROP VIEW MyView\nGO\n\nCREATE VIEW MyView\nAS \n ....\nGO\n</pre>\n" }, { "answer_id": 163283, "author": "Michael Petrotta", "author_id": 23897, "author_profile": "https://Stackoverflow.com/users/23897", "pm_score": 3, "selected": false, "text": "<p>I typically use something like this:</p>\n\n<pre><code>if exists (select * from dbo.sysobjects\n where id = object_id(N'dbo.MyView') and\n OBJECTPROPERTY(id, N'IsView') = 1)\ndrop view dbo.MyView\ngo\ncreate view dbo.MyView [...]\n</code></pre>\n" }, { "answer_id": 163284, "author": "Bryant", "author_id": 10893, "author_profile": "https://Stackoverflow.com/users/10893", "pm_score": 2, "selected": false, "text": "<p>You can use ALTER to update a view, but this is different than the Oracle command since it only works if the view already exists. Probably better off with DaveK's answer since that will always work.</p>\n" }, { "answer_id": 939067, "author": "Tom", "author_id": 13219, "author_profile": "https://Stackoverflow.com/users/13219", "pm_score": 4, "selected": false, "text": "<p>I use:</p>\n\n<pre><code>IF OBJECT_ID('[dbo].[myView]') IS NOT NULL\nDROP VIEW [dbo].[myView]\nGO\nCREATE VIEW [dbo].[myView]\nAS\n</code></pre>\n\n<p>...</p>\n\n<p>Recently I added some utility procedures for this kind of stuff:</p>\n\n<pre><code>CREATE PROCEDURE dbo.DropView\n@ASchema VARCHAR(100),\n@AView VARCHAR(100)\nAS\nBEGIN\n DECLARE @sql VARCHAR(1000);\n IF OBJECT_ID('[' + @ASchema + '].[' + @AView + ']') IS NOT NULL\n BEGIN\n SET @sql = 'DROP VIEW ' + '[' + @ASchema + '].[' + @AView + '] ';\n EXEC(@sql);\n END \nEND\n</code></pre>\n\n<p>So now I write</p>\n\n<pre><code>EXEC dbo.DropView 'mySchema', 'myView'\nGO\nCREATE View myView\n...\nGO\n</code></pre>\n\n<p>I think it makes my changescripts a bit more readable</p>\n" }, { "answer_id": 5184901, "author": "john.da.costa", "author_id": 138921, "author_profile": "https://Stackoverflow.com/users/138921", "pm_score": 8, "selected": true, "text": "<p>The solutions above though they will get the job done do so at the risk of dropping user permissions. I prefer to do my create or replace views or stored procedures as follows.</p>\n\n<pre><code>IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vw_myView]'))\n EXEC sp_executesql N'CREATE VIEW [dbo].[vw_myView] AS SELECT ''This is a code stub which will be replaced by an Alter Statement'' as [code_stub]'\nGO\n\nALTER VIEW [dbo].[vw_myView]\nAS\nSELECT 'This is a code which should be replaced by the real code for your view' as [real_code]\nGO\n</code></pre>\n" }, { "answer_id": 33443738, "author": "Justin Dearing", "author_id": 95195, "author_profile": "https://Stackoverflow.com/users/95195", "pm_score": 3, "selected": false, "text": "<p>As of SQL Server 2016 you have </p>\n\n<pre><code>DROP TABLE IF EXISTS [foo];\n</code></pre>\n\n<p><a href=\"https://msdn.microsoft.com/en-us/library/ms173790.aspx\" rel=\"noreferrer\">MSDN source</a></p>\n" }, { "answer_id": 40707436, "author": "Lukasz Szozda", "author_id": 5070879, "author_profile": "https://Stackoverflow.com/users/5070879", "pm_score": 6, "selected": false, "text": "<p>For reference from <strong><code>SQL Server 2016 SP1+</code></strong> you could use <code>CREATE OR ALTER VIEW</code> syntax.</p>\n<blockquote>\n<p><a href=\"https://msdn.microsoft.com/en-us/library/ms187956.aspx\" rel=\"noreferrer\">MSDN CREATE VIEW</a>:</p>\n<pre><code>CREATE [ OR ALTER ] VIEW [ schema_name . ] view_name [ (column [ ,...n ] ) ] \n[ WITH &lt;view_attribute&gt; [ ,...n ] ] \nAS select_statement \n[ WITH CHECK OPTION ] \n[ ; ]\n</code></pre>\n<p><strong>OR ALTER</strong></p>\n<p>Conditionally alters the view only if it already exists.</p>\n</blockquote>\n<p><strong><a href=\"https://dbfiddle.uk/?rdbms=sqlserver_2017&amp;fiddle=159a876489f078e76c8a0e4cede1295a\" rel=\"noreferrer\">db&lt;&gt;fiddle demo</a></strong></p>\n" }, { "answer_id": 47393102, "author": "Lex", "author_id": 5228885, "author_profile": "https://Stackoverflow.com/users/5228885", "pm_score": 2, "selected": false, "text": "<p>It works fine for me on SQL Server 2017:</p>\n\n<pre><code>USE MSSQLTipsDemo \nGO\nCREATE OR ALTER PROC CreateOrAlterDemo\nAS\nBEGIN\nSELECT TOP 10 * FROM [dbo].[CountryInfoNew]\nEND\nGO\n</code></pre>\n\n<p><a href=\"https://www.mssqltips.com/sqlservertip/4640/new-create-or-alter-statement-in-\" rel=\"nofollow noreferrer\">https://www.mssqltips.com/sqlservertip/4640/new-create-or-alter-statement-in-</a></p>\n" }, { "answer_id": 54666187, "author": "MovGP0", "author_id": 601990, "author_profile": "https://Stackoverflow.com/users/601990", "pm_score": 2, "selected": false, "text": "<p>In SQL Server 2016 (or newer) you can use this: </p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>CREATE OR ALTER VIEW VW_NAMEOFVIEW AS ...\n</code></pre>\n\n<p>In older versions of SQL server you have to use something like</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>DECLARE @script NVARCHAR(MAX) = N'VIEW [dbo].[VW_NAMEOFVIEW] AS ...';\n\nIF NOT EXISTS(SELECT * FROM sys.views WHERE name = 'VW_NAMEOFVIEW')\n-- IF OBJECT_ID('[dbo].[VW_NAMEOFVIEW]') IS NOT NULL\nBEGIN EXEC('CREATE ' + @script) END\nELSE\nBEGIN EXEC('ALTER ' + @script) END\n</code></pre>\n\n<p>Or, if there are no dependencies on the view, you can just drop it and recreate: </p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>IF EXISTS(SELECT * FROM sys.views WHERE name = 'VW_NAMEOFVIEW')\n-- IF OBJECT_ID('[dbo].[VW_NAMEOFVIEW]') IS NOT NULL\nBEGIN \n DROP VIEW [VW_NAMEOFVIEW];\nEND\n\nCREATE VIEW [VW_NAMEOFVIEW] AS ...\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163246", "https://Stackoverflow.com", "https://Stackoverflow.com/users/672/" ]
In Oracle, I can re-create a view with a single statement, as shown here: ``` CREATE OR REPLACE VIEW MY_VIEW AS SELECT SOME_FIELD FROM SOME_TABLE WHERE SOME_CONDITIONS ``` As the syntax implies, this will drop the old view and re-create it with whatever definition I've given. Is there an equivalent in MSSQL (SQL Server 2005 or later) that will do the same thing?
The solutions above though they will get the job done do so at the risk of dropping user permissions. I prefer to do my create or replace views or stored procedures as follows. ``` IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vw_myView]')) EXEC sp_executesql N'CREATE VIEW [dbo].[vw_myView] AS SELECT ''This is a code stub which will be replaced by an Alter Statement'' as [code_stub]' GO ALTER VIEW [dbo].[vw_myView] AS SELECT 'This is a code which should be replaced by the real code for your view' as [real_code] GO ```
163,302
<p>I'm trying to have the modrewrite rules skip the directory <code>vip</code>. I've tried a number of things as you can see below, but to no avail.</p> <pre><code># BEGIN WordPress &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase / #RewriteRule ^vip$ - [PT] RewriteRule ^vip/.$ - [PT] #RewriteCond %{REQUEST_URI} !/vip RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] &lt;/IfModule&gt; # END WordPress </code></pre> <p>How do I get modrewrite to entirely ignore the <code>/vip/</code> directory so that all requests pass directly to the folder?</p> <h3>Update:</h3> <p>As points of clarity:</p> <ul> <li>It's hosted on Dreamhost</li> <li>The folders are within a wordpress directory</li> <li>the /vip/ folder contains a webdav .htaccess etc (though I dont think this is important</li> </ul>
[ { "answer_id": 163401, "author": "Peter Howe", "author_id": 24106, "author_profile": "https://Stackoverflow.com/users/24106", "pm_score": -1, "selected": false, "text": "<p>I'm not sure if I understand your objective, but the following might do what you're after?</p>\n\n<pre><code>RewriteRule ^/vip/(.*)$ /$1?%{QUERY_STRING} [L]\n</code></pre>\n\n<p>This will cause a URL such as <a href=\"http://www.example.com/vip/fred.html\" rel=\"nofollow noreferrer\">http://www.example.com/vip/fred.html</a> to be rewritten without the /vip.</p>\n" }, { "answer_id": 163530, "author": "Patrick McElhaney", "author_id": 437, "author_profile": "https://Stackoverflow.com/users/437", "pm_score": 7, "selected": false, "text": "<p>Try putting this before any other rules.</p>\n\n<pre><code>RewriteRule ^vip - [L,NC] \n</code></pre>\n\n<p>It will match any URI beginning <code>vip</code>. </p>\n\n<ul>\n<li>The <code>-</code> means do nothing. </li>\n<li>The <code>L</code> means this should be last rule; ignore everything following. </li>\n<li>The <code>NC</code> means no-case (so \"VIP\" is also matched).</li>\n</ul>\n\n<p>Note that it matches anything <em>beginning</em> <code>vip</code>. The expression <code>^vip$</code> would match <code>vip</code> but not <code>vip/</code> or <code>vip/index.html</code>. The <code>$</code> may have been your downfall. If you really want to do it right, you might want to go with <code>^vip(/|$)</code> so you don't match <code>vip-page.html</code> </p>\n" }, { "answer_id": 163855, "author": "Jay", "author_id": 20840, "author_profile": "https://Stackoverflow.com/users/20840", "pm_score": 3, "selected": false, "text": "<p>You mentioned you already have a .htaccess file in the directory you want to ignore - you can use </p>\n\n<pre><code>RewriteEngine off\n</code></pre>\n\n<p>In that .htaccess to stop use of mod_rewrite (not sure if you're using mod_rewrite in that folder, if you are then that won't help since you can't turn it off).</p>\n" }, { "answer_id": 273704, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<pre><code>RewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\n</code></pre>\n\n<p>This says if it's an existing file or a directory don't touch it. You should be able to access site.com/vip and no rewrite rule should take place.</p>\n" }, { "answer_id": 2664755, "author": "matdumsa", "author_id": 1775, "author_profile": "https://Stackoverflow.com/users/1775", "pm_score": 2, "selected": false, "text": "<p>I’ve had the same issue using wordpress and found that the issue is linked with not having proper handler for 401 and 403 errors..</p>\n\n<pre><code>RewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\n</code></pre>\n\n<p>These conditions are already supposed not to rewrite the url of existing folders but they don’t do their job for password protected folders. In my case, adding the following two lines to my root .htaccess fixed the problem:</p>\n\n<pre><code>ErrorDocument 401 /misc/myerror.html\nErrorDocument 403 /misc/myerror.html\n</code></pre>\n\n<p>Of course you need to create the /misc/myerror.html,</p>\n" }, { "answer_id": 3435332, "author": "Cody A. Ray", "author_id": 337735, "author_profile": "https://Stackoverflow.com/users/337735", "pm_score": 3, "selected": false, "text": "<p>In summary, the final solution is:</p>\n\n<pre><code>ErrorDocument 401 /misc/myerror.html\nErrorDocument 403 /misc/myerror.html\n\n# BEGIN WordPress\n&lt;IfModule mod_rewrite.c&gt;\nRewriteEngine On\nRewriteBase /\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n&lt;/IfModule&gt;\n\n# END WordPress\n</code></pre>\n\n<p>I posted more about the cause of this problem in my specific situation, involving Wordpress and WebDAV on Dreamhost, which I expect many others to be having on <a href=\"http://codyaray.com/2010/08/wordpress-webdav-and-dreamhost\" rel=\"noreferrer\" title=\"Wordpress, WebDAV, and Dreamhost\">my site</a>.</p>\n" }, { "answer_id": 5136622, "author": "Pat", "author_id": 636920, "author_profile": "https://Stackoverflow.com/users/636920", "pm_score": 2, "selected": false, "text": "<p>This works ...</p>\n\n<pre><code>RewriteRule ^vip - [L,NC]\n</code></pre>\n\n<p>But ensure it is the first rule after </p>\n\n<p>RewriteEngine on</p>\n\n<p>i.e. </p>\n\n<pre><code>ErrorDocument 404 /page-not-found.html\n\nRewriteEngine on\n\nRewriteRule ^vip - [L,NC]\n\nAddType application/x-httpd-php .html .htm\n\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d \n\netc\n</code></pre>\n" }, { "answer_id": 13633771, "author": "Gokul Muralidharan", "author_id": 1618137, "author_profile": "https://Stackoverflow.com/users/1618137", "pm_score": 2, "selected": false, "text": "<pre><code>RewriteCond %{REQUEST_URI} !^pilot/ \n</code></pre>\n\n<p>is the way to do that.</p>\n" }, { "answer_id": 17038150, "author": "ChongFury", "author_id": 2473410, "author_profile": "https://Stackoverflow.com/users/2473410", "pm_score": 3, "selected": false, "text": "<p>Try replacing this part of your code:</p>\n\n<pre>RewriteRule ^vip/.$ - [PT]</pre>\n\n<p>...with the following:</p>\n\n<pre>RewriteCond %{REQUEST_URI} !(vip) [NC]</pre>\n\n<p>That should fix things up.</p>\n" }, { "answer_id": 18157129, "author": "brentonstrine", "author_id": 925897, "author_profile": "https://Stackoverflow.com/users/925897", "pm_score": 3, "selected": false, "text": "<p>The code you are adding, and all answers that are providing Rewrite rules/conditions are useless! The default WordPress code already does everything that you should need it to:</p>\n\n<pre><code>RewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n</code></pre>\n\n<p>Those lines say \"if it's NOT an existing file (<code>-f</code>) or directory (<code>-d</code>), pass it along to WordPress. Adding additional rules, not matter how specific or good they are, is redundant--you should already be covered by the WordPress rules!</p>\n\n<p>So why aren't they working???</p>\n\n<p>The <code>.htaccess</code> in the <code>vip</code> directory is throwing an error. The exact same thing happens if you password protect a directory. </p>\n\n<p>Here is the solution:</p>\n\n<pre><code>ErrorDocument 401 /err.txt\nErrorDocument 403 /err.txt\n</code></pre>\n\n<p>Insert those lines before the WordPress code, and then create /err.txt. This way, when it comes upon your WebDAV (or password protected directory) and fails, it will go to that file, and get caught by the existing default WordPress condition (<code>RewriteCond %{REQUEST_FILENAME} !-f</code>).</p>\n" }, { "answer_id": 26497821, "author": "carlaron", "author_id": 4167867, "author_profile": "https://Stackoverflow.com/users/4167867", "pm_score": 2, "selected": false, "text": "<p>In my case, the answer by <strong>brentonstrine</strong> (and I see <strong>matdumsa</strong> also had the same idea) was the right one... I wanted to up-vote their answers, but being new here, I have no \"reputation\", so I have to write a full answer, in order to emphasize what I think is the real key here.</p>\n\n<p>Several of these answers would successfully stop the WordPress index.php from being used ... but in many cases, the reason for doing this is that there is a real directory with real pages in it that you want to display directly, and the</p>\n\n<pre><code>RewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\n</code></pre>\n\n<p>lines already take care of that, so most of those solutions are a distraction in a case like mine.</p>\n\n<p>The key was <strong>brentonstrine's</strong> insight that the error was a secondary effect, caused by the password-protection inside the directory I was trying to display directly. By putting in the</p>\n\n<pre><code>ErrorDocument 401 /err.txt\nErrorDocument 403 /err.txt\n</code></pre>\n\n<p>lines and creating error pages (I actually created err401.html and err403.html and made more informative error messages) I stopped the 404 response being generated when it couldn't find any page to display for 401 Authentication Required, and then the folder worked as expected... showing an apache login dialog, then the contents of the folder, or on failure, my error 401 page.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163302", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24557/" ]
I'm trying to have the modrewrite rules skip the directory `vip`. I've tried a number of things as you can see below, but to no avail. ``` # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / #RewriteRule ^vip$ - [PT] RewriteRule ^vip/.$ - [PT] #RewriteCond %{REQUEST_URI} !/vip RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress ``` How do I get modrewrite to entirely ignore the `/vip/` directory so that all requests pass directly to the folder? ### Update: As points of clarity: * It's hosted on Dreamhost * The folders are within a wordpress directory * the /vip/ folder contains a webdav .htaccess etc (though I dont think this is important
Try putting this before any other rules. ``` RewriteRule ^vip - [L,NC] ``` It will match any URI beginning `vip`. * The `-` means do nothing. * The `L` means this should be last rule; ignore everything following. * The `NC` means no-case (so "VIP" is also matched). Note that it matches anything *beginning* `vip`. The expression `^vip$` would match `vip` but not `vip/` or `vip/index.html`. The `$` may have been your downfall. If you really want to do it right, you might want to go with `^vip(/|$)` so you don't match `vip-page.html`
163,311
<p>I am using an asp:Calander and I have an object that has a beginning date and an ending date. I need to get all the dates between these two dates and place them in an array so i can then render corresponding dates on the calander with different CSS</p>
[ { "answer_id": 163325, "author": "albertein", "author_id": 23020, "author_profile": "https://Stackoverflow.com/users/23020", "pm_score": 2, "selected": false, "text": "<pre><code>DateTime startDate;\nDateTime endDate;\n\nDateTime currentDate = startDate;\nList&lt;DateTime&gt; dates = new List&lt;DateTime&gt; ();\n\nwhile (true)\n{\n dates.Add (currentDate);\n if (currentDate.Equals (endDate)) break;\n currentDate = currentDate.AddDays (1);\n}\n</code></pre>\n\n<p>It assumes that startDate &lt; than endDate, you get the results on the \"dates\" list</p>\n" }, { "answer_id": 163348, "author": "Kibbee", "author_id": 1862, "author_profile": "https://Stackoverflow.com/users/1862", "pm_score": 2, "selected": true, "text": "<p>I voted up AlbertEin because he gave a good answer, but do you really need a collection to hold all the dates? When you are rendering the day, couldn't you just check if the date is withing the specified range, and then render it differently, no need for a collection. Here's some code to demonstrate</p>\n\n<pre><code>DateTime RangeStartDate,RangeEndDate; //Init as necessary\nDateTime CalendarStartDate,CalendarEndDate; //Init as necessary\nDateTime CurrentDate = CalendarStartDate;\n\nString CSSClass;\n\nwhile (CurrentDate != CalendarEndDate)\n{\n if(CurrentDate &gt;= RangeStartDate &amp;&amp; CurrentDate &lt;= RangeEndDate)\n {\n CSSClass= \"InRange\";\n } \n else\n {\n CSSClass = \"OutOfRange\";\n }\n //Code For rendering calendar goes here\n currentDate = currentDate.AddDays (1);\n}\n</code></pre>\n" }, { "answer_id": 163353, "author": "spoulson", "author_id": 3347, "author_profile": "https://Stackoverflow.com/users/3347", "pm_score": 2, "selected": false, "text": "<pre><code>IEnumerable&lt;DateTime&gt; RangeDays(DateTime RangeStart, DateTime RangeEnd) {\n DateTime EndDate = RangeEnd.Date;\n\n for (DateTime WorkDate = RangeStart.Date; WorkDate &lt;= EndDate; WorkDate = WorkDate.AddDays(1)) {\n yield return WorkDate;\n }\n\n yield break;\n}\n</code></pre>\n\n<p>Untested code... but should work.</p>\n" }, { "answer_id": 163423, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 1, "selected": false, "text": "<pre><code>// inclusive\nvar allDates = Enumerable.Range(0, (endDate - startDate).Days + 1).Select(i =&gt; startDate.AddDays(i));\n\n// exclusive\nvar allDates = Enumerable.Range(1, (endDate - startDate).Days).Select(i =&gt; startDate.AddDays(i));\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163311", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16820/" ]
I am using an asp:Calander and I have an object that has a beginning date and an ending date. I need to get all the dates between these two dates and place them in an array so i can then render corresponding dates on the calander with different CSS
I voted up AlbertEin because he gave a good answer, but do you really need a collection to hold all the dates? When you are rendering the day, couldn't you just check if the date is withing the specified range, and then render it differently, no need for a collection. Here's some code to demonstrate ``` DateTime RangeStartDate,RangeEndDate; //Init as necessary DateTime CalendarStartDate,CalendarEndDate; //Init as necessary DateTime CurrentDate = CalendarStartDate; String CSSClass; while (CurrentDate != CalendarEndDate) { if(CurrentDate >= RangeStartDate && CurrentDate <= RangeEndDate) { CSSClass= "InRange"; } else { CSSClass = "OutOfRange"; } //Code For rendering calendar goes here currentDate = currentDate.AddDays (1); } ```
163,336
<p>Say for example you just queried a database and you recieved this 2D array.</p> <pre><code>$results = array( array('id' =&gt; 1, 'name' =&gt; 'red' , 'spin' =&gt; 1), array('id' =&gt; 2, 'name' =&gt; 'green', 'spin' =&gt; -1), array('id' =&gt; 3, 'name' =&gt; 'blue' , 'spin' =&gt; .5) ); </code></pre> <p>I often find myself writing loops like this.</p> <pre><code>foreach($results as $result) $names[] = $result['name']; </code></pre> <p>My questions is does there exist a way to get this array $names without using a loop? Using callback functions count as using a loop.</p> <p>Here is a more generic example of getting every field.</p> <pre><code>foreach($results as $result) foreach($result as $key =&gt; $value) $fields[$key][] = $value; </code></pre>
[ { "answer_id": 163421, "author": "Devon", "author_id": 13850, "author_profile": "https://Stackoverflow.com/users/13850", "pm_score": 3, "selected": false, "text": "<p>Simply put, no.</p>\n\n<p>You will need to use a loop or a callback function like <a href=\"http://us3.php.net/function.array-walk\" rel=\"noreferrer\">array_walk</a>.</p>\n" }, { "answer_id": 163491, "author": "inxilpro", "author_id": 12549, "author_profile": "https://Stackoverflow.com/users/12549", "pm_score": 4, "selected": false, "text": "<p>I voted @Devon's response up because there really isn't a way to do what you're asking with a built-in function. The best you can do is write your own:</p>\n\n<pre><code>function array_column($array, $column)\n{\n $ret = array();\n foreach ($array as $row) $ret[] = $row[$column];\n return $ret;\n}\n</code></pre>\n" }, { "answer_id": 164045, "author": "Bill", "author_id": 24190, "author_profile": "https://Stackoverflow.com/users/24190", "pm_score": 0, "selected": false, "text": "<p>I think this will do what you want</p>\n\n<p><a href=\"http://us2.php.net/manual/en/function.array-uintersect-uassoc.php\" rel=\"nofollow noreferrer\">array_uintersect_uassoc</a></p>\n\n<p>You would have to do something like this</p>\n\n<pre><code>$results = array(\n array('id' =&gt; 1, 'name' =&gt; 'red' , 'spin' =&gt; 1),\n array('id' =&gt; 2, 'name' =&gt; 'green', 'spin' =&gt; -1),\n array('id' =&gt; 3, 'name' =&gt; 'blue' , 'spin' =&gt; .5)\n);\n$name = array_uintersect_uassoc( $results, array('name' =&gt; 'value') , 0, \"cmpKey\");\nprint_r($name);\n\n//////////////////////////////////////////////////\n// FUNCTIONS\n//////////////////////////////////////////////////\nfunction cmpKey($key1, $key2) {\n if ($key1 == $key2) {\n return 0;\n } else {\n return -1;\n }\n}\n</code></pre>\n\n<p>However, I don't have access to PHP5 so I haven't tested this.</p>\n" }, { "answer_id": 169242, "author": "gradbot", "author_id": 17919, "author_profile": "https://Stackoverflow.com/users/17919", "pm_score": 2, "selected": false, "text": "<p>I did more research on this and found that ruby and prototype both have a function that does this called <a href=\"http://us.php.net/manual/en/function.array-map.php#82256\" rel=\"nofollow noreferrer\">array_pluck</a>,<a href=\"http://groups.google.ca/group/php.notes/browse_thread/thread/0ee4f31c6d98affe\" rel=\"nofollow noreferrer\">2</a>. It's interesting that <code>array_map</code> has a second use that allows you to do the inverse of what i want to do here. I also found a PHP <a href=\"http://www.phpclasses.org/browse/package/3565.html\" rel=\"nofollow noreferrer\">class</a> someone is writing to emulate prototypes manipulation of arrays.</p>\n\n<p>I'm going to do some more digging around and if I don't find anything else I'll work on a patch to submit to the [email protected] mailing list and see if they will add array_pluck.</p>\n" }, { "answer_id": 13561591, "author": "Alexey Petushkov", "author_id": 1258965, "author_profile": "https://Stackoverflow.com/users/1258965", "pm_score": 3, "selected": false, "text": "<p>Starting PHP 5.3, you can use this pretty call with lambda function:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$names = array_map(function ($v){ return $v['name']; }, $results);\n</code></pre>\n\n<p>This will return array sliced by 'name' dimension.</p>\n" }, { "answer_id": 15555791, "author": "Salvador Dali", "author_id": 1090562, "author_profile": "https://Stackoverflow.com/users/1090562", "pm_score": 6, "selected": true, "text": "<p>As of June 20th in PHP-5.5 there is a new function <a href=\"http://us2.php.net/array_column\" rel=\"noreferrer\">array_column</a></p>\n\n<p>For example:</p>\n\n<pre><code>$records = array(\n array(\n 'id' =&gt; 2135,\n 'first_name' =&gt; 'John',\n 'last_name' =&gt; 'Doe'\n ),\n array(\n 'id' =&gt; 3245,\n 'first_name' =&gt; 'Sally',\n 'last_name' =&gt; 'Smith'\n ),\n array(\n 'id' =&gt; 5342,\n 'first_name' =&gt; 'Jane',\n 'last_name' =&gt; 'Jones'\n ),\n array(\n 'id' =&gt; 5623,\n 'first_name' =&gt; 'Peter',\n 'last_name' =&gt; 'Doe'\n )\n);\n\n\n$firstNames = array_column($records, 'first_name');\nprint_r($firstNames);\n</code></pre>\n\n<p>Will return </p>\n\n<pre><code>Array\n(\n [0] =&gt; John\n [1] =&gt; Sally\n [2] =&gt; Jane\n [3] =&gt; Peter\n)\n</code></pre>\n\n<p>There are even more examples in the above mentioned link.</p>\n" }, { "answer_id": 15645399, "author": "yokototo", "author_id": 2213030, "author_profile": "https://Stackoverflow.com/users/2213030", "pm_score": 0, "selected": false, "text": "<p>You could do:</p>\n\n<pre><code>$tmp = array_flip($names);\n$names = array_keys($tmp);\n</code></pre>\n" }, { "answer_id": 19188062, "author": "MirroredFate", "author_id": 771665, "author_profile": "https://Stackoverflow.com/users/771665", "pm_score": 2, "selected": false, "text": "<p>For those of you that cannot upgrade to <code>PHP5.5</code> right now and need this function, here is an implementation of <code>array_column</code>.</p>\n\n<pre><code>function array_column($array, $column){\n $a2 = array();\n array_map(function ($a1) use ($column, &amp;$a2){\n array_push($a2, $a1[$column]);\n }, $array);\n return $a2;\n}\n</code></pre>\n" }, { "answer_id": 24616520, "author": "JohnK", "author_id": 1431728, "author_profile": "https://Stackoverflow.com/users/1431728", "pm_score": 1, "selected": false, "text": "<p>If you are running a version of PHP before 5.5 and <code>array_column()</code>, you can use the official replacement in plain PHP:</p>\n\n<p><a href=\"https://github.com/ramsey/array_column\" rel=\"nofollow\">https://github.com/ramsey/array_column</a></p>\n" }, { "answer_id": 25239265, "author": "Keshav Kalra", "author_id": 1746436, "author_profile": "https://Stackoverflow.com/users/1746436", "pm_score": 0, "selected": false, "text": "<p>This is fast function alternative of array_column()</p>\n\n<pre><code>if(!function_exists('array_column')) {\n function array_column($element_name) {\n $ele = array_map(function($element) {\n return $element[$element_name];\n }, $a);\n return $ele;\n }\n}\n</code></pre>\n" }, { "answer_id": 70503573, "author": "Juan Carlos Constantine", "author_id": 3083631, "author_profile": "https://Stackoverflow.com/users/3083631", "pm_score": 0, "selected": false, "text": "<p>other alternative</p>\n<pre><code> function transpose(array $array): array\n {\n $out = array();\n foreach ($array as $rowkey =&gt; $row) {\n foreach ($row as $colkey =&gt; $col) {\n $out[$colkey][$rowkey] = $col;\n }\n }\n return $out;\n }\n\n function filter_columns(array $arr, string ...$columns): array\n {\n return array_intersect_key($arr, array_flip($columns));\n }\n</code></pre>\n<p>test</p>\n<pre><code>$results = array(\n array('id' =&gt; 1, 'name' =&gt; 'red' , 'spin' =&gt; 1),\n array('id' =&gt; 2, 'name' =&gt; 'green', 'spin' =&gt; -1),\n array('id' =&gt; 3, 'name' =&gt; 'blue' , 'spin' =&gt; .5)\n);\n\n var_dump(filter_columns(transpose($results),'name'));\n var_dump(filter_columns(transpose($results),'id','name'));\n var_dump(filter_columns(transpose($results),'id','spin'));\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17919/" ]
Say for example you just queried a database and you recieved this 2D array. ``` $results = array( array('id' => 1, 'name' => 'red' , 'spin' => 1), array('id' => 2, 'name' => 'green', 'spin' => -1), array('id' => 3, 'name' => 'blue' , 'spin' => .5) ); ``` I often find myself writing loops like this. ``` foreach($results as $result) $names[] = $result['name']; ``` My questions is does there exist a way to get this array $names without using a loop? Using callback functions count as using a loop. Here is a more generic example of getting every field. ``` foreach($results as $result) foreach($result as $key => $value) $fields[$key][] = $value; ```
As of June 20th in PHP-5.5 there is a new function [array\_column](http://us2.php.net/array_column) For example: ``` $records = array( array( 'id' => 2135, 'first_name' => 'John', 'last_name' => 'Doe' ), array( 'id' => 3245, 'first_name' => 'Sally', 'last_name' => 'Smith' ), array( 'id' => 5342, 'first_name' => 'Jane', 'last_name' => 'Jones' ), array( 'id' => 5623, 'first_name' => 'Peter', 'last_name' => 'Doe' ) ); $firstNames = array_column($records, 'first_name'); print_r($firstNames); ``` Will return ``` Array ( [0] => John [1] => Sally [2] => Jane [3] => Peter ) ``` There are even more examples in the above mentioned link.
163,355
<p>I'm on SQL Server 2005 and I am getting an error which I am pretty sure should not be getting.</p> <pre><code>Msg 512, Level 16, State 1, Procedure spGetSavedSearchesByAdminUser, Line 8 Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, &lt;, &lt;= , &gt;, &gt;= or when the subquery is used as an expression. </code></pre> <p>I am following the example# B on <a href="http://msdn.microsoft.com/en-us/library/ms177682(SQL.90).aspx" rel="nofollow noreferrer">this</a> MSDN link.</p> <p>My stored proc code is as follows. I can simplify it for the sake of this post if you request so:</p> <pre><code>ALTER PROCEDURE [dbo].[spGetSavedSearchesByAdminUser] @strUserName varchar(50) ,@bitQuickSearch bit = 0 AS BEGIN SELECT [intSearchID] ,strSearchTypeCode ,[strSearchName] FROM [tblAdminSearches] WHERE strUserName = @strUserName AND strSearchTypeCode IN ( CASE @bitQuickSearch WHEN 1 THEN 'Quick' ELSE (SELECT strSearchTypeCode FROM tblAdvanceSearchTypes) END ) ORDER BY strSearchName END </code></pre> <p>I have checked there is no datatype mismatch between the resultset from the subquery and the strSearchTypeCode the subquery result is compared with.</p> <p>I see no reason why this should not work. If you have any clues then please let me know.</p>
[ { "answer_id": 163371, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 2, "selected": false, "text": "<p>I don't know that you can use the CASE statement inside of an IN clause like that. I'd suggest rewriting that bit to:</p>\n\n<pre><code>WHERE strUserName = @strUserName AND (\n (@bitQuickSearch = 1 AND strSearchTypeCode = 'Quick')\n OR\n (strSearchTypeCode IN (SELECT strSearchTypeCode FROM tblAdvanceSearchTypes))\n)\n</code></pre>\n\n<p>or, if you really like the style you got there:</p>\n\n<pre><code>WHERE strUserName = @strUserName \n AND strSearchTypeCode IN (\n SELECT CASE @bitQuickSearch WHEN 1 THEN 'Quick' ELSE strSearchTypeCode END\n FROM tblAdvanceSearchTypes\n )\n</code></pre>\n\n<p>In general, SQL should be smart to smart enough to optimize away the table if @bitQuickSearch = 1. But, I'd check the query plan just to be sure (trust, but verify).</p>\n" }, { "answer_id": 163373, "author": "Milan Babuškov", "author_id": 14690, "author_profile": "https://Stackoverflow.com/users/14690", "pm_score": 2, "selected": false, "text": "<p>It seems to me that this SELECT:</p>\n\n<pre><code>SELECT strSearchTypeCode FROM tblAdvanceSearchTypes\n</code></pre>\n\n<p>returns multiple rows, and that is your problem. You can rewrite it to be:</p>\n\n<pre><code>SELECT TOP 1 strSearchTypeCode FROM tblAdvanceSearchTypes\n</code></pre>\n" }, { "answer_id": 163377, "author": "finnw", "author_id": 12048, "author_profile": "https://Stackoverflow.com/users/12048", "pm_score": 3, "selected": true, "text": "<p>Try rearranging the query so that the boolean expression occurs inside the subselect, e.g.</p>\n\n<pre><code>ALTER PROCEDURE [dbo].[spGetSavedSearchesByAdminUser] \n @strUserName varchar(50) \n ,@bitQuickSearch bit = 0\nAS\n\nBEGIN\n\n SELECT [intSearchID] ,strSearchTypeCode ,[strSearchName]\n FROM [tblAdminSearches] \n\n WHERE \n strUserName = @strUserName\n AND \n strSearchTypeCode \n IN (SELECT strSearchTypeCode FROM tblAdvanceSearchTypes where @bitQuickSearch=0\n UNION\n SELECT 'Quick' AS strSearchTypeCode WHERE @bitQuickSearch=1)\n\n ORDER BY strSearchName\nEND\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/262613/" ]
I'm on SQL Server 2005 and I am getting an error which I am pretty sure should not be getting. ``` Msg 512, Level 16, State 1, Procedure spGetSavedSearchesByAdminUser, Line 8 Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression. ``` I am following the example# B on [this](http://msdn.microsoft.com/en-us/library/ms177682(SQL.90).aspx) MSDN link. My stored proc code is as follows. I can simplify it for the sake of this post if you request so: ``` ALTER PROCEDURE [dbo].[spGetSavedSearchesByAdminUser] @strUserName varchar(50) ,@bitQuickSearch bit = 0 AS BEGIN SELECT [intSearchID] ,strSearchTypeCode ,[strSearchName] FROM [tblAdminSearches] WHERE strUserName = @strUserName AND strSearchTypeCode IN ( CASE @bitQuickSearch WHEN 1 THEN 'Quick' ELSE (SELECT strSearchTypeCode FROM tblAdvanceSearchTypes) END ) ORDER BY strSearchName END ``` I have checked there is no datatype mismatch between the resultset from the subquery and the strSearchTypeCode the subquery result is compared with. I see no reason why this should not work. If you have any clues then please let me know.
Try rearranging the query so that the boolean expression occurs inside the subselect, e.g. ``` ALTER PROCEDURE [dbo].[spGetSavedSearchesByAdminUser] @strUserName varchar(50) ,@bitQuickSearch bit = 0 AS BEGIN SELECT [intSearchID] ,strSearchTypeCode ,[strSearchName] FROM [tblAdminSearches] WHERE strUserName = @strUserName AND strSearchTypeCode IN (SELECT strSearchTypeCode FROM tblAdvanceSearchTypes where @bitQuickSearch=0 UNION SELECT 'Quick' AS strSearchTypeCode WHERE @bitQuickSearch=1) ORDER BY strSearchName END ```
163,360
<p>I use RegexBuddy while working with regular expressions. From its library I copied the regular expression to match URLs. I tested successfully within RegexBuddy. However, when I copied it as Java <code>String</code> flavor and pasted it into Java code, it does not work. The following class prints <code>false</code>: </p> <pre><code>public class RegexFoo { public static void main(String[] args) { String regex = "\\b(https?|ftp|file)://[-A-Z0-9+&amp;@#/%?=~_|!:,.;]*[-A-Z0-9+&amp;@#/%=~_|]"; String text = "http://google.com"; System.out.println(IsMatch(text,regex)); } private static boolean IsMatch(String s, String pattern) { try { Pattern patt = Pattern.compile(pattern); Matcher matcher = patt.matcher(s); return matcher.matches(); } catch (RuntimeException e) { return false; } } } </code></pre> <p>Does anyone know what I am doing wrong?</p>
[ { "answer_id": 163398, "author": "TomC", "author_id": 13183, "author_profile": "https://Stackoverflow.com/users/13183", "pm_score": 8, "selected": true, "text": "<p>Try the following regex string instead. Your test was probably done in a case-sensitive manner. I have added the lowercase alphas as well as a proper string beginning placeholder.</p>\n\n<pre><code>String regex = \"^(https?|ftp|file)://[-a-zA-Z0-9+&amp;@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&amp;@#/%=~_|]\";\n</code></pre>\n\n<p>This works too:</p>\n\n<pre><code>String regex = \"\\\\b(https?|ftp|file)://[-a-zA-Z0-9+&amp;@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&amp;@#/%=~_|]\";\n</code></pre>\n\n<p>Note:</p>\n\n<pre><code>String regex = \"&lt;\\\\b(https?|ftp|file)://[-a-zA-Z0-9+&amp;@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&amp;@#/%=~_|]&gt;\"; // matches &lt;http://google.com&gt;\n\nString regex = \"&lt;^(https?|ftp|file)://[-a-zA-Z0-9+&amp;@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&amp;@#/%=~_|]&gt;\"; // does not match &lt;http://google.com&gt;\n</code></pre>\n" }, { "answer_id": 163410, "author": "billjamesdev", "author_id": 13824, "author_profile": "https://Stackoverflow.com/users/13824", "pm_score": 6, "selected": false, "text": "<p>I'll try a standard \"Why are you doing it this way?\" answer... Do you know about <code>java.net.URL</code>?</p>\n\n<pre><code>URL url = new URL(stringURL);\n</code></pre>\n\n<p>The above will throw a <code>MalformedURLException</code> if it can't parse the URL.</p>\n" }, { "answer_id": 163539, "author": "Sergio del Amo", "author_id": 2138, "author_profile": "https://Stackoverflow.com/users/2138", "pm_score": 2, "selected": false, "text": "<p>This works too:</p>\n\n<pre><code>String regex = \"\\\\b(https?|ftp|file)://[-a-zA-Z0-9+&amp;@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&amp;@#/%=~_|]\";\n</code></pre>\n\n<p>Note: </p>\n\n<pre><code>String regex = \"&lt;\\\\b(https?|ftp|file)://[-a-zA-Z0-9+&amp;@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&amp;@#/%=~_|]&gt;\"; // matches &lt;http://google.com&gt;\n\nString regex = \"&lt;^(https?|ftp|file)://[-a-zA-Z0-9+&amp;@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&amp;@#/%=~_|]&gt;\"; // does not match &lt;http://google.com&gt;\n</code></pre>\n\n<p>So probably the first one is more useful for general use. </p>\n" }, { "answer_id": 275997, "author": "Jan Goyvaerts", "author_id": 33358, "author_profile": "https://Stackoverflow.com/users/33358", "pm_score": 0, "selected": false, "text": "<p>When using regular expressions from RegexBuddy's library, make sure to use the same matching modes in your own code as the regex from the library. If you generate a source code snippet on the Use tab, RegexBuddy will automatically set the correct matching options in the source code snippet. If you copy/paste the regex, you have to do that yourself.</p>\n\n<p>In this case, as others pointed out, you missed the case insensitivity option.</p>\n" }, { "answer_id": 14426010, "author": "Fuad Efendi", "author_id": 1748983, "author_profile": "https://Stackoverflow.com/users/1748983", "pm_score": 2, "selected": false, "text": "<p>The problem with all suggested approaches: all RegEx is <strong>validating</strong></p>\n\n<p>All RegEx -based code is over-engineered: it will find only valid URLs! As a sample, it will ignore anything starting with \"http://\" and having non-ASCII characters inside.</p>\n\n<p>Even more: I have encountered 1-2-seconds processing times (single-threaded, dedicated) with Java RegEx package (filtering Email addresses from text) for very small and simple sentences, nothing specific; possibly bug in Java 6 RegEx...</p>\n\n<p>Simplest/Fastest solution would be to use StringTokenizer to split text into tokens, to remove tokens starting with \"http://\" etc., and to concatenate tokens into text again.</p>\n\n<p>If you want to filter Emails from text (because later on you will do NLP staff etc) - just remove all tokens containing \"@\" inside.</p>\n\n<p>This is simple text where RegEx of Java 6 fails. Try it in divverent variants of Java. It takes about 1000 milliseconds per RegEx call, in a long running single threaded test application:</p>\n\n<pre><code>pattern = Pattern.compile(\"[A-Za-z0-9](([_\\\\.\\\\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\\\\.\\\\-]?[a-zA-Z0-9]+)*)\\\\.([A-Za-z]{2,})\", Pattern.CASE_INSENSITIVE);\n\n\"Avalanna is such a sweet little girl! It would b heartbreaking if cancer won. She's so precious! #BeliebersPrayForAvalanna\");\n\"@AndySamuels31 Hahahahahahahahahhaha lol, you don't look like a girl hahahahhaahaha, you are... sexy.\";\n</code></pre>\n\n<p>Do not rely on regular expressions if you only need to filter words with \"@\", \"http://\", \"ftp://\", \"mailto:\"; it is huge engineering overhead. </p>\n\n<p>If you really want to use RegEx with Java, try <a href=\"http://www.brics.dk/automaton/\" rel=\"nofollow noreferrer\">Automaton</a></p>\n" }, { "answer_id": 18915455, "author": "Kamil Lelonek", "author_id": 1313175, "author_profile": "https://Stackoverflow.com/users/1313175", "pm_score": 7, "selected": false, "text": "<p>The best way to do it now is:</p>\n\n<pre><code>android.util.Patterns.WEB_URL.matcher(linkUrl).matches();\n</code></pre>\n\n<p>EDIT: Code of <code>Patterns</code> from <a href=\"https://github.com/android/platform_frameworks_base/blob/master/core/java/android/util/Patterns.java\" rel=\"noreferrer\">https://github.com/android/platform_frameworks_base/blob/master/core/java/android/util/Patterns.java</a> :</p>\n\n<pre><code>/*\n * Copyright (C) 2007 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage android.util;\n\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\n/**\n * Commonly used regular expression patterns.\n */\npublic class Patterns {\n /**\n * Regular expression to match all IANA top-level domains.\n * List accurate as of 2011/07/18. List taken from:\n * http://data.iana.org/TLD/tlds-alpha-by-domain.txt\n * This pattern is auto-generated by frameworks/ex/common/tools/make-iana-tld-pattern.py\n *\n * @deprecated Due to the recent profileration of gTLDs, this API is\n * expected to become out-of-date very quickly. Therefore it is now\n * deprecated.\n */\n @Deprecated\n public static final String TOP_LEVEL_DOMAIN_STR =\n \"((aero|arpa|asia|a[cdefgilmnoqrstuwxz])\"\n + \"|(biz|b[abdefghijmnorstvwyz])\"\n + \"|(cat|com|coop|c[acdfghiklmnoruvxyz])\"\n + \"|d[ejkmoz]\"\n + \"|(edu|e[cegrstu])\"\n + \"|f[ijkmor]\"\n + \"|(gov|g[abdefghilmnpqrstuwy])\"\n + \"|h[kmnrtu]\"\n + \"|(info|int|i[delmnoqrst])\"\n + \"|(jobs|j[emop])\"\n + \"|k[eghimnprwyz]\"\n + \"|l[abcikrstuvy]\"\n + \"|(mil|mobi|museum|m[acdeghklmnopqrstuvwxyz])\"\n + \"|(name|net|n[acefgilopruz])\"\n + \"|(org|om)\"\n + \"|(pro|p[aefghklmnrstwy])\"\n + \"|qa\"\n + \"|r[eosuw]\"\n + \"|s[abcdeghijklmnortuvyz]\"\n + \"|(tel|travel|t[cdfghjklmnoprtvwz])\"\n + \"|u[agksyz]\"\n + \"|v[aceginu]\"\n + \"|w[fs]\"\n + \"|(\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae|\\u0438\\u0441\\u043f\\u044b\\u0442\\u0430\\u043d\\u0438\\u0435|\\u0440\\u0444|\\u0441\\u0440\\u0431|\\u05d8\\u05e2\\u05e1\\u05d8|\\u0622\\u0632\\u0645\\u0627\\u06cc\\u0634\\u06cc|\\u0625\\u062e\\u062a\\u0628\\u0627\\u0631|\\u0627\\u0644\\u0627\\u0631\\u062f\\u0646|\\u0627\\u0644\\u062c\\u0632\\u0627\\u0626\\u0631|\\u0627\\u0644\\u0633\\u0639\\u0648\\u062f\\u064a\\u0629|\\u0627\\u0644\\u0645\\u063a\\u0631\\u0628|\\u0627\\u0645\\u0627\\u0631\\u0627\\u062a|\\u0628\\u06be\\u0627\\u0631\\u062a|\\u062a\\u0648\\u0646\\u0633|\\u0633\\u0648\\u0631\\u064a\\u0629|\\u0641\\u0644\\u0633\\u0637\\u064a\\u0646|\\u0642\\u0637\\u0631|\\u0645\\u0635\\u0631|\\u092a\\u0930\\u0940\\u0915\\u094d\\u0937\\u093e|\\u092d\\u093e\\u0930\\u0924|\\u09ad\\u09be\\u09b0\\u09a4|\\u0a2d\\u0a3e\\u0a30\\u0a24|\\u0aad\\u0abe\\u0ab0\\u0aa4|\\u0b87\\u0ba8\\u0bcd\\u0ba4\\u0bbf\\u0baf\\u0bbe|\\u0b87\\u0bb2\\u0b99\\u0bcd\\u0b95\\u0bc8|\\u0b9a\\u0bbf\\u0b99\\u0bcd\\u0b95\\u0baa\\u0bcd\\u0baa\\u0bc2\\u0bb0\\u0bcd|\\u0baa\\u0bb0\\u0bbf\\u0b9f\\u0bcd\\u0b9a\\u0bc8|\\u0c2d\\u0c3e\\u0c30\\u0c24\\u0c4d|\\u0dbd\\u0d82\\u0d9a\\u0dcf|\\u0e44\\u0e17\\u0e22|\\u30c6\\u30b9\\u30c8|\\u4e2d\\u56fd|\\u4e2d\\u570b|\\u53f0\\u6e7e|\\u53f0\\u7063|\\u65b0\\u52a0\\u5761|\\u6d4b\\u8bd5|\\u6e2c\\u8a66|\\u9999\\u6e2f|\\ud14c\\uc2a4\\ud2b8|\\ud55c\\uad6d|xn\\\\-\\\\-0zwm56d|xn\\\\-\\\\-11b5bs3a9aj6g|xn\\\\-\\\\-3e0b707e|xn\\\\-\\\\-45brj9c|xn\\\\-\\\\-80akhbyknj4f|xn\\\\-\\\\-90a3ac|xn\\\\-\\\\-9t4b11yi5a|xn\\\\-\\\\-clchc0ea0b2g2a9gcd|xn\\\\-\\\\-deba0ad|xn\\\\-\\\\-fiqs8s|xn\\\\-\\\\-fiqz9s|xn\\\\-\\\\-fpcrj9c3d|xn\\\\-\\\\-fzc2c9e2c|xn\\\\-\\\\-g6w251d|xn\\\\-\\\\-gecrj9c|xn\\\\-\\\\-h2brj9c|xn\\\\-\\\\-hgbk6aj7f53bba|xn\\\\-\\\\-hlcj6aya9esc7a|xn\\\\-\\\\-j6w193g|xn\\\\-\\\\-jxalpdlp|xn\\\\-\\\\-kgbechtv|xn\\\\-\\\\-kprw13d|xn\\\\-\\\\-kpry57d|xn\\\\-\\\\-lgbbat1ad8j|xn\\\\-\\\\-mgbaam7a8h|xn\\\\-\\\\-mgbayh7gpa|xn\\\\-\\\\-mgbbh1a71e|xn\\\\-\\\\-mgbc0a9azcg|xn\\\\-\\\\-mgberp4a5d4ar|xn\\\\-\\\\-o3cw4h|xn\\\\-\\\\-ogbpf8fl|xn\\\\-\\\\-p1ai|xn\\\\-\\\\-pgbs0dh|xn\\\\-\\\\-s9brj9c|xn\\\\-\\\\-wgbh1c|xn\\\\-\\\\-wgbl6a|xn\\\\-\\\\-xkc2al3hye2a|xn\\\\-\\\\-xkc2dl3a5ee0h|xn\\\\-\\\\-yfro4i67o|xn\\\\-\\\\-ygbi2ammx|xn\\\\-\\\\-zckzah|xxx)\"\n + \"|y[et]\"\n + \"|z[amw])\";\n\n /**\n * Regular expression pattern to match all IANA top-level domains.\n * @deprecated This API is deprecated. See {@link #TOP_LEVEL_DOMAIN_STR}.\n */\n @Deprecated\n public static final Pattern TOP_LEVEL_DOMAIN =\n Pattern.compile(TOP_LEVEL_DOMAIN_STR);\n\n /**\n * Regular expression to match all IANA top-level domains for WEB_URL.\n * List accurate as of 2011/07/18. List taken from:\n * http://data.iana.org/TLD/tlds-alpha-by-domain.txt\n * This pattern is auto-generated by frameworks/ex/common/tools/make-iana-tld-pattern.py\n *\n * @deprecated This API is deprecated. See {@link #TOP_LEVEL_DOMAIN_STR}.\n */\n @Deprecated\n public static final String TOP_LEVEL_DOMAIN_STR_FOR_WEB_URL =\n \"(?:\"\n + \"(?:aero|arpa|asia|a[cdefgilmnoqrstuwxz])\"\n + \"|(?:biz|b[abdefghijmnorstvwyz])\"\n + \"|(?:cat|com|coop|c[acdfghiklmnoruvxyz])\"\n + \"|d[ejkmoz]\"\n + \"|(?:edu|e[cegrstu])\"\n + \"|f[ijkmor]\"\n + \"|(?:gov|g[abdefghilmnpqrstuwy])\"\n + \"|h[kmnrtu]\"\n + \"|(?:info|int|i[delmnoqrst])\"\n + \"|(?:jobs|j[emop])\"\n + \"|k[eghimnprwyz]\"\n + \"|l[abcikrstuvy]\"\n + \"|(?:mil|mobi|museum|m[acdeghklmnopqrstuvwxyz])\"\n + \"|(?:name|net|n[acefgilopruz])\"\n + \"|(?:org|om)\"\n + \"|(?:pro|p[aefghklmnrstwy])\"\n + \"|qa\"\n + \"|r[eosuw]\"\n + \"|s[abcdeghijklmnortuvyz]\"\n + \"|(?:tel|travel|t[cdfghjklmnoprtvwz])\"\n + \"|u[agksyz]\"\n + \"|v[aceginu]\"\n + \"|w[fs]\"\n + \"|(?:\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae|\\u0438\\u0441\\u043f\\u044b\\u0442\\u0430\\u043d\\u0438\\u0435|\\u0440\\u0444|\\u0441\\u0440\\u0431|\\u05d8\\u05e2\\u05e1\\u05d8|\\u0622\\u0632\\u0645\\u0627\\u06cc\\u0634\\u06cc|\\u0625\\u062e\\u062a\\u0628\\u0627\\u0631|\\u0627\\u0644\\u0627\\u0631\\u062f\\u0646|\\u0627\\u0644\\u062c\\u0632\\u0627\\u0626\\u0631|\\u0627\\u0644\\u0633\\u0639\\u0648\\u062f\\u064a\\u0629|\\u0627\\u0644\\u0645\\u063a\\u0631\\u0628|\\u0627\\u0645\\u0627\\u0631\\u0627\\u062a|\\u0628\\u06be\\u0627\\u0631\\u062a|\\u062a\\u0648\\u0646\\u0633|\\u0633\\u0648\\u0631\\u064a\\u0629|\\u0641\\u0644\\u0633\\u0637\\u064a\\u0646|\\u0642\\u0637\\u0631|\\u0645\\u0635\\u0631|\\u092a\\u0930\\u0940\\u0915\\u094d\\u0937\\u093e|\\u092d\\u093e\\u0930\\u0924|\\u09ad\\u09be\\u09b0\\u09a4|\\u0a2d\\u0a3e\\u0a30\\u0a24|\\u0aad\\u0abe\\u0ab0\\u0aa4|\\u0b87\\u0ba8\\u0bcd\\u0ba4\\u0bbf\\u0baf\\u0bbe|\\u0b87\\u0bb2\\u0b99\\u0bcd\\u0b95\\u0bc8|\\u0b9a\\u0bbf\\u0b99\\u0bcd\\u0b95\\u0baa\\u0bcd\\u0baa\\u0bc2\\u0bb0\\u0bcd|\\u0baa\\u0bb0\\u0bbf\\u0b9f\\u0bcd\\u0b9a\\u0bc8|\\u0c2d\\u0c3e\\u0c30\\u0c24\\u0c4d|\\u0dbd\\u0d82\\u0d9a\\u0dcf|\\u0e44\\u0e17\\u0e22|\\u30c6\\u30b9\\u30c8|\\u4e2d\\u56fd|\\u4e2d\\u570b|\\u53f0\\u6e7e|\\u53f0\\u7063|\\u65b0\\u52a0\\u5761|\\u6d4b\\u8bd5|\\u6e2c\\u8a66|\\u9999\\u6e2f|\\ud14c\\uc2a4\\ud2b8|\\ud55c\\uad6d|xn\\\\-\\\\-0zwm56d|xn\\\\-\\\\-11b5bs3a9aj6g|xn\\\\-\\\\-3e0b707e|xn\\\\-\\\\-45brj9c|xn\\\\-\\\\-80akhbyknj4f|xn\\\\-\\\\-90a3ac|xn\\\\-\\\\-9t4b11yi5a|xn\\\\-\\\\-clchc0ea0b2g2a9gcd|xn\\\\-\\\\-deba0ad|xn\\\\-\\\\-fiqs8s|xn\\\\-\\\\-fiqz9s|xn\\\\-\\\\-fpcrj9c3d|xn\\\\-\\\\-fzc2c9e2c|xn\\\\-\\\\-g6w251d|xn\\\\-\\\\-gecrj9c|xn\\\\-\\\\-h2brj9c|xn\\\\-\\\\-hgbk6aj7f53bba|xn\\\\-\\\\-hlcj6aya9esc7a|xn\\\\-\\\\-j6w193g|xn\\\\-\\\\-jxalpdlp|xn\\\\-\\\\-kgbechtv|xn\\\\-\\\\-kprw13d|xn\\\\-\\\\-kpry57d|xn\\\\-\\\\-lgbbat1ad8j|xn\\\\-\\\\-mgbaam7a8h|xn\\\\-\\\\-mgbayh7gpa|xn\\\\-\\\\-mgbbh1a71e|xn\\\\-\\\\-mgbc0a9azcg|xn\\\\-\\\\-mgberp4a5d4ar|xn\\\\-\\\\-o3cw4h|xn\\\\-\\\\-ogbpf8fl|xn\\\\-\\\\-p1ai|xn\\\\-\\\\-pgbs0dh|xn\\\\-\\\\-s9brj9c|xn\\\\-\\\\-wgbh1c|xn\\\\-\\\\-wgbl6a|xn\\\\-\\\\-xkc2al3hye2a|xn\\\\-\\\\-xkc2dl3a5ee0h|xn\\\\-\\\\-yfro4i67o|xn\\\\-\\\\-ygbi2ammx|xn\\\\-\\\\-zckzah|xxx)\"\n + \"|y[et]\"\n + \"|z[amw]))\";\n\n /**\n * Good characters for Internationalized Resource Identifiers (IRI).\n * This comprises most common used Unicode characters allowed in IRI\n * as detailed in RFC 3987.\n * Specifically, those two byte Unicode characters are not included.\n */\n public static final String GOOD_IRI_CHAR =\n \"a-zA-Z0-9\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF\";\n\n public static final Pattern IP_ADDRESS\n = Pattern.compile(\n \"((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\\\.(25[0-5]|2[0-4]\"\n + \"[0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\\\.(25[0-5]|2[0-4][0-9]|[0-1]\"\n + \"[0-9]{2}|[1-9][0-9]|[1-9]|0)\\\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}\"\n + \"|[1-9][0-9]|[0-9]))\");\n\n /**\n * RFC 1035 Section 2.3.4 limits the labels to a maximum 63 octets.\n */\n private static final String IRI\n = \"[\" + GOOD_IRI_CHAR + \"]([\" + GOOD_IRI_CHAR + \"\\\\-]{0,61}[\" + GOOD_IRI_CHAR + \"]){0,1}\";\n\n private static final String GOOD_GTLD_CHAR =\n \"a-zA-Z\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF\";\n private static final String GTLD = \"[\" + GOOD_GTLD_CHAR + \"]{2,63}\";\n private static final String HOST_NAME = \"(\" + IRI + \"\\\\.)+\" + GTLD;\n\n public static final Pattern DOMAIN_NAME\n = Pattern.compile(\"(\" + HOST_NAME + \"|\" + IP_ADDRESS + \")\");\n\n /**\n * Regular expression pattern to match most part of RFC 3987\n * Internationalized URLs, aka IRIs. Commonly used Unicode characters are\n * added.\n */\n public static final Pattern WEB_URL = Pattern.compile(\n \"((?:(http|https|Http|Https|rtsp|Rtsp):\\\\/\\\\/(?:(?:[a-zA-Z0-9\\\\$\\\\-\\\\_\\\\.\\\\+\\\\!\\\\*\\\\'\\\\(\\\\)\"\n + \"\\\\,\\\\;\\\\?\\\\&amp;\\\\=]|(?:\\\\%[a-fA-F0-9]{2})){1,64}(?:\\\\:(?:[a-zA-Z0-9\\\\$\\\\-\\\\_\"\n + \"\\\\.\\\\+\\\\!\\\\*\\\\'\\\\(\\\\)\\\\,\\\\;\\\\?\\\\&amp;\\\\=]|(?:\\\\%[a-fA-F0-9]{2})){1,25})?\\\\@)?)?\"\n + \"(?:\" + DOMAIN_NAME + \")\"\n + \"(?:\\\\:\\\\d{1,5})?)\" // plus option port number\n + \"(\\\\/(?:(?:[\" + GOOD_IRI_CHAR + \"\\\\;\\\\/\\\\?\\\\:\\\\@\\\\&amp;\\\\=\\\\#\\\\~\" // plus option query params\n + \"\\\\-\\\\.\\\\+\\\\!\\\\*\\\\'\\\\(\\\\)\\\\,\\\\_])|(?:\\\\%[a-fA-F0-9]{2}))*)?\"\n + \"(?:\\\\b|$)\"); // and finally, a word boundary or end of\n // input. This is to stop foo.sure from\n // matching as foo.su\n\n public static final Pattern EMAIL_ADDRESS\n = Pattern.compile(\n \"[a-zA-Z0-9\\\\+\\\\.\\\\_\\\\%\\\\-\\\\+]{1,256}\" +\n \"\\\\@\" +\n \"[a-zA-Z0-9][a-zA-Z0-9\\\\-]{0,64}\" +\n \"(\" +\n \"\\\\.\" +\n \"[a-zA-Z0-9][a-zA-Z0-9\\\\-]{0,25}\" +\n \")+\"\n );\n\n /**\n * This pattern is intended for searching for things that look like they\n * might be phone numbers in arbitrary text, not for validating whether\n * something is in fact a phone number. It will miss many things that\n * are legitimate phone numbers.\n *\n * &lt;p&gt; The pattern matches the following:\n * &lt;ul&gt;\n * &lt;li&gt;Optionally, a + sign followed immediately by one or more digits. Spaces, dots, or dashes\n * may follow.\n * &lt;li&gt;Optionally, sets of digits in parentheses, separated by spaces, dots, or dashes.\n * &lt;li&gt;A string starting and ending with a digit, containing digits, spaces, dots, and/or dashes.\n * &lt;/ul&gt;\n */\n public static final Pattern PHONE\n = Pattern.compile( // sdd = space, dot, or dash\n \"(\\\\+[0-9]+[\\\\- \\\\.]*)?\" // +&lt;digits&gt;&lt;sdd&gt;*\n + \"(\\\\([0-9]+\\\\)[\\\\- \\\\.]*)?\" // (&lt;digits&gt;)&lt;sdd&gt;*\n + \"([0-9][0-9\\\\- \\\\.]+[0-9])\"); // &lt;digit&gt;&lt;digit|sdd&gt;+&lt;digit&gt;\n\n /**\n * Convenience method to take all of the non-null matching groups in a\n * regex Matcher and return them as a concatenated string.\n *\n * @param matcher The Matcher object from which grouped text will\n * be extracted\n *\n * @return A String comprising all of the non-null matched\n * groups concatenated together\n */\n public static final String concatGroups(Matcher matcher) {\n StringBuilder b = new StringBuilder();\n final int numGroups = matcher.groupCount();\n\n for (int i = 1; i &lt;= numGroups; i++) {\n String s = matcher.group(i);\n\n if (s != null) {\n b.append(s);\n }\n }\n\n return b.toString();\n }\n\n /**\n * Convenience method to return only the digits and plus signs\n * in the matching string.\n *\n * @param matcher The Matcher object from which digits and plus will\n * be extracted\n *\n * @return A String comprising all of the digits and plus in\n * the match\n */\n public static final String digitsAndPlusOnly(Matcher matcher) {\n StringBuilder buffer = new StringBuilder();\n String matchingRegion = matcher.group();\n\n for (int i = 0, size = matchingRegion.length(); i &lt; size; i++) {\n char character = matchingRegion.charAt(i);\n\n if (character == '+' || Character.isDigit(character)) {\n buffer.append(character);\n }\n }\n return buffer.toString();\n }\n\n /**\n * Do not create this static utility class.\n */\n private Patterns() {}\n}\n</code></pre>\n" }, { "answer_id": 37069466, "author": "Cavaleiro", "author_id": 716861, "author_profile": "https://Stackoverflow.com/users/716861", "pm_score": 2, "selected": false, "text": "<p>In line with billjamesdev answer, here is another approach to validate an URL without using a RegEx:</p>\n\n<p>From <a href=\"https://commons.apache.org/proper/commons-validator/\" rel=\"nofollow\">Apache Commons Validator</a> lib, look at class <a href=\"https://commons.apache.org/proper/commons-validator/apidocs/org/apache/commons/validator/routines/UrlValidator.html\" rel=\"nofollow\">UrlValidator</a>. Some example code:</p>\n\n<p>Construct a UrlValidator with valid schemes of \"http\", and \"https\".</p>\n\n<pre><code>String[] schemes = {\"http\",\"https\"}.\nUrlValidator urlValidator = new UrlValidator(schemes);\nif (urlValidator.isValid(\"ftp://foo.bar.com/\")) {\n System.out.println(\"url is valid\");\n} else {\n System.out.println(\"url is invalid\");\n}\n\nprints \"url is invalid\"\n</code></pre>\n\n<p>If instead the default constructor is used.</p>\n\n<pre><code>UrlValidator urlValidator = new UrlValidator();\nif (urlValidator.isValid(\"ftp://foo.bar.com/\")) {\n System.out.println(\"url is valid\");\n} else {\n System.out.println(\"url is invalid\");\n}\n</code></pre>\n\n<p>prints out \"url is valid\"</p>\n" }, { "answer_id": 56560145, "author": "Abhiraj", "author_id": 11636196, "author_profile": "https://Stackoverflow.com/users/11636196", "pm_score": 2, "selected": false, "text": "<pre><code>((http?|https|ftp|file)://)?((W|w){3}.)?[a-zA-Z0-9]+\\.[a-zA-Z]+\n</code></pre>\n\n<p>check here:- <a href=\"https://www.freeformatter.com/java-regex-tester.html#ad-output\" rel=\"nofollow noreferrer\">https://www.freeformatter.com/java-regex-tester.html#ad-output</a></p>\n\n<p>It sorts out theses entries correctly</p>\n\n<ul>\n<li>google.com</li>\n<li>www.google.com</li>\n<li>wwwgooglecom</li>\n<li>ft.</li>\n<li>Www.google.com</li>\n<li>.ft</li>\n<li><a href=\"https://www.google.com\" rel=\"nofollow noreferrer\">https://www.google.com</a></li>\n<li>https://</li>\n<li><a href=\"https://www\" rel=\"nofollow noreferrer\">https://www</a>.</li>\n<li><a href=\"https://google.com\" rel=\"nofollow noreferrer\">https://google.com</a></li>\n</ul>\n" }, { "answer_id": 66136090, "author": "Rabah LEKHEBASSENE", "author_id": 7201292, "author_profile": "https://Stackoverflow.com/users/7201292", "pm_score": 0, "selected": false, "text": "<p>Here is a proposal of an URL parser regex that recognizes :</p>\n<ul>\n<li>Protocol</li>\n<li>Host</li>\n<li>Port</li>\n<li>Path (Document/folder)</li>\n<li>Get parameters</li>\n</ul>\n<pre><code>^(?&gt;(?&lt;protocol&gt;[[:alpha:]]+(?&gt;\\:[[:alpha:]]+)*)\\:\\/\\/)?(?&lt;host&gt;(?&gt;[[:alnum:]]|[-_.])+)(?&gt;\\:(?&lt;port&gt;[[:digit:]]+))?(?&lt;path&gt;\\/(?&gt;[[:alnum:]]|[-_.\\/])*)?(?&gt;\\?(?&lt;request&gt;(?&gt;[[:alnum:]]+=[[:alnum:]]+)(?&gt;\\&amp;(?&gt;[[:alnum:]]+=[[:alnum:]]+))*))?$\n</code></pre>\n<p>This regex is able to parse an URL such :</p>\n<pre><code>jdbc:hsqldb:hsql://localhost:91/index.\n</code></pre>\n<p>There can be many way to engineer a URL regex, thus the one I propose can be lightly adapted to match more accurate URL grammars.</p>\n<p>It can be tested on the following page : <a href=\"https://regex101.com/r/Dy7HE0/5\" rel=\"nofollow noreferrer\">https://regex101.com/r/Dy7HE0/5</a></p>\n<p>Be aware that langages native API for regex (such as java.util.regex) don't support smart character classes such as <strong>[[:alnum:]]</strong> and <strong>[[:alpha:]]</strong>.</p>\n<p>Use instead <strong>\\w</strong> and <strong>\\d</strong>.</p>\n" }, { "answer_id": 68759694, "author": "Blas Albir", "author_id": 15795723, "author_profile": "https://Stackoverflow.com/users/15795723", "pm_score": 0, "selected": false, "text": "<p>First, an regex example:</p>\n<pre><code>regex = “((http|https)://)(www.)?” \n+ “[a-zA-Z0-9@:%._\\\\+~#?&amp;//=]{2,256}\\\\.[a-z]” \n+ “{2,6}\\\\b([-a-zA-Z0-9@:%._\\\\+~#?&amp;//=]*)”\n</code></pre>\n<p>*The URL must start with either http or https and\n*then followed by :// and\n*then it must contain www. and\n*then followed by subdomain of length (2, 256) and\n*last part contains top level domain like .com, .org etc.</p>\n<hr />\n<h2>In JAVA</h2>\n<pre><code>// Java program to check URL is valid or not\n// using Regular Expression\n \nimport java.util.regex.*;\n \nclass GFG {\n \n // Function to validate URL\n // using regular expression\n public static boolean\n isValidURL(String url)\n {\n // Regex to check valid URL\n String regex = &quot;((http|https)://)(www.)?&quot;\n + &quot;[a-zA-Z0-9@:%._\\\\+~#?&amp;//=]&quot;\n + &quot;{2,256}\\\\.[a-z]&quot;\n + &quot;{2,6}\\\\b([-a-zA-Z0-9@:%&quot;\n + &quot;._\\\\+~#?&amp;//=]*)&quot;;\n \n // Compile the ReGex\n Pattern p = Pattern.compile(regex);\n \n // If the string is empty\n // return false\n if (url == null) {\n return false;\n }\n \n // Find match between given string\n // and regular expression\n // using Pattern.matcher()\n Matcher m = p.matcher(url);\n \n // Return if the string\n // matched the ReGex\n return m.matches();\n }\n \n // Driver code\n public static void main(String args[])\n {\n String url\n = &quot;https://www.superDev.org&quot;;\n if (isValidURL(url) == true) {\n System.out.println(&quot;Yes&quot;);\n }\n else\n System.out.println(&quot;NO&quot;);\n }\n}\n</code></pre>\n<hr />\n<h2>In python 3</h2>\n<pre><code># Python3 program to check\n# URL is valid or not\n# using regular expression\nimport re\n \n# Function to validate URL\n# using regular expression\ndef isValidURL(str):\n \n # Regex to check valid URL\n regex = (&quot;((http|https)://)(www.)?&quot; +\n &quot;[a-zA-Z0-9@:%._\\\\+~#?&amp;//=]&quot; +\n &quot;{2,256}\\\\.[a-z]&quot; +\n &quot;{2,6}\\\\b([-a-zA-Z0-9@:%&quot; +\n &quot;._\\\\+~#?&amp;//=]*)&quot;)\n \n # Compile the ReGex\n p = re.compile(regex)\n \n # If the string is empty\n # return false\n if (str == None):\n return False\n \n # Return if the string\n # matched the ReGex\n if(re.search(p, str)):\n return True\n else:\n return False\n \n# Driver code\n \n# Test Case 1:\nurl = &quot;https://www.superDev.org&quot;\n \nif(isValidURL(url) == True):\n print(&quot;Yes&quot;)\nelse:\n print(&quot;No&quot;)\n \n</code></pre>\n" }, { "answer_id": 71153620, "author": "alexrnov", "author_id": 12787936, "author_profile": "https://Stackoverflow.com/users/12787936", "pm_score": 0, "selected": false, "text": "<p>This regular expression works for me:</p>\n<pre><code>String regex = &quot;(https?://|www\\\\.)[-a-zA-Z0-9+&amp;@#/%?=~_|!:.;]*[-a-zA-Z0-9+&amp;@#/%=~_|]&quot;;\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2138/" ]
I use RegexBuddy while working with regular expressions. From its library I copied the regular expression to match URLs. I tested successfully within RegexBuddy. However, when I copied it as Java `String` flavor and pasted it into Java code, it does not work. The following class prints `false`: ``` public class RegexFoo { public static void main(String[] args) { String regex = "\\b(https?|ftp|file)://[-A-Z0-9+&@#/%?=~_|!:,.;]*[-A-Z0-9+&@#/%=~_|]"; String text = "http://google.com"; System.out.println(IsMatch(text,regex)); } private static boolean IsMatch(String s, String pattern) { try { Pattern patt = Pattern.compile(pattern); Matcher matcher = patt.matcher(s); return matcher.matches(); } catch (RuntimeException e) { return false; } } } ``` Does anyone know what I am doing wrong?
Try the following regex string instead. Your test was probably done in a case-sensitive manner. I have added the lowercase alphas as well as a proper string beginning placeholder. ``` String regex = "^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]"; ``` This works too: ``` String regex = "\\b(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]"; ``` Note: ``` String regex = "<\\b(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]>"; // matches <http://google.com> String regex = "<^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]>"; // does not match <http://google.com> ```
163,365
<p>Let's say that for some reason you need to write a macro: <code>MACRO(X,Y)</code>. <strong>(Let's assume there's a good reason you can't use an inline function.)</strong> You want this macro to emulate a call to a function with no return value.</p> <hr> <h3>Example 1: This should work as expected.</h3> <pre><code>if (x &gt; y) MACRO(x, y); do_something(); </code></pre> <h3>Example 2: This should not result in a compiler error.</h3> <pre><code>if (x &gt; y) MACRO(x, y); else MACRO(y - x, x - y); </code></pre> <h3>Example 3: This should <em>not</em> compile.</h3> <pre><code>do_something(); MACRO(x, y) do_something(); </code></pre> <hr> <p>The naïve way to write the macro is like this:</p> <pre><code>#define MACRO(X,Y) \ cout &lt;&lt; "1st arg is:" &lt;&lt; (X) &lt;&lt; endl; \ cout &lt;&lt; "2nd arg is:" &lt;&lt; (Y) &lt;&lt; endl; \ cout &lt;&lt; "Sum is:" &lt;&lt; ((X)+(Y)) &lt;&lt; endl; </code></pre> <p>This is a very bad solution which fails all three examples, and I shouldn't need to explain why.</p> <p><strong>Ignore what the macro actually does, that's not the point.</strong></p> <hr> <p>Now, the way I most often see macros written is to enclose them in curly braces, like this:</p> <pre><code>#define MACRO(X,Y) \ { \ cout &lt;&lt; "1st arg is:" &lt;&lt; (X) &lt;&lt; endl; \ cout &lt;&lt; "2nd arg is:" &lt;&lt; (Y) &lt;&lt; endl; \ cout &lt;&lt; "Sum is:" &lt;&lt; ((X)+(Y)) &lt;&lt; endl; \ } </code></pre> <p>This solves example 1, because the macro is in one statement block. But example 2 is broken because we put a semicolon after the call to the macro. This makes the compiler think the semicolon is a statement by itself, which means the else statement doesn't correspond to any if statement! And lastly, example 3 compiles OK, even though there is no semicolon, because a code block doesn't need a semicolon.</p> <hr> <p>Is there a way to write a macro so that it pass all three examples?</p> <hr> <p><i>Note: I am submitting my own answer as part of the <a href="https://stackoverflow.com/questions/162246/is-stack-overflow-appropriate-for-sharing-knowledge-tips-tricks-and-interesting">accepted way of sharing a tip</a>, but if anyone has a better solution feel free to post it here, it may get more votes than my method. :)</i></p>
[ { "answer_id": 163366, "author": "Kip", "author_id": 18511, "author_profile": "https://Stackoverflow.com/users/18511", "pm_score": 6, "selected": false, "text": "<p>There is a rather clever solution:</p>\n\n<pre><code>#define MACRO(X,Y) \\\ndo { \\\n cout &lt;&lt; \"1st arg is:\" &lt;&lt; (X) &lt;&lt; endl; \\\n cout &lt;&lt; \"2nd arg is:\" &lt;&lt; (Y) &lt;&lt; endl; \\\n cout &lt;&lt; \"Sum is:\" &lt;&lt; ((X)+(Y)) &lt;&lt; endl; \\\n} while (0)\n</code></pre>\n\n<p>Now you have a single block-level statement, which must be followed by a semicolon. This behaves as expected and desired in all three examples.</p>\n" }, { "answer_id": 163404, "author": "Andrew Stein", "author_id": 13029, "author_profile": "https://Stackoverflow.com/users/13029", "pm_score": 3, "selected": false, "text": "<p>Create a block using</p>\n\n<pre><code> #define MACRO(...) do { ... } while(false)\n</code></pre>\n\n<p>Do not add a ; after the while(false)</p>\n" }, { "answer_id": 163415, "author": "Ates Goral", "author_id": 23501, "author_profile": "https://Stackoverflow.com/users/23501", "pm_score": 0, "selected": false, "text": "<p>If you're willing to adopt the practice of always using curly braces in your if statements,</p>\n\n<p>Your macro would simply be missing the last semicolon:</p>\n\n<pre><code>#define MACRO(X,Y) \\\ncout &lt;&lt; \"1st arg is:\" &lt;&lt; (X) &lt;&lt; endl; \\\ncout &lt;&lt; \"2nd arg is:\" &lt;&lt; (Y) &lt;&lt; endl; \\\ncout &lt;&lt; \"Sum is:\" &lt;&lt; ((X)+(Y)) &lt;&lt; endl\n</code></pre>\n\n<p>Example 1: (compiles)</p>\n\n<pre><code>if (x &gt; y) {\n MACRO(x, y);\n}\ndo_something();\n</code></pre>\n\n<p>Example 2: (compiles)</p>\n\n<pre><code>if (x &gt; y) {\n MACRO(x, y);\n} else {\n MACRO(y - x, x - y);\n}\n</code></pre>\n\n<p>Example 3: (doesn't compile)</p>\n\n<pre><code>do_something();\nMACRO(x, y)\ndo_something();\n</code></pre>\n" }, { "answer_id": 163417, "author": "coppro", "author_id": 16855, "author_profile": "https://Stackoverflow.com/users/16855", "pm_score": 7, "selected": true, "text": "<p>Macros should generally be avoided; prefer inline functions to them at all times. Any compiler worth its salt should be capable of inlining a small function as if it were a macro, and an inline function will respect namespaces and other scopes, as well as evaluating all the arguments once.</p>\n\n<p>If it must be a macro, a while loop (already suggested) will work, or you can try the comma operator:</p>\n\n<pre><code>#define MACRO(X,Y) \\\n ( \\\n (cout &lt;&lt; \"1st arg is:\" &lt;&lt; (X) &lt;&lt; endl), \\\n (cout &lt;&lt; \"2nd arg is:\" &lt;&lt; (Y) &lt;&lt; endl), \\\n (cout &lt;&lt; \"3rd arg is:\" &lt;&lt; ((X) + (Y)) &lt;&lt; endl), \\\n (void)0 \\\n )\n</code></pre>\n\n<p>The <code>(void)0</code> causes the statement to evaluate to one of <code>void</code> type, and the use of commas rather than semicolons allows it to be used inside a statement, rather than only as a standalone. I would still recommend an inline function for a host of reasons, the least of which being scope and the fact that <code>MACRO(a++, b++)</code> will increment <code>a</code> and <code>b</code> twice.</p>\n" }, { "answer_id": 163482, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Your answer suffers from the multiple-evaluation problem, so (eg)</p>\n\n<pre><code>macro( read_int(file1), read_int(file2) );\n</code></pre>\n\n<p>will do something unexpected and probably unwanted.</p>\n" }, { "answer_id": 163636, "author": "jwfearn", "author_id": 10559, "author_profile": "https://Stackoverflow.com/users/10559", "pm_score": 1, "selected": false, "text": "<p>As others have mentioned, you should avoid macros whenever possible. They are dangerous in the presence of side effects if the macro arguments are evaluated more than once. If you know the type of the arguments (or can use C++0x <code>auto</code> feature), you could use temporaries to enforce single evaluation.</p>\n\n<p>Another problem: the order in which multiple evaluations happen may not be what you expect!</p>\n\n<p>Consider this code:</p>\n\n<pre><code>#include &lt;iostream&gt;\nusing namespace std;\n\nint foo( int &amp; i ) { return i *= 10; }\nint bar( int &amp; i ) { return i *= 100; }\n\n#define BADMACRO( X, Y ) do { \\\n cout &lt;&lt; \"X=\" &lt;&lt; (X) &lt;&lt; \", Y=\" &lt;&lt; (Y) &lt;&lt; \", X+Y=\" &lt;&lt; ((X)+(Y)) &lt;&lt; endl; \\\n } while (0)\n\n#define MACRO( X, Y ) do { \\\n int x = X; int y = Y; \\\n cout &lt;&lt; \"X=\" &lt;&lt; x &lt;&lt; \", Y=\" &lt;&lt; y &lt;&lt; \", X+Y=\" &lt;&lt; ( x + y ) &lt;&lt; endl; \\\n } while (0)\n\nint main() {\n int a = 1; int b = 1;\n BADMACRO( foo(a), bar(b) );\n a = 1; b = 1;\n MACRO( foo(a), bar(b) );\n return 0;\n}\n</code></pre>\n\n<p>And it's output as compiled and run on my machine:</p>\n\n<pre>\nX=100, Y=10000, X+Y=110\nX=10, Y=100, X+Y=110\n</pre>\n" }, { "answer_id": 165031, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 4, "selected": false, "text": "<p>I know you said \"ignore what the macro does\", but people will find this question by searching based on the title, so I think discussion of further techniques to emulate functions with macros are warranted.</p>\n\n<p>Closest I know of is:</p>\n\n<pre><code>#define MACRO(X,Y) \\\ndo { \\\n auto MACRO_tmp_1 = (X); \\\n auto MACRO_tmp_2 = (Y); \\\n using std::cout; \\\n using std::endl; \\\n cout &lt;&lt; \"1st arg is:\" &lt;&lt; (MACRO_tmp_1) &lt;&lt; endl; \\\n cout &lt;&lt; \"2nd arg is:\" &lt;&lt; (MACRO_tmp_2) &lt;&lt; endl; \\\n cout &lt;&lt; \"Sum is:\" &lt;&lt; (MACRO_tmp_1 + MACRO_tmp_2) &lt;&lt; endl; \\\n} while(0)\n</code></pre>\n\n<p>This does the following:</p>\n\n<ul>\n<li>Works correctly in each of the stated contexts.</li>\n<li>Evaluates each of its arguments exactly once, which is a guaranteed feature of a function call (assuming in both cases no exceptions in any of those expressions).</li>\n<li>Acts on any types, by use of \"auto\" from C++0x. This is not yet standard C++, but there's no other way to get the tmp variables necessitated by the single-evaluation rule.</li>\n<li>Doesn't require the caller to have imported names from namespace std, which the original macro does, but a function would not.</li>\n</ul>\n\n<p>However, it still differs from a function in that:</p>\n\n<ul>\n<li>In some invalid uses it may give different compiler errors or warnings.</li>\n<li>It goes wrong if X or Y contain uses of 'MACRO_tmp_1' or 'MACRO_tmp_2' from the surrounding scope.</li>\n<li>Related to the namespace std thing: a function uses its own lexical context to look up names, whereas a macro uses the context of its call site. There's no way to write a macro that behaves like a function in this respect.</li>\n<li>It can't be used as the return expression of a void function, which a void expression (such as the comma solution) can. This is even more of an issue when the desired return type is not void, especially when used as an lvalue. But the comma solution can't include using declarations, because they're statements, so pick one or use the ({ ... }) GNU extension.</li>\n</ul>\n" }, { "answer_id": 8590661, "author": "ofavre", "author_id": 508831, "author_profile": "https://Stackoverflow.com/users/508831", "pm_score": 4, "selected": false, "text": "<p>Here is an answer coming right from the <code>libc6</code>!\nTaking a look at <code>/usr/include/x86_64-linux-gnu/bits/byteswap.h</code>, I found the trick you were looking for.</p>\n\n<p>A few critics of previous solutions:</p>\n\n<ul>\n<li>Kip's solution does not permit <em>evaluating to an expression</em>, which is in the end often needed.</li>\n<li>coppro's solution does not permit <em>assigning a variable</em> as the expressions are separate, but can evaluate to an expression.</li>\n<li>Steve Jessop's solution uses the C++11 <code>auto</code> keyword, that's fine, but <em>feel free to use the known/expected type</em> instead.</li>\n</ul>\n\n<p>The trick is to use both the <code>(expr,expr)</code> construct and a <code>{}</code> scope:</p>\n\n<pre><code>#define MACRO(X,Y) \\\n ( \\\n { \\\n register int __x = static_cast&lt;int&gt;(X), __y = static_cast&lt;int&gt;(Y); \\\n std::cout &lt;&lt; \"1st arg is:\" &lt;&lt; __x &lt;&lt; std::endl; \\\n std::cout &lt;&lt; \"2nd arg is:\" &lt;&lt; __y &lt;&lt; std::endl; \\\n std::cout &lt;&lt; \"Sum is:\" &lt;&lt; (__x + __y) &lt;&lt; std::endl; \\\n __x + __y; \\\n } \\\n )\n</code></pre>\n\n<p>Note the use of the <code>register</code> keyword, it's only a hint to the compiler.\nThe <code>X</code> and <code>Y</code> macro parameters are (already) surrounded in parenthesis and <strong>casted</strong> to an expected type.\nThis solution works properly with pre- and post-increment as parameters are evaluated only once.</p>\n\n<p>For the example purpose, even though not requested, I added the <code>__x + __y;</code> statement, which is the way to make the whole bloc to be evaluated as that precise expression.</p>\n\n<p>It's safer to use <code>void();</code> if you want to make sure the macro won't evaluate to an expression, thus being illegal where an <code>rvalue</code> is expected.</p>\n\n<p><strong>However</strong>, the solution is <em>not ISO C++ compliant</em> as will complain <code>g++ -pedantic</code>:</p>\n\n<pre><code>warning: ISO C++ forbids braced-groups within expressions [-pedantic]\n</code></pre>\n\n<p>In order to give some rest to <code>g++</code>, use <code>(__extension__ OLD_WHOLE_MACRO_CONTENT_HERE)</code> so that the new definition reads:</p>\n\n<pre><code>#define MACRO(X,Y) \\\n (__extension__ ( \\\n { \\\n register int __x = static_cast&lt;int&gt;(X), __y = static_cast&lt;int&gt;(Y); \\\n std::cout &lt;&lt; \"1st arg is:\" &lt;&lt; __x &lt;&lt; std::endl; \\\n std::cout &lt;&lt; \"2nd arg is:\" &lt;&lt; __y &lt;&lt; std::endl; \\\n std::cout &lt;&lt; \"Sum is:\" &lt;&lt; (__x + __y) &lt;&lt; std::endl; \\\n __x + __y; \\\n } \\\n ))\n</code></pre>\n\n<p>In order to improve my solution even a bit more, let's use the <code>__typeof__</code> keyword, as seen in <a href=\"https://stackoverflow.com/questions/3437404/min-and-max-in-c/3437484#3437484\">MIN and MAX in C</a>:</p>\n\n<pre><code>#define MACRO(X,Y) \\\n (__extension__ ( \\\n { \\\n __typeof__(X) __x = (X); \\\n __typeof__(Y) __y = (Y); \\\n std::cout &lt;&lt; \"1st arg is:\" &lt;&lt; __x &lt;&lt; std::endl; \\\n std::cout &lt;&lt; \"2nd arg is:\" &lt;&lt; __y &lt;&lt; std::endl; \\\n std::cout &lt;&lt; \"Sum is:\" &lt;&lt; (__x + __y) &lt;&lt; std::endl; \\\n __x + __y; \\\n } \\\n ))\n</code></pre>\n\n<p>Now the compiler will determine the appropriate type. This too is a <code>gcc</code> extension.</p>\n\n<p>Note the removal of the <code>register</code> keyword, as it would the following warning when used with a class type:</p>\n\n<pre><code>warning: address requested for ‘__x’, which is declared ‘register’ [-Wextra]\n</code></pre>\n" }, { "answer_id": 40423852, "author": "Quentin", "author_id": 3233393, "author_profile": "https://Stackoverflow.com/users/3233393", "pm_score": 4, "selected": false, "text": "<p>C++11 brought us lambdas, which can be incredibly useful in this situation:</p>\n\n<pre><code>#define MACRO(X,Y) \\\n [&amp;](x_, y_) { \\\n cout &lt;&lt; \"1st arg is:\" &lt;&lt; x_ &lt;&lt; endl; \\\n cout &lt;&lt; \"2nd arg is:\" &lt;&lt; y_ &lt;&lt; endl; \\\n cout &lt;&lt; \"Sum is:\" &lt;&lt; (x_ + y_) &lt;&lt; endl; \\\n }((X), (Y))\n</code></pre>\n\n<p>You keep the generative power of macros, but have a comfy scope from which you can return whatever you want (including <code>void</code>). Additionally, the issue of evaluating macro parameters multiple times is avoided.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18511/" ]
Let's say that for some reason you need to write a macro: `MACRO(X,Y)`. **(Let's assume there's a good reason you can't use an inline function.)** You want this macro to emulate a call to a function with no return value. --- ### Example 1: This should work as expected. ``` if (x > y) MACRO(x, y); do_something(); ``` ### Example 2: This should not result in a compiler error. ``` if (x > y) MACRO(x, y); else MACRO(y - x, x - y); ``` ### Example 3: This should *not* compile. ``` do_something(); MACRO(x, y) do_something(); ``` --- The naïve way to write the macro is like this: ``` #define MACRO(X,Y) \ cout << "1st arg is:" << (X) << endl; \ cout << "2nd arg is:" << (Y) << endl; \ cout << "Sum is:" << ((X)+(Y)) << endl; ``` This is a very bad solution which fails all three examples, and I shouldn't need to explain why. **Ignore what the macro actually does, that's not the point.** --- Now, the way I most often see macros written is to enclose them in curly braces, like this: ``` #define MACRO(X,Y) \ { \ cout << "1st arg is:" << (X) << endl; \ cout << "2nd arg is:" << (Y) << endl; \ cout << "Sum is:" << ((X)+(Y)) << endl; \ } ``` This solves example 1, because the macro is in one statement block. But example 2 is broken because we put a semicolon after the call to the macro. This makes the compiler think the semicolon is a statement by itself, which means the else statement doesn't correspond to any if statement! And lastly, example 3 compiles OK, even though there is no semicolon, because a code block doesn't need a semicolon. --- Is there a way to write a macro so that it pass all three examples? --- *Note: I am submitting my own answer as part of the [accepted way of sharing a tip](https://stackoverflow.com/questions/162246/is-stack-overflow-appropriate-for-sharing-knowledge-tips-tricks-and-interesting), but if anyone has a better solution feel free to post it here, it may get more votes than my method. :)*
Macros should generally be avoided; prefer inline functions to them at all times. Any compiler worth its salt should be capable of inlining a small function as if it were a macro, and an inline function will respect namespaces and other scopes, as well as evaluating all the arguments once. If it must be a macro, a while loop (already suggested) will work, or you can try the comma operator: ``` #define MACRO(X,Y) \ ( \ (cout << "1st arg is:" << (X) << endl), \ (cout << "2nd arg is:" << (Y) << endl), \ (cout << "3rd arg is:" << ((X) + (Y)) << endl), \ (void)0 \ ) ``` The `(void)0` causes the statement to evaluate to one of `void` type, and the use of commas rather than semicolons allows it to be used inside a statement, rather than only as a standalone. I would still recommend an inline function for a host of reasons, the least of which being scope and the fact that `MACRO(a++, b++)` will increment `a` and `b` twice.
163,367
<p>I get a mysql error:</p> <p><strong>#update (ActiveRecord::StatementInvalid) "Mysql::Error: #HY000Got error 139 from storage engine:</strong></p> <p>When trying to update a text field on a record with a string of length 1429 characters, any ideas on how to track down the problem?</p> <p>Below is the stacktrace. </p> <pre><code>from /var/www/releases/20081002155111/vendor/rails/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb:147:in `log' from /var/www/releases/20081002155111/vendor/rails/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb:299:in `execute' from /var/www/releases/20081002155111/vendor/rails/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb:167:in `update_sql' from /var/www/releases/20081002155111/vendor/rails/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb:314:in `update_sql' from /var/www/releases/20081002155111/vendor/rails/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb:49:in `update_without_query_dirty' from /var/www/releases/20081002155111/vendor/rails/activerecord/lib/active_record/connection_adapters/abstract/query_cache.rb:19:in `update' from /var/www/releases/20081002155111/vendor/rails/activerecord/lib/active_record/base.rb:2481:in `update_without_lock' from /var/www/releases/20081002155111/vendor/rails/activerecord/lib/active_record/locking/optimistic.rb:70:in `update_without_dirty' from /var/www/releases/20081002155111/vendor/rails/activerecord/lib/active_record/dirty.rb:137:in `update_without_callbacks' from /var/www/releases/20081002155111/vendor/rails/activerecord/lib/active_record/callbacks.rb:234:in `update_without_timestamps' from /var/www/releases/20081002155111/vendor/rails/activerecord/lib/active_record/timestamp.rb:38:in `update' from /var/www/releases/20081002155111/vendor/rails/activerecord/lib/active_record/base.rb:2472:in `create_or_update_without_callbacks' from /var/www/releases/20081002155111/vendor/rails/activerecord/lib/active_record/callbacks.rb:207:in `create_or_update' from /var/www/releases/20081002155111/vendor/rails/activerecord/lib/active_record/base.rb:2200:in `save_without_validation' from /var/www/releases/20081002155111/vendor/rails/activerecord/lib/active_record/validations.rb:901:in `save_without_dirty' from /var/www/releases/20081002155111/vendor/rails/activerecord/lib/active_record/dirty.rb:75:in `save_without_transactions' from /var/www/releases/20081002155111/vendor/rails/activerecord/lib/active_record/transactions.rb:106:in `save' from /var/www/releases/20081002155111/vendor/rails/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb:66:in `transaction' from /var/www/releases/20081002155111/vendor/rails/activerecord/lib/active_record/transactions.rb:79:in `transaction' from /var/www/releases/20081002155111/vendor/rails/activerecord/lib/active_record/transactions.rb:98:in `transaction' from /var/www/releases/20081002155111/vendor/rails/activerecord/lib/active_record/transactions.rb:106:in `save' from /var/www/releases/20081002155111/vendor/rails/activerecord/lib/active_record/transactions.rb:118:in `rollback_active_record_state!' from /var/www/releases/20081002155111/vendor/rails/activerecord/lib/active_record/transactions.rb:106:in `save' </code></pre>
[ { "answer_id": 163422, "author": "Matthias Winkelmann", "author_id": 4494, "author_profile": "https://Stackoverflow.com/users/4494", "pm_score": 1, "selected": true, "text": "<p>Maybe it's this bug: <a href=\"http://bugs.mysql.com/bug.php?id=10035\" rel=\"nofollow noreferrer\">#1030 - Got error 139 from storage engine</a>, but it would help if you'd post the query which should come directly after the error message.</p>\n" }, { "answer_id": 166277, "author": "MatthewFord", "author_id": 21596, "author_profile": "https://Stackoverflow.com/users/21596", "pm_score": 0, "selected": false, "text": "<p>It seemed to be a very weird mysql error, where the text was being truncated to 256 characters (for a text type) and throwing the above error is the string was 1000 characters or more. modifying the table column to be text again fixed the issue, or it just fixed it self.. i'm still not sure.</p>\n\n<p>Update:\nChanging the table type to MyISAM fixed this problem</p>\n" }, { "answer_id": 170619, "author": "Dave Cheney", "author_id": 6449, "author_profile": "https://Stackoverflow.com/users/6449", "pm_score": 1, "selected": false, "text": "<p>When you say a text field, is it of type VARCHAR, or TEXT?</p>\n\n<p>If its the former then you cannot store a string larger than 255 chars (possibly less with UTF-8 overhead) in that column. If its the latter, you'd better post your schema definition so people can assist you further.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163367", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21596/" ]
I get a mysql error: **#update (ActiveRecord::StatementInvalid) "Mysql::Error: #HY000Got error 139 from storage engine:** When trying to update a text field on a record with a string of length 1429 characters, any ideas on how to track down the problem? Below is the stacktrace. ``` from /var/www/releases/20081002155111/vendor/rails/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb:147:in `log' from /var/www/releases/20081002155111/vendor/rails/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb:299:in `execute' from /var/www/releases/20081002155111/vendor/rails/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb:167:in `update_sql' from /var/www/releases/20081002155111/vendor/rails/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb:314:in `update_sql' from /var/www/releases/20081002155111/vendor/rails/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb:49:in `update_without_query_dirty' from /var/www/releases/20081002155111/vendor/rails/activerecord/lib/active_record/connection_adapters/abstract/query_cache.rb:19:in `update' from /var/www/releases/20081002155111/vendor/rails/activerecord/lib/active_record/base.rb:2481:in `update_without_lock' from /var/www/releases/20081002155111/vendor/rails/activerecord/lib/active_record/locking/optimistic.rb:70:in `update_without_dirty' from /var/www/releases/20081002155111/vendor/rails/activerecord/lib/active_record/dirty.rb:137:in `update_without_callbacks' from /var/www/releases/20081002155111/vendor/rails/activerecord/lib/active_record/callbacks.rb:234:in `update_without_timestamps' from /var/www/releases/20081002155111/vendor/rails/activerecord/lib/active_record/timestamp.rb:38:in `update' from /var/www/releases/20081002155111/vendor/rails/activerecord/lib/active_record/base.rb:2472:in `create_or_update_without_callbacks' from /var/www/releases/20081002155111/vendor/rails/activerecord/lib/active_record/callbacks.rb:207:in `create_or_update' from /var/www/releases/20081002155111/vendor/rails/activerecord/lib/active_record/base.rb:2200:in `save_without_validation' from /var/www/releases/20081002155111/vendor/rails/activerecord/lib/active_record/validations.rb:901:in `save_without_dirty' from /var/www/releases/20081002155111/vendor/rails/activerecord/lib/active_record/dirty.rb:75:in `save_without_transactions' from /var/www/releases/20081002155111/vendor/rails/activerecord/lib/active_record/transactions.rb:106:in `save' from /var/www/releases/20081002155111/vendor/rails/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb:66:in `transaction' from /var/www/releases/20081002155111/vendor/rails/activerecord/lib/active_record/transactions.rb:79:in `transaction' from /var/www/releases/20081002155111/vendor/rails/activerecord/lib/active_record/transactions.rb:98:in `transaction' from /var/www/releases/20081002155111/vendor/rails/activerecord/lib/active_record/transactions.rb:106:in `save' from /var/www/releases/20081002155111/vendor/rails/activerecord/lib/active_record/transactions.rb:118:in `rollback_active_record_state!' from /var/www/releases/20081002155111/vendor/rails/activerecord/lib/active_record/transactions.rb:106:in `save' ```
Maybe it's this bug: [#1030 - Got error 139 from storage engine](http://bugs.mysql.com/bug.php?id=10035), but it would help if you'd post the query which should come directly after the error message.
163,382
<p>I have the following code that won't compile and although there is a way to make it compile I want to understand why it isn't compiling. Can someone enlighten me as to specifically why I get the error message I will post at the end please?</p> <pre><code>public class Test { public static void main(String args[]) { Test t = new Test(); t.testT(null); } public &lt;T extends Test&gt; void testT(Class&lt;T&gt; type) { Class&lt;T&gt; testType = type == null ? Test.class : type; //Error here System.out.println(testType); } } </code></pre> <p><code>Type mismatch: cannot convert from Class&lt;capture#1-of ? extends Test&gt; to Class&lt;T&gt;</code></p> <p>By casting <code>Test.class</code> to <code>Class&lt;T&gt;</code> this compiles with an <code>Unchecked cast</code> warning and runs perfectly.</p>
[ { "answer_id": 163406, "author": "Ken", "author_id": 20621, "author_profile": "https://Stackoverflow.com/users/20621", "pm_score": 1, "selected": false, "text": "<p>Remove the conditional and the error is a little nicer...</p>\n\n<pre><code>public class Test {\n public static void main(String args[]) {\n Test t = new Test();\n t.testT(null);\n }\n\n public &lt;T extends Test&gt; void testT(Class&lt;T&gt; type) {\n Class&lt;T&gt; testClass = Test.class;\n System.out.println(testClass);\n }\n}\n\n\nTest.java:10: incompatible types\nfound : java.lang.Class&lt;Test&gt;\nrequired: java.lang.Class&lt;T&gt;\n Class&lt;T&gt; testClass = Test.class;\n</code></pre>\n" }, { "answer_id": 163413, "author": "laz", "author_id": 8753, "author_profile": "https://Stackoverflow.com/users/8753", "pm_score": 6, "selected": true, "text": "<p>The reason is that Test.class is of the type Class&lt;Test&gt;. You cannot assign a reference of type Class&lt;Test&gt; to a variable of type Class&lt;T&gt; as they are not the same thing. This, however, works:</p>\n\n<pre><code>Class&lt;? extends Test&gt; testType = type == null ? Test.class : type;\n</code></pre>\n\n<p>The wildcard allows both Class&lt;T&gt; and Class&lt;Test&gt; references to be assigned to testType.</p>\n\n<p>There is a ton of information about Java generics behavior at <a href=\"http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html\" rel=\"noreferrer\" title=\"Java Generics FAQ\">Angelika Langer Java Generics FAQ</a>. I'll provide an example based on some of the information there that uses the <code>Number</code> class heirarchy Java's core API.</p>\n\n<p>Consider the following method:</p>\n\n<pre><code>public &lt;T extends Number&gt; void testNumber(final Class&lt;T&gt; type)\n</code></pre>\n\n<p>This is to allow for the following statements to be successfully compile:</p>\n\n<pre><code>testNumber(Integer.class);\ntestNumber(Number.class);\n</code></pre>\n\n<p>But the following won't compile:</p>\n\n<pre><code>testNumber(String.class);\n</code></pre>\n\n<p>Now consider these statements:</p>\n\n<pre><code>Class&lt;Number&gt; numberClass = Number.class;\nClass&lt;Integer&gt; integerClass = numberClass;\n</code></pre>\n\n<p>The second line fails to compile and produces this error <code>Type mismatch: cannot convert from Class&lt;Number&gt; to Class&lt;Integer&gt;</code>. But <code>Integer</code> extends <code>Number</code>, so why does it fail? Look at these next two statements to see why:</p>\n\n<pre><code>Number anumber = new Long(0);\nInteger another = anumber;\n</code></pre>\n\n<p>It is pretty easy to see why the 2nd line doesn't compile here. You can't assign an instance of <code>Number</code> to a variable of type <code>Integer</code> because there is no way to guarantee that the <code>Number</code> instance is of a compatible type. In this example the <code>Number</code> is actually a <code>Long</code>, which certainly can't be assigned to an <code>Integer</code>. In fact, the error is also a type mismatch: <code>Type mismatch: cannot convert from Number to Integer</code>.</p>\n\n<p>The rule is that an instance cannot be assigned to a variable that is a subclass of the type of the instance as there is no guarantee that is is compatible.</p>\n\n<p>Generics behave in a similar manner. In the generic method signature, <code>T</code> is just a placeholder to indicate what the method allows to the compiler. When the compiler encounters <code>testNumber(Integer.class)</code> it essentially replaces <code>T</code> with <code>Integer</code>. </p>\n\n<p>Wildcards add additional flexibility, as the following will compile:</p>\n\n<pre><code>Class&lt;? extends Number&gt; wildcard = numberClass;\n</code></pre>\n\n<p>Since <code>Class&lt;? extends Number&gt;</code> indicates any type that is a <code>Number</code> or a subclass of <code>Number</code> this is perfectly legal and potentially useful in many circumstances.</p>\n" }, { "answer_id": 165246, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 2, "selected": false, "text": "<p>Suppose I extend Test:</p>\n\n<pre><code>public class SubTest extends Test {\n public static void main(String args[]) {\n Test t = new Test();\n t.testT(new SubTest());\n }\n}\n</code></pre>\n\n<p>Now, when I invoked <code>testT</code>, the type parameter <code>&lt;T&gt;</code> is <code>SubTest</code>, which means the variable <code>testType</code> is a <code>Class&lt;SubTest&gt;</code>. <code>Test.class</code> is of type <code>Class&lt;Test&gt;</code>, which is not assignable to a variable of type <code>Class&lt;SubTest&gt;</code>.</p>\n\n<p>Declaring the variable <code>testType</code> as a <code>Class&lt;? extends Test&gt;</code> is the right solution; casting to <code>Class&lt;T&gt;</code> is hiding a real problem.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6414/" ]
I have the following code that won't compile and although there is a way to make it compile I want to understand why it isn't compiling. Can someone enlighten me as to specifically why I get the error message I will post at the end please? ``` public class Test { public static void main(String args[]) { Test t = new Test(); t.testT(null); } public <T extends Test> void testT(Class<T> type) { Class<T> testType = type == null ? Test.class : type; //Error here System.out.println(testType); } } ``` `Type mismatch: cannot convert from Class<capture#1-of ? extends Test> to Class<T>` By casting `Test.class` to `Class<T>` this compiles with an `Unchecked cast` warning and runs perfectly.
The reason is that Test.class is of the type Class<Test>. You cannot assign a reference of type Class<Test> to a variable of type Class<T> as they are not the same thing. This, however, works: ``` Class<? extends Test> testType = type == null ? Test.class : type; ``` The wildcard allows both Class<T> and Class<Test> references to be assigned to testType. There is a ton of information about Java generics behavior at [Angelika Langer Java Generics FAQ](http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html "Java Generics FAQ"). I'll provide an example based on some of the information there that uses the `Number` class heirarchy Java's core API. Consider the following method: ``` public <T extends Number> void testNumber(final Class<T> type) ``` This is to allow for the following statements to be successfully compile: ``` testNumber(Integer.class); testNumber(Number.class); ``` But the following won't compile: ``` testNumber(String.class); ``` Now consider these statements: ``` Class<Number> numberClass = Number.class; Class<Integer> integerClass = numberClass; ``` The second line fails to compile and produces this error `Type mismatch: cannot convert from Class<Number> to Class<Integer>`. But `Integer` extends `Number`, so why does it fail? Look at these next two statements to see why: ``` Number anumber = new Long(0); Integer another = anumber; ``` It is pretty easy to see why the 2nd line doesn't compile here. You can't assign an instance of `Number` to a variable of type `Integer` because there is no way to guarantee that the `Number` instance is of a compatible type. In this example the `Number` is actually a `Long`, which certainly can't be assigned to an `Integer`. In fact, the error is also a type mismatch: `Type mismatch: cannot convert from Number to Integer`. The rule is that an instance cannot be assigned to a variable that is a subclass of the type of the instance as there is no guarantee that is is compatible. Generics behave in a similar manner. In the generic method signature, `T` is just a placeholder to indicate what the method allows to the compiler. When the compiler encounters `testNumber(Integer.class)` it essentially replaces `T` with `Integer`. Wildcards add additional flexibility, as the following will compile: ``` Class<? extends Number> wildcard = numberClass; ``` Since `Class<? extends Number>` indicates any type that is a `Number` or a subclass of `Number` this is perfectly legal and potentially useful in many circumstances.
163,389
<p>I have a web application where users enter arbitrary sql queries for later batch processing. We want to validate the syntax of the query without actually executing it. Some of the queries will take a long time, which is why we don't want to execute them. I'm using Oracle's dbms_sql.parse to do this.</p> <p>However, I now have a situation where I need to know the number and type of the result set columns. Is there a way to do this without actually executing the query? That is, to have Oracle parse the query and tell me what the result datatypes/names will be returned when the query is actually executed? I'm using Oracle 10g and and it's a Java 1.5/Servlet 2.4 application.</p> <p>Edit: The users who enter the queries are already users on the database. They authenticate to my app with their database credentials and the queries are executed using those credentials. Therefore they can't put in any query that they couldn't run by just connecting with sqlplus.</p>
[ { "answer_id": 163483, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 4, "selected": true, "text": "<p>You should be able to prepare a SQL query to validate the syntax and get result set metadata. Preparing a query should not execute it.</p>\n\n<pre><code>import java.sql.*;\n. . .\nConnection conn;\n. . .\nPreparedStatement ps = conn.prepareStatement(\"SELECT * FROM foo\");\nResultSetMetadata rsmd = ps.getMetaData();\nint numberOfColumns = rsmd.getColumnCount();\n</code></pre>\n\n<p>Then you can get metadata about each column of the result set.</p>\n" }, { "answer_id": 450336, "author": "stjohnroe", "author_id": 2985, "author_profile": "https://Stackoverflow.com/users/2985", "pm_score": 2, "selected": false, "text": "<p>If you want to do this strictly through pl/sql then you could do the following:</p>\n\n<pre><code>DECLARE \n lv_stat varchar2(100) := 'select blah blah blah';\n lv_cur INTEGER;\n lv_col_cnt INTEGER;\n lv_desc DBMS_SQL.desc_tab;\nBEGIN\n DBMS_SQL.parse(lv_cur,lv_stat,DBMS_SQL.NATIVE);\n DBMS_SQL.describe_columns(lv_cur,lv_col_cnt,lv_desc);\n FOR ndx in lv_desc.FIRST .. lv_desc.LAST LOOP\n DBMS_OUTPUT.PUT_LINE(lv_desc(ndx).col_name ||' '||lv_desc(ndx).col_type);\n END LOOP;\nEND;\n</code></pre>\n\n<p>the DBMS_SQL.desc_tab contains pretty much all that you would need to know about the columns.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6479/" ]
I have a web application where users enter arbitrary sql queries for later batch processing. We want to validate the syntax of the query without actually executing it. Some of the queries will take a long time, which is why we don't want to execute them. I'm using Oracle's dbms\_sql.parse to do this. However, I now have a situation where I need to know the number and type of the result set columns. Is there a way to do this without actually executing the query? That is, to have Oracle parse the query and tell me what the result datatypes/names will be returned when the query is actually executed? I'm using Oracle 10g and and it's a Java 1.5/Servlet 2.4 application. Edit: The users who enter the queries are already users on the database. They authenticate to my app with their database credentials and the queries are executed using those credentials. Therefore they can't put in any query that they couldn't run by just connecting with sqlplus.
You should be able to prepare a SQL query to validate the syntax and get result set metadata. Preparing a query should not execute it. ``` import java.sql.*; . . . Connection conn; . . . PreparedStatement ps = conn.prepareStatement("SELECT * FROM foo"); ResultSetMetadata rsmd = ps.getMetaData(); int numberOfColumns = rsmd.getColumnCount(); ``` Then you can get metadata about each column of the result set.
163,407
<p>Is there a way to use Enum values inside a JSP without using scriptlets.</p> <p>e.g. </p> <pre><code>package com.example; public enum Direction { ASC, DESC } </code></pre> <p>so in the JSP I want to do something like this</p> <pre><code>&lt;c:if test="${foo.direction ==&lt;% com.example.Direction.ASC %&gt;}"&gt;... </code></pre>
[ { "answer_id": 163431, "author": "JeeBee", "author_id": 17832, "author_profile": "https://Stackoverflow.com/users/17832", "pm_score": 6, "selected": true, "text": "<p>You could implement the web-friendly text for a direction within the enum as a field:</p>\n\n<pre>\n<code>\n&lt;%@ page import=\"com.example.Direction\" %>\n...\n&lt;p>Direction is &lt;%=foo.direction.getFriendlyName()%>&lt;/p>\n&lt;% if (foo.direction == Direction.ASC) { %>\n&lt;p>That means you're going to heaven!&lt;/p>\n&lt;% } %>\n</code>\n</pre>\n\n<p>but that mixes the view and the model, although for simple uses it can be view-independent (\"Ascending\", \"Descending\", etc).</p>\n\n<p>Unless you don't like putting straight Java into your JSP pages, even when used for basic things like comparisons.</p>\n" }, { "answer_id": 10073363, "author": "Arnoud", "author_id": 494494, "author_profile": "https://Stackoverflow.com/users/494494", "pm_score": 2, "selected": false, "text": "<p>You can simply check against the enum value as a string:</p>\n\n<pre><code>&lt;c:if test=\"${foo.direction == 'ASC'}\"&gt;...\n</code></pre>\n" }, { "answer_id": 48703347, "author": "Mohammed Aslam", "author_id": 866576, "author_profile": "https://Stackoverflow.com/users/866576", "pm_score": 3, "selected": false, "text": "<p>It can be done like this I guess</p>\n<pre><code>&lt;c:set var=&quot;ASC&quot; value=&quot;&lt;%=Direction.ASC%&gt;&quot;/&gt;\n&lt;c:if test=&quot;${foo.direction == ASC}&quot;&gt;&lt;/c:if&gt;\n</code></pre>\n<p>the advantage is when we refactor it will reflect here too</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3332/" ]
Is there a way to use Enum values inside a JSP without using scriptlets. e.g. ``` package com.example; public enum Direction { ASC, DESC } ``` so in the JSP I want to do something like this ``` <c:if test="${foo.direction ==<% com.example.Direction.ASC %>}">... ```
You could implement the web-friendly text for a direction within the enum as a field: ``` <%@ page import="com.example.Direction" %> ... <p>Direction is <%=foo.direction.getFriendlyName()%></p> <% if (foo.direction == Direction.ASC) { %> <p>That means you're going to heaven!</p> <% } %> ``` but that mixes the view and the model, although for simple uses it can be view-independent ("Ascending", "Descending", etc). Unless you don't like putting straight Java into your JSP pages, even when used for basic things like comparisons.
163,432
<p>I am using Borland Builder C++. I have a memory leak and I know it must be because of this class I created, but I am not sure how to fix it. Please look at my code-- any ideas would be greatly appreciated!</p> <p>Here's the .h file:</p> <pre><code>#ifndef HeaderH #define HeaderH #include &lt;vcl.h&gt; #include &lt;string&gt; using std::string; class Header { public: //File Header char FileTitle[31]; char OriginatorName[16]; //Image Header char ImageDateTime[15]; char ImageCordsRep[2]; char ImageGeoLocation[61]; NitfHeader(double latitude, double longitude, double altitude, double heading); ~NitfHeader(); void SetHeader(char * date, char * time, double location[4][2]); private: void ConvertToDegMinSec (double angle, AnsiString &amp; s, bool IsLongitude); AnsiString ImageDate; AnsiString ImageTime; AnsiString Latitude_d; AnsiString Longitude_d; double Latitude; double Longitude; double Heading; double Altitude; }; </code></pre> <p>And here is some of the .cpp file:</p> <pre><code>void Header::SetHeader(char * date, char * time, double location[4][2]){ //File Header strcpy(FileTitle,"Cannon Powershot A640"); strcpy(OperatorName,"Camera Operator"); //Image Header //Image Date and Time ImageDate = AnsiString(date); ImageTime = AnsiString(time); AnsiString secstr = AnsiString(ImageTime.SubString(7,2)); AnsiString rounder = AnsiString(ImageDate.SubString(10,1)); int seconds = secstr.ToInt(); //Round off seconds - will this be necessary with format hh:mm:ss in text file? if (rounder.ToInt() &gt; 4) { seconds++; } AnsiString dateTime = ImageDate.SubString(7,4)+ ImageDate.SubString(4,2) + ImageDate.SubString(1,2) + ImageTime.SubString(1,2) + ImageTime.SubString(4,2) + AnsiString(seconds); strcpy(ImageDateTime,dateTime.c_str()); //Image Coordinates Representation strcpy(ImageCordsRep,"G"); //Image Geographic Location AnsiString lat; AnsiString lon; AnsiString locationlat_d; AnsiString locationlon_d; AnsiString corner; for (int i = 0; i &lt; 4; i++){ ConvertToDegMinSec(location[i][0],lat,false); ConvertToDegMinSec(location[i][1],lon,true); if(location[i][0] &lt; 0){ locationlat_d = 'S'; ConvertToDegMinSec(-location[i][0],lat,false); }else if(location[i][0] &gt; 0){ locationlat_d = 'N'; }else locationlat_d = ' '; if(location[i][1] &lt; 0){ locationlon_d = 'W'; ConvertToDegMinSec(-location[i][1],lon,true); }else if(location[i][1] &gt; 0){ locationlon_d = 'E'; }else locationlon_d = ' '; corner += lat + locationlat_d + lon + locationlon_d; } strcpy(ImageGeoLocation,corner.c_str()); } </code></pre> <p>Now when I use the class in main, basically I just create a pointer:</p> <pre><code>Header * header = new Header; header-&gt;SetHeader(t[5],t[6],corners-&gt;location); char * imageLocation = header-&gt;ImageGeoLocation; //do something with imageLocation delete header; </code></pre> <p>Where corners->location is a string from another class, and t[5] and t[6] are both strings. The problem is that imageLocation doesn't contain what is expected, and often just garbage. I have read a lot about memory leaks and pointers, but I am still very new to programming and some of it is quite confusing. Any suggestions would be fabulous!!</p>
[ { "answer_id": 163438, "author": "coppro", "author_id": 16855, "author_profile": "https://Stackoverflow.com/users/16855", "pm_score": 2, "selected": false, "text": "<p>Your memory leak is in <code>main</code>; you are making a pointer with <code>new</code>, but not subsequently calling <code>delete</code>.</p>\n\n<p>If you wish to just create an object of type <code>Header</code> that will be destroyed when <code>main</code> exits, just declare it as \"<code>Header header;</code>\" If you wish to create a persistent pointer, you should use <code>new</code> as you do, but be sure to <code>delete header;</code> and some point prior to the program ending.</p>\n" }, { "answer_id": 163466, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 4, "selected": true, "text": "<p>I'm afraid there are a number of issues here.</p>\n\n<p>For starters <code>char ImageCordsRep[1];</code> doesn't work ... a string is always null terminated, so when you do <code>strcpy(ImageCordsRep,\"G\");</code> you are overflowing the buffer.</p>\n\n<p>It would also be good practice to terminate all those string buffers with a null in your constructor, so they are always valid strings.</p>\n\n<p>Even better would be to use a string class instead of the char arrays, or at least use 'strncpy' to prevent buffer overruns if the incoming strings are larger than you expect.</p>\n" }, { "answer_id": 163469, "author": "Ken", "author_id": 20621, "author_profile": "https://Stackoverflow.com/users/20621", "pm_score": 0, "selected": false, "text": "<p>Something else...</p>\n\n<p>Be careful not to use imageLocation after the header object is deleted. It's often better to copy the string from the object instead of getting a pointer to it. It could be OK in this case depending on the rest of the code.</p>\n\n<pre><code>Header * header = new Header;\nheader-&gt;SetHeader(t[5],t[6],corners-&gt;location);\nchar * imageLocation = header-&gt;ImageGeoLocation;\n</code></pre>\n" }, { "answer_id": 163486, "author": "Torlack", "author_id": 5243, "author_profile": "https://Stackoverflow.com/users/5243", "pm_score": 1, "selected": false, "text": "<p>Is your problem that ImageGeoLocation is trash or you have a memory leak?</p>\n\n<p>If you code is written as such:</p>\n\n<pre><code>Header * header = new Header;\nheader-&gt;SetHeader(t[5],t[6],corners-&gt;location);\nchar * imageLocation = header-&gt;ImageGeoLocation;\ndelete header;\nprintf(\"ImageLocation is %s\", imageLocation);\n</code></pre>\n\n<p>Then you problem isn't a memory leak, but that you are deleting the memory out from under imageLocation. ImageLocation is just a pointer and doesn't actually contain data, it just points to it. So if you delete the data, then the pointer is pointing to trash.</p>\n\n<p>If that isn't the case, then debug your SetHeader method. Is ImageGeoLocation getting populated with data as you expect? If it is, then imageLocation must point to valid data unless there is some omitted code that is damaging ImageGeoLocation later on. A memory what window looking at ImageGeoLocation can help since you will be able to step through your code and see which line actually changes ImageGeoLocation where you don't expect. </p>\n" }, { "answer_id": 163551, "author": "Shishiree", "author_id": 23970, "author_profile": "https://Stackoverflow.com/users/23970", "pm_score": 0, "selected": false, "text": "<p>Thank you, Torlack, and others for replying so quickly. Basically, imageLocation gets populated fine, unless I have other code before it. For example, I have this string list, which basically contains file names.</p>\n\n<pre><code> AnsiString fileType (\"*.jpg\");\n AnsiString path = f + fileType;\n WIN32_FIND_DATA fd;\n HANDLE hFindJpg = FindFirstFile(path.c_str(),&amp;fd);\n\n //Find all images in folder\n TStringList * imageNames = new TStringList;\n\n if (hFindJpg != INVALID_HANDLE_VALUE) {\n do{\n\n if(!(fd.dwFileAttributes &amp; FILE_ATTRIBUTE_DIRECTORY)){\n image = AnsiString(fd.cFileName);\n imageNames-&gt;Add(image);\n\n jpgFileCount++;\n }\n\n }while(FindNextFile(hFindJpg,&amp;fd));\n }else ShowMessage (\"Cannot find images.\");\n\n FindClose(hFindJpg);\n</code></pre>\n\n<p>Now when I try to refer to an image from the list directly before, I get the name of the image put inside imageLocation.</p>\n\n<pre><code> //char * imageLocation = header-&gt;ImageGeoLocation; //as expected\nImage1-&gt;Picture-&gt;LoadFromFile(imageNames-&gt;Strings[j]);\nchar * imageLocation = header-&gt;ImageGeoLocation; //puts name of jpg file in imageLocation\n</code></pre>\n" }, { "answer_id": 163620, "author": "Shishiree", "author_id": 23970, "author_profile": "https://Stackoverflow.com/users/23970", "pm_score": 1, "selected": false, "text": "<p>I changed <code>strcpy()</code> to <code>strncpy()</code> and it solved my problem.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163432", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23970/" ]
I am using Borland Builder C++. I have a memory leak and I know it must be because of this class I created, but I am not sure how to fix it. Please look at my code-- any ideas would be greatly appreciated! Here's the .h file: ``` #ifndef HeaderH #define HeaderH #include <vcl.h> #include <string> using std::string; class Header { public: //File Header char FileTitle[31]; char OriginatorName[16]; //Image Header char ImageDateTime[15]; char ImageCordsRep[2]; char ImageGeoLocation[61]; NitfHeader(double latitude, double longitude, double altitude, double heading); ~NitfHeader(); void SetHeader(char * date, char * time, double location[4][2]); private: void ConvertToDegMinSec (double angle, AnsiString & s, bool IsLongitude); AnsiString ImageDate; AnsiString ImageTime; AnsiString Latitude_d; AnsiString Longitude_d; double Latitude; double Longitude; double Heading; double Altitude; }; ``` And here is some of the .cpp file: ``` void Header::SetHeader(char * date, char * time, double location[4][2]){ //File Header strcpy(FileTitle,"Cannon Powershot A640"); strcpy(OperatorName,"Camera Operator"); //Image Header //Image Date and Time ImageDate = AnsiString(date); ImageTime = AnsiString(time); AnsiString secstr = AnsiString(ImageTime.SubString(7,2)); AnsiString rounder = AnsiString(ImageDate.SubString(10,1)); int seconds = secstr.ToInt(); //Round off seconds - will this be necessary with format hh:mm:ss in text file? if (rounder.ToInt() > 4) { seconds++; } AnsiString dateTime = ImageDate.SubString(7,4)+ ImageDate.SubString(4,2) + ImageDate.SubString(1,2) + ImageTime.SubString(1,2) + ImageTime.SubString(4,2) + AnsiString(seconds); strcpy(ImageDateTime,dateTime.c_str()); //Image Coordinates Representation strcpy(ImageCordsRep,"G"); //Image Geographic Location AnsiString lat; AnsiString lon; AnsiString locationlat_d; AnsiString locationlon_d; AnsiString corner; for (int i = 0; i < 4; i++){ ConvertToDegMinSec(location[i][0],lat,false); ConvertToDegMinSec(location[i][1],lon,true); if(location[i][0] < 0){ locationlat_d = 'S'; ConvertToDegMinSec(-location[i][0],lat,false); }else if(location[i][0] > 0){ locationlat_d = 'N'; }else locationlat_d = ' '; if(location[i][1] < 0){ locationlon_d = 'W'; ConvertToDegMinSec(-location[i][1],lon,true); }else if(location[i][1] > 0){ locationlon_d = 'E'; }else locationlon_d = ' '; corner += lat + locationlat_d + lon + locationlon_d; } strcpy(ImageGeoLocation,corner.c_str()); } ``` Now when I use the class in main, basically I just create a pointer: ``` Header * header = new Header; header->SetHeader(t[5],t[6],corners->location); char * imageLocation = header->ImageGeoLocation; //do something with imageLocation delete header; ``` Where corners->location is a string from another class, and t[5] and t[6] are both strings. The problem is that imageLocation doesn't contain what is expected, and often just garbage. I have read a lot about memory leaks and pointers, but I am still very new to programming and some of it is quite confusing. Any suggestions would be fabulous!!
I'm afraid there are a number of issues here. For starters `char ImageCordsRep[1];` doesn't work ... a string is always null terminated, so when you do `strcpy(ImageCordsRep,"G");` you are overflowing the buffer. It would also be good practice to terminate all those string buffers with a null in your constructor, so they are always valid strings. Even better would be to use a string class instead of the char arrays, or at least use 'strncpy' to prevent buffer overruns if the incoming strings are larger than you expect.
163,484
<p>Any failed ASSERT statements on Windows cause the below debug message to appear and freeze the applications execution. I realise this is expected behaviour but it is running periodically on a headless machine so prevent the unit tests from failing, instead waiting on user input indefinitely.</p> <p>Is there s a registry key or compiler flag I can use to prevent this message box from requesting user input whilst still allowing the test to fail under ASSERT?</p> <p><strong>Basically, I want to do this without modifying any code, just changing compiler or Windows options.</strong></p> <p>Thanks!</p> <p><a href="http://img519.imageshack.us/img519/853/snapshotbu1.png" rel="nofollow noreferrer" title="Microsoft Visual C++ Debug Library ASSERT">Microsoft Visual C++ Debug Library ASSERT http://img519.imageshack.us/img519/853/snapshotbu1.png</a></p>
[ { "answer_id": 163561, "author": "Andrew Stein", "author_id": 13029, "author_profile": "https://Stackoverflow.com/users/13029", "pm_score": 2, "selected": true, "text": "<p>From MSDN about the ASSERT macro:</p>\n\n<p>In an MFC ISAPI application, an assertion in debug mode will bring up a modal dialog box (ASSERT dialog boxes are now modal by default); this will interrupt or hang the execution. To suppress modal assertion dialogs, add the following lines to your project source file (projectname.cpp):</p>\n\n<pre><code>// For custom assert and trace handling with WebDbg\n#ifdef _DEBUG\nCDebugReportHook g_ReportHook;\n#endif\n</code></pre>\n\n<p>Once you have done this, you can use the WebDbg tool (WebDbg.exe) to see the assertions. </p>\n" }, { "answer_id": 166180, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": 2, "selected": false, "text": "<p>I think this is a dialog shown by _CrtDbgReport for reports of type _CRT_ASSERT. With _CrtSetReportHook, you can tailor that behavior for your entire application. (i.e. requires one local change) In particular, you can continue execution after a failed assertion, thus ignoring it.</p>\n" }, { "answer_id": 2469460, "author": "MartinP", "author_id": 243879, "author_profile": "https://Stackoverflow.com/users/243879", "pm_score": 0, "selected": false, "text": "<p>In a unit-test context, it is often good to convert ASSERTs (actually <code>_CrtDbgReport</code> calls) into some exception, typically a std::exception, that contains some informative text.\nThis tends to wend its way out to the unit test's output log as a fail.\nThat's just what you want: A failed ASSERT should be a failed unit test.</p>\n\n<p>Do that by throwing in your report-hook function, as specified using: <code>_CrtSetReportHook()</code></p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163484", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5355/" ]
Any failed ASSERT statements on Windows cause the below debug message to appear and freeze the applications execution. I realise this is expected behaviour but it is running periodically on a headless machine so prevent the unit tests from failing, instead waiting on user input indefinitely. Is there s a registry key or compiler flag I can use to prevent this message box from requesting user input whilst still allowing the test to fail under ASSERT? **Basically, I want to do this without modifying any code, just changing compiler or Windows options.** Thanks! [Microsoft Visual C++ Debug Library ASSERT http://img519.imageshack.us/img519/853/snapshotbu1.png](http://img519.imageshack.us/img519/853/snapshotbu1.png "Microsoft Visual C++ Debug Library ASSERT")
From MSDN about the ASSERT macro: In an MFC ISAPI application, an assertion in debug mode will bring up a modal dialog box (ASSERT dialog boxes are now modal by default); this will interrupt or hang the execution. To suppress modal assertion dialogs, add the following lines to your project source file (projectname.cpp): ``` // For custom assert and trace handling with WebDbg #ifdef _DEBUG CDebugReportHook g_ReportHook; #endif ``` Once you have done this, you can use the WebDbg tool (WebDbg.exe) to see the assertions.
163,507
<p>Definition of variables in use:</p> <pre><code>Guid fldProId = (Guid)ffdPro.GetProperty("FieldId"); string fldProValue = (string)ffdPro.GetProperty("FieldValue"); FormFieldDef fmProFldDef = new FormFieldDef(); fmProFldDef.Key = fldProId; fmProFldDef.Retrieve(); string fldProName = (string)fmProFldDef.GetProperty("FieldName"); string fldProType = (string)fmProFldDef.GetProperty("FieldType"); </code></pre> <p>Lines giving the problem (specifically line 4 (hTxtBox.Text = ...)):</p> <pre><code>if (fldProType.ToLower() == "textbox") { Label hTxtBox = (Label)findControl(fldProName); hTxtBox.Text = fldProValue; } </code></pre> <p>All data is gathered from the database correctly, however the label goes screwy. Any ideas?</p>
[ { "answer_id": 163519, "author": "Danimal", "author_id": 2757, "author_profile": "https://Stackoverflow.com/users/2757", "pm_score": 0, "selected": false, "text": "<p>Looks like fmProFldDef's FieldName property is screwy. Did you verify that it's getting the hTxtBox's client Id?</p>\n" }, { "answer_id": 163521, "author": "TheSoftwareJedi", "author_id": 18941, "author_profile": "https://Stackoverflow.com/users/18941", "pm_score": 0, "selected": false, "text": "<p>this line is returning null:</p>\n\n<pre><code>Label hTxtBox = (Label)findControl(fldProName);\n</code></pre>\n\n<p>It may be a result of \"FieldName\" not existing (thus this line returning null, then null being used in the lookup)</p>\n\n<pre><code>string fldProName = (string)fmProFldDef.GetProperty(\"FieldName\");\n</code></pre>\n\n<p>or the text within FieldName not representing a form field.</p>\n" }, { "answer_id": 163524, "author": "rcreswick", "author_id": 3446, "author_profile": "https://Stackoverflow.com/users/3446", "pm_score": 3, "selected": true, "text": "<p>Are you sure that findControl is returning a value? </p>\n\n<p>Is hTxtBox.Text a property that does any computation on a set that could be throwing the NullReferenceException?</p>\n" }, { "answer_id": 163529, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 2, "selected": false, "text": "<p>findControl is returning a null value. It could be that the particular Label is not a direct child of the current page, i.e., inside an UpdatePanel or some other control so that the actual name of the control is different than the name applied (and thus it can't find it). For example, if it is named \"name\", the actual name may be ctl0$content$name because it is nested inside another control on the page.</p>\n\n<p>You don't really give enough information about the context for me to give you a better answer.</p>\n" }, { "answer_id": 163777, "author": "Herb Caudill", "author_id": 239663, "author_profile": "https://Stackoverflow.com/users/239663", "pm_score": 0, "selected": false, "text": "<p>FindControl might not be able to see the textbox - is it in a databound control (e.g. ListView, FormView, etc.)? </p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24565/" ]
Definition of variables in use: ``` Guid fldProId = (Guid)ffdPro.GetProperty("FieldId"); string fldProValue = (string)ffdPro.GetProperty("FieldValue"); FormFieldDef fmProFldDef = new FormFieldDef(); fmProFldDef.Key = fldProId; fmProFldDef.Retrieve(); string fldProName = (string)fmProFldDef.GetProperty("FieldName"); string fldProType = (string)fmProFldDef.GetProperty("FieldType"); ``` Lines giving the problem (specifically line 4 (hTxtBox.Text = ...)): ``` if (fldProType.ToLower() == "textbox") { Label hTxtBox = (Label)findControl(fldProName); hTxtBox.Text = fldProValue; } ``` All data is gathered from the database correctly, however the label goes screwy. Any ideas?
Are you sure that findControl is returning a value? Is hTxtBox.Text a property that does any computation on a set that could be throwing the NullReferenceException?
163,531
<p>I am creating an installer for an ASP.Net website using WiX. How do you set the ASP.Net version in IIS using WiX?</p>
[ { "answer_id": 163706, "author": "Vivek", "author_id": 7418, "author_profile": "https://Stackoverflow.com/users/7418", "pm_score": 0, "selected": false, "text": "<ul>\n<li><p>First find the correct .NET version folder. Use DirectorySearch/FileSearch to perform search.</p></li>\n<li><p>Use the above path to call aspnet_regiis.exe and set the version for the webapp from a custom action.</p>\n\n<p><code>aspnet_regiis.exe -s W3SVC/1/ROOT/SampleApp1</code></p></li>\n</ul>\n" }, { "answer_id": 164562, "author": "JasonS", "author_id": 1865, "author_profile": "https://Stackoverflow.com/users/1865", "pm_score": 1, "selected": false, "text": "<p>I found a different way by using the WiX WebApplicationExtension. You can check out the full solution <a href=\"http://www.mail-archive.com/[email protected]/msg11420.html\" rel=\"nofollow noreferrer\">here</a> and <a href=\"http://www.mail-archive.com/[email protected]/msg11451.html\" rel=\"nofollow noreferrer\">here</a>. </p>\n\n<p>I like Wix so far, but man does it takes a lot of digging to find what you are looking for.</p>\n" }, { "answer_id": 200438, "author": "thijs", "author_id": 26796, "author_profile": "https://Stackoverflow.com/users/26796", "pm_score": 6, "selected": true, "text": "<p>We use this:</p>\n\n<p>First determine the .Net framework root directory from the registry:</p>\n\n<pre><code>&lt;Property Id=\"FRAMEWORKROOT\"&gt;\n &lt;RegistrySearch Id=\"FrameworkRootDir\" Root=\"HKLM\"\n Key=\"SOFTWARE\\Microsoft\\.NETFramework\" \n Type=\"directory\" Name=\"InstallRoot\" /&gt;\n&lt;/Property&gt;\n</code></pre>\n\n<p>Then, inside the component that installs your website in IIS:</p>\n\n<pre><code>&lt;!-- Create and configure the virtual directory and application. --&gt;\n&lt;Component Id='WebVirtualDirComponent' Guid='{GUID}' Permanent='no'&gt;\n &lt;iis:WebVirtualDir Id='WebVirtualDir' Alias='YourAlias' Directory='InstallDir' WebSite='DefaultWebSite' DirProperties='DirProperties'&gt;\n &lt;iis:WebApplication Id='WebApplication' Name='YourAppName' WebAppPool='AppPool'&gt;\n &lt;!-- Required to run the application under the .net 2.0 framework --&gt;\n &lt;iis:WebApplicationExtension Extension=\"config\" CheckPath=\"yes\" Script=\"yes\"\n Executable=\"[FRAMEWORKROOT]v2.0.50727\\aspnet_isapi.dll\" Verbs=\"GET,HEAD,POST\" /&gt;\n &lt;iis:WebApplicationExtension Extension=\"resx\" CheckPath=\"yes\" Script=\"yes\"\n Executable=\"[FRAMEWORKROOT]v2.0.50727\\aspnet_isapi.dll\" Verbs=\"GET,HEAD,POST\" /&gt;\n &lt;iis:WebApplicationExtension Extension=\"svc\" CheckPath=\"no\" Script=\"yes\"\n Executable=\"[FRAMEWORKROOT]v2.0.50727\\aspnet_isapi.dll\" Verbs=\"GET,HEAD,POST\" /&gt;\n &lt;/iis:WebApplication&gt;\n &lt;/iis:WebVirtualDir&gt;\n&lt;/Component&gt;\n</code></pre>\n\n<p>For an x64 installer (<strong>THIS IS IMPORTANT</strong>)\nAdd Win64='yes' to the registry search, because the 32 bits environment on a 64 bits machine has a different registry hive (and a different frameworkroot)</p>\n\n<pre><code>&lt;RegistrySearch Id=\"FrameworkRootDir\" Root=\"HKLM\"\n Key=\"SOFTWARE\\Microsoft\\.NETFramework\" \n Type=\"directory\" \n Name=\"InstallRoot\" Win64='yes' /&gt;\n</code></pre>\n" }, { "answer_id": 923508, "author": "johnburns320", "author_id": 81005, "author_profile": "https://Stackoverflow.com/users/81005", "pm_score": 4, "selected": false, "text": "<p>Here is what worked for me after wrestling with it:</p>\n\n<pre><code> &lt;Property Id=\"FRAMEWORKBASEPATH\"&gt;\n &lt;RegistrySearch Id=\"FindFrameworkDir\" Root=\"HKLM\" Key=\"SOFTWARE\\Microsoft\\.NETFramework\" Name=\"InstallRoot\" Type=\"raw\"/&gt;\n &lt;/Property&gt;\n &lt;Property Id=\"ASPNETREGIIS\" &gt;\n &lt;DirectorySearch Path=\"[FRAMEWORKBASEPATH]\" Depth=\"4\" Id=\"FindAspNetRegIis\"&gt;\n &lt;FileSearch Name=\"aspnet_regiis.exe\" MinVersion=\"2.0.5\"/&gt;\n &lt;/DirectorySearch&gt;\n &lt;/Property&gt;\n\n &lt;CustomAction Id=\"MakeWepApp20\" Directory=\"TARGETDIR\" ExeCommand=\"[ASPNETREGIIS] -norestart -s W3SVC/[WEBSITEID]/ROOT/[VIRTUALDIR]\" Return=\"check\"/&gt;\n\n &lt;InstallExecuteSequence&gt;\n &lt;Custom Action=\"MakeWepApp20\" After=\"InstallFinalize\"&gt;ASPNETREGIIS AND NOT Installed&lt;/Custom&gt;\n &lt;/InstallExecuteSequence&gt;\n</code></pre>\n\n<p>[WEBSITEID] and [VIRTUALDIR] are properties you have to define yourself. [VIRTUALDIR] is only necessary if you are setting the ASP.NET version for an application rather than an entire website.</p>\n\n<p>The sequencing of the custom action is critical. Executing it before InstallFinalize will cause it to fail because the web application isn't available until after that.</p>\n\n<p>Thanks to Chris Burrows for a proper example of finding the aspnet_regiis executable (Google \"Using WIX to Secure a Connection String\").</p>\n\n<p>jb</p>\n" }, { "answer_id": 1374002, "author": "uli78", "author_id": 61434, "author_profile": "https://Stackoverflow.com/users/61434", "pm_score": 3, "selected": false, "text": "<p>Don't forget to enable ASP 2.0 on the server</p>\n\n<pre><code>&lt;iis:WebServiceExtension Id=\"ExtensionASP2\" Group=\"ASP.NET v2.0.50727\" Allow=\"yes\" File=\"[NETFRAMEWORK20INSTALLROOTDIR]aspnet_isapi.dll\" Description=\"ASP.NET v2.0.50727\"/&gt;\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/questions/269991/set-existing-web-service-extension-to-allow-using-wix\">Here is the sof-question</a></p>\n" }, { "answer_id": 9665684, "author": "Rory MacLeod", "author_id": 1016, "author_profile": "https://Stackoverflow.com/users/1016", "pm_score": 2, "selected": false, "text": "<p>My answer is basically the same as others seen here; I just wanted to offer people another example.</p>\n\n<p>Given the number of file extensions that ASP.NET handles, and that the list changes in each version, I think the most reliable solution is to run <code>aspnet_regiis</code> at the end of the installation. This does mean though, that I don't have any support for rollback or uninstallation. I you're creating a new application in IIS, it doesn't really matter because it will be deleted by Wix. If you're modifying an existing application, perhaps you could find out from the registry what version of ASP.NET is configured, and run that version's <code>aspnet_regiis</code> to undo your changes.</p>\n\n<p>The following uses Wix 3.5.</p>\n\n<pre><code>&lt;Fragment&gt;\n &lt;!-- Use the properties in Wix instead of doing your own registry search. --&gt;\n &lt;PropertyRef Id=\"IISMAJORVERSION\"/&gt;\n &lt;PropertyRef Id=\"NETFRAMEWORK40FULL\"/&gt;\n &lt;PropertyRef Id=\"NETFRAMEWORK40FULLINSTALLROOTDIR\"/&gt;\n\n &lt;!-- The code I'm using is intended for IIS6 and above, and it needs .NET 4 to be\n installed. --&gt;\n &lt;Condition Message=\"This application requires the .NET Framework 4.0. Please install the required version of the .NET Framework, then run this installer again.\"&gt;\n &lt;![CDATA[Installed OR (NETFRAMEWORK40FULL)]]&gt;\n &lt;/Condition&gt;\n &lt;Condition Message=\"This application requires Windows Server 2003 and Internet Information Services 6.0 or better.\"&gt;\n &lt;![CDATA[Installed OR (VersionNT &gt;= 502)]]&gt;\n &lt;/Condition&gt;\n\n &lt;!-- Populates the command line for CAQuietExec. IISWEBSITEID and IISVDIRNAME \n could be set to default values, passed in by the user, or set in your installer's \n UI. --&gt;\n &lt;CustomAction Id=\"ConfigureIis60AspNetCommand\" Property=\"ConfigureIis60AspNet\"\n Execute=\"immediate\"\n Value=\"&amp;quot;[NETFRAMEWORK40FULLINSTALLROOTDIR]aspnet_regiis.exe&amp;quot; -norestart -s &amp;quot;W3SVC/[IISWEBSITEID]/ROOT/[IISVDIRNAME]&amp;quot;\" /&gt;\n &lt;CustomAction Id=\"ConfigureIis60AspNet\" BinaryKey=\"WixCA\" DllEntry=\"CAQuietExec\" \n Execute=\"deferred\" Return=\"check\" Impersonate=\"no\"/&gt;\n &lt;InstallExecuteSequence&gt;\n &lt;Custom Action=\"ConfigureIis60AspNetCommand\" After=\"CostFinalize\"/&gt;\n\n &lt;!-- Runs the aspnet_regiis command immediately after Wix configures IIS. \n The condition shown here assumes you have a selectable feature in your \n installer with the ID \"WebAppFeature\" that contains your web components. The \n command will not be run if that feature is not being installed, or if IIS is \n not version 6. It *will* run if the application is being repaired. \n\n SKIPCONFIGUREIIS is a property defined by Wix that causes it to skip the IIS\n configuration. --&gt;\n &lt;Custom Action=\"ConfigureIis60AspNet\" After=\"ConfigureIIs\" Overridable=\"yes\"&gt;\n &lt;![CDATA[((&amp;WebAppFeature = 3) OR (REINSTALL AND (!WebAppFeature = 3))) \n AND (NOT SKIPCONFIGUREIIS) AND (IISMAJORVERSION = \"#6\")]]&gt;\n &lt;/Custom&gt;\n &lt;/InstallExecuteSequence&gt;\n &lt;UI&gt;\n &lt;ProgressText Action=\"ConfigureIis60AspNetCommand\"\n &gt;Configuring ASP.NET&lt;/ProgressText&gt;\n &lt;ProgressText Action=\"ConfigureIis60AspNet\"\n &gt;Configuring ASP.NET&lt;/ProgressText&gt;\n &lt;/UI&gt;\n\n&lt;/Fragment&gt;\n</code></pre>\n" }, { "answer_id": 10628243, "author": "LCarter", "author_id": 688126, "author_profile": "https://Stackoverflow.com/users/688126", "pm_score": 1, "selected": false, "text": "<p>This is a bit simpler. I don’t know if this works on updating an existing AppPool, but works for creating an APP Pool and setting the .NET version.</p>\n\n<pre><code>&lt;iis:WebServiceExtension Id=\"AMS_AppPool\" Name=\"AccountManagementSVC1\" Identity=\"other\" ManagedPipelineMode=\"integrated\" ManagedRuntimeVersion=\"v4.0\" User=\"AMS_AppPoolUser\" RecycleMinutes=\"120\" /&gt;\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163531", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1865/" ]
I am creating an installer for an ASP.Net website using WiX. How do you set the ASP.Net version in IIS using WiX?
We use this: First determine the .Net framework root directory from the registry: ``` <Property Id="FRAMEWORKROOT"> <RegistrySearch Id="FrameworkRootDir" Root="HKLM" Key="SOFTWARE\Microsoft\.NETFramework" Type="directory" Name="InstallRoot" /> </Property> ``` Then, inside the component that installs your website in IIS: ``` <!-- Create and configure the virtual directory and application. --> <Component Id='WebVirtualDirComponent' Guid='{GUID}' Permanent='no'> <iis:WebVirtualDir Id='WebVirtualDir' Alias='YourAlias' Directory='InstallDir' WebSite='DefaultWebSite' DirProperties='DirProperties'> <iis:WebApplication Id='WebApplication' Name='YourAppName' WebAppPool='AppPool'> <!-- Required to run the application under the .net 2.0 framework --> <iis:WebApplicationExtension Extension="config" CheckPath="yes" Script="yes" Executable="[FRAMEWORKROOT]v2.0.50727\aspnet_isapi.dll" Verbs="GET,HEAD,POST" /> <iis:WebApplicationExtension Extension="resx" CheckPath="yes" Script="yes" Executable="[FRAMEWORKROOT]v2.0.50727\aspnet_isapi.dll" Verbs="GET,HEAD,POST" /> <iis:WebApplicationExtension Extension="svc" CheckPath="no" Script="yes" Executable="[FRAMEWORKROOT]v2.0.50727\aspnet_isapi.dll" Verbs="GET,HEAD,POST" /> </iis:WebApplication> </iis:WebVirtualDir> </Component> ``` For an x64 installer (**THIS IS IMPORTANT**) Add Win64='yes' to the registry search, because the 32 bits environment on a 64 bits machine has a different registry hive (and a different frameworkroot) ``` <RegistrySearch Id="FrameworkRootDir" Root="HKLM" Key="SOFTWARE\Microsoft\.NETFramework" Type="directory" Name="InstallRoot" Win64='yes' /> ```
163,535
<p>In implementing my first significant script using jquery I needed to find a specific web-control on the page. Since I work with DotNetNuke, there is no guaranteeing the controls ClientID since the container control may change from site to site. I ended up using an attribute selector that looks for an ID that ends with the control's server ID.</p> <pre><code>$("select[id$='cboPanes']") </code></pre> <p>This seems like it might not be the best method. Is there another way to do this?</p> <hr> <p>@Roosteronacid - While I am getting the controls I want, I try to follow the idioms for a given technology/language. When I program in C#, I try to do it in the way that best takes advantage of C# features. As this is my first effort at really using jQuery, and since this will be used by 10's of thousands of users, I want to make sure I am creating code that is also a good example for others.</p> <p>@toohool - that would definitely work, but unfortunately I need to keep the javascript in separate files for performance reasons. You can't really take advantage of caching very well if you inline the javascript since each "page" is dynamically generated. I would end up sending the same javascript to the client over and over again just because other content on the page changed.</p> <hr> <p>@Roosteronacid - While I am getting the controls I want, I try to follow the idioms for a given technology/language. When I program in C#, I try to do it in the way that best takes advantage of C# features. As this is my first effort at really using jQuery, and since this will be used by 10's of thousands of users, I want to make sure I am creating code that is also a good example for others.</p> <p>@toohool - that would definitely work, but unfortunately I need to keep the javascript in separate files for performance reasons. You can't really take advantage of caching very well if you inline the javascript since each "page" is dynamically generated. I would end up sending the same javascript to the client over and over again just because other content on the page changed.</p>
[ { "answer_id": 163559, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 2, "selected": false, "text": "<p>Use a marker class on the control, and select that via jQuery.</p>\n" }, { "answer_id": 163566, "author": "toohool", "author_id": 14334, "author_profile": "https://Stackoverflow.com/users/14334", "pm_score": 3, "selected": false, "text": "<pre><code>$(\"#&lt;%= cboPanes.ClientID %&gt;\")\n</code></pre>\n\n<p>This will dynamically inject the DOM ID of the control. Of course, this means your JS has to be in an ASPX file, not in an external JS file.</p>\n" }, { "answer_id": 163579, "author": "cllpse", "author_id": 20946, "author_profile": "https://Stackoverflow.com/users/20946", "pm_score": 2, "selected": false, "text": "<p>Other than being a bit more expensive, performance-wise, I can't see anything wrong with using that selector. After all; you are getting the controls you want to access.</p>\n" }, { "answer_id": 165572, "author": "Eric Schoonover", "author_id": 3957, "author_profile": "https://Stackoverflow.com/users/3957", "pm_score": 2, "selected": false, "text": "<p>One thing that I have done in the past (in JavaScript not jQuery), in the above my JavaScript imports, is output the dynamic controls ID's similiar to what toohool recommends and assign them to variables that I reference in my script imports.</p>\n\n<p>Something like this, should allow you to take advantage of caching and still enable you to have the exact client IDs:</p>\n\n<pre><code>&lt;head&gt;\n &lt;script type=\"text/javascript&gt;\n var cboPanesID = &lt;%= cboPanes.ClientID %&gt;;\n &lt;/script&gt;\n\n &lt;!-- this JS import references cboPanesID variable declared above --&gt;\n &lt;script src=\"jquery.plugin.js\"&gt;&lt;/script&gt;\n&lt;/head&gt;\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163535", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4820/" ]
In implementing my first significant script using jquery I needed to find a specific web-control on the page. Since I work with DotNetNuke, there is no guaranteeing the controls ClientID since the container control may change from site to site. I ended up using an attribute selector that looks for an ID that ends with the control's server ID. ``` $("select[id$='cboPanes']") ``` This seems like it might not be the best method. Is there another way to do this? --- @Roosteronacid - While I am getting the controls I want, I try to follow the idioms for a given technology/language. When I program in C#, I try to do it in the way that best takes advantage of C# features. As this is my first effort at really using jQuery, and since this will be used by 10's of thousands of users, I want to make sure I am creating code that is also a good example for others. @toohool - that would definitely work, but unfortunately I need to keep the javascript in separate files for performance reasons. You can't really take advantage of caching very well if you inline the javascript since each "page" is dynamically generated. I would end up sending the same javascript to the client over and over again just because other content on the page changed. --- @Roosteronacid - While I am getting the controls I want, I try to follow the idioms for a given technology/language. When I program in C#, I try to do it in the way that best takes advantage of C# features. As this is my first effort at really using jQuery, and since this will be used by 10's of thousands of users, I want to make sure I am creating code that is also a good example for others. @toohool - that would definitely work, but unfortunately I need to keep the javascript in separate files for performance reasons. You can't really take advantage of caching very well if you inline the javascript since each "page" is dynamically generated. I would end up sending the same javascript to the client over and over again just because other content on the page changed.
``` $("#<%= cboPanes.ClientID %>") ``` This will dynamically inject the DOM ID of the control. Of course, this means your JS has to be in an ASPX file, not in an external JS file.
163,537
<p>I'm trying to debug an MSBuild task, and I know there is some way to write to the MSBuild log from within a custom task but I forget how.</p>
[ { "answer_id": 163558, "author": "Kent Boogaart", "author_id": 5380, "author_profile": "https://Stackoverflow.com/users/5380", "pm_score": 4, "selected": true, "text": "<p>The base <a href=\"http://msdn.microsoft.com/en-us/library/microsoft.build.utilities.task.aspx\" rel=\"noreferrer\">Task</a> class has a <code>Log</code> property you can use:</p>\n\n<pre><code>Log.LogMessage(\"My message\");\n</code></pre>\n" }, { "answer_id": 823680, "author": "si618", "author_id": 44540, "author_profile": "https://Stackoverflow.com/users/44540", "pm_score": 1, "selected": false, "text": "<p>For unit testing purposes, I wrap the logger around a helper class</p>\n\n<pre><code>public static void Log(ITask task, string message, MessageImportance importance)\n{\n try\n {\n BuildMessageEventArgs args = new BuildMessageEventArgs(message, string.Empty, \n task.ToString(), importance);\n task.BuildEngine.LogMessageEvent(args);\n }\n catch (NullReferenceException)\n {\n // Don't throw as task and BuildEngine will be null in unit test.\n }\n}\n</code></pre>\n\n<p>Nowadays I'd probably convert that into an extension method for convenience.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163537", "https://Stackoverflow.com", "https://Stackoverflow.com/users/327/" ]
I'm trying to debug an MSBuild task, and I know there is some way to write to the MSBuild log from within a custom task but I forget how.
The base [Task](http://msdn.microsoft.com/en-us/library/microsoft.build.utilities.task.aspx) class has a `Log` property you can use: ``` Log.LogMessage("My message"); ```
163,542
<p>If I do the following:</p> <pre><code>import subprocess from cStringIO import StringIO subprocess.Popen(['grep','f'],stdout=subprocess.PIPE,stdin=StringIO('one\ntwo\nthree\nfour\nfive\nsix\n')).communicate()[0] </code></pre> <p>I get:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in ? File "/build/toolchain/mac32/python-2.4.3/lib/python2.4/subprocess.py", line 533, in __init__ (p2cread, p2cwrite, File "/build/toolchain/mac32/python-2.4.3/lib/python2.4/subprocess.py", line 830, in _get_handles p2cread = stdin.fileno() AttributeError: 'cStringIO.StringI' object has no attribute 'fileno' </code></pre> <p>Apparently a cStringIO.StringIO object doesn't quack close enough to a file duck to suit subprocess.Popen. How do I work around this?</p>
[ { "answer_id": 163556, "author": "Daryl Spitzer", "author_id": 4766, "author_profile": "https://Stackoverflow.com/users/4766", "pm_score": 6, "selected": false, "text": "<p>I figured out this workaround:</p>\n\n<pre><code>&gt;&gt;&gt; p = subprocess.Popen(['grep','f'],stdout=subprocess.PIPE,stdin=subprocess.PIPE)\n&gt;&gt;&gt; p.stdin.write(b'one\\ntwo\\nthree\\nfour\\nfive\\nsix\\n') #expects a bytes type object\n&gt;&gt;&gt; p.communicate()[0]\n'four\\nfive\\n'\n&gt;&gt;&gt; p.stdin.close()\n</code></pre>\n\n<p>Is there a better one?</p>\n" }, { "answer_id": 163870, "author": "Dan Lenski", "author_id": 20789, "author_profile": "https://Stackoverflow.com/users/20789", "pm_score": 4, "selected": false, "text": "<blockquote>\n <p>Apparently a cStringIO.StringIO object doesn't quack close enough to\n a file duck to suit subprocess.Popen</p>\n</blockquote>\n\n<p>I'm afraid not. The pipe is a low-level OS concept, so it absolutely requires a file object that is represented by an OS-level file descriptor. Your workaround is the right one.</p>\n" }, { "answer_id": 165662, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 10, "selected": true, "text": "<p><a href=\"https://docs.python.org/3/library/subprocess.html?highlight=subprocess#subprocess.Popen.communicate\" rel=\"noreferrer\"><code>Popen.communicate()</code></a> documentation:</p>\n<blockquote>\n<p>Note that if you want to send data to\nthe process’s stdin, you need to\ncreate the Popen object with\nstdin=PIPE. Similarly, to get anything\nother than None in the result tuple,\nyou need to give stdout=PIPE and/or\nstderr=PIPE too.</p>\n<p><strong>Replacing os.popen*</strong></p>\n</blockquote>\n<pre><code> pipe = os.popen(cmd, 'w', bufsize)\n # ==&gt;\n pipe = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE).stdin\n</code></pre>\n<blockquote>\n<p><strong>Warning</strong> Use communicate() rather than\nstdin.write(), stdout.read() or\nstderr.read() to avoid deadlocks due\nto any of the other OS pipe buffers\nfilling up and blocking the child\nprocess.</p>\n</blockquote>\n<p>So your example could be written as follows:</p>\n<pre><code>from subprocess import Popen, PIPE, STDOUT\n\np = Popen(['grep', 'f'], stdout=PIPE, stdin=PIPE, stderr=STDOUT) \ngrep_stdout = p.communicate(input=b'one\\ntwo\\nthree\\nfour\\nfive\\nsix\\n')[0]\nprint(grep_stdout.decode())\n# -&gt; four\n# -&gt; five\n# -&gt;\n</code></pre>\n<hr />\n<p>On Python 3.5+ (3.6+ for <code>encoding</code>), you could use <a href=\"https://docs.python.org/3/library/subprocess.html#subprocess.run\" rel=\"noreferrer\"><code>subprocess.run</code></a>, to pass input as a string to an external command and get its exit status, and its output as a string back in one call:</p>\n<pre><code>#!/usr/bin/env python3\nfrom subprocess import run, PIPE\n\np = run(['grep', 'f'], stdout=PIPE,\n input='one\\ntwo\\nthree\\nfour\\nfive\\nsix\\n', encoding='ascii')\nprint(p.returncode)\n# -&gt; 0\nprint(p.stdout)\n# -&gt; four\n# -&gt; five\n# -&gt; \n</code></pre>\n" }, { "answer_id": 732822, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<pre><code>p = Popen(['grep', 'f'], stdout=PIPE, stdin=PIPE, stderr=STDOUT) \np.stdin.write('one\\n')\ntime.sleep(0.5)\np.stdin.write('two\\n')\ntime.sleep(0.5)\np.stdin.write('three\\n')\ntime.sleep(0.5)\ntestresult = p.communicate()[0]\ntime.sleep(0.5)\nprint(testresult)\n</code></pre>\n" }, { "answer_id": 10134899, "author": "Michael Waddell", "author_id": 1238190, "author_profile": "https://Stackoverflow.com/users/1238190", "pm_score": 4, "selected": false, "text": "<pre><code>from subprocess import Popen, PIPE\nfrom tempfile import SpooledTemporaryFile as tempfile\nf = tempfile()\nf.write('one\\ntwo\\nthree\\nfour\\nfive\\nsix\\n')\nf.seek(0)\nprint Popen(['/bin/grep','f'],stdout=PIPE,stdin=f).stdout.read()\nf.close()\n</code></pre>\n" }, { "answer_id": 17109481, "author": "Lucien Hercaud", "author_id": 2486227, "author_profile": "https://Stackoverflow.com/users/2486227", "pm_score": 3, "selected": false, "text": "<pre><code>\"\"\"\nEx: Dialog (2-way) with a Popen()\n\"\"\"\n\np = subprocess.Popen('Your Command Here',\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT,\n stdin=PIPE,\n shell=True,\n bufsize=0)\np.stdin.write('START\\n')\nout = p.stdout.readline()\nwhile out:\n line = out\n line = line.rstrip(\"\\n\")\n\n if \"WHATEVER1\" in line:\n pr = 1\n p.stdin.write('DO 1\\n')\n out = p.stdout.readline()\n continue\n\n if \"WHATEVER2\" in line:\n pr = 2\n p.stdin.write('DO 2\\n')\n out = p.stdout.readline()\n continue\n\"\"\"\n..........\n\"\"\"\n\nout = p.stdout.readline()\n\np.wait()\n</code></pre>\n" }, { "answer_id": 23740991, "author": "Lord Henry Wotton", "author_id": 2426246, "author_profile": "https://Stackoverflow.com/users/2426246", "pm_score": 3, "selected": false, "text": "<p>Beware that <code>Popen.communicate(input=s)</code>may give you trouble if<code>s</code>is too big, because apparently the parent process will buffer it <em>before</em> forking the child subprocess, meaning it needs \"twice as much\" used memory at that point (at least according to the \"under the hood\" explanation and linked documentation found <a href=\"https://stackoverflow.com/a/13329386/2426246\">here</a>). In my particular case,<code>s</code>was a generator that was first fully expanded and only then written to<code>stdin</code> so the parent process was huge right before the child was spawned, \nand no memory was left to fork it:</p>\n\n<p><code>File \"/opt/local/stow/python-2.7.2/lib/python2.7/subprocess.py\", line 1130, in _execute_child\n self.pid = os.fork()\nOSError: [Errno 12] Cannot allocate memory</code></p>\n" }, { "answer_id": 24982453, "author": "qed", "author_id": 562222, "author_profile": "https://Stackoverflow.com/users/562222", "pm_score": 4, "selected": false, "text": "<p>I am using python3 and found out that you need to encode your string before you can pass it into stdin:</p>\n\n<pre><code>p = Popen(['grep', 'f'], stdout=PIPE, stdin=PIPE, stderr=PIPE)\nout, err = p.communicate(input='one\\ntwo\\nthree\\nfour\\nfive\\nsix\\n'.encode())\nprint(out)\n</code></pre>\n" }, { "answer_id": 33482438, "author": "Graham Christensen", "author_id": 637129, "author_profile": "https://Stackoverflow.com/users/637129", "pm_score": 5, "selected": false, "text": "<p>I'm a bit surprised nobody suggested creating a pipe, which is in my opinion the far simplest way to pass a string to stdin of a subprocess:</p>\n\n<pre><code>read, write = os.pipe()\nos.write(write, \"stdin input here\")\nos.close(write)\n\nsubprocess.check_call(['your-command'], stdin=read)\n</code></pre>\n" }, { "answer_id": 41036665, "author": "Flimm", "author_id": 247696, "author_profile": "https://Stackoverflow.com/users/247696", "pm_score": 5, "selected": false, "text": "<p>There's a beautiful solution if you're using Python 3.4 or better. Use the <code>input</code> argument instead of the <code>stdin</code> argument, which accepts a bytes argument:</p>\n<pre><code>output_bytes = subprocess.check_output(\n [&quot;sed&quot;, &quot;s/foo/bar/&quot;],\n input=b&quot;foo&quot;,\n)\n</code></pre>\n<p>This works for <a href=\"https://docs.python.org/3/library/subprocess.html#subprocess.check_output\" rel=\"noreferrer\"><code>check_output</code></a> and <a href=\"https://docs.python.org/3/library/subprocess.html#subprocess.run\" rel=\"noreferrer\"><code>run</code></a>, but not <a href=\"https://docs.python.org/3/library/subprocess.html#subprocess.call\" rel=\"noreferrer\"><code>call</code></a> or <a href=\"https://docs.python.org/3/library/subprocess.html#subprocess.check_call\" rel=\"noreferrer\"><code>check_call</code></a> for some reason.</p>\n<p>In Python 3.7+, you can also add <code>text=True</code> to make <code>check_output</code> take a string as input and return a string (instead of <code>bytes</code>):</p>\n<pre><code>output_string = subprocess.check_output(\n [&quot;sed&quot;, &quot;s/foo/bar/&quot;],\n input=&quot;foo&quot;,\n text=True,\n)\n</code></pre>\n" }, { "answer_id": 59495980, "author": "Boris Verkhovskiy", "author_id": 3064538, "author_profile": "https://Stackoverflow.com/users/3064538", "pm_score": 3, "selected": false, "text": "<p>On Python 3.7+ do this:</p>\n\n<pre><code>my_data = \"whatever you want\\nshould match this f\"\nsubprocess.run([\"grep\", \"f\"], text=True, input=my_data)\n</code></pre>\n\n<p>and you'll probably want to add <code>capture_output=True</code> to get the output of running the command as a string.</p>\n\n<p>On older versions of Python, replace <code>text=True</code> with <code>universal_newlines=True</code>:</p>\n\n<pre><code>subprocess.run([\"grep\", \"f\"], universal_newlines=True, input=my_data)\n</code></pre>\n" }, { "answer_id": 66754162, "author": "Ben DeMott", "author_id": 294253, "author_profile": "https://Stackoverflow.com/users/294253", "pm_score": 2, "selected": false, "text": "<p>This is overkill for <code>grep</code>, but through my journeys I've learned about the Linux command <code>expect</code>, and the python library <code>pexpect</code></p>\n<ul>\n<li><strong><a href=\"https://linux.die.net/man/1/expect\" rel=\"nofollow noreferrer\">expect</a></strong>: dialogue with interactive programs</li>\n<li><strong><a href=\"https://pexpect.readthedocs.io/en/stable/overview.html\" rel=\"nofollow noreferrer\">pexpect</a></strong>: Python module for spawning child applications; controlling them; and responding to expected patterns in their output.</li>\n</ul>\n<pre class=\"lang-sh prettyprint-override\"><code>import pexpect\nchild = pexpect.spawn('grep f', timeout=10)\nchild.sendline('text to match')\nprint(child.before)\n</code></pre>\n<p>Working with interactive shell applications like <code>ftp</code> is trivial with <strong><a href=\"https://pexpect.readthedocs.io/en/stable/overview.html\" rel=\"nofollow noreferrer\">pexpect</a></strong></p>\n<pre class=\"lang-py prettyprint-override\"><code>import pexpect\nchild = pexpect.spawn ('ftp ftp.openbsd.org')\nchild.expect ('Name .*: ')\nchild.sendline ('anonymous')\nchild.expect ('Password:')\nchild.sendline ('[email protected]')\nchild.expect ('ftp&gt; ')\nchild.sendline ('ls /pub/OpenBSD/')\nchild.expect ('ftp&gt; ')\nprint child.before # Print the result of the ls command.\nchild.interact() # Give control of the child to the user.\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4766/" ]
If I do the following: ``` import subprocess from cStringIO import StringIO subprocess.Popen(['grep','f'],stdout=subprocess.PIPE,stdin=StringIO('one\ntwo\nthree\nfour\nfive\nsix\n')).communicate()[0] ``` I get: ``` Traceback (most recent call last): File "<stdin>", line 1, in ? File "/build/toolchain/mac32/python-2.4.3/lib/python2.4/subprocess.py", line 533, in __init__ (p2cread, p2cwrite, File "/build/toolchain/mac32/python-2.4.3/lib/python2.4/subprocess.py", line 830, in _get_handles p2cread = stdin.fileno() AttributeError: 'cStringIO.StringI' object has no attribute 'fileno' ``` Apparently a cStringIO.StringIO object doesn't quack close enough to a file duck to suit subprocess.Popen. How do I work around this?
[`Popen.communicate()`](https://docs.python.org/3/library/subprocess.html?highlight=subprocess#subprocess.Popen.communicate) documentation: > > Note that if you want to send data to > the process’s stdin, you need to > create the Popen object with > stdin=PIPE. Similarly, to get anything > other than None in the result tuple, > you need to give stdout=PIPE and/or > stderr=PIPE too. > > > **Replacing os.popen\*** > > > ``` pipe = os.popen(cmd, 'w', bufsize) # ==> pipe = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE).stdin ``` > > **Warning** Use communicate() rather than > stdin.write(), stdout.read() or > stderr.read() to avoid deadlocks due > to any of the other OS pipe buffers > filling up and blocking the child > process. > > > So your example could be written as follows: ``` from subprocess import Popen, PIPE, STDOUT p = Popen(['grep', 'f'], stdout=PIPE, stdin=PIPE, stderr=STDOUT) grep_stdout = p.communicate(input=b'one\ntwo\nthree\nfour\nfive\nsix\n')[0] print(grep_stdout.decode()) # -> four # -> five # -> ``` --- On Python 3.5+ (3.6+ for `encoding`), you could use [`subprocess.run`](https://docs.python.org/3/library/subprocess.html#subprocess.run), to pass input as a string to an external command and get its exit status, and its output as a string back in one call: ``` #!/usr/bin/env python3 from subprocess import run, PIPE p = run(['grep', 'f'], stdout=PIPE, input='one\ntwo\nthree\nfour\nfive\nsix\n', encoding='ascii') print(p.returncode) # -> 0 print(p.stdout) # -> four # -> five # -> ```
163,550
<p>Is there a maximum number of characters that can be written to a file using a StreamWriter? Or is there a maximum number of characters that <code>WriteLine()</code> can output? I am trying to write some data to a file but all of the data does not seem to make it. This is the current state of my code:</p> <pre><code>StreamWriter sw = new StreamWriter(pathToFile); foreach (GridViewRow record in gv_Records.Rows) { string recordInfo = "recordInformation"; sw.WriteLine(recordInfo); } </code></pre>
[ { "answer_id": 163585, "author": "itsmatt", "author_id": 7862, "author_profile": "https://Stackoverflow.com/users/7862", "pm_score": 6, "selected": true, "text": "<p>Are you calling StreamWriter.Close() or Flush()?</p>\n" }, { "answer_id": 163594, "author": "user7116", "author_id": 7116, "author_profile": "https://Stackoverflow.com/users/7116", "pm_score": 3, "selected": false, "text": "<p>Be sure you wrap your StreamWriter in a using-block, or are careful about your <a href=\"http://msdn.microsoft.com/en-us/library/system.io.streamwriter.close.aspx\" rel=\"noreferrer\">explicit management of the resource's lifetime</a>.</p>\n\n<pre><code>using (StreamWriter writer = new StreamWriter(@\"somefile.txt\"))\n{\n // ...\n writer.WriteLine(largeAmountsOfData);\n // ...\n}\n</code></pre>\n" }, { "answer_id": 163595, "author": "MagicKat", "author_id": 8505, "author_profile": "https://Stackoverflow.com/users/8505", "pm_score": 0, "selected": false, "text": "<p>Make sure that you are calling .Flush()</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2486/" ]
Is there a maximum number of characters that can be written to a file using a StreamWriter? Or is there a maximum number of characters that `WriteLine()` can output? I am trying to write some data to a file but all of the data does not seem to make it. This is the current state of my code: ``` StreamWriter sw = new StreamWriter(pathToFile); foreach (GridViewRow record in gv_Records.Rows) { string recordInfo = "recordInformation"; sw.WriteLine(recordInfo); } ```
Are you calling StreamWriter.Close() or Flush()?
163,563
<p>I have an issue - </p> <p>The javascript <code>Date("mm-dd-yyyy")</code> constructor doesn't work for FF. It works fine for IE.</p> <ul> <li>IE : <code>new Date("04-02-2008")</code> => <code>"Wed Apr 2 00:00:00 EDT 2008"</code></li> <li>FF2 : <code>new Date("04-02-2008")</code> => <code>Invalid Date</code> </li> </ul> <p>So lets try another constructor. Trying this constructor <code>Date("yyyy", "mm", "dd")</code></p> <ul> <li>IE : <code>new Date("2008", "04", "02");</code> => <code>"Fri May 2 00:00:00 EDT 2008"</code></li> <li>FF : <code>new Date("2008", "04", "02");</code> => <code>"Fri May 2 00:00:00 EDT 2008"</code></li> <li>IE : <code>new Date("2008", "03", "02");</code> => <code>"Wed Apr 2 00:00:00 EDT 2008"</code></li> <li>FF : <code>new Date("2008", "03", "02");</code> => <code>"Wed Apr 2 00:00:00 EDT 2008"</code></li> </ul> <p>So the <code>Date("yyyy", "mm", "dd")</code> constructor uses an index of <code>0</code> to represent January. </p> <p>Has anyone dealt with this?<br> There must be a better way than subtracting 1 from the months.</p>
[ { "answer_id": 163584, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 7, "selected": true, "text": "<p>It is the <a href=\"http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date\" rel=\"noreferrer\">definition of the Date object</a> to use values 0-11 for the <code>month</code> field.</p>\n\n<p>I believe that the constructor using a String is system-dependent (not to mention locale/timezone dependent) so you are probably better off using the constructor where you specify year/month/day as seperate parameters.</p>\n\n<p>BTW, in Firefox, </p>\n\n<pre><code>new Date(\"04/02/2008\");\n</code></pre>\n\n<p>works fine for me - it will interpret slashes, but not hyphens. I think this proves my point that using a String to construct a Date object is problemsome. Use explicit values for month/day/year instead:</p>\n\n<pre><code>new Date(2008, 3, 2);\n</code></pre>\n" }, { "answer_id": 163593, "author": "cllpse", "author_id": 20946, "author_profile": "https://Stackoverflow.com/users/20946", "pm_score": 0, "selected": false, "text": "<p>Bold statement.</p>\n\n<p>This might have your interest: <a href=\"http://ejohn.org/blog/javascript-pretty-date/\" rel=\"nofollow noreferrer\">JavaScript Pretty Date</a>.</p>\n" }, { "answer_id": 164821, "author": "roenving", "author_id": 23142, "author_profile": "https://Stackoverflow.com/users/23142", "pm_score": 1, "selected": false, "text": "<p>You're quite right, month is indicated as an index, so January is month number 0 and December is month number 11 ...</p>\n\n<p>-- and there is no work-around as it is stated clearly in the ECMA-script-definition, though simple tricks commonly will work:</p>\n\n<pre><code>var myDate = \"2008,03,02\".split(\",\");\nvar theDate = new Date(myDate[0],myDate[1]-1,myDate[2]); \nalert(theDate);\n</code></pre>\n" }, { "answer_id": 744134, "author": "joedotnot", "author_id": 90259, "author_profile": "https://Stackoverflow.com/users/90259", "pm_score": 4, "selected": false, "text": "<p>nice trick indeed, which i just found out the hard way (by thinking thru it).\nBut i used a more natural date string with hyphen :-)</p>\n\n<pre><code>var myDateArray = \"2008-03-02\".split(\"-\");\nvar theDate = new Date(myDateArray[0],myDateArray[1]-1,myDateArray[2]); \nalert(theDate);\n</code></pre>\n" }, { "answer_id": 5550829, "author": "Frank", "author_id": 692733, "author_profile": "https://Stackoverflow.com/users/692733", "pm_score": 2, "selected": false, "text": "<p>Using</p>\n\n<pre><code>var theDate = new Date(myDate[0],myDate[1]-1,myDate[2]); \n</code></pre>\n\n<p>Is fine, but it shows some strange behaviors when month and day values are erroneous.</p>\n\n<p>Try casting a date where both <code>myDate[1]-1</code> and <code>myDate[2]</code> have values of 55. Javascript still returns a date, though the input is obviously not correct.</p>\n\n<p>I would have preferred javascript to return an error in such a case.</p>\n" }, { "answer_id": 11523950, "author": "Constantine M", "author_id": 733971, "author_profile": "https://Stackoverflow.com/users/733971", "pm_score": 2, "selected": false, "text": "<p>@Frank: you are right. When you need to validate date,</p>\n\n<pre><code>var theDate = new Date(myDate[0],myDate[1]-1,myDate[2]); \n</code></pre>\n\n<p>will not work.</p>\n\n<p>What happens is that it keeps on adding the extra parameter. For example:</p>\n\n<pre><code>new Date(\"2012\", \"11\", \"57\") // Date {Sat Jan 26 2013 00:00:00 GMT+0530 (IST)}\n</code></pre>\n\n<p>Date object takes the extra days (57-31=26) and adds it to the date we created.</p>\n\n<p>Or if we try constructing a date object with:</p>\n\n<pre><code>new Date(\"2012\", \"11\", \"57\", \"57\") //Date {Mon Jan 28 2013 09:00:00 GMT+0530 (IST)}\n</code></pre>\n\n<p>an extra 2 days and 9 hours (57=24+24+9) are added.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7617/" ]
I have an issue - The javascript `Date("mm-dd-yyyy")` constructor doesn't work for FF. It works fine for IE. * IE : `new Date("04-02-2008")` => `"Wed Apr 2 00:00:00 EDT 2008"` * FF2 : `new Date("04-02-2008")` => `Invalid Date` So lets try another constructor. Trying this constructor `Date("yyyy", "mm", "dd")` * IE : `new Date("2008", "04", "02");` => `"Fri May 2 00:00:00 EDT 2008"` * FF : `new Date("2008", "04", "02");` => `"Fri May 2 00:00:00 EDT 2008"` * IE : `new Date("2008", "03", "02");` => `"Wed Apr 2 00:00:00 EDT 2008"` * FF : `new Date("2008", "03", "02");` => `"Wed Apr 2 00:00:00 EDT 2008"` So the `Date("yyyy", "mm", "dd")` constructor uses an index of `0` to represent January. Has anyone dealt with this? There must be a better way than subtracting 1 from the months.
It is the [definition of the Date object](http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date) to use values 0-11 for the `month` field. I believe that the constructor using a String is system-dependent (not to mention locale/timezone dependent) so you are probably better off using the constructor where you specify year/month/day as seperate parameters. BTW, in Firefox, ``` new Date("04/02/2008"); ``` works fine for me - it will interpret slashes, but not hyphens. I think this proves my point that using a String to construct a Date object is problemsome. Use explicit values for month/day/year instead: ``` new Date(2008, 3, 2); ```
163,569
<p>I have a Flex application that calls a function which searches a large document collection. Depending on the search term, the user may want to stop the request from flex. </p> <p>I’d like to not only stop the flex application from expecting the request, but also stop the CFC request. Is this possible? What’s the best approach for doing this?</p>
[ { "answer_id": 163790, "author": "Peter Boughton", "author_id": 9360, "author_profile": "https://Stackoverflow.com/users/9360", "pm_score": 0, "selected": false, "text": "<p>You can programmatically end requests with either <code>&lt;cfabort/&gt;</code> or <code>&lt;cfsetting requesttimeout=\"0\"/&gt;</code> - but that's on the CF server side of things, which I don't think is what you're asking?</p>\n\n<p>Ending it remotely... well, if you have FusionReactor it <em>might</em> be possible to contact that using Flex and have it interrupt the request for you.\n(You can certainly try to end requests within FusionReactor, but whether or not Flex can actually ask FR to stop it... you'd have to ask that on the FR mailing list if there's a way to do that.)</p>\n\n<p><br/>\nPossibly an alternative solution is to try and architect the search so that it works over multiple requests, but how feasible that is will depend on exactly what you're searching.</p>\n" }, { "answer_id": 163821, "author": "Dan Cramer", "author_id": 3274, "author_profile": "https://Stackoverflow.com/users/3274", "pm_score": 1, "selected": false, "text": "<p>If you are using ColdFusion 8 you can make use of the <code>&lt;cfthread&gt;</code> tag. You can spawn the search process off on its own thread and then use the remote call to terminate the search thread as needed.</p>\n\n<ul>\n<li><a href=\"http://livedocs.adobe.com/coldfusion/8/htmldocs/help.html?content=Tags_t_04.html\" rel=\"nofollow noreferrer\">Livedoc page</a> for cfthread</li>\n<li><a href=\"http://livedocs.adobe.com/coldfusion/8/htmldocs/help.html?content=threads_1.html#1120458\" rel=\"nofollow noreferrer\">Using threads in ColdFusion</a></li>\n</ul>\n" }, { "answer_id": 164028, "author": "Ben Doom", "author_id": 12267, "author_profile": "https://Stackoverflow.com/users/12267", "pm_score": 3, "selected": false, "text": "<p>I don't think there is a <strong>direct</strong> way to stop a page call externally. According to the docs, only the thread itself and it's parent can abort a given thread.</p>\n\n<p>However, you could set a flag for a given thread in a shared scope.</p>\n\n<p>Let's say you call a method that starts some background processing. It generates a unique thread ID and returns it to the caller. The thread looks for a flag in (for example) the application scope that tells it to stop. It checks at each substep of the background process. It could abort at any point that flag is thrown. </p>\n\n<p>To throw the flag, add an abort method that takes the name of the thread that is to be aborted, along with sufficient security to make sure a 3rd party can't just start killing off threads.</p>\n" }, { "answer_id": 180145, "author": "Dan Roberts", "author_id": 8345, "author_profile": "https://Stackoverflow.com/users/8345", "pm_score": 3, "selected": true, "text": "<p>To add onto Ben Doom's answer, I'm including some example code of a way this can be accomplished. There are multiple approaches and ways of names, organizing and calling the code below, but hopefully it is helpful.</p>\n\n<p>At some point during request start, store information about the process in shared scope and return an ID to the client. Here are example functions that could be used on page or remote requests.</p>\n\n<pre><code>&lt;cffunction name=\"createProcess\" output=\"false\"&gt;\n &lt;cfset var id = createUUID()&gt;\n &lt;cfset application.processInfo[id] = {\n progress = 0,\n kill = false\n }&gt;\n &lt;cfreturn id /&gt;\n&lt;/cffunction&gt;\n</code></pre>\n\n<p>Client can then check progress by polling server, or submit request to kill process</p>\n\n<pre><code>&lt;cffunction name=\"getProcessProgress\" output=\"false\"&gt;\n &lt;cfargument name=\"processID\" required=\"true\"&gt;\n &lt;cfreturn application.processInfo[arguments.processID].progress /&gt;\n&lt;/cffunction&gt;\n\n&lt;cffunction name=\"killProcess\" output=\"false\"&gt;\n &lt;cfargument name=\"processID\" required=\"true\"&gt;\n &lt;cfset application.processInfo[arguments.processID].kill = true /&gt;\n&lt;/cffunction&gt;\n</code></pre>\n\n<p>The actual server-side process in question can then hit a function, for example during a loop, to check whether it should abort processing and cleanup any work as appropriate.</p>\n\n<pre><code>&lt;cffunction name=\"shouldKillProcess\" output=\"false\"&gt;\n &lt;cfargument name=\"processID\" required=\"true\"&gt;\n &lt;cfreturn application.processInfo[arguments.processID].kill /&gt;\n&lt;/cffunction&gt;\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24563/" ]
I have a Flex application that calls a function which searches a large document collection. Depending on the search term, the user may want to stop the request from flex. I’d like to not only stop the flex application from expecting the request, but also stop the CFC request. Is this possible? What’s the best approach for doing this?
To add onto Ben Doom's answer, I'm including some example code of a way this can be accomplished. There are multiple approaches and ways of names, organizing and calling the code below, but hopefully it is helpful. At some point during request start, store information about the process in shared scope and return an ID to the client. Here are example functions that could be used on page or remote requests. ``` <cffunction name="createProcess" output="false"> <cfset var id = createUUID()> <cfset application.processInfo[id] = { progress = 0, kill = false }> <cfreturn id /> </cffunction> ``` Client can then check progress by polling server, or submit request to kill process ``` <cffunction name="getProcessProgress" output="false"> <cfargument name="processID" required="true"> <cfreturn application.processInfo[arguments.processID].progress /> </cffunction> <cffunction name="killProcess" output="false"> <cfargument name="processID" required="true"> <cfset application.processInfo[arguments.processID].kill = true /> </cffunction> ``` The actual server-side process in question can then hit a function, for example during a loop, to check whether it should abort processing and cleanup any work as appropriate. ``` <cffunction name="shouldKillProcess" output="false"> <cfargument name="processID" required="true"> <cfreturn application.processInfo[arguments.processID].kill /> </cffunction> ```
163,591
<p>In the GNOME Terminal, Bash does smart auto-completion. For example</p> <pre><code>apt-get in&lt;TAB&gt; </code></pre> <p>becomes</p> <pre><code>apt-get install </code></pre> <p>In Emacs shell-mode, this auto-completion doesn't work, even after I explicitly source <code>/etc/bash_completion</code>. The above example sticks as <code>in</code> or auto-completes with a filename in the current directory rather than a valid <code>apt-get</code> command option. Presumably, this is because Emacs is intercepting the Tab key-press. How do I enable smart auto-completion in <code>shell-mode</code>?</p>
[ { "answer_id": 163754, "author": "matli", "author_id": 23896, "author_profile": "https://Stackoverflow.com/users/23896", "pm_score": 4, "selected": false, "text": "<p>I don't know the answer to this. But the reason that it doesn't work as you expect is probably because the completion in emacs shells is handled by emacs internally (by the comint-dynamic-complete function), and doesn't have those smart completion functions built-in.</p>\n\n<p>I'm afraid it is not an easy thing to fix.</p>\n\n<p>Edit: njsf's suggestion of using term-mode is probably as good as it gets. Start it with <pre>M-x term</pre>\nIt is included in the standard emacs distribution (and in emacs21-common or emacs22-common on Ubuntu and Debian at least).</p>\n" }, { "answer_id": 164061, "author": "Scott Alan Miller", "author_id": 23558, "author_profile": "https://Stackoverflow.com/users/23558", "pm_score": -1, "selected": false, "text": "<p>I make no claims to being an emacs expert but this should solve your problem:</p>\n\n<p>Create: ~/.emacs</p>\n\n<p>Add to it:</p>\n\n<p>(require 'shell-command)\n(shell-command-completion-mode)</p>\n\n<p>Emacs takes over the shell so BASH settings don't carry through. This will set auto completion for EMACS itself.</p>\n" }, { "answer_id": 165506, "author": "njsf", "author_id": 4995, "author_profile": "https://Stackoverflow.com/users/4995", "pm_score": 3, "selected": false, "text": "<p>Like Matli said, it is not an easy task, since bash is started with --noediting and TAB is bound to comint-dynamic-complete.</p>\n\n<p>One could possibly rebind TAB to self-insert-command in shell-comand-hook with local-set-key\nand make shell-mode not start with --noediting by M-x customize-variable RET explicit-bash-args, but I suspect that it will not sit well with all other editing.</p>\n\n<p>You might want to try term-mode, but it has another set of problems, because some of the other regular keybindings are overtaken by term-mode.</p>\n\n<p>EDIT: By other regular keybidings being overtaken by term-mode, I mean all but C-c which becomes the escape to be able to switch buffers. So instead of C-x k to kill the buffer you'd have to C-c C-x k. Or to switch to another buffer 'C-c C-x o' or 'C-c C-x 2'</p>\n" }, { "answer_id": 220960, "author": "Steve Lacey", "author_id": 11077, "author_profile": "https://Stackoverflow.com/users/11077", "pm_score": 4, "selected": false, "text": "<p>In the emacs shell, it's actually emacs doing the auto-completion, not bash. If the shell and emacs are out of sync (e.g. by using pushd, popd or some bash user function that changes the shell's current directory), then auto-completion stops working.</p>\n\n<p>To fix this, just type 'dirs' into the shell and things get back in sync.</p>\n\n<p>I also have the following in my .emacs:</p>\n\n<pre><code>(global-set-key \"\\M-\\r\" 'shell-resync-dirs)\n</code></pre>\n\n<p>Then just hitting Esc-return resyncs the auto-completion.</p>\n" }, { "answer_id": 8152737, "author": "David Christiansen", "author_id": 1049788, "author_profile": "https://Stackoverflow.com/users/1049788", "pm_score": 8, "selected": true, "text": "<p>I know this question is three years old, but it's something that I've also been interested in solving. A Web search directed me to a piece of elisp that makes Emacs use bash for completion in shell mode. It works for me, in any case.</p>\n\n<p>Check it out at <a href=\"https://github.com/szermatt/emacs-bash-completion\">https://github.com/szermatt/emacs-bash-completion</a> .</p>\n" }, { "answer_id": 16027937, "author": "duma", "author_id": 245644, "author_profile": "https://Stackoverflow.com/users/245644", "pm_score": 1, "selected": false, "text": "<p>I use Prelude and when I hit Meta+Tab it completes for me.</p>\n\n<p>Also, Ctrl+i seems to do the same thing.</p>\n" }, { "answer_id": 28618762, "author": "gavenkoa", "author_id": 173149, "author_profile": "https://Stackoverflow.com/users/173149", "pm_score": 3, "selected": false, "text": "<p>Please, consider another mode <code>M-x term</code>, like I did this when hit problem in 2011. I tried to gather all efforts over Inet at that time to make shell work with Bash completion, including this question. But since discovering alternative in face of <code>term-mode</code> I don't even want to try <code>eshell</code>.</p>\n\n<p>It is full terminal emulator, so you can run interactive program inside, like Midnight commander. Or switch to <code>zsh</code> completion so you won't lose time on Emacs configuration.</p>\n\n<p>You get TAB completion in bash for free. But more important you get full Readline power, like <strong>incremental or prefixed command search</strong>. To make this setup more convenient check my <a href=\"http://hg.defun.work/skel/file/default/.inputrc\" rel=\"nofollow noreferrer\">.inputrc</a>, <a href=\"http://hg.defun.work/skel/file/default/.bashrc\" rel=\"nofollow noreferrer\">.bashrc</a>, <a href=\"http://hg.defun.work/dot-emacs/file/default/.emacs-my\" rel=\"nofollow noreferrer\">.emacs</a>.</p>\n\n<p>Essential part of <code>.inputrc</code>:</p>\n\n<pre><code># I like this!\nset editing-mode emacs\n\n# Don't strip characters to 7 bits when reading.\nset input-meta on\n\n# Allow iso-latin1 characters to be inserted rather than converted to\n# prefix-meta sequences.\nset convert-meta off\n\n# Display characters with the eighth bit set directly rather than as\n# meta-prefixed characters.\nset output-meta on\n\n# Ignore hidden files.\nset match-hidden-files off\n\n# Ignore case (on/off).\nset completion-ignore-case on\n\nset completion-query-items 100\n\n# First tab suggests ambiguous variants.\nset show-all-if-ambiguous on\n\n# Replace common prefix with ...\nset completion-prefix-display-length 1\n\nset skip-completed-text off\n\n# If set to 'on', completed directory names have a slash appended. The default is 'on'.\nset mark-directories on\nset mark-symlinked-directories on\n\n# If set to 'on', a character denoting a file's type is appended to the\n# filename when listing possible completions. The default is 'off'.\nset visible-stats on\n\nset horizontal-scroll-mode off\n\n$if Bash\n\"\\C-x\\C-e\": edit-and-execute-command\n$endif\n\n# Define my favorite Emacs key bindings.\n\"\\C-@\": set-mark\n\"\\C-w\": kill-region\n\"\\M-w\": copy-region-as-kill\n\n# Ctrl+Left/Right to move by whole words.\n\"\\e[1;5C\": forward-word\n\"\\e[1;5D\": backward-word\n# Same with Shift pressed.\n\"\\e[1;6C\": forward-word\n\"\\e[1;6D\": backward-word\n\n# Ctrl+Backspace/Delete to delete whole words.\n\"\\e[3;5~\": kill-word\n\"\\C-_\": backward-kill-word\n\n# UP/DOWN filter history by typed string as prefix.\n\"\\e[A\": history-search-backward\n\"\\C-p\": history-search-backward\n\"\\eOA\": history-search-backward\n\"\\e[B\": history-search-forward\n\"\\C-n\": history-search-forward\n\"\\eOB\": history-search-forward\n\n# Bind 'Shift+TAB' to complete as in Python TAB was need for another purpose.\n\"\\e[Z\": complete\n# Cycling possible completion forward and backward in place.\n\"\\e[1;3C\": menu-complete # M-Right\n\"\\e[1;3D\": menu-complete-backward # M-Left\n\"\\e[1;5I\": menu-complete # C-TAB\n</code></pre>\n\n<p><code>.bashrc</code> (YEA! There is dabbrev in Bash from any word in <code>~/.bash_history</code>):</p>\n\n<pre><code>set -o emacs\n\nif [[ $- == *i* ]]; then\n bind '\"\\e/\": dabbrev-expand'\n bind '\"\\ee\": edit-and-execute-command'\nfi\n</code></pre>\n\n<p><code>.emacs</code> to make navigation comfortable in term buffer:</p>\n\n<pre><code>(setq term-buffer-maximum-size (lsh 1 14))\n\n(eval-after-load 'term\n '(progn\n (defun my-term-send-delete-word-forward () (interactive) (term-send-raw-string \"\\ed\"))\n (defun my-term-send-delete-word-backward () (interactive) (term-send-raw-string \"\\e\\C-h\"))\n (define-key term-raw-map [C-delete] 'my-term-send-delete-word-forward)\n (define-key term-raw-map [C-backspace] 'my-term-send-delete-word-backward)\n (defun my-term-send-forward-word () (interactive) (term-send-raw-string \"\\ef\"))\n (defun my-term-send-backward-word () (interactive) (term-send-raw-string \"\\eb\"))\n (define-key term-raw-map [C-left] 'my-term-send-backward-word)\n (define-key term-raw-map [C-right] 'my-term-send-forward-word)\n (defun my-term-send-m-right () (interactive) (term-send-raw-string \"\\e[1;3C\"))\n (defun my-term-send-m-left () (interactive) (term-send-raw-string \"\\e[1;3D\"))\n (define-key term-raw-map [M-right] 'my-term-send-m-right)\n (define-key term-raw-map [M-left] 'my-term-send-m-left)\n ))\n\n(defun my-term-mode-hook ()\n (goto-address-mode 1))\n(add-hook 'term-mode-hook #'my-term-mode-hook)\n</code></pre>\n\n<p>As any usual commands as <code>C-x o</code> aren't working in terminal emulation mode I extended keymap with:</p>\n\n<pre><code>(unless\n (ignore-errors\n (require 'ido)\n (ido-mode 1)\n (global-set-key [?\\s-d] #'ido-dired)\n (global-set-key [?\\s-f] #'ido-find-file)\n t)\n (global-set-key [?\\s-d] #'dired)\n (global-set-key [?\\s-f] #'find-file))\n\n(defun my--kill-this-buffer-maybe-switch-to-next ()\n \"Kill current buffer. Switch to next buffer if previous command\nwas switching to next buffer or this command itself allowing\nsequential closing of uninteresting buffers.\"\n (interactive)\n (let ( (cmd last-command) )\n (kill-buffer (current-buffer))\n (when (memq cmd (list 'next-buffer this-command))\n (next-buffer))))\n(global-set-key [s-delete] 'my--kill-this-buffer-maybe-switch-to-next)\n(defun my--backward-other-window ()\n (interactive)\n (other-window -1))\n(global-set-key [s-up] #'my--backward-other-window)\n(global-set-key [s-down] #'other-window)\n(global-set-key [s-tab] 'other-window)\n</code></pre>\n\n<p>Note that I use <code>super</code> key so <code>term-raw-map</code> and possibly any other keymap don't conflict with my key bindings. To make <code>super</code> key from left <code>Win</code> key I use <code>.xmodmaprc</code>:</p>\n\n<pre><code>! To load this config run:\n! $ xmodmap .xmodmaprc\n\n! Win key.\nclear mod3\nclear mod4\n\nkeycode 133 = Super_L\nkeycode 134 = Hyper_R\nadd mod3 = Super_L\nadd mod4 = Hyper_R\n</code></pre>\n\n<p>You just should remember 2 commands: <code>C-c C-j</code> - to enter to normal Emacs editing mode (for copying or grepping in buffer text), <code>C-c C-k</code> - to return to terminal emulation mode.</p>\n\n<p>Mouse selection and <code>Shift-Insert</code> work as in <code>xterm</code>.</p>\n" }, { "answer_id": 42108751, "author": "Alexei", "author_id": 6813231, "author_profile": "https://Stackoverflow.com/users/6813231", "pm_score": 0, "selected": false, "text": "<p>I use helm mode. It's has this functionality (after press \"TAB\"):\n<a href=\"https://i.stack.imgur.com/OeILH.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/OeILH.png\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 59764453, "author": "Prgrm.celeritas", "author_id": 6411120, "author_profile": "https://Stackoverflow.com/users/6411120", "pm_score": 2, "selected": false, "text": "<p>I know this post is over 11 years old now. But I have created a function to give native shell completion in Emacs. It just sends a tab key to the underlying process and intercepts the output, so it is the exact same as you would get in the shell itself.</p>\n\n<p><a href=\"https://github.com/CeleritasCelery/emacs-native-shell-complete\" rel=\"nofollow noreferrer\">https://github.com/CeleritasCelery/emacs-native-shell-complete</a></p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163591", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1412/" ]
In the GNOME Terminal, Bash does smart auto-completion. For example ``` apt-get in<TAB> ``` becomes ``` apt-get install ``` In Emacs shell-mode, this auto-completion doesn't work, even after I explicitly source `/etc/bash_completion`. The above example sticks as `in` or auto-completes with a filename in the current directory rather than a valid `apt-get` command option. Presumably, this is because Emacs is intercepting the Tab key-press. How do I enable smart auto-completion in `shell-mode`?
I know this question is three years old, but it's something that I've also been interested in solving. A Web search directed me to a piece of elisp that makes Emacs use bash for completion in shell mode. It works for me, in any case. Check it out at <https://github.com/szermatt/emacs-bash-completion> .
163,604
<p>I'm trying to select a random 10% sampling from a small table. I thought I'd just use the RAND() function and select those rows where the random number is less than 0.10:</p> <pre><code>SELECT * FROM SomeTable WHERE SomeColumn='SomeCondition' AND RAND() &lt; 0.10 </code></pre> <p>But I soon discovered that RAND() always returns the same number! Reminds me of this <a href="http://xkcd.com/221/" rel="nofollow noreferrer">xkcd cartoon</a>.</p> <p><img src="https://imgs.xkcd.com/comics/random_number.png"></p> <p>OK, no problem, the RAND function takes a seed value. I will be running this query periodically, and I want it to give different results if I run it on a different day, so I seed it with a combination of the date and a unique row ID:</p> <pre><code>SELECT * FROM SomeTable WHERE SomeColumn='SomeCondition' AND RAND(CAST(GETDATE) AS INTEGER) + RowID) &lt; 0.10 </code></pre> <p>I still don't get any results! When I show the random numbers returned by RAND, I discover that they're all within a narrow range. It appears that getting a random number from RAND requires you to use a random seed. If I had a random seed in the first place, I wouldn't need a random number!</p> <p>I've seen the previous discussions related to this problem: </p> <p><a href="https://stackoverflow.com/questions/52964/sql-server-random-sort">SQL Server Random Sort</a><br> <a href="https://stackoverflow.com/questions/19412/how-to-request-a-random-row-in-sql">How to request a random row in SQL?</a></p> <p>They don't help me. TABLESAMPLE works at the page level, which is great for a big table but not for a small one, and it looks like it applies prior to the WHERE clause. TOP with NEWID doesn't work because I don't know ahead of time how many rows I want.</p> <p>Anybody have a solution, or at least a hint?</p> <p><strong>Edit:</strong> Thanks to AlexCuse for a <a href="https://stackoverflow.com/questions/163604/what-am-i-doing-wrong-when-using-rand-in-ms-sql-server-2005#163843">solution</a> which works for my particular case. Now to the larger question, how to make RAND behave?</p>
[ { "answer_id": 163615, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 2, "selected": false, "text": "<p>If your table has a column (perhaps even the <strong>rowid</strong> column) that is numeric in the general sense, like integer, floating point or SQL numeric, please try the following:</p>\n\n<pre><code>SELECT * FROM SomeTable WHERE SomeColumn='SomeCondition' AND 0*rowid+RAND() &lt; 0.10\n</code></pre>\n\n<p>In order to evaluate <code>RAND()</code> once for <em>every row</em>, not once at <em>the start of your query</em>.</p>\n\n<p>The query optimizer is to blame. Perhaps there is another way, but I believe this will work for you.</p>\n" }, { "answer_id": 163843, "author": "AlexCuse", "author_id": 794, "author_profile": "https://Stackoverflow.com/users/794", "pm_score": 4, "selected": true, "text": "<p>This type of approach (shown by ΤΖΩΤΖΙΟΥ) will not guarantee a 10% sampling. It will only give you all rows where Rand() is evaluated to &lt; .10 which will not be consistent. </p>\n\n<p>Something like</p>\n\n<pre><code>select top 10 percent * from MyTable order by NEWID()\n</code></pre>\n\n<p>will do the trick.</p>\n\n<p><strong>edit:</strong> there is not really a good way to make RAND behave. This is what I've used in the past (kludge alert - it kills you not being able to use Rand() in a UDF)</p>\n\n<pre><code>CREATE VIEW RandView AS \n\nSELECT RAND() AS Val\n\nGO\n\nCREATE FUNCTION RandomFloat()\nRETURNS FLOAT\nAS\nBEGIN\n\nRETURN (SELECT Val FROM RandView)\n\nEND\n</code></pre>\n\n<p>Then you just have <code>select blah, dbo.RandomFloat() from table</code> in your query.</p>\n" }, { "answer_id": 164189, "author": "Joshua Carmody", "author_id": 8409, "author_profile": "https://Stackoverflow.com/users/8409", "pm_score": 0, "selected": false, "text": "<p>Did you see this question?</p>\n\n<p><a href=\"https://stackoverflow.com/questions/94906/how-do-i-return-random-numbers-as-a-column-in-sql-server-2005\">How do I return random numbers as a column in SQL Server 2005?</a></p>\n\n<p>Adam posted a UDF you can use in place of Rand() that works much better.</p>\n" }, { "answer_id": 164195, "author": "Jason DeFontes", "author_id": 6159, "author_profile": "https://Stackoverflow.com/users/6159", "pm_score": 1, "selected": false, "text": "<p>This seems to work:</p>\n\n<pre><code>select * from SomeTable\nwhere rand(0*SomeTableID + cast(cast(newid() as binary(4)) as int)) &lt;= 0.10\n</code></pre>\n" }, { "answer_id": 4806011, "author": "Jonas Stensved", "author_id": 348841, "author_profile": "https://Stackoverflow.com/users/348841", "pm_score": 0, "selected": false, "text": "<p>This seems to work</p>\n\n<pre><code>SELECT TOP 10 PERCENT * FROM schema.MyTable ORDER BY NEWID()\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5987/" ]
I'm trying to select a random 10% sampling from a small table. I thought I'd just use the RAND() function and select those rows where the random number is less than 0.10: ``` SELECT * FROM SomeTable WHERE SomeColumn='SomeCondition' AND RAND() < 0.10 ``` But I soon discovered that RAND() always returns the same number! Reminds me of this [xkcd cartoon](http://xkcd.com/221/). ![](https://imgs.xkcd.com/comics/random_number.png) OK, no problem, the RAND function takes a seed value. I will be running this query periodically, and I want it to give different results if I run it on a different day, so I seed it with a combination of the date and a unique row ID: ``` SELECT * FROM SomeTable WHERE SomeColumn='SomeCondition' AND RAND(CAST(GETDATE) AS INTEGER) + RowID) < 0.10 ``` I still don't get any results! When I show the random numbers returned by RAND, I discover that they're all within a narrow range. It appears that getting a random number from RAND requires you to use a random seed. If I had a random seed in the first place, I wouldn't need a random number! I've seen the previous discussions related to this problem: [SQL Server Random Sort](https://stackoverflow.com/questions/52964/sql-server-random-sort) [How to request a random row in SQL?](https://stackoverflow.com/questions/19412/how-to-request-a-random-row-in-sql) They don't help me. TABLESAMPLE works at the page level, which is great for a big table but not for a small one, and it looks like it applies prior to the WHERE clause. TOP with NEWID doesn't work because I don't know ahead of time how many rows I want. Anybody have a solution, or at least a hint? **Edit:** Thanks to AlexCuse for a [solution](https://stackoverflow.com/questions/163604/what-am-i-doing-wrong-when-using-rand-in-ms-sql-server-2005#163843) which works for my particular case. Now to the larger question, how to make RAND behave?
This type of approach (shown by ΤΖΩΤΖΙΟΥ) will not guarantee a 10% sampling. It will only give you all rows where Rand() is evaluated to < .10 which will not be consistent. Something like ``` select top 10 percent * from MyTable order by NEWID() ``` will do the trick. **edit:** there is not really a good way to make RAND behave. This is what I've used in the past (kludge alert - it kills you not being able to use Rand() in a UDF) ``` CREATE VIEW RandView AS SELECT RAND() AS Val GO CREATE FUNCTION RandomFloat() RETURNS FLOAT AS BEGIN RETURN (SELECT Val FROM RandView) END ``` Then you just have `select blah, dbo.RandomFloat() from table` in your query.
163,628
<p>When placing email addresses on a webpage do you place them as text like this:</p> <pre><code>[email protected] </code></pre> <p>or use a clever trick to try and fool the email address harvester bots? For example:</p> <p><strong>HTML Escape Characters:</strong></p> <pre><code>&amp;#106;&amp;#111;&amp;#101;&amp;#46;&amp;#115;&amp;#111;&amp;#109;&amp;#101;&amp;#98;&amp;#111;&amp;#100;&amp;#121;&amp;#64;&amp;#99;&amp;#111;&amp;#109;&amp;#112;&amp;#97;&amp;#110;&amp;#121;&amp;#46;&amp;#99;&amp;#111;&amp;#109; </code></pre> <p><strong>Javascript Decrypter:</strong></p> <pre><code>function XOR_Crypt(EmailAddress) { Result = new String(); for (var i = 0; i &lt; EmailAddress.length; i++) { Result += String.fromCharCode(EmailAddress.charCodeAt(i) ^ 128); } document.write(Result); } XOR_Crypt("êïå®óïíåâïäùÀãïíðáîù®ãïí"); </code></pre> <p><strong>Human Decode:</strong></p> <pre><code>[email protected] joe.somebody AT company.com </code></pre> <p>What do you use or do you even bother?</p>
[ { "answer_id": 163641, "author": "tloach", "author_id": 14092, "author_profile": "https://Stackoverflow.com/users/14092", "pm_score": 7, "selected": true, "text": "<p>I generally don't bother. I used to be on a mailing list that got several thousand spams every day. Our spam filter (spamassassin) let maybe 1 or 2 a day through. With filters this good, why make it difficult for legitimate people to contact you?</p>\n" }, { "answer_id": 163658, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 3, "selected": false, "text": "<p>I wouldn't bother -- it is fighting the SPAM war at the wrong level. Particularly for company web sites I think it makes things look very unprofessional if you have anything other than the straight text on the page with a mailto hyperlink.</p>\n\n<p>There is so much spam flying around that you need good filtering anyway, and any bot is going end up understanding all the common tricks anyway.</p>\n" }, { "answer_id": 163672, "author": "GavinCattell", "author_id": 21644, "author_profile": "https://Stackoverflow.com/users/21644", "pm_score": 4, "selected": false, "text": "<p>You can protect your email address with reCAPTCHA, they offer a free service so people have to enter a CAPTCHA (Completely Automated Public Turing test to tell Computers and Humans Apart) to see your email: <a href=\"https://www.google.com/recaptcha/admin#mailhide\" rel=\"noreferrer\">https://www.google.com/recaptcha/admin#mailhide</a></p>\n" }, { "answer_id": 163729, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 5, "selected": false, "text": "<p>Invent your own crazy email address obfuscation scheme. Doesn't matter what it is, really, as long as it's not too similar to any of the commonly known methods.</p>\n\n<p>The problem is that there really isn't a good solution to this, they're all either relatively simple to bypass, or rather irritating for the user. If any one method becomes prevalent, then someone <em>will</em> find a way around it.</p>\n\n<p>So rather than looking for the One True email address obfuscation technique, come up with your own. Count on the fact that these bot authors don't care enough about your site to sit around writing a thing to bypass your slightly crazy rendering-text-with-css-and-element-borders or your completely bizarre, easily-cracked javascript encryption. It doesn't matter if it's trivial, nobody will bother trying to bypass it just so they can spam you.</p>\n" }, { "answer_id": 163736, "author": "Joe Phillips", "author_id": 20471, "author_profile": "https://Stackoverflow.com/users/20471", "pm_score": 1, "selected": false, "text": "<p>I make mine [email protected] and then next to it I write \"Remove the capital letters\"</p>\n" }, { "answer_id": 163743, "author": "gabr", "author_id": 4997, "author_profile": "https://Stackoverflow.com/users/4997", "pm_score": 2, "selected": false, "text": "<p>The only safest way is of course not to put the email address onto web page in the first place.</p>\n" }, { "answer_id": 163781, "author": "Joe Phillips", "author_id": 20471, "author_profile": "https://Stackoverflow.com/users/20471", "pm_score": 1, "selected": false, "text": "<p>Another, possibly unique, technique might be to use multiple images and a few plain-text letters to display the address. That might confuse the bots.</p>\n" }, { "answer_id": 163784, "author": "cllpse", "author_id": 20946, "author_profile": "https://Stackoverflow.com/users/20946", "pm_score": 3, "selected": false, "text": "<p>HTML:</p>\n\n<pre><code>&lt;a href=\"#\" class=\"--mailto--john--domain--com-- other classes goes here\" /&gt;\n</code></pre>\n\n<p>JavaScript, using <a href=\"http://jquery.com\" rel=\"noreferrer\">jQuery</a>:</p>\n\n<pre><code>// match all a-elements with \"--mailto--\" somehere in the class property\n$(\"a[class*='--mailto--']\").each(function ()\n{\n /*\n for each of those elements use a regular expression to pull\n out the data you need to construct a valid e-mail adress\n */\n var validEmailAdress = this.className.match();\n\n $(this).click(function ()\n {\n window.location = validEmailAdress;\n });\n});\n</code></pre>\n" }, { "answer_id": 163824, "author": "Prog", "author_id": 23890, "author_profile": "https://Stackoverflow.com/users/23890", "pm_score": 0, "selected": false, "text": "<p>A script that saves email addresses to png files would be a secure solution ( if you have enough space and you are allowed to embed images in your page )</p>\n" }, { "answer_id": 163840, "author": "Herb Caudill", "author_id": 239663, "author_profile": "https://Stackoverflow.com/users/239663", "pm_score": 0, "selected": false, "text": "<p>This is what we use (VB.NET):</p>\n\n<pre><code>Dim rxEmailLink As New Regex(\"&lt;a\\b[^&gt;]*mailto:\\b[^&gt;]*&gt;(.*?)&lt;/a&gt;\")\nDim m As Match = rxEmailLink.Match(Html)\nWhile m.Success\n Dim strEntireLinkOrig As String = m.Value\n Dim strEntireLink As String = strEntireLinkOrig\n strEntireLink = strEntireLink.Replace(\"'\", \"\"\"\") ' replace any single quotes with double quotes to make sure the javascript is well formed\n Dim rxLink As New Regex(\"(&lt;a\\b[^&gt;]*mailto:)([\\w.\\-_^@]*@[\\w.\\-_^@]*)(\\b[^&gt;]*?)&gt;(.*?)&lt;/a&gt;\")\n Dim rxLinkMatch As Match = rxLink.Match(strEntireLink)\n Dim strReplace As String = String.Format(\"&lt;script language=\"\"JavaScript\"\"&gt;document.write('{0}{1}{2}&gt;{3}&lt;/a&gt;');&lt;/script&gt;\", _\n RandomlyChopStringJS(rxLinkMatch.Groups(1).ToString), _\n ConvertToAsciiHex(rxLinkMatch.Groups(2).ToString), _\n rxLinkMatch.Groups(3), _\n ConvertToHtmlEntites(rxLinkMatch.Groups(4).ToString))\n Result = Result.Replace(strEntireLinkOrig, strReplace)\n m = m.NextMatch()\nEnd While\n</code></pre>\n\n<p>and</p>\n\n<pre><code> Public Function RandomlyChopStringJS(ByVal s As String) As String\n Dim intChop As Integer = Int(6 * Rnd()) + 1\n Dim intCount As Integer = 0\n RandomlyChopStringJS = \"\"\n If Not s Is Nothing AndAlso Len(s) &gt; 0 Then\n For Each c As Char In s.ToCharArray()\n If intCount = intChop Then\n RandomlyChopStringJS &amp;= \"'+'\"\n intChop = Int(6 * Rnd()) + 1\n intCount = 0\n End If\n RandomlyChopStringJS &amp;= c\n intCount += 1\n Next\n End If\n End Function\n</code></pre>\n\n<p>We override Render and run the outgoing HTML through this before it goes out the door. This renders email addresses that render normally to a browser, but look like this in the source:</p>\n\n<pre><code>&lt;script language=\"JavaScript\"&gt;document.write('&lt;a '+'clas'+'s='+'\"Mail'+'Link'+'\" hr'+'ef'+'=\"ma'+'ilto:%69%6E%66%6F%40%62%69%63%75%73%61%2E%6F%72%67\"&gt;&amp;#105;&amp;#110;&amp;#102;&amp;#111;&amp;#64;&amp;#98;&amp;#105;&amp;#99;&amp;#117;&amp;#115;&amp;#97;&amp;#46;&amp;#111;&amp;#114;&amp;#103;&lt;/a&gt;');&lt;/script&gt;\n</code></pre>\n\n<p>Obviously not foolproof, but hopefully cuts down on a certain amount of harvesting without making things hard for the visitor.</p>\n" }, { "answer_id": 163841, "author": "Bill", "author_id": 24190, "author_profile": "https://Stackoverflow.com/users/24190", "pm_score": 2, "selected": false, "text": "<p>Use a contact form instead. Put all of your email addresses into a database and create an HTML form (subject, body, from ...) that submits the contents of the email that the user fills out in the form (along with an id or name that is used to lookup that person's email address in your database) to a server side script that then sends an email to the specified person. At no time is the email address exposed. You will probably want to implement some form of CAPTCHA to deter spambots as well.</p>\n" }, { "answer_id": 163884, "author": "Scott Alan Miller", "author_id": 23558, "author_profile": "https://Stackoverflow.com/users/23558", "pm_score": 0, "selected": false, "text": "<p>It depends on what exactly your needs are. For most sites with which I work, I have found it far more useful to put in a \"contact me/us\" form which sends an email from the system to whomever needs to be contacted. I know that this isn't exactly the solution that you are seeking but it does completely protect against harvesting and so far I have never seen spam sent through a form like that. It will happen but it is very rare and you are never harvested.</p>\n\n<p>This also gives you a chance to log the messages before sending them giving you an extra level of protection against losing a contact, if you so desire.</p>\n" }, { "answer_id": 164046, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Gmail which is free has an awesome spam filter.</p>\n\n<p>If you don't want to use Gmail directly you could send the email to gmail and use gmail forwarding to send it back to you after it has gone through their spam filter.</p>\n\n<p>In a more complex situation, when you need to show a @business.com address you could show the [email protected] and have all this mail forwarded to a gmail account who then forwards it back to the [email protected]</p>\n\n<p>I guess it's not a direct solution to your question but it might help.\nGmail being free and having such a good SPAM filter makes using it a very wise choice IMHO.</p>\n\n<p>I receive about 100 spam per day in my gmail account but I can't remember the last time one of them got to my inbox.</p>\n\n<p>To sum up, use a good spam filter whether Gmail or another. Having the user retype or modify the email address that is shown is like using DRM to protect against piracy. Putting the burden on the \"good\" guy shouldn't be the way to go about doing anything. :)</p>\n" }, { "answer_id": 164277, "author": "Phil", "author_id": 8555, "author_profile": "https://Stackoverflow.com/users/8555", "pm_score": 2, "selected": false, "text": "<p>I don't bother. You'll only annoy sophisticated users and confuse unsophisticated users. As others have said, Gmail provides very effective spam filters for a personal/small business domain, and corporate filters are generally also very good.</p>\n" }, { "answer_id": 296970, "author": "Kornel", "author_id": 27009, "author_profile": "https://Stackoverflow.com/users/27009", "pm_score": 4, "selected": false, "text": "<p>I've written an <a href=\"http://hcard.geekhood.net/encode/?addr=test%40example.com\" rel=\"nofollow noreferrer\">encoder</a> (<a href=\"https://github.com/pornel/hCardValidator/blob/master/encode/index.php\" rel=\"nofollow noreferrer\">source</a>) that uses all kinds of parsing tricks that I could think of (different kinds of HTML entities, URL encoding, comments, multiline attributes, soft hyphens, non-obvious structure of mailto: URL, etc)</p>\n\n<p>It doesn't stop all harvesters, but OTOH it's completely standards-compliant and transparent to the users.</p>\n\n<p>Another IMHO good approach (which you can use in addition to tricky encoding) is along lines of:</p>\n\n<pre><code>&lt;a href=\"mailto:[email protected]\" \n onclick=\"this.href=this.href.replace(/hatestogetspam/,'')\"&gt;\n</code></pre>\n" }, { "answer_id": 483222, "author": "guerda", "author_id": 32043, "author_profile": "https://Stackoverflow.com/users/32043", "pm_score": 2, "selected": false, "text": "<p>The best method hiding email addresses is only good until bot programmer discover this \"encoding\" and implement a decryption algorithm.</p>\n\n<p>The JavaScript option won't work long, because there are a lot of crawler interpreting JavaScript.</p>\n\n<p>There's no answer, imho.</p>\n" }, { "answer_id": 483224, "author": "Gumbo", "author_id": 53114, "author_profile": "https://Stackoverflow.com/users/53114", "pm_score": 2, "selected": false, "text": "<p>There are probably bots that recognize the <code>[at]</code> and other disguises as <code>@</code> symbol. So this is not a really effective method.</p>\n\n<p>Sure you could use some encodings like URL encode or HTML character references (or both):</p>\n\n<pre><code>// PHP example\n// encodes every character using URL encoding (%hh)\nfunction foo($str) {\n $retVal = '';\n $length = strlen($str);\n for ($i=0; $i&lt;$length; $i++) $retVal.=sprintf('%%%X', ord($str[$i]));\n return $retVal;\n}\n// encodes every character into HTML character references (&amp;#xhh;)\nfunction bar($str) {\n $retVal = '';\n $length = strlen($str);\n for ($i=0; $i&lt;$length; $i++) $retVal.=sprintf('&amp;#x%X;', ord($str[$i]));\n return $retVal;\n}\n\n$email = '[email protected]';\necho '&lt;a href=\"'.bar('mailto:?to=' . foo(','.$email.'')).'\"&gt;mail me&lt;/a&gt;';\n\n// output\n// &lt;a href=\"&amp;#x6D;&amp;#x61;&amp;#x69;&amp;#x6C;&amp;#x74;&amp;#x6F;&amp;#x3A;&amp;#x3F;&amp;#x74;&amp;#x6F;&amp;#x3D;&amp;#x25;&amp;#x32;&amp;#x43;&amp;#x25;&amp;#x37;&amp;#x35;&amp;#x25;&amp;#x37;&amp;#x33;&amp;#x25;&amp;#x36;&amp;#x35;&amp;#x25;&amp;#x37;&amp;#x32;&amp;#x25;&amp;#x34;&amp;#x30;&amp;#x25;&amp;#x36;&amp;#x35;&amp;#x25;&amp;#x37;&amp;#x38;&amp;#x25;&amp;#x36;&amp;#x31;&amp;#x25;&amp;#x36;&amp;#x44;&amp;#x25;&amp;#x37;&amp;#x30;&amp;#x25;&amp;#x36;&amp;#x43;&amp;#x25;&amp;#x36;&amp;#x35;&amp;#x25;&amp;#x32;&amp;#x45;&amp;#x25;&amp;#x36;&amp;#x33;&amp;#x25;&amp;#x36;&amp;#x46;&amp;#x25;&amp;#x36;&amp;#x44;\"&gt;mail me&lt;/a&gt;\n</code></pre>\n\n<p>But as it is legal to use them, every browser/e-mail client should handle these encodings too.</p>\n" }, { "answer_id": 483225, "author": "Romain Linsolas", "author_id": 26457, "author_profile": "https://Stackoverflow.com/users/26457", "pm_score": 2, "selected": false, "text": "<p>One easy solution is to use HTML entities instead of actual characters.\nFor example, the \"[email protected]\" will be converted into :</p>\n\n<pre><code>&lt;a href=\"&amp;#109;&amp;#97;&amp;#105;&amp;#108;&amp;#116;&amp;#111;&amp;#58;&amp;#109;&amp;#101;&amp;#64;&amp;#101;&amp;#120;&amp;#97;&amp;#109;&amp;#112;&amp;#108;&amp;#101;&amp;#46;&amp;#99;&amp;#111;&amp;#109;\"&gt;email me&lt;/A&gt;\n</code></pre>\n" }, { "answer_id": 483229, "author": "Vatine", "author_id": 34771, "author_profile": "https://Stackoverflow.com/users/34771", "pm_score": 1, "selected": false, "text": "<p>Does it work if I right-click on the link and choose \"copy URL\"? If not, it's very much not an ideal situation (I very seldom click on a mailto link, preferring to copy the email address and paste it into my mail application or wherever else I need it at a specific point in time).</p>\n\n<p>I used to be fairly paranoid protecting my mail address on-line (UseNet, web and the like), but these days I suspect more \"possible targets for spam\" are actually generated matching local-parts to domains programmatically. I base this on having, on occasion, gone through my mail server logs. There tends to be quite a few delivery attempts to non-existing addresses (including truncated versions of spam-bait I dangled on UseNet back in the late 90s, when address-scraping was very prevalent).</p>\n" }, { "answer_id": 483239, "author": "roundcrisis", "author_id": 162325, "author_profile": "https://Stackoverflow.com/users/162325", "pm_score": 7, "selected": false, "text": "<p>Have a look at <a href=\"https://matt.berther.io/2009/01/15/hiding-an-email-address-from-spam-harvesters/\" rel=\"noreferrer\">this way</a>, pretty clever and using css.</p>\n\n<p><strong>CSS</strong></p>\n\n<pre><code>span.reverse {\n unicode-bidi: bidi-override;\n direction: rtl;\n}\n</code></pre>\n\n<p><strong>HTML</strong> </p>\n\n<pre><code>&lt;span class=\"reverse\"&gt;moc.rehtrebttam@retsambew&lt;/span&gt;\n</code></pre>\n\n<p>The CSS above will then override the reading direction and present the text to the user in the correct order. </p>\n\n<p>Hope it helps</p>\n\n<p>Cheers </p>\n" }, { "answer_id": 483252, "author": "mati", "author_id": 58128, "author_profile": "https://Stackoverflow.com/users/58128", "pm_score": 4, "selected": false, "text": "<p>If you have php support, you can do something like this: </p>\n\n<pre><code>&lt;img src=\"scriptname.php\"&gt;\n</code></pre>\n\n<p>And the scriptname.php:</p>\n\n<pre><code>&lt;?php\nheader(\"Content-type: image/png\");\n// Your email address which will be shown in the image\n$email = \"[email protected]\";\n$length = (strlen($email)*8);\n$im = @ImageCreate ($length, 20)\n or die (\"Kann keinen neuen GD-Bild-Stream erzeugen\");\n$background_color = ImageColorAllocate ($im, 255, 255, 255); // White: 255,255,255\n$text_color = ImageColorAllocate ($im, 55, 103, 122);\nimagestring($im, 3,5,2,$email, $text_color);\nimagepng ($im);\n?&gt;\n</code></pre>\n" }, { "answer_id": 483401, "author": "rmeador", "author_id": 10861, "author_profile": "https://Stackoverflow.com/users/10861", "pm_score": 4, "selected": false, "text": "<p>I think the only foolproof method you can have is creating a Contact Me page that is a form that submits to a script that sends to your email address. That way, your address is never exposed to the public at all. This may be undesirable for some reason, but I think it's a pretty good solution. It often irks me when I'm forced to copy/paste someone's email address from their site to my mail client and send them a message; I'd rather do it right through a form on their site. Also, this approach allows you to have anonymous comments sent to you, etc. Just be sure to protect your form using some kind of anti-bot scheme, such as a captcha. There are plenty of them discussed here on SO.</p>\n" }, { "answer_id": 483430, "author": "ofaurax", "author_id": 15209, "author_profile": "https://Stackoverflow.com/users/15209", "pm_score": 3, "selected": false, "text": "<p>You can try to hide characters using <strong>html entities in hexa</strong> (ex: &amp;#x40 for @).\nThis is convenient solution, as a correct browser will translate it, and you can have a normal link.\nThe drawback is that a bot can translate it theorically, but it's a bit unusual.\nI use this to protect my e-mail on my blog.</p>\n\n<p>Another solution is to <strong>use javascript</strong> to assemble part of the address and to decode on-the-fly the address.\nThe drawback is that a javascript-disabled browser won't show your adress.</p>\n\n<p>The most effective solution is to <strong>use an image</strong>, but it's a pain for the user to have to copy the address by hand.</p>\n\n<p><strong>Your solution is pretty good</strong>, as you only add a drawback (writing manually the @) only for user that have javascript disabled.\nYou can also be more secure with :</p>\n\n<pre><code>onclick=\"this.href='mailto:' + 'admin' + '&amp;#x40;' + 'domain.com'\"\n</code></pre>\n" }, { "answer_id": 484654, "author": "xaddict", "author_id": 59159, "author_profile": "https://Stackoverflow.com/users/59159", "pm_score": 1, "selected": false, "text": "<p>First I would make sure the email address only shows when you have javascript enabled. This way, there is no plain text that can be read without javascript.</p>\n\n<p>Secondly, A way of implementing a safe feature is by staying away from the <code>&lt;button&gt;</code> tag. This tag needs a text insert between the tags, which makes it computer-readable. Instead try the <code>&lt;input type=\"button\"&gt;</code> with a javascript handler for an onClick.\nThen use all of the techniques mentioned by otherse to implement a safe email notation.</p>\n\n<p>One other option is to have a button with \"Click to see emailaddress\". Once clicked this changes into a coded email (the characters in HTML codes). On another click this redirects to the 'mailto:email' function</p>\n\n<p>An uncoded version of the last idea, with selectable and non-selectable email addresses:</p>\n\n<pre><code>&lt;html&gt;\n&lt;body&gt;\n&lt;script type=\"text/javascript\"&gt;\n e1=\"@domain\";\n e2=\"me\";\n e3=\".extension\";\nemail_link=\"mailto:\"+e2+e1+e3;\n&lt;/script&gt;\n&lt;input type=\"text\" onClick=\"this.onClick=window.open(email_link);\" value=\"Click for mail\"/&gt;\n&lt;input type=\"text\" onClick=\"this.value=email;\" value=\"Click for mail-address\"/&gt;\n&lt;input type=\"button\" onClick=\"this.onClick=window.open(email_link);\" value=\"Click for mail\"/&gt;\n&lt;input type=\"button\" onClick=\"this.value=email;\" value=\"Click for mail-address\"/&gt;\n&lt;/body&gt;&lt;/html&gt;\n</code></pre>\n\n<p>See if this is something you would want and combine it with others' ideas. You can never be too sure.</p>\n" }, { "answer_id": 1687359, "author": "Wedge", "author_id": 332, "author_profile": "https://Stackoverflow.com/users/332", "pm_score": 1, "selected": false, "text": "<p>For your own email address I'd recommend not worrying about it too much. If you have a need to make your email address available to thousands of users then I would recommend either using a gmail address (vanilla or via google apps) or using a high quality spam filter.</p>\n\n<p>However, when displaying other users email addresses on your website I think some level of due diligence is required. Luckily, a blogger named Silvan Mühlemann has <a href=\"http://techblog.tilllate.com/2008/07/20/ten-methods-to-obfuscate-e-mail-addresses-compared/\" rel=\"nofollow noreferrer\">done all the difficult work for you</a>. He tested out different methods of obfuscation over a period of 1.5 years and determined the best ones, most of them involve css or javascript tricks that allow the address to be presented correctly in the browser but will confuse automated scrapers.</p>\n" }, { "answer_id": 2392582, "author": "ychaouche", "author_id": 212044, "author_profile": "https://Stackoverflow.com/users/212044", "pm_score": 0, "selected": false, "text": "<p>Spam bots will have their own Javascript and CSS engines over time, so I think you shouldn't look in this direction.</p>\n" }, { "answer_id": 3395273, "author": "SimonDowdles", "author_id": 302341, "author_profile": "https://Stackoverflow.com/users/302341", "pm_score": 3, "selected": false, "text": "<p>One of my favorite methods is to obfuscate the email address using php, a classic example is to convert the characters to HEX values like so:</p>\n\n<pre><code>function myobfiscate($emailaddress){\n $email= $emailaddress; \n $length = strlen($email); \n for ($i = 0; $i &lt; $length; $i++){ \n $obfuscatedEmail .= \"&amp;#\" . ord($email[$i]).\";\";\n }\n echo $obfuscatedEmail;\n}\n</code></pre>\n\n<p>And then in my markup I'll simply call it as follows:</p>\n\n<pre><code> &lt;a href=\"mailto:&lt;?php echo myobfiscate('[email protected]'); ?&gt;\"\ntitle=\"Email me!\"&gt;&lt;?php echo myobfiscate('[email protected]');?&gt; &lt;/a&gt;\n</code></pre>\n\n<p>Then examine your source, you'll be pleasantly surprised!</p>\n" }, { "answer_id": 7308749, "author": "Haluk", "author_id": 174559, "author_profile": "https://Stackoverflow.com/users/174559", "pm_score": 0, "selected": false, "text": "<p>Here is a simple jquery solution to this problem:</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\n$(document).ready(function() {\n str1=\"mailto:\";\n str2=\"info\";\n str3=\"@test.com\";\n $(\"#email_a\").attr(\"href\", str1+str2+str3);\n\n});\n&lt;/script&gt;\n\n&lt;a href=\"#\" id=\"email_a\"&gt;&lt;img src=\"sample.png\"/&gt;&lt;/a&gt;\n</code></pre>\n" }, { "answer_id": 10300743, "author": "Fuhrmanator", "author_id": 1168342, "author_profile": "https://Stackoverflow.com/users/1168342", "pm_score": 7, "selected": false, "text": "<p>This is the method I used, with a server-side include, e.g. <code>&lt;!--#include file=&quot;emailObfuscator.include&quot; --&gt;</code> where <code>emailObfuscator.include</code> contains the following:</p>\n<pre><code>&lt;!-- // http://lists.evolt.org/archive/Week-of-Mon-20040202/154813.html --&gt;\n&lt;script type=&quot;text/javascript&quot;&gt;\n function gen_mail_to_link(lhs,rhs,subject) {\n document.write(&quot;&lt;a href=\\&quot;mailto&quot;);\n document.write(&quot;:&quot; + lhs + &quot;@&quot;);\n document.write(rhs + &quot;?subject=&quot; + subject + &quot;\\&quot;&gt;&quot; + lhs + &quot;@&quot; + rhs + &quot;&lt;\\/a&gt;&quot;);\n }\n&lt;/script&gt;\n</code></pre>\n<p>To include an address, I use JavaScript:</p>\n<pre><code>&lt;script type=&quot;text/javascript&quot;&gt; \n gen_mail_to_link('john.doe','example.com','Feedback about your site...');\n&lt;/script&gt;\n&lt;noscript&gt;\n &lt;em&gt;Email address protected by JavaScript. Activate JavaScript to see the email.&lt;/em&gt;\n&lt;/noscript&gt;\n</code></pre>\n<p>Because I have been getting email via Gmail since 2005, spam is pretty much a non-issue. So, I can't speak of how effective this method is. You might want to read <a href=\"https://web.archive.org/web/20160304042853/http://techblog.tilllate.com/2008/07/20/ten-methods-to-obfuscate-e-mail-addresses-compared/\" rel=\"nofollow noreferrer\">this study</a> (although it's old) that produced this graph:</p>\n<p><img src=\"https://i.stack.imgur.com/To13I.png\" alt=\"enter image description here\" /></p>\n" }, { "answer_id": 13282029, "author": "Abdalla Mohamed Aly Ibrahim", "author_id": 1641233, "author_profile": "https://Stackoverflow.com/users/1641233", "pm_score": 1, "selected": false, "text": "<p>after using so many techniques i found an easy way and very friendly, the bots search for @ Símbolo and recently they search for [at] ant it's variation so i use 2 techniques</p>\n\n<ol>\n<li>i write my email on an image like the domaintolls use and it works\nperfectly or</li>\n<li>to replace the Símbolo (@) with an image of it like</li>\n</ol>\n\n<p><img src=\"https://i.stack.imgur.com/Hx1XJ.gif\" alt=\"@ replace\">\nand the image alt will be alt=\"@\" so the bot will find an image and any human will see it as a normal address so if he copy it he will copy the email and the job is don\nso the code will be </p>\n\n<pre><code>&lt;p&gt;myname&lt;img src=\"http://www.traidnt.net/vb/images/mail2.gif\" width=\"11\" height=\"9\" alt=\"@\" /&gt;domain.com&lt;/p&gt;\n</code></pre>\n" }, { "answer_id": 14097794, "author": "Donny", "author_id": 1939034, "author_profile": "https://Stackoverflow.com/users/1939034", "pm_score": 0, "selected": false, "text": "<p>I like ofaurax's answer best but I would modify to this for a little more hidden email:</p>\n\n<pre><code>onclick=\"p1='admin'; p2='domain.com'; this.href='mailto:' + p1 + '&amp; #x40;' + p2\"\n</code></pre>\n" }, { "answer_id": 14137666, "author": "Johann de Vries", "author_id": 1939080, "author_profile": "https://Stackoverflow.com/users/1939080", "pm_score": 2, "selected": false, "text": "<p>!- Adding this for reference, don't know how outdated the information might be, but it tells about a few simple solutions that don't require the use of any scripting</p>\n\n<p>After searching for this myself i came across this page but also these pages:</p>\n\n<p><a href=\"http://nadeausoftware.com/articles/2007/05/stop_spammer_email_harvesters_obfuscating_email_addresses\" rel=\"nofollow\">http://nadeausoftware.com/articles/2007/05/stop_spammer_email_harvesters_obfuscating_email_addresses</a></p>\n\n<p>try reversing the emailadress</p>\n\n<p><strong>Example plain HTML:</strong></p>\n\n<pre><code>&lt;bdo dir=\"rtl\"&gt;moc.elpmaxe@nosrep&lt;/bdo&gt;\nResult : [email protected]\n</code></pre>\n\n<p><strong>The same effect using CSS</strong></p>\n\n<pre><code>CSS:\n.reverse { unicode-bidi:bidi-override; direction:rtl; }\nHTML:\n&lt;span class=\"reverse\"&gt;moc.elpmaxe@nosrep&lt;/span&gt;\nResult : [email protected]\n</code></pre>\n\n<p>Combining this with any of earlier mentioned methods may even make it more effective</p>\n" }, { "answer_id": 16287550, "author": "T.Todua", "author_id": 2377343, "author_profile": "https://Stackoverflow.com/users/2377343", "pm_score": 1, "selected": false, "text": "<p>what about HTML_CHARACTER?:</p>\n\n<pre><code>joe&amp;#064;mail.com\n</code></pre>\n\n<p>outputs</p>\n\n<pre><code>[email protected]\n</code></pre>\n" }, { "answer_id": 18419069, "author": "Jani Hyytiäinen", "author_id": 611056, "author_profile": "https://Stackoverflow.com/users/611056", "pm_score": 3, "selected": false, "text": "<p>I know my answer won't be liked by many but please consider the points outlined here before thumbing down.</p>\n\n<p>Anything easily machine readable will be easily machine readable by the spammers. Even though their actions seem stupid to us, they're not stupid people. They're innovative and resourceful. They do not just use bots to harvest e-mails, they have a plethora of methods at their disposal and in addition to that, they simply pay for good fresh lists of e-mails. What it means is, that they got thousands of black-hat hackers worldwide to execute their jobs. People ready to code malware that scrape the screens of other peoples' browsers which eventually renders any method you're trying to achieve useless. This thread has already been read by 10+ such people and they're laughing at us. Some of them may be even bored to tears to find out we cannot put up a new challenge to them.</p>\n\n<p>Keep in mind that you're not eventually trying to save your time but the time of others. Because of this, please consider spending some extra time here. There is no easy-to-execute magic bullet that would work. If you work in a company that publishes 100 peoples' e-mails on the site and you can reduce 1 spam e-mail per day per person, we're talking about 36500 spam emails a year. If deleting such e-mail takes 5 seconds on average, we're talking about 50 working hours yearly. Not to mention the reduced amount of annoyance. So, why not spend a few hours on this?</p>\n\n<p>It's not only you and the people who receive the e-mail that consider time an asset. Therefore, you must find a way to obfuscate the e-mail addresses in such way, that it doesn't pay off to crack it. If you use some widely used method to obfuscate the e-mails, it really pays off to crack it. Since as an result, the cracker will get their hands on thousands, if not tens or hundreds of thousands of fresh e-mails. And for them, they will get money.</p>\n\n<p>So, go ahead and code your own method. This is a rare case where reinventing the wheel really pays off. Use a method that is not machine readable and one which will preferably require some user interaction without sacrificing the user experience.</p>\n\n<p>I spent some 20 minutes to code off an example of what I mean. In the example, I used KnockoutJS simply because I like it and I know you won't probably use it yourself. But it's irrelevant anyway. It's a custom solution which is not widely used. Cracking it won't pose a reward for doing it since the method of doing it would only work on a single page in the vast internet.</p>\n\n<p>Here's the fiddle: <a href=\"http://jsfiddle.net/hzaw6/\" rel=\"noreferrer\">http://jsfiddle.net/hzaw6/</a></p>\n\n<p>The below code is not meant to be an example of good code. But just a quick sample of code which is very hard for machine to figure out we even handle e-mails in here. And even if it could be done, it's not gonna pay off to execute in large scale.</p>\n\n<p>And yes, I do know it doesn't work on IE = lte8 because of 'Unable to get property 'attributes' of undefined or null reference' but I simply don't care because it's just a demo of method, not actual implementation, and not intended to be used on production as it is. Feel free to code your own which is cooler, technically more solid etc.. </p>\n\n<p>Oh, and never ever ever name something mail or email in html or javascript. It's just way too easy to scrape the DOM and the window object for anything named mail or email and check if it contains something that matches an e-mail. This is why you don't want any variables ever that would contain e-mail in it's full form and this is also why you want user to interact with the page before you assign such variables. If your javascript object model contains any e-mail addresses on DOM ready state, you're exposing them to the spammers.</p>\n\n<p>The HTML:</p>\n\n<pre><code>&lt;div data-bind=\"foreach: contacts\"&gt;\n &lt;div class=\"contact\"&gt;\n &lt;div&gt;\n &lt;h5 data-bind=\"text: firstName + ' ' + lastName + ' / ' + department\"&gt;&lt;/h5&gt;\n &lt;ul&gt;\n &lt;li&gt;Phone: &lt;span data-bind=\"text: phone\"&gt;&lt;/span&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"#999\" data-bind=\"click:$root.reveal\"&gt;E-mail&lt;/a&gt; &lt;span data-bind=\"visible: $root.msgMeToThis() != ''\"&gt;&lt;input class=\"merged\" data-bind=\"value: mPrefix\" readonly=\"readonly\" /&gt;&lt;span data-bind=\"text: '@' + domain\"&gt;&lt;/span&gt;&lt;/span&gt;&lt;/li&gt;\n &lt;/ul&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>The JS</p>\n\n<pre><code>function ViewModel(){\n var self = this;\n\n self.contacts = ko.observableArray([\n { firstName:'John', mPrefix: 'john.doe', domain: 'domain.com', lastName: 'Doe', department: 'Sales', phone: '+358 12 345 6789' },\n { firstName:'Joe', mPrefix: 'joe.w', domain: 'wonder.com', lastName: 'Wonder', department: 'Time wasting', phone: '+358 98 765 4321' },\n { firstName:'Mike', mPrefix: 'yo', domain: 'rappin.com', lastName: 'Rophone', department: 'Audio', phone: '+358 11 222 3333' }\n ]);\n self.msgMeToThis = ko.observable('');\n self.reveal = function(m, e){\n var name = e.target.attributes.href.value;\n name = name.replace('#', '');\n self.msgMeToThis(name);\n };\n}\nvar viewModel = new ViewModel();\nko.applyBindings(viewModel);\n</code></pre>\n" }, { "answer_id": 18428998, "author": "Jani Hyytiäinen", "author_id": 611056, "author_profile": "https://Stackoverflow.com/users/611056", "pm_score": 0, "selected": false, "text": "<p>I just have to provide an another answer. I just came up with something fun to play with.</p>\n\n<p>I found out that in many common character tables, the letters @ and a-z reappear more than once. You can map the original characters to the new mappings and make it harder for spam bots to figure out what the e-mail is.</p>\n\n<p>If you loop through the string, and get the character code of a letter, then add 65248 to it and build a html entity based on the number, you come up with a human readable e-mail address. </p>\n\n<pre><code>var str = '[email protected]';\nstr = str.toLowerCase().replace(/[\\.@a-z]/gi, function(match, position, str){\n var num = str.charCodeAt(position);\n return ('&amp;#' + (num + 65248) + ';');\n});\n</code></pre>\n\n<p>Here is a working fiddle: <a href=\"http://jsfiddle.net/EhtSC/8/\" rel=\"nofollow\">http://jsfiddle.net/EhtSC/8/</a></p>\n\n<p>You can improve this approach by creating a more complete set of mappings between characters that look the same. But if you copy/paste the e-mail to notepad, for example, you get a lot of boxes.</p>\n\n<p>To overcome some of the user experience issues, I created the e-mail as link. When you click it, it remaps the characters back to their originals.</p>\n\n<p>To improve this, you can create more complex character mappings if you like. If you can find several characters that can be used for example in the place of 'a' why not randomly mapping to those.</p>\n\n<p>Probably not the most secure approach ever but I really had fun playing around with it :D</p>\n" }, { "answer_id": 19349775, "author": "webrama.pl", "author_id": 1317014, "author_profile": "https://Stackoverflow.com/users/1317014", "pm_score": 1, "selected": false, "text": "<p>And my function. I've created it looking at answers placed in this topic.</p>\n\n<pre><code> function antiboteEmail($email)\n {\n $html = '';\n\n $email = strrev($email);\n $randId = rand(1, 500);\n\n $html .= '&lt;span id=\"addr-'.$randId.'\" class=\"addr\"&gt;[turn javascript on to see the e-mail]&lt;/span&gt;';\n $html .= &lt;&lt;&lt;EOD\n &lt;script&gt;\n $(document).ready(function(){\n\n var addr = \"$email\";\n addr = addr.split(\"\").reverse().join(\"\");\n $(\"#addr-$randId\").html(\"&lt;a href=\\\"mailto:\" + addr + \"\\\"&gt;\" + addr + \" &lt;/a&gt;\");\n });\n &lt;/script&gt;\nEOD;\n\n return $html;\n }\n</code></pre>\n\n<p>It uses two methods: right to left dir and javascript putting. </p>\n" }, { "answer_id": 22217705, "author": "saun4frsh", "author_id": 2666947, "author_profile": "https://Stackoverflow.com/users/2666947", "pm_score": 1, "selected": false, "text": "<p>Option 1 : Split email address into multiple parts and create an array in JavaScript out of these parts. \nNext join these parts in the correct order and use the .innerHTML property to add the email address to the web page.</p>\n\n<pre><code> &lt;span id=\"email\"&gt; &lt;/span&gt; // blank tag\n\n &lt;script&gt;\n var parts = [\"info\", \"XXXXabc\", \"com\", \"&amp;#46;\", \"&amp;#64;\"];\n var email = parts[0] + parts[4] + parts[1] + parts[3] + parts[2];\n document.getElementById(\"email\").innerHTML=email; \n &lt;/script&gt;\n</code></pre>\n\n<p>Option 2 : Use image instead of email text</p>\n\n<p>Image creator website from text : <a href=\"http://www.chxo.com/labelgen/\" rel=\"nofollow\">http://www.chxo.com/labelgen/</a> </p>\n\n<p>Option 3 : We can use AT instead of \"@\" and DOT instead of \" . \" </p>\n\n<p>i.e : </p>\n\n<pre><code> info(AT)XXXabc(DOT)com \n</code></pre>\n" }, { "answer_id": 22217773, "author": "saun4frsh", "author_id": 2666947, "author_profile": "https://Stackoverflow.com/users/2666947", "pm_score": 0, "selected": false, "text": "<p>Option 1 : Split email address into multiple parts and create an array in JavaScript out of these parts. \nNext join these parts in the correct order and use the .innerHTML property to add the email address to the web page.</p>\n\n<pre><code> &lt;span id=\"email\"&gt; &lt;/span&gt; // blank tag\n\n &lt;script&gt;\n var parts = [\"info\", \"XXXXabc\", \"com\", \"&amp;#46;\", \"&amp;#64;\"];\n var email = parts[0] + parts[4] + parts[1] + parts[3] + parts[2];\n document.getElementById(\"email\").innerHTML=email; \n &lt;/script&gt;\n</code></pre>\n\n<p>Option 2 : Use image instead of email text</p>\n\n<p>Image creator website from text : <a href=\"http://www.chxo.com/labelgen/\" rel=\"nofollow\">http://www.chxo.com/labelgen/</a> </p>\n\n<p>Option 3 : We can use AT instead of \"@\" and DOT instead of \" . \" </p>\n\n<p>i.e : </p>\n\n<pre><code> info(AT)XXXabc(DOT)com \n</code></pre>\n" }, { "answer_id": 24135598, "author": "Sasse", "author_id": 3725049, "author_profile": "https://Stackoverflow.com/users/3725049", "pm_score": 0, "selected": false, "text": "<p>I just coded the following. Don't know if it's good but it's better then just writing the email in plain text. Many robots will be fooled but not all of them.</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\n $(function () {\n setTimeout(function () {\n var m = ['com', '.', 'domain', '@', 'info', ':', 'mailto'].reverse().join('');\n\n /* Set the contact email url for each \"contact us\" links.*/\n $('.contactUsLink').prop(\"href\", m);\n }, 200);\n });\n&lt;/script&gt;\n</code></pre>\n\n<p>If the robot solve this then there's no need to add more \"simple logic\" code like \"if (1 == 1 ? '@' : '')\" or adding the array elements in another order since the robot just evals the code anyway.</p>\n" }, { "answer_id": 26420534, "author": "Andy Swift", "author_id": 72958, "author_profile": "https://Stackoverflow.com/users/72958", "pm_score": 6, "selected": false, "text": "<p>Not my idea originally but I can't find the author:</p>\n\n<pre><code>&lt;a href=\"mailto:[email protected]\"\n onmouseover=\"this.href=this.href.replace(/x/g,'');\"&gt;link&lt;/a&gt;\n</code></pre>\n\n<p>Add as many x's as you like. It works perfectly to read, copy and paste, and can't be read by a bot.</p>\n" }, { "answer_id": 30476468, "author": "Sergiu", "author_id": 612847, "author_profile": "https://Stackoverflow.com/users/612847", "pm_score": 2, "selected": false, "text": "<p>A <a href=\"https://stackoverflow.com/a/30476576/612847\">response</a> of mine on a similar question:</p>\n\n<blockquote>\n <p>I use a very simple combination of CSS and jQuery which displays the\n email address correctly to the user and also works when the anchor is\n clicked:</p>\n \n <p>HTML:</p>\n\n<pre><code>&lt;a href=\"mailto:[email protected]\" id=\"lnkMail\"&gt;moc.elpmaxe@em&lt;/a&gt;\n</code></pre>\n \n <p>CSS:</p>\n\n<pre><code>#lnkMail {\n unicode-bidi: bidi-override;\n direction: rtl;\n}\n</code></pre>\n \n <p>jQuery:</p>\n\n<pre><code>$('#lnkMail').hover(function(){\n // here you can use whatever replace you want\n var newHref = $(this).attr('href').replace('spam', 'com');\n $(this).attr('href', newHref);\n});\n</code></pre>\n \n <p><a href=\"https://jsfiddle.net/qy1dkkbh/\" rel=\"nofollow noreferrer\">Here</a> is a working example.</p>\n</blockquote>\n" }, { "answer_id": 30476576, "author": "Sergiu", "author_id": 612847, "author_profile": "https://Stackoverflow.com/users/612847", "pm_score": 2, "selected": false, "text": "<p>I use a very simple combination of CSS and jQuery which displays the email address correctly to the user and also works when the anchor is clicked or hovered:</p>\n\n<p>HTML:</p>\n\n<pre><code>&lt;a href=\"mailto:[email protected]\" id=\"lnkMail\"&gt;moc.elpmaxe@em&lt;/a&gt;\n</code></pre>\n\n<p>CSS:</p>\n\n<pre><code>#lnkMail {\n unicode-bidi: bidi-override;\n direction: rtl;\n}\n</code></pre>\n\n<p>jQuery:</p>\n\n<pre><code>$('#lnkMail').hover(function(){\n // here you can use whatever replace you want\n var newHref = $(this).attr('href').replace('spam', 'com');\n $(this).attr('href', newHref);\n});\n</code></pre>\n\n<p><a href=\"https://jsfiddle.net/qy1dkkbh/\" rel=\"nofollow\">Here</a> is a working example.</p>\n" }, { "answer_id": 34044386, "author": "Mr. B.", "author_id": 1792858, "author_profile": "https://Stackoverflow.com/users/1792858", "pm_score": 1, "selected": false, "text": "<p>I don't like JavaScript and HTML to be mixed, that's why I use this solution. It works fine for me, for now.</p>\n\n<p><strong>Idea</strong>: you could make it more complicated by providing encrypted information in the <code>data</code>-attributes and decrypt it within the JS. This is simply done by replacing letters or just reversing them. </p>\n\n<p><strong>HTML</strong>: </p>\n\n<pre><code>&lt;span class=\"generate-email\" data-part1=\"john\" data-part2=\"gmail\" data-part3=\"com\"&gt;placeholder&lt;/span&gt;\n</code></pre>\n\n<p><strong>JS</strong>:</p>\n\n<pre><code>$(function() {\n $('.generate-email').each(function() {\n var that = $(this);\n that.html(\n that.data('part1') + '@' + that.data('part2') + '.' + that.data('part3')\n );\n }); \n});\n</code></pre>\n\n<p>Try it: <a href=\"http://jsfiddle.net/x6g9L817/\" rel=\"nofollow\">http://jsfiddle.net/x6g9L817/</a></p>\n" }, { "answer_id": 37175227, "author": "Darius", "author_id": 1293700, "author_profile": "https://Stackoverflow.com/users/1293700", "pm_score": 2, "selected": false, "text": "<p>Here is my working version:</p>\n\n<hr>\n\n<p>Create somewhere a container with a fallback text:</p>\n\n<pre><code>&lt;div id=\"knock_knock\"&gt;Activate JavaScript, please.&lt;/div&gt;\n</code></pre>\n\n<p>And add at the bottom of the DOM (w.r.t. the rendering) the following snippet:</p>\n\n<pre><code>&lt;script&gt;\n (function(d,id,lhs,rhs){\n d.getElementById(id).innerHTML = \"&lt;a rel=\\\"nofollow\\\" href=\\\"mailto\"+\":\"+lhs+\"@\"+rhs+\"\\\"&gt;\"+\"Mail\"+\"&lt;\\/a&gt;\";\n })(window.document, \"knock_knock\", \"your.name\", \"example.com\");\n&lt;/script&gt;\n</code></pre>\n\n<p>It adds the generated hyperlink to the specified container:</p>\n\n<pre><code>&lt;div id=\"knock_knock\"&gt;&lt;a rel=\"nofollow\" href=\"[email protected]\"&gt;Mail&lt;/a&gt;&lt;/div&gt;\n</code></pre>\n\n<p>In addition here is a minified version:</p>\n\n<pre><code>&lt;script&gt;(function(d,i,l,r){d.getElementById(i).innerHTML=\"&lt;a rel=\\\"nofollow\\\" href=\\\"mailto\"+\":\"+l+\"@\"+r+\"\\\"&gt;\"+\"Mail\"+\"&lt;\\/a&gt;\";})(window.document,\"knock_knock\",\"your.name\",\"example.com\");&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 41566570, "author": "cyptus", "author_id": 1216595, "author_profile": "https://Stackoverflow.com/users/1216595", "pm_score": 7, "selected": false, "text": "<p>Working with content and attr in CSS:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.cryptedmail:after {\r\n content: attr(data-name) \"@\" attr(data-domain) \".\" attr(data-tld); \r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;a href=\"#\" class=\"cryptedmail\"\r\n data-name=\"info\"\r\n data-domain=\"example\"\r\n data-tld=\"org\"\r\n onclick=\"window.location.href = 'mailto:' + this.dataset.name + '@' + this.dataset.domain + '.' + this.dataset.tld; return false;\"&gt;&lt;/a&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>When javascript is disabled, just the click event will not work, email is still displayed.</p>\n\n<p>Another interesting approach (at least without a click event) would be to make use of the right-to-left mark to override the writing direction. more about this: <a href=\"https://en.wikipedia.org/wiki/Right-to-left_mark\" rel=\"noreferrer\">https://en.wikipedia.org/wiki/Right-to-left_mark</a></p>\n" }, { "answer_id": 43749902, "author": "Aaron Esau", "author_id": 3678023, "author_profile": "https://Stackoverflow.com/users/3678023", "pm_score": 3, "selected": false, "text": "<p>Spambots won't interpret this, because it is a lesser-known method :)</p>\n\n<p>First, define the css:</p>\n\n<pre><code>email:before {\n content: \"admin\";\n}\n\nemail:after {\n content: \"@example.com\";\n}\n</code></pre>\n\n<p>Now, wherever you want to display your email, simply insert the following HTML:</p>\n\n<pre><code>&lt;div id=\"email\"&gt;&lt;/div&gt;\n</code></pre>\n\n<p>And tada!</p>\n" }, { "answer_id": 46271172, "author": "Ogun Adebali", "author_id": 5181427, "author_profile": "https://Stackoverflow.com/users/5181427", "pm_score": 0, "selected": false, "text": "<p>Font-awesome works!</p>\n\n<pre><code>&lt;link rel=\"stylesheet\" href=\"path/to/font-awesome/css/font-awesome.min.css\"&gt;\n\n&lt;p&gt;myemail&lt;i class=\"fa fa-at\" aria-hidden=\"true\"&gt;&lt;/i&gt;mydomain.com&lt;/p&gt;\n</code></pre>\n\n<p><a href=\"http://fontawesome.io/\" rel=\"nofollow noreferrer\">http://fontawesome.io/</a></p>\n" }, { "answer_id": 47967275, "author": "Project Mayhem", "author_id": 1262673, "author_profile": "https://Stackoverflow.com/users/1262673", "pm_score": -1, "selected": false, "text": "<p>Another option, I perefer font awesome icons</p>\n\n<p>Fa implementation:</p>\n\n<pre><code>&lt;link rel=\"stylesheet\" href=\"path/to/font-awesome/css/font-awesome.min.css\"&gt;\n</code></pre>\n\n<p>Mail Address:</p>\n\n<pre><code>&lt;a href=\"mailto:[email protected]\"&gt;&lt;span class=\"label\"&gt;info&lt;i class=\"fa fa-at\"&gt;&lt;/i&gt;uploadimage.club&lt;/span&gt;&lt;/a&gt;\n</code></pre>\n" }, { "answer_id": 62969771, "author": "mrts", "author_id": 258772, "author_profile": "https://Stackoverflow.com/users/258772", "pm_score": 2, "selected": false, "text": "<p>A neat trick is to have a <code>div</code> with the word <em>Contact</em> and reveal the email address only when the user moves the mouse over it. E-mail can be Base64-encoded for extra protection.</p>\n<p>Here's how:</p>\n<pre class=\"lang-html prettyprint-override\"><code>&lt;div id=&quot;contacts&quot;&gt;Contacts&lt;/div&gt;\n\n&lt;script&gt;\n document.querySelector(&quot;#contacts&quot;).addEventListener(&quot;mouseover&quot;, (event) =&gt; {\n // Base64-encode your email and provide it as argument to atob()\n event.target.textContent = atob('aW5mb0BjbGV2ZXJpbmcuZWU=')\n });\n&lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 63862335, "author": "Emeric", "author_id": 9753985, "author_profile": "https://Stackoverflow.com/users/9753985", "pm_score": 2, "selected": false, "text": "<p>One possibility would be to use <code>isTrusted</code> property (Javascript).</p>\n<blockquote>\n<p>The isTrusted read-only property of the Event interface is a Boolean\nthat is true when the event was generated by a user action, and false\nwhen the event was created or modified by a script or dispatched via\nEventTarget.dispatchEvent().</p>\n</blockquote>\n<p>eg in your case:</p>\n<pre><code>getEmail() {\n if (event.isTrusted) {\n /* The event is trusted */\n return '[email protected]';\n } else {\n /* The event is not trusted */\n return '[email protected]';\n }\n}\n</code></pre>\n<p>⚠ IE isn't compatible !</p>\n<p>Read more from doc: <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Event/isTrusted\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/API/Event/isTrusted</a></p>\n" }, { "answer_id": 68775296, "author": "ztom", "author_id": 10944219, "author_profile": "https://Stackoverflow.com/users/10944219", "pm_score": 0, "selected": false, "text": "<p><strong>Hidden Base64 solution.</strong></p>\n<p>I think it does not matter if you put an email address in a :before/:after pseudo or split it in reverse written data attributes ... Spambots are clever and analyze parsed webpages.</p>\n<p>This solution is interactive. The user has to click &quot;show&quot; to get an base64 decoded email address which can be copied and/or is clickable.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>// search for [data-b64mail] attributes\ndocument.querySelectorAll('[data-b64mail]').forEach(el =&gt; {\n\n // set \"show\" link\n el.innerHTML = '&lt;span style=\"text-decoration:underline;cursor:pointer\"&gt;show&lt;/span&gt;';\n \n // set click event to all elements\n el.addEventListener('click', function (e) {\n let cT = e.currentTarget;\n\n // show address\n cT.innerHTML = atob(cT.getAttribute('data-b64mail'));\n \n // set mailto on a tags\n if (cT.tagName === 'A')\n cT.setAttribute('href', 'mailto:' + atob(cT.getAttribute('data-b64mail')));\n\n });\n\n});\n\n// get base64 encoded string\nconsole.log(btoa('[email protected]'));</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;p&gt;E-mail (span): &lt;span data-b64mail=\"bWFpbEBleGFtcGxlLm9yZw==\"&gt;&lt;/span&gt;&lt;/p&gt;\n\n&lt;p&gt;E-mail (link): &lt;a href=\"#\" data-b64mail=\"bWFpbEBleGFtcGxlLm9yZw==\"&gt;&lt;/a&gt;&lt;/p&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13227/" ]
When placing email addresses on a webpage do you place them as text like this: ``` [email protected] ``` or use a clever trick to try and fool the email address harvester bots? For example: **HTML Escape Characters:** ``` &#106;&#111;&#101;&#46;&#115;&#111;&#109;&#101;&#98;&#111;&#100;&#121;&#64;&#99;&#111;&#109;&#112;&#97;&#110;&#121;&#46;&#99;&#111;&#109; ``` **Javascript Decrypter:** ``` function XOR_Crypt(EmailAddress) { Result = new String(); for (var i = 0; i < EmailAddress.length; i++) { Result += String.fromCharCode(EmailAddress.charCodeAt(i) ^ 128); } document.write(Result); } XOR_Crypt("êïå®óïíåâïäùÀãïíðáîù®ãïí"); ``` **Human Decode:** ``` [email protected] joe.somebody AT company.com ``` What do you use or do you even bother?
I generally don't bother. I used to be on a mailing list that got several thousand spams every day. Our spam filter (spamassassin) let maybe 1 or 2 a day through. With filters this good, why make it difficult for legitimate people to contact you?
163,662
<p>Alright, I'm trying to read a comma delimited file and then put that into a ListView (or any grid, really). I have the delimiting part of the job taken care of, with the fields of the file being put into a multidimensional string array. The problem is trying to get it into the ListView.</p> <p>It appears that there isn't a real way of adding columns or items dynamically, since each column and item needs to be manually declared. This poses a problem, because I need the ListView to be as large as the file is, who's size isn't set. It could be huge one time, and small another. </p> <p>Any help with this would be appreciated.</p> <hr> <p>In response to Jeffrey's answer.</p> <p>I would do exactly that, but the problem that I'm running into is a basic one. How can I create these objects without naming them. Noobie question, but a problem for me, sadly. This is what I have so far.</p> <pre><code>int x = 0; int y = 0; while (y &lt; linenum) { while (x &lt; width) { ListViewItem listViewItem1 = new ListViewItem(list[y,x]); x++; } y++; x = 0; } </code></pre> <p>What should I do for the name of listViewItem1?</p>
[ { "answer_id": 163689, "author": "Jeffrey L Whitledge", "author_id": 10174, "author_profile": "https://Stackoverflow.com/users/10174", "pm_score": 2, "selected": true, "text": "<p>Just loop through each of the arrays in that you've created and create a new ListViewItem object (there is a constructor that takes an array of strings, I believe). The pass the ListViewItem to the ListView.Items.Add() method.</p>\n" }, { "answer_id": 163723, "author": "Aaron Fischer", "author_id": 5618, "author_profile": "https://Stackoverflow.com/users/5618", "pm_score": 1, "selected": false, "text": "<p>You can <a href=\"http://www.dotnetspider.com/resources/646-Handling-CSV-Files-ADO.aspx\" rel=\"nofollow noreferrer\">load a csv file with ado.net</a> and bind it to a datagrids data source. Or you could use <a href=\"http://weblogs.asp.net/pleloup/archive/2008/04/12/linq-to-csv-library.aspx\" rel=\"nofollow noreferrer\">linq for xml</a> to parse the file and bind those results to a datagrid's data source property.</p>\n" }, { "answer_id": 163786, "author": "Timothy Lee Russell", "author_id": 12919, "author_profile": "https://Stackoverflow.com/users/12919", "pm_score": 1, "selected": false, "text": "<p>I would use the <a href=\"http://filehelpers.sourceforge.net/\" rel=\"nofollow noreferrer\">FileHelpers Library</a> to read in the CSV file and then DataBind the collection to the ListView.</p>\n\n<p>Use the DelimitedClassBuilder to dynamically create columns with the typeof(string) equal to the number of columns in your source file.</p>\n\n<p>Load your CSV file into a DataTable using the RecordClass that you created and then set the ListView.DataSource to the DataTable.</p>\n" }, { "answer_id": 163848, "author": "kenny", "author_id": 3225, "author_profile": "https://Stackoverflow.com/users/3225", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://www.codeproject.com/KB/linq/LINQtoCSV.aspx\" rel=\"nofollow noreferrer\">Linq To CSV</a></p>\n" }, { "answer_id": 163934, "author": "user24591", "author_id": 24591, "author_profile": "https://Stackoverflow.com/users/24591", "pm_score": 0, "selected": false, "text": "<p>Is there a reason you can't use a DataTable? Use the DataSource member off of it.</p>\n\n<p>Also, I hope you are using the String.Split function, and not manually parsing...</p>\n\n<p>~S</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23875/" ]
Alright, I'm trying to read a comma delimited file and then put that into a ListView (or any grid, really). I have the delimiting part of the job taken care of, with the fields of the file being put into a multidimensional string array. The problem is trying to get it into the ListView. It appears that there isn't a real way of adding columns or items dynamically, since each column and item needs to be manually declared. This poses a problem, because I need the ListView to be as large as the file is, who's size isn't set. It could be huge one time, and small another. Any help with this would be appreciated. --- In response to Jeffrey's answer. I would do exactly that, but the problem that I'm running into is a basic one. How can I create these objects without naming them. Noobie question, but a problem for me, sadly. This is what I have so far. ``` int x = 0; int y = 0; while (y < linenum) { while (x < width) { ListViewItem listViewItem1 = new ListViewItem(list[y,x]); x++; } y++; x = 0; } ``` What should I do for the name of listViewItem1?
Just loop through each of the arrays in that you've created and create a new ListViewItem object (there is a constructor that takes an array of strings, I believe). The pass the ListViewItem to the ListView.Items.Add() method.
163,747
<p>I'm working on a configuration script for a JNI wrapper. One of the configuration parameters is the path to <code>jni.h</code>. What's a good quick-and-dirty Autoconf test for whether this parameter is set correctly for C++ compilation? You can assume you're running on Linux and <code>g++</code> is available.</p> <p>Alternatively, is there a way to get <code>javah</code> (or a supporting tool) to give me this path directly?</p>
[ { "answer_id": 164030, "author": "Braden", "author_id": 18144, "author_profile": "https://Stackoverflow.com/users/18144", "pm_score": 4, "selected": true, "text": "<p>Checking for headers is easy; just use <code>AC_CHECK_HEADER</code>. If it's in a weird place (i.e., one the compiler doesn't know about), it's entirely reasonable to expect users to set <code>CPPFLAGS</code>.</p>\n\n<p>The hard part is actually locating <code>libjvm</code>. You typically don't want to link with this; but you may want to default to a location to <code>dlopen</code> it from if <code>JAVA_HOME</code> is not set at run time.</p>\n\n<p>But I don't have a better solution than requiring that <code>JAVA_HOME</code> be set at configure time. There's just too much variation in how this stuff is deployed across various OSes (even just Linux distributions). This is what I do:</p>\n\n<pre><code>AC_CHECK_HEADER([jni.h], [have_jni=yes])\nAC_ARG_VAR([JAVA_HOME], [Java Runtime Environment (JRE) location])\nAC_ARG_ENABLE([java-feature],\n [AC_HELP_STRING([--disable-java-feature],\n [disable Java feature])])\ncase $target_cpu in\n x86_64) JVM_ARCH=amd64 ;;\n i?86) JVM_ARCH=i386 ;;\n *) JVM_ARCH=$target_cpu ;;\nesac\nAC_SUBST([JVM_ARCH])\nAS_IF([test X$enable_java_feature != Xno],\n[AS_IF([test X$have_jni != Xyes],\n [AC_MSG_FAILURE([The Java Native Interface is required for Java feature.])])\nAS_IF([test -z \"$JAVA_HOME\"],\n[AC_MSG_WARN([JAVA_HOME has not been set. JAVA_HOME must be set at run time to locate libjvm.])],\n[save_LDFLAGS=$LDFLAGS\nLDFLAGS=\"-L$JAVA_HOME/lib/$JVM_ARCH/client -L$JAVA_HOME/lib/$JVM_ARCH/server $LDFLAGS\"\nAC_CHECK_LIB([jvm], [JNI_CreateJavaVM], [LIBS=$LIBS],\n [AC_MSG_WARN([no libjvm found at JAVA_HOME])])\nLDFLAGS=$save_LDFLAGS\n])])\n</code></pre>\n" }, { "answer_id": 17338895, "author": "Christopher Smith", "author_id": 60871, "author_profile": "https://Stackoverflow.com/users/60871", "pm_score": 3, "selected": false, "text": "<p>Then there is the easy way: <a href=\"http://www.gnu.org/software/autoconf-archive/ax_jni_include_dir.html\" rel=\"noreferrer\">http://www.gnu.org/software/autoconf-archive/ax_jni_include_dir.html</a></p>\n\n<p>Sometimes it is best to just use the standard recipies.</p>\n" }, { "answer_id": 65376766, "author": "Quincey Koziol", "author_id": 2602941, "author_profile": "https://Stackoverflow.com/users/2602941", "pm_score": 0, "selected": false, "text": "<p>FYI - the patch below against the latest ax_jni_include_dir.m4 works for me on Macos 11.1.</p>\n<pre><code>--- a/m4/ax_jni_include_dir.m4\n+++ b/m4/ax_jni_include_dir.m4\n@@ -73,13 +73,19 @@ fi\n \n case &quot;$host_os&quot; in\n darwin*) # Apple Java headers are inside the Xcode bundle.\n- macos_version=$(sw_vers -productVersion | sed -n -e 's/^@&lt;:@0-9@:&gt;@\n*.\\(@&lt;:@0-9@:&gt;@*\\).@&lt;:@0-9@:&gt;@*/\\1/p')\n- if @&lt;:@ &quot;$macos_version&quot; -gt &quot;7&quot; @:&gt;@; then\n- _JTOPDIR=&quot;$(xcrun --show-sdk-path)/System/Library/Frameworks/JavaVM.framework&quot;\n- _JINC=&quot;$_JTOPDIR/Headers&quot;\n+ major_macos_version=$(sw_vers -productVersion | sed -n -e 's/^\\(@&lt;:@0-9@:&gt;@*\\).@&lt;:@0-9@:&gt;@*.@&lt;:@0-9@:&gt;@*/\\1/p')\n+ if @&lt;:@ &quot;$major_macos_version&quot; -gt &quot;10&quot; @:&gt;@; then\n+ _JTOPDIR=&quot;$(/usr/libexec/java_home)&quot;\n+ _JINC=&quot;$_JTOPDIR/include&quot;\n else\n- _JTOPDIR=&quot;/System/Library/Frameworks/JavaVM.framework&quot;\n- _JINC=&quot;$_JTOPDIR/Headers&quot;\n+ macos_version=$(sw_vers -productVersion | sed -n -e 's/^@&lt;:@0-9@:&gt;@*.\\(@&lt;:@0-9@:&gt;@*\\).@&lt;:@0-9@:&gt;@*/\\1/p')\n+ if @&lt;:@ &quot;$macos_version&quot; -gt &quot;7&quot; @:&gt;@; then\n+ _JTOPDIR=&quot;$(xcrun --show-sdk-path)/System/Library/Frameworks/JavaVM.framework&quot;\n+ _JINC=&quot;$_JTOPDIR/Headers&quot;\n+ else\n+ _JTOPDIR=&quot;/System/Library/Frameworks/JavaVM.framework&quot;\n+ _JINC=&quot;$_JTOPDIR/Headers&quot;\n+ fi\n fi\n ;;\n *) _JINC=&quot;$_JTOPDIR/include&quot;;;\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1412/" ]
I'm working on a configuration script for a JNI wrapper. One of the configuration parameters is the path to `jni.h`. What's a good quick-and-dirty Autoconf test for whether this parameter is set correctly for C++ compilation? You can assume you're running on Linux and `g++` is available. Alternatively, is there a way to get `javah` (or a supporting tool) to give me this path directly?
Checking for headers is easy; just use `AC_CHECK_HEADER`. If it's in a weird place (i.e., one the compiler doesn't know about), it's entirely reasonable to expect users to set `CPPFLAGS`. The hard part is actually locating `libjvm`. You typically don't want to link with this; but you may want to default to a location to `dlopen` it from if `JAVA_HOME` is not set at run time. But I don't have a better solution than requiring that `JAVA_HOME` be set at configure time. There's just too much variation in how this stuff is deployed across various OSes (even just Linux distributions). This is what I do: ``` AC_CHECK_HEADER([jni.h], [have_jni=yes]) AC_ARG_VAR([JAVA_HOME], [Java Runtime Environment (JRE) location]) AC_ARG_ENABLE([java-feature], [AC_HELP_STRING([--disable-java-feature], [disable Java feature])]) case $target_cpu in x86_64) JVM_ARCH=amd64 ;; i?86) JVM_ARCH=i386 ;; *) JVM_ARCH=$target_cpu ;; esac AC_SUBST([JVM_ARCH]) AS_IF([test X$enable_java_feature != Xno], [AS_IF([test X$have_jni != Xyes], [AC_MSG_FAILURE([The Java Native Interface is required for Java feature.])]) AS_IF([test -z "$JAVA_HOME"], [AC_MSG_WARN([JAVA_HOME has not been set. JAVA_HOME must be set at run time to locate libjvm.])], [save_LDFLAGS=$LDFLAGS LDFLAGS="-L$JAVA_HOME/lib/$JVM_ARCH/client -L$JAVA_HOME/lib/$JVM_ARCH/server $LDFLAGS" AC_CHECK_LIB([jvm], [JNI_CreateJavaVM], [LIBS=$LIBS], [AC_MSG_WARN([no libjvm found at JAVA_HOME])]) LDFLAGS=$save_LDFLAGS ])]) ```
163,757
<p>I am using boost::signal in a native C++ class, and I now I am writing a .NET wrapper in C++/CLI, so that I can expose the native C++ callbacks as .NET events. When I try to use boost::bind to take the address of a member function of my managed class, I get compiler error 3374, saying I cannot take the address of a member function unless I am creating a delegate instance. Does anyone know how to bind a member function of a managed class using boost::bind?</p> <p>For clarification, the following sample code causes Compiler Error 3374:</p> <pre><code>#include &lt;boost/bind.hpp&gt; public ref class Managed { public: Managed() { boost::bind(&amp;Managed::OnSomeEvent, this); } void OnSomeEvent(void) { } }; </code></pre>
[ { "answer_id": 165362, "author": "Brian Stewart", "author_id": 3114, "author_profile": "https://Stackoverflow.com/users/3114", "pm_score": 2, "selected": false, "text": "<p>After googling some more, I finally found a <a href=\"http://mr-sharpoblunto.junkship.org/2007/11/mapping-boostsignals-to-net-events.html\" rel=\"nofollow noreferrer\">nice blog post</a> about how to do this. The code in that post was a little more than I needed, but the main nugget was to use a global free function that takes an argument of the managed this pointer wrapped in a gcroot&lt;> template. See the <strong>SomeEventProxy(...)</strong> in the code below for an example. This function then turns around and calls the managed member I was trying to bind. My solution appears below for future reference.</p>\n\n<pre><code>#include &lt;msclr/marshal.h&gt;\n\n#include &lt;boost/bind.hpp&gt;\n#include &lt;boost/signal.hpp&gt;\n#include &lt;iostream&gt;\n\n#using &lt;mscorlib.dll&gt;\n\nusing namespace System;\nusing namespace msclr::interop;\n\ntypedef boost::signal&lt;void (void)&gt; ChangedSignal;\ntypedef boost::signal&lt;void (void)&gt;::slot_function_type ChangedSignalCB;\ntypedef boost::signals::connection Callback;\n\n\nclass Native\n{\npublic:\n\n void ChangeIt() \n {\n changed();\n }\n\n Callback RegisterCallback(ChangedSignalCB Subscriber)\n {\n return changed.connect(Subscriber);\n }\n\n void UnregisterCallback(Callback CB)\n {\n changed.disconnect(CB);\n }\n\nprivate:\n ChangedSignal changed;\n};\n\n\n\ndelegate void ChangeHandler(void);\n\n\npublic ref class Managed\n{\npublic:\n Managed(Native* Nat);\n ~Managed();\n void OnSomeEvent(void);\n\n event ChangeHandler^ OnChange;\n\nprivate:\n Native* native;\n Callback* callback;\n};\n\n\nvoid SomeEventProxy(gcroot&lt;Managed^&gt; This)\n{\n This-&gt;OnSomeEvent();\n}\n\n\nManaged::Managed(Native* Nat)\n : native(Nat)\n{\n native = Nat;\n callback = new Callback;\n *callback = native-&gt;RegisterCallback(boost::bind( SomeEventProxy, gcroot&lt;Managed^&gt;(this) ) );\n}\n\nManaged::~Managed()\n{\n native-&gt;UnregisterCallback(*callback);\n delete callback;\n}\n\nvoid Managed::OnSomeEvent(void)\n{\n OnChange();\n}\n\n\nvoid OnChanged(void)\n{\n Console::WriteLine(\"Got it!\");\n}\n\nint main(array&lt;System::String ^&gt; ^args)\n{\n Native* native = new Native;\n Managed^ managed = gcnew Managed(native);\n\n managed-&gt;OnChange += gcnew ChangeHandler(OnChanged);\n\n native-&gt;ChangeIt();\n\n delete native;\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 703105, "author": "yagni", "author_id": 80525, "author_profile": "https://Stackoverflow.com/users/80525", "pm_score": 4, "selected": true, "text": "<p>While your answer works, it exposes some of your implementation to the world (Managed::OnSomeEvent). If you don't want people to be able to raise the OnChange event willy-nilly by invoking OnSomeEvent(), you can update your Managed class as follows (based on <a href=\"http://msdn.microsoft.com/en-us/library/367eeye0(VS.80).aspx\" rel=\"noreferrer\">this advice</a>):</p>\n\n<pre><code>public delegate void ChangeHandler(void);\ntypedef void (__stdcall *ChangeCallback)(void);\n\npublic ref class Managed\n{\npublic:\n Managed(Native* Nat);\n ~Managed();\n\n event ChangeHandler^ OnChange;\n\nprivate:\n void OnSomeEvent(void);\n Native* native;\n Callback* callback;\n GCHandle gch;\n};\n\nManaged::Managed(Native* Nat)\n : native(Nat)\n{\n callback = new Callback;\n\n ChangeHandler^ handler = gcnew ChangeHandler( this, &amp;Managed::OnSomeEvent );\n gch = GCHandle::Alloc( handler );\n System::IntPtr ip = Marshal::GetFunctionPointerForDelegate( handler );\n ChangeCallback cbFunc = static_cast&lt;ChangeCallback&gt;( ip.ToPointer() );\n\n *callback = native-&gt;RegisterCallback(boost::bind&lt;void&gt;( cbFunc ) );\n}\n\nManaged::~Managed()\n{\n native-&gt;UnregisterCallback(*callback);\n delete callback;\n if ( gch.IsAllocated )\n {\n gch.Free();\n }\n}\n\nvoid Managed::OnSomeEvent(void)\n{\n OnChange();\n}\n</code></pre>\n\n<p>Note the alternate <code>bind&lt;R&gt;()</code> form that's used.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163757", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3114/" ]
I am using boost::signal in a native C++ class, and I now I am writing a .NET wrapper in C++/CLI, so that I can expose the native C++ callbacks as .NET events. When I try to use boost::bind to take the address of a member function of my managed class, I get compiler error 3374, saying I cannot take the address of a member function unless I am creating a delegate instance. Does anyone know how to bind a member function of a managed class using boost::bind? For clarification, the following sample code causes Compiler Error 3374: ``` #include <boost/bind.hpp> public ref class Managed { public: Managed() { boost::bind(&Managed::OnSomeEvent, this); } void OnSomeEvent(void) { } }; ```
While your answer works, it exposes some of your implementation to the world (Managed::OnSomeEvent). If you don't want people to be able to raise the OnChange event willy-nilly by invoking OnSomeEvent(), you can update your Managed class as follows (based on [this advice](http://msdn.microsoft.com/en-us/library/367eeye0(VS.80).aspx)): ``` public delegate void ChangeHandler(void); typedef void (__stdcall *ChangeCallback)(void); public ref class Managed { public: Managed(Native* Nat); ~Managed(); event ChangeHandler^ OnChange; private: void OnSomeEvent(void); Native* native; Callback* callback; GCHandle gch; }; Managed::Managed(Native* Nat) : native(Nat) { callback = new Callback; ChangeHandler^ handler = gcnew ChangeHandler( this, &Managed::OnSomeEvent ); gch = GCHandle::Alloc( handler ); System::IntPtr ip = Marshal::GetFunctionPointerForDelegate( handler ); ChangeCallback cbFunc = static_cast<ChangeCallback>( ip.ToPointer() ); *callback = native->RegisterCallback(boost::bind<void>( cbFunc ) ); } Managed::~Managed() { native->UnregisterCallback(*callback); delete callback; if ( gch.IsAllocated ) { gch.Free(); } } void Managed::OnSomeEvent(void) { OnChange(); } ``` Note the alternate `bind<R>()` form that's used.
163,760
<p>I have a Form being launched from another form on a different thread. Most of the time it works perfectly, but I get the below error from time to time. Can anyone help?</p> <pre><code>at System.Drawing.Bitmap..ctor(Int32 width, Int32 height, PixelFormat format) at System.Drawing.Bitmap..ctor(Int32 width, Int32 height) at System.Drawing.Icon.ToBitmap() at System.Windows.Forms.ThreadExceptionDialog..ctor(Exception t) at System.Windows.Forms.Application.ThreadContext.OnThreadException(Exception t) at System.Windows.Forms.Control.WndProcException(Exception e) at System.Windows.Forms.Control.ControlNativeWindow.OnThreadException(Exception e) at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG&amp; msg) at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData) at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context) at System.Windows.Forms.Form.ShowDialog(IWin32Window owner) at System.Windows.Forms.Form.ShowDialog() </code></pre>
[ { "answer_id": 163816, "author": "Vivek", "author_id": 7418, "author_profile": "https://Stackoverflow.com/users/7418", "pm_score": 0, "selected": false, "text": "<p>Can you elaborate what you are trying to do here?\nIf you are trying to show a Form from a different thread than the UI thread then refer to this question:\n<a href=\"https://stackoverflow.com/questions/160555/my-form-doesnt-properly-display-when-it-is-launched-from-another-thread\">My form doesn&#39;t properly display when it is launched from another thread</a></p>\n" }, { "answer_id": 167171, "author": "joek1975", "author_id": 4770, "author_profile": "https://Stackoverflow.com/users/4770", "pm_score": 0, "selected": false, "text": "<p>The application is an Explorer-Type customer management system. An account form is launched from the \"Main\" explorer form on a separate background thread. We do this because the user needs to be able to have multiple accounts open at the same time.</p>\n\n<p>We launch the form using this code:</p>\n\n<pre><code>Thread = New Thread(AddressOf ShowForm)\nThread.SetApartmentState(ApartmentState.STA)\nThread.IsBackground = True\n</code></pre>\n" }, { "answer_id": 175658, "author": "John Rudy", "author_id": 14048, "author_profile": "https://Stackoverflow.com/users/14048", "pm_score": 2, "selected": true, "text": "<p>The user has to be able to see multiple open accounts simultaneously, right? So you need multiple instances of a form?</p>\n\n<p>Unless I'm misreading something, I don't think you need threads for this scenario, and I think you are just introducing yourself to a world of hurt (like these exceptions) as a result.</p>\n\n<p>Assuming your account form is called AccountForm, I'd do this instead:</p>\n\n<pre><code>Dim acctForm As New AccountForm()\nacctForm.Show()\n</code></pre>\n\n<p>(Of course you'll have your own logic for that ... ) I might even put it in the <code>ShowForm</code> method so that I could just update my caller thusly:</p>\n\n<pre><code>ShowForm()\n</code></pre>\n\n<p>And be done. Now all of this assumes that you've encapsulated the AccountForm nicely so that each instance has its own data, and they don't share anything between instances.</p>\n\n<p>Using threads for this is not only overkill, but likely to introduce bugs like the exception at the top. And my experience in debugging multi-threaded WinForms apps has shown that these bugs are often very difficult to replicate, and extremely tricky to find and fix. Oftentimes, the best fix is to not multithread unless you absolutely, positively <strong>have</strong> to.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4770/" ]
I have a Form being launched from another form on a different thread. Most of the time it works perfectly, but I get the below error from time to time. Can anyone help? ``` at System.Drawing.Bitmap..ctor(Int32 width, Int32 height, PixelFormat format) at System.Drawing.Bitmap..ctor(Int32 width, Int32 height) at System.Drawing.Icon.ToBitmap() at System.Windows.Forms.ThreadExceptionDialog..ctor(Exception t) at System.Windows.Forms.Application.ThreadContext.OnThreadException(Exception t) at System.Windows.Forms.Control.WndProcException(Exception e) at System.Windows.Forms.Control.ControlNativeWindow.OnThreadException(Exception e) at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg) at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData) at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context) at System.Windows.Forms.Form.ShowDialog(IWin32Window owner) at System.Windows.Forms.Form.ShowDialog() ```
The user has to be able to see multiple open accounts simultaneously, right? So you need multiple instances of a form? Unless I'm misreading something, I don't think you need threads for this scenario, and I think you are just introducing yourself to a world of hurt (like these exceptions) as a result. Assuming your account form is called AccountForm, I'd do this instead: ``` Dim acctForm As New AccountForm() acctForm.Show() ``` (Of course you'll have your own logic for that ... ) I might even put it in the `ShowForm` method so that I could just update my caller thusly: ``` ShowForm() ``` And be done. Now all of this assumes that you've encapsulated the AccountForm nicely so that each instance has its own data, and they don't share anything between instances. Using threads for this is not only overkill, but likely to introduce bugs like the exception at the top. And my experience in debugging multi-threaded WinForms apps has shown that these bugs are often very difficult to replicate, and extremely tricky to find and fix. Oftentimes, the best fix is to not multithread unless you absolutely, positively **have** to.
163,761
<p>I have a hidden embedded QuickTime object on my page that I'm trying to control via JavaScript, but it's not working. The object looks like this:</p> <pre><code>&lt;object id="myPlayer" data="" type="audio/mpeg" pluginspage="http://www.apple.com/quicktime/download" width="0" height="0"&gt; &lt;param name="autoPlay" value="false" /&gt; &lt;param name="controller" value="false" /&gt; &lt;param name="enablejavascript" value="true" /&gt; &lt;/object&gt; </code></pre> <p>There is nothing in the data parameter because at render time, I don't know the URL that's going to be loaded. I set it like this:</p> <pre><code>var player = document.getElementById("myPlayer"); player.SetURL(url); </code></pre> <p>The audio will later be played back with:</p> <pre><code>player.Play(); </code></pre> <p>Firefox 3.0.3 produces no error in the JavaScript console, but no playback occurs when <code>Play()</code> is called. Safari 3.0.4 produces the following error in the console:</p> <pre><code>"Value undefined (result of expression player.SetURL) is not object." </code></pre> <p>Internet Explorer 7.0.5730.11 gives the following extremely helpful error message:</p> <pre><code>"Unspecified error." </code></pre> <p>I have QuickTime version 7.4 installed on my machine. <a href="http://developer.apple.com/documentation/QuickTime/Conceptual/QTScripting_JavaScript/bQTScripting_JavaScri_Document/chapter_1000_section_5.html" rel="nofollow noreferrer">Apple's documentation</a> says that <code>SetURL()</code> is correct, so why does it not work?</p>
[ { "answer_id": 429916, "author": "Kev", "author_id": 16777, "author_profile": "https://Stackoverflow.com/users/16777", "pm_score": 0, "selected": false, "text": "<p>I don't know the QuickTime API, but this might be worth a shot:</p>\n\n<pre><code>player.attributes.getNamedItem('data').value = 'http://yoururlhere';\n</code></pre>\n" }, { "answer_id": 429920, "author": "Kev", "author_id": 16777, "author_profile": "https://Stackoverflow.com/users/16777", "pm_score": 0, "selected": false, "text": "<p>The page you linked to doesn't mention a 'data' attribute. They have an EMBED and PARAM within an OBJECT, with the EMBED's 'src' attribute having the url, but I don't see an EMBED in what you posted.</p>\n" }, { "answer_id": 452830, "author": "mczepiel", "author_id": 44780, "author_profile": "https://Stackoverflow.com/users/44780", "pm_score": 2, "selected": true, "text": "<p>Try giving the object element some width and height (1px by 1px) and make it visible within the viewport when you attempt to communicate with the plugin via JavaScript.</p>\n\n<p>I've noticed that if the plugin area is not visible on screen it's unresponsive to JS commands.</p>\n\n<p>This might explain why this isn't working for you in IE. </p>\n\n<p>Safari and Opera should work, but FireFox will definitely require the Netscape style embed element, and really you should provide both. Additionally, once you have both, you need to ascertain which element (the object versus the embed) to address in which browser.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163761", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4287/" ]
I have a hidden embedded QuickTime object on my page that I'm trying to control via JavaScript, but it's not working. The object looks like this: ``` <object id="myPlayer" data="" type="audio/mpeg" pluginspage="http://www.apple.com/quicktime/download" width="0" height="0"> <param name="autoPlay" value="false" /> <param name="controller" value="false" /> <param name="enablejavascript" value="true" /> </object> ``` There is nothing in the data parameter because at render time, I don't know the URL that's going to be loaded. I set it like this: ``` var player = document.getElementById("myPlayer"); player.SetURL(url); ``` The audio will later be played back with: ``` player.Play(); ``` Firefox 3.0.3 produces no error in the JavaScript console, but no playback occurs when `Play()` is called. Safari 3.0.4 produces the following error in the console: ``` "Value undefined (result of expression player.SetURL) is not object." ``` Internet Explorer 7.0.5730.11 gives the following extremely helpful error message: ``` "Unspecified error." ``` I have QuickTime version 7.4 installed on my machine. [Apple's documentation](http://developer.apple.com/documentation/QuickTime/Conceptual/QTScripting_JavaScript/bQTScripting_JavaScri_Document/chapter_1000_section_5.html) says that `SetURL()` is correct, so why does it not work?
Try giving the object element some width and height (1px by 1px) and make it visible within the viewport when you attempt to communicate with the plugin via JavaScript. I've noticed that if the plugin area is not visible on screen it's unresponsive to JS commands. This might explain why this isn't working for you in IE. Safari and Opera should work, but FireFox will definitely require the Netscape style embed element, and really you should provide both. Additionally, once you have both, you need to ascertain which element (the object versus the embed) to address in which browser.
163,796
<p>I have a lot of XML files and I'd like to generate a report from them. The report should provide information such as:</p> <pre><code>root 100% a*1 90% b*1 80% c*5 40% </code></pre> <p>meaning that all documents have a root element, 90% have one <strong>a</strong> element in the root, 80% have one <strong>b</strong> element in the root, 40% have 5 <strong>c</strong> elements in <strong>b</strong>.</p> <p>If for example some documents have 4 <strong>c</strong> elements, some 5 and some 6, it should say something like: </p> <pre><code>c*4.3 4 6 40% </code></pre> <p>meaning that 40% have between 4 and 6 <strong>c</strong> elements there, and the average is 4.3.</p> <p>I am looking for free software, if it doesn't exist I'll write it. I was about to do it, but I thought about checking it. I may not be the first one to have to analyze and get an structural overview of thousand of XML files.</p>
[ { "answer_id": 164830, "author": "JeniT", "author_id": 6739, "author_profile": "https://Stackoverflow.com/users/6739", "pm_score": 4, "selected": false, "text": "<p>Here's an XSLT 2.0 method.</p>\n\n<p>Assuming that <code>$docs</code> contains a sequence of document nodes that you want to scan, you want to create one line for each element that appears in the documents. You can use <code>&lt;xsl:for-each-group&gt;</code> to do that:</p>\n\n<pre><code>&lt;xsl:for-each-group select=\"$docs//*\" group-by=\"name()\"&gt;\n &lt;xsl:sort select=\"current-group-key()\" /&gt;\n &lt;xsl:variable name=\"name\" as=\"xs:string\" select=\"current-grouping-key()\" /&gt;\n &lt;xsl:value-of select=\"$name\" /&gt;\n ...\n&lt;/xsl:for-each-group&gt;\n</code></pre>\n\n<p>Then you want to find out the stats for that element amongst the documents. First, find the documents have an element of that name in them:</p>\n\n<pre><code>&lt;xsl:variable name=\"docs-with\" as=\"document-node()+\"\n select=\"$docs[//*[name() = $name]\" /&gt;\n</code></pre>\n\n<p>Second, you need a sequence of the number of elements of that name in each of the documents:</p>\n\n<pre><code>&lt;xsl:variable name=\"elem-counts\" as=\"xs:integer+\"\n select=\"$docs-with/count(//*[name() = $name])\" /&gt;\n</code></pre>\n\n<p>And now you can do the calculations. Average, minimum and maximum can be calculated with the <code>avg()</code>, <code>min()</code> and <code>max()</code> functions. The percentage is simply the number of documents that contain the element divided by the total number of documents, formatted.</p>\n\n<p>Putting that together:</p>\n\n<pre><code>&lt;xsl:for-each-group select=\"$docs//*\" group-by=\"name()\"&gt;\n &lt;xsl:sort select=\"current-group-key()\" /&gt;\n &lt;xsl:variable name=\"name\" as=\"xs:string\" select=\"current-grouping-key()\" /&gt;\n &lt;xsl:variable name=\"docs-with\" as=\"document-node()+\"\n select=\"$docs[//*[name() = $name]\" /&gt;\n &lt;xsl:variable name=\"elem-counts\" as=\"xs:integer+\"\n select=\"$docs-with/count(//*[name() = $name])\" /&gt;\n &lt;xsl:value-of select=\"$name\" /&gt;\n &lt;xsl:text&gt;* &lt;/xsl:text&gt;\n &lt;xsl:value-of select=\"format-number(avg($elem-counts), '#,##0.0')\" /&gt;\n &lt;xsl:text&gt; &lt;/xsl:text&gt;\n &lt;xsl:value-of select=\"format-number(min($elem-counts), '#,##0')\" /&gt;\n &lt;xsl:text&gt; &lt;/xsl:text&gt;\n &lt;xsl:value-of select=\"format-number(max($elem-counts), '#,##0')\" /&gt;\n &lt;xsl:text&gt; &lt;/xsl:text&gt;\n &lt;xsl:value-of select=\"format-number((count($docs-with) div count($docs)) * 100, '#0')\" /&gt;\n &lt;xsl:text&gt;%&lt;/xsl:text&gt;\n &lt;xsl:text&gt;&amp;#xA;&lt;/xsl:text&gt;\n&lt;/xsl:for-each-group&gt;\n</code></pre>\n\n<p>What I haven't done here is indented the lines according to the depth of the element. I've just ordered the elements alphabetically to give you statistics. Two reasons for that: first, it's significantly harder (like too involved to write here) to display the element statistics in some kind of structure that reflects how they appear in the documents, not least because different documents may have different structures. Second, in many markup languages, the precise structure of the documents can't be known (because, for example, sections can nest within sections to any depth).</p>\n\n<p>I hope it's useful none the less.</p>\n\n<p>UPDATE:</p>\n\n<p>Need the XSLT wrapper and some instructions for running XSLT? OK. First, get your hands on <a href=\"http://saxon.sourceforge.net/\" rel=\"nofollow noreferrer\">Saxon 9B</a>.</p>\n\n<p>You'll need to put all the files you want to analyse in a directory. Saxon allows you to access all the files in that directory (or its subdirectories) using a collection using a <a href=\"http://www.saxonica.com/documentation/sourcedocs/collections.html\" rel=\"nofollow noreferrer\">special URI syntax</a>. It's worth having a look at that syntax if you want to search recursively or filter the files that you're looking at by their filename.</p>\n\n<p>Now the full XSLT:</p>\n\n<pre><code>&lt;xsl:stylesheet version=\"2.0\"\n xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"\n xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"\n exclude-result-prefixes=\"xs\"&gt;\n\n&lt;xsl:param name=\"dir\" as=\"xs:string\"\n select=\"'file:///path/to/default/directory?select=*.xml'\" /&gt;\n\n&lt;xsl:output method=\"text\" /&gt;\n\n&lt;xsl:variable name=\"docs\" as=\"document-node()*\"\n select=\"collection($dir)\" /&gt;\n\n&lt;xsl:template name=\"main\"&gt;\n &lt;xsl:for-each-group select=\"$docs//*\" group-by=\"name()\"&gt;\n &lt;xsl:sort select=\"current-group-key()\" /&gt;\n &lt;xsl:variable name=\"name\" as=\"xs:string\" select=\"current-grouping-key()\" /&gt;\n &lt;xsl:variable name=\"docs-with\" as=\"document-node()+\"\n select=\"$docs[//*[name() = $name]\" /&gt;\n &lt;xsl:variable name=\"elem-counts\" as=\"xs:integer+\"\n select=\"$docs-with/count(//*[name() = $name])\" /&gt;\n &lt;xsl:value-of select=\"$name\" /&gt;\n &lt;xsl:text&gt;* &lt;/xsl:text&gt;\n &lt;xsl:value-of select=\"format-number(avg($elem-counts), '#,##0.0')\" /&gt;\n &lt;xsl:text&gt; &lt;/xsl:text&gt;\n &lt;xsl:value-of select=\"format-number(min($elem-counts), '#,##0')\" /&gt;\n &lt;xsl:text&gt; &lt;/xsl:text&gt;\n &lt;xsl:value-of select=\"format-number(max($elem-counts), '#,##0')\" /&gt;\n &lt;xsl:text&gt; &lt;/xsl:text&gt;\n &lt;xsl:value-of select=\"format-number((count($docs-with) div count($docs)) * 100, '#0')\" /&gt;\n &lt;xsl:text&gt;%&lt;/xsl:text&gt;\n &lt;xsl:text&gt;&amp;#xA;&lt;/xsl:text&gt;\n &lt;/xsl:for-each-group&gt;\n&lt;/xsl:template&gt; \n\n&lt;/xsl:stylesheet&gt;\n</code></pre>\n\n<p>And to run it you would do something like:</p>\n\n<pre>\n> java -jar path/to/saxon.jar -it:main -o:report.txt dir=file:///path/to/your/directory?select=*.xml\n</pre>\n\n<p>This tells Saxon to start the process with the template named <code>main</code>, to set the <code>dir</code> parameter to <code>file:///path/to/your/directory?select=*.xml</code> and send the output to <code>report.txt</code>.</p>\n" }, { "answer_id": 171334, "author": "Mads Hansen", "author_id": 14419, "author_profile": "https://Stackoverflow.com/users/14419", "pm_score": 2, "selected": false, "text": "<p>Check out <a href=\"https://web.archive.org/web/20140928025041/http://simile.mit.edu:80/wiki/Gadget\" rel=\"nofollow noreferrer\"><strong>Gadget</strong></a></p>\n\n<p><a href=\"https://i.stack.imgur.com/SAMNI.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/SAMNI.png\" alt=\"alt text\"></a><br>\n<sub>(source: <a href=\"http://web.archive.org/web/20131225224913/http://simile.mit.edu/mediawiki/images/0/0f/Gadget-screenshot-1.png\" rel=\"nofollow noreferrer\">mit.edu</a>)</sub> </p>\n" }, { "answer_id": 171340, "author": "jeremy", "author_id": 24530, "author_profile": "https://Stackoverflow.com/users/24530", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://www.crummy.com/software/BeautifulSoup/documentation.html\" rel=\"nofollow noreferrer\">Beautiful Soup</a> makes parsing XML trivial in python. </p>\n" }, { "answer_id": 172142, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 0, "selected": false, "text": "<p>[community post, here: no karma involved;) ]<br>\nI propose a <strong><a href=\"https://stackoverflow.com/questions/172184\">code-challenge</a></strong> here:</p>\n\n<p><strong>parse all xml find in xmlfiles.com/examples and try to come up with the following output:</strong></p>\n\n<pre><code>Analyzing plant_catalog.xml: \nAnalyzing note.xml: \nAnalyzing portfolio.xml: \nAnalyzing note_ex_dtd.xml: \nAnalyzing home.xml: \nAnalyzing simple.xml: \nAnalyzing cd_catalog.xml: \nAnalyzing portfolio_xsl.xml: \nAnalyzing note_in_dtd.xml: \nStatistical Elements Analysis of 9 xml documents with 34 elements\nCATALOG*2 22%\n CD*26 50%\n ARTIST*26 100%\n COMPANY*26 100%\n COUNTRY*26 100%\n PRICE*26 100%\n TITLE*26 100%\n YEAR*26 100%\n PLANT*36 50%\n AVAILABILITY*36 100%\n BOTANICAL*36 100%\n COMMON*36 100%\n LIGHT*36 100%\n PRICE*36 100%\n ZONE*36 100%\nbreakfast-menu*1 11%\n food*5 100%\n calories*5 100%\n description*5 100%\n name*5 100%\n price*5 100%\nnote*3 33%\n body*1 100%\n from*1 100%\n heading*1 100%\n to*1 100%\npage*1 11%\n para*1 100%\n title*1 100%\nportfolio*2 22%\n stock*2 100%\n name*2 100%\n price*2 100%\n symbol*2 100%\n</code></pre>\n" }, { "answer_id": 172149, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 0, "selected": false, "text": "<p>Here is a possible solution in ruby to this <a href=\"https://stackoverflow.com/questions/172184\">code-challenge</a>...<br>\nSince it is my very first ruby program, I am sure it is quite terribly coded, but at least it may answer J. Pablo Fernandez's question.</p>\n\n<p>Copy-paste it in a '.rb file and calls ruby on it. If you have an Internet connection, it will work ;)</p>\n\n<pre><code>require \"rexml/document\"\nrequire \"net/http\"\nrequire \"iconv\"\ninclude REXML\nclass NodeAnalyzer\n @@fullPathToFilesToSubNodesNamesToCardinalities = Hash.new()\n @@fullPathsToFiles = Hash.new() #list of files in which a fullPath node is detected\n @@fullPaths = Array.new # all fullpaths sorted alphabetically\n attr_reader :name, :father, :subNodesAnalyzers, :indent, :file, :subNodesNamesToCardinalities\n def initialize(aName=\"\", aFather=nil, aFile=\"\")\n @name = aName; @father = aFather; @subNodesAnalyzers = []; @file = aFile\n @subNodesNamesToCardinalities = Hash.new(0)\n if aFather &amp;&amp; !aFather.name.empty? then @indent = \" \" else @indent = \"\" end\n if aFather\n @indent = @father.indent + self.indent\n @father.subNodesAnalyzers &lt;&lt; self\n @father.updateSubNodesNamesToCardinalities(@name)\n end\n end\n @@nodesRootAnalyzer = NodeAnalyzer.new\n def NodeAnalyzer.nodesRootAnalyzer\n return @@nodesRootAnalyzer\n end\n def updateSubNodesNamesToCardinalities(aSubNodeName)\n aSubNodeCardinality = @subNodesNamesToCardinalities[aSubNodeName]\n @subNodesNamesToCardinalities[aSubNodeName] = aSubNodeCardinality + 1\n end\n def NodeAnalyzer.recordNode(aNodeAnalyzer)\n if aNodeAnalyzer.fullNodePath.empty? == false\n if @@fullPaths.include?(aNodeAnalyzer.fullNodePath) == false then @@fullPaths &lt;&lt; aNodeAnalyzer.fullNodePath end\n # record a full path in regard to its xml file (records it only one for a given xlm file)\n someFiles = @@fullPathsToFiles[aNodeAnalyzer.fullNodePath]\n if someFiles == nil \n someFiles = Array.new(); @@fullPathsToFiles[aNodeAnalyzer.fullNodePath] = someFiles; \n end\n if !someFiles.include?(aNodeAnalyzer.file) then someFiles &lt;&lt; aNodeAnalyzer.file end\n end\n #record cardinalties of sub nodes for a given xml file\n someFilesToSubNodesNamesToCardinalities = @@fullPathToFilesToSubNodesNamesToCardinalities[aNodeAnalyzer.fullNodePath]\n if someFilesToSubNodesNamesToCardinalities == nil \n someFilesToSubNodesNamesToCardinalities = Hash.new(); @@fullPathToFilesToSubNodesNamesToCardinalities[aNodeAnalyzer.fullNodePath] = someFilesToSubNodesNamesToCardinalities ; \n end\n someSubNodesNamesToCardinalities = someFilesToSubNodesNamesToCardinalities[aNodeAnalyzer.file]\n if someSubNodesNamesToCardinalities == nil\n someSubNodesNamesToCardinalities = Hash.new(0); someFilesToSubNodesNamesToCardinalities[aNodeAnalyzer.file] = someSubNodesNamesToCardinalities\n someSubNodesNamesToCardinalities.update(aNodeAnalyzer.subNodesNamesToCardinalities)\n else\n aNodeAnalyzer.subNodesNamesToCardinalities.each() do |aSubNodeName, aCardinality|\n someSubNodesNamesToCardinalities[aSubNodeName] = someSubNodesNamesToCardinalities[aSubNodeName] + aCardinality\n end\n end \n #puts \"someSubNodesNamesToCardinalities for #{aNodeAnalyzer.fullNodePath}: #{someSubNodesNamesToCardinalities}\"\n end\n def file\n #if @file.empty? then @father.file else return @file end\n if @file.empty? then if @father != nil then return @father.file else return '' end else return @file end\n end\n def fullNodePath\n if @father == nil then return '' elsif @father.name.empty? then return @name else return @father.fullNodePath+\"/\"+@name end\n end\n def to_s\n s = \"\"\n if @name.empty? == false\n s = \"#{@indent}#{self.fullNodePath} [#{self.file}]\\n\"\n end\n @subNodesAnalyzers.each() do |aSubNodeAnalyzer|\n s = s + aSubNodeAnalyzer.to_s\n end\n return s\n end\n def NodeAnalyzer.displayStats(aFullPath=\"\")\n s = \"\";\n if aFullPath.empty? then s = \"Statistical Elements Analysis of #{@@nodesRootAnalyzer.subNodesAnalyzers.length} xml documents with #{@@fullPaths.length} elements\\n\" end\n someFullPaths = @@fullPaths.sort\n someFullPaths.each do |aFullPath|\n s = s + getIndentedNameFromFullPath(aFullPath) + \"*\"\n nbFilesWithThatFullPath = getNbFilesWithThatFullPath(aFullPath);\n aParentFullPath = getParentFullPath(aFullPath)\n nbFilesWithParentFullPath = getNbFilesWithThatFullPath(aParentFullPath);\n aNameFromFullPath = getNameFromFullPath(aFullPath)\n someFilesToSubNodesNamesToCardinalities = @@fullPathToFilesToSubNodesNamesToCardinalities[aParentFullPath]\n someCardinalities = Array.new()\n someFilesToSubNodesNamesToCardinalities.each() do |aFile, someSubNodesNamesToCardinalities|\n aCardinality = someSubNodesNamesToCardinalities[aNameFromFullPath]\n if aCardinality &gt; 0 &amp;&amp; someCardinalities.include?(aCardinality) == false then someCardinalities &lt;&lt; aCardinality end\n end\n if someCardinalities.length == 1\n s = s + someCardinalities.to_s + \" \"\n else\n anAvg = someCardinalities.inject(0) {|sum,value| Float(sum) + Float(value) } / Float(someCardinalities.length)\n s = s + sprintf('%.1f', anAvg) + \" \" + someCardinalities.min.to_s + \"...\" + someCardinalities.max.to_s + \" \"\n end\n s = s + sprintf('%d', Float(nbFilesWithThatFullPath) / Float(nbFilesWithParentFullPath) * 100) + '%'\n s = s + \"\\n\"\n end\n return s\n end\n def NodeAnalyzer.getNameFromFullPath(aFullPath)\n if aFullPath.include?(\"/\") == false then return aFullPath end\n aNameFromFullPath = aFullPath.dup\n aNameFromFullPath[/^(?:[^\\/]+\\/)+/] = \"\"\n return aNameFromFullPath\n end\n def NodeAnalyzer.getIndentedNameFromFullPath(aFullPath)\n if aFullPath.include?(\"/\") == false then return aFullPath end\n anIndentedNameFromFullPath = aFullPath.dup\n anIndentedNameFromFullPath = anIndentedNameFromFullPath.gsub(/[^\\/]+\\//, \" \")\n return anIndentedNameFromFullPath\n end\n def NodeAnalyzer.getParentFullPath(aFullPath)\n if aFullPath.include?(\"/\") == false then return \"\" end\n aParentFullPath = aFullPath.dup\n aParentFullPath[/\\/[^\\/]+$/] = \"\"\n return aParentFullPath\n end\n def NodeAnalyzer.getNbFilesWithThatFullPath(aFullPath)\n if aFullPath.empty? \n return @@nodesRootAnalyzer.subNodesAnalyzers.length\n else\n return @@fullPathsToFiles[aFullPath].length;\n end\n end\nend\nclass REXML::Document\n def analyze(node, aFatherNodeAnalyzer, aFile=\"\")\n anNodeAnalyzer = NodeAnalyzer.new(node.name, aFatherNodeAnalyzer, aFile)\n node.elements.each() do |aSubNode| analyze(aSubNode, anNodeAnalyzer) end\n NodeAnalyzer.recordNode(anNodeAnalyzer)\n end\nend\n\nbegin\n anXmlFilesDirectory = \"xmlfiles.com/examples/\"\n anXmlFilesRegExp = Regexp.new(\"http:\\/\\/\" + anXmlFilesDirectory + \"([^\\\"]*)\")\n a = Net::HTTP.get(URI(\"http://www.google.fr/search?q=site:\"+anXmlFilesDirectory+\"+filetype:xml&amp;num=100&amp;as_qdr=all&amp;filter=0\"))\n someXmlFiles = a.scan(anXmlFilesRegExp)\n someXmlFiles.each() do |anXmlFile|\n anXmlFileContent = Net::HTTP.get(URI(\"http://\" + anXmlFilesDirectory + anXmlFile.to_s))\n anUTF8XmlFileContent = Iconv.conv(\"ISO-8859-1//ignore\", 'UTF-8', anXmlFileContent).gsub(/\\s+encoding\\s*=\\s*\\\"[^\\\"]+\\\"\\s*\\?/,\"?\")\n anXmlDocument = Document.new(anUTF8XmlFileContent)\n puts \"Analyzing #{anXmlFile}: #{NodeAnalyzer.nodesRootAnalyzer.name}\"\n anXmlDocument.analyze(anXmlDocument.root,NodeAnalyzer.nodesRootAnalyzer, anXmlFile.to_s)\n end\n NodeAnalyzer.recordNode(NodeAnalyzer.nodesRootAnalyzer)\n puts NodeAnalyzer.displayStats\nend\n</code></pre>\n" }, { "answer_id": 172201, "author": "David Robbins", "author_id": 19799, "author_profile": "https://Stackoverflow.com/users/19799", "pm_score": 0, "selected": false, "text": "<p>Go with JeniT's answer - she's one of the first XSLT guru's I started learning from back on '02. To really appreciate the power of XML you should work with XPath and XSLT and learn to manipulate the nodes.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163796", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6068/" ]
I have a lot of XML files and I'd like to generate a report from them. The report should provide information such as: ``` root 100% a*1 90% b*1 80% c*5 40% ``` meaning that all documents have a root element, 90% have one **a** element in the root, 80% have one **b** element in the root, 40% have 5 **c** elements in **b**. If for example some documents have 4 **c** elements, some 5 and some 6, it should say something like: ``` c*4.3 4 6 40% ``` meaning that 40% have between 4 and 6 **c** elements there, and the average is 4.3. I am looking for free software, if it doesn't exist I'll write it. I was about to do it, but I thought about checking it. I may not be the first one to have to analyze and get an structural overview of thousand of XML files.
Here's an XSLT 2.0 method. Assuming that `$docs` contains a sequence of document nodes that you want to scan, you want to create one line for each element that appears in the documents. You can use `<xsl:for-each-group>` to do that: ``` <xsl:for-each-group select="$docs//*" group-by="name()"> <xsl:sort select="current-group-key()" /> <xsl:variable name="name" as="xs:string" select="current-grouping-key()" /> <xsl:value-of select="$name" /> ... </xsl:for-each-group> ``` Then you want to find out the stats for that element amongst the documents. First, find the documents have an element of that name in them: ``` <xsl:variable name="docs-with" as="document-node()+" select="$docs[//*[name() = $name]" /> ``` Second, you need a sequence of the number of elements of that name in each of the documents: ``` <xsl:variable name="elem-counts" as="xs:integer+" select="$docs-with/count(//*[name() = $name])" /> ``` And now you can do the calculations. Average, minimum and maximum can be calculated with the `avg()`, `min()` and `max()` functions. The percentage is simply the number of documents that contain the element divided by the total number of documents, formatted. Putting that together: ``` <xsl:for-each-group select="$docs//*" group-by="name()"> <xsl:sort select="current-group-key()" /> <xsl:variable name="name" as="xs:string" select="current-grouping-key()" /> <xsl:variable name="docs-with" as="document-node()+" select="$docs[//*[name() = $name]" /> <xsl:variable name="elem-counts" as="xs:integer+" select="$docs-with/count(//*[name() = $name])" /> <xsl:value-of select="$name" /> <xsl:text>* </xsl:text> <xsl:value-of select="format-number(avg($elem-counts), '#,##0.0')" /> <xsl:text> </xsl:text> <xsl:value-of select="format-number(min($elem-counts), '#,##0')" /> <xsl:text> </xsl:text> <xsl:value-of select="format-number(max($elem-counts), '#,##0')" /> <xsl:text> </xsl:text> <xsl:value-of select="format-number((count($docs-with) div count($docs)) * 100, '#0')" /> <xsl:text>%</xsl:text> <xsl:text>&#xA;</xsl:text> </xsl:for-each-group> ``` What I haven't done here is indented the lines according to the depth of the element. I've just ordered the elements alphabetically to give you statistics. Two reasons for that: first, it's significantly harder (like too involved to write here) to display the element statistics in some kind of structure that reflects how they appear in the documents, not least because different documents may have different structures. Second, in many markup languages, the precise structure of the documents can't be known (because, for example, sections can nest within sections to any depth). I hope it's useful none the less. UPDATE: Need the XSLT wrapper and some instructions for running XSLT? OK. First, get your hands on [Saxon 9B](http://saxon.sourceforge.net/). You'll need to put all the files you want to analyse in a directory. Saxon allows you to access all the files in that directory (or its subdirectories) using a collection using a [special URI syntax](http://www.saxonica.com/documentation/sourcedocs/collections.html). It's worth having a look at that syntax if you want to search recursively or filter the files that you're looking at by their filename. Now the full XSLT: ``` <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="xs"> <xsl:param name="dir" as="xs:string" select="'file:///path/to/default/directory?select=*.xml'" /> <xsl:output method="text" /> <xsl:variable name="docs" as="document-node()*" select="collection($dir)" /> <xsl:template name="main"> <xsl:for-each-group select="$docs//*" group-by="name()"> <xsl:sort select="current-group-key()" /> <xsl:variable name="name" as="xs:string" select="current-grouping-key()" /> <xsl:variable name="docs-with" as="document-node()+" select="$docs[//*[name() = $name]" /> <xsl:variable name="elem-counts" as="xs:integer+" select="$docs-with/count(//*[name() = $name])" /> <xsl:value-of select="$name" /> <xsl:text>* </xsl:text> <xsl:value-of select="format-number(avg($elem-counts), '#,##0.0')" /> <xsl:text> </xsl:text> <xsl:value-of select="format-number(min($elem-counts), '#,##0')" /> <xsl:text> </xsl:text> <xsl:value-of select="format-number(max($elem-counts), '#,##0')" /> <xsl:text> </xsl:text> <xsl:value-of select="format-number((count($docs-with) div count($docs)) * 100, '#0')" /> <xsl:text>%</xsl:text> <xsl:text>&#xA;</xsl:text> </xsl:for-each-group> </xsl:template> </xsl:stylesheet> ``` And to run it you would do something like: ``` > java -jar path/to/saxon.jar -it:main -o:report.txt dir=file:///path/to/your/directory?select=*.xml ``` This tells Saxon to start the process with the template named `main`, to set the `dir` parameter to `file:///path/to/your/directory?select=*.xml` and send the output to `report.txt`.
163,803
<p>I would like to override the use of the standard app.config by passing a command line parameter. How do I change the default application configuration file so that when I access ConfigurationManager.AppSettings I am accessing the config file specified on the command line?</p> <p>Edit:</p> <p>It turns out that the correct way to load a config file that is different than the name of the EXE plus .config is to use OpenMappedExeConfiguration. E.g. </p> <pre><code>ExeConfigurationFileMap configFile = new ExeConfigurationFileMap(); configFile.ExeConfigFilename = Path.Combine(Environment.CurrentDirectory, "Shell2.exe.config"); currentConfiguration = ConfigurationManager.OpenMappedExeConfiguration(configFile,ConfigurationUserLevel.None); </code></pre> <p>This partially works. I can see all of the keys in the appSettings section but all the values are null.</p>
[ { "answer_id": 163815, "author": "kenny", "author_id": 3225, "author_profile": "https://Stackoverflow.com/users/3225", "pm_score": 2, "selected": false, "text": "<p>A batch file that copies your desired configuration file to appname.exe.config and then runs the appname.exe.</p>\n" }, { "answer_id": 163829, "author": "Eric Schoonover", "author_id": 3957, "author_profile": "https://Stackoverflow.com/users/3957", "pm_score": 1, "selected": false, "text": "<p>This is not exactly what you are wanting... to redirect the actual <a href=\"http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.aspx\" rel=\"nofollow noreferrer\"><code>ConfigurationManager</code></a> static object to point at a different path. But I think it is the right solution to your problem. Check out the <a href=\"http://msdn.microsoft.com/en-us/library/ms224437.aspx\" rel=\"nofollow noreferrer\"><code>OpenExeConfiguration</code></a> method on the <a href=\"http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.aspx\" rel=\"nofollow noreferrer\"><code>ConfigurationManager</code></a> class.</p>\n\n<p>If the above method is not what you are looking for I think it would also be worth taking a look at using the <a href=\"http://msdn.microsoft.com/en-us/library/microsoft.practices.enterpriselibrary.common.configuration.aspx\" rel=\"nofollow noreferrer\">Configuration capabilities</a> of the Enterprise Library framework (developed and maintained by the Microsoft Patterns &amp; Practices team).</p>\n\n<p>Specifically take a look at the <a href=\"http://msdn.microsoft.com/en-us/library/microsoft.practices.enterpriselibrary.common.configuration.fileconfigurationsource.fileconfigurationsource.aspx\" rel=\"nofollow noreferrer\"><code>FileConfigurationSource</code></a> class.</p>\n\n<p>Here is some code that highlights the use of the <code>FileConfigurationSource</code> from <a href=\"http://www.microsoft.com/downloads/details.aspx?familyid=90DE37E0-7B42-4044-99BE-F8ECFBBC5B65&amp;displaylang=en&amp;Hash=oOfFascYgZ%2bhSk6bMSD0ctdKGJBo3jL9XEtSJS2%2bCaArLTPNHRCuJ5k%2bnhgG8YkFIMOdGq74qSBJRzpD6zppRg%3d%3d\" rel=\"nofollow noreferrer\">Enterprise Library</a>, I believe this fully meets your goals. The only assembly you need from Ent Lib for this is <code>Microsoft.Practices.EnterpriseLibrary.Common.dll</code>.</p>\n\n<pre><code>static void Main(string[] args)\n{\n //read from current app.config as default\n AppSettingsSection ass = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).AppSettings;\n\n //if args[0] is a valid file path assume it's a config for this example and attempt to load\n if (args.Length &gt; 0 &amp;&amp; File.Exists(args[0]))\n {\n //using FileConfigurationSource from Enterprise Library\n FileConfigurationSource fcs = new FileConfigurationSource(args[0]);\n ass = (AppSettingsSection) fcs.GetSection(\"appSettings\");\n }\n\n //print value from configuration\n Console.WriteLine(ass.Settings[\"test\"].Value);\n Console.ReadLine(); //pause\n}\n</code></pre>\n" }, { "answer_id": 164119, "author": "Ron Savage", "author_id": 12476, "author_profile": "https://Stackoverflow.com/users/12476", "pm_score": 1, "selected": false, "text": "<p>I needed to do this for an app of mine as well, and dealing with the standard config objects turned into such a freakin' hassle for such a simple concept that I went this route:</p>\n\n<ol>\n<li>Keep multiple config files in XML format similar to app.config</li>\n<li>Load the specified config file into a <strong>DataSet</strong> (via .ReadXML), and use the <strong>DataTable</strong> with the config info in it as my <strong>Configuration object</strong>.</li>\n<li>So all my code just deals with the <strong>Configuration DataTable</strong> to retrieve values and not that craptastically obfuscated app config object.</li>\n</ol>\n\n<p>then I can pass in whatever config filename I need on the command line and if one isn't there - just load app.config into the <strong>DataSet</strong>.</p>\n\n<p>Jeezus it was sooo much simpler after that. :-)</p>\n\n<p>Ron</p>\n" }, { "answer_id": 164221, "author": "Darrel Miller", "author_id": 6819, "author_profile": "https://Stackoverflow.com/users/6819", "pm_score": 5, "selected": true, "text": "<p>So here is the code that actually allows me to actually access the appSettings section in a config file other than the default one.</p>\n\n<pre><code>ExeConfigurationFileMap configFile = new ExeConfigurationFileMap();\nconfigFile.ExeConfigFilename = Path.Combine(Environment.CurrentDirectory, \"Alternate.config\");\nConfiguration config = ConfigurationManager.OpenMappedExeConfiguration(configFile,ConfigurationUserLevel.None);\n\nAppSettingsSection section = (AppSettingsSection)config.GetSection(\"appSettings\");\nstring MySetting = section.Settings[\"MySetting\"].Value;\n</code></pre>\n" }, { "answer_id": 1091909, "author": "majkinetor", "author_id": 82660, "author_profile": "https://Stackoverflow.com/users/82660", "pm_score": 1, "selected": false, "text": "<p>This is the relevant part of the source for app that uses default config and accepts override via command line:</p>\n\n<p><strong>Get current or user config into the Config object</strong></p>\n\n<pre><code>Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);\nstring defCfgName = Environment.GetCommandLineArgs()[0] + \".config\";\n\nif (arg.Length != 0)\n{\n string ConfigFileName = arg[0];\n if (!File.Exists(ConfigFileName))\n Fatal(\"File doesn't exist: \" + ConfigFileName, -1); \n config = ConfigurationManager.OpenMappedExeConfiguration(new ExeConfigurationFileMap { ExeConfigFilename = ConfigFileName }, ConfigurationUserLevel.None);\n}\nelse if (!File.Exists(defCfgName)) Fatal(\"Default configuration file doesn't exist and no override is set.\" , -1);\n</code></pre>\n\n<p><strong>Use the config object</strong></p>\n\n<pre><code>AppSettingsSection s = (AppSettingsSection)config.GetSection(\"appSettings\");\nKeyValueConfigurationCollection a = s.Settings;\nConnectionString = a[\"ConnectionString\"].Value;\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6819/" ]
I would like to override the use of the standard app.config by passing a command line parameter. How do I change the default application configuration file so that when I access ConfigurationManager.AppSettings I am accessing the config file specified on the command line? Edit: It turns out that the correct way to load a config file that is different than the name of the EXE plus .config is to use OpenMappedExeConfiguration. E.g. ``` ExeConfigurationFileMap configFile = new ExeConfigurationFileMap(); configFile.ExeConfigFilename = Path.Combine(Environment.CurrentDirectory, "Shell2.exe.config"); currentConfiguration = ConfigurationManager.OpenMappedExeConfiguration(configFile,ConfigurationUserLevel.None); ``` This partially works. I can see all of the keys in the appSettings section but all the values are null.
So here is the code that actually allows me to actually access the appSettings section in a config file other than the default one. ``` ExeConfigurationFileMap configFile = new ExeConfigurationFileMap(); configFile.ExeConfigFilename = Path.Combine(Environment.CurrentDirectory, "Alternate.config"); Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFile,ConfigurationUserLevel.None); AppSettingsSection section = (AppSettingsSection)config.GetSection("appSettings"); string MySetting = section.Settings["MySetting"].Value; ```
163,809
<p>I'm looking for an example algorithm of smart pagination. By smart, what I mean is that I only want to show, for example, 2 adjacent pages to the current page, so instead of ending up with a ridiculously long page list, I truncate it.</p> <p>Here's a quick example to make it clearer... this is what I have now:</p> <pre><code>Pages: 1 2 3 4 [5] 6 7 8 9 10 11 </code></pre> <p>This is what I want to end up with:</p> <pre><code>Pages: ... 3 4 [5] 6 7 ... </code></pre> <p>(In this example, I'm only showing 2 adjacent pages to the current page)</p> <p>I'm implementing it in PHP/Mysql, and the "basic" pagination (no trucating) is already coded, I'm just looking for an example to optimize it... It can be an example in any language, as long as it gives me an idea as to how to implement it...</p>
[ { "answer_id": 163825, "author": "changelog", "author_id": 5646, "author_profile": "https://Stackoverflow.com/users/5646", "pm_score": 6, "selected": true, "text": "<p>Here is some code based on original code from <a href=\"https://www.strangerstudios.com/sandbox/pagination/diggstyle.php\" rel=\"nofollow noreferrer\">this very old link</a>. It uses markup compatible with Bootstrap's pagination component, and outputs page links like this:</p>\n<pre class=\"lang-none prettyprint-override\"><code>[1] 2 3 4 5 6 ... 100\n1 [2] 3 4 5 6 ... 100\n...\n1 2 ... 14 15 [16] 17 18 ... 100\n...\n1 2 ... 97 [98] 99 100\n</code></pre>\n<pre class=\"lang-php prettyprint-override\"><code>&lt;?php\n\n// How many adjacent pages should be shown on each side?\n$adjacents = 3;\n\n//how many items to show per page\n$limit = 5;\n\n// if no page var is given, default to 1.\n$page = (int)$_GET[&quot;page&quot;] ?? 1;\n\n//first item to display on this page\n$start = ($page - 1) * $limit;\n\n/* Get data. */\n$data = $db\n -&gt;query(&quot;SELECT * FROM mytable LIMIT $start, $limit&quot;)\n -&gt;fetchAll();\n\n$total_pages = count($data);\n\n/* Setup page vars for display. */\n$prev = $page - 1;\n$next = $page + 1;\n$lastpage = ceil($total_pages / $limit);\n//last page minus 1\n$lpm1 = $lastpage - 1;\n\n$first_pages = &quot;&lt;li class='page-item'&gt;&lt;a class='page-link' href='?page=1'&gt;1&lt;/a&gt;&lt;/li&gt;&quot; .\n &quot;&lt;li class='page-item'&gt;&lt;a class='page-link' href='?page=2'&gt;2&lt;/a&gt;&quot;;\n\n$ellipsis = &quot;&lt;li class='page-item disabled'&gt;&lt;span class='page-link'&gt;...&lt;/span&gt;&lt;/li&gt;&quot;;\n\n$last_pages = &quot;&lt;li class='page-item'&gt;&lt;a class='page-link' href='?page=$lpm1'&gt;$lpm1&lt;/a&gt;&lt;/li&gt;&quot; .\n &quot;&lt;li class='page-item'&gt;&lt;a class='page-link' href='?page=$lastpage'&gt;$lastpage&lt;/a&gt;&quot;;\n\n$pagination = &quot;&lt;nav aria-label='page navigation'&gt;&quot;;\n$pagincation .= &quot;&lt;ul class='pagination'&gt;&quot;;\n\n//previous button\n\n$disabled = ($page === 1) ? &quot;disabled&quot; : &quot;&quot;;\n$pagination.= &quot;&lt;li class='page-item $disabled'&gt;&lt;a class='page-link' href='?page=$prev'&gt;« previous&lt;/a&gt;&lt;/li&gt;&quot;;\n\n//pages \n//not enough pages to bother breaking it up\nif ($lastpage &lt; 7 + ($adjacents * 2)) { \n for ($i = 1; $i &lt;= $lastpage; $i++) {\n $active = $i === $page ? &quot;active&quot; : &quot;&quot;;\n $pagination .= &quot;&lt;li class='page-item $active'&gt;&lt;a class='page-link' href='?page=$i'&gt;$i&lt;/a&gt;&lt;/li&gt;&quot;;\n }\n} elseif($lastpage &gt; 5 + ($adjacents * 2)) {\n //enough pages to hide some\n //close to beginning; only hide later pages\n if($page &lt; 1 + ($adjacents * 2)) {\n for ($i = 1; $i &lt; 4 + ($adjacents * 2); $i++) {\n $active = $i === $page ? &quot;active&quot; : &quot;&quot;;\n $pagination .= &quot;&lt;li class='page-item $active'&gt;&lt;a class='page-link' href='?page=$i'&gt;$i&lt;/a&gt;&lt;/li&gt;&quot;;\n }\n $pagination .= $ellipsis;\n $pagination .= $last_pages;\n } elseif($lastpage - ($adjacents * 2) &gt; $page &amp;&amp; $page &gt; ($adjacents * 2)) {\n //in middle; hide some front and some back\n $pagination .= $first_pages;\n $pagination .= $ellipsis\n for ($i = $page - $adjacents; $i &lt;= $page + $adjacents; $i++) {\n $active = $i === $page ? &quot;active&quot; : &quot;&quot;;\n $pagination .= &quot;&lt;li class='page-item $active'&gt;&lt;a class='page-link' href='?page=$i'&gt;$i&lt;/a&gt;&lt;/li&gt;&quot;;\n }\n $pagination .= $ellipsis;\n $pagination .= $last_pages;\n } else {\n //close to end; only hide early pages\n $pagination .= $first_pages;\n $pagination .= $ellipsis;\n $pagination .= &quot;&lt;li class='page-item disabled'&gt;&lt;span class='page-link'&gt;...&lt;/span&gt;&lt;/li&gt;&quot;;\n for ($i = $lastpage - (2 + ($adjacents * 2)); $i &lt;= $lastpage; $i++) {\n $active = $i === $page ? &quot;active&quot; : &quot;&quot;;\n $pagination .= &quot;&lt;li class='page-item $active'&gt;&lt;a class='page-link' href='?page=$i'&gt;$i&lt;/a&gt;&lt;/li&gt;&quot;;\n }\n }\n}\n\n//next button\n$disabled = ($page === $last) ? &quot;disabled&quot; : &quot;&quot;;\n$pagination.= &quot;&lt;li class='page-item $disabled'&gt;&lt;a class='page-link' href='?page=$next'&gt;next »&lt;/a&gt;&lt;/li&gt;&quot;;\n\n$pagination .= &quot;&lt;/ul&gt;&lt;/nav&gt;&quot;;\n\nif($lastpage &lt;= 1) {\n $pagination = &quot;&quot;;\n}\n\n\necho $pagination;\n\nforeach ($data as $row) {\n // display your data\n}\n\necho $pagination;\n\n</code></pre>\n" }, { "answer_id": 163845, "author": "Fernando Barrocal", "author_id": 2274, "author_profile": "https://Stackoverflow.com/users/2274", "pm_score": 0, "selected": false, "text": "<p>I would use something simple on the page you are showing the paginator, like:</p>\n\n<pre><code>if (\n $page_number == 1 || $page_number == $last_page ||\n $page_number == $actual_page ||\n $page_number == $actual_page+1 || $page_number == $actual_page+2 ||\n $page_number == $actual_page-1 || $page_number == $actual_page-2\n ) echo $page_number;\n</code></pre>\n\n<p>You can adapt it to show each 10 or so pages with <code>%</code> operator ...</p>\n\n<p><em>I think using switch() case would be better in this case, I just don't remember the syntax now</em></p>\n\n<p>Keep it Simple :)</p>\n" }, { "answer_id": 164592, "author": "Jacob", "author_id": 8119, "author_profile": "https://Stackoverflow.com/users/8119", "pm_score": 2, "selected": false, "text": "<p>I made a pagination class and put in on Google Code a while ago. Check it out its pretty simple\n<a href=\"http://code.google.com/p/spaceshipcollaborative/wiki/PHPagination\" rel=\"nofollow noreferrer\"><a href=\"http://code.google.com/p/spaceshipcollaborative/wiki/PHPagination\" rel=\"nofollow noreferrer\">http://code.google.com/p/spaceshipcollaborative/wiki/PHPagination</a></a></p>\n\n<pre><code>$paging = new Pagination();\n$paging-&gt;set('urlscheme','class.pagination.php?page=%page%');\n$paging-&gt;set('perpage',10);\n$paging-&gt;set('page',15);\n$paging-&gt;set('total',3000);\n$paging-&gt;set('nexttext','Next Page');\n$paging-&gt;set('prevtext','Previous Page');\n$paging-&gt;set('focusedclass','selected');\n$paging-&gt;set('delimiter','');\n$paging-&gt;set('numlinks',9);\n$paging-&gt;display();\n</code></pre>\n" }, { "answer_id": 2759696, "author": "lazaro", "author_id": 331613, "author_profile": "https://Stackoverflow.com/users/331613", "pm_score": 2, "selected": false, "text": "<pre><code>List&lt;int&gt; pages = new List&lt;int&gt;();\nint pn = 2; //example of actual pagenumber\nint total = 8;\n\nfor(int i = pn - 9; i &lt;= pn + 9; i++)\n{\n if(i &lt; 1) continue;\n if(i &gt; total) break;\n pages.Add(i);\n}\n\nreturn pages;\n</code></pre>\n" }, { "answer_id": 7562895, "author": "Alix Axel", "author_id": 89771, "author_profile": "https://Stackoverflow.com/users/89771", "pm_score": 4, "selected": false, "text": "<p>Kinda late =), but here is my go at it:</p>\n\n<pre><code>function Pagination($data, $limit = null, $current = null, $adjacents = null)\n{\n $result = array();\n\n if (isset($data, $limit) === true)\n {\n $result = range(1, ceil($data / $limit));\n\n if (isset($current, $adjacents) === true)\n {\n if (($adjacents = floor($adjacents / 2) * 2 + 1) &gt;= 1)\n {\n $result = array_slice($result, max(0, min(count($result) - $adjacents, intval($current) - ceil($adjacents / 2))), $adjacents);\n }\n }\n }\n\n return $result;\n}\n</code></pre>\n\n<hr>\n\n<p><strong>Example:</strong></p>\n\n<pre><code>$total = 1024;\n$per_page = 10;\n$current_page = 2;\n$adjacent_links = 4;\n\nprint_r(Pagination($total, $per_page, $current_page, $adjacent_links));\n</code></pre>\n\n<p><strong>Output (<a href=\"http://codepad.org/vcULT1DA\">@ Codepad</a>):</strong></p>\n\n<pre><code>Array\n(\n [0] =&gt; 1\n [1] =&gt; 2\n [2] =&gt; 3\n [3] =&gt; 4\n [4] =&gt; 5\n)\n</code></pre>\n\n<hr>\n\n<p><strong>Another example:</strong></p>\n\n<pre><code>$total = 1024;\n$per_page = 10;\n$current_page = 42;\n$adjacent_links = 4;\n\nprint_r(Pagination($total, $per_page, $current_page, $adjacent_links));\n</code></pre>\n\n<p><strong>Output (<a href=\"http://codepad.org/HAKkgrb2\">@ Codepad</a>):</strong></p>\n\n<pre><code>Array\n(\n [0] =&gt; 40\n [1] =&gt; 41\n [2] =&gt; 42\n [3] =&gt; 43\n [4] =&gt; 44\n)\n</code></pre>\n" }, { "answer_id": 7824252, "author": "Robert Eisele", "author_id": 1003538, "author_profile": "https://Stackoverflow.com/users/1003538", "pm_score": 0, "selected": false, "text": "<p>If it's possible to generate the pagination on the client, I would suggest my new Pagination plugin: <a href=\"http://www.xarg.org/2011/09/jquery-pagination-revised/\" rel=\"nofollow\">http://www.xarg.org/2011/09/jquery-pagination-revised/</a></p>\n\n<p>The solution to your question would be:</p>\n\n<pre><code>$(\"#pagination\").paging(1000, { // Your number of elements\n format: '. - nncnn - ', // Format to get Pages: ... 3 4 [5] 6 7 ...\n onSelect: function (page) {\n // add code which gets executed when user selects a page\n },\n onFormat: function (type) {\n switch (type) {\n case 'block': // n and c\n return '&lt;a&gt;' + this.value + '&lt;/a&gt;';\n case 'fill': // -\n return '...';\n case 'leap': // .\n return 'Pages:';\n }\n }\n});\n</code></pre>\n" }, { "answer_id": 7833191, "author": "Natrium", "author_id": 59119, "author_profile": "https://Stackoverflow.com/users/59119", "pm_score": 0, "selected": false, "text": "<p>The code of the <a href=\"http://codeigniter.com/user_guide/libraries/pagination.html\" rel=\"nofollow\">CodeIgniter pagination</a>-class can be found <a href=\"https://github.com/EllisLab/CodeIgniter/blob/develop/system/libraries/Pagination.php\" rel=\"nofollow\">on GitHub</a></p>\n\n<p>(what you call) Smart pagination can be achieved by configuration.</p>\n\n<pre><code>$config['num_links'] = 2;\n</code></pre>\n\n<blockquote>\n <p>The number of \"digit\" links you would like before and after the\n selected page number. For example, the number 2 will place two digits\n on either side, as in the example links at the very top of this page.</p>\n</blockquote>\n" }, { "answer_id": 8608998, "author": "Edwin", "author_id": 1079096, "author_profile": "https://Stackoverflow.com/users/1079096", "pm_score": 3, "selected": false, "text": "<p>I started from the lazaro's post and tried to make a robust and light algorithm with javascript/jquery...\nNo additional and/or bulky pagination libraries needed...\nLook on fiddle for an live example: <a href=\"http://jsfiddle.net/97JtZ/1/\" rel=\"noreferrer\">http://jsfiddle.net/97JtZ/1/</a></p>\n\n<pre><code>var totalPages = 50, buttons = 5;\nvar currentPage = lowerLimit = upperLimit = Math.min(9, totalPages);\n\n//Search boundaries\nfor (var b = 1; b &lt; buttons &amp;&amp; b &lt; totalPages;) {\n if (lowerLimit &gt; 1 ) { lowerLimit--; b++; }\n if (b &lt; buttons &amp;&amp; upperLimit &lt; totalPages) { upperLimit++; b++; }\n}\n\n//Do output to a html element\nfor (var i = lowerLimit; i &lt;= upperLimit; i++) {\n if (i == currentPage) $('#pager').append('&lt;li&gt;' + i + '&lt;/li&gt; ');\n else $('#pager').append('&lt;a href=\"#\"&gt;&lt;li&gt;&lt;em&gt;' + i + '&lt;/em&gt;&lt;/li&gt;&lt;/a&gt; ');\n}\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163809", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14981/" ]
I'm looking for an example algorithm of smart pagination. By smart, what I mean is that I only want to show, for example, 2 adjacent pages to the current page, so instead of ending up with a ridiculously long page list, I truncate it. Here's a quick example to make it clearer... this is what I have now: ``` Pages: 1 2 3 4 [5] 6 7 8 9 10 11 ``` This is what I want to end up with: ``` Pages: ... 3 4 [5] 6 7 ... ``` (In this example, I'm only showing 2 adjacent pages to the current page) I'm implementing it in PHP/Mysql, and the "basic" pagination (no trucating) is already coded, I'm just looking for an example to optimize it... It can be an example in any language, as long as it gives me an idea as to how to implement it...
Here is some code based on original code from [this very old link](https://www.strangerstudios.com/sandbox/pagination/diggstyle.php). It uses markup compatible with Bootstrap's pagination component, and outputs page links like this: ```none [1] 2 3 4 5 6 ... 100 1 [2] 3 4 5 6 ... 100 ... 1 2 ... 14 15 [16] 17 18 ... 100 ... 1 2 ... 97 [98] 99 100 ``` ```php <?php // How many adjacent pages should be shown on each side? $adjacents = 3; //how many items to show per page $limit = 5; // if no page var is given, default to 1. $page = (int)$_GET["page"] ?? 1; //first item to display on this page $start = ($page - 1) * $limit; /* Get data. */ $data = $db ->query("SELECT * FROM mytable LIMIT $start, $limit") ->fetchAll(); $total_pages = count($data); /* Setup page vars for display. */ $prev = $page - 1; $next = $page + 1; $lastpage = ceil($total_pages / $limit); //last page minus 1 $lpm1 = $lastpage - 1; $first_pages = "<li class='page-item'><a class='page-link' href='?page=1'>1</a></li>" . "<li class='page-item'><a class='page-link' href='?page=2'>2</a>"; $ellipsis = "<li class='page-item disabled'><span class='page-link'>...</span></li>"; $last_pages = "<li class='page-item'><a class='page-link' href='?page=$lpm1'>$lpm1</a></li>" . "<li class='page-item'><a class='page-link' href='?page=$lastpage'>$lastpage</a>"; $pagination = "<nav aria-label='page navigation'>"; $pagincation .= "<ul class='pagination'>"; //previous button $disabled = ($page === 1) ? "disabled" : ""; $pagination.= "<li class='page-item $disabled'><a class='page-link' href='?page=$prev'>« previous</a></li>"; //pages //not enough pages to bother breaking it up if ($lastpage < 7 + ($adjacents * 2)) { for ($i = 1; $i <= $lastpage; $i++) { $active = $i === $page ? "active" : ""; $pagination .= "<li class='page-item $active'><a class='page-link' href='?page=$i'>$i</a></li>"; } } elseif($lastpage > 5 + ($adjacents * 2)) { //enough pages to hide some //close to beginning; only hide later pages if($page < 1 + ($adjacents * 2)) { for ($i = 1; $i < 4 + ($adjacents * 2); $i++) { $active = $i === $page ? "active" : ""; $pagination .= "<li class='page-item $active'><a class='page-link' href='?page=$i'>$i</a></li>"; } $pagination .= $ellipsis; $pagination .= $last_pages; } elseif($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2)) { //in middle; hide some front and some back $pagination .= $first_pages; $pagination .= $ellipsis for ($i = $page - $adjacents; $i <= $page + $adjacents; $i++) { $active = $i === $page ? "active" : ""; $pagination .= "<li class='page-item $active'><a class='page-link' href='?page=$i'>$i</a></li>"; } $pagination .= $ellipsis; $pagination .= $last_pages; } else { //close to end; only hide early pages $pagination .= $first_pages; $pagination .= $ellipsis; $pagination .= "<li class='page-item disabled'><span class='page-link'>...</span></li>"; for ($i = $lastpage - (2 + ($adjacents * 2)); $i <= $lastpage; $i++) { $active = $i === $page ? "active" : ""; $pagination .= "<li class='page-item $active'><a class='page-link' href='?page=$i'>$i</a></li>"; } } } //next button $disabled = ($page === $last) ? "disabled" : ""; $pagination.= "<li class='page-item $disabled'><a class='page-link' href='?page=$next'>next »</a></li>"; $pagination .= "</ul></nav>"; if($lastpage <= 1) { $pagination = ""; } echo $pagination; foreach ($data as $row) { // display your data } echo $pagination; ```
163,823
<p>I have a <code>Person</code> model that has a foreign key relationship to <code>Book</code>, which has a number of fields, but I'm most concerned about <code>author</code> (a standard CharField).</p> <p>With that being said, in my <code>PersonAdmin</code> model, I'd like to display <code>book.author</code> using <code>list_display</code>:</p> <pre><code>class PersonAdmin(admin.ModelAdmin): list_display = ['book.author',] </code></pre> <p>I've tried all of the obvious methods for doing so, but nothing seems to work.</p> <p>Any suggestions?</p>
[ { "answer_id": 163968, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 5, "selected": false, "text": "<p>According to the documentation, you can only display the <code>__unicode__</code> representation of a ForeignKey:</p>\n\n<p><a href=\"http://docs.djangoproject.com/en/dev/ref/contrib/admin/#list-display\" rel=\"noreferrer\">http://docs.djangoproject.com/en/dev/ref/contrib/admin/#list-display</a></p>\n\n<p>Seems odd that it doesn't support the <code>'book__author'</code> style format which is used everywhere else in the DB API.</p>\n\n<p>Turns out there's <a href=\"http://code.djangoproject.com/ticket/5863\" rel=\"noreferrer\">a ticket for this feature</a>, which is marked as Won't Fix.</p>\n" }, { "answer_id": 164631, "author": "imjoevasquez", "author_id": 24630, "author_profile": "https://Stackoverflow.com/users/24630", "pm_score": 10, "selected": true, "text": "<p>As another option, you can do look ups like:</p>\n<pre><code>class UserAdmin(admin.ModelAdmin):\n list_display = (..., 'get_author')\n \n def get_author(self, obj):\n return obj.book.author\n get_author.short_description = 'Author'\n get_author.admin_order_field = 'book__author'\n</code></pre>\n<p>Since Django 3.2 you can use <a href=\"https://docs.djangoproject.com/en/3.2/ref/contrib/admin/#the-display-decorator\" rel=\"nofollow noreferrer\"><code>display()</code></a> decorator:</p>\n<pre><code>class UserAdmin(admin.ModelAdmin):\n list_display = (..., 'get_author')\n \n @admin.display(ordering='book__author', description='Author')\n def get_author(self, obj):\n return obj.book.author\n</code></pre>\n" }, { "answer_id": 475086, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>This one's already accepted, but if there are any other dummies out there (like me) that didn't immediately get it from the <a href=\"https://stackoverflow.com/a/164631/58668\">presently accepted answer</a>, here's a bit more detail. </p>\n\n<p>The model class referenced by the <code>ForeignKey</code> needs to have a <code>__unicode__</code> method within it, like here: </p>\n\n<pre><code>class Category(models.Model):\n name = models.CharField(max_length=50)\n\n def __unicode__(self):\n return self.name\n</code></pre>\n\n<p>That made the difference for me, and should apply to the above scenario. This works on Django 1.0.2.</p>\n" }, { "answer_id": 496453, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>You can show whatever you want in list display by using a callable. It would look like this:</p>\n\n<pre>\n\ndef book_author(object):\n return object.book.author\n\nclass PersonAdmin(admin.ModelAdmin):\n list_display = [book_author,]</pre>\n" }, { "answer_id": 679791, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>AlexRobbins' answer worked for me, except that the first two lines need to be in the model (perhaps this was assumed?), and should reference self:</p>\n\n<pre><code>def book_author(self):\n return self.book.author\n</code></pre>\n\n<p>Then the admin part works nicely.</p>\n" }, { "answer_id": 3351431, "author": "Arjen", "author_id": 390441, "author_profile": "https://Stackoverflow.com/users/390441", "pm_score": 6, "selected": false, "text": "<p>Like the rest, I went with callables too. But they have one downside: by default, you can't order on them. Fortunately, there is a solution for that:</p>\n\n<h1>Django >= 1.8</h1>\n\n<pre><code>def author(self, obj):\n return obj.book.author\nauthor.admin_order_field = 'book__author'\n</code></pre>\n\n<h1>Django &lt; 1.8</h1>\n\n<pre><code>def author(self):\n return self.book.author\nauthor.admin_order_field = 'book__author'\n</code></pre>\n" }, { "answer_id": 14677451, "author": "Jack Cushman", "author_id": 307769, "author_profile": "https://Stackoverflow.com/users/307769", "pm_score": 4, "selected": false, "text": "<p>I just posted a snippet that makes admin.ModelAdmin support '__' syntax:</p>\n\n<p><a href=\"http://djangosnippets.org/snippets/2887/\" rel=\"noreferrer\">http://djangosnippets.org/snippets/2887/</a></p>\n\n<p>So you can do:</p>\n\n<pre><code>class PersonAdmin(RelatedFieldAdmin):\n list_display = ['book__author',]\n</code></pre>\n\n<p>This is basically just doing the same thing described in the other answers, but it automatically takes care of (1) setting admin_order_field (2) setting short_description and (3) modifying the queryset to avoid a database hit for each row.</p>\n" }, { "answer_id": 21456615, "author": "Eyal Ch", "author_id": 3218482, "author_profile": "https://Stackoverflow.com/users/3218482", "pm_score": 2, "selected": false, "text": "<p>if you try it in Inline, you wont succeed unless:</p>\n\n<p>in your inline:</p>\n\n<pre><code>class AddInline(admin.TabularInline):\n readonly_fields = ['localname',]\n model = MyModel\n fields = ('localname',)\n</code></pre>\n\n<p>in your model (MyModel):</p>\n\n<pre><code>class MyModel(models.Model):\n localization = models.ForeignKey(Localizations)\n\n def localname(self):\n return self.localization.name\n</code></pre>\n" }, { "answer_id": 23747842, "author": "Will", "author_id": 464923, "author_profile": "https://Stackoverflow.com/users/464923", "pm_score": 8, "selected": false, "text": "<p>Despite all the great answers above and due to me being new to Django, I was still stuck. Here's my explanation from a very newbie perspective.</p>\n\n<p><strong>models.py</strong></p>\n\n<pre><code>class Author(models.Model):\n name = models.CharField(max_length=255)\n\nclass Book(models.Model):\n author = models.ForeignKey(Author)\n title = models.CharField(max_length=255)\n</code></pre>\n\n<p><strong>admin.py (Incorrect Way)</strong> - you think it would work by using 'model__field' to reference, but it doesn't</p>\n\n<pre><code>class BookAdmin(admin.ModelAdmin):\n model = Book\n list_display = ['title', 'author__name', ]\n\nadmin.site.register(Book, BookAdmin)\n</code></pre>\n\n<p><strong>admin.py (Correct Way)</strong> - this is how you reference a foreign key name the Django way</p>\n\n<pre><code>class BookAdmin(admin.ModelAdmin):\n model = Book\n list_display = ['title', 'get_name', ]\n\n def get_name(self, obj):\n return obj.author.name\n get_name.admin_order_field = 'author' #Allows column order sorting\n get_name.short_description = 'Author Name' #Renames column head\n\n #Filtering on side - for some reason, this works\n #list_filter = ['title', 'author__name']\n\nadmin.site.register(Book, BookAdmin)\n</code></pre>\n\n<p>For additional reference, see the Django model link <a href=\"https://docs.djangoproject.com/en/dev/ref/contrib/admin/#list-display\" rel=\"noreferrer\">here</a></p>\n" }, { "answer_id": 28190954, "author": "Hunger", "author_id": 2251785, "author_profile": "https://Stackoverflow.com/users/2251785", "pm_score": 6, "selected": false, "text": "<p>Please note that adding the <code>get_author</code> function would slow the list_display in the admin, because showing each person would make a SQL query.</p>\n\n<p>To avoid this, you need to modify <code>get_queryset</code> method in PersonAdmin, for example:</p>\n\n<pre><code>def get_queryset(self, request):\n return super(PersonAdmin,self).get_queryset(request).select_related('book')\n</code></pre>\n\n<blockquote>\n <p>Before: 73 queries in 36.02ms (67 duplicated queries in admin)</p>\n \n <p>After: 6 queries in 10.81ms</p>\n</blockquote>\n" }, { "answer_id": 34735225, "author": "Cauê Thenório", "author_id": 780262, "author_profile": "https://Stackoverflow.com/users/780262", "pm_score": 3, "selected": false, "text": "<p>If you have a lot of relation attribute fields to use in <code>list_display</code> and do not want create a function (and it's attributes) for each one, a dirt but simple solution would be override the <code>ModelAdmin</code> instace <code>__getattr__</code> method, creating the callables on the fly:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>class DynamicLookupMixin(object):\n '''\n a mixin to add dynamic callable attributes like 'book__author' which\n return a function that return the instance.book.author value\n '''\n\n def __getattr__(self, attr):\n if ('__' in attr\n and not attr.startswith('_')\n and not attr.endswith('_boolean')\n and not attr.endswith('_short_description')):\n\n def dyn_lookup(instance):\n # traverse all __ lookups\n return reduce(lambda parent, child: getattr(parent, child),\n attr.split('__'),\n instance)\n\n # get admin_order_field, boolean and short_description\n dyn_lookup.admin_order_field = attr\n dyn_lookup.boolean = getattr(self, '{}_boolean'.format(attr), False)\n dyn_lookup.short_description = getattr(\n self, '{}_short_description'.format(attr),\n attr.replace('_', ' ').capitalize())\n\n return dyn_lookup\n\n # not dynamic lookup, default behaviour\n return self.__getattribute__(attr)\n\n\n# use examples \n\[email protected](models.Person)\nclass PersonAdmin(admin.ModelAdmin, DynamicLookupMixin):\n list_display = ['book__author', 'book__publisher__name',\n 'book__publisher__country']\n\n # custom short description\n book__publisher__country_short_description = 'Publisher Country'\n\n\[email protected](models.Product)\nclass ProductAdmin(admin.ModelAdmin, DynamicLookupMixin):\n list_display = ('name', 'category__is_new')\n\n # to show as boolean field\n category__is_new_boolean = True\n</code></pre>\n\n<p>As <a href=\"https://gist.github.com/cauethenorio/9db40c59cf406bf328fd\" rel=\"noreferrer\">gist here</a></p>\n\n<p>Callable especial attributes like <code>boolean</code> and <code>short_description</code> must be defined as <code>ModelAdmin</code> attributes, eg <code>book__author_verbose_name = 'Author name'</code> and <code>category__is_new_boolean = True</code>.</p>\n\n<p>The callable <code>admin_order_field</code> attribute is defined automatically.</p>\n\n<p>Don't forget to use the <a href=\"https://docs.djangoproject.com/en/1.9/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_select_related\" rel=\"noreferrer\" title=\"list_select_related\">list_select_related</a> attribute in your <code>ModelAdmin</code> to make Django avoid aditional queries.</p>\n" }, { "answer_id": 37497913, "author": "Vlad Schnakovszki", "author_id": 1195527, "author_profile": "https://Stackoverflow.com/users/1195527", "pm_score": 4, "selected": false, "text": "<p>There is a very easy to use package available in PyPI that handles exactly that: <a href=\"https://pypi.python.org/pypi/django-related-admin\" rel=\"noreferrer\">django-related-admin</a>. You can also <a href=\"https://github.com/PetrDlouhy/django-related-admin\" rel=\"noreferrer\">see the code in GitHub</a>.</p>\n\n<p>Using this, what you want to achieve is as simple as:</p>\n\n<pre><code>class PersonAdmin(RelatedFieldAdmin):\n list_display = ['book__author',]\n</code></pre>\n\n<p>Both links contain full details of installation and usage so I won't paste them here in case they change.</p>\n\n<p>Just as a side note, if you're already using something other than <code>model.Admin</code> (e.g. I was using <code>SimpleHistoryAdmin</code> instead), you can do this: <code>class MyAdmin(SimpleHistoryAdmin, RelatedFieldAdmin)</code>.</p>\n" }, { "answer_id": 39642294, "author": "wieczorek1990", "author_id": 761200, "author_profile": "https://Stackoverflow.com/users/761200", "pm_score": -1, "selected": false, "text": "<p>I prefer this:</p>\n\n<pre><code>class CoolAdmin(admin.ModelAdmin):\n list_display = ('pk', 'submodel__field')\n\n @staticmethod\n def submodel__field(obj):\n return obj.submodel.field\n</code></pre>\n" }, { "answer_id": 67746847, "author": "Cesar Canassa", "author_id": 360829, "author_profile": "https://Stackoverflow.com/users/360829", "pm_score": 5, "selected": false, "text": "<h1>For Django &gt;= 3.2</h1>\n<p>The proper way to do it with Django 3.2 or higher is by using the <a href=\"https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.display\" rel=\"noreferrer\">display decorator</a></p>\n<pre class=\"lang-py prettyprint-override\"><code>class BookAdmin(admin.ModelAdmin):\n model = Book\n list_display = ['title', 'get_author_name']\n\n @admin.display(description='Author Name', ordering='author__name')\n def get_author_name(self, obj):\n return obj.author.name\n</code></pre>\n" }, { "answer_id": 69360403, "author": "Eyong Kevin Enowanyo", "author_id": 8665639, "author_profile": "https://Stackoverflow.com/users/8665639", "pm_score": 2, "selected": false, "text": "<p>I may be late, but this is another way to do it. You can simply define a method in your model and access it via the <code>list_display</code> as below:</p>\n<p><strong>models.py</strong></p>\n<pre><code>class Person(models.Model):\n book = models.ForeignKey(Book, on_delete=models.CASCADE)\n\n def get_book_author(self):\n return self.book.author\n</code></pre>\n<p><strong>admin.py</strong></p>\n<pre><code>class PersonAdmin(admin.ModelAdmin):\n list_display = ('get_book_author',)\n</code></pre>\n<p>But this and the other approaches mentioned above add two extra queries per row in your listview page. To optimize this, we can override the <code>get_queryset</code> to annotate the required field, then use the annotated field in our ModelAdmin method</p>\n<p><strong>admin.py</strong></p>\n<pre><code>from django.db.models.expressions import F\n\[email protected](models.Person)\nclass PersonAdmin(admin.ModelAdmin):\n list_display = ('get_author',)\n def get_queryset(self, request):\n queryset = super().get_queryset(request)\n queryset = queryset.annotate(\n _author = F('book__author')\n )\n return queryset\n\n @admin.display(ordering='_author', description='Author')\n def get_author(self, obj):\n return obj._author\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163823", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10040/" ]
I have a `Person` model that has a foreign key relationship to `Book`, which has a number of fields, but I'm most concerned about `author` (a standard CharField). With that being said, in my `PersonAdmin` model, I'd like to display `book.author` using `list_display`: ``` class PersonAdmin(admin.ModelAdmin): list_display = ['book.author',] ``` I've tried all of the obvious methods for doing so, but nothing seems to work. Any suggestions?
As another option, you can do look ups like: ``` class UserAdmin(admin.ModelAdmin): list_display = (..., 'get_author') def get_author(self, obj): return obj.book.author get_author.short_description = 'Author' get_author.admin_order_field = 'book__author' ``` Since Django 3.2 you can use [`display()`](https://docs.djangoproject.com/en/3.2/ref/contrib/admin/#the-display-decorator) decorator: ``` class UserAdmin(admin.ModelAdmin): list_display = (..., 'get_author') @admin.display(ordering='book__author', description='Author') def get_author(self, obj): return obj.book.author ```
163,834
<p>What's the most elegant templating (preferably in pure PHP!) solution you've seen?</p> <p>Specifically i'm interested in handling:</p> <ol> <li>Detecting in a repeating block whether it's the first or last element</li> <li>Easy handling of odd/even cases, like a zebra striped table, or similar</li> <li>Other modulos logic, where you'd do something every n'th time.</li> </ol> <p>I'm looking for something that makes this less of a pain:</p> <pre><code>&lt;?php $persons = array('John', 'Jack', 'Jill', 'Jason'); ?&gt; &lt;?php $i = 0; ?&gt; &lt;?php if (isset($persons)): ?&gt; &lt;ul&gt; &lt;?php foreach ($persons as $name): ?&gt; &lt;li class="&lt;?= ($i++ % 2 === 0) ? 'odd' : 'even' ?&gt;"&gt;&lt;?= $name ?&gt;&lt;/li&gt; &lt;?php endforeach ?&gt; &lt;/ul&gt; &lt;?php endif ?&gt; </code></pre> <p>Does it really take the mess above to create something like this below?</p> <pre><code>&lt;ul&gt; &lt;li class="odd"&gt;John&lt;/li&gt; &lt;li class="even"&gt;Jack&lt;/li&gt; &lt;li class="odd"&gt;Jill&lt;/li&gt; &lt;li class="even"&gt;Jason&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>Is it only me that find the above near hideous? </p> <p>All those starting and closing of php-tags makes me cringe.</p>
[ { "answer_id": 163849, "author": "Patrick Desjardins", "author_id": 13913, "author_profile": "https://Stackoverflow.com/users/13913", "pm_score": 0, "selected": false, "text": "<p>I use Modulo like you did in your example all the time.</p>\n" }, { "answer_id": 163860, "author": "Cruachan", "author_id": 7315, "author_profile": "https://Stackoverflow.com/users/7315", "pm_score": 3, "selected": false, "text": "<p>Tiny But Strong</p>\n\n<p><a href=\"http://www.tinybutstrong.com\" rel=\"nofollow noreferrer\">www.tinybutstrong.com</a></p>\n\n<p>It doesn't make the smarty mistake of embedding another macro language in the page, but does allow you to handle every practical web display issue I've ever thrown at it. In particular the above odd/even constructs are a doddle. For something like your code selecting from a database table</p>\n\n<p>In the PHP file</p>\n\n<pre><code>$TBS-&gt;MergeBlock('blk1',$sqlconnect, \"SELECT name from people \");\n</code></pre>\n\n<p>And in the HTML file</p>\n\n<pre><code>&lt;ul&gt;\n &lt;li class=\"odd\"&gt;[blk.name;block=ul]&lt;/li&gt;\n &lt;li class=\"even\"&gt;[blk.name;block=ul]&lt;/li&gt;\n&lt;/ul&gt;\n</code></pre>\n\n<p>And that's it. Notice that the HTML is completely Dreamweaver compatible. Furthermore if I wanted to make that alternate over three line styles all I'd need to do is add the extra line, maybe with different classes, so</p>\n\n<pre><code>&lt;ul&gt;\n &lt;li class=\"linestyle1\"&gt;[blk.name;block=ul]&lt;/li&gt;\n &lt;li class=\"linestyle2\"&gt;[blk.name;block=ul]&lt;/li&gt;\n &lt;li class=\"linestyle3\"&gt;[blk.name;block=ul]&lt;/li&gt;\n&lt;/ul&gt;\n</code></pre>\n" }, { "answer_id": 163869, "author": "Ericko", "author_id": 1620279, "author_profile": "https://Stackoverflow.com/users/1620279", "pm_score": 0, "selected": false, "text": "<p>If what cringes you is the opening and closing tags, write a function that creates the html string and then have it return it. At least it will save you some tags.</p>\n" }, { "answer_id": 163894, "author": "fijter", "author_id": 3215, "author_profile": "https://Stackoverflow.com/users/3215", "pm_score": 2, "selected": false, "text": "<p>It ain't pure PHP (the templating syntax then), but it works realy nice; <a href=\"http://www.smarty.net\" rel=\"noreferrer\">Smarty</a>.</p>\n\n<p>For loops you can do:</p>\n\n<pre><code>\n&lt;ul&gt;\n{foreach from=$var name=loop item=test}\n {if $smarty.foreach.loop.first}&lt;li&gt;This is the first item&lt;/li&gt;{/if}\n &lt;li class=\"{cycle values=\"odd,even\"}\">{$var.name}&lt;/li&gt;\n {if $smarty.foreach.loop.last}&lt;li&gt;This was the last item&lt;/li&gt;{/if}\n{/foreach}\n&lt;/ul&gt;\n</code></pre>\n" }, { "answer_id": 163896, "author": "cllpse", "author_id": 20946, "author_profile": "https://Stackoverflow.com/users/20946", "pm_score": 1, "selected": false, "text": "<p>I've used <a href=\"http://www.smarty.net/\" rel=\"nofollow noreferrer\">Smarty Template Engine</a> in the past. It's Pretty solid. And as you can probably tell from the website; it has quite the large user-base and is updated regularly.</p>\n\n<p>It's in pure PHP as well.</p>\n" }, { "answer_id": 164101, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 2, "selected": false, "text": "<p>have you considered <a href=\"http://phptal.motion-twin.com/\" rel=\"nofollow noreferrer\">phptal</a>?. one main benefit of it (or something similar) is that you get templates which can pass validation. most php template engines seem to ignore this.</p>\n" }, { "answer_id": 164172, "author": "Randy", "author_id": 9361, "author_profile": "https://Stackoverflow.com/users/9361", "pm_score": 4, "selected": false, "text": "<p>You don't need to open the tags more than once. You can also make a function out of it if you do the same thing multiple times:</p>\n\n<pre><code>&lt;?php\nfunction makeul($items, $classes) {\n $c = count($classes);\n $out = \"\";\n\n if (isset($items) &amp;&amp; count($items) &gt; 0) {\n $out = \"&lt;ul&gt;\\n\";\n foreach ($items as $item) {\n $out .= \"\\t&lt;li class=\\\"\" . $classes[$i++%$c] . \"\\\"&gt;$item&lt;/li&gt;\\n\";\n }\n $out .= \"&lt;/ul&gt;\\n\";\n }\n return $out;\n}\n?&gt;\n\nother page content\n\n&lt;?php\n$persons = array('John', 'Jack', 'Jill', 'Jason');\n$classes = array('odd', 'even');\nprint makeul($persons, $classes);\n?&gt;\n</code></pre>\n\n<p>Also, if you don't mind using Javascript, <a href=\"http://jquery.com/\" rel=\"noreferrer\">Jquery</a> makes things done mod 2 pretty easy (e.g., for zebra striping a table):</p>\n\n<pre><code>$(\"tr:odd\").addClass(\"odd\");\n$(\"tr:even\").addClass(\"even\");\n</code></pre>\n" }, { "answer_id": 165930, "author": "Shabbyrobe", "author_id": 15004, "author_profile": "https://Stackoverflow.com/users/15004", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://www.phpsavant.com/\" rel=\"nofollow noreferrer\">Savant</a> is a lightweight, pure PHP templating engine. Version 2 has a <a href=\"http://www.phpsavant.com/yawiki/index.php?area=Savant2&amp;page=PluginCycle#\" rel=\"nofollow noreferrer\">cycle</a> plugin similar to the Smarty one mentioned earlier. I haven't been able to find a reference to the same plugin in version 3, but I'm sure you could write it fairly easily.</p>\n" }, { "answer_id": 168484, "author": "Robert K", "author_id": 24950, "author_profile": "https://Stackoverflow.com/users/24950", "pm_score": 2, "selected": false, "text": "<p>I use <a href=\"http://phptal.motion-twin.com/\" rel=\"nofollow noreferrer\">PHPTAL</a> for templating because it is written in 100% actual HTML with placeholder data, so it even works in a WYSIWYG editor for a web designer. That and it's just way easy to understand.</p>\n\n<p>Here's what it would look like for me. Please forgive the markup, I'm new here and the four spaces block wasn't working right for me (the list was a list, not the markup).</p>\n\n<p><em>PHP Code:</em></p>\n\n<pre>\n $tal = new PHPTAL;\n $tal->setTemplate('people.htm')\n ->set('people', array('John', 'Jack', 'Jill', 'Jason'));\n echo $tal->execute();\n</pre>\n\n<p><em>Template:</em></p>\n\n<pre>\n &lt;ul&gt;\n &lt;li tal:repeat=\"person people\" tal:content=\"person\"&gt;John Doe&lt;/li&gt;\n &lt;/ul&gt;\n</pre>\n\n<p><em>Output:</em></p>\n\n<blockquote>\n <p><li>John</li><li>Jack</li><li>Jill</li><li>Jason</li></p>\n</blockquote>\n\n<p>Now obviously I wouldn't make a template for this little, but I could use a macro for it or build a whole page and include that variable. But you get the idea. Using <a href=\"http://phptal.motion-twin.com/\" rel=\"nofollow noreferrer\">PHPTAL</a> has just about tripled my speed at templating and programming, just by the simplicity (no new syntax to learn like smarty).</p>\n" }, { "answer_id": 1004532, "author": "Sam Saffron", "author_id": 17174, "author_profile": "https://Stackoverflow.com/users/17174", "pm_score": 0, "selected": false, "text": "<p>I have been a fan of HAML for quite a while, it looks like PHP folk have HAML now: see <a href=\"http://phphaml.sourceforge.net/\" rel=\"nofollow noreferrer\">http://phphaml.sourceforge.net/</a></p>\n" }, { "answer_id": 1004554, "author": "gahooa", "author_id": 64004, "author_profile": "https://Stackoverflow.com/users/64004", "pm_score": 3, "selected": false, "text": "<p><strong>A small help on the looping:</strong></p>\n\n<pre><code>&lt;? $b=false; foreach($MyList as $name) { ?&gt;\n &lt;li class=\"row&lt;?= $b=!$b ?&gt;\"&gt;&lt;?= htmlspecialchars($name); ?&gt;&lt;/li&gt;\n&lt;? } ?&gt;\n</code></pre>\n\n<p>By saying <code>$b=!$b</code>, it automatically alternates between true and false. Since false prints as \"\", and true prints as \"1\", then by defining css classes <code>row</code> and <code>row1</code>, you can get your altering rows without any trouble.</p>\n\n<p>consider using <code>:first-child</code> css to style the first one differently.</p>\n" }, { "answer_id": 1053303, "author": "Erik", "author_id": 129877, "author_profile": "https://Stackoverflow.com/users/129877", "pm_score": 0, "selected": false, "text": "<pre><code>&lt;?= ($i++ % 2 === 0) ? 'odd' : 'even' ?&gt;\n</code></pre>\n\n<p>You're doing it the other way around. Your first item is now called even instead of odd. Use ++$i.</p>\n\n<p>I'm having the same problem. But I think your original solution is the neatest. So I'll go with that.</p>\n" }, { "answer_id": 1268725, "author": "bytebrite", "author_id": 144629, "author_profile": "https://Stackoverflow.com/users/144629", "pm_score": 2, "selected": false, "text": "<p>How's about <a href=\"http://us.php.net/xsl\" rel=\"nofollow noreferrer\">XSLT</a>? The only template system that has a standards body behind it. Works the same across programming languages. Learn it once, use it everywhere!</p>\n" }, { "answer_id": 1826238, "author": "Meep3D", "author_id": 130417, "author_profile": "https://Stackoverflow.com/users/130417", "pm_score": 0, "selected": false, "text": "<p>I created a simple templating system in PHP to solve this problem a while ago:</p>\n\n<p><a href=\"http://code.google.com/p/templatephp/\" rel=\"nofollow noreferrer\">http://code.google.com/p/templatephp/</a></p>\n\n<p>It takes a multidimensional array, and requires the addition of some extra tags to the HMTL to create the combined template.</p>\n\n<p>It's not as complicated (albeit powerful) as Smarty and some other solutons, but wins out in simplicity a lot of the time. A demo of the menu creation:</p>\n\n<pre><code>&lt;p&gt;Main Menu&lt;/p&gt;\n&lt;ul&gt;\n{block:menu_items}\n &lt;li&gt;&lt;a href=\"{var:link}\"&gt;{var:name}&lt;/a&gt;&lt;/li&gt;\n{/block:menu_items}\n&lt;/ul&gt;\n</code></pre>\n\n<p>Merged with...</p>\n\n<pre><code> array (\n 'menu_items' =&gt; array (\n array (\n 'link' =&gt; 'home.htm',\n 'name' =&gt; 'Home'\n ),\n array (\n 'link' =&gt; 'about.htm',\n 'name' =&gt; 'About Us'\n ),\n array (\n 'link' =&gt; 'portfolio.htm',\n 'name' =&gt; 'Portfolio'\n ),\n array (\n 'link' =&gt; 'contact.htm',\n 'name' =&gt; 'Contact Us'\n )\n )\n);\n</code></pre>\n\n<p>Will create the menu...</p>\n\n<pre><code>&lt;p&gt;Main Menu&lt;/p&gt;\n&lt;ul&gt;\n &lt;li&gt;&lt;a href=\"home.htm\"&gt;Home&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"about.htm\"&gt;About Us&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"portfolio.htm\"&gt;Portfolio&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"contact.htm\"&gt;Contact Us&lt;/a&gt;&lt;/li&gt;\n&lt;/ul&gt;\n</code></pre>\n" }, { "answer_id": 1826296, "author": "Jon Winstanley", "author_id": 42106, "author_profile": "https://Stackoverflow.com/users/42106", "pm_score": 2, "selected": false, "text": "<h1>Symfony Components: Templating</h1>\n\n<p><a href=\"https://i.stack.imgur.com/ldWj4.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ldWj4.png\" alt=\"alt text\"></a><br>\n<sub>(source: <a href=\"http://components.symfony-project.org/images/components/templating/home.png\" rel=\"nofollow noreferrer\">symfony-project.org</a>)</sub> </p>\n\n<p><strong>Symfony intends on moving to a new templating system</strong> based on the lightweight PHP templating system <a href=\"http://santiance.com/twig/Framework\" rel=\"nofollow noreferrer\">twig</a>. </p>\n\n<p>The lead developer Fabien Potencier, explains the decision here: <a href=\"http://fabien.potencier.org/article/35/templating-engines-in-php-follow-up\" rel=\"nofollow noreferrer\">http://fabien.potencier.org/article/35/templating-engines-in-php-follow-up</a></p>\n\n<p>Symfony can usually be replied upon to make very informed decisions on such matters, so this framework should be <strong>something to look into</strong>.</p>\n\n<p>The component is here: <a href=\"http://components.symfony-project.org/templating/\" rel=\"nofollow noreferrer\">http://components.symfony-project.org/templating/</a></p>\n" }, { "answer_id": 16573170, "author": "Angie Rabelero", "author_id": 1306041, "author_profile": "https://Stackoverflow.com/users/1306041", "pm_score": 1, "selected": false, "text": "<p>If is just to apply a CSS style, why don't you use the :nth-of-type(odd) selector.</p>\n\n<p>For example:\n li:nth-of-type(odd) {\n background: #f2f6f8;\n background: linear-gradient(top, #f2f6f8 0%, #e0eff9 100%);\n }</p>\n\n<p><a href=\"http://jsfiddle.net/melonangie/nU7qK/\" rel=\"nofollow\">http://jsfiddle.net/melonangie/nU7qK/</a><code>enter code here</code></p>\n" }, { "answer_id": 18478585, "author": "Dave C", "author_id": 1664439, "author_profile": "https://Stackoverflow.com/users/1664439", "pm_score": 0, "selected": false, "text": "<pre><code>&lt;?php\n define ('CRLF', \"\\r\\n\");\n $persons = array('John', 'Jack', 'Jill', 'Jason');\n\n $color = 'white'; // Init $color for striped list\n $ho = '&lt;UL&gt;' . CRLF; // Start HTML Output variable\n foreach ($persons as $name)\n {\n $ho .= ' &lt;li class=\"' . $color . '\"&gt;' . $name . '&lt;/li&gt;' . CRLF;\n $color = ($color == 'white') ? 'grey' : 'white'; // if white, make it grey else white\n }\n $ho .= '&lt;/ul&gt;' . CRLF;\n echo $ho;\n?&gt;\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163834", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20538/" ]
What's the most elegant templating (preferably in pure PHP!) solution you've seen? Specifically i'm interested in handling: 1. Detecting in a repeating block whether it's the first or last element 2. Easy handling of odd/even cases, like a zebra striped table, or similar 3. Other modulos logic, where you'd do something every n'th time. I'm looking for something that makes this less of a pain: ``` <?php $persons = array('John', 'Jack', 'Jill', 'Jason'); ?> <?php $i = 0; ?> <?php if (isset($persons)): ?> <ul> <?php foreach ($persons as $name): ?> <li class="<?= ($i++ % 2 === 0) ? 'odd' : 'even' ?>"><?= $name ?></li> <?php endforeach ?> </ul> <?php endif ?> ``` Does it really take the mess above to create something like this below? ``` <ul> <li class="odd">John</li> <li class="even">Jack</li> <li class="odd">Jill</li> <li class="even">Jason</li> </ul> ``` Is it only me that find the above near hideous? All those starting and closing of php-tags makes me cringe.
You don't need to open the tags more than once. You can also make a function out of it if you do the same thing multiple times: ``` <?php function makeul($items, $classes) { $c = count($classes); $out = ""; if (isset($items) && count($items) > 0) { $out = "<ul>\n"; foreach ($items as $item) { $out .= "\t<li class=\"" . $classes[$i++%$c] . "\">$item</li>\n"; } $out .= "</ul>\n"; } return $out; } ?> other page content <?php $persons = array('John', 'Jack', 'Jill', 'Jason'); $classes = array('odd', 'even'); print makeul($persons, $classes); ?> ``` Also, if you don't mind using Javascript, [Jquery](http://jquery.com/) makes things done mod 2 pretty easy (e.g., for zebra striping a table): ``` $("tr:odd").addClass("odd"); $("tr:even").addClass("even"); ```
163,887
<p>Suppose I have a "tags" table with two columns: <strong>tagid</strong> and <strong>contentid</strong>. Each row represents a tag assigned to a piece of content. I want a query that will give me the contentid of every piece of content which is tagged with tagids 334, 338, and 342.</p> <p>The "easy" way to do this would be (<em>pseudocode</em>):</p> <pre><code>select contentid from tags where tagid = 334 and contentid in ( select contentid from tags where tagid = 338 and contentid in ( select contentid from tags where tagid = 342 ) ) </code></pre> <p>However, my gut tells me that there's a better, faster, more extensible way to do this. For example, what if I needed to find the intersection of 12 tags? This could quickly get horrendous. Any ideas?</p> <p><strong>EDIT</strong>: Turns out that this is also covered in <a href="http://weblogs.sqlteam.com/jeffs/jeffs/archive/2007/06/12/60230.aspx" rel="noreferrer">this excellent blog post</a>.</p>
[ { "answer_id": 163902, "author": "albertein", "author_id": 23020, "author_profile": "https://Stackoverflow.com/users/23020", "pm_score": 1, "selected": false, "text": "<p>The only alternative way i can think of is:</p>\n\n<pre><code>select a.contentid from tags a\ninner join tags b on a.contentid = b.contentid and b.tagid=334\ninner join tags c on a.contentid = c.contentid and c.tagid=342\nwhere a.tagid=338\n</code></pre>\n" }, { "answer_id": 163907, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 6, "selected": true, "text": "<pre><code>SELECT contentID\nFROM tags\nWHERE tagID in (334, 338, 342)\nGROUP BY contentID\nHAVING COUNT(DISTINCT tagID) = 3\n\n\n--In general\nSELECT contentID\nFROM tags\nWHERE tagID in (...) --taglist\nGROUP BY contentID\nHAVING COUNT(DISTINCT tagID) = ... --tagcount\n</code></pre>\n" }, { "answer_id": 163910, "author": "Meff", "author_id": 9647, "author_profile": "https://Stackoverflow.com/users/9647", "pm_score": -1, "selected": false, "text": "<p>What type of SQL? MS SQL Server, Oracle, MySQL?</p>\n\n<p>In SQL Server doesn't this equate to:</p>\n\n<pre><code>select contentid from tags where tagid IN (334,338,342)\n</code></pre>\n" }, { "answer_id": 163927, "author": "Bob Probst", "author_id": 12424, "author_profile": "https://Stackoverflow.com/users/12424", "pm_score": 0, "selected": false, "text": "<p>I don't know if this is better but it might be more maintainable</p>\n\n<pre><code>select contentid from tags where tagid = 334\nintersect\nselect contentid from tags where tagid = 338\nintersect\nselect contentid from tags where tagid = 342\n</code></pre>\n\n<p>You'd have to build it dynamically which wouldn't be as bad as your original solution.</p>\n" }, { "answer_id": 304314, "author": "adrian", "author_id": 39182, "author_profile": "https://Stackoverflow.com/users/39182", "pm_score": 2, "selected": false, "text": "<p>Here's a solution that has worked much faster than the for me on a very large database of objects and tags. This is an example for a three-tag intersection. It just chains many joins on the object-tag table (<code>objtags</code>) to indicate the same object and stipulates the tag IDs in the <code>WHERE</code> clause:</p>\n\n<pre><code>SELECT w0.objid\n\nFROM objtags t0\nINNER JOIN objtags t1 ON t1.objid=t0.objid\nINNER JOIN objtags t2 ON t2.objid=t1.objid\n\nWHERE t0.tagid=512\n AND t1.tagid=256\n AND t2.tagid=128\n</code></pre>\n\n<p>I have no idea why this runs faster. It was inspired by the search code in the MusicBrainz server. Doing this in Postgres, I usually get a ~8-10x speedup over the <code>HAVING COUNT(...)</code> solution.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16034/" ]
Suppose I have a "tags" table with two columns: **tagid** and **contentid**. Each row represents a tag assigned to a piece of content. I want a query that will give me the contentid of every piece of content which is tagged with tagids 334, 338, and 342. The "easy" way to do this would be (*pseudocode*): ``` select contentid from tags where tagid = 334 and contentid in ( select contentid from tags where tagid = 338 and contentid in ( select contentid from tags where tagid = 342 ) ) ``` However, my gut tells me that there's a better, faster, more extensible way to do this. For example, what if I needed to find the intersection of 12 tags? This could quickly get horrendous. Any ideas? **EDIT**: Turns out that this is also covered in [this excellent blog post](http://weblogs.sqlteam.com/jeffs/jeffs/archive/2007/06/12/60230.aspx).
``` SELECT contentID FROM tags WHERE tagID in (334, 338, 342) GROUP BY contentID HAVING COUNT(DISTINCT tagID) = 3 --In general SELECT contentID FROM tags WHERE tagID in (...) --taglist GROUP BY contentID HAVING COUNT(DISTINCT tagID) = ... --tagcount ```
163,898
<p>I would like to dynamically switch the video source in a streaming video application. However, the different video sources have unique image dimensions. I can generate individual SDP files for each video source, but I would like to combine them into a single SDP file so that the viewing client could automatically resize the display window as the video source changed. Here are two example SDP files:</p> <p>640x480.sdp:</p> <pre> v=0 o=VideoServer 305419896 9876543210 IN IP4 192.168.0.2 s=VideoStream640x480 t=0 0 c=IN IP4 192.168.0.2 m=video 8000/2 RTP/AVP 96 a=rtpmap:96 H264/90000 a=fmtp:96 packetization-mode=0; profile-level-id=4D4033; sprop-parameter-sets=Z01AM5ZkBQHtCAAAAwAIAAADAYR4wZU=,aO48gJ== a=control:trackID=1 </pre> <p>960x480.sdp:</p> <pre> v=0 o=VideoServer 305419896 9876543210 IN IP4 192.168.0.2 s=VideoStream960x480 t=0 0 c=IN IP4 192.168.0.2 m=video 8000/2 RTP/AVP 96 a=rtpmap:96 H264/90000 a=fmtp:96 packetization-mode=0; profile-level-id=4D4033; sprop-parameter-sets=J01AM5WwPA9sBAIA,KO4G8gA= a=control:trackID=1 </pre> <p>How can these individual files be combined into a single SDP file?</p>
[ { "answer_id": 171821, "author": "Stu Thompson", "author_id": 2961, "author_profile": "https://Stackoverflow.com/users/2961", "pm_score": 2, "selected": false, "text": "<p>I've gone over the RFC (<a href=\"http://www.faqs.org/rfcs/rfc2327.html\" rel=\"nofollow noreferrer\">RFC2327 - SDP: Session Description Protocol</a>) and it appears you can just concatenate the two SDP documents. The document states explicitly:</p>\n\n<blockquote>\n <p>When SDP is conveyed by SAP, only one session description is allowed per packet. When SDP is conveyed by other means, <strong>many SDP session descriptions may be concatenated together (the `v=' line indicating the start of a session description terminates the previous description)</strong>. </p>\n</blockquote>\n" }, { "answer_id": 173634, "author": "shodanex", "author_id": 11589, "author_profile": "https://Stackoverflow.com/users/11589", "pm_score": 0, "selected": false, "text": "<p>I think it depends on your decoder. If it supports parameters change inside the stream, then if you can tell the encoder to put the corresponding header when changing resolution, your decoder should automatically switch.</p>\n\n<p>What is your question exactly ?\nIs it : How can I change resolution without stopping / restarting the stream ?</p>\n\n<p>I don't Think you can tell in advance to a decoder, here are the potential resolution that you will see with some sdp magic. Either your decoder is able to understand H264 parameter change, and then you are fine, or you have to stop restart the whole thing, and then dynamic sdp is sufficient.</p>\n\n<p>I know that for example, VLC is able to detect MP4 encoding change (for example moving from variable bit rate to constant bit rate), but will crash if you change resolution\nThe only thing you can do with sdp is to combine different media description, for example with different dynamic payload type and different control-id attribute.</p>\n" }, { "answer_id": 231552, "author": "John Restrick", "author_id": 30960, "author_profile": "https://Stackoverflow.com/users/30960", "pm_score": 4, "selected": true, "text": "<p>The parameters in your two sdp examples are very close - the stream name and the sprop-parameter-sets differ. I assume you don't care about the stream name. If you need separate sprop-parameter-sets and the clients support the standard well you can use separate dynamic payload types for each resolution and have a single SDP as follows:</p>\n<pre> v=0\n o=VideoServer 305419896 9876543210 IN IP4 192.168.0.2\n s=VideoStream640x480\n t=0 0\n c=IN IP4 192.168.0.2\n m=video 8000/2 RTP/AVP 96 <B>97</B>\n a=rtpmap:96 H264/90000\n a=fmtp:96 packetization-mode=0; profile-level-id=4D4033; sprop-parameter-sets=Z01AM5ZkBQHtCAAAAwAIAAADAYR4wZU=,aO48gJ==\n a=rtpmap:<b>97</b> H264/90000\n a=fmtp:<b>97</b> packetization-mode=0; profile-level-id=4D4033; sprop-parameter-sets=J01AM5WwPA9sBAIA,KO4G8gA=\n a=control:trackID=1\n</pre>\n<p>Similar to other answers if you don't actually need the different stream names or the different sprop-parameter-sets you should be able to use your first SDP and switch format mid stream. I don't know the actual payload of H.264 or your particular decoder well enough to ensure that this will work in your applications but it is very common in videoconferencing applications to allow dynamically switching between resolutions without signaling a change or requiring a separate dynamic payload type.</p>\n<p>Although you can concatenate two SDP documents as mentioned in another answer I don't think it will help in this case. H.264 decoders can only work with a single sprop-parameter-sets parameter at a time I believe. Since both SDPs would have the same payload type, source port, etc. the receiver would not know when to use which sprop-parameter-sets parameter. UPDATE: Note some implementations get their sprops inband and not from the SDP (or only initially from the SDP). If that applies in your environment the SDP sprop-parameter-sets can be updated inband</p>\n<p>References:</p>\n<ol>\n<li><a href=\"http://www.ietf.org/rfc/rfc3984.txt\" rel=\"nofollow noreferrer\">RFC 3984 RTP Payload Format for H.264 Video</a></li>\n<li><a href=\"https://www.rfc-editor.org/rfc/rfc6184\" rel=\"nofollow noreferrer\">New proposed H.264 RTP Payload Format RFC 6184</a></li>\n<li><a href=\"https://www.rfc-editor.org/rfc/rfc4566.html\" rel=\"nofollow noreferrer\">RFC 4566 SDP: Session Description Protocol</a></li>\n</ol>\n<p>[Sorry for not giving the full cite - feel free to correct]</p>\n" }, { "answer_id": 1682388, "author": "jesup", "author_id": 105687, "author_profile": "https://Stackoverflow.com/users/105687", "pm_score": 0, "selected": false, "text": "<p>You can either do the dynamic payload change or the in-stream parameter set change, or SIP re-INVITE.</p>\n\n<p>Payload changes have a problem that if you don't control the encoder and decoder you need to make sure the other end accepts both payloads, and that they'll switch payloads correctly (and fast enough for you - there's no requirement on that).</p>\n\n<p>in-stream changes have a problem if the parameter-set packets are lost. You can use a different set of parameter sets (switch from parameter-set 1 to 2 when you change) to avoid mis-decoding - if the sets are lost, you should just get a frozen or blank picture. I'd advise retransmitting them a few times (not in too-quick succession).</p>\n\n<p>SIP re-INVITE is out-of-band and handshaked, and thus safe, but adds delay to any switch and may glitch depending on the receiver, and could be rejected.</p>\n\n<p>(Note: I'm an author of RFC 3984bis, the update to RFC 3984)</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163898", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5065/" ]
I would like to dynamically switch the video source in a streaming video application. However, the different video sources have unique image dimensions. I can generate individual SDP files for each video source, but I would like to combine them into a single SDP file so that the viewing client could automatically resize the display window as the video source changed. Here are two example SDP files: 640x480.sdp: ``` v=0 o=VideoServer 305419896 9876543210 IN IP4 192.168.0.2 s=VideoStream640x480 t=0 0 c=IN IP4 192.168.0.2 m=video 8000/2 RTP/AVP 96 a=rtpmap:96 H264/90000 a=fmtp:96 packetization-mode=0; profile-level-id=4D4033; sprop-parameter-sets=Z01AM5ZkBQHtCAAAAwAIAAADAYR4wZU=,aO48gJ== a=control:trackID=1 ``` 960x480.sdp: ``` v=0 o=VideoServer 305419896 9876543210 IN IP4 192.168.0.2 s=VideoStream960x480 t=0 0 c=IN IP4 192.168.0.2 m=video 8000/2 RTP/AVP 96 a=rtpmap:96 H264/90000 a=fmtp:96 packetization-mode=0; profile-level-id=4D4033; sprop-parameter-sets=J01AM5WwPA9sBAIA,KO4G8gA= a=control:trackID=1 ``` How can these individual files be combined into a single SDP file?
The parameters in your two sdp examples are very close - the stream name and the sprop-parameter-sets differ. I assume you don't care about the stream name. If you need separate sprop-parameter-sets and the clients support the standard well you can use separate dynamic payload types for each resolution and have a single SDP as follows: ``` v=0 o=VideoServer 305419896 9876543210 IN IP4 192.168.0.2 s=VideoStream640x480 t=0 0 c=IN IP4 192.168.0.2 m=video 8000/2 RTP/AVP 96 **97** a=rtpmap:96 H264/90000 a=fmtp:96 packetization-mode=0; profile-level-id=4D4033; sprop-parameter-sets=Z01AM5ZkBQHtCAAAAwAIAAADAYR4wZU=,aO48gJ== a=rtpmap:**97** H264/90000 a=fmtp:**97** packetization-mode=0; profile-level-id=4D4033; sprop-parameter-sets=J01AM5WwPA9sBAIA,KO4G8gA= a=control:trackID=1 ``` Similar to other answers if you don't actually need the different stream names or the different sprop-parameter-sets you should be able to use your first SDP and switch format mid stream. I don't know the actual payload of H.264 or your particular decoder well enough to ensure that this will work in your applications but it is very common in videoconferencing applications to allow dynamically switching between resolutions without signaling a change or requiring a separate dynamic payload type. Although you can concatenate two SDP documents as mentioned in another answer I don't think it will help in this case. H.264 decoders can only work with a single sprop-parameter-sets parameter at a time I believe. Since both SDPs would have the same payload type, source port, etc. the receiver would not know when to use which sprop-parameter-sets parameter. UPDATE: Note some implementations get their sprops inband and not from the SDP (or only initially from the SDP). If that applies in your environment the SDP sprop-parameter-sets can be updated inband References: 1. [RFC 3984 RTP Payload Format for H.264 Video](http://www.ietf.org/rfc/rfc3984.txt) 2. [New proposed H.264 RTP Payload Format RFC 6184](https://www.rfc-editor.org/rfc/rfc6184) 3. [RFC 4566 SDP: Session Description Protocol](https://www.rfc-editor.org/rfc/rfc4566.html) [Sorry for not giving the full cite - feel free to correct]
163,900
<p>I'm putting together a little tool that some business people can run on their local filesystems, since we don't want to setup a host for it.</p> <p>Basically, its just HTML + Javascript (using jQuery) to pull some reports using REST from a 3rd party.</p> <p>The problem is, FF3 and IE don't allow the ajax call, I get:</p> <pre><code>Access to restricted URI denied" code: "1012 </code></pre> <p>Obviously its an XSS issue...how do I work around it? The data returned is in XML format.</p> <p>I was trying to do it this way:</p> <pre><code>$.get(productUrl, function (data){ alert (data); }); </code></pre> <p><strong>EDIT</strong>: To be clear...I'm not setting up an internal host for this(Way to much red tape), and we CANNOT host this externally due to the data being retrieved.</p> <p><strong>EDIT #2</strong>: A little testing shows that I can use an IFRAME to make the request. Does anyone know if there any downsides to using a hidden IFRAME?</p>
[ { "answer_id": 163950, "author": "Greg", "author_id": 13009, "author_profile": "https://Stackoverflow.com/users/13009", "pm_score": -1, "selected": false, "text": "<p>If you have Python installed, a webserver to serve files can be as simple as </p>\n\n<pre><code>python -c “import SimpleHTTPServer;SimpleHTTPServer.test()”\n</code></pre>\n\n<p><strong>Edit:</strong> Original poster can't use this approach, but in general I think this is the way to solve this particular problem for future users with this issue.</p>\n" }, { "answer_id": 165154, "author": "Chris Lundie", "author_id": 20685, "author_profile": "https://Stackoverflow.com/users/20685", "pm_score": 3, "selected": true, "text": "<p>In a similar situation, my solution was to use Mark Of The Web, which is a special HTML comment that IE recognizes. It places the page in a different security zone.</p>\n\n<p>Reference: <a href=\"http://msdn.microsoft.com/en-us/library/ms537628(VS.85).aspx\" rel=\"nofollow noreferrer\">MSDN</a></p>\n" }, { "answer_id": 166502, "author": "Morgan ARR Allen", "author_id": 22474, "author_profile": "https://Stackoverflow.com/users/22474", "pm_score": -1, "selected": false, "text": "<p>Do you control the server providing the data? If so you can setup a callback. The basic idea is you have a function in the script that handles incoming data (in your case an XML string). Then the server responds to the request with a JavaScript snippet of your callback function with the string as the argument. And instead of using AJAX, you add a new script tag to the page. This is the basis for JSONP. It looks something like this.</p>\n\n<p>local page.</p>\n\n<pre><code>&lt;script&gt;\n function callback(str) {\n alert(str);\n }\n function makeRequest(param) {\n var s = document.createElement('script');\n s.src = 'http://serveranywhere/script.bla?' + params;\n document.getElementsByTagName[0].appendChild(s);\n }\n&lt;/script&gt;\n</code></pre>\n\n<p>remote server returns</p>\n\n<pre><code>callback('&lt;xml&gt;&lt;that&gt;&lt;does&gt;&lt;something&gt;&lt;/something&gt;&lt;/does&gt;&lt;/that&gt;&lt;/xml&gt;');\n</code></pre>\n\n<p>now when the script is added to the page, the function callback will be executed you the string you provide. And jQuery call do all of this for you using JSONP in the $.ajax call. Hope this helps.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163900", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ]
I'm putting together a little tool that some business people can run on their local filesystems, since we don't want to setup a host for it. Basically, its just HTML + Javascript (using jQuery) to pull some reports using REST from a 3rd party. The problem is, FF3 and IE don't allow the ajax call, I get: ``` Access to restricted URI denied" code: "1012 ``` Obviously its an XSS issue...how do I work around it? The data returned is in XML format. I was trying to do it this way: ``` $.get(productUrl, function (data){ alert (data); }); ``` **EDIT**: To be clear...I'm not setting up an internal host for this(Way to much red tape), and we CANNOT host this externally due to the data being retrieved. **EDIT #2**: A little testing shows that I can use an IFRAME to make the request. Does anyone know if there any downsides to using a hidden IFRAME?
In a similar situation, my solution was to use Mark Of The Web, which is a special HTML comment that IE recognizes. It places the page in a different security zone. Reference: [MSDN](http://msdn.microsoft.com/en-us/library/ms537628(VS.85).aspx)
163,994
<p>I have a very large table (8gb) with information about files, and i need to run a report against it that would would look something like this:</p> <pre><code>(select * from fs_walk_scan where file_path like '\\\\server1\\groot$\\%' order by file_size desc limit 0,30) UNION ALL (select * from fs_walk_scan where file_path like '\\\\server1\\hroot$\\%' order by file_size desc limit 0,30) UNION ALL (select * from fs_walk_scan where file_path like '\\\\server1\\iroot$\\%' order by file_size desc limit 0,30) UNION ALL (select * from fs_walk_scan where file_path like '\\\\server2\\froot$\\%' order by file_size desc limit 0,30) UNION ALL (select * from fs_walk_scan where file_path like '\\\\server2\\groot$\\%' order by file_size desc limit 0,30) UNION ALL (select * from fs_walk_scan where file_path like '\\\\server3\\hroot$\\%' order by file_size desc limit 0,30) UNION ALL (select * from fs_walk_scan where file_path like '\\\\server4\\iroot$\\%' order by file_size desc limit 0,30) UNION ALL (select * from fs_walk_scan where file_path like '\\\\server5\\iroot$\\%' order by file_size desc limit 0,30) [...] order by substring_index(file_path,'\\',4), file_size desc </code></pre> <p>This method accomplishes what I need to do: Get a list of the 30 biggest files for each volume. However, this is deathly slow, and the 'like' searches are hardcoded even though they are sitting in another table and can be gotten that way.</p> <p>What I'm looking for is a way to do this without going through the huge table several times. Anyone have any ideas?</p> <p>Thanks.</p> <p>P.S. I cant change the structure of the huge source table in any way.</p> <p>Update: There are indexes on file_path and file_size, but each one of those sub(?)queries still takes about 10 mins, and I have to do 22 minimum.</p>
[ { "answer_id": 164007, "author": "bobwienholt", "author_id": 24257, "author_profile": "https://Stackoverflow.com/users/24257", "pm_score": 2, "selected": false, "text": "<p>What kind of indexes do you have on that table? This index:</p>\n\n<p>CREATE INDEX fs_search_idx ON fs_walk_scan(file_path, file_size desc)</p>\n\n<p>would speed this query up significantly... if you don't already have one like it.</p>\n\n<p>Update:</p>\n\n<p>You said there are already indexes on file_path and file_size... are they individual indexes? Or is there one single index with both columns indexed together? The difference would be huge for this query. Even with 22 subqueries, if indexed right, this should be blazing fast.</p>\n" }, { "answer_id": 164009, "author": "warren", "author_id": 4418, "author_profile": "https://Stackoverflow.com/users/4418", "pm_score": 0, "selected": false, "text": "<p>How about something like this (haven't tested it, but looks close):</p>\n\n<pre><code>select * from fs_walk_scan where file_path like '\\\\\\\\server' and file_path like 'root$\\\\%' order by file_size desc \n</code></pre>\n\n<p>This way you're doing a pair of comparisons on the individual field which will generically match what you've described. It may be possible to use a regex, too, but I've not done it.</p>\n" }, { "answer_id": 164322, "author": "dland", "author_id": 18625, "author_profile": "https://Stackoverflow.com/users/18625", "pm_score": 2, "selected": false, "text": "<p>You could use a regexp:</p>\n\n<pre><code>select * from fs_walk_scan\n where file_path regexp '^\\\\\\\\server(1\\\\[ghi]|2\\\\[fg]|3\\\\h|[45]\\\\i)root$\\\\'\n</code></pre>\n\n<p>Otherwise if you can modify your table structure, add two columns to hold the server name and base path (and index them), so that you can create a simpler query:</p>\n\n<pre><code>select * from fs_walk_scan\n where server = 'server1' and base_path in ('groot$', 'hroot$', 'iroot$')\n or server = 'server2' and base_path in ('froot$', 'groot$')\n</code></pre>\n\n<p>You can either set up a trigger to initialise the fields when you insert the record, or else do a bulk update afterwards to fill in the two extra columns.</p>\n" }, { "answer_id": 164910, "author": "bobwienholt", "author_id": 24257, "author_profile": "https://Stackoverflow.com/users/24257", "pm_score": 1, "selected": false, "text": "<p>You could do something like this... assuming fs_list has a list of your \"LIKE\" searches:</p>\n\n<pre><code>DELIMITER $$\n\nDROP PROCEDURE IF EXISTS `test`.`proc_fs_search` $$\nCREATE PROCEDURE `test`.`proc_fs_search` ()\nBEGIN\n\nDECLARE cur_path VARCHAR(255);\nDECLARE done INT DEFAULT 0;\n\n\nDECLARE list_cursor CURSOR FOR select file_path from fs_list;\n\nDECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;\n\nSET @sql_query = '';\n\nOPEN list_cursor;\n\nREPEAT\n FETCH list_cursor INTO cur_path;\n\n IF NOT done THEN\n IF @sql_query &lt;&gt; '' THEN\n SET @sql_query = CONCAT(@sql_query, ' UNION ALL ');\n END IF;\n\n SET @sql_query = CONCAT(@sql_query, ' (select * from fs_walk_scan where file_path like ''', cur_path , ''' order by file_size desc limit 0,30)');\n END IF;\n\nUNTIL done END REPEAT;\n\nSET @sql_query = CONCAT(@sql_query, ' order by file_path, file_size desc');\n\nPREPARE stmt FROM @sql_query;\nEXECUTE stmt;\nDEALLOCATE PREPARE stmt;\n\nEND $$\n\nDELIMITER ;\n</code></pre>\n" }, { "answer_id": 166408, "author": "AJ.", "author_id": 7211, "author_profile": "https://Stackoverflow.com/users/7211", "pm_score": 1, "selected": false, "text": "<p>Try this.<br>\nYou want to get every record where there are fewer than 30 records with greater file size and the same file path. </p>\n\n<pre><code>SELECT * \nFROM fs_walk_scan a\nWHERE ( SELECT COUNT(*) \n FROM fs_walk_scan b \n WHERE b.file_size &gt; a.file_size \n AND b.file_path = a.file_path\n ) &lt; 30\n</code></pre>\n\n<h2>Edit:</h2>\n\n<p>Apparently this performs like a dog. So... How about this looping syntax? </p>\n\n<pre><code>SELECT DISTINCT file_path\nINTO tmp1\nFROM fs_walk_scan a\n\nDECLARE path VARCHAR(255);\n\nSELECT MIN(file_path)\nINTO path\nFROM tmp1 \n\nWHILE path IS NOT NULL DO\n SELECT * \n FROM fs_walk_scan\n WHERE file_path = path\n ORDER BY file_size DESC\n LIMIT 0,30\n\n SELECT MIN(file_path)\n INTO path\n FROM tmp1\n WHERE file_path &gt; path \nEND WHILE\n</code></pre>\n\n<p>The idea here is to \n1. get a list of the file paths\n2. loop, doing a query for each path which will get the 30 largest file sizes. </p>\n\n<p>(I did look up the syntax, but I'm not very hot on MySQL, so appologies if it's not quite there. Feel free to edit/comment)</p>\n" }, { "answer_id": 7134821, "author": "Lambs", "author_id": 837416, "author_profile": "https://Stackoverflow.com/users/837416", "pm_score": 0, "selected": false, "text": "<p>You can use grouping and self join for achieving this.</p>\n\n<pre><code>SELECT substring_index(file_path, '\\\\', 4), file_path\nfrom fs_walk_scan as ws1\nWHERE 30&lt;= (\nselect count(*) from fs_Walk_scan as ws2\nwhere substring_index(ws2.file_path, '\\\\', 4) = substring_index(ws1.file_path, '\\\\', 4)\nand ws2.file_size &gt; ws1.file_size\nand ws2.file_path &lt;&gt; ws1.file_path)\ngroup by substring_index(file_path, '\\\\', 4)\n</code></pre>\n\n<p>It still is an O(n) query (n being number of groups) but is more flexible and shorter.</p>\n\n<p>Edit:\nAnother approach is using variables. Feasibility for your purpose will depend on how you are going to run this query.</p>\n\n<pre><code>set @idx=0; set @cur_vol=0; \nSELECT file_volume, file_path, file_size FROM (\n SELECT file_volume, file_path, file_size,\n IF(@cur_vol != a.file_volume, @idx:=1, @idx:=@idx+1) AS row_index,\n IF(@cur_vol != a.file_volume, @cur_vol:=a.file_volume, 0) AS discard\n FROM (SELECT substring_index(file_path, '\\\\', 4) as file_volume, file_path, file_size \n FROM fs_walk_scan\n ORDER BY substring_index(file_path,'\\\\',4), file_size DESC) AS a\n HAVING row_index &lt;= 30) AS b;\n</code></pre>\n\n<p>I haven't tried this code yet, but the concept of variables can be used like this for your purpose.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163994", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17785/" ]
I have a very large table (8gb) with information about files, and i need to run a report against it that would would look something like this: ``` (select * from fs_walk_scan where file_path like '\\\\server1\\groot$\\%' order by file_size desc limit 0,30) UNION ALL (select * from fs_walk_scan where file_path like '\\\\server1\\hroot$\\%' order by file_size desc limit 0,30) UNION ALL (select * from fs_walk_scan where file_path like '\\\\server1\\iroot$\\%' order by file_size desc limit 0,30) UNION ALL (select * from fs_walk_scan where file_path like '\\\\server2\\froot$\\%' order by file_size desc limit 0,30) UNION ALL (select * from fs_walk_scan where file_path like '\\\\server2\\groot$\\%' order by file_size desc limit 0,30) UNION ALL (select * from fs_walk_scan where file_path like '\\\\server3\\hroot$\\%' order by file_size desc limit 0,30) UNION ALL (select * from fs_walk_scan where file_path like '\\\\server4\\iroot$\\%' order by file_size desc limit 0,30) UNION ALL (select * from fs_walk_scan where file_path like '\\\\server5\\iroot$\\%' order by file_size desc limit 0,30) [...] order by substring_index(file_path,'\\',4), file_size desc ``` This method accomplishes what I need to do: Get a list of the 30 biggest files for each volume. However, this is deathly slow, and the 'like' searches are hardcoded even though they are sitting in another table and can be gotten that way. What I'm looking for is a way to do this without going through the huge table several times. Anyone have any ideas? Thanks. P.S. I cant change the structure of the huge source table in any way. Update: There are indexes on file\_path and file\_size, but each one of those sub(?)queries still takes about 10 mins, and I have to do 22 minimum.
What kind of indexes do you have on that table? This index: CREATE INDEX fs\_search\_idx ON fs\_walk\_scan(file\_path, file\_size desc) would speed this query up significantly... if you don't already have one like it. Update: You said there are already indexes on file\_path and file\_size... are they individual indexes? Or is there one single index with both columns indexed together? The difference would be huge for this query. Even with 22 subqueries, if indexed right, this should be blazing fast.
163,998
<p>Is there any built-in functionality for classical set operations on the java.util.Collection class? My specific implementation would be for ArrayList, but this sounds like something that should apply for all subclasses of Collection. I'm looking for something like:</p> <pre><code>ArrayList&lt;Integer&gt; setA ... ArrayList&lt;Integer&gt; setB ... ArrayList&lt;Integer&gt; setAintersectionB = setA.intersection(setB); ArrayList&lt;Integer&gt; setAminusB = setA.subtract(setB); </code></pre> <p>After some searching, I was only able to find home-grown solutions. Also, I realize I may be confusing the idea of a "Set" with the idea of a "Collection", not allowing and allowing duplicates respectively. Perhaps this is really just functionality for the Set interface?</p> <p>In the event that nobody knows of any built-in functionality, perhaps we could use this as a repository for standard practice Java set operation code? I imagine this wheel has been reinvented numerous times.</p>
[ { "answer_id": 164033, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 3, "selected": false, "text": "<p>Are you looking for <a href=\"http://java.sun.com/javase/6/docs/api/java/util/Set.html\" rel=\"nofollow noreferrer\" title=\"Set\">java.util.Set</a> interface (and its implementations HashSet and TreeSet (sorted))?<br>\nThe interface defines removeAll(Collection c) which looks like substract(), and retainAll(Collection c) which looks like intersection.</p>\n" }, { "answer_id": 164104, "author": "Benno Richters", "author_id": 3565, "author_profile": "https://Stackoverflow.com/users/3565", "pm_score": 4, "selected": false, "text": "<p>I would recommend <a href=\"https://code.google.com/p/guava-libraries/\" rel=\"nofollow noreferrer\">Google Guava</a>. The <a href=\"https://google.github.io/guava/releases/snapshot-jre/api/docs/com/google/common/collect/Sets.html\" rel=\"nofollow noreferrer\">Sets</a> class seems to have exactly what you are looking for. It has a <a href=\"https://google.github.io/guava/releases/snapshot-jre/api/docs/com/google/common/collect/Sets.html#intersection-java.util.Set-java.util.Set-\" rel=\"nofollow noreferrer\">intersection</a> method and a <a href=\"https://google.github.io/guava/releases/snapshot-jre/api/docs/com/google/common/collect/Sets.html#difference-java.util.Set-java.util.Set-\" rel=\"nofollow noreferrer\">difference</a> method.</p>\n\n<p><a href=\"http://smallwig.blogspot.com/2008/08/google-collections-presentation.html\" rel=\"nofollow noreferrer\">This presentation</a> is probably something you want to watch if you're interested. It refers to Google Collections, which was Guava's original name.</p>\n" }, { "answer_id": 164145, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 8, "selected": true, "text": "<p>Intersection is done with <code>Collection.retainAll</code>; subtraction with <code>Collection.removeAll</code>; union with <code>Collection.addAll</code>. In each case, as <code>Set</code> will act like a set and a <code>List</code> will act like a list.</p>\n\n<p>As mutable objects, they operate in place. You'll need to explicitly copy if you want to retain the original mutable object unmutated.</p>\n" }, { "answer_id": 34439881, "author": "mhstnsc", "author_id": 736533, "author_profile": "https://Stackoverflow.com/users/736533", "pm_score": 3, "selected": false, "text": "<p>For mutable operations see accepted answer.</p>\n\n<p>For an imutable variant you can do this with java 8</p>\n\n<p>subtraction</p>\n\n<pre><code>set1\n .stream()\n .filter(item-&gt; !set2.contains(item))\n .collect(Collectors.toSet())\n</code></pre>\n\n<p>intersection</p>\n\n<pre><code>set1\n .stream()\n .filter(item-&gt; set2.contains(item))\n .collect(Collectors.toSet())\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/163998", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19147/" ]
Is there any built-in functionality for classical set operations on the java.util.Collection class? My specific implementation would be for ArrayList, but this sounds like something that should apply for all subclasses of Collection. I'm looking for something like: ``` ArrayList<Integer> setA ... ArrayList<Integer> setB ... ArrayList<Integer> setAintersectionB = setA.intersection(setB); ArrayList<Integer> setAminusB = setA.subtract(setB); ``` After some searching, I was only able to find home-grown solutions. Also, I realize I may be confusing the idea of a "Set" with the idea of a "Collection", not allowing and allowing duplicates respectively. Perhaps this is really just functionality for the Set interface? In the event that nobody knows of any built-in functionality, perhaps we could use this as a repository for standard practice Java set operation code? I imagine this wheel has been reinvented numerous times.
Intersection is done with `Collection.retainAll`; subtraction with `Collection.removeAll`; union with `Collection.addAll`. In each case, as `Set` will act like a set and a `List` will act like a list. As mutable objects, they operate in place. You'll need to explicitly copy if you want to retain the original mutable object unmutated.
164,002
<p>I am writing a C library that reads a file into memory. It skips the first 54 bytes of the file (header) and then reads the remainder as data. I use fseek to determine the length of the file, and then use fread to read in the file.</p> <p>The loop runs once and then ends because the EOF is reached (no errors). At the end, bytesRead = 10624, ftell(stream) = 28726, and the buffer contains 28726 values. I expect fread to read 30,000 bytes and the file position to be 30054 when EOF is reached.</p> <p>C is not my native language so I suspect I've got a dumb beginner mistake somewhere.</p> <p>Code is as follows:</p> <pre><code>const size_t headerLen = 54; FILE * stream; errno_t ferrno = fopen_s( &amp;stream, filename.c_str(), "r" ); if(ferrno!=0) { return -1; } fseek( stream, 0L, SEEK_END ); size_t bytesTotal = (size_t)(ftell( stream )) - headerLen; //number of data bytes to read size_t bytesRead = 0; BYTE* localBuffer = new BYTE[bytesTotal]; fseek(stream,headerLen,SEEK_SET); while(!feof(stream) &amp;&amp; !ferror(stream)) { size_t result = fread(localBuffer+bytesRead,sizeof(BYTE),bytesTotal-bytesRead,stream); bytesRead+=result; } </code></pre> <hr> <p>Depending on the reference you use, it's quite apparent that adding a "b" to the mode flag is the answer. Seeking nominations for the bonehead-badge. :-)</p> <p><a href="http://www.cplusplus.com/reference/clibrary/cstdio/fopen.html" rel="noreferrer">This reference</a> talks about it in the second paragraph, second sentence (though not in their table).</p> <p><a href="http://msdn.microsoft.com/en-us/library/z5hh6ee9(VS.80).aspx" rel="noreferrer">MSDN</a> doesn't discuss the binary flag until halfway down the page.</p> <p><a href="http://www.opengroup.org/onlinepubs/009695399/functions/fopen.html" rel="noreferrer">OpenGroup</a> mentions the existance of the "b" tag, but states that it "shall have no effect".</p>
[ { "answer_id": 164012, "author": "Evan Teran", "author_id": 13430, "author_profile": "https://Stackoverflow.com/users/13430", "pm_score": 7, "selected": true, "text": "<p>perhaps it's a binary mode issue. Try opening the file with <code>\"r+b\"</code> as the mode.</p>\n\n<p><strong>EDIT</strong>: as noted in a comment <code>\"rb\"</code> is likely a better match to your original intent since <code>\"r+b\"</code> will open it for read/write and <code>\"rb\"</code> is read-only.</p>\n" }, { "answer_id": 164281, "author": "Richard Harrison", "author_id": 19624, "author_profile": "https://Stackoverflow.com/users/19624", "pm_score": 0, "selected": false, "text": "<p>Also worth noting that simply including binmode.obj into your link command will do this for you for all file opens.</p>\n" }, { "answer_id": 24431357, "author": "Kumar Pushkar", "author_id": 3779460, "author_profile": "https://Stackoverflow.com/users/3779460", "pm_score": -1, "selected": false, "text": "<p>A solution, based on the previous answers:</p>\n\n<pre><code> size_t bytesRead = 0;\n BYTE* localBuffer = new BYTE[bytesTotal];\n fseek(stream,headerLen,SEEK_SET);\n while(!feof(stream) &amp;&amp; !ferror(stream)) {\n size_t result = fread(localBuffer+bytesRead,sizeof(BYTE),bytesTotal-\n bytesRead,stream);\n bytesRead+=result;\n}\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/164002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17871/" ]
I am writing a C library that reads a file into memory. It skips the first 54 bytes of the file (header) and then reads the remainder as data. I use fseek to determine the length of the file, and then use fread to read in the file. The loop runs once and then ends because the EOF is reached (no errors). At the end, bytesRead = 10624, ftell(stream) = 28726, and the buffer contains 28726 values. I expect fread to read 30,000 bytes and the file position to be 30054 when EOF is reached. C is not my native language so I suspect I've got a dumb beginner mistake somewhere. Code is as follows: ``` const size_t headerLen = 54; FILE * stream; errno_t ferrno = fopen_s( &stream, filename.c_str(), "r" ); if(ferrno!=0) { return -1; } fseek( stream, 0L, SEEK_END ); size_t bytesTotal = (size_t)(ftell( stream )) - headerLen; //number of data bytes to read size_t bytesRead = 0; BYTE* localBuffer = new BYTE[bytesTotal]; fseek(stream,headerLen,SEEK_SET); while(!feof(stream) && !ferror(stream)) { size_t result = fread(localBuffer+bytesRead,sizeof(BYTE),bytesTotal-bytesRead,stream); bytesRead+=result; } ``` --- Depending on the reference you use, it's quite apparent that adding a "b" to the mode flag is the answer. Seeking nominations for the bonehead-badge. :-) [This reference](http://www.cplusplus.com/reference/clibrary/cstdio/fopen.html) talks about it in the second paragraph, second sentence (though not in their table). [MSDN](http://msdn.microsoft.com/en-us/library/z5hh6ee9(VS.80).aspx) doesn't discuss the binary flag until halfway down the page. [OpenGroup](http://www.opengroup.org/onlinepubs/009695399/functions/fopen.html) mentions the existance of the "b" tag, but states that it "shall have no effect".
perhaps it's a binary mode issue. Try opening the file with `"r+b"` as the mode. **EDIT**: as noted in a comment `"rb"` is likely a better match to your original intent since `"r+b"` will open it for read/write and `"rb"` is read-only.
164,085
<p>I need to execute a callback when an IFRAME has finished loading. I have no control over the content in the IFRAME, so I can't fire the callback from there.</p> <p>This IFRAME is programmaticly created, and I need to pass its data as a variable in the callback, as well as destroy the iframe.</p> <p>Any ideas?</p> <p><strong>EDIT:</strong></p> <p>Here is what I have now:</p> <pre><code>function xssRequest(url, callback) { var iFrameObj = document.createElement('IFRAME'); iFrameObj.src = url; document.body.appendChild(iFrameObj); $(iFrameObj).load(function() { document.body.removeChild(iFrameObj); callback(iFrameObj.innerHTML); }); } </code></pre> <p>This callsback before the iFrame has loaded, so the callback has no data returned.</p>
[ { "answer_id": 164151, "author": "roryf", "author_id": 270, "author_profile": "https://Stackoverflow.com/users/270", "pm_score": 0, "selected": false, "text": "<p>I've had exactly the same problem in the past and the only way I found to fix it was to add the callback into the iframe page. Of course that only works when you have control over the iframe content.</p>\n" }, { "answer_id": 204781, "author": "Pier Luigi", "author_id": 27789, "author_profile": "https://Stackoverflow.com/users/27789", "pm_score": 1, "selected": false, "text": "<p>I have a similar code in my projects that works fine.\nAdapting my code to your function, a solution could be the following:</p>\n\n<pre><code>function xssRequest(url, callback)\n{\n var iFrameObj = document.createElement('IFRAME');\n iFrameObj.id = 'myUniqueID';\n document.body.appendChild(iFrameObj); \n iFrameObj.src = url; \n\n $(iFrameObj).load(function() \n {\n callback(window['myUniqueID'].document.body.innerHTML);\n document.body.removeChild(iFrameObj);\n });\n}\n</code></pre>\n\n<p>Maybe you have an empty innerHTML because (one or both causes):\n 1. you should use it against the body element\n 2. you have removed the iframe from the your page DOM</p>\n" }, { "answer_id": 209723, "author": "Remy Sharp", "author_id": 22617, "author_profile": "https://Stackoverflow.com/users/22617", "pm_score": 6, "selected": false, "text": "<p>First up, going by the function name <em>xssRequest</em> it sounds like you're trying cross site request - which if that's right, you're not going to be able to read the contents of the iframe.</p>\n\n<p>On the other hand, if the iframe's URL is on your domain you can access the body, but I've found that if I use a timeout to remove the iframe the callback works fine:</p>\n\n<pre><code>// possibly excessive use of jQuery - but I've got a live working example in production\n$('#myUniqueID').load(function () {\n if (typeof callback == 'function') {\n callback($('body', this.contentWindow.document).html());\n }\n setTimeout(function () {$('#frameId').remove();}, 50);\n});\n</code></pre>\n" }, { "answer_id": 342991, "author": "Ryan Cook", "author_id": 43029, "author_profile": "https://Stackoverflow.com/users/43029", "pm_score": 3, "selected": false, "text": "<p>I have had to do this in cases where documents such as word docs and pdfs were being streamed to the iframe and found a solution that works pretty well. The key is handling the <code>onreadystatechanged</code> event on the iframe.</p>\n\n<p>Lets say the name of your frame is \"myIframe\". First somewhere in your code startup (I do it inline any where after the iframe) add something like this to register the event handler:</p>\n\n<pre><code>document.getElementById('myIframe').onreadystatechange = MyIframeReadyStateChanged;\n</code></pre>\n\n<p>I was not able to use an onreadystatechage attribute on the iframe, I can't remember why, but the app had to work in IE 7 and Safari 3, so that may of been a factor.</p>\n\n<p>Here is an example of a how to get the complete state:</p>\n\n<pre><code>function MyIframeReadyStateChanged()\n{\n if(document.getElementById('myIframe').readyState == 'complete')\n {\n // Do your complete stuff here.\n }\n}\n</code></pre>\n" }, { "answer_id": 1328303, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I think the load event is right. \nWhat is not right is the way you use to retreive the content from iframe content dom.</p>\n\n<p>What you need is the html of the page loaded in the iframe not the html of the iframe object.</p>\n\n<p>What you have to do is to access the content document with <code>iFrameObj.contentDocument</code>.\nThis returns the dom of the page loaded inside the iframe, if it is on the same domain of the current page.</p>\n\n<p>I would retreive the content before removing the iframe.</p>\n\n<p>I've tested in firefox and opera.</p>\n\n<p>Then i think you can retreive your data with <code>$(childDom).html()</code> or <code>$(childDom).find('some selector') ...</code></p>\n" }, { "answer_id": 2251109, "author": "allyourcode", "author_id": 62163, "author_profile": "https://Stackoverflow.com/users/62163", "pm_score": 3, "selected": false, "text": "<p>The innerHTML of your iframe is blank because your iframe tag doesn't surround any content in the parent document. In order to get the content from the page referred to by the iframe's src attribute, you need to access the iframe's contentDocument property. An exception will be thrown if the src is from a different domain though. This is a security feature that prevents you from executing arbitrary JavaScript on someone else's page, which would create a cross-site scripting vulnerability. Here is some example code the illustrates what I'm talking about:</p>\n\n<pre><code>&lt;script src=\"http://prototypejs.org/assets/2009/8/31/prototype.js\" type=\"text/javascript\"&gt;&lt;/script&gt;\n\n&lt;h1&gt;Parent&lt;/h1&gt;\n\n&lt;script type=\"text/javascript\"&gt;\nfunction on_load(iframe) {\n try {\n // Displays the first 50 chars in the innerHTML of the\n // body of the page that the iframe is showing.\n // EDIT 2012-04-17: for wider support, fallback to contentWindow.document\n var doc = iframe.contentDocument || iframe.contentWindow.document;\n alert(doc.body.innerHTML.substring(0, 50));\n } catch (e) {\n // This can happen if the src of the iframe is\n // on another domain\n alert('exception: ' + e);\n }\n}\n&lt;/script&gt;\n&lt;iframe id=\"child\" src=\"iframe_content.html\" onload=\"on_load(this)\"&gt;&lt;/iframe&gt;\n</code></pre>\n\n<p>To further the example, try using this as the content of the iframe:</p>\n\n<pre><code>&lt;h1&gt;Child&lt;/h1&gt;\n\n&lt;a href=\"http://www.google.com/\"&gt;Google&lt;/a&gt;\n\n&lt;p&gt;Use the preceeding link to change the src of the iframe\nto see what happens when the src domain is different from\nthat of the parent page&lt;/p&gt;\n</code></pre>\n" }, { "answer_id": 7370519, "author": "Automatico", "author_id": 741850, "author_profile": "https://Stackoverflow.com/users/741850", "pm_score": 2, "selected": false, "text": "<p>I had a similar problem as you. What I did is that I use something called jQuery. What you then do in the javascript code is this:</p>\n\n<pre><code>$(function(){ //this is regular jQuery code. It waits for the dom to load fully the first time you open the page.\n\n $(\"#myIframeId\").load(function(){\n callback($(\"#myIframeId\").html());\n $(\"#myIframeId\").remove();\n\n });\n\n});\n</code></pre>\n\n<p>It seems as you delete you iFrame before you grab the html from it. Now, I do see a problem with that :p</p>\n\n<p>Hope this helps :).</p>\n" }, { "answer_id": 16363322, "author": "Neo", "author_id": 405238, "author_profile": "https://Stackoverflow.com/users/405238", "pm_score": 5, "selected": false, "text": "<p>I am using jQuery and surprisingly this seems to load as I just tested and loaded a heavy page and I didn't get the alert for a few seconds until I saw the iframe load:</p>\n\n<pre><code>$('#the_iframe').load(function(){\n alert('loaded!');\n});\n</code></pre>\n\n<p>So if you don't want to use jQuery take a look at their source code and see if this function behaves differently with iframe DOM elements, I will look at it myself later as I am interested and post here. Also I only tested in the latest chrome.</p>\n" }, { "answer_id": 27396147, "author": "Nada N. Hantouli", "author_id": 2513046, "author_profile": "https://Stackoverflow.com/users/2513046", "pm_score": 3, "selected": false, "text": "<p>I wanted to hide the waiting spinner div when the i frame content is fully loaded on IE, i tried literally every solution mentioned in Stackoverflow.Com, but with nothing worked as i wanted.</p>\n\n<p>Then i had an idea, that when the i frame content is fully loaded, the $(Window ) load event might be fired. And that exactly what happened. So, i wrote this small script, and worked like magic:</p>\n\n<pre><code> $(window).load(function () {\n //alert(\"Done window ready \");\n var lblWait = document.getElementById(\"lblWait\");\n if (lblWait != null ) {\n lblWait.style.visibility = \"false\";\n document.getElementById(\"divWait\").style.display = \"none\";\n }\n });\n</code></pre>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 49486714, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>Using <code>onload</code> attrbute will solve your problem.</p>\n\n<p>Here is an example. </p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function a() {\r\nalert(\"Your iframe has been loaded\");\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;iframe src=\"https://stackoverflow.com\" onload=\"a()\"&gt;&lt;/iframe&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Is this what you want?</p>\n\n<p><a href=\"https://www.w3schools.com/tags/ev_onload.asp\" rel=\"nofollow noreferrer\">Click here</a> for more information.</p>\n" }, { "answer_id": 69694808, "author": "arafatgazi", "author_id": 15757382, "author_profile": "https://Stackoverflow.com/users/15757382", "pm_score": 2, "selected": false, "text": "<p>This function will run your callback function immediately if the iFrame is already loaded or wait until the iFrame is completely loaded.</p>\n<p>This also addresses the following issues:</p>\n<ol>\n<li><p>Chrome initializes every iFrame with an <code>about:blank</code> page which will have <code>readyState == &quot;complete&quot;</code>. Later, it will replace `about:blank with the actual iframe src value. So, the initial value of readyState will not represent the readyState of your actual iFrame. Therefore, besides checking for readyState value, this function also addresses the about:blank issue.</p>\n</li>\n<li><p><code>DOMContentLoaded</code> event doesn't work with iFrame. So it uses the <code>load</code> event for running the callback function if iFrame isn't already loaded. The <code>load</code> event is equivalent to <code>readyState == &quot;complete&quot;</code> which has been used to check whether iFrame is already loaded. So, in any scenario, the callback function will run after iFrame is fully loaded.</p>\n</li>\n<li><p>iFrame src can have redirects and therefore load a page different from the original src url. This function will also work in that scenario.</p>\n</li>\n</ol>\n<p><strong>Pass in your callback function that you want to run when the iFrame finishes loading and the <code>&lt;iframe&gt;</code> element to this function:</strong></p>\n<pre><code>function iframeReady(callback, iframeElement) {\n const iframeWindow = iframeElement.contentWindow;\n if ((iframeElement.src == &quot;about:blank&quot; || (iframeElement.src != &quot;about:blank&quot; &amp;&amp; iframeWindow.location.href != &quot;about:blank&quot;)) &amp;&amp; iframeWindow.document.readyState == &quot;complete&quot;) {\n callback();\n } else {\n iframeWindow.addEventListener(&quot;load&quot;, callback);\n }\n}\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/164085", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ]
I need to execute a callback when an IFRAME has finished loading. I have no control over the content in the IFRAME, so I can't fire the callback from there. This IFRAME is programmaticly created, and I need to pass its data as a variable in the callback, as well as destroy the iframe. Any ideas? **EDIT:** Here is what I have now: ``` function xssRequest(url, callback) { var iFrameObj = document.createElement('IFRAME'); iFrameObj.src = url; document.body.appendChild(iFrameObj); $(iFrameObj).load(function() { document.body.removeChild(iFrameObj); callback(iFrameObj.innerHTML); }); } ``` This callsback before the iFrame has loaded, so the callback has no data returned.
First up, going by the function name *xssRequest* it sounds like you're trying cross site request - which if that's right, you're not going to be able to read the contents of the iframe. On the other hand, if the iframe's URL is on your domain you can access the body, but I've found that if I use a timeout to remove the iframe the callback works fine: ``` // possibly excessive use of jQuery - but I've got a live working example in production $('#myUniqueID').load(function () { if (typeof callback == 'function') { callback($('body', this.contentWindow.document).html()); } setTimeout(function () {$('#frameId').remove();}, 50); }); ```
164,093
<p>in a C program I have an long* that I want to serialize (thus converting to chars). A long doesn't fit in a single char, and the size varies depending of the processor (can be 4 bytes or 8 bytes).</p> <p>Theres a good way to make the serialization and de-serialization? </p>
[ { "answer_id": 164115, "author": "warren", "author_id": 4418, "author_profile": "https://Stackoverflow.com/users/4418", "pm_score": 0, "selected": false, "text": "<p>If you create a char pointer that points to the beginning of the long array, when you increment through the char \"array\", you'll get 8 bits at a time. Be aware, though, that the long won't be null-terminated (necessarily, it might be), so you need to keep track where the end of it is.</p>\n\n<p>For example:</p>\n\n<pre><code>long list[MAX];\nchar *serial = list;\nint chunk = sizeof(long);\nint k;\nfor(k=0; k&lt;(MAX*chunk); k++){\n // do something with the \"char\"\n}\n</code></pre>\n" }, { "answer_id": 164116, "author": "Lev", "author_id": 7224, "author_profile": "https://Stackoverflow.com/users/7224", "pm_score": 2, "selected": true, "text": "<pre><code>long * longs;\n\n// ...\n\nint numChars = numLongs * sizeof(long);\nchar* longsAsChars = (char*) longs;\nchar* chars = malloc(numChars);\nmemcpy(chars, longsAsChars, numChars);\n</code></pre>\n" }, { "answer_id": 164125, "author": "Georg Schölly", "author_id": 24587, "author_profile": "https://Stackoverflow.com/users/24587", "pm_score": 1, "selected": false, "text": "<p>In C you can get the size of a long with</p>\n\n<pre><code>sizeof(long)\n</code></pre>\n\n<p>But if your stored long has to be transferable between multiple platforms you should serialize it always as 4 bytes. Larger numbers couldn't be read by the 4byte processor anyway.</p>\n" }, { "answer_id": 164138, "author": "user10392", "author_id": 10392, "author_profile": "https://Stackoverflow.com/users/10392", "pm_score": 2, "selected": false, "text": "<p>You are likely solving the wrong problem. You should serialize to a fixed size int, using int32_t for instance. You probably want to use this fixed size type throughout your program, or you'll have problems when a 64-bit program can't save to the smaller size (or use int64_t).</p>\n\n<p>If know you'll never have to load 64-bit saves on a 32-bit platform, then don't bother. Just write out sizeof(long) bytes to the file, and read back sizeof(long) bytes. But put a flag early in your data that indicates the source platform to avoid mistakes.</p>\n" }, { "answer_id": 164242, "author": "Richard Harrison", "author_id": 19624, "author_profile": "https://Stackoverflow.com/users/19624", "pm_score": 2, "selected": false, "text": "<p>You don't have to serialize as chars - you can fwrite as longs (to a file). To serialise to a char array invest a byte at the beginning to indicate the size of int and the byte order - you will need this later.</p>\n\n<p>i.e.</p>\n\n<pre><code>char *p = &amp;long_array[0];\n</code></pre>\n\n<p>To access the long array as char simply cast it - and multiple the length of the array by sizeof(long) to get the size in chars.</p>\n\n<p>A simple example illustrates this:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\nmain()\n{\n int aaa[10];\n int i;\n char *p;\n\n for(i=0;i&lt;sizeof(aaa)/sizeof(aaa[0]);i++)\n {\n aaa[i] = i;\n printf (\"setting aaa[%d] = %8x\\n\",i,aaa[i]);\n }\n\n aaa[9] = 0xaabbccdd;\n\n printf (\"sizeof aaa (bytes) :%d\\n\",sizeof(aaa));\n printf (\"each element of aaa bytes :%d\\n\",sizeof(aaa[0]));\n\n p = (char*) aaa;\n for(i=0;i&lt;sizeof(aaa);i++)\n printf (\"%d: %8x\\n\",i,(unsigned char)p[i]);\n}\n</code></pre>\n" }, { "answer_id": 180698, "author": "PhirePhly", "author_id": 20082, "author_profile": "https://Stackoverflow.com/users/20082", "pm_score": 2, "selected": false, "text": "<p>This is portable, but nowhere near as inefficient as using printf/scanf</p>\n\n<pre><code>void longtochar(char *buffer, unsigned long number) {\n int i;\n for (i=0; i&lt;sizeof(long); i++) {\n buffer[i] = number &amp; 0xFF; // place bottom 8 bits in char\n number = number &gt;&gt; 8; // shift down remaining bits\n }\n return; // the long is now stored in the first few (2,4,or 8) bytes of buffer\n}\n</code></pre>\n\n<p>And to unpack it again (assuming long is the same size)</p>\n\n<pre><code>long chartolong(char *buffer) {\n long number = 0;\n int i;\n for (i=sizeof(long)-1; i&gt;=0; i--) {\n number = number &lt;&lt; 8; // left shift bits in long already\n number += buffer[i]; // add in bottom 8 bits\n }\n return number;\n}\n</code></pre>\n\n<p>Do note the BIG assumption that long is the same length on both systems. Safe thing to do is #include &lt;stdint.h&gt; and use the types it provides (uint32&#95;t or uint16&#95;t).</p>\n\n<p>Also, my code has it as an unsigned long. I don't have access to a C compiler right now, so I can't confirm if it would or not would not work with signed integers. If memory serves me, the behavior of it might be undefined (though it might not matter, how I handle it).</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/164093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18403/" ]
in a C program I have an long\* that I want to serialize (thus converting to chars). A long doesn't fit in a single char, and the size varies depending of the processor (can be 4 bytes or 8 bytes). Theres a good way to make the serialization and de-serialization?
``` long * longs; // ... int numChars = numLongs * sizeof(long); char* longsAsChars = (char*) longs; char* chars = malloc(numChars); memcpy(chars, longsAsChars, numChars); ```
164,095
<p>I'm writing a DSL in Ruby to control an Arduino project I'm working on; Bardino. It's a bar monkey that will be software controlled to serve drinks. The Arduino takes commands via the serial port to tell the Arduino what pumps to turn on and for how long.</p> <p>It currently reads a recipe (see below) and prints it back out. The code for serial communications still need to be worked in as well as some other ideas that I have mentioned below.</p> <p>This is my first DSL and I'm working off of a previous example so it's very rough around the edges. Any critiques, code improvements (are there any good references for Ruby DSL best practices or idioms?) or any general comments.</p> <p>I currently have a rough draft of the DSL so a drink recipe looks like the following (<a href="http://github.com/mwilliams/barduino-tender/tree/571fb9128c02ce72b1f891d841930bf526f1432c/examples/water.rb" rel="nofollow noreferrer">Github link</a>):</p> <pre><code>desc "Simple glass of water" recipe "water" do ingredients( "Water" =&gt; 2.ounces ) end </code></pre> <p>This in turn is interpreted and currently results with the following (<a href="http://github.com/mwilliams/barduino-tender/tree/571fb9128c02ce72b1f891d841930bf526f1432c/barduino-tender.rb" rel="nofollow noreferrer">Github link</a>):</p> <pre><code>[mwilliams@Danzig barduino-tender]$ ruby barduino-tender.rb examples/water.rb Preparing: Simple glass of water Ingredients: Water: 2 ounces </code></pre> <p>This is a good start for the DSL, however, I do think it could be implemented a little bit better. Some ideas I had below:</p> <ol> <li>Defining what "ingredients" are available using the name of the ingredient and the number pump that it's connected to. Maybe using a hash? ingredients = {"water" => 1, "vodka" => 2}. This way, when an ingredient is interpreted it can either a) send the pump number over the serial port followed by the number of ounces for the Arduino to dispense b) tell the user that ingredient does not exist and abort so nothing is dispensed c) easily have the capability to change or add new ingredients if they're changed.</li> <li>Making the recipe look less code like, which is the main purpose of a DSL, maybe build a recipe builder? Using the available ingredients to prompt the user for a drink name, ingredients involved and how much?</li> </ol> <p>The Github project is <a href="http://github.com/mwilliams/barduino-tender/tree/master" rel="nofollow noreferrer">here</a>, feel free to fork and make pull requests, or post your code suggestions and examples here for other users to see. And if you're at all curious, the Arduino code, using the Ruby Arduino Development framework is <a href="http://github.com/mwilliams/barduino/tree/master" rel="nofollow noreferrer">here</a>.</p> <p><strong>Update</strong></p> <p>I modified and cleaned things up a bit to reflect Orion Edwards suggestion for a recipe. It now looks like the following.</p> <pre><code>description 'Screwdriver' do serve_in 'Highball Glass' ingredients do 2.ounces :vodka 5.ounces :orange_juice end end </code></pre> <p>I also added a hash (key being the ingredient and the value the pump number it's hooked up to). I think this provided much progress. I'll leave the question open for any further suggestions for now, but will ultimately select Orion's answer. The updated DSL code is <a href="http://github.com/mwilliams/barduino-tender/tree/master/barduino-tender.rb" rel="nofollow noreferrer">here</a>.</p>
[ { "answer_id": 164358, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 4, "selected": true, "text": "<p>Without looking into implementation details (or your github links), I'd try write a DSL like this:</p>\n\n<p>(stealing from here: <a href=\"http://supercocktails.com/1310/Long-Island-Iced-Tea-\" rel=\"nofollow noreferrer\">http://supercocktails.com/1310/Long-Island-Iced-Tea-</a>)</p>\n\n<pre><code>describe \"Long Island Iced Tea\" do\n serve_in 'Highball Glass'\n\n ingredients do\n half.ounce.of :vodka\n half.ounce.of :tequila\n half.ounce.of :light_rum\n half.ounce.of :gin\n 1.dash.of :coca_cola\n #ignoring lemon peel as how can a robot peel a lemon?\n end\n\n steps do\n add :vodka, :tequila, :light_rum, :gin\n stir :gently\n add :coca_cola\n end\nend\n</code></pre>\n\n<p>Hope that helps!</p>\n" }, { "answer_id": 165827, "author": "user24631", "author_id": 24631, "author_profile": "https://Stackoverflow.com/users/24631", "pm_score": 1, "selected": false, "text": "<p>Orion's DSL looks very nice. \nThe only change I'd possibly suggest from you \"updated\" code is</p>\n\n<ol>\n<li>Replace <code>description</code> with <code>recipe</code>. It is a more descriptive term</li>\n<li><p>Since the set of ingredients and actions is fixed, bind the ingredients to variables rather than symbols i.e you have <code>vodka = :vodka</code> defined someplace. Its is easier to say </p>\n\n<p>mix vodka, gin and triple_sec # instead of using :vodka, :gin and :triple_sec.</p></li>\n</ol>\n\n<p>anyways that's a minor nit. </p>\n" }, { "answer_id": 365747, "author": "Christian Lescuyer", "author_id": 341, "author_profile": "https://Stackoverflow.com/users/341", "pm_score": 2, "selected": false, "text": "<p>If you want the recipe to look more natural, why not (from the same recipe Orion Ewards used, thanks!):</p>\n\n<pre><code>Recipe for Long Island Iced Tea #1\nIngredients:\n 1/2 oz Vodka\n 1/2 oz Tequila\n 1/2 oz Light Rum\n 1/2 oz Gin\n 1 Dash Coca-Cola\n # ignored Twist of Lemon Peel (or Lime)\n</code></pre>\n\n<p>Then add <a href=\"http://treetop.rubyforge.org/\" rel=\"nofollow noreferrer\">Treetop</a> to the mix. You could have rules such as:</p>\n\n<pre><code>grammar Cocktail\n rule cocktail\n title ingredients\n end\n\n rule title\n 'Recipe for' S text:(.*) EOF\n end\n\n rule ingredients\n ingredient+\n end\n\n rule ingredient\n qty S liquid\n end\n# ...\nend\n</code></pre>\n\n<p>Which the treetop compiler will transform into a nice ruby module. Then:</p>\n\n<pre><code>parser = CocktailParser.new\nr = parser.parse(recipe)\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/164095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23909/" ]
I'm writing a DSL in Ruby to control an Arduino project I'm working on; Bardino. It's a bar monkey that will be software controlled to serve drinks. The Arduino takes commands via the serial port to tell the Arduino what pumps to turn on and for how long. It currently reads a recipe (see below) and prints it back out. The code for serial communications still need to be worked in as well as some other ideas that I have mentioned below. This is my first DSL and I'm working off of a previous example so it's very rough around the edges. Any critiques, code improvements (are there any good references for Ruby DSL best practices or idioms?) or any general comments. I currently have a rough draft of the DSL so a drink recipe looks like the following ([Github link](http://github.com/mwilliams/barduino-tender/tree/571fb9128c02ce72b1f891d841930bf526f1432c/examples/water.rb)): ``` desc "Simple glass of water" recipe "water" do ingredients( "Water" => 2.ounces ) end ``` This in turn is interpreted and currently results with the following ([Github link](http://github.com/mwilliams/barduino-tender/tree/571fb9128c02ce72b1f891d841930bf526f1432c/barduino-tender.rb)): ``` [mwilliams@Danzig barduino-tender]$ ruby barduino-tender.rb examples/water.rb Preparing: Simple glass of water Ingredients: Water: 2 ounces ``` This is a good start for the DSL, however, I do think it could be implemented a little bit better. Some ideas I had below: 1. Defining what "ingredients" are available using the name of the ingredient and the number pump that it's connected to. Maybe using a hash? ingredients = {"water" => 1, "vodka" => 2}. This way, when an ingredient is interpreted it can either a) send the pump number over the serial port followed by the number of ounces for the Arduino to dispense b) tell the user that ingredient does not exist and abort so nothing is dispensed c) easily have the capability to change or add new ingredients if they're changed. 2. Making the recipe look less code like, which is the main purpose of a DSL, maybe build a recipe builder? Using the available ingredients to prompt the user for a drink name, ingredients involved and how much? The Github project is [here](http://github.com/mwilliams/barduino-tender/tree/master), feel free to fork and make pull requests, or post your code suggestions and examples here for other users to see. And if you're at all curious, the Arduino code, using the Ruby Arduino Development framework is [here](http://github.com/mwilliams/barduino/tree/master). **Update** I modified and cleaned things up a bit to reflect Orion Edwards suggestion for a recipe. It now looks like the following. ``` description 'Screwdriver' do serve_in 'Highball Glass' ingredients do 2.ounces :vodka 5.ounces :orange_juice end end ``` I also added a hash (key being the ingredient and the value the pump number it's hooked up to). I think this provided much progress. I'll leave the question open for any further suggestions for now, but will ultimately select Orion's answer. The updated DSL code is [here](http://github.com/mwilliams/barduino-tender/tree/master/barduino-tender.rb).
Without looking into implementation details (or your github links), I'd try write a DSL like this: (stealing from here: <http://supercocktails.com/1310/Long-Island-Iced-Tea->) ``` describe "Long Island Iced Tea" do serve_in 'Highball Glass' ingredients do half.ounce.of :vodka half.ounce.of :tequila half.ounce.of :light_rum half.ounce.of :gin 1.dash.of :coca_cola #ignoring lemon peel as how can a robot peel a lemon? end steps do add :vodka, :tequila, :light_rum, :gin stir :gently add :coca_cola end end ``` Hope that helps!
164,102
<p>For example, suppose I have a class:</p> <pre><code>class Foo { public: std::string&amp; Name() { m_maybe_modified = true; return m_name; } const std::string&amp; Name() const { return m_name; } protected: std::string m_name; bool m_maybe_modified; }; </code></pre> <p>And somewhere else in the code, I have something like this:</p> <pre><code>Foo *a; // Do stuff... std::string name = a-&gt;Name(); // &lt;-- chooses the non-const version </code></pre> <p>Does anyone know why the compiler would choose the non-const version in this case?</p> <p>This is a somewhat contrived example, but the actual problem we are trying to solve is periodically auto-saving an object if it has changed, and the pointer must be non-const because it might be changed at some point. </p>
[ { "answer_id": 164130, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": true, "text": "<p>Two answers spring to mind:</p>\n<ol>\n<li><p>The non-const version is a closer match.</p>\n</li>\n<li><p>If it called the const overload for the non-const case, then under what circumstances would it <em>ever</em> call the non-const overload?</p>\n</li>\n</ol>\n<p>You can get it to use the other overload by casting <code>a</code> to a <code>const Foo *</code>.</p>\n<p><strong>Edit:</strong> From <a href=\"http://www.icce.rug.nl/documents/cplusplus/cplusplus07.html\" rel=\"nofollow noreferrer\">C++ Annotations</a></p>\n<blockquote>\n<p>Earlier, in section 2.5.11 the concept\nof function overloading was\nintroduced. There it noted that member\nfunctions may be overloaded merely by\ntheir const attribute. In those cases,\nthe compiler will use the member\nfunction <em><strong>matching most closely the\nconst-qualification of the object:</strong></em></p>\n</blockquote>\n" }, { "answer_id": 164139, "author": "Lev", "author_id": 7224, "author_profile": "https://Stackoverflow.com/users/7224", "pm_score": 4, "selected": false, "text": "<p>Because a is not a const pointer. Therefore, a non-const function is a closer match. Here is how you can call the const function:</p>\n\n<pre><code>const Foo* b = a;\nstd::string name = b-&gt;Name();\n</code></pre>\n\n<p>If you have both a const and a non-const overload, and want to call the const one on a non-const object, this might be an indication of bad design.</p>\n" }, { "answer_id": 164208, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 3, "selected": false, "text": "<p>The compiler does not take into account how you are using the return value in its determination; that's not part of the rules. It doesn't know if you're doing</p>\n\n<pre><code>std::string name = b-&gt;Name();\n</code></pre>\n\n<p>or</p>\n\n<pre><code>b-&gt;Name() = \"me\";\n</code></pre>\n\n<p>It has to choose the version that works in both cases.</p>\n" }, { "answer_id": 164523, "author": "Greg Rogers", "author_id": 5963, "author_profile": "https://Stackoverflow.com/users/5963", "pm_score": 2, "selected": false, "text": "<p>You can add a \"cName\" function that is equivalent to \"Name() const\". This way you can call the const version of the function without casting to a const object first.</p>\n\n<p>This is mostly useful with the new keyword auto in C++0x, which is why they are updating the library to include cbegin(), cend(), crbegin(), crend() to return const_iterator's even if the object is non-const.</p>\n\n<p>What you are doing is probably better done by having a setName() function that allows you to change the name rather than returning a reference to the underlying container and then \"maybe\" it is modified.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/164102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9876/" ]
For example, suppose I have a class: ``` class Foo { public: std::string& Name() { m_maybe_modified = true; return m_name; } const std::string& Name() const { return m_name; } protected: std::string m_name; bool m_maybe_modified; }; ``` And somewhere else in the code, I have something like this: ``` Foo *a; // Do stuff... std::string name = a->Name(); // <-- chooses the non-const version ``` Does anyone know why the compiler would choose the non-const version in this case? This is a somewhat contrived example, but the actual problem we are trying to solve is periodically auto-saving an object if it has changed, and the pointer must be non-const because it might be changed at some point.
Two answers spring to mind: 1. The non-const version is a closer match. 2. If it called the const overload for the non-const case, then under what circumstances would it *ever* call the non-const overload? You can get it to use the other overload by casting `a` to a `const Foo *`. **Edit:** From [C++ Annotations](http://www.icce.rug.nl/documents/cplusplus/cplusplus07.html) > > Earlier, in section 2.5.11 the concept > of function overloading was > introduced. There it noted that member > functions may be overloaded merely by > their const attribute. In those cases, > the compiler will use the member > function ***matching most closely the > const-qualification of the object:*** > > >
164,163
<p>When implementing Quicksort, one of the things you have to do is to choose a pivot. But when I look at pseudocode like the one below, it is not clear how I should choose the pivot. First element of list? Something else?</p> <pre><code> function quicksort(array) var list less, greater if length(array) ≤ 1 return array select and remove a pivot value pivot from array for each x in array if x ≤ pivot then append x to less else append x to greater return concatenate(quicksort(less), pivot, quicksort(greater)) </code></pre> <p>Can someone help me grasp the concept of choosing a pivot and whether or not different scenarios call for different strategies.</p>
[ { "answer_id": 164177, "author": "Kip", "author_id": 18511, "author_profile": "https://Stackoverflow.com/users/18511", "pm_score": 8, "selected": true, "text": "<p>Choosing a random pivot minimizes the chance that you will encounter worst-case O(n<sup>2</sup>) performance (always choosing first or last would cause worst-case performance for nearly-sorted or nearly-reverse-sorted data). Choosing the middle element would also be acceptable in the majority of cases.</p>\n\n<p>Also, if you are implementing this yourself, there are versions of the algorithm that work in-place (i.e. without creating two new lists and then concatenating them).</p>\n" }, { "answer_id": 164183, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 6, "selected": false, "text": "<p>It depends on your requirements. Choosing a pivot at random makes it harder to create a data set that generates O(N^2) performance. 'Median-of-three' (first, last, middle) is also a way of avoiding problems. Beware of relative performance of comparisons, though; if your comparisons are costly, then Mo3 does more comparisons than choosing (a single pivot value) at random. Database records can be costly to compare.</p>\n\n<hr>\n\n<p>Update: Pulling comments into answer.</p>\n\n<p><a href=\"https://stackoverflow.com/users/31455/mdkess\">mdkess</a> asserted:</p>\n\n<blockquote>\n <p>'Median of 3' is NOT first last middle. Choose three random indexes, and take the middle value of this. The whole point is to make sure that your choice of pivots is not deterministic - if it is, worst case data can be quite easily generated.</p>\n</blockquote>\n\n<p>To which I responded:</p>\n\n<ul>\n<li><p><a href=\"http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.39.1103\" rel=\"noreferrer\">Analysis Of Hoare's Find Algorithm With Median-Of-Three Partition</a> (1997)\nby P Kirschenhofer, H Prodinger, C Martínez supports your contention (that 'median-of-three' is three random items).</p></li>\n<li><p>There's an article described at <a href=\"http://portal.acm.org/citation.cfm?id=1176.1243&amp;coll=GUIDE&amp;dl=GUIDE&amp;CFID=20869026&amp;CFTOKEN=55062919\" rel=\"noreferrer\">portal.acm.org</a> that is about 'The Worst Case Permutation for Median-of-Three Quicksort' by Hannu Erkiö, published in The Computer Journal, Vol 27, No 3, 1984. [Update 2012-02-26: Got the text for the <a href=\"http://comjnl.oxfordjournals.org/content/27/3/276\" rel=\"noreferrer\">article</a>. Section 2 'The Algorithm' begins: '<em>By using the median of the first, middle and last elements of A[L:R], efficient partitions into parts of fairly equal sizes can be achieved in most practical situations.</em>' Thus, it is discussing the first-middle-last Mo3 approach.]</p></li>\n<li><p>Another short article that is interesting is by M. D. McIlroy, <a href=\"http://www.cs.dartmouth.edu/~doug/mdmspe.pdf\" rel=\"noreferrer\">\"A Killer Adversary for Quicksort\"</a>, published in Software-Practice and Experience, Vol. 29(0), 1–4 (0 1999). It explains how to make almost any Quicksort behave quadratically.</p></li>\n<li><p>AT&amp;T Bell Labs Tech Journal, Oct 1984 \"Theory and Practice in the Construction of a Working Sort Routine\" states \"Hoare suggested partitioning around the median of several randomly selected lines. Sedgewick [...] recommended choosing the median of the first [...] last [...] and middle\". This indicates that both techniques for 'median-of-three' are known in the literature. (Update 2014-11-23: The article appears to be available at <a href=\"http://ieeexplore.ieee.org/iel7/6731004/6771897/06771921.pdf?arnumber=6771921\" rel=\"noreferrer\">IEEE Xplore</a> or from <a href=\"http://onlinelibrary.wiley.com/doi/10.1002/j.1538-7305.1984.tb00067.x/abstract\" rel=\"noreferrer\">Wiley</a> — if you have membership or are prepared to pay a fee.)</p></li>\n<li><p><a href=\"http://www.cs.fit.edu/~pkc/classes/writing/samples/bentley93engineering.pdf\" rel=\"noreferrer\">'Engineering a Sort Function'</a> by J L Bentley and M D McIlroy, published in Software Practice and Experience, Vol 23(11), November 1993, goes into an extensive discussion of the issues, and they chose an adaptive partitioning algorithm based in part on the size of the data set. There is a lot of discussion of trade-offs for various approaches.</p></li>\n<li><p>A Google search for 'median-of-three' works pretty well for further tracking.</p></li>\n</ul>\n\n<p>Thanks for the information; I had only encountered the deterministic 'median-of-three' before.</p>\n" }, { "answer_id": 164184, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 2, "selected": false, "text": "<p>If you are sorting a random-accessible collection (like an array), it's general best to pick the physical middle item. With this, if the array is all ready sorted (or nearly sorted), the two partitions will be close to even, and you'll get the best speed.</p>\n\n<p>If you are sorting something with only linear access (like a linked-list), then it's best to choose the first item, because it's the fastest item to access. Here, however,if the list is already sorted, you're screwed -- one partition will always be null, and the other have everything, producing the worst time.</p>\n\n<p>However, for a linked-list, picking anything besides the first, will just make matters worse. It pick the middle item in a listed-list, you'd have to step through it on each partition step -- adding a O(N/2) operation which is done logN times making total time O(1.5 N *log N) and that's if we know how long the list is before we start -- usually we don't so we'd have to step all the way through to count them, then step half-way through to find the middle, then step through a third time to do the actual partition: O(2.5N * log N)</p>\n" }, { "answer_id": 164201, "author": "Joe Phillips", "author_id": 20471, "author_profile": "https://Stackoverflow.com/users/20471", "pm_score": 2, "selected": false, "text": "<p>It is entirely dependent on how your data is sorted to begin with. If you think it will be pseudo-random then your best bet is to either pick a random selection or choose the middle.</p>\n" }, { "answer_id": 164205, "author": "Chris Cudmore", "author_id": 18907, "author_profile": "https://Stackoverflow.com/users/18907", "pm_score": 5, "selected": false, "text": "<p>Heh, I just taught this class.</p>\n\n<p>There are several options.<br>\nSimple: Pick the first or last element of the range. (bad on partially sorted input)\nBetter: Pick the item in the middle of the range. (better on partially sorted input)</p>\n\n<p>However, picking any arbitrary element runs the risk of poorly partitioning the array of size n into two arrays of size 1 and n-1. If you do that often enough, your quicksort runs the risk of becoming O(n^2).</p>\n\n<p>One improvement I've seen is pick median(first, last, mid); \nIn the worst case, it can still go to O(n^2), but probabilistically, this is a rare case.</p>\n\n<p>For most data, picking the first or last is sufficient. But, if you find that you're running into worst case scenarios often (partially sorted input), the first option would be to pick the central value( Which is a statistically good pivot for partially sorted data). </p>\n\n<p>If you're still running into problems, then go the median route.</p>\n" }, { "answer_id": 237070, "author": "mindvirus", "author_id": 31455, "author_profile": "https://Stackoverflow.com/users/31455", "pm_score": 4, "selected": false, "text": "<p>Never ever choose a fixed pivot - this can be attacked to exploit your algorithm's worst case O(n<sup>2</sup>) runtime, which is just asking for trouble. Quicksort's worst case runtime occurs when partitioning results in one array of 1 element, and one array of n-1 elements. Suppose you choose the first element as your partition. If someone feeds an array to your algorithm that is in decreasing order, your first pivot will be the biggest, so everything else in the array will move to the left of it. Then when you recurse, the first element will be the biggest again, so once more you put everything to the left of it, and so on.</p>\n<p>A better technique is the <strong>median-of-3 method</strong>, where you pick three elements at random, and choose the middle. You know that the element that you choose won't be the the first or the last, but also, by the central limit theorem, the distribution of the middle element will be normal, which means that you will tend towards the middle (and hence, nlog(n) time).</p>\n<p>If you absolutely want to guarantee O(nlog(n)) runtime for the algorithm, the <strong>columns-of-5 method</strong> for finding the median of an array runs in O(n) time, which means that the recurrence equation for quicksort in the worst case will be:</p>\n<pre><code>T(n) = O(n) (find the median) + O(n) (partition) + 2T(n/2) (recurse left and right)\n</code></pre>\n<p>By the Master Theorem, this is O(nlog(n)). However, the constant factor will be huge, and if worst case performance is your primary concern, use a merge sort instead, which is only a little bit slower than quicksort on average, and guarantees O(nlog(n)) time (and will be much faster than this lame median quicksort).</p>\n<p><a href=\"https://stackoverflow.com/questions/12545795/explanation-of-the-median-of-medians-algorithm\">Explanation of the Median of Medians Algorithm</a></p>\n" }, { "answer_id": 237514, "author": "paperhorse", "author_id": 4498, "author_profile": "https://Stackoverflow.com/users/4498", "pm_score": 3, "selected": false, "text": "<p>Don't try and get too clever and combine pivoting strategies. If you combined median of 3 with random pivot by picking the median of the first, last and a random index in the middle, then you'll still be vulnerable to many of the distributions which send median of 3 quadratic (so its actually worse than plain random pivot)<p>\nE.g a pipe organ distribution (1,2,3...N/2..3,2,1) first and last will both be 1 and the random index will be some number greater than 1, taking the median gives 1 (either first or last) and you get an extermely unbalanced partitioning.</p>\n" }, { "answer_id": 5254733, "author": "Uglybb", "author_id": 652759, "author_profile": "https://Stackoverflow.com/users/652759", "pm_score": 2, "selected": false, "text": "<p>It is easier to break the quicksort into three sections doing this</p>\n\n<ol>\n<li>Exchange or swap data element function</li>\n<li>The partition function</li>\n<li>Processing the partitions</li>\n</ol>\n\n<p>It is only slightly more inefficent than one long function but is alot easier to understand.</p>\n\n<p>Code follows:</p>\n\n<pre><code>/* This selects what the data type in the array to be sorted is */\n\n#define DATATYPE long\n\n/* This is the swap function .. your job is to swap data in x &amp; y .. how depends on\ndata type .. the example works for normal numerical data types .. like long I chose\nabove */\n\nvoid swap (DATATYPE *x, DATATYPE *y){ \n DATATYPE Temp;\n\n Temp = *x; // Hold current x value\n *x = *y; // Transfer y to x\n *y = Temp; // Set y to the held old x value\n};\n\n\n/* This is the partition code */\n\nint partition (DATATYPE list[], int l, int h){\n\n int i;\n int p; // pivot element index\n int firsthigh; // divider position for pivot element\n\n // Random pivot example shown for median p = (l+h)/2 would be used\n p = l + (short)(rand() % (int)(h - l + 1)); // Random partition point\n\n swap(&amp;list[p], &amp;list[h]); // Swap the values\n firsthigh = l; // Hold first high value\n for (i = l; i &lt; h; i++)\n if(list[i] &lt; list[h]) { // Value at i is less than h\n swap(&amp;list[i], &amp;list[firsthigh]); // So swap the value\n firsthigh++; // Incement first high\n }\n swap(&amp;list[h], &amp;list[firsthigh]); // Swap h and first high values\n return(firsthigh); // Return first high\n};\n\n\n\n/* Finally the body sort */\n\nvoid quicksort(DATATYPE list[], int l, int h){\n\n int p; // index of partition \n if ((h - l) &gt; 0) {\n p = partition(list, l, h); // Partition list \n quicksort(list, l, p - 1); // Sort lower partion\n quicksort(list, p + 1, h); // Sort upper partition\n };\n};\n</code></pre>\n" }, { "answer_id": 16063456, "author": "Faizan", "author_id": 1709718, "author_profile": "https://Stackoverflow.com/users/1709718", "pm_score": 0, "selected": false, "text": "<p>Ideally the pivot should be the middle value in the entire array.\nThis will reduce the chances of getting worst case performance.</p>\n" }, { "answer_id": 19256999, "author": "Morten Kloster", "author_id": 2860123, "author_profile": "https://Stackoverflow.com/users/2860123", "pm_score": 0, "selected": false, "text": "<p>In a truly optimized implementation, the method for choosing pivot should depend on the array size - for a large array, it pays off to spend more time choosing a good pivot. Without doing a full analysis, I would guess \"middle of O(log(n)) elements\" is a good start, and this has the added bonus of not requiring any extra memory: Using tail-call on the larger partition and in-place partitioning, we use the same O(log(n)) extra memory at almost every stage of the algorithm.</p>\n" }, { "answer_id": 20391880, "author": "vivek", "author_id": 2763724, "author_profile": "https://Stackoverflow.com/users/2763724", "pm_score": 0, "selected": false, "text": "<p>Quick sort's complexity varies greatly with the selection of pivot value. for example if you always choose first element as an pivot, algorithm's complexity becomes as worst as O(n^2). here is an smart method to choose pivot element-\n1. choose the first, mid, last element of the array.\n2. compare these three numbers and find the number which is greater than one and smaller than other i.e. median.\n3. make this element as pivot element.</p>\n\n<p>choosing the pivot by this method splits the array in nearly two half and hence the complexity \nreduces to O(nlog(n)).</p>\n" }, { "answer_id": 40128196, "author": "S0lo", "author_id": 3441572, "author_profile": "https://Stackoverflow.com/users/3441572", "pm_score": 0, "selected": false, "text": "<p>On the average, Median of 3 is good for small n. Median of 5 is a bit better for larger n. The ninther, which is the \"median of three medians of three\" is even better for very large n.</p>\n\n<p>The higher you go with sampling the better you get as n increases, but the improvement dramatically slows down as you increase the samples. And you incur the overhead of sampling and sorting samples.</p>\n" }, { "answer_id": 45580322, "author": "Milesman34", "author_id": 7630331, "author_profile": "https://Stackoverflow.com/users/7630331", "pm_score": 0, "selected": false, "text": "<p>I recommend using the middle index, as it can be calculated easily.</p>\n\n<p>You can calculate it by rounding (array.length / 2).</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/164163", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20032/" ]
When implementing Quicksort, one of the things you have to do is to choose a pivot. But when I look at pseudocode like the one below, it is not clear how I should choose the pivot. First element of list? Something else? ``` function quicksort(array) var list less, greater if length(array) ≤ 1 return array select and remove a pivot value pivot from array for each x in array if x ≤ pivot then append x to less else append x to greater return concatenate(quicksort(less), pivot, quicksort(greater)) ``` Can someone help me grasp the concept of choosing a pivot and whether or not different scenarios call for different strategies.
Choosing a random pivot minimizes the chance that you will encounter worst-case O(n2) performance (always choosing first or last would cause worst-case performance for nearly-sorted or nearly-reverse-sorted data). Choosing the middle element would also be acceptable in the majority of cases. Also, if you are implementing this yourself, there are versions of the algorithm that work in-place (i.e. without creating two new lists and then concatenating them).
164,167
<p>Warning: this is the actual code generated from my system:</p> <pre><code>;WITH RESULTS AS ( SELECT 1174 AS BatchRunID, 'STATINV' AS Program, m.APPL_CD, m.ALBASE, 'CountFocusRecords' AS Measure, COUNT(*) AS Value FROM [MISWork].[SX_FOCUS_NATIVE_200806] AS m WITH(NOLOCK) INNER JOIN MISProcess.SXProcessCatalog AS cat WITH(NOLOCK) ON cat.APPL_CD = m.APPL_CD AND cat.ALBASE = m.ALBASE AND COALESCE(cat.ProcessName, 'STATINV') = 'STATINV' GROUP BY m.APPL_CD, m.ALBASE UNION SELECT 1174 AS BatchRunID, 'STATINV' AS Program, c.APPL_CD, c.ALBASE, 'CountBiminiRecords' AS Measure, COUNT(*) AS Value FROM [MISWork].[SX_STATINV] AS c WITH(NOLOCK) INNER JOIN MISProcess.SXProcessCatalog AS cat WITH(NOLOCK) ON cat.APPL_CD = c.APPL_CD AND cat.ALBASE = c.ALBASE AND COALESCE(cat.ProcessName, 'STATINV') = 'STATINV' GROUP BY c.APPL_CD, c.ALBASE UNION SELECT 1174 AS BatchRunID, 'STATINV' AS Program, m.APPL_CD, m.ALBASE, 'RecordsInFocusMissingInBimini' AS Measure, COUNT(*) AS Value FROM [MISWork].[SX_FOCUS_NATIVE_200806] AS m WITH(NOLOCK) LEFT JOIN [MISWork].[SX_STATINV] AS c WITH(NOLOCK) ON m.[YEAR] = c.[YEAR] AND m.[MONTH] = c.[MONTH] AND m.[BANK_NO] = c.[BANK_NO] AND m.[COST_CENTER] = c.[COST_CENTER] AND m.[GLACCOUNT_NO] = c.[GLACCOUNT_NO] AND m.[CUSTACCOUNT] = c.[CUSTACCOUNT] AND m.[APPL_CD] = c.[APPL_CD] AND m.[ALBASE] = c.[ALBASE] INNER JOIN MISProcess.SXProcessCatalog AS cat WITH(NOLOCK) ON cat.APPL_CD = m.APPL_CD AND cat.ALBASE = m.ALBASE AND COALESCE(cat.ProcessName, 'STATINV') = 'STATINV' WHERE c.[YEAR] IS NULL GROUP BY m.APPL_CD, m.ALBASE UNION SELECT 1174 AS BatchRunID, 'STATINV' AS Program, c.APPL_CD, c.ALBASE, 'RecordsInBiminiMissingInFocus' AS Measure, COUNT(*) AS Value FROM [MISWork].[SX_FOCUS_NATIVE_200806] AS m WITH(NOLOCK) RIGHT JOIN [MISWork].[SX_STATINV] AS c WITH(NOLOCK) ON m.[YEAR] = c.[YEAR] AND m.[MONTH] = c.[MONTH] AND m.[BANK_NO] = c.[BANK_NO] AND m.[COST_CENTER] = c.[COST_CENTER] AND m.[GLACCOUNT_NO] = c.[GLACCOUNT_NO] AND m.[CUSTACCOUNT] = c.[CUSTACCOUNT] AND m.[APPL_CD] = c.[APPL_CD] AND m.[ALBASE] = c.[ALBASE] INNER JOIN MISProcess.SXProcessCatalog AS cat WITH(NOLOCK) ON cat.APPL_CD = c.APPL_CD AND cat.ALBASE = c.ALBASE AND COALESCE(cat.ProcessName, 'STATINV') = 'STATINV' WHERE m.[YEAR] IS NULL GROUP BY c.APPL_CD, c.ALBASE ) SELECT * FROM RESULTS ORDER BY Program, APPL_CD, ALBASE, Measure </code></pre> <p>The code just sits there, no locking or blocking.</p> <p>The individual components of the UNION return in a few seconds each. The code works in general for checking the output results of all the other programs in the STAT group, but just halts for this one.</p> <p>Remove the CTE, no effect, sits there for 30 minutes/an hour, however long you care to wait before cancelling.</p> <p>Remove the UNION, and the 4 result sets return in 11 seconds, total of 19 records accross all 4 result sets.</p> <p>Run just the first two together - works fine, run just the last 2 together, also fine. First 3 together, fine, too.</p> <p>I've already modified the code to output these to a #temp table, for other requirements, so I'm just going to change it to output each to the #temp table in sequence, but I have never seen SQL just stop like that with no evidence of blocking or anything.</p>
[ { "answer_id": 164396, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 1, "selected": false, "text": "<p>Change to UNION ALL, since you'll never have dupes (the Measure column is hard coded to be different). UNION must first sort the rows, and then find dupes and eliminate.</p>\n\n<p>My real guess is it's a parallelization issue. Try adding OPTION (MAXDOP 1) at the end.</p>\n" }, { "answer_id": 216687, "author": "Brent Ozar", "author_id": 26837, "author_profile": "https://Stackoverflow.com/users/26837", "pm_score": 0, "selected": false, "text": "<p>If you can post the query execution plan in XML format, that'll help us determine what parts of the query are causing problems. In SSMS, click Query, Display Estimated Execution Plan, and when it comes up, right-click on it and save as XML.</p>\n" }, { "answer_id": 219012, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 0, "selected": false, "text": "<p>I've moved on to regression testing 200808, but the fundamental query is the same, with a different batchrunid and different known good table.</p>\n\n<pre><code>&lt;?xml version=\"1.0\"?&gt;\n&lt;ShowPlanXML xmlns=\"http://schemas.microsoft.com/sqlserver/2004/07/showplan\" Version=\"1.0\" Build=\"9.00.3239.00\"&gt;\n &lt;BatchSequence&gt;\n &lt;Batch&gt;\n &lt;Statements&gt;\n &lt;StmtSimple StatementText=\"&amp;#13;&amp;#10;;WITH RESULTS AS (&amp;#13;&amp;#10;SELECT 1251 AS BatchRunID, 'STATINV' AS Program, m.APPL_CD, m.ALBASE, 'CountFocusRecords' AS Measure, COUNT(*) AS Value&amp;#13;&amp;#10;FROM [MISWork].[SX_FOCUS_NATIVE_200808] AS m WITH(NOLOCK)&amp;#13;&amp;#10;INNER JOIN MISProcess.SXProcessCatalog AS cat WITH(NOLOCK)&amp;#13;&amp;#10;ON cat.APPL_CD = m.APPL_CD&amp;#13;&amp;#10;AND cat.ALBASE = m.ALBASE&amp;#13;&amp;#10;AND COALESCE(cat.ProcessName, 'STATINV') = 'STATINV'&amp;#13;&amp;#10;GROUP BY m.APPL_CD, m.ALBASE&amp;#13;&amp;#10;UNION&amp;#13;&amp;#10;SELECT 1251 AS BatchRunID, 'STATINV' AS Program, c.APPL_CD, c.ALBASE, 'CountBiminiRecords' AS Measure, COUNT(*) AS Value&amp;#13;&amp;#10;FROM [MISWork].[SX_STATINV] AS c WITH(NOLOCK)&amp;#13;&amp;#10;INNER JOIN MISProcess.SXProcessCatalog AS cat WITH(NOLOCK)&amp;#13;&amp;#10;ON cat.APPL_CD = c.APPL_CD&amp;#13;&amp;#10;AND cat.ALBASE = c.ALBASE&amp;#13;&amp;#10;AND COALESCE(cat.ProcessName, 'STATINV') = 'STATINV'&amp;#13;&amp;#10;GROUP BY c.APPL_CD, c.ALBASE&amp;#13;&amp;#10;UNION&amp;#13;&amp;#10;SELECT 1251 AS BatchRunID, 'STATINV' AS Program, m.APPL_CD, m.ALBASE, 'RecordsInFocusMissingInBimini' AS Measure, COUNT(*) AS Value&amp;#13;&amp;#10;FROM [MISWork].[SX_FOCUS_NATIVE_200808] AS m WITH(NOLOCK)&amp;#13;&amp;#10;LEFT JOIN [MISWork].[SX_STATINV] AS c WITH(NOLOCK)&amp;#13;&amp;#10;ON m.[YEAR] = c.[YEAR]&amp;#13;&amp;#10; AND m.[MONTH] = c.[MONTH]&amp;#13;&amp;#10; AND m.[BANK_NO] = c.[BANK_NO]&amp;#13;&amp;#10; AND m.[COST_CENTER] = c.[COST_CENTER]&amp;#13;&amp;#10; AND m.[GLACCOUNT_NO] = c.[GLACCOUNT_NO]&amp;#13;&amp;#10; AND m.[CUSTACCOUNT] = c.[CUSTACCOUNT]&amp;#13;&amp;#10; AND m.[APPL_CD] = c.[APPL_CD]&amp;#13;&amp;#10; AND m.[ALBASE] = c.[ALBASE]&amp;#13;&amp;#10;INNER JOIN MISProcess.SXProcessCatalog AS cat WITH(NOLOCK)&amp;#13;&amp;#10;ON cat.APPL_CD = m.APPL_CD&amp;#13;&amp;#10;AND cat.ALBASE = m.ALBASE&amp;#13;&amp;#10;AND COALESCE(cat.ProcessName, 'STATINV') = 'STATINV'&amp;#13;&amp;#10;WHERE c.[YEAR] IS NULL&amp;#13;&amp;#10;GROUP BY m.APPL_CD, m.ALBASE&amp;#13;&amp;#10;UNION&amp;#13;&amp;#10;SELECT 1251 AS BatchRunID, 'STATINV' AS Program, c.APPL_CD, c.ALBASE, 'RecordsInBiminiMissingInFocus' AS Measure, COUNT(*) AS Value&amp;#13;&amp;#10;FROM [MISWork].[SX_FOCUS_NATIVE_200808] AS m WITH(NOLOCK)&amp;#13;&amp;#10;RIGHT JOIN [MISWork].[SX_STATINV] AS c WITH(NOLOCK)&amp;#13;&amp;#10;ON m.[YEAR] = c.[YEAR]&amp;#13;&amp;#10; AND m.[MONTH] = c.[MONTH]&amp;#13;&amp;#10; AND m.[BANK_NO] = c.[BANK_NO]&amp;#13;&amp;#10; AND m.[COST_CENTER] = c.[COST_CENTER]&amp;#13;&amp;#10; AND m.[GLACCOUNT_NO] = c.[GLACCOUNT_NO]&amp;#13;&amp;#10; AND m.[CUSTACCOUNT] = c.[CUSTACCOUNT]&amp;#13;&amp;#10; AND m.[APPL_CD] = c.[APPL_CD]&amp;#13;&amp;#10; AND m.[ALBASE] = c.[ALBASE]&amp;#13;&amp;#10;INNER JOIN MISProcess.SXProcessCatalog AS cat WITH(NOLOCK)&amp;#13;&amp;#10;ON cat.APPL_CD = c.APPL_CD&amp;#13;&amp;#10;AND cat.ALBASE = c.ALBASE&amp;#13;&amp;#10;AND COALESCE(cat.ProcessName, 'STATINV') = 'STATINV'&amp;#13;&amp;#10;WHERE m.[YEAR] IS NULL&amp;#13;&amp;#10;GROUP BY c.APPL_CD, c.ALBASE&amp;#13;&amp;#10;) SELECT * FROM RESULTS ORDER BY Program, APPL_CD, ALBASE, Measure&amp;#13;&amp;#10;&amp;#13;&amp;#10;\" StatementId=\"1\" StatementCompId=\"1\" StatementType=\"SELECT\" StatementSubTreeCost=\"1209.5\" StatementEstRows=\"13965.1\" StatementOptmLevel=\"FULL\"&gt;\n &lt;StatementSetOptions QUOTED_IDENTIFIER=\"false\" ARITHABORT=\"true\" CONCAT_NULL_YIELDS_NULL=\"false\" ANSI_NULLS=\"false\" ANSI_PADDING=\"false\" ANSI_WARNINGS=\"false\" NUMERIC_ROUNDABORT=\"false\"/&gt;\n &lt;QueryPlan CachedPlanSize=\"504\" CompileTime=\"1244\" CompileCPU=\"1099\" CompileMemory=\"5016\"&gt;\n &lt;MissingIndexes&gt;\n &lt;MissingIndexGroup Impact=\"29.2539\"&gt;\n &lt;MissingIndex Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\"&gt;\n &lt;ColumnGroup Usage=\"EQUALITY\"&gt;\n &lt;Column Name=\"[APPL_CD]\" ColumnId=\"7\"/&gt;\n &lt;Column Name=\"[ALBASE]\" ColumnId=\"8\"/&gt;\n &lt;/ColumnGroup&gt;\n &lt;ColumnGroup Usage=\"INCLUDE\"&gt;\n &lt;Column Name=\"[YEAR]\" ColumnId=\"1\"/&gt;\n &lt;Column Name=\"[MONTH]\" ColumnId=\"2\"/&gt;\n &lt;Column Name=\"[BANK_NO]\" ColumnId=\"3\"/&gt;\n &lt;Column Name=\"[COST_CENTER]\" ColumnId=\"4\"/&gt;\n &lt;Column Name=\"[GLACCOUNT_NO]\" ColumnId=\"5\"/&gt;\n &lt;Column Name=\"[CUSTACCOUNT]\" ColumnId=\"6\"/&gt;\n &lt;/ColumnGroup&gt;\n &lt;/MissingIndex&gt;\n &lt;/MissingIndexGroup&gt;\n &lt;MissingIndexGroup Impact=\"29.6796\"&gt;\n &lt;MissingIndex Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\"&gt;\n &lt;ColumnGroup Usage=\"EQUALITY\"&gt;\n &lt;Column Name=\"[APPL_CD]\" ColumnId=\"7\"/&gt;\n &lt;Column Name=\"[ALBASE]\" ColumnId=\"8\"/&gt;\n &lt;/ColumnGroup&gt;\n &lt;/MissingIndex&gt;\n &lt;/MissingIndexGroup&gt;\n &lt;/MissingIndexes&gt;\n &lt;RelOp NodeId=\"0\" PhysicalOp=\"Parallelism\" LogicalOp=\"Gather Streams\" EstimateRows=\"13965.1\" EstimateIO=\"0\" EstimateCPU=\"0.121489\" AvgRowSize=\"45\" EstimatedTotalSubtreeCost=\"1209.5\" Parallel=\"1\" EstimateRebinds=\"0\" EstimateRewinds=\"0\"&gt;\n &lt;OutputList&gt;\n &lt;ColumnReference Column=\"Union1039\"/&gt;\n &lt;ColumnReference Column=\"Union1040\"/&gt;\n &lt;ColumnReference Column=\"Union1041\"/&gt;\n &lt;ColumnReference Column=\"Union1042\"/&gt;\n &lt;ColumnReference Column=\"Union1043\"/&gt;\n &lt;ColumnReference Column=\"Union1044\"/&gt;\n &lt;/OutputList&gt;\n &lt;Parallelism&gt;\n &lt;OrderBy&gt;\n &lt;OrderByColumn Ascending=\"1\"&gt;\n &lt;ColumnReference Column=\"Union1041\"/&gt;\n &lt;/OrderByColumn&gt;\n &lt;OrderByColumn Ascending=\"1\"&gt;\n &lt;ColumnReference Column=\"Union1042\"/&gt;\n &lt;/OrderByColumn&gt;\n &lt;OrderByColumn Ascending=\"1\"&gt;\n &lt;ColumnReference Column=\"Union1043\"/&gt;\n &lt;/OrderByColumn&gt;\n &lt;/OrderBy&gt;\n &lt;RelOp NodeId=\"1\" PhysicalOp=\"Sort\" LogicalOp=\"Sort\" EstimateRows=\"13965.1\" EstimateIO=\"0.00281532\" EstimateCPU=\"0.220682\" AvgRowSize=\"45\" EstimatedTotalSubtreeCost=\"1209.37\" Parallel=\"1\" EstimateRebinds=\"0\" EstimateRewinds=\"0\"&gt;\n &lt;OutputList&gt;\n &lt;ColumnReference Column=\"Union1039\"/&gt;\n &lt;ColumnReference Column=\"Union1040\"/&gt;\n &lt;ColumnReference Column=\"Union1041\"/&gt;\n &lt;ColumnReference Column=\"Union1042\"/&gt;\n &lt;ColumnReference Column=\"Union1043\"/&gt;\n &lt;ColumnReference Column=\"Union1044\"/&gt;\n &lt;/OutputList&gt;\n &lt;MemoryFractions Input=\"0.0191727\" Output=\"1\"/&gt;\n &lt;Sort Distinct=\"0\"&gt;\n &lt;OrderBy&gt;\n &lt;OrderByColumn Ascending=\"1\"&gt;\n &lt;ColumnReference Column=\"Union1041\"/&gt;\n &lt;/OrderByColumn&gt;\n &lt;OrderByColumn Ascending=\"1\"&gt;\n &lt;ColumnReference Column=\"Union1042\"/&gt;\n &lt;/OrderByColumn&gt;\n &lt;OrderByColumn Ascending=\"1\"&gt;\n &lt;ColumnReference Column=\"Union1043\"/&gt;\n &lt;/OrderByColumn&gt;\n &lt;/OrderBy&gt;\n &lt;RelOp NodeId=\"2\" PhysicalOp=\"Concatenation\" LogicalOp=\"Concatenation\" EstimateRows=\"13965.1\" EstimateIO=\"0\" EstimateCPU=\"0.000349132\" AvgRowSize=\"45\" EstimatedTotalSubtreeCost=\"1209.15\" Parallel=\"1\" EstimateRebinds=\"0\" EstimateRewinds=\"0\"&gt;\n &lt;OutputList&gt;\n &lt;ColumnReference Column=\"Union1039\"/&gt;\n &lt;ColumnReference Column=\"Union1040\"/&gt;\n &lt;ColumnReference Column=\"Union1041\"/&gt;\n &lt;ColumnReference Column=\"Union1042\"/&gt;\n &lt;ColumnReference Column=\"Union1043\"/&gt;\n &lt;ColumnReference Column=\"Union1044\"/&gt;\n &lt;/OutputList&gt;\n &lt;Concat&gt;\n &lt;DefinedValues&gt;\n &lt;DefinedValue&gt;\n &lt;ColumnReference Column=\"Union1039\"/&gt;\n &lt;ColumnReference Column=\"Expr1006\"/&gt;\n &lt;ColumnReference Column=\"Expr1014\"/&gt;\n &lt;ColumnReference Column=\"Expr1025\"/&gt;\n &lt;ColumnReference Column=\"Expr1036\"/&gt;\n &lt;/DefinedValue&gt;\n &lt;DefinedValue&gt;\n &lt;ColumnReference Column=\"Union1040\"/&gt;\n &lt;ColumnReference Column=\"Expr1007\"/&gt;\n &lt;ColumnReference Column=\"Expr1015\"/&gt;\n &lt;ColumnReference Column=\"Expr1026\"/&gt;\n &lt;ColumnReference Column=\"Expr1037\"/&gt;\n &lt;/DefinedValue&gt;\n &lt;DefinedValue&gt;\n &lt;ColumnReference Column=\"Union1041\"/&gt;\n &lt;ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\" Alias=\"[m]\" Column=\"APPL_CD\"/&gt;\n &lt;ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_STATINV]\" Alias=\"[c]\" Column=\"APPL_CD\"/&gt;\n &lt;ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\" Alias=\"[m]\" Column=\"APPL_CD\"/&gt;\n &lt;ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_STATINV]\" Alias=\"[c]\" Column=\"APPL_CD\"/&gt;\n &lt;/DefinedValue&gt;\n &lt;DefinedValue&gt;\n &lt;ColumnReference Column=\"Union1042\"/&gt;\n &lt;ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\" Alias=\"[m]\" Column=\"ALBASE\"/&gt;\n &lt;ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_STATINV]\" Alias=\"[c]\" Column=\"ALBASE\"/&gt;\n &lt;ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\" Alias=\"[m]\" Column=\"ALBASE\"/&gt;\n &lt;ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_STATINV]\" Alias=\"[c]\" Column=\"ALBASE\"/&gt;\n &lt;/DefinedValue&gt;\n &lt;DefinedValue&gt;\n &lt;ColumnReference Column=\"Union1043\"/&gt;\n &lt;ColumnReference Column=\"Expr1008\"/&gt;\n &lt;ColumnReference Column=\"Expr1016\"/&gt;\n &lt;ColumnReference Column=\"Expr1027\"/&gt;\n &lt;ColumnReference Column=\"Expr1038\"/&gt;\n &lt;/DefinedValue&gt;\n &lt;DefinedValue&gt;\n &lt;ColumnReference Column=\"Union1044\"/&gt;\n &lt;ColumnReference Column=\"Expr1005\"/&gt;\n &lt;ColumnReference Column=\"Expr1013\"/&gt;\n &lt;ColumnReference Column=\"Expr1024\"/&gt;\n &lt;ColumnReference Column=\"Expr1035\"/&gt;\n &lt;/DefinedValue&gt;\n &lt;/DefinedValues&gt;\n &lt;RelOp NodeId=\"4\" PhysicalOp=\"Compute Scalar\" LogicalOp=\"Compute Scalar\" EstimateRows=\"7140\" EstimateIO=\"0\" EstimateCPU=\"0.0001785\" AvgRowSize=\"42\" EstimatedTotalSubtreeCost=\"362.728\" Parallel=\"1\" EstimateRebinds=\"0\" EstimateRewinds=\"0\"&gt;\n &lt;OutputList&gt;\n &lt;ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\" Alias=\"[m]\" Column=\"APPL_CD\"/&gt;\n &lt;ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\" Alias=\"[m]\" Column=\"ALBASE\"/&gt;\n &lt;ColumnReference Column=\"Expr1005\"/&gt;\n &lt;ColumnReference Column=\"Expr1006\"/&gt;\n &lt;ColumnReference Column=\"Expr1007\"/&gt;\n &lt;ColumnReference Column=\"Expr1008\"/&gt;\n &lt;/OutputList&gt;\n &lt;ComputeScalar&gt;\n &lt;DefinedValues&gt;\n &lt;DefinedValue&gt;\n &lt;ColumnReference Column=\"Expr1006\"/&gt;\n &lt;ScalarOperator ScalarString=\"(1251)\"&gt;\n &lt;Const ConstValue=\"(1251)\"/&gt;\n &lt;/ScalarOperator&gt;\n &lt;/DefinedValue&gt;\n &lt;DefinedValue&gt;\n &lt;ColumnReference Column=\"Expr1007\"/&gt;\n &lt;ScalarOperator ScalarString=\"'STATINV'\"&gt;\n &lt;Const ConstValue=\"'STATINV'\"/&gt;\n &lt;/ScalarOperator&gt;\n &lt;/DefinedValue&gt;\n &lt;DefinedValue&gt;\n &lt;ColumnReference Column=\"Expr1008\"/&gt;\n &lt;ScalarOperator ScalarString=\"'CountFocusRecords'\"&gt;\n &lt;Const ConstValue=\"'CountFocusRecords'\"/&gt;\n &lt;/ScalarOperator&gt;\n &lt;/DefinedValue&gt;\n &lt;/DefinedValues&gt;\n &lt;RelOp NodeId=\"6\" PhysicalOp=\"Compute Scalar\" LogicalOp=\"Compute Scalar\" EstimateRows=\"7140\" EstimateIO=\"0\" EstimateCPU=\"0.0001785\" AvgRowSize=\"23\" EstimatedTotalSubtreeCost=\"362.728\" Parallel=\"1\" EstimateRebinds=\"0\" EstimateRewinds=\"0\"&gt;\n &lt;OutputList&gt;\n &lt;ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\" Alias=\"[m]\" Column=\"APPL_CD\"/&gt;\n &lt;ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\" Alias=\"[m]\" Column=\"ALBASE\"/&gt;\n &lt;ColumnReference Column=\"Expr1005\"/&gt;\n &lt;/OutputList&gt;\n &lt;ComputeScalar&gt;\n &lt;DefinedValues&gt;\n &lt;DefinedValue&gt;\n &lt;ColumnReference Column=\"Expr1005\"/&gt;\n &lt;ScalarOperator ScalarString=\"CONVERT_IMPLICIT(int,[globalagg1083],0)\"&gt;\n &lt;Convert DataType=\"int\" Style=\"0\" Implicit=\"1\"&gt;\n &lt;ScalarOperator&gt;\n &lt;Identifier&gt;\n &lt;ColumnReference Column=\"globalagg1083\"/&gt;\n &lt;/Identifier&gt;\n &lt;/ScalarOperator&gt;\n &lt;/Convert&gt;\n &lt;/ScalarOperator&gt;\n &lt;/DefinedValue&gt;\n &lt;/DefinedValues&gt;\n &lt;RelOp NodeId=\"7\" PhysicalOp=\"Hash Match\" LogicalOp=\"Aggregate\" EstimateRows=\"7140\" EstimateIO=\"0\" EstimateCPU=\"0.114864\" AvgRowSize=\"27\" EstimatedTotalSubtreeCost=\"362.728\" Parallel=\"1\" EstimateRebinds=\"0\" EstimateRewinds=\"0\"&gt;\n &lt;OutputList&gt;\n &lt;ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\" Alias=\"[m]\" Column=\"APPL_CD\"/&gt;\n &lt;ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\" Alias=\"[m]\" Column=\"ALBASE\"/&gt;\n &lt;ColumnReference Column=\"globalagg1083\"/&gt;\n &lt;/OutputList&gt;\n &lt;MemoryFractions Input=\"0.5\" Output=\"0.980827\"/&gt;\n &lt;Hash&gt;\n &lt;DefinedValues&gt;\n &lt;DefinedValue&gt;\n &lt;ColumnReference Column=\"globalagg1083\"/&gt;\n &lt;ScalarOperator ScalarString=\"SUM([partialagg1082])\"&gt;\n &lt;Aggregate Distinct=\"0\" AggType=\"SUM\"&gt;\n &lt;ScalarOperator&gt;\n &lt;Identifier&gt;\n &lt;ColumnReference Column=\"partialagg1082\"/&gt;\n &lt;/Identifier&gt;\n &lt;/ScalarOperator&gt;\n &lt;/Aggregate&gt;\n &lt;/ScalarOperator&gt;\n &lt;/DefinedValue&gt;\n &lt;/DefinedValues&gt;\n &lt;HashKeysBuild&gt;\n &lt;ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\" Alias=\"[m]\" Column=\"APPL_CD\"/&gt;\n &lt;ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\" Alias=\"[m]\" Column=\"ALBASE\"/&gt;\n &lt;/HashKeysBuild&gt;\n &lt;BuildResidual&gt;\n &lt;ScalarOperator ScalarString=\"[DUASFIN].[MISWork].[SX_FOCUS_NATIVE_200808].[APPL_CD] as [m].[APPL_CD] = [DUASFIN].[MISWork].[SX_FOCUS_NATIVE_200808].[APPL_CD] as [m].[APPL_CD] AND [DUASFIN].[MISWork].[SX_FOCUS_NATIVE_200808].[ALBASE] as [m].[ALBASE] = [DUASFIN].[MISWork].[SX_FOCUS_NATIVE_200808].[ALBASE] as [m].[ALBASE]\"&gt;\n &lt;Logical Operation=\"AND\"&gt;\n &lt;ScalarOperator&gt;\n &lt;Compare CompareOp=\"IS\"&gt;\n &lt;ScalarOperator&gt;\n &lt;Identifier&gt;\n &lt;ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\" Alias=\"[m]\" Column=\"APPL_CD\"/&gt;\n &lt;/Identifier&gt;\n &lt;/ScalarOperator&gt;\n &lt;ScalarOperator&gt;\n &lt;Identifier&gt;\n &lt;ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\" Alias=\"[m]\" Column=\"APPL_CD\"/&gt;\n &lt;/Identifier&gt;\n &lt;/ScalarOperator&gt;\n &lt;/Compare&gt;\n &lt;/ScalarOperator&gt;\n &lt;ScalarOperator&gt;\n &lt;Compare CompareOp=\"IS\"&gt;\n &lt;ScalarOperator&gt;\n &lt;Identifier&gt;\n &lt;ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\" Alias=\"[m]\" Column=\"ALBASE\"/&gt;\n &lt;/Identifier&gt;\n &lt;/ScalarOperator&gt;\n &lt;ScalarOperator&gt;\n &lt;Identifier&gt;\n &lt;ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\" Alias=\"[m]\" Column=\"ALBASE\"/&gt;\n &lt;/Identifier&gt;\n &lt;/ScalarOperator&gt;\n &lt;/Compare&gt;\n &lt;/ScalarOperator&gt;\n &lt;/Logical&gt;\n &lt;/ScalarOperator&gt;\n &lt;/BuildResidual&gt;\n &lt;RelOp NodeId=\"8\" PhysicalOp=\"Parallelism\" LogicalOp=\"Repartition Streams\" EstimateRows=\"28560\" EstimateIO=\"0\" EstimateCPU=\"0.0614707\" AvgRowSize=\"27\" EstimatedTotalSubtreeCost=\"362.613\" Parallel=\"1\" EstimateRebinds=\"0\" EstimateRewinds=\"0\"&gt;\n &lt;OutputList&gt;\n &lt;ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\" Alias=\"[m]\" Column=\"APPL_CD\"/&gt;\n &lt;ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\" Alias=\"[m]\" Column=\"ALBASE\"/&gt;\n &lt;ColumnReference Column=\"partialagg1082\"/&gt;\n &lt;/OutputList&gt;\n &lt;Parallelism PartitioningType=\"Hash\"&gt;\n &lt;PartitionColumns&gt;\n &lt;ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\" Alias=\"[m]\" Column=\"APPL_CD\"/&gt;\n &lt;ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\" Alias=\"[m]\" Column=\"ALBASE\"/&gt;\n &lt;/PartitionColumns&gt;\n &lt;RelOp NodeId=\"9\" PhysicalOp=\"Hash Match\" LogicalOp=\"Partial Aggregate\" EstimateRows=\"28560\" EstimateIO=\"0\" EstimateCPU=\"1.7277\" AvgRowSize=\"27\" EstimatedTotalSubtreeCost=\"362.551\" Parallel=\"1\" EstimateRebinds=\"0\" EstimateRewinds=\"0\"&gt;\n &lt;OutputList&gt;\n &lt;ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\" Alias=\"[m]\" Column=\"APPL_CD\"/&gt;\n &lt;ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\" Alias=\"[m]\" Column=\"ALBASE\"/&gt;\n &lt;ColumnReference Column=\"partialagg1082\"/&gt;\n &lt;/OutputList&gt;\n &lt;MemoryFractions Input=\"0\" Output=\"0\"/&gt;\n &lt;Hash&gt;\n &lt;DefinedValues&gt;\n &lt;DefinedValue&gt;\n &lt;ColumnReference Column=\"partialagg1082\"/&gt;\n &lt;ScalarOperator ScalarString=\"COUNT(*)\"&gt;\n &lt;Aggregate Distinct=\"0\" AggType=\"COUNT*\"/&gt;\n &lt;/ScalarOperator&gt;\n &lt;/DefinedValue&gt;\n &lt;/DefinedValues&gt;\n &lt;HashKeysBuild&gt;\n &lt;ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\" Alias=\"[m]\" Column=\"APPL_CD\"/&gt;\n &lt;ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\" Alias=\"[m]\" Column=\"ALBASE\"/&gt;\n &lt;/HashKeysBuild&gt;\n &lt;BuildResidual&gt;\n &lt;ScalarOperator ScalarString=\"[DUASFIN].[MISWork].[SX_FOCUS_NATIVE_200808].[APPL_CD] as [m].[APPL_CD] = [DUASFIN].[MISWork].[SX_FOCUS_NATIVE_200808].[APPL_CD] as [m].[APPL_CD] AND [DUASFIN].[MISWork].[SX_FOCUS_NATIVE_200808].[ALBASE] as [m].[ALBASE] = [DUASFIN].[MISWork].[SX_FOCUS_NATIVE_200808].[ALBASE] as [m].[ALBASE]\"&gt;\n &lt;Logical Operation=\"AND\"&gt;\n &lt;ScalarOperator&gt;\n &lt;Compare CompareOp=\"IS\"&gt;\n &lt;ScalarOperator&gt;\n &lt;Identifier&gt;\n &lt;ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\" Alias=\"[m]\" Column=\"APPL_CD\"/&gt;\n &lt;/Identifier&gt;\n &lt;/ScalarOperator&gt;\n &lt;ScalarOperator&gt;\n &lt;Identifier&gt;\n &lt;ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\" Alias=\"[m]\" Column=\"APPL_CD\"/&gt;\n &lt;/Identifier&gt;\n &lt;/ScalarOperator&gt;\n &lt;/Compare&gt;\n &lt;/ScalarOperator&gt;\n &lt;ScalarOperator&gt;\n &lt;Compare CompareOp=\"IS\"&gt;\n &lt;ScalarOperator&gt;\n &lt;Identifier&gt;\n &lt;ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\" Alias=\"[m]\" Column=\"ALBASE\"/&gt;\n &lt;/Identifier&gt;\n &lt;/ScalarOperator&gt;\n &lt;ScalarOperator&gt;\n &lt;Identifier&gt;\n &lt;ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\" Alias=\"[m]\" Column=\"ALBASE\"/&gt;\n &lt;/Identifier&gt;\n &lt;/ScalarOperator&gt;\n &lt;/Compare&gt;\n &lt;/ScalarOperator&gt;\n &lt;/Logical&gt;\n &lt;/ScalarOperator&gt;\n &lt;/BuildResidual&gt;\n &lt;RelOp NodeId=\"10\" PhysicalOp=\"Hash Match\" LogicalOp=\"Inner Join\" EstimateRows=\"879583\" EstimateIO=\"0\" EstimateCPU=\"62.0602\" AvgRowSize=\"19\" EstimatedTotalSubtreeCost=\"360.824\" Parallel=\"1\" EstimateRebinds=\"0\" EstimateRewinds=\"0\"&gt;\n &lt;OutputList&gt;\n &lt;ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\" Alias=\"[m]\" Column=\"APPL_CD\"/&gt;\n &lt;ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\" Alias=\"[m]\" Column=\"ALBASE\"/&gt;\n &lt;/OutputList&gt;\n &lt;MemoryFractions Input=\"1\" Output=\"0.5\"/&gt;\n &lt;Hash&gt;\n &lt;DefinedValues/&gt;\n &lt;HashKeysBuild&gt;\n &lt;ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISProcess]\" Table=\"[SXProcessCatalog]\" Alias=\"[cat]\" Column=\"APPL_CD\"/&gt;\n &lt;ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISProcess]\" Table=\"[SXProcessCatalog]\" Alias=\"[cat]\" Column=\"ALBASE\"/&gt;\n &lt;/HashKeysBuild&gt;\n &lt;HashKeysProbe&gt;\n &lt;ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\" Alias=\"[m]\" Column=\"APPL_CD\"/&gt;\n &lt;ColumnReference Database=\"[DUASFIN]\" Schema=\"[MISWork]\" Table=\"[SX_FOCUS_NATIVE_200808]\" Alias=\"[m]\" Column=\"ALBASE\"/&gt;\n &lt;/HashKeysProbe&gt;\n &lt;ProbeResidual&gt;\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/164167", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18255/" ]
Warning: this is the actual code generated from my system: ``` ;WITH RESULTS AS ( SELECT 1174 AS BatchRunID, 'STATINV' AS Program, m.APPL_CD, m.ALBASE, 'CountFocusRecords' AS Measure, COUNT(*) AS Value FROM [MISWork].[SX_FOCUS_NATIVE_200806] AS m WITH(NOLOCK) INNER JOIN MISProcess.SXProcessCatalog AS cat WITH(NOLOCK) ON cat.APPL_CD = m.APPL_CD AND cat.ALBASE = m.ALBASE AND COALESCE(cat.ProcessName, 'STATINV') = 'STATINV' GROUP BY m.APPL_CD, m.ALBASE UNION SELECT 1174 AS BatchRunID, 'STATINV' AS Program, c.APPL_CD, c.ALBASE, 'CountBiminiRecords' AS Measure, COUNT(*) AS Value FROM [MISWork].[SX_STATINV] AS c WITH(NOLOCK) INNER JOIN MISProcess.SXProcessCatalog AS cat WITH(NOLOCK) ON cat.APPL_CD = c.APPL_CD AND cat.ALBASE = c.ALBASE AND COALESCE(cat.ProcessName, 'STATINV') = 'STATINV' GROUP BY c.APPL_CD, c.ALBASE UNION SELECT 1174 AS BatchRunID, 'STATINV' AS Program, m.APPL_CD, m.ALBASE, 'RecordsInFocusMissingInBimini' AS Measure, COUNT(*) AS Value FROM [MISWork].[SX_FOCUS_NATIVE_200806] AS m WITH(NOLOCK) LEFT JOIN [MISWork].[SX_STATINV] AS c WITH(NOLOCK) ON m.[YEAR] = c.[YEAR] AND m.[MONTH] = c.[MONTH] AND m.[BANK_NO] = c.[BANK_NO] AND m.[COST_CENTER] = c.[COST_CENTER] AND m.[GLACCOUNT_NO] = c.[GLACCOUNT_NO] AND m.[CUSTACCOUNT] = c.[CUSTACCOUNT] AND m.[APPL_CD] = c.[APPL_CD] AND m.[ALBASE] = c.[ALBASE] INNER JOIN MISProcess.SXProcessCatalog AS cat WITH(NOLOCK) ON cat.APPL_CD = m.APPL_CD AND cat.ALBASE = m.ALBASE AND COALESCE(cat.ProcessName, 'STATINV') = 'STATINV' WHERE c.[YEAR] IS NULL GROUP BY m.APPL_CD, m.ALBASE UNION SELECT 1174 AS BatchRunID, 'STATINV' AS Program, c.APPL_CD, c.ALBASE, 'RecordsInBiminiMissingInFocus' AS Measure, COUNT(*) AS Value FROM [MISWork].[SX_FOCUS_NATIVE_200806] AS m WITH(NOLOCK) RIGHT JOIN [MISWork].[SX_STATINV] AS c WITH(NOLOCK) ON m.[YEAR] = c.[YEAR] AND m.[MONTH] = c.[MONTH] AND m.[BANK_NO] = c.[BANK_NO] AND m.[COST_CENTER] = c.[COST_CENTER] AND m.[GLACCOUNT_NO] = c.[GLACCOUNT_NO] AND m.[CUSTACCOUNT] = c.[CUSTACCOUNT] AND m.[APPL_CD] = c.[APPL_CD] AND m.[ALBASE] = c.[ALBASE] INNER JOIN MISProcess.SXProcessCatalog AS cat WITH(NOLOCK) ON cat.APPL_CD = c.APPL_CD AND cat.ALBASE = c.ALBASE AND COALESCE(cat.ProcessName, 'STATINV') = 'STATINV' WHERE m.[YEAR] IS NULL GROUP BY c.APPL_CD, c.ALBASE ) SELECT * FROM RESULTS ORDER BY Program, APPL_CD, ALBASE, Measure ``` The code just sits there, no locking or blocking. The individual components of the UNION return in a few seconds each. The code works in general for checking the output results of all the other programs in the STAT group, but just halts for this one. Remove the CTE, no effect, sits there for 30 minutes/an hour, however long you care to wait before cancelling. Remove the UNION, and the 4 result sets return in 11 seconds, total of 19 records accross all 4 result sets. Run just the first two together - works fine, run just the last 2 together, also fine. First 3 together, fine, too. I've already modified the code to output these to a #temp table, for other requirements, so I'm just going to change it to output each to the #temp table in sequence, but I have never seen SQL just stop like that with no evidence of blocking or anything.
Change to UNION ALL, since you'll never have dupes (the Measure column is hard coded to be different). UNION must first sort the rows, and then find dupes and eliminate. My real guess is it's a parallelization issue. Try adding OPTION (MAXDOP 1) at the end.
164,168
<p>If I want to construct a std::string with a line like:</p> <pre><code>std::string my_string("a\0b"); </code></pre> <p>Where i want to have three characters in the resulting string (a, null, b), I only get one. What is the proper syntax?</p>
[ { "answer_id": 164185, "author": "17 of 26", "author_id": 2284, "author_profile": "https://Stackoverflow.com/users/2284", "pm_score": 4, "selected": false, "text": "<p>I have no idea <em>why</em> you'd want to do such a thing, but try this:</p>\n\n<pre><code>std::string my_string(\"a\\0b\", 3);\n</code></pre>\n" }, { "answer_id": 164211, "author": "Jurney", "author_id": 2642, "author_profile": "https://Stackoverflow.com/users/2642", "pm_score": -1, "selected": false, "text": "<p>Almost all implementations of std::strings are null-terminated, so you probably shouldn't do this. Note that \"a\\0b\" is actually four characters long because of the automatic null terminator (a, null, b, null). If you really want to do this and break std::string's contract, you can do:</p>\n\n<pre><code>std::string s(\"aab\");\ns.at(1) = '\\0';\n</code></pre>\n\n<p>but if you do, all your friends will laugh at you, you will never find true happiness.</p>\n" }, { "answer_id": 164220, "author": "Andrew Stein", "author_id": 13029, "author_profile": "https://Stackoverflow.com/users/13029", "pm_score": 3, "selected": false, "text": "<p>The following will work...</p>\n\n<pre><code>std::string s;\ns.push_back('a');\ns.push_back('\\0');\ns.push_back('b');\n</code></pre>\n" }, { "answer_id": 164257, "author": "Doug T.", "author_id": 8123, "author_profile": "https://Stackoverflow.com/users/8123", "pm_score": 5, "selected": false, "text": "<p>If you are doing manipulation like you would with a c-style string (array of chars) consider using</p>\n\n<pre><code>std::vector&lt;char&gt;\n</code></pre>\n\n<p>You have more freedom to treat it like an array in the same manner you would treat a c-string. You can use copy() to copy into a string: </p>\n\n<pre><code>std::vector&lt;char&gt; vec(100)\nstrncpy(&amp;vec[0], \"blah blah blah\", 100);\nstd::string vecAsStr( vec.begin(), vec.end());\n</code></pre>\n\n<p>and you can use it in many of the same places you can use c-strings</p>\n\n<pre><code>printf(\"%s\" &amp;vec[0])\nvec[10] = '\\0';\nvec[11] = 'b';\n</code></pre>\n\n<p>Naturally, however, you suffer from the same problems as c-strings. You may forget your null terminal or write past the allocated space.</p>\n" }, { "answer_id": 164269, "author": "Harold Ekstrom", "author_id": 8429, "author_profile": "https://Stackoverflow.com/users/8429", "pm_score": 1, "selected": false, "text": "<p>Better to use std::vector&lt;char&gt; if this question isn't just for educational purposes.</p>\n" }, { "answer_id": 164274, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 8, "selected": true, "text": "<h3>Since C++14</h3>\n<p>we have been able to create <a href=\"https://en.cppreference.com/w/cpp/string/basic_string/operator%22%22s\" rel=\"noreferrer\">literal <code>std::string</code></a></p>\n<pre><code>#include &lt;iostream&gt;\n#include &lt;string&gt;\n\nint main()\n{\n using namespace std::string_literals;\n\n std::string s = &quot;pl-\\0-op&quot;s; // &lt;- Notice the &quot;s&quot; at the end\n // This is a std::string literal not\n // a C-String literal.\n std::cout &lt;&lt; s &lt;&lt; &quot;\\n&quot;;\n}\n</code></pre>\n<h3>Before C++14</h3>\n<p>The problem is the <code>std::string</code> constructor that takes a <code>const char*</code> assumes the input is a C-string. C-strings are <code>\\0</code> terminated and thus parsing stops when it reaches the <code>\\0</code> character.</p>\n<p>To compensate for this, you need to use the constructor that builds the string from a char array (not a C-String). This takes two parameters - a pointer to the array and a length:</p>\n<pre><code>std::string x(&quot;pq\\0rs&quot;); // Two characters because input assumed to be C-String\nstd::string x(&quot;pq\\0rs&quot;,5); // 5 Characters as the input is now a char array with 5 characters.\n</code></pre>\n<p>Note: C++ <code>std::string</code> is <strong>NOT</strong> <code>\\0</code>-terminated (as suggested in other posts). However, you can extract a pointer to an internal buffer that contains a C-String with the method <code>c_str()</code>.</p>\n<p>Also check out <a href=\"https://stackoverflow.com/questions/164168/how-do-you-construct-a-stdstring-with-an-embedded-null#164257\">Doug T's answer</a> below about using a <code>vector&lt;char&gt;</code>.</p>\n<p>Also check out <a href=\"https://stackoverflow.com/a/34723611/14065\">RiaD</a> for a C++14 solution.</p>\n" }, { "answer_id": 2175911, "author": "Dil09", "author_id": 263408, "author_profile": "https://Stackoverflow.com/users/263408", "pm_score": -1, "selected": false, "text": "<p>I know it is a long time this question has been asked. But for anyone who is having a similar problem might be interested in the following code.</p>\n\n<pre><code>CComBSTR(20,\"mystring1\\0mystring2\\0\")\n</code></pre>\n" }, { "answer_id": 12738351, "author": "anonym", "author_id": 1721734, "author_profile": "https://Stackoverflow.com/users/1721734", "pm_score": 4, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/questions/237804/user-defined-literals-in-c11-a-much-needed-addition-or-making-c-even-more-b\">What new capabilities do user-defined literals add to C++?</a> presents an elegant answer: Define</p>\n\n<pre><code>std::string operator \"\" _s(const char* str, size_t n) \n{ \n return std::string(str, n); \n}\n</code></pre>\n\n<p>then you can create your string this way:</p>\n\n<pre><code>std::string my_string(\"a\\0b\"_s);\n</code></pre>\n\n<p>or even so:</p>\n\n<pre><code>auto my_string = \"a\\0b\"_s;\n</code></pre>\n\n<p>There's an \"old style\" way:</p>\n\n<pre><code>#define S(s) s, sizeof s - 1 // trailing NUL does not belong to the string\n</code></pre>\n\n<p>then you can define</p>\n\n<pre><code>std::string my_string(S(\"a\\0b\"));\n</code></pre>\n" }, { "answer_id": 12884464, "author": "David Stone", "author_id": 852254, "author_profile": "https://Stackoverflow.com/users/852254", "pm_score": 3, "selected": false, "text": "<p>You'll have to be careful with this. If you replace 'b' with any numeric character, you will silently create the wrong string using most methods. See: <a href=\"https://stackoverflow.com/questions/10220401/c-string-literals-escape-character\">Rules for C++ string literals escape character</a>.</p>\n\n<p>For example, I dropped this innocent looking snippet in the middle of a program</p>\n\n<pre><code>// Create '\\0' followed by '0' 40 times ;)\nstd::string str(\"\\00\\00\\00\\00\\00\\00\\00\\00\\00\\00\\00\\00\\00\\00\\00\\00\\00\\00\\00\\00\\00\\00\\00\\00\\00\\00\\00\\00\\00\\00\\00\\00\\00\\00\\00\\00\\00\\00\\00\\00\", 80);\nstd::cerr &lt;&lt; \"Entering loop.\\n\";\nfor (char &amp; c : str) {\n std::cerr &lt;&lt; c;\n // 'Q' is way cooler than '\\0' or '0'\n c = 'Q';\n}\nstd::cerr &lt;&lt; \"\\n\";\nfor (char &amp; c : str) {\n std::cerr &lt;&lt; c;\n}\nstd::cerr &lt;&lt; \"\\n\";\n</code></pre>\n\n<p>Here is what this program output for me:</p>\n\n<pre><code>Entering loop.\nEntering loop.\n\nvector::_M_emplace_ba\nQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ\n</code></pre>\n\n<p>That was my first print statement twice, several non-printing characters, followed by a newline, followed by something in internal memory, which I just overwrote (and then printed, showing that it has been overwritten). Worst of all, even compiling this with <a href=\"https://stackoverflow.com/questions/5088460/flags-to-enable-thorough-and-verbose-g-warnings/9862800#9862800\">thorough and verbose gcc warnings</a> gave me no indication of something being wrong, and running the program through valgrind didn't complain about any improper memory access patterns. In other words, it's completely undetectable by modern tools.</p>\n\n<p>You can get this same problem with the much simpler <code>std::string(\"0\", 100);</code>, but the example above is a little trickier, and thus harder to see what's wrong.</p>\n\n<p>Fortunately, C++11 gives us a good solution to the problem using initializer list syntax. This saves you from having to specify the number of characters (which, as I showed above, you can do incorrectly), and avoids combining escaped numbers. <code>std::string str({'a', '\\0', 'b'})</code> is safe for any string content, unlike versions that take an array of <code>char</code> and a size.</p>\n" }, { "answer_id": 34723611, "author": "RiaD", "author_id": 768110, "author_profile": "https://Stackoverflow.com/users/768110", "pm_score": 2, "selected": false, "text": "<p>In C++14 you now may use literals</p>\n\n<pre><code>using namespace std::literals::string_literals;\nstd::string s = \"a\\0b\"s;\nstd::cout &lt;&lt; s.size(); // 3\n</code></pre>\n" }, { "answer_id": 40514043, "author": "Kyle Strand", "author_id": 1858225, "author_profile": "https://Stackoverflow.com/users/1858225", "pm_score": 1, "selected": false, "text": "<p>anonym's answer is excellent, but there's a non-macro solution in C++98 as well:</p>\n\n<pre><code>template &lt;size_t N&gt;\nstd::string RawString(const char (&amp;ch)[N])\n{\n return std::string(ch, N-1); // Again, exclude trailing `null`\n}\n</code></pre>\n\n<p>With this function, <code>RawString(/* literal */)</code> will produce the same string as <code>S(/* literal */)</code>:</p>\n\n<pre><code>std::string my_string_t(RawString(\"a\\0b\"));\nstd::string my_string_m(S(\"a\\0b\"));\nstd::cout &lt;&lt; \"Using template: \" &lt;&lt; my_string_t &lt;&lt; std::endl;\nstd::cout &lt;&lt; \"Using macro: \" &lt;&lt; my_string_m &lt;&lt; std::endl;\n</code></pre>\n\n<p>Additionally, there's an issue with the macro: the expression is not actually a <code>std::string</code> as written, and therefore can't be used e.g. for simple assignment-initialization:</p>\n\n<pre><code>std::string s = S(\"a\\0b\"); // ERROR!\n</code></pre>\n\n<p>...so it might be preferable to use:</p>\n\n<pre><code>#define std::string(s, sizeof s - 1)\n</code></pre>\n\n<p>Obviously you should only use one or the other solution in your project and call it whatever you think is appropriate.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/164168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17958/" ]
If I want to construct a std::string with a line like: ``` std::string my_string("a\0b"); ``` Where i want to have three characters in the resulting string (a, null, b), I only get one. What is the proper syntax?
### Since C++14 we have been able to create [literal `std::string`](https://en.cppreference.com/w/cpp/string/basic_string/operator%22%22s) ``` #include <iostream> #include <string> int main() { using namespace std::string_literals; std::string s = "pl-\0-op"s; // <- Notice the "s" at the end // This is a std::string literal not // a C-String literal. std::cout << s << "\n"; } ``` ### Before C++14 The problem is the `std::string` constructor that takes a `const char*` assumes the input is a C-string. C-strings are `\0` terminated and thus parsing stops when it reaches the `\0` character. To compensate for this, you need to use the constructor that builds the string from a char array (not a C-String). This takes two parameters - a pointer to the array and a length: ``` std::string x("pq\0rs"); // Two characters because input assumed to be C-String std::string x("pq\0rs",5); // 5 Characters as the input is now a char array with 5 characters. ``` Note: C++ `std::string` is **NOT** `\0`-terminated (as suggested in other posts). However, you can extract a pointer to an internal buffer that contains a C-String with the method `c_str()`. Also check out [Doug T's answer](https://stackoverflow.com/questions/164168/how-do-you-construct-a-stdstring-with-an-embedded-null#164257) below about using a `vector<char>`. Also check out [RiaD](https://stackoverflow.com/a/34723611/14065) for a C++14 solution.
164,181
<p>How can I fetch images from a server?</p> <p>I've got this bit of code which allows me to draw some images on a canvas.</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;script type="text/javascript"&gt; function draw(){ var canvas = document.getElementById('canv'); var ctx = canvas.getContext('2d'); for (i=0;i&lt;document.images.length;i++){ ctx.drawImage(document.images[i],i*150,i*130); } } &lt;/script&gt; &lt;/head&gt; &lt;body onload="draw();"&gt; &lt;canvas id="canv" width="1024" height="1024"&gt;&lt;/canvas&gt; &lt;img src="http://www.google.com/intl/en_ALL/images/logo.gif"&gt; &lt;img src="http://l.yimg.com/a/i/ww/beta/y3.gif"&gt; &lt;img src="http://static.ak.fbcdn.net/images/welcome/welcome_page_map.png"&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Instead of looping over document.images, i would like to continually fetch images from a server.</p> <pre><code>for (;;) { /* how to fetch myimage??? */ myimage = fetch???('http://myserver/nextimage.cgi'); ctx.drawImage(myimage, x, y); } </code></pre>
[ { "answer_id": 164191, "author": "Eric Schoonover", "author_id": 3957, "author_profile": "https://Stackoverflow.com/users/3957", "pm_score": 6, "selected": true, "text": "<p>Use the built-in <a href=\"http://www.w3schools.com/htmldom/dom_obj_image.asp\" rel=\"noreferrer\">JavaScript Image object</a>.</p>\n\n<p>Here is a very simple example of using the Image object:</p>\n\n<pre><code>myimage = new Image();\nmyimage.src = 'http://myserver/nextimage.cgi';\n</code></pre>\n\n<p>Here is a more appropriate mechanism for your scenario from the comments on this answer.</p>\n\n<p>Thanks <a href=\"https://stackoverflow.com/users/784/olliej\">olliej</a>!</p>\n\n<blockquote>\n <p>It's worth noting that you can't synchronously request a resource, so you should actually do something along the lines of:</p>\n</blockquote>\n\n<pre><code>myimage = new Image();\nmyimage.onload = function() {\n ctx.drawImage(myimage, x, y);\n }\nmyimage.src = 'http://myserver/nextimage.cgi';\n</code></pre>\n" }, { "answer_id": 164210, "author": "Diodeus - James MacFarlane", "author_id": 12579, "author_profile": "https://Stackoverflow.com/users/12579", "pm_score": 2, "selected": false, "text": "<p>To add an image in JavaScript you can do the following:</p>\n\n<pre><code>myimage = new Image()\nmyimage.src='http://....'\n</code></pre>\n\n<p>If an image on your page has an ID \"image1\", you can assign the src of image1 to myimage.src.</p>\n" }, { "answer_id": 164262, "author": "Darryl Hein", "author_id": 5441, "author_profile": "https://Stackoverflow.com/users/5441", "pm_score": -1, "selected": false, "text": "<p>If you are using jQuery you can do:</p>\n\n<pre><code>$.('&lt;img src=\"http://myserver/nextimage.cgi\" /&gt;').appendTo('#canv');\n</code></pre>\n\n<p>You can also add widths and anything else in the img tag.</p>\n" }, { "answer_id": 165387, "author": "olliej", "author_id": 784, "author_profile": "https://Stackoverflow.com/users/784", "pm_score": 3, "selected": false, "text": "<p>If you want to draw an image to a canvas you also need to wait for the image to actually load, so the correct thing to do will be:</p>\n\n<pre><code>myimage = new Image();\nmyimage.onload = function() {\n context.drawImage(myimage, ...);\n}\nmyimage.src = 'http://myserver/nextimage.cgi';\n</code></pre>\n" }, { "answer_id": 9636983, "author": "TheCrzyMan", "author_id": 1259665, "author_profile": "https://Stackoverflow.com/users/1259665", "pm_score": 1, "selected": false, "text": "<p>I have found that using prototypes is very helpful here. If you aren't familiar with them, prototypes are part of objects that allow you to set your own variables and/or methods to them.</p>\n\n<p>Doing something like:</p>\n\n<pre><code>Image.prototype.position = {\n x: 0,\n y: 0\n}\n\nImage.prototype.onload = function(){\n context.drawImage(this, this.position.x, this.position.y);\n}\n</code></pre>\n\n<p>allows you to set position and draw to the canvas without too much work.</p>\n\n<p>The \"position\" variable allows you to move it around on the canvas.<br>\nSo it's possible to do:</p>\n\n<pre><code>var myImg = new Image();\nmyImg.position.x = 20;\nmyImg.position.y = 200;\nmyImg.src = \"http://www.google.com/intl/en_ALL/images/logo.gif\";\n</code></pre>\n\n<p>and the image will automatically draw to the canvas at (20,200).</p>\n\n<p>Prototype works for all HTML and native Javascript objects. So</p>\n\n<pre><code>Array.prototype.sum = function(){\n var _sum = 0.0;\n for (var i=0; i&lt;this.length; i++){\n _sum += parseFloat(this[i]);\n }\n return _sum;\n}\n</code></pre>\n\n<p>gives a new function to all Arrays.</p>\n\n<p>However, </p>\n\n<pre><code>var Bob;\nBob.Prototype.sayHi = function(){\n alert(\"Hello there.\");\n}\n</code></pre>\n\n<p>will not work (for multiple reasons, but i'll just talk about prototypes).<br>\nPrototype is a \"property\" of sorts, which contains all the your properties/methods that you input, and is already in each of the HTML and native Javascript objects (not the ones you make).<br>\nPrototypes also allow for easy calling (you can do \"myImg.position.x\" instead of \"myImg.prototype.position.x\" ).</p>\n\n<p>Besides, if you are defining you variable, you should do it more like this.</p>\n\n<pre><code>var Bob = function(){\n this.sayHi = function(){\n alert(\"Hello there.\");\n }\n}\n</code></pre>\n" }, { "answer_id": 70388230, "author": "Ray Foss", "author_id": 370238, "author_profile": "https://Stackoverflow.com/users/370238", "pm_score": 0, "selected": false, "text": "<p>Using Promises:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>class App {\n imageUrl = 'https://img-prod-cms-rt-microsoft-com.akamaized.net/cms/api/am/imageFileData/RE4HZBo'\n\n constructor(dom) {\n this.start(dom)\n }\n\n async start(dom) {\n const appEl = dom.createElement('div')\n dom.body.append(appEl)\n \n const imageEl = await this.loadImage(this.imageUrl)\n \n const canvas = dom.createElement('canvas')\n canvas.width = imageEl.width\n canvas.height = imageEl.height\n const ctx = canvas.getContext('2d')\n ctx.drawImage(imageEl, 0, 0)\n \n appEl.append(canvas)\n }\n \n loadImage = async (url) =&gt; \n new Promise((resolve) =&gt; {\n const imageEl = new Image()\n imageEl.src = url\n imageEl.onload = () =&gt; resolve(imageEl)\n })\n}\n\nnew App(document)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/164181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/116/" ]
How can I fetch images from a server? I've got this bit of code which allows me to draw some images on a canvas. ``` <html> <head> <script type="text/javascript"> function draw(){ var canvas = document.getElementById('canv'); var ctx = canvas.getContext('2d'); for (i=0;i<document.images.length;i++){ ctx.drawImage(document.images[i],i*150,i*130); } } </script> </head> <body onload="draw();"> <canvas id="canv" width="1024" height="1024"></canvas> <img src="http://www.google.com/intl/en_ALL/images/logo.gif"> <img src="http://l.yimg.com/a/i/ww/beta/y3.gif"> <img src="http://static.ak.fbcdn.net/images/welcome/welcome_page_map.png"> </body> </html> ``` Instead of looping over document.images, i would like to continually fetch images from a server. ``` for (;;) { /* how to fetch myimage??? */ myimage = fetch???('http://myserver/nextimage.cgi'); ctx.drawImage(myimage, x, y); } ```
Use the built-in [JavaScript Image object](http://www.w3schools.com/htmldom/dom_obj_image.asp). Here is a very simple example of using the Image object: ``` myimage = new Image(); myimage.src = 'http://myserver/nextimage.cgi'; ``` Here is a more appropriate mechanism for your scenario from the comments on this answer. Thanks [olliej](https://stackoverflow.com/users/784/olliej)! > > It's worth noting that you can't synchronously request a resource, so you should actually do something along the lines of: > > > ``` myimage = new Image(); myimage.onload = function() { ctx.drawImage(myimage, x, y); } myimage.src = 'http://myserver/nextimage.cgi'; ```
164,194
<p>The following code receives seg fault on line 2:</p> <pre><code>char *str = "string"; str[0] = 'z'; // could be also written as *str = 'z' printf("%s\n", str); </code></pre> <p>While this works perfectly well:</p> <pre><code>char str[] = "string"; str[0] = 'z'; printf("%s\n", str); </code></pre> <p>Tested with MSVC and GCC.</p>
[ { "answer_id": 164227, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>Because the type of <code>\"whatever\"</code> in the context of the 1st example is <code>const char *</code> (even if you assign it to a non-const char*), which means you shouldn't try and write to it.</p>\n\n<p>The compiler has enforced this by putting the string in a read-only part of memory, hence writing to it generates a segfault.</p>\n" }, { "answer_id": 164229, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 7, "selected": false, "text": "<p>Normally, string literals are stored in read-only memory when the program is run. This is to prevent you from accidentally changing a string constant. In your first example, <code>\"string\"</code> is stored in read-only memory and <code>*str</code> points to the first character. The segfault happens when you try to change the first character to <code>'z'</code>.</p>\n\n<p>In the second example, the string <code>\"string\"</code> is <em>copied</em> by the compiler from its read-only home to the <code>str[]</code> array. Then changing the first character is permitted. You can check this by printing the address of each:</p>\n\n<pre><code>printf(\"%p\", str);\n</code></pre>\n\n<p>Also, printing the size of <code>str</code> in the second example will show you that the compiler has allocated 7 bytes for it:</p>\n\n<pre><code>printf(\"%d\", sizeof(str));\n</code></pre>\n" }, { "answer_id": 164233, "author": "DougN", "author_id": 7442, "author_profile": "https://Stackoverflow.com/users/7442", "pm_score": 3, "selected": false, "text": "<pre><code>char *str = \"string\"; \n</code></pre>\n\n<p>The above sets <code>str</code> to point to the literal value <code>\"string\"</code> which is hard-coded in the program's binary image, which is probably flagged as read-only in memory. </p>\n\n<p>So <code>str[0]=</code> is attempting to write to the read-only code of the application. I would guess this is probably compiler dependent though.</p>\n" }, { "answer_id": 164235, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 4, "selected": false, "text": "<p>In the first code, \"string\" is a string constant, and string constants should never be modified because they are often placed into read only memory. \"str\" is a pointer being used to modify the constant.</p>\n\n<p>In the second code, \"string\" is an array initializer, sort of short hand for</p>\n\n<pre><code>char str[7] = { 's', 't', 'r', 'i', 'n', 'g', '\\0' };\n</code></pre>\n\n<p>\"str\" is an array allocated on the stack and can be modified freely.</p>\n" }, { "answer_id": 164239, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 3, "selected": false, "text": "<pre><code>char *str = \"string\";\n</code></pre>\n\n<p>allocates a pointer to a string literal, which the compiler is putting in a non-modifiable part of your executable;</p>\n\n<pre><code>char str[] = \"string\";\n</code></pre>\n\n<p>allocates and initializes a local array which is modifiable</p>\n" }, { "answer_id": 164244, "author": "Jurney", "author_id": 2642, "author_profile": "https://Stackoverflow.com/users/2642", "pm_score": 2, "selected": false, "text": "<p>String literals like \"string\" are probably allocated in your executable's address space as read-only data (give or take your compiler). When you go to touch it, it freaks out that you're in its bathing suit area and lets you know with a seg fault.</p>\n\n<p>In your first example, you're getting a pointer to that const data. In your second example, you're initializing an array of 7 characters with a copy of the const data.</p>\n" }, { "answer_id": 164256, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 2, "selected": false, "text": "<p>The </p>\n\n<pre><code> char *str = \"string\";\n</code></pre>\n\n<p>line defines a pointer and points it to a literal string. The literal string is not writable so when you do:</p>\n\n<pre><code> str[0] = 'z';\n</code></pre>\n\n<p>you get a seg fault. On some platforms, the literal might be in writable memory so you won't see a segfault, but it's invalid code (resulting in undefined behavior) regardless.</p>\n\n<p>The line:</p>\n\n<pre><code>char str[] = \"string\";\n</code></pre>\n\n<p>allocates an array of characters and <strong>copies</strong> the literal string into that array, which is fully writable, so the subsequent update is no problem.</p>\n" }, { "answer_id": 164258, "author": "matli", "author_id": 23896, "author_profile": "https://Stackoverflow.com/users/23896", "pm_score": 9, "selected": true, "text": "<p>See the C FAQ, <a href=\"http://c-faq.com/decl/strlitinit.html\" rel=\"noreferrer\">Question 1.32</a></p>\n\n<blockquote>\n <p><strong>Q</strong>: What is the difference between these initializations?<br>\n <code>char a[] = \"string literal\";</code><br>\n <code>char *p = \"string literal\";</code><br>\n My program crashes if I try to assign a new value to <code>p[i]</code>.</p>\n \n <p><strong>A</strong>: A string literal (the formal term\n for a double-quoted string in C\n source) can be used in two slightly\n different ways:</p>\n \n <ol>\n <li>As the initializer for an array of char, as in the declaration of <code>char a[]</code> , it specifies the initial values\n of the characters in that array (and,\n if necessary, its size).</li>\n <li>Anywhere else, it turns into an unnamed, static array of characters,\n and this unnamed array may be stored\n in read-only memory, and which\n therefore cannot necessarily be\n modified. In an expression context,\n the array is converted at once to a\n pointer, as usual (see section 6), so\n the second declaration initializes p\n to point to the unnamed array's first\n element. </li>\n </ol>\n \n <p>Some compilers have a switch\n controlling whether string literals\n are writable or not (for compiling old\n code), and some may have options to\n cause string literals to be formally\n treated as arrays of const char (for\n better error catching).</p>\n</blockquote>\n" }, { "answer_id": 164265, "author": "David Thornley", "author_id": 14148, "author_profile": "https://Stackoverflow.com/users/14148", "pm_score": 1, "selected": false, "text": "<p>In the first place, <code>str</code> is a pointer that points at <code>\"string\"</code>. The compiler is allowed to put string literals in places in memory that you cannot write to, but can only read. (This really should have triggered a warning, since you're assigning a <code>const char *</code> to a <code>char *</code>. Did you have warnings disabled, or did you just ignore them?)</p>\n\n<p>In the second place, you're creating an array, which is memory that you've got full access to, and initializing it with <code>\"string\"</code>. You're creating a <code>char[7]</code> (six for the letters, one for the terminating '\\0'), and you do whatever you like with it.</p>\n" }, { "answer_id": 164285, "author": "rpj", "author_id": 23498, "author_profile": "https://Stackoverflow.com/users/23498", "pm_score": 3, "selected": false, "text": "<p>The C FAQ that @matli linked to mentions it, but no one else here has yet, so for clarification: if a string literal (double-quoted string in your source) is used anywhere <em>other than</em> to initialize a character array (ie: @Mark's second example, which works correctly), that string is stored by the compiler in a special <em>static string table</em>, which is akin to creating a global static variable (read-only, of course) that is essentially anonymous (has no variable \"name\"). The <em>read-only</em> part is the important part, and is why the @Mark's first code example segfaults.</p>\n" }, { "answer_id": 166280, "author": "Bob Somers", "author_id": 1384, "author_profile": "https://Stackoverflow.com/users/1384", "pm_score": 5, "selected": false, "text": "<p>Most of these answers are correct, but just to add a little more clarity...</p>\n\n<p>The \"read only memory\" that people are referring to is the text segment in ASM terms. It's the same place in memory where the instructions are loaded. This is read-only for obvious reasons like security. When you create a char* initialized to a string, the string data is compiled into the text segment and the program initializes the pointer to point into the text segment. So if you try to change it, kaboom. Segfault.</p>\n\n<p>When written as an array, the compiler places the initialized string data in the data segment instead, which is the same place that your global variables and such live. This memory is mutable, since there are no instructions in the data segment. This time when the compiler initializes the character array (which is still just a char*) it's pointing into the data segment rather than the text segment, which you can safely alter at run-time.</p>\n" }, { "answer_id": 8934638, "author": "jokeysmurf", "author_id": 1024343, "author_profile": "https://Stackoverflow.com/users/1024343", "pm_score": 2, "selected": false, "text": "<pre><code>// create a string constant like this - will be read only\nchar *str_p;\nstr_p = \"String constant\";\n\n// create an array of characters like this \nchar *arr_p;\nchar arr[] = \"String in an array\";\narr_p = &amp;arr[0];\n\n// now we try to change a character in the array first, this will work\n*arr_p = 'E';\n\n// lets try to change the first character of the string contant\n*str_p = 'G'; // this will result in a segmentation fault. Comment it out to work.\n\n\n/*-----------------------------------------------------------------------------\n * String constants can't be modified. A segmentation fault is the result,\n * because most operating systems will not allow a write\n * operation on read only memory.\n *-----------------------------------------------------------------------------*/\n\n//print both strings to see if they have changed\nprintf(\"%s\\n\", str_p); //print the string without a variable\nprintf(\"%s\\n\", arr_p); //print the string, which is in an array. \n</code></pre>\n" }, { "answer_id": 14145422, "author": "Raghu Srikanth Reddy", "author_id": 589026, "author_profile": "https://Stackoverflow.com/users/589026", "pm_score": -1, "selected": false, "text": "<p>Segmentation fault is caused when you try to access the memory which is inaccessible. </p>\n\n<p><code>char *str</code> is a pointer to a string that is nonmodifiable(the reason for getting segfault).</p>\n\n<p>whereas <code>char str[]</code> is an array and can be modifiable..</p>\n" }, { "answer_id": 19313852, "author": "libralhb", "author_id": 2827991, "author_profile": "https://Stackoverflow.com/users/2827991", "pm_score": 0, "selected": false, "text": "<p>First is one constant string which can't be modified. Second is an array with initialized value, so it can be modified. </p>\n" }, { "answer_id": 20441961, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>To understand this error or problem you should first know difference b/w the pointer and array\nso here firstly i have explain you differences b/w them</p>\n<h3>string array</h3>\n<pre><code> char strarray[] = &quot;hello&quot;;\n</code></pre>\n<p>In memory array is stored in continuous memory cells, stored as <code>[h][e][l][l][o][\\0] =&gt;[]</code> is 1 char byte size memory cell ,and this continuous memory cells can be access by name named strarray here.so here string array <code>strarray</code> itself containing all characters of string initialized to it.in this case here <code>&quot;hello&quot;</code>\nso we can easily change its memory content by accessing each character by its index value</p>\n<pre><code>`strarray[0]='m'` it access character at index 0 which is 'h'in strarray\n</code></pre>\n<p>and its value changed to <code>'m'</code> so strarray value changed to <code>&quot;mello&quot;</code>;</p>\n<p>one point to note here that we can change the content of string array by changing character by character but can not initialized other string directly to it like <code>strarray=&quot;new string&quot;</code> is invalid</p>\n<h3>Pointer</h3>\n<p>As we all know pointer points to memory location in memory ,\nuninitialized pointer points to random memory location so and after initialization points to particular memory location</p>\n<pre><code>char *ptr = &quot;hello&quot;;\n</code></pre>\n<p>here pointer ptr is initialized to string <code>&quot;hello&quot;</code> which is constant string stored in read only memory (ROM) so <code>&quot;hello&quot;</code> can not be changed as it is stored in ROM</p>\n<p>and ptr is stored in stack section and pointing to constant string <code>&quot;hello&quot;</code></p>\n<p>so ptr[0]='m' is invalid since you can not access read only memory</p>\n<p>But ptr can be initialised to other string value directly since it is just pointer so it can be point to any memory address of variable of its data type</p>\n<pre><code>ptr=&quot;new string&quot;; is valid\n</code></pre>\n" }, { "answer_id": 30662213, "author": "Ciro Santilli OurBigBook.com", "author_id": 895245, "author_profile": "https://Stackoverflow.com/users/895245", "pm_score": 5, "selected": false, "text": "<blockquote>\n <p>Why do I get a segmentation fault when writing to a string?</p>\n</blockquote>\n\n<p><strong>C99 N1256 draft</strong></p>\n\n<p>There are two different uses of character string literals:</p>\n\n<ol>\n<li><p>Initialize <code>char[]</code>:</p>\n\n<pre><code>char c[] = \"abc\"; \n</code></pre>\n\n<p>This is \"more magic\", and described at 6.7.8/14 \"Initialization\":</p>\n\n<blockquote>\n <p>An array of character type may be initialized by a character string literal, optionally\n enclosed in braces. Successive characters of the character string literal (including the\n terminating null character if there is room or if the array is of unknown size) initialize the\n elements of the array.</p>\n</blockquote>\n\n<p>So this is just a shortcut for:</p>\n\n<pre><code>char c[] = {'a', 'b', 'c', '\\0'};\n</code></pre>\n\n<p>Like any other regular array, <code>c</code> can be modified.</p></li>\n<li><p>Everywhere else: it generates an:</p>\n\n<ul>\n<li>unnamed</li>\n<li>array of char <a href=\"https://stackoverflow.com/questions/2245664/what-is-the-type-of-string-literals-in-c-c\">What is the type of string literals in C and C++?</a></li>\n<li>with static storage</li>\n<li>that gives UB if modified</li>\n</ul>\n\n<p>So when you write:</p>\n\n<pre><code>char *c = \"abc\";\n</code></pre>\n\n<p>This is similar to:</p>\n\n<pre><code>/* __unnamed is magic because modifying it gives UB. */\nstatic char __unnamed[] = \"abc\";\nchar *c = __unnamed;\n</code></pre>\n\n<p>Note the implicit cast from <code>char[]</code> to <code>char *</code>, which is always legal.</p>\n\n<p>Then if you modify <code>c[0]</code>, you also modify <code>__unnamed</code>, which is UB.</p>\n\n<p>This is documented at 6.4.5 \"String literals\":</p>\n\n<blockquote>\n <p>5 In translation phase 7, a byte or code of value zero is appended to each multibyte\n character sequence that results from a string literal or literals. The multibyte character\n sequence is then used to initialize an array of static storage duration and length just\n sufficient to contain the sequence. For character string literals, the array elements have\n type char, and are initialized with the individual bytes of the multibyte character\n sequence [...]</p>\n \n <p>6 It is unspecified whether these arrays are distinct provided their elements have the\n appropriate values. If the program attempts to modify such an array, the behavior is\n undefined.</p>\n</blockquote></li>\n</ol>\n\n<p>6.7.8/32 \"Initialization\" gives a direct example:</p>\n\n<blockquote>\n <p>EXAMPLE 8: The declaration</p>\n\n<pre><code>char s[] = \"abc\", t[3] = \"abc\";\n</code></pre>\n \n <p>defines \"plain\" char array objects <code>s</code> and <code>t</code> whose elements are initialized with character string literals.</p>\n \n <p>This declaration is identical to</p>\n\n<pre><code>char s[] = { 'a', 'b', 'c', '\\0' },\nt[] = { 'a', 'b', 'c' };\n</code></pre>\n \n <p>The contents of the arrays are modifiable. On the other hand, the declaration</p>\n\n<pre><code>char *p = \"abc\";\n</code></pre>\n \n <p>defines <code>p</code> with type \"pointer to char\" and initializes it to point to an object with type \"array of char\" with length 4 whose elements are initialized with a character string literal. If an attempt is made to use <code>p</code> to modify the contents of the array, the behavior is undefined.</p>\n</blockquote>\n\n<p><strong>GCC 4.8 x86-64 ELF implementation</strong></p>\n\n<p>Program:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\nint main(void) {\n char *s = \"abc\";\n printf(\"%s\\n\", s);\n return 0;\n}\n</code></pre>\n\n<p>Compile and decompile:</p>\n\n<pre><code>gcc -ggdb -std=c99 -c main.c\nobjdump -Sr main.o\n</code></pre>\n\n<p>Output contains:</p>\n\n<pre><code> char *s = \"abc\";\n8: 48 c7 45 f8 00 00 00 movq $0x0,-0x8(%rbp)\nf: 00 \n c: R_X86_64_32S .rodata\n</code></pre>\n\n<p>Conclusion: GCC stores <code>char*</code> it in <code>.rodata</code> section, not in <code>.text</code>.</p>\n\n<p>If we do the same for <code>char[]</code>:</p>\n\n<pre><code> char s[] = \"abc\";\n</code></pre>\n\n<p>we obtain:</p>\n\n<pre><code>17: c7 45 f0 61 62 63 00 movl $0x636261,-0x10(%rbp)\n</code></pre>\n\n<p>so it gets stored in the stack (relative to <code>%rbp</code>).</p>\n\n<p>Note however that the default linker script puts <code>.rodata</code> and <code>.text</code> in the same segment, which has execute but no write permission. This can be observed with:</p>\n\n<pre><code>readelf -l a.out\n</code></pre>\n\n<p>which contains:</p>\n\n<pre><code> Section to Segment mapping:\n Segment Sections...\n 02 .text .rodata\n</code></pre>\n" }, { "answer_id": 54517972, "author": "Venki", "author_id": 751865, "author_profile": "https://Stackoverflow.com/users/751865", "pm_score": 1, "selected": false, "text": "<p>Assume the strings are,</p>\n\n<pre><code>char a[] = \"string literal copied to stack\";\nchar *p = \"string literal referenced by p\";\n</code></pre>\n\n<p>In the first case, the literal is to be copied when 'a' comes into scope. Here 'a' is an array defined on stack. It means the string will be created on the stack and its data is copied from code (text) memory, which is typically read-only (this is implementation specific, a compiler can place this read-only program data in read-writable memory also).</p>\n\n<p>In the second case, p is a pointer defined on stack (local scope) and referring a string literal (program data or text) stored else where. Usually modifying such memory is not good practice nor encouraged.</p>\n" }, { "answer_id": 68607670, "author": "Hari", "author_id": 1047213, "author_profile": "https://Stackoverflow.com/users/1047213", "pm_score": 1, "selected": false, "text": "<p><code>Section 5.5 Character Pointers and Functions</code> of <code>K&amp;R</code> also discusses about this topic:</p>\n<blockquote>\n<p>There is an important difference between these definitions:</p>\n<p><code>char amessage[] = &quot;now is the time&quot;; /* an array */</code><br />\n<code>char *pmessage = &quot;now is the time&quot;; /* a pointer */</code></p>\n<p><code>amessage</code> is an array, just big enough to hold the sequence of characters and <code>'\\0'</code> that initializes it. Individual characters within the array may be changed but <code>amessage</code> will always refer to the same storage. On the other hand, <code>pmessage</code> is a pointer, initialized to point to a string constant; the pointer may subsequently be modified to point elsewhere, but the result is undefined if you try to modify the string contents.</p>\n</blockquote>\n" }, { "answer_id": 69005668, "author": "Tim Skov Jacobsen", "author_id": 5993892, "author_profile": "https://Stackoverflow.com/users/5993892", "pm_score": 1, "selected": false, "text": "<h3>Constant memory</h3>\n<p>Since string literals are read-only by design, they are stored in the <strong>Constant part</strong> of memory. Data stored there is immutable, i.e., cannot be changed. Thus, all string literals defined in C code get a read-only memory address here.</p>\n<h3>Stack memory</h3>\n<p>The <strong>Stack part</strong> of memory is where the addresses of local variables live, e.g., variables defined in functions.</p>\n<hr />\n<p>As @matli's answer suggests, there are two ways of working with string these constant strings.</p>\n<h3>1. Pointer to string literal</h3>\n<p>When we define a pointer to a string literal, we are creating a pointer variable living in <strong>Stack memory</strong>. It points to the read-only address where the underlying string literal resides.</p>\n<pre class=\"lang-c prettyprint-override\"><code>#include &lt;stdio.h&gt;\n\nint main(void) {\n char *s = &quot;hello&quot;;\n printf(&quot;%p\\n&quot;, &amp;s); // Prints a read-only address, e.g. 0x7ffc8e224620\n return 0;\n}\n</code></pre>\n<p>If we try to modify <code>s</code> by inserting</p>\n<pre class=\"lang-c prettyprint-override\"><code>s[0] = 'H';\n</code></pre>\n<p>we get a <code>Segmentation fault (core dumped)</code>. We are trying to access memory that we shouldn't access. We are attempting to modify the value of a read-only address, <code>0x7ffc8e224620</code>.</p>\n<h3>2. Array of chars</h3>\n<p>For the sake of the example, suppose the string literal <code>&quot;Hello&quot;</code> stored in constant memory has a read-only memory address identical to the one above, <code>0x7ffc8e224620</code>.</p>\n<pre class=\"lang-c prettyprint-override\"><code>#include &lt;stdio.h&gt;\n\nint main(void) {\n // We create an array from a string literal with address 0x7ffc8e224620.\n // C initializes an array variable in the stack, let's give it address\n // 0x7ffc7a9a9db2.\n // C then copies the read-only value from 0x7ffc8e224620 into \n // 0x7ffc7a9a9db2 to give us a local copy we can mutate.\n char a[] = &quot;hello&quot;;\n\n // We can now mutate the local copy\n a[0] = 'H';\n\n printf(&quot;%p\\n&quot;, &amp;a); // Prints the Stack address, e.g. 0x7ffc7a9a9db2\n printf(&quot;%s\\n&quot;, a); // Prints &quot;Hello&quot;\n\n return 0;\n}\n</code></pre>\n<hr />\n<blockquote>\n<p><strong>Note:</strong> When using pointers to string literals as in 1., best practice is to use the <code>const</code> keyword, like <code>const *s = &quot;hello&quot;</code>. This is more readable and the compiler will provide better help when it's violated. It will then throw an error like <code>error: assignment of read-only location ‘*s’</code> instead of the seg fault. Linters in editors will also likely pick up the error before you manually compile the code.</p>\n</blockquote>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/164194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24622/" ]
The following code receives seg fault on line 2: ``` char *str = "string"; str[0] = 'z'; // could be also written as *str = 'z' printf("%s\n", str); ``` While this works perfectly well: ``` char str[] = "string"; str[0] = 'z'; printf("%s\n", str); ``` Tested with MSVC and GCC.
See the C FAQ, [Question 1.32](http://c-faq.com/decl/strlitinit.html) > > **Q**: What is the difference between these initializations? > > `char a[] = "string literal";` > > `char *p = "string literal";` > > My program crashes if I try to assign a new value to `p[i]`. > > > **A**: A string literal (the formal term > for a double-quoted string in C > source) can be used in two slightly > different ways: > > > 1. As the initializer for an array of char, as in the declaration of `char a[]` , it specifies the initial values > of the characters in that array (and, > if necessary, its size). > 2. Anywhere else, it turns into an unnamed, static array of characters, > and this unnamed array may be stored > in read-only memory, and which > therefore cannot necessarily be > modified. In an expression context, > the array is converted at once to a > pointer, as usual (see section 6), so > the second declaration initializes p > to point to the unnamed array's first > element. > > > Some compilers have a switch > controlling whether string literals > are writable or not (for compiling old > code), and some may have options to > cause string literals to be formally > treated as arrays of const char (for > better error catching). > > >
164,284
<p>I would like to transfer a text file to a webserver using wininet as if the file was being transferred using a web form that posts the file to the server.</p> <p>Based on answers I've received I've tried the following code:</p> <pre><code> static TCHAR hdrs[] = "Content-Type: multipart/form-data\nContent-Length: 25"; static TCHAR frmdata[] = "file=filename.txt\ncontent"; HINTERNET hSession = InternetOpen("MyAgent", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); HINTERNET hConnect = InternetConnect(hSession, "example.com", INTERNET_DEFAULT_HTTP_PORT, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 1); HINTERNET hRequest = HttpOpenRequest(hConnect, "POST", "test.php", NULL, NULL, NULL, 0, 1); HttpSendRequest(hRequest, hdrs, strlen(hdrs), frmdata, strlen(frmdata));"); </code></pre> <p>The test.php script is being run, but it doesn't appear to be getting the correct data.</p> <p>Could anyone give me any additional help or somewhere to look? Thanks.</p>
[ { "answer_id": 164299, "author": "dguaraglia", "author_id": 2384, "author_profile": "https://Stackoverflow.com/users/2384", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/aa384322(VS.85).aspx#Posting_data_to_the_\" rel=\"nofollow noreferrer\">Here</a>'s a general description of the things involved in that. Basically, you have to create an HTTP request to a web address, attach information to the request and then send it. The request must be a POST request in your case.</p>\n" }, { "answer_id": 164502, "author": "Gustavo Carreno", "author_id": 8167, "author_profile": "https://Stackoverflow.com/users/8167", "pm_score": 2, "selected": false, "text": "<p>Let's take this one step at a time.</p>\n\n<p>First the HTTP headers Involved:</p>\n\n<ol>\n<li>Content-Type: multipart/form-data</li>\n<li>Content-Length: &lt;this depends on the sum of the bytes of the contents&gt;</li>\n</ol>\n\n<p>Then you have to build a string with the contents of a POST Form. Lets assume you have the input named file:</p>\n\n<blockquote>\n <p>file=filename.txt<br />\n <strong>&lt;You now add the content of the file after that carriage return&gt;</strong></p>\n</blockquote>\n\n<p>You calculate the length of this string and put on the Content-Length above.</p>\n\n<p>Ok a complete HTTP Request would look like this:</p>\n\n<pre><code>POST /file_upload.php HTTP/1.0\nContent-type: multipart/form-data\nContent-length: &lt;calculated string's length: integer&gt;\n\nfile=filename.txt\n...File Content...\n</code></pre>\n\n<p>Now some code from the PHP manual:</p>\n\n<pre><code>&lt;?php\n// In PHP versions earlier than 4.1.0, $HTTP_POST_FILES should be used instead\n// of $_FILES.\n\n$uploaddir = '/var/www/uploads/';\n$uploadfile = $uploaddir . basename($_FILES['file']['name']);\n\necho '&lt;pre&gt;';\nif (move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)) {\n echo \"File is valid, and was successfully uploaded.\\n\";\n} else {\n echo \"Possible file upload attack!\\n\";\n}\n\necho 'Here is some more debugging info:';\nprint_r($_FILES);\n\nprint \"&lt;/pre&gt;\";\n\n?&gt;\n</code></pre>\n\n<p>Knowing me I've probably messed the format for the content but this is the general idea.</p>\n" }, { "answer_id": 167269, "author": "Rob", "author_id": 24628, "author_profile": "https://Stackoverflow.com/users/24628", "pm_score": 2, "selected": true, "text": "<p>Changing the form data and headers that I had above to the following solved the problem:</p>\n\n<pre><code> static TCHAR frmdata[] = \"-----------------------------7d82751e2bc0858\\nContent-Disposition: form-data; name=\\\"uploadedfile\\\"; filename=\\\"file.txt\\\"\\nContent-Type: text/plain\\n\\nfile contents here\\n-----------------------------7d82751e2bc0858--\";\n static TCHAR hdrs[] = \"Content-Type: multipart/form-data; boundary=---------------------------7d82751e2bc0858\";\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/164284", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24628/" ]
I would like to transfer a text file to a webserver using wininet as if the file was being transferred using a web form that posts the file to the server. Based on answers I've received I've tried the following code: ``` static TCHAR hdrs[] = "Content-Type: multipart/form-data\nContent-Length: 25"; static TCHAR frmdata[] = "file=filename.txt\ncontent"; HINTERNET hSession = InternetOpen("MyAgent", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); HINTERNET hConnect = InternetConnect(hSession, "example.com", INTERNET_DEFAULT_HTTP_PORT, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 1); HINTERNET hRequest = HttpOpenRequest(hConnect, "POST", "test.php", NULL, NULL, NULL, 0, 1); HttpSendRequest(hRequest, hdrs, strlen(hdrs), frmdata, strlen(frmdata));"); ``` The test.php script is being run, but it doesn't appear to be getting the correct data. Could anyone give me any additional help or somewhere to look? Thanks.
Changing the form data and headers that I had above to the following solved the problem: ``` static TCHAR frmdata[] = "-----------------------------7d82751e2bc0858\nContent-Disposition: form-data; name=\"uploadedfile\"; filename=\"file.txt\"\nContent-Type: text/plain\n\nfile contents here\n-----------------------------7d82751e2bc0858--"; static TCHAR hdrs[] = "Content-Type: multipart/form-data; boundary=---------------------------7d82751e2bc0858"; ```
164,305
<p>I'm using CodeSynthesis XSD C++/Tree Mapping utility to convert an existing xsd into c++ code we can populate the values in. This was we always make sure we follow the schema.</p> <p>After doing the conversion, I'm trying to get it to work so I can test it. Problem is, I'm not used to doing this in c++ and it's my first time with this tool.</p> <p>I start with a class called ABSTRACTNETWORKMODEL with types <code>versno_type</code> and <code>fromtime_type</code> typedef'd inside. Here is the constructor I am trying to use as well as the typedefs</p> <pre><code>ABSTRACTNETWORKMODEL(const versno_type&amp;, const fromtime_type&amp;); typedef ::xml_schema::double_ versno_type; typedef ::xml_schema::time fromtime_type; </code></pre> <p>all these are in the ABSTRACTNETWORKMODEL class and the definitions for double_ and time are:</p> <pre><code>typedef ::xsd::cxx::tree::time&lt;char, simple_type&gt; time; typedef double double_; </code></pre> <p>where the definition for time is a class with multiple constructors:</p> <pre><code>template&lt;typename C, typename B&gt; class time: public B, public time_zone { public: time(unsigned short hours, unsigned short minutes, double seconds); ... } </code></pre> <p>I know I'm not correctly creating a new ABSTRACTNETWORKMODEL but I don't know what I need to do this. Here is all I'm trying to do at this point:</p> <pre><code> ::xml_schema::time t(); ABSTRACTNETWORKMODEL anm(1234, t); </code></pre> <p>This, of course, throws an error about converting the second parameter, but can somebody tell me what it is that is incorrect? Or at least point me down the right path, as one of the things I'm trying to do right now is learn more c++.</p>
[ { "answer_id": 164679, "author": "Fry", "author_id": 23553, "author_profile": "https://Stackoverflow.com/users/23553", "pm_score": 0, "selected": false, "text": "<p>Asked around the office, and it appears my problem wasn't creating the ABSTRACTNETWORKMODEL, but it was actually the ::xml_schema::time.</p>\n\n<p>I find it odd that the instantiation of time didn't cause an error, given that it doesn't have any default constructors or why it wasn't accepted even though the template and types were correct.</p>\n" }, { "answer_id": 168157, "author": "Max Lybbert", "author_id": 10593, "author_profile": "https://Stackoverflow.com/users/10593", "pm_score": 3, "selected": true, "text": "<p>I've been bitten by this before. If the line:</p>\n\n<pre><code>::xml_schema::time t();\n</code></pre>\n\n<p>is exactly as it appears in your code (that is, with the parens) then the problem is that you didn't actually instantiate an object like you think.</p>\n\n<p>To instantiate an object you would use</p>\n\n<pre><code>::xml_schema::time t;\n</code></pre>\n\n<p>The first line, instead, declares a function t() that takes no arguments and returns an object of type <code>::xml_schema::time</code>. Since there is no body, the compiler thinks you will define the function later. It is perfectly legal C++, and it's something that people do a lot (say, in header files) so the compiler accepts it, does not issue a warning because it has no way of knowing that's not what you meant, and does something you weren't expecting.</p>\n\n<p>And when you pass that function to the <code>ABSTRACTNETWORKMODEL</code> constructor you get an error because you can't pass a function as an argument (you can pass a pointer to the function, and you can call the function, passing the resulting temporary):</p>\n\n<pre><code>::xml_schema::time t();\nABSTRACTNETWORKMODEL anm(1234, t()); // calls t(), gets a temporary of type ::xml_schema::time, and passes the temporary to the constructor\n</code></pre>\n\n<p>So the reason \"the instantiation of time didn't cause an error\" is that a time object was never instantiated. The time class doesn't have a default constructor either, and attempting to instantiate t with the correct syntax would have thrown the error you were expecting.</p>\n\n<p>For the record, the parenthesis are required in some cases. For instance, when instantiating a temporary object and manipulating that temporary in the same line:</p>\n\n<pre><code>int hours = time().get_hours(); // assuming that there is now a default constructor\n</code></pre>\n\n<p>Because dropping the first set of parenthesis will result in an error:</p>\n\n<pre><code>int hours = time.set_time(\"12:00:00am\"); // error: there is a time class, but no object named \"time\"\n</code></pre>\n\n<p>Believe me, I really like C++, but the syntax can get really difficult to keep straight some times.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/164305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23553/" ]
I'm using CodeSynthesis XSD C++/Tree Mapping utility to convert an existing xsd into c++ code we can populate the values in. This was we always make sure we follow the schema. After doing the conversion, I'm trying to get it to work so I can test it. Problem is, I'm not used to doing this in c++ and it's my first time with this tool. I start with a class called ABSTRACTNETWORKMODEL with types `versno_type` and `fromtime_type` typedef'd inside. Here is the constructor I am trying to use as well as the typedefs ``` ABSTRACTNETWORKMODEL(const versno_type&, const fromtime_type&); typedef ::xml_schema::double_ versno_type; typedef ::xml_schema::time fromtime_type; ``` all these are in the ABSTRACTNETWORKMODEL class and the definitions for double\_ and time are: ``` typedef ::xsd::cxx::tree::time<char, simple_type> time; typedef double double_; ``` where the definition for time is a class with multiple constructors: ``` template<typename C, typename B> class time: public B, public time_zone { public: time(unsigned short hours, unsigned short minutes, double seconds); ... } ``` I know I'm not correctly creating a new ABSTRACTNETWORKMODEL but I don't know what I need to do this. Here is all I'm trying to do at this point: ``` ::xml_schema::time t(); ABSTRACTNETWORKMODEL anm(1234, t); ``` This, of course, throws an error about converting the second parameter, but can somebody tell me what it is that is incorrect? Or at least point me down the right path, as one of the things I'm trying to do right now is learn more c++.
I've been bitten by this before. If the line: ``` ::xml_schema::time t(); ``` is exactly as it appears in your code (that is, with the parens) then the problem is that you didn't actually instantiate an object like you think. To instantiate an object you would use ``` ::xml_schema::time t; ``` The first line, instead, declares a function t() that takes no arguments and returns an object of type `::xml_schema::time`. Since there is no body, the compiler thinks you will define the function later. It is perfectly legal C++, and it's something that people do a lot (say, in header files) so the compiler accepts it, does not issue a warning because it has no way of knowing that's not what you meant, and does something you weren't expecting. And when you pass that function to the `ABSTRACTNETWORKMODEL` constructor you get an error because you can't pass a function as an argument (you can pass a pointer to the function, and you can call the function, passing the resulting temporary): ``` ::xml_schema::time t(); ABSTRACTNETWORKMODEL anm(1234, t()); // calls t(), gets a temporary of type ::xml_schema::time, and passes the temporary to the constructor ``` So the reason "the instantiation of time didn't cause an error" is that a time object was never instantiated. The time class doesn't have a default constructor either, and attempting to instantiate t with the correct syntax would have thrown the error you were expecting. For the record, the parenthesis are required in some cases. For instance, when instantiating a temporary object and manipulating that temporary in the same line: ``` int hours = time().get_hours(); // assuming that there is now a default constructor ``` Because dropping the first set of parenthesis will result in an error: ``` int hours = time.set_time("12:00:00am"); // error: there is a time class, but no object named "time" ``` Believe me, I really like C++, but the syntax can get really difficult to keep straight some times.
164,307
<p>With the MacPorts version of ImageMagick 6.4.4 installed, I'm getting an error installing the RMagick gem.</p> <pre><code>/opt/local/bin/ruby extconf.rb update rmagick checking for Ruby version &gt;= 1.8.2... yes checking for /usr/bin/gcc-4.0... yes checking for Magick-config... no Can't install RMagick 2.7.0. Can't find Magick-config in /System/Library/Frameworks/JavaVM.framework/Versions/1.5/Commands: /Users/jason/.bin:/opt/local/bin:/usr/local/bin:/usr/local/mysql/bin: /usr/local/ec2-api-tools/bin:/opt/local/bin:/usr/bin: /usr/local/bin:/bin:/usr/sbin:/sbin:/usr/X11/bin </code></pre> <p>I've installed older versions of rmagick successfully. I've seen references to a dev package of ImageMagick, but it doesn't seem to be available from MacPorts.</p> <p>How can I install RMagick 2.7 on Mac OS X with ImageMagick 6.4.4 from MacPorts?</p>
[ { "answer_id": 164807, "author": "Mike", "author_id": 24316, "author_profile": "https://Stackoverflow.com/users/24316", "pm_score": 2, "selected": false, "text": "<p>The install script can't find Magick-config in your path. Did you use a non-standard install location when you installed ImageMagick through MacPorts? Usually it goes into /opt/local/bin/</p>\n\n<p>You can see where MacPorts put your Magick-config by running:</p>\n\n<blockquote>\n <p>port contents ImageMagick</p>\n</blockquote>\n\n<p>If you find it listed there, then make sure that the directory is included in your PATH and rerun the rmagick install.</p>\n" }, { "answer_id": 165656, "author": "user6325", "author_id": 6325, "author_profile": "https://Stackoverflow.com/users/6325", "pm_score": 3, "selected": false, "text": "<p>Try this from the command line before installing the rmagick gem:</p>\n\n<pre><code>sudo port install tiff -macosx imagemagick +q8 +gs +wmf\n</code></pre>\n\n<p>Also have you read the installation documentation <a href=\"http://rmagick.rubyforge.org/install-osx.html\" rel=\"noreferrer\">here</a> ?</p>\n" }, { "answer_id": 1476485, "author": "ehaselwanter", "author_id": 97734, "author_profile": "https://Stackoverflow.com/users/97734", "pm_score": 1, "selected": false, "text": "<p>I've run the install command, but I keep getting this error:</p>\n\n<blockquote>\n <p>/Library/Ruby/Site/1.8/rubygems/custom_require.rb:31:in `gem_original_require': no such file to load -- RMagick2.so (LoadError)</p>\n</blockquote>\n\n<p>Turns out it correctly builds the shared object file, but the name is \"wrong\".</p>\n\n<p>The file I get is named <code>/Library/Ruby/Gems/1.8/gems/rmagick-2.11.1/lib/RMagick2.bundle</code>; renaming it to <code>RMagick2.so</code> fixes this issue.</p>\n" }, { "answer_id": 4328661, "author": "balexand", "author_id": 239965, "author_profile": "https://Stackoverflow.com/users/239965", "pm_score": 5, "selected": false, "text": "<p>I suggest using <a href=\"https://brew.sh/\" rel=\"nofollow noreferrer\">Homebrew</a> instead of Macports. After installing Homebrew, run:</p>\n<pre><code>brew install imagemagick\ngem install rmagick\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/164307", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11078/" ]
With the MacPorts version of ImageMagick 6.4.4 installed, I'm getting an error installing the RMagick gem. ``` /opt/local/bin/ruby extconf.rb update rmagick checking for Ruby version >= 1.8.2... yes checking for /usr/bin/gcc-4.0... yes checking for Magick-config... no Can't install RMagick 2.7.0. Can't find Magick-config in /System/Library/Frameworks/JavaVM.framework/Versions/1.5/Commands: /Users/jason/.bin:/opt/local/bin:/usr/local/bin:/usr/local/mysql/bin: /usr/local/ec2-api-tools/bin:/opt/local/bin:/usr/bin: /usr/local/bin:/bin:/usr/sbin:/sbin:/usr/X11/bin ``` I've installed older versions of rmagick successfully. I've seen references to a dev package of ImageMagick, but it doesn't seem to be available from MacPorts. How can I install RMagick 2.7 on Mac OS X with ImageMagick 6.4.4 from MacPorts?
I suggest using [Homebrew](https://brew.sh/) instead of Macports. After installing Homebrew, run: ``` brew install imagemagick gem install rmagick ```
164,319
<p>I learned something simple about SQL the other day:</p> <pre><code>SELECT c FROM myTbl GROUP BY C </code></pre> <p>Has the same result as:</p> <pre><code>SELECT DISTINCT C FROM myTbl </code></pre> <p>What I am curious of, is there anything different in the way an SQL engine processes the command, or are they truly the same thing? </p> <p>I personally prefer the distinct syntax, but I am sure it's more out of habit than anything else.</p> <p>EDIT: This is not a question about aggregates. The use of <code>GROUP BY</code> with aggregate functions is understood.</p>
[ { "answer_id": 164323, "author": "Hank Gay", "author_id": 4203, "author_profile": "https://Stackoverflow.com/users/4203", "pm_score": 3, "selected": false, "text": "<p>They have different semantics, even if they happen to have equivalent results on your particular data.</p>\n" }, { "answer_id": 164329, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 8, "selected": false, "text": "<p><code>GROUP BY</code> lets you use aggregate functions, like <code>AVG</code>, <code>MAX</code>, <code>MIN</code>, <code>SUM</code>, and <code>COUNT</code>. \nOn the other hand <code>DISTINCT</code> just removes duplicates.</p>\n\n<p>For example, if you have a bunch of purchase records, and you want to know how much was spent by each department, you might do something like:</p>\n\n<pre><code>SELECT department, SUM(amount) FROM purchases GROUP BY department\n</code></pre>\n\n<p>This will give you one row per department, containing the department name and the sum of all of the <code>amount</code> values in all rows for that department.</p>\n" }, { "answer_id": 164331, "author": "jkramer", "author_id": 12523, "author_profile": "https://Stackoverflow.com/users/12523", "pm_score": 5, "selected": false, "text": "<p>Use <code>DISTINCT</code> if you just want to remove duplicates. Use <code>GROUPY BY</code> if you want to apply aggregate operators (<code>MAX</code>, <code>SUM</code>, <code>GROUP_CONCAT</code>, ..., or a <code>HAVING</code> clause).</p>\n" }, { "answer_id": 164332, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 4, "selected": false, "text": "<p>For the query you posted, they are identical. But for other queries that may not be true.</p>\n\n<p>For example, it's not the same as:</p>\n\n<pre><code>SELECT C FROM myTbl GROUP BY C, D\n</code></pre>\n" }, { "answer_id": 164333, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 4, "selected": false, "text": "<p>If you use DISTINCT with multiple columns, the result set won't be grouped as it will with GROUP BY, and you can't use aggregate functions with DISTINCT.</p>\n" }, { "answer_id": 164337, "author": "Jeffrey L Whitledge", "author_id": 10174, "author_profile": "https://Stackoverflow.com/users/10174", "pm_score": 2, "selected": false, "text": "<p>In that particular query there is no difference. But, of course, if you add any aggregate columns then you'll have to use group by.</p>\n" }, { "answer_id": 164352, "author": "Danimal", "author_id": 2757, "author_profile": "https://Stackoverflow.com/users/2757", "pm_score": 2, "selected": false, "text": "<p>group by is used in aggregate operations -- like when you want to get a count of Bs broken down by column C</p>\n\n<pre><code>select C, count(B) from myTbl group by C\n</code></pre>\n\n<p>distinct is what it sounds like -- you get unique rows.</p>\n\n<p>In sql server 2005, it looks like the query optimizer is able to optimize away the difference in the simplistic examples I ran. Dunno if you can count on that in all situations, though.</p>\n" }, { "answer_id": 164357, "author": "Chris Cudmore", "author_id": 18907, "author_profile": "https://Stackoverflow.com/users/18907", "pm_score": 2, "selected": false, "text": "<p>You're only noticing that because you are selecting a single column.</p>\n\n<p>Try selecting two fields and see what happens.</p>\n\n<p>Group By is intended to be used like this:</p>\n\n<pre><code>SELECT name, SUM(transaction) FROM myTbl GROUP BY name\n</code></pre>\n\n<p>Which would show the sum of all transactions for each person.</p>\n" }, { "answer_id": 164376, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 3, "selected": false, "text": "<p>GROUP BY has a very specific meaning that is distinct (heh) from the DISTINCT function.</p>\n\n<p>GROUP BY causes the query results to be grouped using the chosen expression, aggregate functions can then be applied, and these will act on each group, rather than the entire resultset.</p>\n\n<p>Here's an example that might help:</p>\n\n<p>Given a table that looks like this:</p>\n\n<pre><code>name\n------\nbarry\ndave\nbill\ndave\ndave\nbarry\njohn\n</code></pre>\n\n<p>This query:</p>\n\n<pre><code>SELECT name, count(*) AS count FROM table GROUP BY name;\n</code></pre>\n\n<p>Will produce output like this:</p>\n\n<pre><code>name count\n-------------\nbarry 2\ndave 3\nbill 1\njohn 1\n</code></pre>\n\n<p>Which is obviously very different from using DISTINCT. If you want to group your results, use GROUP BY, if you just want a unique list of a specific column, use DISTINCT. This will give your database a chance to optimise the query for your needs.</p>\n" }, { "answer_id": 164485, "author": "MusiGenesis", "author_id": 14606, "author_profile": "https://Stackoverflow.com/users/14606", "pm_score": 6, "selected": false, "text": "<p><strong>There is no difference</strong> (in SQL Server, at least). Both queries use the same execution plan.</p>\n\n<p><a href=\"http://sqlmag.com/database-performance-tuning/distinct-vs-group\" rel=\"noreferrer\">http://sqlmag.com/database-performance-tuning/distinct-vs-group</a></p>\n\n<p>Maybe there <em>is</em> a difference, if there are sub-queries involved:</p>\n\n<p><a href=\"http://blog.sqlauthority.com/2007/03/29/sql-server-difference-between-distinct-and-group-by-distinct-vs-group-by/\" rel=\"noreferrer\">http://blog.sqlauthority.com/2007/03/29/sql-server-difference-between-distinct-and-group-by-distinct-vs-group-by/</a></p>\n\n<p><strong>There is no difference</strong> (Oracle-style):</p>\n\n<p><a href=\"http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:32961403234212\" rel=\"noreferrer\">http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:32961403234212</a></p>\n" }, { "answer_id": 164533, "author": "Dave Costa", "author_id": 6568, "author_profile": "https://Stackoverflow.com/users/6568", "pm_score": 5, "selected": false, "text": "<p>I expect there is the possibility for subtle differences in their execution.\nI checked the execution plans for two functionally equivalent queries along these lines in Oracle 10g:</p>\n\n<pre><code>core&gt; select sta from zip group by sta;\n\n---------------------------------------------------------------------------\n| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |\n---------------------------------------------------------------------------\n| 0 | SELECT STATEMENT | | 58 | 174 | 44 (19)| 00:00:01 |\n| 1 | HASH GROUP BY | | 58 | 174 | 44 (19)| 00:00:01 |\n| 2 | TABLE ACCESS FULL| ZIP | 42303 | 123K| 38 (6)| 00:00:01 |\n---------------------------------------------------------------------------\n\ncore&gt; select distinct sta from zip;\n\n---------------------------------------------------------------------------\n| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |\n---------------------------------------------------------------------------\n| 0 | SELECT STATEMENT | | 58 | 174 | 44 (19)| 00:00:01 |\n| 1 | HASH UNIQUE | | 58 | 174 | 44 (19)| 00:00:01 |\n| 2 | TABLE ACCESS FULL| ZIP | 42303 | 123K| 38 (6)| 00:00:01 |\n---------------------------------------------------------------------------\n</code></pre>\n\n<p>The middle operation is slightly different: \"HASH GROUP BY\" vs. \"HASH UNIQUE\", but the estimated costs etc. are identical. I then executed these with tracing on and the actual operation counts were the same for both (except that the second one didn't have to do any physical reads due to caching).</p>\n\n<p>But I think that because the operation names are different, the execution would follow somewhat different code paths and that opens the possibility of more significant differences.</p>\n\n<p>I think you should prefer the DISTINCT syntax for this purpose. It's not just habit, it more clearly indicates the purpose of the query.</p>\n" }, { "answer_id": 164544, "author": "Skeolan", "author_id": 9640, "author_profile": "https://Stackoverflow.com/users/9640", "pm_score": 9, "selected": true, "text": "<p><a href=\"https://stackoverflow.com/questions/164319/is-there-any-difference-between-group-by-and-distinct#164485\">MusiGenesis</a>' response is functionally the correct one with regard to your question as stated; the SQL Server is smart enough to realize that if you are using \"Group By\" and not using any aggregate functions, then what you actually mean is \"Distinct\" - and therefore it generates an execution plan as if you'd simply used \"Distinct.\"</p>\n\n<p>However, I think it's important to note <a href=\"https://stackoverflow.com/questions/164319/is-there-any-difference-between-group-by-and-distinct#164323\">Hank</a>'s response as well - cavalier treatment of \"Group By\" and \"Distinct\" could lead to some pernicious gotchas down the line if you're not careful. It's not entirely correct to say that this is \"not a question about aggregates\" because you're asking about the functional difference between two SQL query keywords, one of which is <strong>meant to be used with aggregates</strong> and one of which is not.</p>\n\n<p>A hammer can work to drive in a screw sometimes, but if you've got a screwdriver handy, why bother?</p>\n\n<p>(for the purposes of this analogy, <code>Hammer : Screwdriver :: GroupBy : Distinct</code> and <code>screw =&gt; get list of unique values in a table column</code>)</p>\n" }, { "answer_id": 164569, "author": "Andy Lester", "author_id": 8454, "author_profile": "https://Stackoverflow.com/users/8454", "pm_score": 3, "selected": false, "text": "<p>Please don't use GROUP BY when you mean DISTINCT, even if they happen to work the same. I'm assuming you're trying to shave off milliseconds from queries, and I have to point out that developer time is orders of magnitude more expensive than computer time.</p>\n" }, { "answer_id": 164605, "author": "Zenshai", "author_id": 17785, "author_profile": "https://Stackoverflow.com/users/17785", "pm_score": 0, "selected": false, "text": "<p>The way I always understood it is that using distinct is the same as grouping by every field you selected in the order you selected them. </p>\n\n<p>i.e:</p>\n\n<pre><code>select distinct a, b, c from table;\n</code></pre>\n\n<p>is the same as:</p>\n\n<pre><code>select a, b, c from table group by a, b, c\n</code></pre>\n" }, { "answer_id": 166194, "author": "onedaywhen", "author_id": 15354, "author_profile": "https://Stackoverflow.com/users/15354", "pm_score": 2, "selected": false, "text": "<p>From a 'SQL the language' perspective the two constructs are equivalent and which one you choose is one of those 'lifestyle' choices we all have to make. I think there is a good case for DISTINCT being more explicit (and therefore is more considerate to the person who will inherit your code etc) but that doesn't mean the GROUP BY construct is an invalid choice. </p>\n\n<p>I think this 'GROUP BY is for aggregates' is the wrong emphasis. Folk should be aware that the set function (MAX, MIN, COUNT, etc) can be omitted so that they can understand the coder's intent when it is.</p>\n\n<p>The ideal optimizer will recognize equivalent SQL constructs and will always pick the ideal plan accordingly. For your real life SQL engine of choice, you must test :)</p>\n\n<p>PS note the position of the DISTINCT keyword in the select clause may produce different results e.g. contrast: </p>\n\n<pre><code>SELECT COUNT(DISTINCT C) FROM myTbl;\n\nSELECT DISTINCT COUNT(C) FROM myTbl;\n</code></pre>\n" }, { "answer_id": 8655324, "author": "Vikram Mahapatra", "author_id": 1118832, "author_profile": "https://Stackoverflow.com/users/1118832", "pm_score": 3, "selected": false, "text": "<p>If you are using a GROUP BY without any aggregate function then internally it will treated as DISTINCT, so in this case there is no difference between GROUP BY and DISTINCT.</p>\n\n<p>But when you are provided with DISTINCT clause better to use it for finding your unique records because the objective of GROUP BY is to achieve aggregation.</p>\n" }, { "answer_id": 10639305, "author": "The Light", "author_id": 133212, "author_profile": "https://Stackoverflow.com/users/133212", "pm_score": 4, "selected": false, "text": "<p>I read all the above comments but didn't see anyone pointed to the main difference between Group By and Distinct apart from the aggregation bit.</p>\n\n<p>Distinct returns all the rows then de-duplicates them whereas Group By de-deduplicate the rows as they're read by the algorithm one by one.</p>\n\n<p>This means they can produce different results!</p>\n\n<p>For example, the below codes generate different results:</p>\n\n<pre><code>SELECT distinct ROW_NUMBER() OVER (ORDER BY Name), Name FROM NamesTable\n\n SELECT ROW_NUMBER() OVER (ORDER BY Name), Name FROM NamesTable\nGROUP BY Name\n</code></pre>\n\n<p>If there are 10 names in the table where 1 of which is a duplicate of another then the first query returns 10 rows whereas the second query returns 9 rows.</p>\n\n<p>The reason is what I said above so they can behave differently!</p>\n" }, { "answer_id": 28437372, "author": "Vinod Narwal", "author_id": 3285874, "author_profile": "https://Stackoverflow.com/users/3285874", "pm_score": -1, "selected": false, "text": "<p>There is no significantly difference between group by and distinct clause except the usage of aggregate functions.\nBoth can be used to distinguish the values but if in performance point of view group by is better.\nWhen distinct keyword is used , internally it used sort operation which can be view in execution plan.</p>\n<p>Try simple example</p>\n<pre><code>Declare @tmpresult table\n(\n Id tinyint\n)\n\nInsert into @tmpresult\nSelect 5\nUnion all\nSelect 2\nUnion all\nSelect 3\nUnion all\nSelect 4\n\n\nSelect distinct \nId\nFrom @tmpresult\n</code></pre>\n" }, { "answer_id": 35088897, "author": "Gabriel", "author_id": 5858049, "author_profile": "https://Stackoverflow.com/users/5858049", "pm_score": 2, "selected": false, "text": "<p>I know it's an old post. But it happens that I had a query that used group by just to return distinct values when using that query in toad and oracle reports everything worked fine, I mean a good response time. When we migrated from Oracle 9i to 11g the response time in Toad was excellent but in the reporte it took about 35 minutes to finish the report when using previous version it took about 5 minutes.</p>\n\n<p>The solution was to change the group by and use DISTINCT and now the report runs in about 30 secs.</p>\n\n<p>I hope this is useful for someone with the same situation.</p>\n" }, { "answer_id": 45833583, "author": "Lukas Eder", "author_id": 521799, "author_profile": "https://Stackoverflow.com/users/521799", "pm_score": 6, "selected": false, "text": "<h3>What's the difference from a mere duplicate removal functionality point of view</h3>\n\n<p>Apart from the fact that unlike <code>DISTINCT</code>, <code>GROUP BY</code> allows for aggregating data <em>per group</em> (which has been mentioned by many other answers), the most important difference in my opinion is the fact that the two operations \"happen\" at two very different steps in the <a href=\"https://blog.jooq.org/2016/12/09/a-beginners-guide-to-the-true-order-of-sql-operations\" rel=\"noreferrer\">logical order of operations that are executed in a <code>SELECT</code> statement</a>. </p>\n\n<p>Here are the most important operations:</p>\n\n<ul>\n<li><code>FROM</code> (including <code>JOIN</code>, <code>APPLY</code>, etc.)</li>\n<li><code>WHERE</code></li>\n<li><code>GROUP BY</code> <em>(can remove duplicates)</em></li>\n<li>Aggregations</li>\n<li><code>HAVING</code></li>\n<li>Window functions</li>\n<li><code>SELECT</code></li>\n<li><code>DISTINCT</code> <em>(can remove duplicates)</em></li>\n<li><code>UNION</code>, <code>INTERSECT</code>, <code>EXCEPT</code> <em>(can remove duplicates)</em></li>\n<li><code>ORDER BY</code></li>\n<li><code>OFFSET</code></li>\n<li><code>LIMIT</code></li>\n</ul>\n\n<p>As you can see, the logical order of each operation influences what can be done with it and how it influences subsequent operations. In particular, the fact that the <code>GROUP BY</code> operation <em>\"happens before\"</em> the <code>SELECT</code> operation (the projection) means that:</p>\n\n<ol>\n<li>It doesn't depend on the projection (which can be an advantage)</li>\n<li>It cannot use any values from the projection (which can be a disadvantage)</li>\n</ol>\n\n<h3>1. It doesn't depend on the projection</h3>\n\n<p>An example where not depending on the projection is useful is if you want to calculate window functions on distinct values:</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT rating, row_number() OVER (ORDER BY rating) AS rn\nFROM film\nGROUP BY rating\n</code></pre>\n\n<p>When run against the <a href=\"https://www.jooq.org/sakila\" rel=\"noreferrer\">Sakila database</a>, this yields:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>rating rn\n-----------\nG 1\nNC-17 2\nPG 3\nPG-13 4\nR 5\n</code></pre>\n\n<p>The same couldn't be achieved with <code>DISTINCT</code> easily:</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT DISTINCT rating, row_number() OVER (ORDER BY rating) AS rn\nFROM film\n</code></pre>\n\n<p>That query is \"wrong\" and yields something like:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>rating rn\n------------\nG 1\nG 2\nG 3\n...\nG 178\nNC-17 179\nNC-17 180\n...\n</code></pre>\n\n<p>This is not what we wanted. The <code>DISTINCT</code> operation <em>\"happens after\"</em> the projection, so we can no longer remove <code>DISTINCT</code> ratings because the window function was already calculated and projected. In order to use <code>DISTINCT</code>, we'd have to nest that part of the query:</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT rating, row_number() OVER (ORDER BY rating) AS rn\nFROM (\n SELECT DISTINCT rating FROM film\n) f\n</code></pre>\n\n<p>Side-note: <a href=\"https://blog.jooq.org/2013/10/09/sql-trick-row_number-is-to-select-what-dense_rank-is-to-select-distinct/\" rel=\"noreferrer\">In this particular case, we could also use <code>DENSE_RANK()</code></a></p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT DISTINCT rating, dense_rank() OVER (ORDER BY rating) AS rn\nFROM film\n</code></pre>\n\n<h3>2. It cannot use any values from the projection</h3>\n\n<p>One of SQL's drawbacks is its verbosity at times. For the same reason as what we've seen before (namely the logical order of operations), we cannot \"easily\" group by something we're projecting.</p>\n\n<p>This is invalid SQL:</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT first_name || ' ' || last_name AS name\nFROM customer\nGROUP BY name\n</code></pre>\n\n<p>This is valid (repeating the expression)</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT first_name || ' ' || last_name AS name\nFROM customer\nGROUP BY first_name || ' ' || last_name\n</code></pre>\n\n<p>This is valid, too (nesting the expression)</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT name\nFROM (\n SELECT first_name || ' ' || last_name AS name\n FROM customer\n) c\nGROUP BY name\n</code></pre>\n\n<p><a href=\"https://blog.jooq.org/2016/12/09/a-beginners-guide-to-the-true-order-of-sql-operations\" rel=\"noreferrer\">I've written about this topic more in depth in a blog post</a></p>\n" }, { "answer_id": 48161536, "author": "Jun", "author_id": 8449311, "author_profile": "https://Stackoverflow.com/users/8449311", "pm_score": 0, "selected": false, "text": "<p>Funtional efficiency is totally different. \nIf you would like to select only \"return value\" except duplicate one, use distinct is better than group by. Because \"group by\" include ( sorting + removing ) , \"distinct\" include ( removing ) </p>\n" }, { "answer_id": 50919180, "author": "Ram Ghadiyaram", "author_id": 647053, "author_profile": "https://Stackoverflow.com/users/647053", "pm_score": 3, "selected": false, "text": "<p><a href=\"https://www.dwhpro.com/distinct-vs-group-teradata/\" rel=\"noreferrer\">In Teradata perspective</a> : </p>\n\n<p>From a result set point of view, it does not matter if you use DISTINCT or GROUP BY in Teradata. The answer set will be the same.</p>\n\n<p>From a performance point of view, it is not the same.</p>\n\n<p>To understand what impacts performance, you need to know what happens on Teradata when executing a statement with DISTINCT or GROUP BY.</p>\n\n<p>In the case of DISTINCT, the rows are redistributed immediately without any preaggregation taking place, while in the case of GROUP BY, in a first step a preaggregation is done and only then are the unique values redistributed across the AMPs.</p>\n\n<p>Don’t think now that GROUP BY is always better from a performance point of view. When you have many different values, the preaggregation step of GROUP BY is not very efficient. Teradata has to sort the data to remove duplicates. In this case, it may be better to the redistribution first, i.e. use the DISTINCT statement. Only if there are many duplicate values, the GROUP BY statement is probably the better choice as only once the deduplication step takes place, after redistribution. </p>\n\n<p>In short, DISTINCT vs. GROUP BY in Teradata means:</p>\n\n<p>GROUP BY -> for many duplicates\nDISTINCT -> no or a few duplicates only . \nAt times, when using DISTINCT, you run out of spool space on an AMP. The reason is that redistribution takes place immediately, and skewing could cause AMPs to run out of space. </p>\n\n<p>If this happens, you have probably a better chance with GROUP BY, as duplicates are already removed in a first step, and less data is moved across the AMPs.</p>\n" }, { "answer_id": 51126218, "author": "John Jiang", "author_id": 437441, "author_profile": "https://Stackoverflow.com/users/437441", "pm_score": 1, "selected": false, "text": "<p>In Hive (HQL), <code>GROUP BY</code> can be way faster than <code>DISTINCT</code>, because the former does not require comparing all fields in the table.</p>\n<p>See: <a href=\"https://sqlperformance.com/2017/01/t-sql-queries/surprises-assumptions-group-by-distinct\" rel=\"nofollow noreferrer\">https://sqlperformance.com/2017/01/t-sql-queries/surprises-assumptions-group-by-distinct</a>.</p>\n" }, { "answer_id": 57084722, "author": "SkyRar", "author_id": 4753716, "author_profile": "https://Stackoverflow.com/users/4753716", "pm_score": 2, "selected": false, "text": "<p>Sometimes they may give you the same results but they are meant to be used in different sense/case. The main difference is in syntax. </p>\n\n<p>Minutely notice the example below. <code>DISTINCT</code> is used to filter out the duplicate set of values. (6, cs, 9.1) and (1, cs, 5.5) are two different sets. So <code>DISTINCT</code> is going to display both the rows while <code>GROUP BY Branch</code> is going to display only one set.</p>\n\n<pre><code> SELECT * FROM student; \n+------+--------+------+\n| Id | Branch | CGPA |\n+------+--------+------+\n| 3 | civil | 7.2 |\n| 2 | mech | 6.3 |\n| 6 | cs | 9.1 |\n| 4 | eee | 8.2 |\n| 1 | cs | 5.5 |\n+------+--------+------+\n5 rows in set (0.001 sec)\n\nSELECT DISTINCT * FROM student; \n+------+--------+------+\n| Id | Branch | CGPA |\n+------+--------+------+\n| 3 | civil | 7.2 |\n| 2 | mech | 6.3 |\n| 6 | cs | 9.1 |\n| 4 | eee | 8.2 |\n| 1 | cs | 5.5 |\n+------+--------+------+\n5 rows in set (0.001 sec)\n\nSELECT * FROM student GROUP BY Branch;\n+------+--------+------+\n| Id | Branch | CGPA |\n+------+--------+------+\n| 3 | civil | 7.2 |\n| 6 | cs | 9.1 |\n| 4 | eee | 8.2 |\n| 2 | mech | 6.3 |\n+------+--------+------+\n4 rows in set (0.001 sec)\n</code></pre>\n\n<p>Sometimes the results that can be achieved by <code>GROUP BY</code> clause is not possible to achieved by <code>DISTINCT</code> without using some extra clause or conditions. E.g in above case. </p>\n\n<p>To get the same result as <code>DISTINCT</code> you have to pass all the column names in <code>GROUP BY</code> clause like below. So see the syntactical difference. You must have knowledge about all the column names to use <code>GROUP BY</code> clause in that case.</p>\n\n<pre><code>SELECT * FROM student GROUP BY Id, Branch, CGPA;\n+------+--------+------+\n| Id | Branch | CGPA |\n+------+--------+------+\n| 1 | cs | 5.5 |\n| 2 | mech | 6.3 |\n| 3 | civil | 7.2 |\n| 4 | eee | 8.2 |\n| 6 | cs | 9.1 |\n+------+--------+------+\n</code></pre>\n\n<p>Also I have noticed <code>GROUP BY</code> displays the results in ascending order by default which <code>DISTINCT</code> does not. But I am not sure about this. It may be differ vendor wise. </p>\n\n<p>Source : <a href=\"https://dbjpanda.me/dbms/languages/sql/sql-syntax-with-examples#group-by\" rel=\"nofollow noreferrer\">https://dbjpanda.me/dbms/languages/sql/sql-syntax-with-examples#group-by</a></p>\n" }, { "answer_id": 57729375, "author": "Lova Chittumuri", "author_id": 5256337, "author_profile": "https://Stackoverflow.com/users/5256337", "pm_score": 0, "selected": false, "text": "<p>Generally we can use <code>DISTINCT</code> for eliminate the duplicates on Specific Column in the table.</p>\n\n<blockquote>\n <p>In Case of 'GROUP BY' we can Apply the Aggregation Functions like\n <code>AVG</code>, <code>MAX</code>, <code>MIN</code>, <code>SUM</code>, and <code>COUNT</code> on Specific column and fetch\n the column name and it aggregation function result on the same column.\n </p>\n</blockquote>\n\n<p>Example :</p>\n\n<pre><code>select specialColumn,sum(specialColumn) from yourTableName group by specialColumn;\n</code></pre>\n" }, { "answer_id": 58132051, "author": "Felix Labayen", "author_id": 2503754, "author_profile": "https://Stackoverflow.com/users/2503754", "pm_score": 1, "selected": false, "text": "<p>In terms of usage, GROUP BY is used for grouping those rows you want to calculate. DISTINCT will not do any calculation. It will show no duplicate rows.</p>\n\n<p>I always used DISTINCT if I want to present data without duplicates.</p>\n\n<p>If I want to do calculations like summing up the total quantity of mangoes, I will use GROUP BY</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/164319", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5836/" ]
I learned something simple about SQL the other day: ``` SELECT c FROM myTbl GROUP BY C ``` Has the same result as: ``` SELECT DISTINCT C FROM myTbl ``` What I am curious of, is there anything different in the way an SQL engine processes the command, or are they truly the same thing? I personally prefer the distinct syntax, but I am sure it's more out of habit than anything else. EDIT: This is not a question about aggregates. The use of `GROUP BY` with aggregate functions is understood.
[MusiGenesis](https://stackoverflow.com/questions/164319/is-there-any-difference-between-group-by-and-distinct#164485)' response is functionally the correct one with regard to your question as stated; the SQL Server is smart enough to realize that if you are using "Group By" and not using any aggregate functions, then what you actually mean is "Distinct" - and therefore it generates an execution plan as if you'd simply used "Distinct." However, I think it's important to note [Hank](https://stackoverflow.com/questions/164319/is-there-any-difference-between-group-by-and-distinct#164323)'s response as well - cavalier treatment of "Group By" and "Distinct" could lead to some pernicious gotchas down the line if you're not careful. It's not entirely correct to say that this is "not a question about aggregates" because you're asking about the functional difference between two SQL query keywords, one of which is **meant to be used with aggregates** and one of which is not. A hammer can work to drive in a screw sometimes, but if you've got a screwdriver handy, why bother? (for the purposes of this analogy, `Hammer : Screwdriver :: GroupBy : Distinct` and `screw => get list of unique values in a table column`)
164,324
<p>I need to get the Folder size and display the info on a report (SSRS). I need to do this for a number of Databases (loop!). These DB's are websites' backends.</p> <p>Are any samples available for this? Does xp_filesize and the like the right solution?</p>
[ { "answer_id": 179648, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 1, "selected": false, "text": "<p>Could you clarify who should do what in your scenario? Do you want SQL Server do get the info or do you want Reporting Server do that? </p>\n\n<p>What exactly do you mean by \"folder size\"? Is \"one folder, sum up each file\" enough or does it need to be recursive? Either way, I'd go for a little custom .NET function that uses <code>System.IO.Directory</code> and it's relatives.</p>\n" }, { "answer_id": 186836, "author": "Meff", "author_id": 9647, "author_profile": "https://Stackoverflow.com/users/9647", "pm_score": 3, "selected": true, "text": "<p>Looking at the question and Tomalak's response, and I'm assuming the reporting server will be able to reach the folders held in the DB:</p>\n\n<p>Firstly set up the query to get you back the result-set of paths - I assume you'll have no trouble with this part. Next you'll need to add a custom code function to your report: <a href=\"http://msdn.microsoft.com/en-us/library/ms155798.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms155798.aspx</a> - This function will take the folder path as a parameter, and pass back the size of the folder. You'll have to write in VB.Net if you want to embed the code in the report, or you could code up a DLL and bring that in.</p>\n\n<p>An example VB.Net code block (Remember you may need to prefix objects with System.IO.) <a href=\"http://www.freevbcode.com/ShowCode.asp?ID=4287\" rel=\"nofollow noreferrer\">http://www.freevbcode.com/ShowCode.asp?ID=4287</a></p>\n\n<pre><code>Public Shared Function GetFolderSize(ByVal DirPath As String, _\n Optional IncludeSubFolders as Boolean = True) As Long\n\n Dim lngDirSize As Long\n Dim objFileInfo As FileInfo\n Dim objDir As DirectoryInfo = New DirectoryInfo(DirPath)\n Dim objSubFolder As DirectoryInfo\n\nTry\n\n'add length of each file\n For Each objFileInfo In objDir.GetFiles()\n lngDirSize += objFileInfo.Length\n Next\n\n 'call recursively to get sub folders\n 'if you don't want this set optional\n 'parameter to false \nIf IncludeSubFolders then\n For Each objSubFolder In objDir.GetDirectories()\n lngDirSize += GetFolderSize(objSubFolder.FullName)\n Next\nEnd if\n\nCatch Ex As Exception\n\n\nEnd Try\n\n Return lngDirSize\nEnd Function\n</code></pre>\n\n<p>Now, in your report, in your table, you'd have for the cell that shows the folder size an expression something like:</p>\n\n<pre><code>=Code.GetFolderSize(Fields!FolderPath.Value)\n</code></pre>\n\n<p>I doubt this approach will be performant for a manually-viewed report, but you might get away with it for small result sets, or a scheduled report delivered by email?</p>\n\n<p>Oh, and this piece suggests you 'may' run into permissions issues using System.IO from within RS: <a href=\"http://blogs.sqlxml.org/bryantlikes/pages/824.aspx\" rel=\"nofollow noreferrer\">http://blogs.sqlxml.org/bryantlikes/pages/824.aspx</a></p>\n" }, { "answer_id": 242947, "author": "James Green", "author_id": 31736, "author_profile": "https://Stackoverflow.com/users/31736", "pm_score": 1, "selected": false, "text": "<p>I'd consider splitting this into two pieces, maybe a Windows Service to scan the directories and aggregate the data into a database, then use SSRS to report on the database as usual.</p>\n\n<p>The reason I suggest this is to use master..xp_filesize and it's kin the account the SQL Server service is starting with needs access to the paths to be scanned. Once this turns into accessing paths on other machines I'd be less comfortable with the security implications of that.</p>\n\n<p>Hope this helps</p>\n" }, { "answer_id": 258238, "author": "balaweblog", "author_id": 22162, "author_profile": "https://Stackoverflow.com/users/22162", "pm_score": 1, "selected": false, "text": "<p>In SSRS you can to do this with the help of custom data extension. U need give the path for the datasource as your folder name and it will retrive your files and its related informations and displayed</p>\n\n<p>For further reference and custom dll use this\n<a href=\"http://www.devx.com/dbzone/Article/31336/0/page/4\" rel=\"nofollow noreferrer\">http://www.devx.com/dbzone/Article/31336/0/page/4</a></p>\n\n<p>I have done this earlier.</p>\n\n<p>Note: you have to make related changes to Report Designer and Report Manager configuration files.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/164324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10385/" ]
I need to get the Folder size and display the info on a report (SSRS). I need to do this for a number of Databases (loop!). These DB's are websites' backends. Are any samples available for this? Does xp\_filesize and the like the right solution?
Looking at the question and Tomalak's response, and I'm assuming the reporting server will be able to reach the folders held in the DB: Firstly set up the query to get you back the result-set of paths - I assume you'll have no trouble with this part. Next you'll need to add a custom code function to your report: <http://msdn.microsoft.com/en-us/library/ms155798.aspx> - This function will take the folder path as a parameter, and pass back the size of the folder. You'll have to write in VB.Net if you want to embed the code in the report, or you could code up a DLL and bring that in. An example VB.Net code block (Remember you may need to prefix objects with System.IO.) <http://www.freevbcode.com/ShowCode.asp?ID=4287> ``` Public Shared Function GetFolderSize(ByVal DirPath As String, _ Optional IncludeSubFolders as Boolean = True) As Long Dim lngDirSize As Long Dim objFileInfo As FileInfo Dim objDir As DirectoryInfo = New DirectoryInfo(DirPath) Dim objSubFolder As DirectoryInfo Try 'add length of each file For Each objFileInfo In objDir.GetFiles() lngDirSize += objFileInfo.Length Next 'call recursively to get sub folders 'if you don't want this set optional 'parameter to false If IncludeSubFolders then For Each objSubFolder In objDir.GetDirectories() lngDirSize += GetFolderSize(objSubFolder.FullName) Next End if Catch Ex As Exception End Try Return lngDirSize End Function ``` Now, in your report, in your table, you'd have for the cell that shows the folder size an expression something like: ``` =Code.GetFolderSize(Fields!FolderPath.Value) ``` I doubt this approach will be performant for a manually-viewed report, but you might get away with it for small result sets, or a scheduled report delivered by email? Oh, and this piece suggests you 'may' run into permissions issues using System.IO from within RS: <http://blogs.sqlxml.org/bryantlikes/pages/824.aspx>
164,335
<p>Any XPath like /NodeName/position() would give you the position of the Node w.r.t it's parent node.</p> <p>There is no method on the XElement (Linq to XML) object that can get the position of the Element. Is there?</p>
[ { "answer_id": 164444, "author": "Michael Damatov", "author_id": 23372, "author_profile": "https://Stackoverflow.com/users/23372", "pm_score": 0, "selected": false, "text": "<pre><code>static int Position(this XNode node) {\n var position = 0;\n foreach(var n in node.Parent.Nodes()) {\n if(n == node) {\n return position;\n }\n position++;\n }\n return -1;\n}\n</code></pre>\n" }, { "answer_id": 164462, "author": "Bryant", "author_id": 10893, "author_profile": "https://Stackoverflow.com/users/10893", "pm_score": 3, "selected": false, "text": "<p>You could use the NodesBeforeSelf method to do this:</p>\n\n<pre><code> XElement root = new XElement(\"root\",\n new XElement(\"one\", \n new XElement(\"oneA\"),\n new XElement(\"oneB\")\n ),\n new XElement(\"two\"),\n new XElement(\"three\")\n );\n\n foreach (XElement x in root.Elements())\n {\n Console.WriteLine(x.Name);\n Console.WriteLine(x.NodesBeforeSelf().Count()); \n }\n</code></pre>\n\n<p>Update: If you really just want a Position method, just add an extension method.</p>\n\n<pre><code>public static class ExMethods\n{\n public static int Position(this XNode node)\n {\n return node.NodesBeforeSelf().Count(); \n }\n}\n</code></pre>\n\n<p>Now you can just call x.Position(). :)</p>\n" }, { "answer_id": 165013, "author": "Vin", "author_id": 1747, "author_profile": "https://Stackoverflow.com/users/1747", "pm_score": 5, "selected": true, "text": "<p>Actually NodesBeforeSelf().Count doesn't work because it gets everything even of type XText</p>\n\n<p>Question was about XElement object.\nSo I figured it's </p>\n\n<pre><code>int position = obj.ElementsBeforeSelf().Count();\n</code></pre>\n\n<p>that should be used,</p>\n\n<p>Thanks to Bryant for the direction.</p>\n" }, { "answer_id": 165068, "author": "Tim Jarvis", "author_id": 10387, "author_profile": "https://Stackoverflow.com/users/10387", "pm_score": 1, "selected": false, "text": "<p>Actually in the Load method of XDocument you can set a load option of SetLineInfo, you can then typecast XElements to IXMLLineInfo to get the line number.</p>\n\n<p>you could do something like</p>\n\n<pre><code>var list = from xe in xmldoc.Descendants(\"SomeElem\")\n let info = (IXmlLineInfo)xe\n select new \n {\n LineNum = info.LineNumber,\n Element = xe\n }\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/164335", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1747/" ]
Any XPath like /NodeName/position() would give you the position of the Node w.r.t it's parent node. There is no method on the XElement (Linq to XML) object that can get the position of the Element. Is there?
Actually NodesBeforeSelf().Count doesn't work because it gets everything even of type XText Question was about XElement object. So I figured it's ``` int position = obj.ElementsBeforeSelf().Count(); ``` that should be used, Thanks to Bryant for the direction.
164,342
<p>I'm considering one of two IRepository interfaces, one that is a descendant of IQueryable and one that contains IQueryable. </p> <p>Like this:</p> <pre><code>public interface IRepository&lt;T&gt; : IQueryable&lt;T&gt; { T Save(T entity); void Delete(T entity); } </code></pre> <p>Or this:</p> <pre><code>public interface IRepository&lt;T&gt; { T Save(T entity); void Delete(T entity); IQueryable&lt;T&gt; Query(); } </code></pre> <p>LINQ usage would be:</p> <pre><code>from dos in ServiceLocator.Current.GetInstance&lt;IRepository&lt;DomainObject&gt;&gt;() where dos.Id == id select dos </code></pre> <p>Or...</p> <pre><code>from dos in ServiceLocator.Current.GetInstance&lt;IRepository&lt;DomainObject&gt;&gt;().Query where dos.Id == id select dos </code></pre> <p>I kinda like the first one, but it's problematic to mock. How have other people implemented LINQable, mockable repositories?</p>
[ { "answer_id": 164380, "author": "MagicKat", "author_id": 8505, "author_profile": "https://Stackoverflow.com/users/8505", "pm_score": 5, "selected": true, "text": "<p>Depends on if you want a Has-A or an Is-A relationship.</p>\n\n<p>The first one is an Is-A relationship. The IRepository interface is a IQueryable interface. The second is a has-a. The IRepository has an IQueryable interface. In the process of writing this, I actually like the second better then the first, simply because when use your second IRepository, I can give the Query() method ANYTHING that returns IQueryable. To me, that is more flexible then the first implementation.</p>\n" }, { "answer_id": 943864, "author": "Kim Johansson", "author_id": 88000, "author_profile": "https://Stackoverflow.com/users/88000", "pm_score": 0, "selected": false, "text": "<p>You could always quick write stuff against List, it's not mocking using a mock framework, but it sure works great.</p>\n" }, { "answer_id": 5319662, "author": "Pure.Krome", "author_id": 30674, "author_profile": "https://Stackoverflow.com/users/30674", "pm_score": 3, "selected": false, "text": "<p>Personally, I use the <code>Repository Pattern</code> to return all items from the Repository as an <code>IQueryable</code>. By doing this, my repository layer is now very very light, small .. with the service layer (which consumes the Repository layer) can now be open to all types of query manipulation.</p>\n\n<p>Basically, all my logic now sits in the service layer (which has no idea what type of repository it will be using .. and doesn't want to know &lt;-- separation of concerns) .. while my repository layer is just dealing with Getting data and Saving data to the repo (a sql server, a file, a satellite in space.. etc &lt;-- more separation of concerns).</p>\n\n<p>eg. More or less pseduo code as i'm remembering what we've done in our code and simplifying it for this answer...</p>\n\n<pre><code>public interface IRepository&lt;T&gt;\n{\n IQueryable&lt;T&gt; Find();\n void Save(T entity);\n void Delete(T entity);\n}\n</code></pre>\n\n<p>and to have a user repository...</p>\n\n<pre><code>public class UserRepository : IRepository&lt;User&gt;\n{\n public IQueryable&lt;User&gt; Find()\n {\n // Context is some Entity Framework context or \n // Linq-to-Sql or NHib or an Xml file, etc...\n // I didn't bother adding this, to this example code.\n return context.Users().AsQueryable();\n }\n\n // ... etc\n}\n</code></pre>\n\n<p>and now for the best bit :)</p>\n\n<pre><code>public void UserServices : IUserServices\n{\n private readonly IRepository&lt;User&gt; _userRepository;\n\n public UserServices(IRepository&lt;User&gt; userRepository)\n {\n _userRepository = userRepository;\n }\n\n public User FindById(int userId)\n {\n return _userRepository.Find()\n .WithUserId(userId)\n .SingleOrDefault(); // &lt;-- This will be null, if the \n // user doesn't exist\n // in the repository.\n }\n\n // Note: some people might not want the FindBySingle method because this\n // uber method can do that, also. But i wanted to show u the power\n // of having the Repository return an IQuerable.\n public User FindSingle(Expression&lt;Func&lt;User, bool&gt;&gt; predicate)\n {\n return _userRepository\n .Find()\n .SingleOrDefault(predicate);\n }\n}\n</code></pre>\n\n<p>Bonus Points: WTF is <code>WithUserId(userId)</code> in the <code>FindById</code> method? That's a <a href=\"http://www.asp.net/mvc/videos/aspnet-mvc-storefront-part-3-pipes-and-filters\">Pipe and Filter</a>. Use them :) love them :) hug them :) They make your code SOOO much readable :) Now, if u're wanting to know what that does.. this is the extension method.</p>\n\n<pre><code>public static User WithId(this IQueryable&lt;User&gt; source, int userId)\n{\n return source.Where(u =&gt; u.UserId == userId).SingleOrDefault();\n}\n</code></pre>\n\n<p>HTH's even though this question is .. well ... nearly two years old :)</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/164342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3759/" ]
I'm considering one of two IRepository interfaces, one that is a descendant of IQueryable and one that contains IQueryable. Like this: ``` public interface IRepository<T> : IQueryable<T> { T Save(T entity); void Delete(T entity); } ``` Or this: ``` public interface IRepository<T> { T Save(T entity); void Delete(T entity); IQueryable<T> Query(); } ``` LINQ usage would be: ``` from dos in ServiceLocator.Current.GetInstance<IRepository<DomainObject>>() where dos.Id == id select dos ``` Or... ``` from dos in ServiceLocator.Current.GetInstance<IRepository<DomainObject>>().Query where dos.Id == id select dos ``` I kinda like the first one, but it's problematic to mock. How have other people implemented LINQable, mockable repositories?
Depends on if you want a Has-A or an Is-A relationship. The first one is an Is-A relationship. The IRepository interface is a IQueryable interface. The second is a has-a. The IRepository has an IQueryable interface. In the process of writing this, I actually like the second better then the first, simply because when use your second IRepository, I can give the Query() method ANYTHING that returns IQueryable. To me, that is more flexible then the first implementation.
164,344
<p>How can I make my <code>std::fstream</code> object start reading a text file from the second line?</p>
[ { "answer_id": 164353, "author": "Doug T.", "author_id": 8123, "author_profile": "https://Stackoverflow.com/users/8123", "pm_score": 5, "selected": false, "text": "<p>Use getline() to read the first line, then begin reading the rest of the stream.</p>\n\n<pre><code>ifstream stream(\"filename.txt\");\nstring dummyLine;\ngetline(stream, dummyLine);\n// Begin reading your stream here\nwhile (stream)\n ...\n</code></pre>\n\n<p>(Changed to std::getline (thanks dalle.myopenid.com))</p>\n" }, { "answer_id": 164367, "author": "Adam", "author_id": 1366, "author_profile": "https://Stackoverflow.com/users/1366", "pm_score": 1, "selected": false, "text": "<p>Call getline() once to throw away the first line</p>\n\n<p>There are other methods, but the problem is this, you don't know how long the first line will be do you? So you can't skip it till you know where that first '\\n' is. If however you did know how long the first line was going to be, you could simply seek past it, then begin reading, this would be faster.</p>\n\n<p>So to do it the first way would look something like:</p>\n\n<pre><code>#include &lt;fstream&gt;\n#include &lt;iostream&gt;\nusing namespace std;\n\nint main () \n{\n // Open your file\n ifstream someStream( \"textFile.txt\" );\n\n // Set up a place to store our data read from the file\n string line;\n\n // Read and throw away the first line simply by doing\n // nothing with it and reading again\n getline( someStream, line );\n\n // Now begin your useful code\n while( !someStream.eof() ) {\n // This will just over write the first line read\n getline( someStream, line );\n cout &lt;&lt; line &lt;&lt; endl;\n }\n\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 164374, "author": "m_pGladiator", "author_id": 446104, "author_profile": "https://Stackoverflow.com/users/446104", "pm_score": -1, "selected": false, "text": "<pre><code>#include &lt;fstream&gt;\n#include &lt;iostream&gt;\nusing namespace std;\n\nint main () \n{\n char buffer[256];\n ifstream myfile (\"test.txt\");\n\n // first line\n myfile.getline (buffer,100);\n\n // the rest\n while (! myfile.eof() )\n {\n myfile.getline (buffer,100);\n cout &lt;&lt; buffer &lt;&lt; endl;\n }\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 164694, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 5, "selected": false, "text": "<p>You could use the ignore feature of the stream:</p>\n\n<pre><code>ifstream stream(\"filename.txt\");\n\n// Get and drop a line\nstream.ignore ( std::numeric_limits&lt;std::streamsize&gt;::max(), '\\n' );\n\n// Get and store a line for processing.\n// std::getline() has a third parameter the defaults to '\\n' as the line\n// delimiter.\nstd::string line;\nstd::getline(stream,line);\n\nstd::string word;\nstream &gt;&gt; word; // Reads one space separated word from the stream.\n</code></pre>\n\n<h3>A common mistake for reading a file:</h3>\n\n<pre><code>while( someStream.good() ) // !someStream.eof()\n{\n getline( someStream, line );\n cout &lt;&lt; line &lt;&lt; endl;\n}\n</code></pre>\n\n<p>This fails because: When reading the last line it does not read the EOF marker. So the stream is still good, but there is no more data left in the stream to read. So the loop is re-entered. std::getline() then attempts to read another line from someStream and fails, but still write a line to std::cout.</p>\n\nSimple solution:\n\n<pre><code>while( someStream ) // Same as someStream.good()\n{\n getline( someStream, line );\n if (someStream) // streams when used in a boolean context are converted to a type that is usable in that context. If the stream is in a good state the object returned can be used as true\n {\n // Only write to cout if the getline did not fail.\n cout &lt;&lt; line &lt;&lt; endl;\n }\n}\n</code></pre>\n\nCorrect Solution:\n\n<pre><code>while(getline( someStream, line ))\n{\n // Loop only entered if reading a line from somestream is OK.\n // Note: getline() returns a stream reference. This is automatically cast\n // to boolean for the test. streams have a cast to bool operator that checks\n // good()\n cout &lt;&lt; line &lt;&lt; endl;\n}\n</code></pre>\n" }, { "answer_id": 16623167, "author": "Aaron Sterling", "author_id": 2396572, "author_profile": "https://Stackoverflow.com/users/2396572", "pm_score": -1, "selected": false, "text": "<pre><code>#include &lt;iostream&gt;\n#include &lt;fstream&gt;\n#include &lt;string&gt;\n\nusing namespace std;\n\nint main()\n{\nstring textString;\nstring anotherString;\nifstream textFile;\ntextFile.open(\"TextFile.txt\");\nif (textFile.is_open()) {\n while (getline(textFile, textString)){\n anotherString = anotherString + textString;\n }\n}\n\nstd::cout &lt;&lt; anotherString;\n\ntextFile.close();\nreturn 0;\n}\n</code></pre>\n" }, { "answer_id": 25012489, "author": "Arthur P. Golubev", "author_id": 1790694, "author_profile": "https://Stackoverflow.com/users/1790694", "pm_score": 2, "selected": false, "text": "<p>The more efficient way is ignoring strings with <strong>std::istream::ignore</strong></p>\n\n<pre><code>for (int currLineNumber = 0; currLineNumber &lt; startLineNumber; ++currLineNumber){\n if (addressesFile.ignore(numeric_limits&lt;streamsize&gt;::max(), addressesFile.widen('\\n'))){ \n //just skipping the line\n } else \n return HandleReadingLineError(addressesFile, currLineNumber);\n}\n</code></pre>\n\n<p>HandleReadingLineError is not standart but <em>hand-made</em>, of course.\nThe first parameter is maximum number of characters to extract. If this is exactly numeric_limits::max(), there is no limit:\nLink at cplusplus.com: <a href=\"http://www.cplusplus.com/reference/istream/istream/ignore/\" rel=\"nofollow\">std::istream::ignore</a></p>\n\n<p>If you are going to skip a lot of lines you definitely should use it instead of getline: when i needed to skip 100000 lines in my file it took about a second in opposite to 22 seconds with getline.</p>\n" }, { "answer_id": 58258729, "author": "Chabs", "author_id": 12172738, "author_profile": "https://Stackoverflow.com/users/12172738", "pm_score": -1, "selected": false, "text": "<p>this code can read file from your specified line from file but you have to make file in file explorer before hand my file name is \"temp\" code is given below</p>\n\n<p><a href=\"https://i.stack.imgur.com/OTrsj.png\" rel=\"nofollow noreferrer\">https://i.stack.imgur.com/OTrsj.png</a></p>\n\n<p>hope this can help</p>\n" }, { "answer_id": 61342527, "author": "Sina Raoufi", "author_id": 12541646, "author_profile": "https://Stackoverflow.com/users/12541646", "pm_score": -1, "selected": false, "text": "<p>You can use ignore function as follow:</p>\n\n<pre><code>fstream dataFile(\"file.txt\");\ndataFile.ignore(1, '\\n'); // ignore one line\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/164344", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How can I make my `std::fstream` object start reading a text file from the second line?
Use getline() to read the first line, then begin reading the rest of the stream. ``` ifstream stream("filename.txt"); string dummyLine; getline(stream, dummyLine); // Begin reading your stream here while (stream) ... ``` (Changed to std::getline (thanks dalle.myopenid.com))
164,356
<p>For example, I'm writing a multi-threaded time-critical application that processes and streams audio in real-time. Interruptions in the audio are totally unacceptable. Does this mean I cannot use the STL because of the potential slow down when an exception is thrown? </p>
[ { "answer_id": 164377, "author": "Greg Rogers", "author_id": 5963, "author_profile": "https://Stackoverflow.com/users/5963", "pm_score": 5, "selected": false, "text": "<p>Generally, the only exceptions that STL containers will throw by themselves is an std::bad_alloc if new fails. The only other times are when user code (for example constructors, assignments, copy constructors) throws. If your user code never throws then you only have to guard against new throwing, which you would have had to do anyways most likely.</p>\n\n<p>Other things that can throw exceptions:\n- at() functions can throw std::out_of_range if you access them out of bounds. This is a serious program error anyways.</p>\n\n<p>Secondly, exceptions aren't always slow. If an exception occurs in your audio processing, its probably because of a serious error that you will need to handle anyways. The error handling code is probably going to be significantly more expensive than the exception handling code to transport the exception to the catch site.</p>\n" }, { "answer_id": 164384, "author": "Nemanja Trifunovic", "author_id": 8899, "author_profile": "https://Stackoverflow.com/users/8899", "pm_score": 3, "selected": false, "text": "<p>If an STL container throws, you are probably having much bigger problem than the slow down :)</p>\n" }, { "answer_id": 164423, "author": "Henk", "author_id": 4613, "author_profile": "https://Stackoverflow.com/users/4613", "pm_score": 1, "selected": false, "text": "<p>I'm struggling to think which portions of the STL specify that they can raise an exception. In my experience most error handling is handled by return codes or as a prerequisite of the STL's use.\nAn object passed to the STL could definitely raise an exception, e.g. copy constructor, but that would be an issue regardless of the use of STL.\nOthers have mentioned functions such as <code>std::vector::at()</code> but you can perform a check or use an alternate method usually to ensure no exception can be thrown.</p>\n\n<p>Certainly a particular implementation of the STL can performs \"checks\", generally for debug builds, on your use of the STL, I think it will raise an assertion only, but perhaps some will throw an exception.</p>\n\n<p>If there is no try/catch present I believe no/minimal performance hit will be incurred unless an exception is raised by your own classes.</p>\n\n<p>On Visual Studio you can disable the use of C++ exceptions entirely see <code>Project Properties -> C/C++ -> Code Generation -> Enable C++ Exceptions</code>. I presume this is available on most C++ platforms.</p>\n" }, { "answer_id": 164536, "author": "Jeroen Dirks", "author_id": 7743, "author_profile": "https://Stackoverflow.com/users/7743", "pm_score": 2, "selected": false, "text": "<p>Do not be afraid of exceptions with regard to performance. </p>\n\n<p>In the old days of C++ a build with exceptions enabled could be a lot slower on some compilers.</p>\n\n<p>These days it really does not matter if your build with or without exception handling.</p>\n\n<p>In general STL does not throw exceptions unless you run out of memory so that should not be a problem for your type of application either.</p>\n\n<p>(Now do not use a language with GC.....)</p>\n" }, { "answer_id": 164576, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 0, "selected": false, "text": "<p>You talk as if exceptions are inevitable. Simply don't do anything that could cause an exception -- fix your bugs, verify your inputs.</p>\n" }, { "answer_id": 164617, "author": "Roddy", "author_id": 1737, "author_profile": "https://Stackoverflow.com/users/1737", "pm_score": 2, "selected": false, "text": "<p>It's worth noting a couple of points:</p>\n\n<ul>\n<li><p>Your application is multi-threaded. If one thread (maybe a GUI one) is slowed down by an exception, it should not affect the performance of the real-time threads.</p></li>\n<li><p>Exceptions are for exceptional circumstances. If an exception is thrown in your real-time thread, the chances are it will mean that you couldn't continue playing audio anyway. If you find for whatever reason that you are continually processing exceptions in those threads, redesign to avoid the exceptions in the first place.</p></li>\n</ul>\n\n<p>I'd recommend you accept the STL with it's exceptions (unless the STL itself proves too slow - but remember: <strong>measure first, optimise second</strong>), and also to adopt exception handling for your own 'exceptional situations' (audio hardware failure, whatever) in your application.</p>\n" }, { "answer_id": 1281627, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 4, "selected": true, "text": "<p>It's not clearly written in the previous answers, so:</p>\n<h2>Exceptions happen in C++</h2>\n<p>Using the STL or not won't remove the RAII code that will free the objects's resources you allocated.</p>\n<p>For example:</p>\n<pre><code>void doSomething()\n{\n MyString str ;\n doSomethingElse() ;\n}\n</code></pre>\n<p>In the code above, the compiler will generate the code to free the MyString resources (i.e. will call the MyString destructor), no matter what happens in the meantime including if if an exception is thrown by doSomethingElse or if you do a &quot;return&quot; before the end of the function scope.</p>\n<p>If you have a problem with that, then either you should revise your mindset, or try C.</p>\n<h2>Exceptions are supposed to be exceptional</h2>\n<p>Usually, when an exception occurs (<a href=\"https://stackoverflow.com/questions/1897940/in-what-ways-do-c-exceptions-slow-down-code-when-there-are-no-exceptions-thown\">and only when</a>), you'll have a performance hit.</p>\n<p>But then, the exception should only sent when:</p>\n<ul>\n<li>You have an exceptional event to handle (i.e. some kind of error)</li>\n<li>In very exceptional cases (i.e. a &quot;massive return&quot; from multiple function call in the stack, like when doing a complicated search, or unwinding the stack prior a thread graceful interruption)</li>\n</ul>\n<p>The keyword here is &quot;exceptional&quot;, which is good because we are discussing &quot;exception&quot; (see the pattern?).</p>\n<p>In your case, if you have an exception thrown, chances are good something so bad happened your program would have crashed anyway without exception.</p>\n<p>In this case, your problem is not dealing with the performance hit. It is to deal with a graceful handling of the error, or, at worse, graceful termination of your program (including a &quot;Sorry&quot; messagebox, saving unsaved data into a temporary file for later recovery, etc.).</p>\n<p>This means (unless in very exceptional cases), don't use exceptions as &quot;return data&quot;. Throw exceptions when something very bad happens. Catch an exception only if you know what to do with that. Avoid try/catching (unless you know how to handle the exception).</p>\n<h2>What about the STL ?</h2>\n<p>Now that we know that:</p>\n<ul>\n<li>You still want to use C++</li>\n<li>Your aim is not to throw thousand exceptions each and every seconds just for the fun of it</li>\n</ul>\n<p>We should discuss STL:</p>\n<p>STL will (if possible) usually verify if you're doing something wrong with it. And if you do, it will throw an exception. Still, in C++, you usually won't pay for something you won't use.</p>\n<p>An example of that is the access to a vector data.</p>\n<p>If you <b>know</b> you won't go out of bounds, then you should use the operator [].</p>\n<p>If you <b>know</b> you won't verify the bounds, then you should use the method at().</p>\n<p>Example A:</p>\n<pre><code>typedef std::vector&lt;std::string&gt; Vector ;\n\nvoid outputAllData(const Vector &amp; aString)\n{\n for(Vector::size_type i = 0, iMax = aString.size() ; i != iMax ; ++i)\n {\n std::cout &lt;&lt; i &lt;&lt; &quot; : &quot; &lt;&lt; aString[i] &lt;&lt; std::endl ;\n }\n}\n</code></pre>\n<p>Example B:</p>\n<pre><code>typedef std::vector&lt;std::string&gt; Vector ;\n\nvoid outputSomeData(const Vector &amp; aString, Vector::size_type iIndex)\n{\n std::cout &lt;&lt; iIndex &lt;&lt; &quot; : &quot; &lt;&lt; aString.at(iIndex) &lt;&lt; std::endl ;\n}\n</code></pre>\n<p>The example A &quot;trust&quot; the programmer, and no time will be lost in verification (and thus, less chance of an exception thrown <i>at that time</i> if there is an error anyway... Which usually means the error/exception/crash will usually happen after, which won't help debugging and will let more data be corrupted).</p>\n<p>The example B asks the vector to verify the index is correct, and throw an exception if not.</p>\n<p>The choice is yours.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/164356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13760/" ]
For example, I'm writing a multi-threaded time-critical application that processes and streams audio in real-time. Interruptions in the audio are totally unacceptable. Does this mean I cannot use the STL because of the potential slow down when an exception is thrown?
It's not clearly written in the previous answers, so: Exceptions happen in C++ ------------------------ Using the STL or not won't remove the RAII code that will free the objects's resources you allocated. For example: ``` void doSomething() { MyString str ; doSomethingElse() ; } ``` In the code above, the compiler will generate the code to free the MyString resources (i.e. will call the MyString destructor), no matter what happens in the meantime including if if an exception is thrown by doSomethingElse or if you do a "return" before the end of the function scope. If you have a problem with that, then either you should revise your mindset, or try C. Exceptions are supposed to be exceptional ----------------------------------------- Usually, when an exception occurs ([and only when](https://stackoverflow.com/questions/1897940/in-what-ways-do-c-exceptions-slow-down-code-when-there-are-no-exceptions-thown)), you'll have a performance hit. But then, the exception should only sent when: * You have an exceptional event to handle (i.e. some kind of error) * In very exceptional cases (i.e. a "massive return" from multiple function call in the stack, like when doing a complicated search, or unwinding the stack prior a thread graceful interruption) The keyword here is "exceptional", which is good because we are discussing "exception" (see the pattern?). In your case, if you have an exception thrown, chances are good something so bad happened your program would have crashed anyway without exception. In this case, your problem is not dealing with the performance hit. It is to deal with a graceful handling of the error, or, at worse, graceful termination of your program (including a "Sorry" messagebox, saving unsaved data into a temporary file for later recovery, etc.). This means (unless in very exceptional cases), don't use exceptions as "return data". Throw exceptions when something very bad happens. Catch an exception only if you know what to do with that. Avoid try/catching (unless you know how to handle the exception). What about the STL ? -------------------- Now that we know that: * You still want to use C++ * Your aim is not to throw thousand exceptions each and every seconds just for the fun of it We should discuss STL: STL will (if possible) usually verify if you're doing something wrong with it. And if you do, it will throw an exception. Still, in C++, you usually won't pay for something you won't use. An example of that is the access to a vector data. If you **know** you won't go out of bounds, then you should use the operator []. If you **know** you won't verify the bounds, then you should use the method at(). Example A: ``` typedef std::vector<std::string> Vector ; void outputAllData(const Vector & aString) { for(Vector::size_type i = 0, iMax = aString.size() ; i != iMax ; ++i) { std::cout << i << " : " << aString[i] << std::endl ; } } ``` Example B: ``` typedef std::vector<std::string> Vector ; void outputSomeData(const Vector & aString, Vector::size_type iIndex) { std::cout << iIndex << " : " << aString.at(iIndex) << std::endl ; } ``` The example A "trust" the programmer, and no time will be lost in verification (and thus, less chance of an exception thrown *at that time* if there is an error anyway... Which usually means the error/exception/crash will usually happen after, which won't help debugging and will let more data be corrupted). The example B asks the vector to verify the index is correct, and throw an exception if not. The choice is yours.
164,369
<p>While I'm googling/reading for this answer I thought I would also ask here. </p> <p>I have a class that is a wrapper for a SDK. The class accepts an ILoader object and uses the ILoader object to create an ISBAObject which is cast into an ISmallBusinessInstance object. I am simply trying to mock this behavior using Moq.</p> <pre><code> [TestMethod] public void Test_Customer_GetByID() { var mock = new Mock&lt;ILoader&gt;(); var sbainst = new Mock&lt;ISbaObjects&gt;(); mock.Expect(x =&gt; x.GetSbaObjects("")).Returns(sbainst); } </code></pre> <p>The compiler error reads: Error 1 The best overloaded method match for 'Moq.Language.IReturns.Returns(Microsoft.BusinessSolutions.SmallBusinessAccounting.Loader.ISbaObjects)' has some invalid arguments</p> <p>What is going on here? I expected the Mock of ISbaObjects to be able to be returned without a problem.</p>
[ { "answer_id": 164398, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 4, "selected": true, "text": "<p>You need to use sbainst.Object, as sbinst isn't an instance of ISbaObjects - it's just the mock part.</p>\n" }, { "answer_id": 169182, "author": "Trevor Abell", "author_id": 2916, "author_profile": "https://Stackoverflow.com/users/2916", "pm_score": 2, "selected": false, "text": "<p>Updated, correct code</p>\n\n<pre><code>[TestMethod]\npublic void Test_Customer_GetByID()\n{\n var mock = new Mock&lt;ILoader&gt;();\n\n var sbainst = new Mock&lt;ISbaObjects&gt;();\n\n mock.Expect(x =&gt; x.GetSbaObjects(\"\")).Returns(sbainst.Object);\n\n\n}\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/164369", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2916/" ]
While I'm googling/reading for this answer I thought I would also ask here. I have a class that is a wrapper for a SDK. The class accepts an ILoader object and uses the ILoader object to create an ISBAObject which is cast into an ISmallBusinessInstance object. I am simply trying to mock this behavior using Moq. ``` [TestMethod] public void Test_Customer_GetByID() { var mock = new Mock<ILoader>(); var sbainst = new Mock<ISbaObjects>(); mock.Expect(x => x.GetSbaObjects("")).Returns(sbainst); } ``` The compiler error reads: Error 1 The best overloaded method match for 'Moq.Language.IReturns.Returns(Microsoft.BusinessSolutions.SmallBusinessAccounting.Loader.ISbaObjects)' has some invalid arguments What is going on here? I expected the Mock of ISbaObjects to be able to be returned without a problem.
You need to use sbainst.Object, as sbinst isn't an instance of ISbaObjects - it's just the mock part.
164,395
<p>I'm wondering if its possible to add new class data members at run-time in PHP?</p>
[ { "answer_id": 164416, "author": "Eran Galperin", "author_id": 10585, "author_profile": "https://Stackoverflow.com/users/10585", "pm_score": 2, "selected": false, "text": "<p>It is. You can add public members are run time with no additional code, and can affect protected/private members using the magical overloading methods __get() / __set(). See <a href=\"http://www.php.net/manual/en/language.oop5.overloading.php\" rel=\"nofollow noreferrer\">here</a> for more details.</p>\n" }, { "answer_id": 164418, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 5, "selected": true, "text": "<p>Yes.</p>\n\n<pre><code>$prop = 'newname';\n$obj-&gt;$prop = 42;\n</code></pre>\n\n<p>will do the same thing as:</p>\n\n<pre><code>$obj-&gt;newname = 42;\n</code></pre>\n\n<p>Either one will add \"newname\" as a property in $obj if it does not yet exist.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/164395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10708/" ]
I'm wondering if its possible to add new class data members at run-time in PHP?
Yes. ``` $prop = 'newname'; $obj->$prop = 42; ``` will do the same thing as: ``` $obj->newname = 42; ``` Either one will add "newname" as a property in $obj if it does not yet exist.
164,397
<p>How can I print a message to the error console, preferably including a variable? </p> <p>For example, something like:</p> <pre><code>print('x=%d', x); </code></pre>
[ { "answer_id": 164408, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 10, "selected": true, "text": "<p>Install <a href=\"http://en.wikipedia.org/wiki/Firebug_(software)\" rel=\"noreferrer\">Firebug</a> and then you can use <code>console.log(...)</code> and <code>console.debug(...)</code>, etc. (see <a href=\"http://getfirebug.com/wiki/index.php/Console_Panel#Message_types\" rel=\"noreferrer\">the documentation</a> for more).</p>\n" }, { "answer_id": 164542, "author": "Devon", "author_id": 13850, "author_profile": "https://Stackoverflow.com/users/13850", "pm_score": 3, "selected": false, "text": "<p>If you are using <a href=\"http://getfirebug.com/\" rel=\"noreferrer\">Firebug</a> and need to support IE, Safari or Opera as well, <a href=\"http://getfirebug.com/lite.html\" rel=\"noreferrer\">Firebug Lite</a> adds console.log() support to these browsers.</p>\n" }, { "answer_id": 165611, "author": "olliej", "author_id": 784, "author_profile": "https://Stackoverflow.com/users/784", "pm_score": 3, "selected": false, "text": "<p>The <a href=\"http://en.wikipedia.org/wiki/WebKit\" rel=\"nofollow noreferrer\">WebKit</a> Web Inspector also supports <a href=\"http://en.wikipedia.org/wiki/Firebug\" rel=\"nofollow noreferrer\">Firebug's</a> console API (just a minor addition to <a href=\"https://stackoverflow.com/questions/164397/javascript-how-do-i-print-a-message-to-the-error-console/164408#164408\">Dan's answer</a>).</p>\n" }, { "answer_id": 166162, "author": "Ian Oxley", "author_id": 1904, "author_profile": "https://Stackoverflow.com/users/1904", "pm_score": 6, "selected": false, "text": "<p>One good way to do this that works cross-browser is outlined in <em><a href=\"http://www.sitepoint.com/debugging-javascript-throw-away-your-alerts/\" rel=\"noreferrer\">Debugging JavaScript: Throw Away Your Alerts!</a></em>.</p>\n" }, { "answer_id": 3060267, "author": "Ivo Danihelka", "author_id": 101097, "author_profile": "https://Stackoverflow.com/users/101097", "pm_score": 6, "selected": false, "text": "<p>Exceptions are logged into the JavaScript console. You can use that if you want to keep <a href=\"http://en.wikipedia.org/wiki/Firebug_%28software%29\" rel=\"noreferrer\">Firebug</a> disabled.</p>\n\n<pre><code>function log(msg) {\n setTimeout(function() {\n throw new Error(msg);\n }, 0);\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>log('Hello World');\nlog('another message');\n</code></pre>\n" }, { "answer_id": 4306111, "author": "Yuval A.", "author_id": 522169, "author_profile": "https://Stackoverflow.com/users/522169", "pm_score": 3, "selected": false, "text": "<p>A note about 'throw()' mentioned above. It seems that it stops execution of the page completely (I checked in IE8) , so it's not very useful for logging \"on going processes\" (like to track a certain variable...)</p>\n\n<p>My suggestion is perhaps to add a <em>textarea</em> element somewhere in your document and to change (or append to) its <em>value</em> (which would change its text) for logging information whenever needed...</p>\n" }, { "answer_id": 4823263, "author": "dlaliberte", "author_id": 311389, "author_profile": "https://Stackoverflow.com/users/311389", "pm_score": 4, "selected": false, "text": "<p>Here is a solution to the literal question of how to print a message to the browser's error console, not the debugger console. (There might be good reasons to bypass the debugger.)</p>\n\n<p>As I noted in comments about the suggestion to throw an error to get a message in the error console, one problem is that this will interrupt the thread of execution. If you don't want to interrupt the thread, you can throw the error in a separate thread, one created using setTimeout. Hence my solution (which turns out to be an elaboration of the one by Ivo Danihelka):</p>\n\n<pre><code>var startTime = (new Date()).getTime();\nfunction logError(msg)\n{\n var milliseconds = (new Date()).getTime() - startTime;\n window.setTimeout(function () {\n throw( new Error(milliseconds + ': ' + msg, \"\") );\n });\n}\nlogError('testing');\n</code></pre>\n\n<p>I include the time in milliseconds since the start time because the timeout could skew the order in which you might expect to see the messages. </p>\n\n<p>The second argument to the Error method is for the filename, which is an empty string here to prevent output of the useless filename and line number. It is possible to get the caller function but not in a simple browser independent way. </p>\n\n<p>It would be nice if we could display the message with a warning or message icon instead of the error icon, but I can't find a way to do that.</p>\n\n<p>Another problem with using throw is that it could be caught and thrown away by an enclosing try-catch, and putting the throw in a separate thread avoids that obstacle as well. However, there is yet another way the error could be caught, which is if the window.onerror handler is replaced with one that does something different. Can't help you there.</p>\n" }, { "answer_id": 5367944, "author": "Chris S", "author_id": 21574, "author_profile": "https://Stackoverflow.com/users/21574", "pm_score": 3, "selected": false, "text": "<p>As always, Internet&nbsp;Explorer is the big elephant in rollerskates that stops you just simply using <code>console.log()</code>.</p>\n\n<p><a href=\"http://plugins.jquery.com/files/jquery.log.js_0.txt\" rel=\"nofollow\">jQuery's log</a> can be adapted quite easily, but is a pain having to add it everywhere. One solution if you're using jQuery is to put it into your jQuery file at the end, minified first:</p>\n\n<pre><code>function log()\n{\n if (arguments.length &gt; 0)\n {\n // Join for graceful degregation\n var args = (arguments.length &gt; 1) ? Array.prototype.join.call(arguments, \" \") : arguments[0];\n\n // This is the standard; Firebug and newer WebKit browsers support this.\n try {\n console.log(args);\n return true;\n } catch(e) {\n // Newer Opera browsers support posting erros to their consoles.\n try {\n opera.postError(args);\n return true;\n } \n catch(e) \n {\n }\n }\n\n // Catch all; a good old alert box.\n alert(args);\n return false;\n }\n}\n</code></pre>\n" }, { "answer_id": 9664336, "author": "Lukas", "author_id": 1263715, "author_profile": "https://Stackoverflow.com/users/1263715", "pm_score": 4, "selected": false, "text": "<p>If you use <strong>Safari</strong>, you can write</p>\n\n<pre><code>console.log(\"your message here\");\n</code></pre>\n\n<p>and it appears right on the console of the browser.</p>\n" }, { "answer_id": 12516572, "author": "Nicholas", "author_id": 1163414, "author_profile": "https://Stackoverflow.com/users/1163414", "pm_score": 8, "selected": false, "text": "<pre><code>console.error(message); // Outputs an error message to the Web Console\nconsole.log(message); // Outputs a message to the Web Console\nconsole.warn(message); // Outputs a warning message to the Web Console\nconsole.info(message); // Outputs an informational message to the Web Console. In some browsers it shows a small &quot;i&quot; in front of the message.\n</code></pre>\n<p>You also can add CSS:</p>\n<pre><code>console.log('%c My message here', &quot;background: blue; color: white; padding-left:10px;&quot;);\n</code></pre>\n<p>More info can be found here: <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/console\" rel=\"noreferrer\">https://developer.mozilla.org/en-US/docs/Web/API/console</a></p>\n" }, { "answer_id": 19544487, "author": "mmm", "author_id": 1549834, "author_profile": "https://Stackoverflow.com/users/1549834", "pm_score": 0, "selected": false, "text": "<p>This does not print to the Console, but will open you an alert Popup with your message which might be useful for some debugging:</p>\n\n<p>just do:</p>\n\n<pre><code>alert(\"message\");\n</code></pre>\n" }, { "answer_id": 21497693, "author": "D.K", "author_id": 3239530, "author_profile": "https://Stackoverflow.com/users/3239530", "pm_score": 1, "selected": false, "text": "<pre><code>console.log(\"your message here\");\n</code></pre>\n\n<p>working for me.. i'm searching for this.. i used Firefox.\nhere is my Script.</p>\n\n<pre><code> $('document').ready(function() {\nconsole.log('all images are loaded');\n});\n</code></pre>\n\n<p>works in Firefox and Chrome.</p>\n" }, { "answer_id": 22663170, "author": "Yster", "author_id": 1317559, "author_profile": "https://Stackoverflow.com/users/1317559", "pm_score": 3, "selected": false, "text": "<p>To actually answer the question:</p>\n\n<pre><code>console.error('An error occurred!');\nconsole.error('An error occurred! ', 'My variable = ', myVar);\nconsole.error('An error occurred! ' + 'My variable = ' + myVar);\n</code></pre>\n\n<p>Instead of error, you can also use info, log or warn.</p>\n" }, { "answer_id": 30376939, "author": "devSouth555", "author_id": 2464921, "author_profile": "https://Stackoverflow.com/users/2464921", "pm_score": 2, "selected": false, "text": "<p>Visit <a href=\"https://developer.chrome.com/devtools/docs/console-api\" rel=\"nofollow noreferrer\">https://developer.chrome.com/devtools/docs/console-api</a> for a complete console api reference</p>\n\n<pre><code> console.error(object[Obj,....])\\\n</code></pre>\n\n<p>In this case, object would be your error string</p>\n" }, { "answer_id": 32392602, "author": "Kenneth John Falbous", "author_id": 1042251, "author_profile": "https://Stackoverflow.com/users/1042251", "pm_score": 1, "selected": false, "text": "<p>The simplest way to do this is:</p>\n\n<pre><code>console.warn(\"Text to print on console\");\n</code></pre>\n" }, { "answer_id": 40428915, "author": "Parth Raval", "author_id": 5734387, "author_profile": "https://Stackoverflow.com/users/5734387", "pm_score": 2, "selected": false, "text": "<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function foo() {\r\n function bar() {\r\n console.trace(\"Tracing is Done here\");\r\n }\r\n bar();\r\n}\r\n\r\nfoo();</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>console.log(console); //to print console object\r\nconsole.clear('console.clear'); //to clear console\r\nconsole.log('console.log'); //to print log message\r\nconsole.info('console.info'); //to print log message \r\nconsole.debug('console.debug'); //to debug message\r\nconsole.warn('console.warn'); //to print Warning\r\nconsole.error('console.error'); //to print Error\r\nconsole.table([\"car\", \"fruits\", \"color\"]);//to print data in table structure\r\nconsole.assert('console.assert'); //to print Error\r\nconsole.dir({\"name\":\"test\"});//to print object\r\nconsole.dirxml({\"name\":\"test\"});//to print object as xml formate</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<pre><code>To Print Error:- console.error('x=%d', x);\n</code></pre>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>console.log(\"This is the outer level\");\r\nconsole.group();\r\nconsole.log(\"Level 2\");\r\nconsole.group();\r\nconsole.log(\"Level 3\");\r\nconsole.warn(\"More of level 3\");\r\nconsole.groupEnd();\r\nconsole.log(\"Back to level 2\");\r\nconsole.groupEnd();\r\nconsole.log(\"Back to the outer level\");</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 47903642, "author": "jkordas", "author_id": 6034325, "author_profile": "https://Stackoverflow.com/users/6034325", "pm_score": 0, "selected": false, "text": "<p>With es6 syntax you can use:</p>\n\n<pre><code>console.log(`x = ${x}`);\n</code></pre>\n" }, { "answer_id": 50818375, "author": "Aniket Kulkarni", "author_id": 2183868, "author_profile": "https://Stackoverflow.com/users/2183868", "pm_score": 1, "selected": false, "text": "<p>To answer your question you can use ES6 features,</p>\n\n<pre><code>var var=10;\nconsole.log(`var=${var}`);\n</code></pre>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/164397", "https://Stackoverflow.com", "https://Stackoverflow.com/users/116/" ]
How can I print a message to the error console, preferably including a variable? For example, something like: ``` print('x=%d', x); ```
Install [Firebug](http://en.wikipedia.org/wiki/Firebug_(software)) and then you can use `console.log(...)` and `console.debug(...)`, etc. (see [the documentation](http://getfirebug.com/wiki/index.php/Console_Panel#Message_types) for more).
164,400
<p>I'm running SqlServer 2005 express edition on my laptop for development purposes. It seems that when I open a connection to the database, the setup time is REALLY slow. It can take up to 10 seconds to get a connection. I usually have multiple connections open at the same time (Profiler, Development environment, Query Analyser, etc.) I have a hunch that the slow times are related to the fact that I have multiple connections open. </p> <p>Is there a governor in Express edition that throttles connection times when multiple connections are made to an instance?</p> <p>Update: My workstation is not on active directory, and SQL is running mixed mode security. I will try the login with sql authentication. I am not using user instances.</p> <p>Update2: I setup a trace to try and figure out what is going on. When the connection to the database is opened the follow command is executed:</p> <pre><code>master.dbo.sp_MShasdbaccess </code></pre> <p>This command takes 6 seconds to execute.</p>
[ { "answer_id": 164445, "author": "MusiGenesis", "author_id": 14606, "author_profile": "https://Stackoverflow.com/users/14606", "pm_score": 0, "selected": false, "text": "<p>Are you sure the connection is the bottleneck? Is it your conn.Open() line that is taking 10 seconds? </p>\n" }, { "answer_id": 164494, "author": "Duncan Smart", "author_id": 1278, "author_profile": "https://Stackoverflow.com/users/1278", "pm_score": 0, "selected": false, "text": "<p>AFAIK there's no governer anymore in SQL Express. </p>\n\n<p>Now, are you on a Windows Active Directory Domain? If so, there might be an issue with your DNS or something that means the connection to the domain controller to validate your logon to the server instance is taking the time. I suggest you experiment switching the server over to use SQL Security, give the SA account a password, and try logging in as SA and see if that makes a difference.</p>\n" }, { "answer_id": 166317, "author": "Aheho", "author_id": 21155, "author_profile": "https://Stackoverflow.com/users/21155", "pm_score": 3, "selected": true, "text": "<p>I figured it out. The problem was I had multiple databases with AutoClose set to true. I shut it off in all my databases and the problem went away.</p>\n\n<p>see <a href=\"http://www.sqlservercentral.com/articles/Administering/autoclosefordatabases/891/\" rel=\"nofollow noreferrer\">this article</a> for more info.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/164400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21155/" ]
I'm running SqlServer 2005 express edition on my laptop for development purposes. It seems that when I open a connection to the database, the setup time is REALLY slow. It can take up to 10 seconds to get a connection. I usually have multiple connections open at the same time (Profiler, Development environment, Query Analyser, etc.) I have a hunch that the slow times are related to the fact that I have multiple connections open. Is there a governor in Express edition that throttles connection times when multiple connections are made to an instance? Update: My workstation is not on active directory, and SQL is running mixed mode security. I will try the login with sql authentication. I am not using user instances. Update2: I setup a trace to try and figure out what is going on. When the connection to the database is opened the follow command is executed: ``` master.dbo.sp_MShasdbaccess ``` This command takes 6 seconds to execute.
I figured it out. The problem was I had multiple databases with AutoClose set to true. I shut it off in all my databases and the problem went away. see [this article](http://www.sqlservercentral.com/articles/Administering/autoclosefordatabases/891/) for more info.
164,414
<p>I'm processing a file, line-by-line, and I'd like to do an inverse match. For instance, I want to match lines where there is a string of six letters, but only if these six letters are not '<em>Andrea</em>'. How should I do that?</p> <p>I'm using <a href="https://en.wikipedia.org/wiki/RegexBuddy" rel="noreferrer">RegexBuddy</a>, but still having trouble.</p>
[ { "answer_id": 164419, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 8, "selected": true, "text": "<pre><code>(?!Andrea).{6}\n</code></pre>\n<p>Assuming your regexp engine supports negative lookaheads...</p>\n<p>...or maybe you'd prefer to use <code>[A-Za-z]{6}</code> in place of <code>.{6}</code></p>\n<p>Note that lookaheads and lookbehinds are generally not the right way to &quot;inverse&quot; a regular expression match. Regexps aren't really set up for doing negative matching; they leave that to whatever language you are using them with.</p>\n" }, { "answer_id": 164440, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://www.regular-expressions.info/lookaround.html\" rel=\"noreferrer\">Negative lookahead assertion</a></p>\n\n<pre><code>(?!Andrea)\n</code></pre>\n\n<p>This is not exactly an inverted match, but it's the best you can directly do with regex. Not all platforms support them though.</p>\n" }, { "answer_id": 164486, "author": "Hamish Downer", "author_id": 3189, "author_profile": "https://Stackoverflow.com/users/3189", "pm_score": 4, "selected": false, "text": "<p>The capabilities and syntax of the regex implementation matter.</p>\n<p>You could use look-ahead. Using Python as an example,</p>\n<pre><code>import re\n\nnot_andrea = re.compile('(?!Andrea)\\w{6}', re.IGNORECASE)\n</code></pre>\n<p>To break that down:</p>\n<p><strong>(?!Andrea)</strong> means 'match if the next 6 characters are not &quot;Andrea&quot;'; if so then</p>\n<p><strong>\\w</strong> means a &quot;word character&quot; - alphanumeric characters. This is equivalent to the class [a-zA-Z0-9_]</p>\n<p><strong>\\w{6}</strong> means exactly six word characters.</p>\n<p><strong>re.IGNORECASE</strong> means that you will exclude &quot;Andrea&quot;, &quot;andrea&quot;, &quot;ANDREA&quot; ...</p>\n<p>Another way is to use your program logic - use all lines not matching <em>Andrea</em> and put them through a second regex to check for six characters. Or first check for at least six word characters, and then check that it does not match <em>Andrea</em>.</p>\n" }, { "answer_id": 164561, "author": "phreakre", "author_id": 12051, "author_profile": "https://Stackoverflow.com/users/12051", "pm_score": -1, "selected": false, "text": "<p>In Perl you can do:</p>\n<pre><code>process($line) if ($line =~ !/Andrea/);\n</code></pre>\n" }, { "answer_id": 402485, "author": "Jan Goyvaerts", "author_id": 33358, "author_profile": "https://Stackoverflow.com/users/33358", "pm_score": 3, "selected": false, "text": "<p>If you want to do this in RegexBuddy, there are two ways to get a list of all lines not matching a regex.</p>\n\n<p>On the toolbar on the Test panel, set the test scope to \"Line by line\". When you do that, an item List All Lines without Matches will appear under the List All button on the same toolbar. (If you don't see the List All button, click the Match button in the main toolbar.)</p>\n\n<p>On the GREP panel, you can turn on the \"line-based\" and the \"invert results\" checkboxes to get a list of non-matching lines in the files you're grepping through.</p>\n" }, { "answer_id": 1909960, "author": "Dmytro", "author_id": 232398, "author_profile": "https://Stackoverflow.com/users/232398", "pm_score": 6, "selected": false, "text": "<p>For Python/Java, </p>\n\n<pre><code>^(.(?!(some text)))*$\n</code></pre>\n\n<p><a href=\"http://www.lisnichenko.com/articles/javapython-inverse-regex.html\" rel=\"noreferrer\">http://www.lisnichenko.com/articles/javapython-inverse-regex.html</a></p>\n" }, { "answer_id": 27192482, "author": "weakish", "author_id": 222893, "author_profile": "https://Stackoverflow.com/users/222893", "pm_score": 3, "selected": false, "text": "<p><code>(?!</code> is useful in practice. Although strictly speaking, looking ahead is not a regular expression as defined mathematically.</p>\n<p>You can write an inverted regular expression manually.</p>\n<p>Here is <a href=\"http://www.vidarholen.net/contents/junk/files/invert.hs\" rel=\"nofollow noreferrer\">a program</a> to calculate the result automatically.\nIts result is machine generated, which is usually much more complex than hand writing one. But the result works.</p>\n" }, { "answer_id": 38846455, "author": "Zenexer", "author_id": 1188377, "author_profile": "https://Stackoverflow.com/users/1188377", "pm_score": 5, "selected": false, "text": "<p>In <a href=\"https://en.wikipedia.org/wiki/Perl_Compatible_Regular_Expressions\" rel=\"noreferrer\">PCRE</a> and similar variants, you can actually create a regex that matches any line not containing a value:</p>\n<pre><code>^(?:(?!Andrea).)*$\n</code></pre>\n<p>This is called <a href=\"https://stackoverflow.com/a/37343088/1188377\">a tempered greedy token</a>. The downside is that it doesn't perform well.</p>\n" }, { "answer_id": 44287287, "author": "Matthias Herrmann", "author_id": 5111904, "author_profile": "https://Stackoverflow.com/users/5111904", "pm_score": 3, "selected": false, "text": "<p>I just came up with this method which may be hardware intensive but it is working:</p>\n\n<p>You can replace all characters which match the regex by an empty string. </p>\n\n<p>This is a oneliner:</p>\n\n<p><code>notMatched = re.sub(regex, \"\", string)</code></p>\n\n<p>I used this because I was forced to use a very complex regex and couldn't figure out how to invert every part of it within a reasonable amount of time. </p>\n\n<p><strong>This will only return you the string result, not any match objects!</strong></p>\n" }, { "answer_id": 72182648, "author": "Dodo", "author_id": 8567437, "author_profile": "https://Stackoverflow.com/users/8567437", "pm_score": 2, "selected": false, "text": "<p>If you have the possibility to do two regex matches for the inverse and join them together you can use two capturing groups to first capture everything before your regex</p>\n<p><code>^((?!yourRegex).)*</code></p>\n<p>and then capture everything behind your regex</p>\n<p><code>(?&lt;=yourRegex).*</code></p>\n<p>This works for most regexes. One problem I discovered was when I had a quantifier like {2,4} at the end. Then you gotta get creative.</p>\n" } ]
2008/10/02
[ "https://Stackoverflow.com/questions/164414", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21384/" ]
I'm processing a file, line-by-line, and I'd like to do an inverse match. For instance, I want to match lines where there is a string of six letters, but only if these six letters are not '*Andrea*'. How should I do that? I'm using [RegexBuddy](https://en.wikipedia.org/wiki/RegexBuddy), but still having trouble.
``` (?!Andrea).{6} ``` Assuming your regexp engine supports negative lookaheads... ...or maybe you'd prefer to use `[A-Za-z]{6}` in place of `.{6}` Note that lookaheads and lookbehinds are generally not the right way to "inverse" a regular expression match. Regexps aren't really set up for doing negative matching; they leave that to whatever language you are using them with.