qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
331,641
<p>I am dealing with <a href="http://framework.zend.com/manual/en/zend.form.html" rel="nofollow noreferrer"><code>Zend_Form</code></a> right now and I am having a difficult time figuring out how to:</p> <ol> <li>Use custom images for form buttons and,</li> <li>Insert text and links in specific places (in my case I want to put a "forgot your password?" link before the submit button).</li> </ol> <p>I've read through the manual but am not seeing anything about this.</p>
[ { "answer_id": 332133, "author": "monzee", "author_id": 31003, "author_profile": "https://Stackoverflow.com/users/31003", "pm_score": 0, "selected": false, "text": "echo $this->form->element" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/331641", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11252/" ]
331,642
<p>In a bash script I execute a command on a remote machine through ssh. If user breaks the script by pressing Ctrl+C it only stops the script - not even ssh client. Moreover even if I kill ssh client the remote command is still running...</p> <p>How can make bash to kill local ssh client and remote command invocation on Crtl+c?</p> <p>A simple script:</p> <pre><code>#/bin/bash ssh -n -x root@db-host 'mysqldump db' -r file.sql </code></pre>
[ { "answer_id": 331679, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 1, "selected": false, "text": "trap \"some_command\" SIGINT\n some_command help trap ssh ssh -n -x root@db-host 'killall mysqldump' some_command" }, { "answer_id": 337061, "author": "tkokoszka", "author_id": 42201, "author_profile": "https://Stackoverflow.com/users/42201", "pm_score": 6, "selected": true, "text": "#/bin/bash\nssh -t -x root@db-host 'mysqldump db' -r file.sql\n" }, { "answer_id": 1876682, "author": "Peter Cordes", "author_id": 224132, "author_profile": "https://Stackoverflow.com/users/224132", "pm_score": 2, "selected": false, "text": "shopt -s huponexit; your_command ssh -t" }, { "answer_id": 63294615, "author": "Chuck Newman", "author_id": 7490666, "author_profile": "https://Stackoverflow.com/users/7490666", "pm_score": 0, "selected": false, "text": "#!/bin/bash\nAnswer=(Alive Dead)\nIndex=0\nwhile [ ${Index} -eq 0 ]; do\n if ! kill -0 ${PPID} 2> /dev/null ; then Index=1; fi\n echo \"Parent PID ${PPID} is ${Answer[$Index]} at $(date +%Y%m%d%H%M%S%Z)\" > ~/NowTime.txt\n sleep 1\ndone\n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/331642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42201/" ]
331,663
<p>Is there a difference in behavior between adding a control to the ASPX page directly and loading a control programmatically and adding to a placeholder?</p> <p>The control inherits from <code>System.Web.UI.WebControls.DataBoundControl</code>.</p> <p>The reason I ask is that I have a control that works when I add it to the ASPX page like so:</p> <pre><code>... &lt;blah:GoogleMap ID="GoogleMap1" runat="server" Width="640px" Height="600px" ... DataSourceID="_odsMarkers" DataAddressField="Address" DataTextField="Description"&gt; &lt;/blah:GoogleMap&gt; ... </code></pre> <p>But not when I use the following in a codebehind page:</p> <pre><code>GoogleMap map = (GoogleMap)this.LoadControl(typeof(GoogleMap), new object[] { }); //... set properties this.placeholder1.Controls.Add(map); //add to placeholder </code></pre> <p>Anyone have any ideas why this might be the case?</p>
[ { "answer_id": 331734, "author": "Cristian Libardo", "author_id": 16526, "author_profile": "https://Stackoverflow.com/users/16526", "pm_score": 3, "selected": true, "text": "C:\\Windows\\Microsoft.NET\\Framework\\v2.0.50727\\Temporary ASP.NET Files\n" }, { "answer_id": 331850, "author": "Yona", "author_id": 40007, "author_profile": "https://Stackoverflow.com/users/40007", "pm_score": 2, "selected": false, "text": "GoogleMap map = (GoogleMap)this.LoadControl(\"~/Controls/GoogleMap.ascx\");\n GoogleMap map = new GoogleMap();\n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/331663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38522/" ]
331,666
<p>I have the following very simple Javascript-compatible regular expression:</p> <pre><code>&lt;script type="text/javascript" id="(.+)" src="([^"]+)"&gt; </code></pre> <p>I am trying to match on script tags and gather both the ID and src attributes. I'd like to make the order of the attributes irrelevant, so that the following will still match:</p> <pre><code>&lt;script id="..." type="text/javascript" src="..."&gt; &lt;script src="..." id="..." type="text/javascript"&gt; &lt;script id="..." src="..." type="text/javascript"&gt; </code></pre> <p>Is it possible to allow the attributes to appear in any order without compromising its ability to collect the matching ID and src?</p> <p><em>edit</em> The string to match on is coming from innerHTML, making DOM traversal impossible. Also, I cannot use any third party libraries for this specific application.</p>
[ { "answer_id": 331700, "author": "Nick Berardi", "author_id": 17, "author_profile": "https://Stackoverflow.com/users/17", "pm_score": 0, "selected": false, "text": "<script\\s*\\S*\\s*(id=\"([^\"]+)\")?\\s*\\S*\\s*(src=\"([^\"]+)\")\\s*\\S*\\s*(id=\"([^\"]+)\")?[^>]*>\n <script\\s*(([^=]*)=\"([^\"]*)\")+\\s*>\n" }, { "answer_id": 331708, "author": "Nick Berardi", "author_id": 17, "author_profile": "https://Stackoverflow.com/users/17", "pm_score": 1, "selected": false, "text": "$(\"script\").each(function() {\n var src = $(this).attr(\"src\");\n var id = $(this).attr(\"id\");\n\n alert(id + \": \" + src);\n});\n" }, { "answer_id": 331934, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 3, "selected": true, "text": "var html = \"variable/property holding your html source\";\nvar re_script = /<script\\s.+?>/ig;\nvar re_id = /id=\"(.*?)\"/i;\nvar re_src = /src=\"(.*?)\"/i;\n\nvar scriptTag = null;\nwhile (scriptTag = re_script.exec(html))\n{\n var matchId = re_id.exec(scriptTag);\n var matchSrc = re_src.exec(scriptTag);\n\n if (matchId && matchSrc)\n {\n var scriptId = matchId[1];\n var scriptSrc = matchSrc[1];\n alert('Found script ID=\"' + scriptId + '\", SRC=\"' + scriptSrc + '\"');\n }\n}\n $(\"script\").each()" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/331666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8215/" ]
331,690
<p>What is the standard encoding of C++ source code? Does the C++ standard even say something about this? Can I write C++ source in Unicode?</p> <p>For example, can I use non-ASCII characters such as Chinese characters in comments? If so, is full Unicode allowed or just a subset of Unicode? (e.g., that 16-bit first page or whatever it's called.)</p> <p>Furthermore, can I use Unicode for strings? For example:</p> <pre><code>Wstring str=L"Strange chars: â Țđ ě €€"; </code></pre>
[ { "answer_id": 331724, "author": "Head Geek", "author_id": 12193, "author_profile": "https://Stackoverflow.com/users/12193", "pm_score": 4, "selected": false, "text": "warning C4819: The file contains a character that cannot be represented\nin the current code page (932). Save the file in Unicode format to prevent\ndata loss.\n" }, { "answer_id": 331725, "author": "Rob", "author_id": 9236, "author_profile": "https://Stackoverflow.com/users/9236", "pm_score": 3, "selected": false, "text": "std::wstring str = L\"\\u20AC\"; // Euro character\n" }, { "answer_id": 331935, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 6, "selected": true, "text": "char universal-character-names \\uffff \\Uffffffff -finput-charset=charset -fexec-charset=charset utf-8 -fwide-exec-charset=charset utf-16 utf-32 wchar_t" }, { "answer_id": 331982, "author": "coppro", "author_id": 16855, "author_profile": "https://Stackoverflow.com/users/16855", "pm_score": 2, "selected": false, "text": "wchar_t u8\"text\" char16_t char32_t u\"text\" U\"text\" \\uxxxx \\Uxxxxxxxx" }, { "answer_id": 337423, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": 3, "selected": false, "text": "int (*♫)(); const std::set<int> ∅; typedef void ‼; // Also known as \\u203C\nclass ooɟ {\n operator ‼() {}\n};\n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/331690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30187/" ]
331,695
<p>My problem:</p> <p>I'm looking for a way to represent a person's name and address as an encoded id. The id should contain only alpha-numeric characters, be collision-proof, and be represented in a smallest number of characters possible. My first thought was to simply use a cryptographic hash function like MD5 or SHA1, but this seems like overkill (security isn't important - doesn't need to be one-way) and I'd prefer to find something that would produce a shorter id. Does anyone know of an existing algorithm that fits this problem?</p> <p>In other words, what is the best way to implement the following function so that the return value is the same consistently for the same input, collisions are unlikely, and ids are less than 20 characters?</p> <pre><code>&gt;&gt;&gt; make_fake_id(fname = 'Oscar', lname = 'Grouch', stnum = '1', stname = 'Sesame', zip = '12345') N1743123734 </code></pre> <p>Application Context (for those that are interested):</p> <p>This will be used for a <a href="http://en.wikipedia.org/wiki/Record_linkage_problem" rel="nofollow noreferrer">record linkage app</a>. Given an input name and address we search a very large database for the best match and return the database id and other data (how we do this is not important here). If there isn't a match I need to generate this psuedo/generated/derived id from the search input (entity's name and address data). Every search record should result in an output record with either a real (the actual database id resulting from a match/link) or this generated psuedo/generated/derived id. The psuedo id will be prefixed with a character (e.g. N) to differentiate it from a real id.</p>
[ { "answer_id": 331721, "author": "Charles Bretana", "author_id": 32632, "author_profile": "https://Stackoverflow.com/users/32632", "pm_score": -1, "selected": false, "text": "You could use AAAAA01 for first person at first address,\n AAAAA02 for second person at first address,\n AAAAB07 for the seventh resident at the second adresss, etc.\n" }, { "answer_id": 336386, "author": "orip", "author_id": 37020, "author_profile": "https://Stackoverflow.com/users/37020", "pm_score": 2, "selected": false, "text": "N_HASH_CHARS = 11\nimport hashlib, re\ndef digest(name, address):\n hash = hashlib.md5(name + \"|\" + address).digest().encode(\"base64\")\n alnum_hash = re.sub(r'[^a-zA-Z0-9]', \"\", hash)\n return alnum_hash[:N_HASH_CHARS]\n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/331695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42203/" ]
331,731
<p>Is there a way in .net to refer to a control generically (so that if the control name changes, etc.) you don't have a problem.</p> <p>I.e., the object level version of the "me" keyword.</p> <p>So, I'd like to use something generic instead of RadioButton1 in the example below.</p> <pre><code>Private Sub RadioButton1_CheckedChanged(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles RadioButton1.CheckedChanged If RadioButton1.Checked Then Beep() End Sub </code></pre>
[ { "answer_id": 331738, "author": "Patrick Desjardins", "author_id": 13913, "author_profile": "https://Stackoverflow.com/users/13913", "pm_score": 2, "selected": false, "text": "this.checkbox.EventXYZ += new EventXZY(checkedEvent);\n public ... checkedEvent(object sender,...)\n ((RadioButton)sender).....\n" }, { "answer_id": 331742, "author": "Cristian Libardo", "author_id": 16526, "author_profile": "https://Stackoverflow.com/users/16526", "pm_score": 3, "selected": true, "text": "Dim rb as RadioButton = sender\nIf rb.Checked Then...\n" }, { "answer_id": 331803, "author": "thoughtcrimes", "author_id": 37814, "author_profile": "https://Stackoverflow.com/users/37814", "pm_score": 2, "selected": false, "text": "Private Sub rbtn_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs)\n    Dim rbtn As RadioButton = TryCast(sender, RadioButton)\n    If rbtn IsNot Nothing Then\n        If rbtn.Checked Then\n            rbtn.Text = rbtn.Text & \"(checked)\"\n        End If\n    End If\nEnd Sub\n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/331731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4906/" ]
331,744
<p>Is it possible for a JPA entity class to contain two embedded (<code>@Embedded</code>) fields? An example would be:</p> <pre><code>@Entity public class Person { @Embedded public Address home; @Embedded public Address work; } public class Address { public String street; ... } </code></pre> <p>In this case a <code>Person</code> can contain two <code>Address</code> instances - home and work. I'm using JPA with Hibernate's implementation. When I generate the schema using Hibernate Tools, it only embeds one <code>Address</code>. What I'd like is two embedded <code>Address</code> instances, each with its column names distinguished or pre-pended with some prefix (such as home and work). I know of <code>@AttributeOverrides</code>, but this requires that each attribute be individually overridden. This can get cumbersome if the embedded object (<code>Address</code>) gets big as each column needs to be individually overridden.</p>
[ { "answer_id": 9246639, "author": "Philihp Busby", "author_id": 643928, "author_profile": "https://Stackoverflow.com/users/643928", "pm_score": 6, "selected": false, "text": "@Entity \npublic class Person {\n @AttributeOverrides({\n @AttributeOverride(name=\"street\",column=@Column(name=\"homeStreet\")),\n ...\n })\n @Embedded public Address home;\n\n @AttributeOverrides({\n @AttributeOverride(name=\"street\",column=@Column(name=\"workStreet\")),\n ...\n })\n @Embedded public Address work;\n }\n\n @Embeddable public class Address {\n @Basic public String street;\n ...\n }\n}\n" }, { "answer_id": 36043791, "author": "ruediste", "author_id": 1290557, "author_profile": "https://Stackoverflow.com/users/1290557", "pm_score": 3, "selected": false, "text": "public class EmbeddedFieldNamesSessionCustomizer implements SessionCustomizer {\n\n@SuppressWarnings(\"rawtypes\")\n@Override\npublic void customize(Session session) throws Exception {\n Map<Class, ClassDescriptor> descriptors = session.getDescriptors();\n for (ClassDescriptor classDescriptor : descriptors.values()) {\n for (DatabaseMapping databaseMapping : classDescriptor.getMappings()) {\n if (databaseMapping.isAggregateObjectMapping()) {\n AggregateObjectMapping m = (AggregateObjectMapping) databaseMapping;\n Map<String, DatabaseField> mapping = m.getAggregateToSourceFields();\n\n ClassDescriptor refDesc = descriptors.get(m.getReferenceClass());\n for (DatabaseMapping refMapping : refDesc.getMappings()) {\n if (refMapping.isDirectToFieldMapping()) {\n DirectToFieldMapping refDirectMapping = (DirectToFieldMapping) refMapping;\n String refFieldName = refDirectMapping.getField().getName();\n if (!mapping.containsKey(refFieldName)) {\n DatabaseField mappedField = refDirectMapping.getField().clone();\n mappedField.setName(m.getAttributeName() + \"_\" + mappedField.getName());\n mapping.put(refFieldName, mappedField);\n }\n }\n\n }\n }\n\n }\n }\n}\n\n}\n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/331744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24396/" ]
331,755
<p>How do I setup TeamCity 4.0 so that I can access it over port 443 on the internet? e.g. <a href="https://teamcity.mydomain.com" rel="nofollow noreferrer">https://teamcity.mydomain.com</a></p> <p>I am running IIS 7 on the same server that TeamCity is installed. I see two options:</p> <ol> <li><p>Setup TeamCity to use port 8443 and create a reverse proxy in IIS that routes requests to the TeamCity public IP address to the Tomcat port on the internal IP address.</p></li> <li><p>Setup Tomcat to run on a different IP address than IIS 7, and configure TeamCity to run on port 443.</p></li> </ol> <p>I'm not sure on the details of either of these steps.</p>
[ { "answer_id": 1060810, "author": "dvkwong", "author_id": 67613, "author_profile": "https://Stackoverflow.com/users/67613", "pm_score": 0, "selected": false, "text": "LoadModule proxy_module bin/mod_proxy.so \nLoadModule proxy_http_module bin/mod_proxy_http.so\n\nProxyPass /TeamCity http://localhost/TeamCity\nProxyPassReverse /TeamCity http://localhost/TeamCity\n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/331755", "https://Stackoverflow.com", "https://Stackoverflow.com/users/571/" ]
331,757
<p>On Mac OS X, I am running Flex Builder (which is basically a customized Eclipse). When I do a Find it beeps if it cannot find the selected text and when it wraps the search to the top.</p> <p>Is it possible to turn off that beep? I've searched the internet and the preferences pane to no avail.</p>
[ { "answer_id": 16117318, "author": "kevinarpe", "author_id": 257299, "author_profile": "https://Stackoverflow.com/users/257299", "pm_score": 2, "selected": false, "text": "xset b off xset b 0 0 0 .xinitrc .bashrc" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/331757", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27081/" ]
331,758
<p>Let's say I checked in a changelist (in Perforce) with lots of files and I'd like to revert the entire changelist. Is there an easy way to "revert" the entire changelist in one fell swoop?</p> <p>Currently I do something like this for each file in the changelist:</p> <ul> <li>p4 sync //path/to/file#n (where "n" is the previous version of the file)</li> <li>cp file file#n</li> <li>p4 sync //path/to/file</li> <li>p4 edit //path/to/file</li> <li>cp file#n file</li> <li>rm file#n</li> </ul> <p>As you can imagine, this is quite cumbersome for a large changelist.</p>
[ { "answer_id": 22145028, "author": "Arnon Zilca", "author_id": 3374591, "author_profile": "https://Stackoverflow.com/users/3374591", "pm_score": 0, "selected": false, "text": "#!/bin/bash\n\nset -e\n\nif [[ $# -ne 1 ]]; then\necho \"usage: $(basename $0) changelist\"\n exit 1\nfi\n\nCHANGELIST=$1\n\n#make sure changelist exist.\np4 describe -s $CHANGELIST > /dev/null # set -e will exit automatically if fails\n\np4 shelve -d -c $CHANGELIST 2> /dev/null || true # changelist can be shelveless\nfiles_to_revert=$(p4 opened 2> /dev/null | grep \"change $CHANGELIST\" | sed \"s/#.*//g\")\nif [[ -n \"$files_to_revert\" ]]; then\n p4 revert $files_to_revert\nfi\np4 change -d $CHANGELIST\n" }, { "answer_id": 27024627, "author": "Aaron Smith", "author_id": 4055987, "author_profile": "https://Stackoverflow.com/users/4055987", "pm_score": 1, "selected": false, "text": "p4 describe -s [changelist_number] | grep // | sed \"s/\\.\\.\\. //\" | sed \"s/#.*//\" | p4 -ztag -x - where | grep \"... path \" | sed \"s/\\.\\.\\. path //\"\n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/331758", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27020/" ]
331,767
<p>I've created a small python script to toggle between two files I'm using for testing.</p> <p>My question is, what is a good Python format style for the following code:</p> <pre><code>import filecmp import shutil local = "local.txt" remote = "remote.txt" config_file = "C:\some\path\file.txt" shutil.copyfile( remote if( filecmp.cmp(local, config_file ) ) else local, config_file ) </code></pre> <p>Or</p> <pre><code>shutil.copyfile( remote if( filecmp.cmp(local, config_file ) ) else local, config_file ) </code></pre> <p>Or</p> <pre><code>tocopy = remote if( filecmp.cmp( local, config_file ) ) else local shutil.copyfile( tocopy, config_file ) </code></pre> <p>Or what?</p> <p>Also, what is the preferred way to name var in python for many-word names, is it "to_copy", "tocopy", "toCopy", "ToCopy"</p>
[ { "answer_id": 331775, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 3, "selected": false, "text": "source = remote if filecmp.cmp(local, config_file) else local\n\nshutil.copyfile(source, config_file)\n def copy_to(source, destination):\n shutil.copyfile(source,destination)\n\nif filecmp.cmp(local, config_file):\n copy_to(remote, config_file)\nelse:\n copy_to(local, config_file)\n" }, { "answer_id": 331776, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 5, "selected": true, "text": "if filecmp.cmp(local, config_file):\n shutil.copyfile(remote, config_file)\nelse:\n shutil.copyfile(local, config_file)\n y if x else z" }, { "answer_id": 331788, "author": "Patrick Harrington", "author_id": 41165, "author_profile": "https://Stackoverflow.com/users/41165", "pm_score": 3, "selected": false, "text": "if foo == 'blah':\n do_blah_thing()\ndo_one()\ndo_two()\ndo_three()\n if filecmp.cmp(local, config_file):\n shutil.copyfile(remote, config_file)\nelse:\n shutil.copyfile(local, config_file)\n if foo == 'blah': do_blah_thing()\ndo_one(); do_two(); do_three()\n" }, { "answer_id": 331906, "author": "Tim Lesher", "author_id": 14942, "author_profile": "https://Stackoverflow.com/users/14942", "pm_score": 3, "selected": false, "text": "import filecmp\nimport shutil\n\nlocal = \"local.txt\"\nremote = \"remote.txt\"\n\ndestination = r\"C:\\some\\path\\file.txt\"\nsource = remote if filecmp.cmp(local, destination) else local\n\nshutil.copyfile(source, destination)\n" }, { "answer_id": 331923, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "import filecmp\nimport shutil\n\nlocal = \"local.txt\"\nremote = \"remote.txt\"\nconfig_file = \"C:\\some\\path\\file.txt\"\n\n\nif filecmp.cmp( local, config_file):\n to_copy = remote\nelse:\n to_copy = local\n\n\nshutil.copyfile( to_copy, config_file )\n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/331767", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20654/" ]
331,770
<pre><code>SELECT avg(con_hits) as avg_hits FROM content WHERE con_type = 1 AND con_posttime &lt; $twelve_hrs_ago AND con_refresh = 0 ORDER BY con_posttime DESC LIMIT 100 </code></pre> <p>I would like it to go to the first record that was posted at least 12 hours ago (denoted by the <code>$twelve_hrs_ago</code> variable which has the suitable timestamp), and take the average of the <code>con_hits</code> column, for the next 100 records. In my example, it disregards the <code>LIMIT</code>, and takes the average of every record in the table.</p> <p>Is there a way to bypass that?</p>
[ { "answer_id": 331783, "author": "troelskn", "author_id": 18180, "author_profile": "https://Stackoverflow.com/users/18180", "pm_score": 5, "selected": true, "text": "LIMIT AVG SELECT avg(con_hits) as avg_hits\nFROM (\n SELECT con_hits\n FROM content\n WHERE\n con_type = 1\n AND con_posttime < $twelve_hrs_ago\n AND con_refresh = 0\n ORDER BY con_posttime DESC\n LIMIT 100\n) x;\n $twelve_hrs_ago date_add(now(), interval -12 hour)\n" }, { "answer_id": 331792, "author": "Rob", "author_id": 34224, "author_profile": "https://Stackoverflow.com/users/34224", "pm_score": 1, "selected": false, "text": "\nSELECT avg(con_hits) as avg_hits FROM (\n SELECT con_hits FROM content \n WHERE con_type = 1 AND con_posttime < $twelve_hrs_ago AND con_refresh = 0\n ORDER BY con_posttime DESC\n LIMIT 100\n ) \n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/331770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
331,777
<p>What are my options for running Java 6 on OS X? </p> <p>I have an MacBook Pro Intel Core Duo running Mac OS X 10.4. Do I have any options for running Java 6 on this hardware and OS?</p> <p>Related questions: Which Macs (either current or forthcoming) support 64-bit computing? Are there any Apple laptops (either current or forthcoming) that will have a 64 bit architecture?</p> <p>Any relevant links would be appreciated.</p>
[ { "answer_id": 1379197, "author": "Marcus Adams", "author_id": 168493, "author_profile": "https://Stackoverflow.com/users/168493", "pm_score": 2, "selected": false, "text": "$ export JAVA_HOME=/Users/madams/Desktop/soylatte16-i386-1.0.3\n$ export PATH=/Users/madams/Desktop/soylatte16-i386-1.0.3/bin:$PATH\n$ java -jar /Users/madams/Desktop/test.jar\n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/331777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32174/" ]
331,786
<p>If I understand correctly the .net runtime will always clean up after me. So if I create new objects and I stop referencing them in my code, the runtime will clean up those objects and free the memory they occupied.</p> <p>Since this is the case why then do some objects need to have a destructor or dispose method? Won’t the runtime clean up after them when they are not referenced anymore?</p>
[ { "answer_id": 331795, "author": "Yona", "author_id": 40007, "author_profile": "https://Stackoverflow.com/users/40007", "pm_score": 8, "selected": true, "text": "Dispose Dispose Dispose public void Log(string line)\n{\n var sw = new StreamWriter(File.Open(\n \"LogFile.log\", FileMode.OpenOrCreate, FileAccess.Write, FileShare.None));\n\n sw.WriteLine(line);\n\n // Since we don't close the stream the FileStream finalizer will do that for \n // us but we don't know when that will be and until then the file is locked.\n}\n StreamWriter public void Log(string line)\n{\n using (var sw = new StreamWriter(File.Open(\n \"LogFile.log\", FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))) {\n\n sw.WriteLine(line);\n }\n\n // Since we use the using block (which conveniently calls Dispose() for us)\n // the file well be closed at this point.\n}\n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/331786", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42214/" ]
331,794
<p>I added a text file to a testapp's solution and I want to read said file. I don't remember how to do this, I know it has to do with reflections but I need a push in the right direction.</p>
[ { "answer_id": 331819, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 1, "selected": false, "text": "String My.Resources.name_of_file Dim content = My.Computer.FileSystem.ReadAllText(\"filename\")\n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/331794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25515/" ]
331,855
<p>I need to check whether a page is being redirected or not without actually downloading the content. I just need the final URL. What's the best way of doing this is Python? Thanks!</p>
[ { "answer_id": 331871, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 1, "selected": false, "text": "urllib2 info()" }, { "answer_id": 331890, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 4, "selected": true, "text": "urllib urllib2 httplib import httplib\n\nh = httplib.HTTPConnection('www.example.com')\nh.request('HEAD', '/')\nresponse = h.getresponse()\n\n// Check for 30x status code\nif 300 <= response.status < 400:\n // It's a redirect\n location = response.getheader('Location')\n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/331855", "https://Stackoverflow.com", "https://Stackoverflow.com/users/280/" ]
331,856
<p>I may be barking up the wrong tree... However, what I have is a MySQL server that accepts connections only from a client with a valid SSL cert (see <a href="http://dev.mysql.com/doc/refman/5.0/en/secure-create-certs.html" rel="nofollow noreferrer">this link</a>). This works great for example with Rails. I have my database on one server, and a Rails app that connects using the client certificate. Maybe not the fastest, but it works.</p> <p>The configuration in <strong>database.yml</strong> looks something like this:</p> <pre><code>sslkey: /path/to/client-key.pem sslcert: /path/to/client-cert.pem sslca: /path/to/ca-cert.pem </code></pre> <p>The problem is that I'd like to host phpMyAdmin on the same server as the Rails app. I think that phpMyAdmin is simply more limited in its connection options because I can't seem to find a way for it to use a client certificate to connect. But what I found odd was that Googling for answers didn't turn up much on this subject (which makes me wonder if I'm taking the wrong approach to this).</p> <p>Obviously, I can easily set up phpMyAdmin itself to be hosted behind an SSL certificate (which will encrypt requests between the client browser and my phpMyAdmin server) but I want the phpMyAdmin &lt;-&gt; db connection to be encrypted as well.</p> <p>Is this possible? Is this a bad design choice? Are there better ways to do this?</p>
[ { "answer_id": 331895, "author": "Stepan Mazurov", "author_id": 40786, "author_profile": "https://Stackoverflow.com/users/40786", "pm_score": 4, "selected": true, "text": "config.inc.php $cfg['Servers'][$i]['ssl']=true; \n" }, { "answer_id": 60654570, "author": "Ken Silverman", "author_id": 13051432, "author_profile": "https://Stackoverflow.com/users/13051432", "pm_score": 2, "selected": false, "text": "conf.d phpmyadmin phpmyadmin phpmyadmin cert" }, { "answer_id": 66492771, "author": "jszoja", "author_id": 621659, "author_profile": "https://Stackoverflow.com/users/621659", "pm_score": 2, "selected": false, "text": "// IP address of your instance\n$cfg['Servers'][$i]['host'] = '8.8.8.8';\n// Use SSL for connection\n$cfg['Servers'][$i]['ssl'] = true;\n// Client secret key\n$cfg['Servers'][$i]['ssl_key'] = '../client-key.pem';\n// Client certificate\n$cfg['Servers'][$i]['ssl_cert'] = '../client-cert.pem';\n// Server certification authority\n$cfg['Servers'][$i]['ssl_ca'] = '../server-ca.pem';\n// Disable SSL verification (see above note)\n$cfg['Servers'][$i]['ssl_verify'] = false;\n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/331856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39034/" ]
331,862
<p>I'm switching between different Java SDKs (1.4.2, 1.5.0 and 1.6.0) for various projects. I would like to set the JAVA_HOME environment variable on my Windows XP machine without going through the tedious My Computer -> Advanced -> [Select System Variable] -> Edit -> Ok -> Ok</p> <p>Is it possible to do this from the command line, or is there a utility that can do this?</p> <p>(Note that I am not referring to the standard batch file "SET" command - I want to set the environment variable "globally," not just for the life of a console window).</p>
[ { "answer_id": 331898, "author": "Patrick Cuff", "author_id": 7903, "author_profile": "https://Stackoverflow.com/users/7903", "pm_score": 1, "selected": false, "text": "set args = WScript.Arguments\nSet objShell = WScript.CreateObject(\"WScript.Shell\")\nSet colSystemEnvVars = objShell.Environment(\"System\")\nSet colUserEnvVars = objShell.Environment(\"User\")\n\n' Parse args\nselect case args.Count\ncase 0, 1, 2\n help\ncase 3\n sVariable = args(0)\n sValue = args(1)\n sScope = UCase(args(2))\n sMode = \"\"\ncase 4\n sVariable = args(0)\n sValue = args(1)\n sScope = UCase(args(2))\n sMode = UCase(args(3))\nend select\n\nselect case sScope\n case \"S\"\n if sMode = \"A\" then\n sValue = colSystemEnvVars(sVariable) & sValue\n end if\n colSystemEnvVars(sVariable) = sValue\n case \"U\"\n if sMode = \"A\" then\n sValue = colUserEnvVars(sVariable) & sValue\n end if\n colUserEnvVars(sVariable) = sValue\n case else\n help\nend select\n\nWScript.Quit\n\n'******************************************************************************\nSub help()\n WScript.Echo \"\"\n WScript.Echo \"Create or update an environment variable.\"\n WScript.Echo \"\"\n WScript.Echo \"usage:\"\n WScript.Echo \"======\" \n WScript.Echo \"cscript SetVar.vbs variable value {S|U} [A]\"\n WScript.Echo \"\"\n WScript.Echo \"eg:\"\n WScript.Echo \"===\" \n WScript.Echo \"cscript SetVar.vbs MYVAR 'Hello world' U\"\n WScript.Echo \"cscript SetVar.vbs PATH 'C:\\MyPath' S A\"\n\n WScript.Quit\nEnd Sub \n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/331862", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7507/" ]
331,889
<p>I have an input file that I want to sort based on timestamp which is a substring of each record. I want to store multiple attributes of the </p> <p>The list is currently about 1000 records. But, I want it to be able to scale up a bit just in case.</p> <p>When I did it with a Linked List by searching the entire list for insertion it took about 20 seconds. Now, just filling up a vector and outputting to file is taking 4 seconds (does that sound too long)?</p> <p>I would like to use merge sort or quick sort (merge sort appears to be a little easier to me). The trouble that I'm running into is that I don't see many examples of implementing these sorts using objects rather than primitive data types.</p> <p>I could use either a vector or Linked list. The feedback that I've gotten from this site has been most helpful so far. I'm hoping that someone can sprinkle on the magic pixie dust to make this easier on me :)</p> <p>Any links or examples on the easiest way to do this with pretty decent performance would be most appreciated. I'm getting stuck on how to implement these sorts with objects because I'm newbie at C++ :)</p> <p>Here's what my new code looks like (no sorting yet):</p> <pre><code>class CFileInfo { public: std::string m_PackLine; std::string m_FileDateTime; int m_NumDownloads; }; void main() { CFileInfo packInfo; vector&lt;CFileInfo&gt; unsortedFiles; vector&lt;CFileInfo&gt;::iterator Iter; packInfo.m_PackLine = "Sample Line 1"; packInfo.m_FileDateTime = "06/22/2008 04:34"; packInfo.m_NumDownloads = 0; unsortedFiles.push_back(packInfo); packInfo.m_PackLine = "Sample Line 2"; packInfo.m_FileDateTime = "12/05/2007 14:54"; packInfo.m_NumDownloads = 1; unsortedFiles.push_back(packInfo); for (Iter = unsortedFiles.begin(); Iter != unsortedFiles.end(); ++Iter ) { cout &lt;&lt; " " &lt;&lt; (*Iter).m_PackLine; } } </code></pre>
[ { "answer_id": 331897, "author": "Paul Nathan", "author_id": 26227, "author_profile": "https://Stackoverflow.com/users/26227", "pm_score": 2, "selected": false, "text": " <algorithm>\n" }, { "answer_id": 331910, "author": "Edouard A.", "author_id": 41363, "author_profile": "https://Stackoverflow.com/users/41363", "pm_score": 3, "selected": false, "text": "struct sort_functor\n{\n bool operator()(const CFileInfo & a, const CFileInfo & b) const\n {\n\n // may be a little bit more subtle depending on what your strings look like\n return a.m_FileDateTime < b.m_FileDateTime;\n }\n}\n\nstd::sort(unsortedFiles.begin(), unsortedFile.end(), sort_functor());\n std::sort(unsortedFiles.begin(), \n unsortedFile.end(),\n bind(&CFileInfo::m_FileDateTime, _1) < bind(&CFileInfo::m_FileDateTime, _2));\n" }, { "answer_id": 333105, "author": "Mr.Ree", "author_id": 37946, "author_profile": "https://Stackoverflow.com/users/37946", "pm_score": 4, "selected": true, "text": "#define PRINT(DATA,N) for(int i=0; i<N; i++) { cout << (i>0?\", \":\"\") << DATA[i]; } cout << endl;\n\nint\nmain() \n{\n // Creating and Sorting a stack-based array.\n int d [10] = { 1, 4, 0, 2, 8, 6, 3, 5, 9, 7 };\n PRINT(d,10);\n sort( d, d+10 );\n PRINT(d,10);\n\n cout << endl;\n\n // Creating a vector.\n int eData [10] = { 1, 4, 0, 2, 8, 6, 3, 5, 9, 7 };\n vector<int> e;\n for(int i=0; i<10; i++ )\n e.push_back( eData[i] );\n\n // Sorting a vector.\n PRINT(e,10);\n sort(e.begin(), e.end());\n PRINT(e,10);\n}\n class Data\n{ \npublic: \n string m_PackLine; \n string m_FileDateTime; \n int m_NumberDownloads;\n\n /* Lets simplify creating Data elements down below. */\n Data( const string & thePackLine = \"\",\n const string & theDateTime = \"\",\n int theDownloads = 0 )\n : m_PackLine ( thePackLine ),\n m_FileDateTime ( theDateTime ),\n m_NumberDownloads ( theDownloads )\n { }\n\n /* Can't use constructor with arrays */\n void set( const string & thePackLine,\n const string & theDateTime,\n int theDownloads = 0 )\n {\n m_PackLine = thePackLine;\n m_FileDateTime = theDateTime;\n m_NumberDownloads = theDownloads;\n }\n\n /* Lets simplify printing out down below. */ \n ostream & operator<<( ostream & theOstream ) const\n {\n theOstream << \"PackLine=\\\"\" << m_PackLine\n << \"\\\" fileDateTime=\\\"\" << m_FileDateTime\n << \"\\\" downloads=\" << m_NumberDownloads;\n return theOstream;\n }\n\n\n /*\n * This is IT! All you need to add to use sort()!\n * Note: Sort is just on m_FileDateTime. Everything else is superfluous.\n * Note: Assumes \"YEAR/MONTH/DAY HOUR:MINUTE\" format.\n */\n bool operator< ( const Data & theOtherData ) const\n { return m_FileDateTime < theOtherData.m_FileDateTime; }\n\n};\n\n /* Rest of simplifying printing out down below. */ \nostream & operator<<( ostream & theOstream, const Data & theData )\n { return theData.operator<<( theOstream ); }\n\n\n /* Printing out data set. */\n#define PRINT(DATA,N) for(int i=0; i<N; i++) { cout << \"[\" << i << \"] \" << DATA[i] << endl; } cout << endl;\n\nint\nmain()\n{ \n // Creating a stack-based array.\n Data d [10];\n d[0].set( \"Line 1\", \"2008/01/01 04:34\", 1 );\n d[1].set( \"Line 4\", \"2008/01/04 04:34\", 4 );\n d[2].set( \"Line 0\", \"2008/01/00 04:34\", 0 );\n d[3].set( \"Line 2\", \"2008/01/02 04:34\", 2 );\n d[4].set( \"Line 8\", \"2008/01/08 04:34\", 8 );\n d[5].set( \"Line 6\", \"2008/01/06 04:34\", 6 );\n d[6].set( \"Line 3\", \"2008/01/03 04:34\", 3 );\n d[7].set( \"Line 5\", \"2008/01/05 04:34\", 5 );\n d[8].set( \"Line 9\", \"2008/01/09 04:34\", 9 );\n d[9].set( \"Line 7\", \"2008/01/07 04:34\", 7 );\n\n // Sorting a stack-based array.\n PRINT(d,10);\n sort( d, d+10 );\n PRINT(d,10);\n\n cout << endl;\n\n // Creating a vector.\n vector<Data> e;\n e.push_back( Data( \"Line 1\", \"2008/01/01 04:34\", 1 ) );\n e.push_back( Data( \"Line 4\", \"2008/01/04 04:34\", 4 ) );\n e.push_back( Data( \"Line 0\", \"2008/01/00 04:34\", 0 ) );\n e.push_back( Data( \"Line 2\", \"2008/01/02 04:34\", 2 ) );\n e.push_back( Data( \"Line 8\", \"2008/01/08 04:34\", 8 ) );\n e.push_back( Data( \"Line 6\", \"2008/01/06 04:34\", 6 ) );\n e.push_back( Data( \"Line 3\", \"2008/01/03 04:34\", 3 ) );\n e.push_back( Data( \"Line 5\", \"2008/01/05 04:34\", 5 ) );\n e.push_back( Data( \"Line 9\", \"2008/01/09 04:34\", 9 ) );\n e.push_back( Data( \"Line 7\", \"2008/01/07 04:34\", 7 ) );\n\n // Sorting a vector.\n PRINT(e,10);\n sort(e.begin(), e.end());\n PRINT(e,10);\n}\n" }, { "answer_id": 339273, "author": "Mr.Ree", "author_id": 37946, "author_profile": "https://Stackoverflow.com/users/37946", "pm_score": 0, "selected": false, "text": "#define SHOW(X) cout << # X \" = \" << (X)\n\nint\nmain()\n{\n const string s = \"2008/12/03 12:48\";\n struct tm datetime;\n time_t t;\n\n memset( & datetime, 0, sizeof(datetime) );\n\n if ( 5 != sscanf( s.c_str(), \"%d/%d/%d %d:%d\",\n & datetime.tm_year,\n & datetime.tm_mon,\n & datetime.tm_mday,\n & datetime.tm_hour,\n & datetime.tm_min ) )\n {\n cout << \"FAILED to parse: \\\"\" << s << \"\\\"\" << endl;\n exit(-1);\n }\n\n /* tm_year - The number of years since 1900. */\n datetime.tm_year -= 1900;\n\n /* tm_mon - The number of months since January, in the range 0 to 11. */\n datetime.tm_mon --;\n\n /* tm_mday - The day of the month, in the range 1 to 31. */\n /* tm_hour - The number of hours past midnight, in the range 0 to 23. */\n /* tm_min - The number of minutes after the hour, in the range 0 to 59. */\n // No change.\n\n /* If using mktime, you may need these to force UTC time:\n * setenv(\"TZ\",\"\",1);\n * tzset();\n */\n\n t = mktime( & datetime );\n\n SHOW( t ) << endl;\n SHOW( asctime( & datetime ) );\n SHOW( ctime( & t ) );\n}\n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/331889", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39360/" ]
331,918
<p>I'm attempting to use Python to convert a multi-page PDF into a series of JPEGs. I can split the PDF up into individual pages easily enough with available tools, but I haven't been able to find anything that can covert PDFs to images.</p> <p>PIL does not work, as it can't read PDFs. The two options I've found are using either GhostScript or ImageMagick through the shell. This is not a viable option for me, since this program needs to be cross-platform, and I can't be sure either of those programs will be available on the machines it will be installed and used on.</p> <p>Are there any Python libraries out there that can do this?</p>
[ { "answer_id": 36113000, "author": "Idan Yacobi", "author_id": 5459259, "author_profile": "https://Stackoverflow.com/users/5459259", "pm_score": 3, "selected": false, "text": "import ghostscript\n\ndef pdf2jpeg(pdf_input_path, jpeg_output_path):\n args = [\"pdf2jpeg\", # actual value doesn't matter\n \"-dNOPAUSE\",\n \"-sDEVICE=jpeg\",\n \"-r144\",\n \"-sOutputFile=\" + jpeg_output_path,\n pdf_input_path]\n ghostscript.Ghostscript(*args)\n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/331918", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21885/" ]
331,937
<p>I'm building a GUI class for C++ and dealing a lot with pointers. An example call:</p> <pre><code>mainGui.activeWindow-&gt;activeWidget-&gt;init(); </code></pre> <p>My problem here is that I want to cast the <strong>activeWidget</strong> pointer to another type. <strong>activeWidget</strong> is of type GUI_BASE. Derived from BASE I have other classes, such as GUI_BUTTON and GUI_TEXTBOX. I want to cast the <strong>activeWidget</strong> pointer from GUI_BASE to GUI_TEXTBOX. I assume it would look something like this:</p> <pre><code>(GUI_TEXTBOX*)(mainGui.activeWindow-&gt;activeWidget)-&gt;function(); </code></pre> <p>This isn't working, because the compiler still thinks the pointer is of type GUI_BASE. The following bit of code does work, however:</p> <pre><code>GUI_TEXTBOX *textbox_pointer; textbox_pointer = (GUI_TEXTBOX*)mainGui.activeWindow-&gt;activeWidget; textbox_pointer-&gt;function(); </code></pre> <p>I'm hoping my problem here is just a syntax issue. Thanks for the help :)</p>
[ { "answer_id": 331942, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 2, "selected": false, "text": "((GUI_TEXTBOX*)(mainGui.activeWindow->activeWidget))->function();\n ((GUI_TEXTBOX*)mainGui.activeWindow->activeWidget)->function();\n" }, { "answer_id": 331943, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 0, "selected": false, "text": "((GUI_TEXTBOX*)(mainGui.activeWindow->activeWidget))->function();\n" }, { "answer_id": 331948, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 5, "selected": true, "text": "((GUI_TEXTBOX*)mainGui.activeWindow->activeWidget)->function(); // Extra parentheses\ndynamic_cast<GUI_TEXTBOX*>(mainGui.activeWindow->activeWidget)->function(); // C++ style cast\n" }, { "answer_id": 331956, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 2, "selected": false, "text": "((GUI_TEXTBOX*)(mainGui.activeWindow->activeWidget))->function();\n -> dynamic_cast<>" }, { "answer_id": 331962, "author": "Brian", "author_id": 16457, "author_profile": "https://Stackoverflow.com/users/16457", "pm_score": 1, "selected": false, "text": "->" }, { "answer_id": 332004, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 3, "selected": false, "text": "GUI_TEXTBOX* textboxPointer = dynamic_cast<GUI_TEXTBOX*>(mainGui.activeWindow->activeWidget);\nif (textboxPointer)\n{\n // If activeWidget is not a text box then dynamic_cast\n // will return a NULL.\n textboxPointer->textBoxMethod();\n}\n\n// or \n\ndynamic_cast<GUI_TEXTBOX&>(*mainGui.activeWindow->activeWidget).textBoxMethod();\n\n// This will throw bad_cast if the activeWidget is not a GUI_TEXTBOX\n" }, { "answer_id": 332017, "author": "Carl", "author_id": 13760, "author_profile": "https://Stackoverflow.com/users/13760", "pm_score": 0, "selected": false, "text": "if( GUI_TEXTBOX* ptr = \n dynamic_cast<GUI_TEXTBOX *>(mainGui.activeWindow->activeWidget) )\n{\n ptr->function();\n}\n" }, { "answer_id": 332347, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 1, "selected": false, "text": "dynamic_cast<GUI_TEXTBOX&>(*mainGui.activeWindow->activeWidget).function();\n std::bad_cast static_cast<GUI_TEXTBOX*>(mainGui.activeWindow->activeWidget)->function();\n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/331937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42224/" ]
331,953
<p>I recently came across this in some code - basically someone trying to create a large object, coping when there's not enough heap to create it:</p> <pre><code>try { // try to perform an operation using a huge in-memory array byte[] massiveArray = new byte[BIG_NUMBER]; } catch (OutOfMemoryError oome) { // perform the operation in some slower but less // memory intensive way... } </code></pre> <p>This doesn't seem right, since Sun themselves recommend that you shouldn't try to catch <code>Error</code> or its subclasses. We discussed it, and another idea that came up was explicitly checking for free heap:</p> <pre><code>if (Runtime.getRuntime().freeMemory() &gt; SOME_MEMORY) { // quick memory-intensive approach } else { // slower, less demanding approach } </code></pre> <p>Again, this seems unsatisfactory - particularly in that picking a value for <code>SOME_MEMORY</code> is difficult to easily relate to the job in question: for some arbitrary large object, how can I estimate how much memory its instantiation might need?</p> <p>Is there a better way of doing this? Is it even possible in Java, or is any idea of managing memory below the abstraction level of the language itself? </p> <p><strong>Edit 1:</strong> in the first example, it might actually be feasible to estimate the amount of memory a <code>byte[]</code> of a given length might occupy, but is there a more generic way that extends to arbitrary large objects?</p> <p><strong>Edit 2:</strong> as @erickson points out, there are ways to estimate the size of an object once it's created, but (ignoring a statistical approach based on previous object sizes) is there a way of doing so for yet-uncreated objects?</p> <p>There also seems to be some debate as to whether it's reasonable to catch <code>OutOfMemoryError</code> - anyone know anything conclusive?</p>
[ { "answer_id": 332022, "author": "jsight", "author_id": 1432, "author_profile": "https://Stackoverflow.com/users/1432", "pm_score": 2, "selected": false, "text": "System.gc()" }, { "answer_id": 332023, "author": "OscarRyz", "author_id": 20654, "author_profile": "https://Stackoverflow.com/users/20654", "pm_score": 2, "selected": false, "text": "-Xmx \n java -Xmx8g some.name.YourMemConsumingApp\n if (isEnoughMemory(SOME_MEMORY)) {\n strategy = new InMemoryStrategy();\n} else {\n strategy = new DiskStrategy();\n}\n\nstrategy.performTheAction();\n ...\nstrategy = new ImaginaryCloudComputingStrategy();\n...\n while( !isDone() ) {\n if (isMemoryLow()) {\n //Runtime.getRuntime().freeMemory() < SOME_MEMORY + some other validations \n swapToDisk(); // and make sure resources are GC'able\n }\n\n byte [] array new byte[PREDEFINED_BUFFER_SIZE];\n process( array );\n\n process( array );\n}\n\ncleanUp();\n" }, { "answer_id": 332031, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 2, "selected": false, "text": "System.gc() OutOfMemoryError" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/331953", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21849/" ]
331,963
<p>I'm trying to "single source" a form page which can be in edit mode or view mode. For various reasons, this isn't using the ASP.Net FormView or DetailsView controls.</p> <p>Since there is no way to disable a textbox without turning its contents gray (well, we could "eat" all of the keystrokes into it, but that isn't very elegant either) and disabling a dropdown list or listbox isn't what we want, our first try was to duplicate all of the form input controls with a label and use CSS to select which ones are visible depending on the mode of the form. That works, but it's ugly to edit and the code-behind has to populate both controls every time.</p> <p>We could control the visibility in the code-behind to avoid filling both controls, but we still have to add them both to the form.</p> <p>So I had the idea to use jQuery to swap out the input controls for <code>&lt;label&gt;</code>, <code>&lt;div&gt;</code>, or <code>&lt;span&gt;</code> elements. This works, to some extent, by creating the appropriate selectors and using the <code>replace()</code> jQuery method to swap out the elements dynamically.</p> <p>The problem is that I not only need to copy the contents, but also the styles, attributes, and sizing of the original input controls (at this point we're only talking about textboxes - we have a different solution for dropdown lists and listboxes). </p> <p>Brute force should work - "backup" all of the attributes of the input control, create the new "read only" element, then replace the input control with the new element. What I'm looking for is something simpler.</p> <p>Succinctly, using jQuery, what is the best way to replace a textbox with a label and have the label have the same contents and appear in the same location and style as the textbox?</p> <p>Here is what I have so far:</p> <pre><code>$(":text").each( function() { var oldClass = $(this).attr("class"); var oldId = $(this).attr("id"); var oldHeight = $(this).outerHeight(); var oldWidth = $(this).outerWidth(); var oldStyle = $(this).attr("style"); $(this).replaceWith("&lt;div id='" + oldId + "'&gt;" + $(this).val() + "&lt;/div&gt;"); $("div#" + oldId).attr("class", oldClass); $("div#" + oldId).attr("style", oldStyle); $("div#" + oldId).width(oldWidth); $("div#" + oldId).height(oldHeight); $("div#" + oldId).css("display", "inline-block"); }); </code></pre>
[ { "answer_id": 331997, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 1, "selected": false, "text": "<input <select <input" }, { "answer_id": 332246, "author": "Benry", "author_id": 28408, "author_profile": "https://Stackoverflow.com/users/28408", "pm_score": 3, "selected": true, "text": "<input> <textarea> \"input[readonly] {}\"" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/331963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14894/" ]
331,972
<p>I'm working on a menu-generating HtmlHelper extension method. This method will need to know which Action is being executed. So if Home/Index is executing, the extension method would show all links to other actions that're "coordinated." In a sense, all I need to know during the execution of the Home controller's Index action is the name of the Controller and the name of the Action that are being executed so that other logic can be executed. Is this possible?</p>
[ { "answer_id": 331998, "author": "Nick Berardi", "author_id": 17, "author_profile": "https://Stackoverflow.com/users/17", "pm_score": 3, "selected": true, "text": "var action = HtmlHelper.ViewContext.RouteData.Values[\"action\"];\nvar controller = HtmlHelper.ViewContext.RouteData.Values[\"controller\"];\n" }, { "answer_id": 332077, "author": "Tim Scott", "author_id": 29493, "author_profile": "https://Stackoverflow.com/users/29493", "pm_score": 0, "selected": false, "text": "filterContext.RouteData.Values[\"action\"].ToString();\n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/331972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28686/" ]
331,976
<p>I'm attempting to use the following code to serialize an anonymous type to JSON:</p> <pre><code>var serializer = new DataContractJsonSerializer(thing.GetType()); var ms = new MemoryStream(); serializer.WriteObject(ms, thing); var json = Encoding.Default.GetString(ms.ToArray()); </code></pre> <p>However, I get the following exception when this is executed:</p> <blockquote> <p>Type '&lt;>f__AnonymousType1`3[System.Int32,System.Int32,System.Object[]]' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. See the Microsoft .NET Framework documentation for other supported types.</p> </blockquote> <p>I can't apply attributes to an anonymous type (as far as I know). Is there another way to do this serialization or am I missing something? </p>
[ { "answer_id": 331983, "author": "Nick Berardi", "author_id": 17, "author_profile": "https://Stackoverflow.com/users/17", "pm_score": 8, "selected": true, "text": "JavaScriptSerializer serializer = new JavaScriptSerializer();\nvar output = serializer.Serialize(your_anon_object);\n" }, { "answer_id": 332325, "author": "Paul", "author_id": 41301, "author_profile": "https://Stackoverflow.com/users/41301", "pm_score": 1, "selected": false, "text": "[System.Web.Script.Services.ScriptService]\n [ScriptMethod(ResponseFormat = ResponseFormat.Json)]\n" }, { "answer_id": 3508497, "author": "mythz", "author_id": 85785, "author_profile": "https://Stackoverflow.com/users/85785", "pm_score": 4, "selected": false, "text": "var customer = new Customer { Name=\"Joe Bloggs\", Age=31 };\nvar json = customer.ToJson();\nvar fromJson = json.FromJson<Customer>(); \n" }, { "answer_id": 5461193, "author": "harryovers", "author_id": 202241, "author_profile": "https://Stackoverflow.com/users/202241", "pm_score": -1, "selected": false, "text": "public static class JsonSerializer\n{\n public static string Serialize<T>(this T data)\n {\n try\n {\n DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));\n var stream = new MemoryStream();\n serializer.WriteObject(stream, data);\n string jsonData = Encoding.UTF8.GetString(stream.ToArray(), 0, (int)stream.Length);\n stream.Close();\n return jsonData;\n }\n catch\n {\n return \"\";\n }\n }\n public static T Deserialize<T>(this string jsonData)\n {\n try\n {\n DataContractJsonSerializer slzr = new DataContractJsonSerializer(typeof(T));\n var stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonData));\n T data = (T)slzr.ReadObject(stream);\n stream.Close();\n return data;\n }\n catch\n {\n return default(T);\n }\n }\n}\n" }, { "answer_id": 10524654, "author": "Matthew Nichols", "author_id": 165031, "author_profile": "https://Stackoverflow.com/users/165031", "pm_score": 6, "selected": false, "text": "return JsonConvert.SerializeObject(\n new\n {\n DataElement1,\n SomethingElse\n });\n" }, { "answer_id": 23826527, "author": "i31nGo", "author_id": 1345106, "author_profile": "https://Stackoverflow.com/users/1345106", "pm_score": 4, "selected": false, "text": "var obj = new {Id = thing.Id, Name = thing.Name, Age = 30};\nJavaScriptSerializer serializer = new JavaScriptSerializer();\nstring json = serializer.Serialize(obj);\n" }, { "answer_id": 57787817, "author": "Ahmet Arslan", "author_id": 2115690, "author_profile": "https://Stackoverflow.com/users/2115690", "pm_score": 3, "selected": false, "text": "var warningJSON = JsonConvert.SerializeObject(new {\n warningMessage = \"You have been warned...\"\n });\n var warningJSON = JsonSerializer.Serialize(new {\n warningMessage = \"You have been warned...\"\n });\n" }, { "answer_id": 64759452, "author": "SmartE", "author_id": 8606289, "author_profile": "https://Stackoverflow.com/users/8606289", "pm_score": 3, "selected": false, "text": "var model = new Model\n{\n Name = \"Test Name\",\n Age = 5\n};\n\nstring json = JsonSerializer.Serialize(model);\n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/331976", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4541/" ]
331,992
<p>My list (@degree) is built from a SQL command. The NVL command in the SQL isn't working, neither are tests such as:</p> <pre><code>if (@degree[$i] == "") if (@degree[$i] == " ") if (@degree[$i] == '') if (@degree[$i] == -1) if (@degree[$i] == 0) if (@degree[$i] == ()) if (@degree[$i] == undef) </code></pre> <p>$i is a counter variable in a for loop. Basically it goes through and grabs unique degrees from a table and ends up creating <code>("AFA", "AS", "AAS", "", "BS")</code>. The list is not always this long, and the empty element is not always in that position 3.</p> <p>Can anyone help?</p> <p>I want to either test during the for loop, or after the loop completes for where this empty element is and then replace it with the word, "OTHER".</p> <p>Thanks for anything -Ken</p>
[ { "answer_id": 332011, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 4, "selected": true, "text": "if (defined($degree[$i]))" }, { "answer_id": 334663, "author": "derobert", "author_id": 27727, "author_profile": "https://Stackoverflow.com/users/27727", "pm_score": 1, "selected": false, "text": "COALESCE SELECT COALESCE(column, 'no value') AS column FROM whatever ...\n" }, { "answer_id": 334693, "author": "Yanick", "author_id": 10356, "author_profile": "https://Stackoverflow.com/users/10356", "pm_score": 3, "selected": false, "text": "my @degree = ('AFA', 'AS', 'AAS', '', 'BS');\n\n$_ ||= 'OTHER' for @degree;\n\nprint join ' ' => @degree; # prints 'AFA AS AAS OTHER BS'\n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/331992", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42229/" ]
331,996
<p>I'm having quite a bit of pain inserting and deleting UITableViewCells from the same UITableView!</p> <p>I don't normally post code, but I thought this was the best way of showing where I'm having the problem:</p> <hr> <pre><code>- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 5; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { if (iSelectedSection == section) return 5; return 1; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { //NSLog(@"drawing row:%d section:%d", [indexPath row], [indexPath section]); static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease]; } if (iSelectedSection == [indexPath section]) { cell.textColor = [UIColor redColor]; } else { cell.textColor = [UIColor blackColor]; } cell.text = [NSString stringWithFormat:@"Section: %d Row: %d", [indexPath section], [indexPath row]]; // Set up the cell return cell; } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { // Navigation logic -- create and push a new view controller if ([indexPath row] == 0) { NSMutableArray *rowsToRemove = [NSMutableArray array]; NSMutableArray *rowsToAdd = [NSMutableArray array]; for(int i=0; i&lt;5; i++) { //NSLog(@"Adding row:%d section:%d ", i, [indexPath section]); //NSLog(@"Removing row:%d section:%d ", i, iSelectedSection); [rowsToAdd addObject:[NSIndexPath indexPathForRow:i inSection:[indexPath section]]]; [rowsToRemove addObject:[NSIndexPath indexPathForRow:i inSection:iSelectedSection]]; } iSelectedSection = [indexPath section]; [tableView beginUpdates]; [tableView deleteRowsAtIndexPaths:rowsToRemove withRowAnimation:YES]; [tableView insertRowsAtIndexPaths:rowsToAdd withRowAnimation:YES]; [tableView endUpdates]; } } </code></pre> <hr> <p>This code creates 5 sections, the 1st (indexed from 0) with 5 rows. When you select a section - it removes the rows from the section you had previously selected and adds rows to the section you just selected.</p> <p>Pictorally, when I load up the app, I have something like this:</p> <p><a href="http://www.freeimagehosting.net/uploads/1b9f2d57e7.png" rel="noreferrer">http://www.freeimagehosting.net/uploads/1b9f2d57e7.png http://www.freeimagehosting.net/uploads/1b9f2d57e7.png</a></p> <p>Image here: <a href="http://www.freeimagehosting.net/uploads/1b9f2d57e7.png" rel="noreferrer">http://www.freeimagehosting.net/uploads/1b9f2d57e7.png</a></p> <p>After selecting a table row 0 of section 2, I then delete the rows of section 1 (which is selected by default) and add the rows of section 2. But I get this:</p> <p><a href="http://www.freeimagehosting.net/uploads/6d5d904e84.png" rel="noreferrer">http://www.freeimagehosting.net/uploads/6d5d904e84.png http://www.freeimagehosting.net/uploads/6d5d904e84.png</a></p> <p>Image here: <a href="http://www.freeimagehosting.net/uploads/6d5d904e84.png" rel="noreferrer">http://www.freeimagehosting.net/uploads/6d5d904e84.png</a></p> <p>...which isn't what I expect to happen! It seems like the first row of section 2 somehow remains - even though it definitly gets deleted.</p> <p>If I just do a [tableView reloadData], everything appears as normal... but I obviously forefit the nice animations.</p> <p>I'd really appreciate it if someone could shine some light here! It's driving me a little crazy!</p> <p>Thanks again, Nick.</p>
[ { "answer_id": 332097, "author": "e.James", "author_id": 33686, "author_profile": "https://Stackoverflow.com/users/33686", "pm_score": 0, "selected": false, "text": "for (int i=1; i<5; i++)\n{\n // ...\n}" }, { "answer_id": 351133, "author": "codelogic", "author_id": 43427, "author_profile": "https://Stackoverflow.com/users/43427", "pm_score": 1, "selected": false, "text": "- (void)tableView:(UITableView *)tableView \n didSelectRowAtIndexPath:(NSIndexPath *)indexPath {\n // ....\n [self performSelectorOnMainThread: @selector(insertRows:)\n withObject: someObjectOrNil]; // double check args\n}\n\n- (void) insertRows: (NSObject*)someObjectOrNil {\n [tableView beginUpdates];\n // update logic\n [tableView endUpdates];\n\n // don't call reloadData here, but ensure that data returned from the \n // table view delegate functions are in sync\n}\n" }, { "answer_id": 913640, "author": "samvermette", "author_id": 87158, "author_profile": "https://Stackoverflow.com/users/87158", "pm_score": 3, "selected": false, "text": "NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];\n[tableView beginUpdates];\n[dataSource insertObject:[artistField text] atIndex:0];\n[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationTop];\n[tableView endUpdates];\n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/331996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1221378/" ]
332,005
<p>When I look at a directory in Windows Explorer, I can see a ProductName and ProductVersion property for the DLL's in that directory.</p> <p>I need to export this DLL list with ProductName and ProductVersion into a text file.</p> <p>If I do <code>c:\&gt;dir *.dll &gt; test.log</code>, the test.log does not have the ProductName and ProductVersion.</p> <p>Could someone help me to get these properties exported to a file along with the filename?</p> <p>Even if it is a freeware tool or some other <code>dir</code> switch, that will be useful.</p>
[ { "answer_id": 332015, "author": "Dirk Vollmar", "author_id": 40347, "author_profile": "https://Stackoverflow.com/users/40347", "pm_score": 2, "selected": true, "text": "Set objShell = CreateObject (\"Shell.Application\")\nSet objFolder = objShell.Namespace (\"C:\\Scripts\")\nSet objFSO = CreateObject(\"Scripting.FileSystemObject\")\nDim arrHeaders(40)\n\nFor i = 0 to 40\n arrHeaders(i) = objFolder.GetDetailsOf (objFolder.Items, i)\nNext\n\nFor Each strFileName in objFolder.Items\n For i = 0 to 40\n Wscript.echo arrHeaders(i) & \": \" & objFolder.GetDetailsOf (strFileName, i) \n Next\n Wscript.Echo\nNext\n" }, { "answer_id": 332024, "author": "Patrick Harrington", "author_id": 41165, "author_profile": "https://Stackoverflow.com/users/41165", "pm_score": 0, "selected": false, "text": "SYNTAX\n~~~~~~\nStrFInfo[.EXE] ExeDllOcxFileName [Property1 [Property2 ...]]\n\nCOMMON PROPERTIES\n~~~~~~~~~~~~~~~~~\nFileDescription FileVersion InternalName\nOriginalFileName ProductName ProductVersion\nCompanyName LegalCopyRight $Translation\n" }, { "answer_id": 332029, "author": "Andrew Flanagan", "author_id": 39034, "author_profile": "https://Stackoverflow.com/users/39034", "pm_score": 1, "selected": false, "text": "using System;\nusing System.Diagnostics;\n\nstatic class MainClass\n{\n static void Main(string[] args)\n {\n\n FileVersionInfo info = FileVersionInfo.GetVersionInfo(\"c:\\\\test.txt\");\n\n // Display version information.\n Console.WriteLine(\"Checking File: \" + info.FileName);\n Console.WriteLine(\"Product Name: \" + info.ProductName);\n Console.WriteLine(\"Product Version: \" + info.ProductVersion);\n Console.WriteLine(\"Company Name: \" + info.CompanyName);\n\n }\n}\n" }, { "answer_id": 332081, "author": "Stefan", "author_id": 19307, "author_profile": "https://Stackoverflow.com/users/19307", "pm_score": 1, "selected": false, "text": "Sub CreateLog(ByVal Logfile As String, ByVal PathToLog As String, Optional ByVal SearchPattern As String = \"*.*\")\n\n Dim FileInfo As FileVersionInfo\n Dim ret As String = \"\"\n For Each File As String In IO.Directory.GetFiles(PathToLog, SearchPattern)\n FileInfo = FileVersionInfo.GetVersionInfo(File)\n If FileInfo.ProductName & FileInfo.ProductVersion <> \"\" Then\n ret &= FileInfo.ProductName & \", \" & FileInfo.ProductVersion & vbCrLf\n End If\n Next\n\n IO.File.WriteAllText(Logfile, ret)\n\nEnd Sub\n" }, { "answer_id": 332186, "author": "Dan Blanchard", "author_id": 5460, "author_profile": "https://Stackoverflow.com/users/5460", "pm_score": 2, "selected": false, "text": "dir c:\\windows\\*.dll | % {[System.Diagnostics.FileVersionInfo]::GetVersionInfo($_)} | % { $_.ProductName + \", \" + $_.ProductVersion + \", \" + $_.FileName} > test.log" }, { "answer_id": 332350, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 0, "selected": false, "text": "Set shell = CreateObject(\"Shell.Application\")\nSet folder = shell.Namespace(\"D:\\Documents\")\n\nSet fso = CreateObject(\"Scripting.FileSystemObject\")\nFor Each fileName in folder.Items\n i = 0\n emptyNb = 0\n Do\n detail = folder.GetDetailsOf(folder.Items, i)\n If detail = \"\" Then\n emptyNb = emptyNb + 1\n Else\n detailValue = folder.GetDetailsOf(fileName, i)\n If detailValue <> \"\" Then\n Wscript.Echo i & \" \" & detail & \": \" & detailValue\n End If\n emptyNb = 0\n End If\n i = i + 1\n Loop While emptyNb < 3 ' Arbirary, adjust as you see fit\n detailValue = folder.GetDetailsOf(fileName, -1)\n If detailValue <> \"\" Then\n Wscript.Echo \"Tooltip:\" & vbCrLf & detailValue\n End If\n Wscript.Echo\nNext\n detail" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/332005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32670/" ]
332,030
<p>What are the proper uses of:</p> <ul> <li><a href="https://en.cppreference.com/w/cpp/language/static_cast" rel="noreferrer"><code>static_cast</code></a></li> <li><a href="https://en.cppreference.com/w/cpp/language/dynamic_cast" rel="noreferrer"><code>dynamic_cast</code></a></li> <li><a href="https://en.cppreference.com/w/cpp/language/const_cast" rel="noreferrer"><code>const_cast</code></a></li> <li><a href="https://en.cppreference.com/w/cpp/language/reinterpret_cast" rel="noreferrer"><code>reinterpret_cast</code></a></li> <li><a href="https://en.cppreference.com/w/cpp/language/explicit_cast" rel="noreferrer"><code>(type)value</code></a> (C-style cast)</li> <li><a href="https://en.cppreference.com/w/cpp/language/explicit_cast" rel="noreferrer"><code>type(value)</code></a> (function-style cast)</li> </ul> <p>How does one decide which to use in which specific cases?</p>
[ { "answer_id": 332054, "author": "andreas buykx", "author_id": 19863, "author_profile": "https://Stackoverflow.com/users/19863", "pm_score": 4, "selected": false, "text": "reinterpret_cast dynamic_cast static_cast dynamic_cast" }, { "answer_id": 332070, "author": "Fred Larson", "author_id": 10077, "author_profile": "https://Stackoverflow.com/users/10077", "pm_score": 9, "selected": false, "text": "dynamic_cast static_cast reinterpret_cast const_cast const/volatile" }, { "answer_id": 332086, "author": "coppro", "author_id": 16855, "author_profile": "https://Stackoverflow.com/users/16855", "pm_score": 13, "selected": true, "text": "static_cast int float void* static_cast T(something) (T)something T(something, something_else) static_cast virtual static_cast const_cast const reinterpret_cast const const const const const const const_cast volatile dynamic_cast dynamic_cast nullptr std::bad_cast dynamic_cast virtual protected private reinterpret_cast int reinterpret_cast reinterpret_cast (type)object type(object) const_cast static_cast static_cast const_cast reinterpret_cast reinterpret_cast const_cast reinterpret_cast static_cast reinterpret_cast static_cast" }, { "answer_id": 21249454, "author": "Sumit Arora", "author_id": 671170, "author_profile": "https://Stackoverflow.com/users/671170", "pm_score": 8, "selected": false, "text": "OnEventData(void* pData)\n\n{\n ......\n\n // pData is a void* pData, \n\n // EventData is a structure e.g. \n // typedef struct _EventData {\n // std::string id;\n // std:: string remote_id;\n // } EventData;\n\n // On Some Situation a void pointer *pData\n // has been static_casted as \n // EventData* pointer \n\n EventData *evtdata = static_cast<EventData*>(pData);\n .....\n}\n void DebugLog::OnMessage(Message *msg)\n{\n static DebugMsgData *debug;\n static XYZMsgData *xyz;\n\n if(debug = dynamic_cast<DebugMsgData*>(msg->pdata)){\n // debug message\n }\n else if(xyz = dynamic_cast<XYZMsgData*>(msg->pdata)){\n // xyz message\n }\n else/* if( ... )*/{\n // ...\n }\n}\n // *Passwd declared as a const\n\nconst unsigned char *Passwd\n\n\n// on some situation it require to remove its constness\n\nconst_cast<unsigned char*>(Passwd)\n typedef unsigned short uint16;\n\n// Read Bytes returns that 2 bytes got read. \n\nbool ByteBuffer::ReadUInt16(uint16& val) {\n return ReadBytes(reinterpret_cast<char*>(&val), 2);\n}\n" }, { "answer_id": 30558433, "author": "Serge Rogatch", "author_id": 1915854, "author_profile": "https://Stackoverflow.com/users/1915854", "pm_score": 4, "selected": false, "text": "static_cast reinterpret_cast CoCreateInstance() void** void** static_cast reinterpret_cast<void**>(&yourPointer) #include <windows.h>\n#include <netfw.h>\n.....\nINetFwPolicy2* pNetFwPolicy2 = nullptr;\nHRESULT hr = CoCreateInstance(__uuidof(NetFwPolicy2), nullptr,\n CLSCTX_INPROC_SERVER, __uuidof(INetFwPolicy2),\n //static_cast<void**>(&pNetFwPolicy2) would give a compile error\n reinterpret_cast<void**>(&pNetFwPolicy2) );\n static_cast reinterpret_cast #include <windows.h>\n#include <netfw.h>\n.....\nINetFwPolicy2* pNetFwPolicy2 = nullptr;\nvoid* tmp = nullptr;\nHRESULT hr = CoCreateInstance(__uuidof(NetFwPolicy2), nullptr,\n CLSCTX_INPROC_SERVER, __uuidof(INetFwPolicy2),\n &tmp );\npNetFwPolicy2 = static_cast<INetFwPolicy2*>(tmp);\n" }, { "answer_id": 41082284, "author": "Shital Shah", "author_id": 207661, "author_profile": "https://Stackoverflow.com/users/207661", "pm_score": 7, "selected": false, "text": "float int static_cast A B static_cast B A A A::operator B() B A A* B* A& B& (Base*) (Derived*) A* B* A& B& set<T> T& SomeClass::foo() const T& SomeClass::foo() const float int float" }, { "answer_id": 51965683, "author": "Timmy_A", "author_id": 3599970, "author_profile": "https://Stackoverflow.com/users/3599970", "pm_score": 4, "selected": false, "text": "(Type) var Type(var) int a=rand(); // Random number.\n\nint* pa1=reinterpret_cast<int*>(a); // OK. Here developer clearly expressed he wanted to do this potentially dangerous operation.\n\nint* pa2=static_cast<int*>(a); // Compiler error.\nint* pa3=dynamic_cast<int*>(a); // Compiler error.\n\nint* pa4=(int*) a; // OK. C-style cast can do such cast. The question is if it was intentional or developer just did some typo.\n\n*pa4=5; // Program crashes.\n" }, { "answer_id": 53878614, "author": "pkthapa", "author_id": 1163286, "author_profile": "https://Stackoverflow.com/users/1163286", "pm_score": 3, "selected": false, "text": "struct Foo{};\nstruct Bar{};\n\nint main(int argc, char** argv)\n{\n Foo* f = new Foo;\n\n Bar* b1 = f; // (1)\n Bar* b2 = static_cast<Bar*>(f); // (2)\n Bar* b3 = dynamic_cast<Bar*>(f); // (3)\n Bar* b4 = reinterpret_cast<Bar*>(f); // (4)\n Bar* b5 = const_cast<Bar*>(f); // (5)\n\n return 0;\n}\n" }, { "answer_id": 60414256, "author": "Ciro Santilli OurBigBook.com", "author_id": 895245, "author_profile": "https://Stackoverflow.com/users/895245", "pm_score": 4, "selected": false, "text": "static_cast dynamic_cast reinterpret_cast static_cast dyanamic_cast static_cast nullptr nullptr static_cast dynamic_cast -NDEBUG static_cast reinterpret_cast #include <iostream>\n\nstruct B1 {\n B1(int int_in_b1) : int_in_b1(int_in_b1) {}\n virtual ~B1() {}\n void f0() {}\n virtual int f1() { return 1; }\n int int_in_b1;\n};\n\nstruct B2 {\n B2(int int_in_b2) : int_in_b2(int_in_b2) {}\n virtual ~B2() {}\n virtual int f2() { return 2; }\n int int_in_b2;\n};\n\nstruct D : public B1, public B2 {\n D(int int_in_b1, int int_in_b2, int int_in_d)\n : B1(int_in_b1), B2(int_in_b2), int_in_d(int_in_d) {}\n void d() {}\n int f2() { return 3; }\n int int_in_d;\n};\n\nint main() {\n B2 *b2s[2];\n B2 b2{11};\n D *dp;\n D d{1, 2, 3};\n\n // The memory layout must support the virtual method call use case.\n b2s[0] = &b2;\n // An upcast is an implicit static_cast<>().\n b2s[1] = &d;\n std::cout << \"&d \" << &d << std::endl;\n std::cout << \"b2s[0] \" << b2s[0] << std::endl;\n std::cout << \"b2s[1] \" << b2s[1] << std::endl;\n std::cout << \"b2s[0]->f2() \" << b2s[0]->f2() << std::endl;\n std::cout << \"b2s[1]->f2() \" << b2s[1]->f2() << std::endl;\n\n // Now for some downcasts.\n\n // Cannot be done implicitly\n // error: invalid conversion from ‘B2*’ to ‘D*’ [-fpermissive]\n // dp = (b2s[0]);\n\n // Undefined behaviour to an unrelated memory address because this is a B2, not D.\n dp = static_cast<D*>(b2s[0]);\n std::cout << \"static_cast<D*>(b2s[0]) \" << dp << std::endl;\n std::cout << \"static_cast<D*>(b2s[0])->int_in_d \" << dp->int_in_d << std::endl;\n\n // OK\n dp = static_cast<D*>(b2s[1]);\n std::cout << \"static_cast<D*>(b2s[1]) \" << dp << std::endl;\n std::cout << \"static_cast<D*>(b2s[1])->int_in_d \" << dp->int_in_d << std::endl;\n\n // Segfault because dp is nullptr.\n dp = dynamic_cast<D*>(b2s[0]);\n std::cout << \"dynamic_cast<D*>(b2s[0]) \" << dp << std::endl;\n //std::cout << \"dynamic_cast<D*>(b2s[0])->int_in_d \" << dp->int_in_d << std::endl;\n\n // OK\n dp = dynamic_cast<D*>(b2s[1]);\n std::cout << \"dynamic_cast<D*>(b2s[1]) \" << dp << std::endl;\n std::cout << \"dynamic_cast<D*>(b2s[1])->int_in_d \" << dp->int_in_d << std::endl;\n\n // Undefined behaviour to an unrelated memory address because this\n // did not calculate the offset to get from B2* to D*.\n dp = reinterpret_cast<D*>(b2s[1]);\n std::cout << \"reinterpret_cast<D*>(b2s[1]) \" << dp << std::endl;\n std::cout << \"reinterpret_cast<D*>(b2s[1])->int_in_d \" << dp->int_in_d << std::endl;\n}\n\n g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o main.out main.cpp\nsetarch `uname -m` -R ./main.out\ngdb -batch -ex \"disassemble/rs main\" main.out\n setarch &d 0x7fffffffc930\nb2s[0] 0x7fffffffc920\nb2s[1] 0x7fffffffc940\nb2s[0]->f2() 2\nb2s[1]->f2() 3\nstatic_cast<D*>(b2s[0]) 0x7fffffffc910\nstatic_cast<D*>(b2s[0])->int_in_d 1\nstatic_cast<D*>(b2s[1]) 0x7fffffffc930\nstatic_cast<D*>(b2s[1])->int_in_d 3\ndynamic_cast<D*>(b2s[0]) 0\ndynamic_cast<D*>(b2s[1]) 0x7fffffffc930\ndynamic_cast<D*>(b2s[1])->int_in_d 3\nreinterpret_cast<D*>(b2s[1]) 0x7fffffffc940\nreinterpret_cast<D*>(b2s[1])->int_in_d 32767\n B1:\n +0: pointer to virtual method table of B1\n +4: value of int_in_b1\n B2 B2:\n +0: pointer to virtual method table of B2\n +4: value of int_in_b2\n D D:\n +0: pointer to virtual method table of D (for B1)\n +4: value of int_in_b1\n +8: pointer to virtual method table of D (for B2)\n +12: value of int_in_b2\n +16: value of int_in_d\n D B1 B2 int_in_b1 int_in_b2 D B2 D B2 b2s[1] = &d;\n d &d 0x7fffffffc930\nb2s[1] 0x7fffffffc940\n static_cast D B2 B1 static_cast<D*>(b2s[0]) 0x7fffffffc910 B2 D b2s[0] D 49 dp = static_cast<D*>(b2s[0]);\n 0x0000000000000fc8 <+414>: 48 8b 45 d0 mov -0x30(%rbp),%rax\n 0x0000000000000fcc <+418>: 48 85 c0 test %rax,%rax\n 0x0000000000000fcf <+421>: 74 0a je 0xfdb <main()+433>\n 0x0000000000000fd1 <+423>: 48 8b 45 d0 mov -0x30(%rbp),%rax\n 0x0000000000000fd5 <+427>: 48 83 e8 10 sub $0x10,%rax\n 0x0000000000000fd9 <+431>: eb 05 jmp 0xfe0 <main()+438>\n 0x0000000000000fdb <+433>: b8 00 00 00 00 mov $0x0,%eax\n 0x0000000000000fe0 <+438>: 48 89 45 98 mov %rax,-0x68(%rbp)\n D dynamic_cast<D*>(b2s[0]) 0 nullptr 59 dp = dynamic_cast<D*>(b2s[0]);\n 0x00000000000010ec <+706>: 48 8b 45 d0 mov -0x30(%rbp),%rax\n 0x00000000000010f0 <+710>: 48 85 c0 test %rax,%rax\n 0x00000000000010f3 <+713>: 74 1d je 0x1112 <main()+744>\n 0x00000000000010f5 <+715>: b9 10 00 00 00 mov $0x10,%ecx\n 0x00000000000010fa <+720>: 48 8d 15 f7 0b 20 00 lea 0x200bf7(%rip),%rdx # 0x201cf8 <_ZTI1D>\n 0x0000000000001101 <+727>: 48 8d 35 28 0c 20 00 lea 0x200c28(%rip),%rsi # 0x201d30 <_ZTI2B2>\n 0x0000000000001108 <+734>: 48 89 c7 mov %rax,%rdi\n 0x000000000000110b <+737>: e8 c0 fb ff ff callq 0xcd0 <__dynamic_cast@plt>\n 0x0000000000001110 <+742>: eb 05 jmp 0x1117 <main()+749>\n 0x0000000000001112 <+744>: b8 00 00 00 00 mov $0x0,%eax\n 0x0000000000001117 <+749>: 48 89 45 98 mov %rax,-0x68(%rbp)\n __dynamic_cast __dynamic_cast B2 D b2s[0] dynamic_cast static_cast reinterpret_cast<D*>(b2s[1]) 0x7fffffffc940 D b2s[1] -O0 70 dp = reinterpret_cast<D*>(b2s[1]);\n 0x00000000000011fa <+976>: 48 8b 45 d8 mov -0x28(%rbp),%rax\n 0x00000000000011fe <+980>: 48 89 45 98 mov %rax,-0x68(%rbp)\n" }, { "answer_id": 71897639, "author": "Adrian", "author_id": 11723575, "author_profile": "https://Stackoverflow.com/users/11723575", "pm_score": 0, "selected": false, "text": "reinterpret_cast void* static_cast void* int i = 13;\n void *p = &i;\n auto *pi = static_cast<int*>(p);\n reinterpret_cast #include<iostream>\n\nusing any_fcn_ptr_t = void(*)();\n\n\nvoid print(int i)\n{\n std::cout << i <<std::endl;\n}\n\nint main()\n{ \n //Create type-erased pointer to function:\n auto any_ptr = reinterpret_cast<any_fcn_ptr_t>(&print);\n \n //Retrieve the original pointer:\n auto ptr = reinterpret_cast< void(*)(int) >(any_ptr);\n \n ptr(7);\n}\n reinterpret_cast void* static_cast ptr print reinterpret_cast" }, { "answer_id": 73518416, "author": "Özgür Murat Sağdıçoğlu", "author_id": 5106317, "author_profile": "https://Stackoverflow.com/users/5106317", "pm_score": 2, "selected": false, "text": "reinterpret_cast static_cast #include <iostream>\nusing namespace std;\n\nclass A\n{\n int a;\n};\n\nclass B\n{\n int b;\n};\n\nclass C : public A, public B\n{\n int c;\n};\n\nint main()\n{\n {\n B b;\n cout << &b << endl;\n cout << static_cast<C *>(&b) << endl; // 1\n cout << reinterpret_cast<C *>(&b) << endl; // 2\n }\n cout << endl;\n {\n C c;\n cout << &c << endl;\n cout << static_cast<B *>(&c) << endl; // 3\n cout << reinterpret_cast<B *>(&c) << endl; // 4\n }\n cout << endl;\n {\n A a;\n cout << &a << endl;\n cout << static_cast<C *>(&a) << endl;\n cout << reinterpret_cast<C *>(&a) << endl;\n }\n cout << endl;\n {\n C c;\n cout << &c << endl;\n cout << static_cast<A *>(&c) << endl;\n cout << reinterpret_cast<A *>(&c) << endl;\n }\n return 0;\n}\n 0x7ffcede34f0c\n0x7ffcede34f08 // 1\n0x7ffcede34f0c // 2\n\n0x7ffcede34f0c\n0x7ffcede34f10 // 3\n0x7ffcede34f0c // 4\n\n0x7ffcede34f0c\n0x7ffcede34f0c\n0x7ffcede34f0c\n\n0x7ffcede34f0c\n0x7ffcede34f0c\n0x7ffcede34f0c\n 1 2 3 4 static_cast reinterpret_cast C B B C static_cast B C reinterpret_cast B A C" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/332030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33686/" ]
332,048
<p>I've been trying to add a swf over a swf on a html page, it's working fine in Firefox, but in IE, the one that's added first is always on top of the other one. I used z-index but it's not working, does anyone know how to solve this? Thanks.</p> <p>I already added wmode:transparent, it is working in firefox but not in IE 6.</p>
[ { "answer_id": 332054, "author": "andreas buykx", "author_id": 19863, "author_profile": "https://Stackoverflow.com/users/19863", "pm_score": 4, "selected": false, "text": "reinterpret_cast dynamic_cast static_cast dynamic_cast" }, { "answer_id": 332070, "author": "Fred Larson", "author_id": 10077, "author_profile": "https://Stackoverflow.com/users/10077", "pm_score": 9, "selected": false, "text": "dynamic_cast static_cast reinterpret_cast const_cast const/volatile" }, { "answer_id": 332086, "author": "coppro", "author_id": 16855, "author_profile": "https://Stackoverflow.com/users/16855", "pm_score": 13, "selected": true, "text": "static_cast int float void* static_cast T(something) (T)something T(something, something_else) static_cast virtual static_cast const_cast const reinterpret_cast const const const const const const const_cast volatile dynamic_cast dynamic_cast nullptr std::bad_cast dynamic_cast virtual protected private reinterpret_cast int reinterpret_cast reinterpret_cast (type)object type(object) const_cast static_cast static_cast const_cast reinterpret_cast reinterpret_cast const_cast reinterpret_cast static_cast reinterpret_cast static_cast" }, { "answer_id": 21249454, "author": "Sumit Arora", "author_id": 671170, "author_profile": "https://Stackoverflow.com/users/671170", "pm_score": 8, "selected": false, "text": "OnEventData(void* pData)\n\n{\n ......\n\n // pData is a void* pData, \n\n // EventData is a structure e.g. \n // typedef struct _EventData {\n // std::string id;\n // std:: string remote_id;\n // } EventData;\n\n // On Some Situation a void pointer *pData\n // has been static_casted as \n // EventData* pointer \n\n EventData *evtdata = static_cast<EventData*>(pData);\n .....\n}\n void DebugLog::OnMessage(Message *msg)\n{\n static DebugMsgData *debug;\n static XYZMsgData *xyz;\n\n if(debug = dynamic_cast<DebugMsgData*>(msg->pdata)){\n // debug message\n }\n else if(xyz = dynamic_cast<XYZMsgData*>(msg->pdata)){\n // xyz message\n }\n else/* if( ... )*/{\n // ...\n }\n}\n // *Passwd declared as a const\n\nconst unsigned char *Passwd\n\n\n// on some situation it require to remove its constness\n\nconst_cast<unsigned char*>(Passwd)\n typedef unsigned short uint16;\n\n// Read Bytes returns that 2 bytes got read. \n\nbool ByteBuffer::ReadUInt16(uint16& val) {\n return ReadBytes(reinterpret_cast<char*>(&val), 2);\n}\n" }, { "answer_id": 30558433, "author": "Serge Rogatch", "author_id": 1915854, "author_profile": "https://Stackoverflow.com/users/1915854", "pm_score": 4, "selected": false, "text": "static_cast reinterpret_cast CoCreateInstance() void** void** static_cast reinterpret_cast<void**>(&yourPointer) #include <windows.h>\n#include <netfw.h>\n.....\nINetFwPolicy2* pNetFwPolicy2 = nullptr;\nHRESULT hr = CoCreateInstance(__uuidof(NetFwPolicy2), nullptr,\n CLSCTX_INPROC_SERVER, __uuidof(INetFwPolicy2),\n //static_cast<void**>(&pNetFwPolicy2) would give a compile error\n reinterpret_cast<void**>(&pNetFwPolicy2) );\n static_cast reinterpret_cast #include <windows.h>\n#include <netfw.h>\n.....\nINetFwPolicy2* pNetFwPolicy2 = nullptr;\nvoid* tmp = nullptr;\nHRESULT hr = CoCreateInstance(__uuidof(NetFwPolicy2), nullptr,\n CLSCTX_INPROC_SERVER, __uuidof(INetFwPolicy2),\n &tmp );\npNetFwPolicy2 = static_cast<INetFwPolicy2*>(tmp);\n" }, { "answer_id": 41082284, "author": "Shital Shah", "author_id": 207661, "author_profile": "https://Stackoverflow.com/users/207661", "pm_score": 7, "selected": false, "text": "float int static_cast A B static_cast B A A A::operator B() B A A* B* A& B& (Base*) (Derived*) A* B* A& B& set<T> T& SomeClass::foo() const T& SomeClass::foo() const float int float" }, { "answer_id": 51965683, "author": "Timmy_A", "author_id": 3599970, "author_profile": "https://Stackoverflow.com/users/3599970", "pm_score": 4, "selected": false, "text": "(Type) var Type(var) int a=rand(); // Random number.\n\nint* pa1=reinterpret_cast<int*>(a); // OK. Here developer clearly expressed he wanted to do this potentially dangerous operation.\n\nint* pa2=static_cast<int*>(a); // Compiler error.\nint* pa3=dynamic_cast<int*>(a); // Compiler error.\n\nint* pa4=(int*) a; // OK. C-style cast can do such cast. The question is if it was intentional or developer just did some typo.\n\n*pa4=5; // Program crashes.\n" }, { "answer_id": 53878614, "author": "pkthapa", "author_id": 1163286, "author_profile": "https://Stackoverflow.com/users/1163286", "pm_score": 3, "selected": false, "text": "struct Foo{};\nstruct Bar{};\n\nint main(int argc, char** argv)\n{\n Foo* f = new Foo;\n\n Bar* b1 = f; // (1)\n Bar* b2 = static_cast<Bar*>(f); // (2)\n Bar* b3 = dynamic_cast<Bar*>(f); // (3)\n Bar* b4 = reinterpret_cast<Bar*>(f); // (4)\n Bar* b5 = const_cast<Bar*>(f); // (5)\n\n return 0;\n}\n" }, { "answer_id": 60414256, "author": "Ciro Santilli OurBigBook.com", "author_id": 895245, "author_profile": "https://Stackoverflow.com/users/895245", "pm_score": 4, "selected": false, "text": "static_cast dynamic_cast reinterpret_cast static_cast dyanamic_cast static_cast nullptr nullptr static_cast dynamic_cast -NDEBUG static_cast reinterpret_cast #include <iostream>\n\nstruct B1 {\n B1(int int_in_b1) : int_in_b1(int_in_b1) {}\n virtual ~B1() {}\n void f0() {}\n virtual int f1() { return 1; }\n int int_in_b1;\n};\n\nstruct B2 {\n B2(int int_in_b2) : int_in_b2(int_in_b2) {}\n virtual ~B2() {}\n virtual int f2() { return 2; }\n int int_in_b2;\n};\n\nstruct D : public B1, public B2 {\n D(int int_in_b1, int int_in_b2, int int_in_d)\n : B1(int_in_b1), B2(int_in_b2), int_in_d(int_in_d) {}\n void d() {}\n int f2() { return 3; }\n int int_in_d;\n};\n\nint main() {\n B2 *b2s[2];\n B2 b2{11};\n D *dp;\n D d{1, 2, 3};\n\n // The memory layout must support the virtual method call use case.\n b2s[0] = &b2;\n // An upcast is an implicit static_cast<>().\n b2s[1] = &d;\n std::cout << \"&d \" << &d << std::endl;\n std::cout << \"b2s[0] \" << b2s[0] << std::endl;\n std::cout << \"b2s[1] \" << b2s[1] << std::endl;\n std::cout << \"b2s[0]->f2() \" << b2s[0]->f2() << std::endl;\n std::cout << \"b2s[1]->f2() \" << b2s[1]->f2() << std::endl;\n\n // Now for some downcasts.\n\n // Cannot be done implicitly\n // error: invalid conversion from ‘B2*’ to ‘D*’ [-fpermissive]\n // dp = (b2s[0]);\n\n // Undefined behaviour to an unrelated memory address because this is a B2, not D.\n dp = static_cast<D*>(b2s[0]);\n std::cout << \"static_cast<D*>(b2s[0]) \" << dp << std::endl;\n std::cout << \"static_cast<D*>(b2s[0])->int_in_d \" << dp->int_in_d << std::endl;\n\n // OK\n dp = static_cast<D*>(b2s[1]);\n std::cout << \"static_cast<D*>(b2s[1]) \" << dp << std::endl;\n std::cout << \"static_cast<D*>(b2s[1])->int_in_d \" << dp->int_in_d << std::endl;\n\n // Segfault because dp is nullptr.\n dp = dynamic_cast<D*>(b2s[0]);\n std::cout << \"dynamic_cast<D*>(b2s[0]) \" << dp << std::endl;\n //std::cout << \"dynamic_cast<D*>(b2s[0])->int_in_d \" << dp->int_in_d << std::endl;\n\n // OK\n dp = dynamic_cast<D*>(b2s[1]);\n std::cout << \"dynamic_cast<D*>(b2s[1]) \" << dp << std::endl;\n std::cout << \"dynamic_cast<D*>(b2s[1])->int_in_d \" << dp->int_in_d << std::endl;\n\n // Undefined behaviour to an unrelated memory address because this\n // did not calculate the offset to get from B2* to D*.\n dp = reinterpret_cast<D*>(b2s[1]);\n std::cout << \"reinterpret_cast<D*>(b2s[1]) \" << dp << std::endl;\n std::cout << \"reinterpret_cast<D*>(b2s[1])->int_in_d \" << dp->int_in_d << std::endl;\n}\n\n g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o main.out main.cpp\nsetarch `uname -m` -R ./main.out\ngdb -batch -ex \"disassemble/rs main\" main.out\n setarch &d 0x7fffffffc930\nb2s[0] 0x7fffffffc920\nb2s[1] 0x7fffffffc940\nb2s[0]->f2() 2\nb2s[1]->f2() 3\nstatic_cast<D*>(b2s[0]) 0x7fffffffc910\nstatic_cast<D*>(b2s[0])->int_in_d 1\nstatic_cast<D*>(b2s[1]) 0x7fffffffc930\nstatic_cast<D*>(b2s[1])->int_in_d 3\ndynamic_cast<D*>(b2s[0]) 0\ndynamic_cast<D*>(b2s[1]) 0x7fffffffc930\ndynamic_cast<D*>(b2s[1])->int_in_d 3\nreinterpret_cast<D*>(b2s[1]) 0x7fffffffc940\nreinterpret_cast<D*>(b2s[1])->int_in_d 32767\n B1:\n +0: pointer to virtual method table of B1\n +4: value of int_in_b1\n B2 B2:\n +0: pointer to virtual method table of B2\n +4: value of int_in_b2\n D D:\n +0: pointer to virtual method table of D (for B1)\n +4: value of int_in_b1\n +8: pointer to virtual method table of D (for B2)\n +12: value of int_in_b2\n +16: value of int_in_d\n D B1 B2 int_in_b1 int_in_b2 D B2 D B2 b2s[1] = &d;\n d &d 0x7fffffffc930\nb2s[1] 0x7fffffffc940\n static_cast D B2 B1 static_cast<D*>(b2s[0]) 0x7fffffffc910 B2 D b2s[0] D 49 dp = static_cast<D*>(b2s[0]);\n 0x0000000000000fc8 <+414>: 48 8b 45 d0 mov -0x30(%rbp),%rax\n 0x0000000000000fcc <+418>: 48 85 c0 test %rax,%rax\n 0x0000000000000fcf <+421>: 74 0a je 0xfdb <main()+433>\n 0x0000000000000fd1 <+423>: 48 8b 45 d0 mov -0x30(%rbp),%rax\n 0x0000000000000fd5 <+427>: 48 83 e8 10 sub $0x10,%rax\n 0x0000000000000fd9 <+431>: eb 05 jmp 0xfe0 <main()+438>\n 0x0000000000000fdb <+433>: b8 00 00 00 00 mov $0x0,%eax\n 0x0000000000000fe0 <+438>: 48 89 45 98 mov %rax,-0x68(%rbp)\n D dynamic_cast<D*>(b2s[0]) 0 nullptr 59 dp = dynamic_cast<D*>(b2s[0]);\n 0x00000000000010ec <+706>: 48 8b 45 d0 mov -0x30(%rbp),%rax\n 0x00000000000010f0 <+710>: 48 85 c0 test %rax,%rax\n 0x00000000000010f3 <+713>: 74 1d je 0x1112 <main()+744>\n 0x00000000000010f5 <+715>: b9 10 00 00 00 mov $0x10,%ecx\n 0x00000000000010fa <+720>: 48 8d 15 f7 0b 20 00 lea 0x200bf7(%rip),%rdx # 0x201cf8 <_ZTI1D>\n 0x0000000000001101 <+727>: 48 8d 35 28 0c 20 00 lea 0x200c28(%rip),%rsi # 0x201d30 <_ZTI2B2>\n 0x0000000000001108 <+734>: 48 89 c7 mov %rax,%rdi\n 0x000000000000110b <+737>: e8 c0 fb ff ff callq 0xcd0 <__dynamic_cast@plt>\n 0x0000000000001110 <+742>: eb 05 jmp 0x1117 <main()+749>\n 0x0000000000001112 <+744>: b8 00 00 00 00 mov $0x0,%eax\n 0x0000000000001117 <+749>: 48 89 45 98 mov %rax,-0x68(%rbp)\n __dynamic_cast __dynamic_cast B2 D b2s[0] dynamic_cast static_cast reinterpret_cast<D*>(b2s[1]) 0x7fffffffc940 D b2s[1] -O0 70 dp = reinterpret_cast<D*>(b2s[1]);\n 0x00000000000011fa <+976>: 48 8b 45 d8 mov -0x28(%rbp),%rax\n 0x00000000000011fe <+980>: 48 89 45 98 mov %rax,-0x68(%rbp)\n" }, { "answer_id": 71897639, "author": "Adrian", "author_id": 11723575, "author_profile": "https://Stackoverflow.com/users/11723575", "pm_score": 0, "selected": false, "text": "reinterpret_cast void* static_cast void* int i = 13;\n void *p = &i;\n auto *pi = static_cast<int*>(p);\n reinterpret_cast #include<iostream>\n\nusing any_fcn_ptr_t = void(*)();\n\n\nvoid print(int i)\n{\n std::cout << i <<std::endl;\n}\n\nint main()\n{ \n //Create type-erased pointer to function:\n auto any_ptr = reinterpret_cast<any_fcn_ptr_t>(&print);\n \n //Retrieve the original pointer:\n auto ptr = reinterpret_cast< void(*)(int) >(any_ptr);\n \n ptr(7);\n}\n reinterpret_cast void* static_cast ptr print reinterpret_cast" }, { "answer_id": 73518416, "author": "Özgür Murat Sağdıçoğlu", "author_id": 5106317, "author_profile": "https://Stackoverflow.com/users/5106317", "pm_score": 2, "selected": false, "text": "reinterpret_cast static_cast #include <iostream>\nusing namespace std;\n\nclass A\n{\n int a;\n};\n\nclass B\n{\n int b;\n};\n\nclass C : public A, public B\n{\n int c;\n};\n\nint main()\n{\n {\n B b;\n cout << &b << endl;\n cout << static_cast<C *>(&b) << endl; // 1\n cout << reinterpret_cast<C *>(&b) << endl; // 2\n }\n cout << endl;\n {\n C c;\n cout << &c << endl;\n cout << static_cast<B *>(&c) << endl; // 3\n cout << reinterpret_cast<B *>(&c) << endl; // 4\n }\n cout << endl;\n {\n A a;\n cout << &a << endl;\n cout << static_cast<C *>(&a) << endl;\n cout << reinterpret_cast<C *>(&a) << endl;\n }\n cout << endl;\n {\n C c;\n cout << &c << endl;\n cout << static_cast<A *>(&c) << endl;\n cout << reinterpret_cast<A *>(&c) << endl;\n }\n return 0;\n}\n 0x7ffcede34f0c\n0x7ffcede34f08 // 1\n0x7ffcede34f0c // 2\n\n0x7ffcede34f0c\n0x7ffcede34f10 // 3\n0x7ffcede34f0c // 4\n\n0x7ffcede34f0c\n0x7ffcede34f0c\n0x7ffcede34f0c\n\n0x7ffcede34f0c\n0x7ffcede34f0c\n0x7ffcede34f0c\n 1 2 3 4 static_cast reinterpret_cast C B B C static_cast B C reinterpret_cast B A C" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/332048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34797/" ]
332,060
<p>I have been working my way through Scott Guthrie's excellent post on <a href="http://weblogs.asp.net/scottgu/archive/2008/10/16/asp-net-mvc-beta-released.aspx" rel="noreferrer">ASP.NET MVC Beta 1</a>. In it he shows the improvements made to the UpdateModel method and how they improve unit testing. I have recreated a similar project however anytime I run a UnitTest that contains a call to UpdateModel I receive an ArgumentNullException naming the controllerContext parameter.</p> <p>Here's the relevant bits, starting with my model:</p> <pre><code>public class Country { public Int32 ID { get; set; } public String Name { get; set; } public String Iso3166 { get; set; } } </code></pre> <p>The controller action:</p> <pre><code>[AcceptVerbs(HttpVerbs.Post)] public ActionResult Edit(Int32 id, FormCollection form) { using ( ModelBindingDataContext db = new ModelBindingDataContext() ) { Country country = db.Countries.Where(c =&gt; c.CountryID == id).SingleOrDefault(); try { UpdateModel(country, form); db.SubmitChanges(); return RedirectToAction("Index"); } catch { return View(country); } } } </code></pre> <p>And finally my unit test that's failing:</p> <pre><code>[TestMethod] public void Edit() { CountryController controller = new CountryController(); FormCollection form = new FormCollection(); form.Add("Name", "Canada"); form.Add("Iso3166", "CA"); var result = controller.Edit(2 /*Canada*/, form) as RedirectToRouteResult; Assert.IsNotNull(result, "Expected to be redirected on successful POST."); Assert.AreEqual("Show", result.RouteName, "Expected to redirect to the View action."); } </code></pre> <p><code>ArgumentNullException</code> is thrown by the call to <code>UpdateModel</code> with the message "Value cannot be null. Parameter name: controllerContext". I'm assuming that somewhere the <code>UpdateModel</code> requires the <code>System.Web.Mvc.ControllerContext</code> which isn't present during execution of the test.</p> <p>I'm also assuming that I'm doing something wrong somewhere and just need to pointed in the right direction.</p> <p>Help Please!</p>
[ { "answer_id": 332089, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 4, "selected": true, "text": "var routeData = new RouteData();\nvar httpContext = MockRepository.GenerateStub<HttpContextBase>();\nFormCollection formParameters = new FormCollection();\n\nEventController controller = new EventController();\nControllerContext controllerContext = \n MockRepository.GenerateStub<ControllerContext>( httpContext,\n routeData,\n controller );\ncontroller.ControllerContext = controllerContext;\n\nViewResult result = controller.Create( formParameters ) as ViewResult;\n\nAssert.AreEqual( \"Event\", result.Values[\"controller\"] );\nAssert.AreEqual( \"Show\", result.Values[\"action\"] );\nAssert.AreEqual( 0, result.Values[\"id\"] );\n protected internal bool TryUpdateModel<TModel>( ... ) where TModel : class\n{\n\n ....\n\n ModelBindingContext bindingContext =\n new ModelBindingContext( ControllerContext,\n valueProvider,\n typeof(TModel),\n prefix,\n () => model,\n ModelState,\n propertyFilter );\n\n ...\n}\n" }, { "answer_id": 2552071, "author": "Sergey Makridenkov", "author_id": 141458, "author_profile": "https://Stackoverflow.com/users/141458", "pm_score": 0, "selected": false, "text": "public class CountryEdit {\n public String Name { get; set; }\n public String Iso3166 { get; set; }\n}\n public ActionResult Edit(Int32 id, CountryEdit input)\n{\n var Country = input.ToDb();\n // Continue your code\n}\n" }, { "answer_id": 4349722, "author": "Brian", "author_id": 875507, "author_profile": "https://Stackoverflow.com/users/875507", "pm_score": 2, "selected": false, "text": "CountryController controller = new CountryController();\ncontroller.ControllerContext = new ControllerContext();\n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/332060", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32588/" ]
332,067
<p>My application's context root is /foobar and I am running an exploded deployment with maven-jetty-plugin.</p> <p>I need to dynamically remap requets for /images/* to /foobar/images/*, and I cannot remap my application's context root to /.</p> <p>For weblogic I have a halfwit solution where I deploy an additional war containing a proxy to context root /images. </p> <p>The problem is that I cannot get this to work with maven-jetty-plugin, because I dont see how it can deploy two apps.</p> <p>Anyone know how to do this ?</p>
[ { "answer_id": 332089, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 4, "selected": true, "text": "var routeData = new RouteData();\nvar httpContext = MockRepository.GenerateStub<HttpContextBase>();\nFormCollection formParameters = new FormCollection();\n\nEventController controller = new EventController();\nControllerContext controllerContext = \n MockRepository.GenerateStub<ControllerContext>( httpContext,\n routeData,\n controller );\ncontroller.ControllerContext = controllerContext;\n\nViewResult result = controller.Create( formParameters ) as ViewResult;\n\nAssert.AreEqual( \"Event\", result.Values[\"controller\"] );\nAssert.AreEqual( \"Show\", result.Values[\"action\"] );\nAssert.AreEqual( 0, result.Values[\"id\"] );\n protected internal bool TryUpdateModel<TModel>( ... ) where TModel : class\n{\n\n ....\n\n ModelBindingContext bindingContext =\n new ModelBindingContext( ControllerContext,\n valueProvider,\n typeof(TModel),\n prefix,\n () => model,\n ModelState,\n propertyFilter );\n\n ...\n}\n" }, { "answer_id": 2552071, "author": "Sergey Makridenkov", "author_id": 141458, "author_profile": "https://Stackoverflow.com/users/141458", "pm_score": 0, "selected": false, "text": "public class CountryEdit {\n public String Name { get; set; }\n public String Iso3166 { get; set; }\n}\n public ActionResult Edit(Int32 id, CountryEdit input)\n{\n var Country = input.ToDb();\n // Continue your code\n}\n" }, { "answer_id": 4349722, "author": "Brian", "author_id": 875507, "author_profile": "https://Stackoverflow.com/users/875507", "pm_score": 2, "selected": false, "text": "CountryController controller = new CountryController();\ncontroller.ControllerContext = new ControllerContext();\n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/332067", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23691/" ]
332,079
<p>I'm working with some example java code for making md5 hashes. One part converts the results from bytes to a string of hex digits:</p> <pre><code>byte messageDigest[] = algorithm.digest(); StringBuffer hexString = new StringBuffer(); for (int i=0;i&lt;messageDigest.length;i++) { hexString.append(Integer.toHexString(0xFF &amp; messageDigest[i])); } </code></pre> <p>However, it doesn't quite work since toHexString apparently drops off leading zeros. So, what's the simplest way to go from byte array to hex string that maintains the leading zeros?</p>
[ { "answer_id": 332093, "author": "kgiannakakis", "author_id": 24054, "author_profile": "https://Stackoverflow.com/users/24054", "pm_score": 2, "selected": false, "text": "public static String getMD5(String filename)\n throws NoSuchAlgorithmException, IOException {\n MessageDigest messageDigest = \n java.security.MessageDigest.getInstance(\"MD5\");\n\n InputStream in = new FileInputStream(filename);\n\n byte [] buffer = new byte[8192];\n int len = in.read(buffer, 0, buffer.length);\n\n while (len > 0) {\n messageDigest.update(buffer, 0, len);\n len = in.read(buffer, 0, buffer.length);\n }\n in.close();\n\n return new BigInteger(1, messageDigest.digest()).toString(16);\n}\n" }, { "answer_id": 332101, "author": "Michael Myers", "author_id": 13531, "author_profile": "https://Stackoverflow.com/users/13531", "pm_score": 8, "selected": true, "text": "Integer.toHexString() public static String toHexString(byte[] bytes) {\n StringBuilder hexString = new StringBuilder();\n\n for (int i = 0; i < bytes.length; i++) {\n String hex = Integer.toHexString(0xFF & bytes[i]);\n if (hex.length() == 1) {\n hexString.append('0');\n }\n hexString.append(hex);\n }\n\n return hexString.toString();\n}\n" }, { "answer_id": 332105, "author": "Ed Marty", "author_id": 36007, "author_profile": "https://Stackoverflow.com/users/36007", "pm_score": 3, "selected": false, "text": "String result = String.format(\"%0\" + messageDigest.length + \"s\", hexString.toString())\n String.format" }, { "answer_id": 332127, "author": "Fernando Miguélez", "author_id": 34880, "author_profile": "https://Stackoverflow.com/users/34880", "pm_score": 1, "selected": false, "text": "byte messageDigest[] = algorithm.digest();\nStringBuffer hexString = new StringBuffer();\nfor (int i = 0; i < messageDigest.length; i++) {\n String hexByte = Integer.toHexString(0xFF & messageDigest[i]);\n int numDigits = 2 - hexByte.length();\n while (numDigits-- > 0) {\n hexString.append('0');\n }\n hexString.append(hexByte);\n}\n" }, { "answer_id": 332433, "author": "Brandon DuRette", "author_id": 17834, "author_profile": "https://Stackoverflow.com/users/17834", "pm_score": 7, "selected": false, "text": "import org.apache.commons.codec.binary.Hex;\n\nString hex = Hex.encodeHexString(bytes);\n" }, { "answer_id": 334295, "author": "agentbillo", "author_id": 32116, "author_profile": "https://Stackoverflow.com/users/32116", "pm_score": 3, "selected": false, "text": "public static String toHexString(byte bytes[]) {\n if (bytes == null) {\n return null;\n }\n\n StringBuffer sb = new StringBuffer();\n for (int iter = 0; iter < bytes.length; iter++) {\n byte high = (byte) ( (bytes[iter] & 0xf0) >> 4);\n byte low = (byte) (bytes[iter] & 0x0f);\n sb.append(nibble2char(high));\n sb.append(nibble2char(low));\n }\n\n return sb.toString();\n}\n\nprivate static char nibble2char(byte b) {\n byte nibble = (byte) (b & 0x0f);\n if (nibble < 10) {\n return (char) ('0' + nibble);\n }\n return (char) ('a' + nibble - 10);\n}\n" }, { "answer_id": 943963, "author": "Ayman", "author_id": 77222, "author_profile": "https://Stackoverflow.com/users/77222", "pm_score": 7, "selected": false, "text": "public static String toHex(byte[] bytes) {\n BigInteger bi = new BigInteger(1, bytes);\n return String.format(\"%0\" + (bytes.length << 1) + \"X\", bi);\n}\n \"x\"" }, { "answer_id": 947243, "author": "Peter Lawrey", "author_id": 57695, "author_profile": "https://Stackoverflow.com/users/57695", "pm_score": 3, "selected": false, "text": "public static String toHexString(byte[]bytes) {\n StringBuilder sb = new StringBuilder(bytes.length*2);\n for(byte b: bytes)\n sb.append(Integer.toHexString(b+0x800).substring(1));\n return sb.toString();\n}\n" }, { "answer_id": 997269, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "hexString.append(hexArray[0xFF & messageDigest[i]]);\n String[] hexArray = {\n\"00\",\"01\",\"02\",\"03\",\"04\",\"05\",\"06\",\"07\",\"08\",\"09\",\"0A\",\"0B\",\"0C\",\"0D\",\"0E\",\"0F\",\n\"10\",\"11\",\"12\",\"13\",\"14\",\"15\",\"16\",\"17\",\"18\",\"19\",\"1A\",\"1B\",\"1C\",\"1D\",\"1E\",\"1F\",\n\"20\",\"21\",\"22\",\"23\",\"24\",\"25\",\"26\",\"27\",\"28\",\"29\",\"2A\",\"2B\",\"2C\",\"2D\",\"2E\",\"2F\",\n\"30\",\"31\",\"32\",\"33\",\"34\",\"35\",\"36\",\"37\",\"38\",\"39\",\"3A\",\"3B\",\"3C\",\"3D\",\"3E\",\"3F\",\n\"40\",\"41\",\"42\",\"43\",\"44\",\"45\",\"46\",\"47\",\"48\",\"49\",\"4A\",\"4B\",\"4C\",\"4D\",\"4E\",\"4F\",\n\"50\",\"51\",\"52\",\"53\",\"54\",\"55\",\"56\",\"57\",\"58\",\"59\",\"5A\",\"5B\",\"5C\",\"5D\",\"5E\",\"5F\",\n\"60\",\"61\",\"62\",\"63\",\"64\",\"65\",\"66\",\"67\",\"68\",\"69\",\"6A\",\"6B\",\"6C\",\"6D\",\"6E\",\"6F\",\n\"70\",\"71\",\"72\",\"73\",\"74\",\"75\",\"76\",\"77\",\"78\",\"79\",\"7A\",\"7B\",\"7C\",\"7D\",\"7E\",\"7F\",\n\"80\",\"81\",\"82\",\"83\",\"84\",\"85\",\"86\",\"87\",\"88\",\"89\",\"8A\",\"8B\",\"8C\",\"8D\",\"8E\",\"8F\",\n\"90\",\"91\",\"92\",\"93\",\"94\",\"95\",\"96\",\"97\",\"98\",\"99\",\"9A\",\"9B\",\"9C\",\"9D\",\"9E\",\"9F\",\n\"A0\",\"A1\",\"A2\",\"A3\",\"A4\",\"A5\",\"A6\",\"A7\",\"A8\",\"A9\",\"AA\",\"AB\",\"AC\",\"AD\",\"AE\",\"AF\",\n\"B0\",\"B1\",\"B2\",\"B3\",\"B4\",\"B5\",\"B6\",\"B7\",\"B8\",\"B9\",\"BA\",\"BB\",\"BC\",\"BD\",\"BE\",\"BF\",\n\"C0\",\"C1\",\"C2\",\"C3\",\"C4\",\"C5\",\"C6\",\"C7\",\"C8\",\"C9\",\"CA\",\"CB\",\"CC\",\"CD\",\"CE\",\"CF\",\n\"D0\",\"D1\",\"D2\",\"D3\",\"D4\",\"D5\",\"D6\",\"D7\",\"D8\",\"D9\",\"DA\",\"DB\",\"DC\",\"DD\",\"DE\",\"DF\",\n\"E0\",\"E1\",\"E2\",\"E3\",\"E4\",\"E5\",\"E6\",\"E7\",\"E8\",\"E9\",\"EA\",\"EB\",\"EC\",\"ED\",\"EE\",\"EF\",\n\"F0\",\"F1\",\"F2\",\"F3\",\"F4\",\"F5\",\"F6\",\"F7\",\"F8\",\"F9\",\"FA\",\"FB\",\"FC\",\"FD\",\"FE\",\"FF\"};\n" }, { "answer_id": 1047234, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "public static String hash(String text, String algorithm)\n throws NoSuchAlgorithmException {\n byte[] hash = MessageDigest.getInstance(algorithm).digest(text.getBytes());\n return new BigInteger(1, hash).toString(16);\n}\n public static String hash(String text, String algorithm)\n throws NoSuchAlgorithmException {\n byte[] hash = MessageDigest.getInstance(algorithm).digest(text.getBytes());\n BigInteger bi = new BigInteger(1, hash);\n String result = bi.toString(16);\n if (result.length() % 2 != 0) {\n return \"0\" + result;\n }\n return result;\n}\n" }, { "answer_id": 1059731, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "public static String toHexString(byte[] bytes) {\n char[] hexArray = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};\n char[] hexChars = new char[10000000];\n int c = 0;\n int v;\n for ( j = 0; j < bytes.length; j++ ) {\n v = bytes[j] & 0xFF;\n hexChars[c] = hexArray[v/16];\n c++;\n hexChars[c] = hexArray[v%16];\n c++;\n }\n return new String(hexChars, 0, c); }\n" }, { "answer_id": 2197650, "author": "Jemenake", "author_id": 265932, "author_profile": "https://Stackoverflow.com/users/265932", "pm_score": 5, "selected": false, "text": "public static String toHexString(byte[] bytes) {\n char[] hexArray = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};\n char[] hexChars = new char[bytes.length * 2];\n int v;\n for ( int j = 0; j < bytes.length; j++ ) {\n v = bytes[j] & 0xFF;\n hexChars[j*2] = hexArray[v/16];\n hexChars[j*2 + 1] = hexArray[v%16];\n }\n return new String(hexChars);\n}\n" }, { "answer_id": 2638404, "author": "Illarion Kovalchuk", "author_id": 255667, "author_profile": "https://Stackoverflow.com/users/255667", "pm_score": 4, "selected": false, "text": "static String toHex(byte[] digest) {\n StringBuilder sb = new StringBuilder();\n for (byte b : digest) {\n sb.append(String.format(\"%1$02X\", b));\n }\n\n return sb.toString();\n}\n" }, { "answer_id": 3236053, "author": "F.X", "author_id": 389618, "author_profile": "https://Stackoverflow.com/users/389618", "pm_score": 2, "selected": false, "text": "public static String MD5hash(String text) throws NoSuchAlgorithmException {\n byte[] hash = MessageDigest.getInstance(\"MD5\").digest(text.getBytes());\n return String.format(\"%032x\",new BigInteger(1, hash));\n}\n" }, { "answer_id": 3889053, "author": "max", "author_id": 470049, "author_profile": "https://Stackoverflow.com/users/470049", "pm_score": 2, "selected": false, "text": "static String toHex(byte[] digest) {\n String digits = \"0123456789abcdef\";\n StringBuilder sb = new StringBuilder(digest.length * 2);\n for (byte b : digest) {\n int bi = b & 0xff;\n sb.append(digits.charAt(bi >> 4));\n sb.append(digits.charAt(bi & 0xf));\n }\n return sb.toString();\n}\n" }, { "answer_id": 9032075, "author": "Divij", "author_id": 761662, "author_profile": "https://Stackoverflow.com/users/761662", "pm_score": 0, "selected": false, "text": "byte messageDigest[] = algorithm.digest();\nfor (int i = 0; i < messageDigest.length; i++) {\n hexString.append(Integer.toHexString(0xFF & messageDigest[i]));\n} \n byte messageDigest[] = algorithm.digest();\nfor (int i = 0; i < messageDigest.length; i++) {\n int temp=0xFF & messageDigest[i];\n String s=Integer.toHexString(temp);\n if(temp<=0x0F){\n s=\"0\"+s;\n }\n hexString.append(s);\n}\n" }, { "answer_id": 12143840, "author": "neel", "author_id": 1217987, "author_profile": "https://Stackoverflow.com/users/1217987", "pm_score": -1, "selected": false, "text": "HexBin.encode(messageDigest).toLowerCase();\n" }, { "answer_id": 12514417, "author": "arutaku", "author_id": 1565171, "author_profile": "https://Stackoverflow.com/users/1565171", "pm_score": 2, "selected": false, "text": "String hex = (new HexBinaryAdapter()).marshal(md5.digest(YOUR_STRING.getBytes()))\n" }, { "answer_id": 12522709, "author": "bearontheroof", "author_id": 365954, "author_profile": "https://Stackoverflow.com/users/365954", "pm_score": 2, "selected": false, "text": "byte[] digest = new byte[16]; \n\nFormatter fmt = new Formatter(); \nfor (byte b : digest) { \n fmt.format(\"%02X\", b); \n}\n\nfmt.toString()\n" }, { "answer_id": 14552724, "author": "Gareth", "author_id": 2016421, "author_profile": "https://Stackoverflow.com/users/2016421", "pm_score": 5, "selected": false, "text": "javax.xml.bind.DatatypeConverter.printHexBinary() byte[] DatatypeConverter javax.xml.bind DatatypeConverter byte bytes[] = {(byte)0, (byte)0, (byte)134, (byte)0, (byte)61};\nString hex = javax.xml.bind.DatatypeConverter.printHexBinary(bytes);\n 000086003D\n" }, { "answer_id": 14615037, "author": "Hatto", "author_id": 2025971, "author_profile": "https://Stackoverflow.com/users/2025971", "pm_score": 0, "selected": false, "text": "public String toString(byte b){\n final char[] Hex = new String(\"0123456789ABCDEF\").toCharArray();\n return \"0x\"+ Hex[(b & 0xF0) >> 4]+ Hex[(b & 0x0F)];\n}\n" }, { "answer_id": 17063662, "author": "Dhimant Jayswal", "author_id": 1196389, "author_profile": "https://Stackoverflow.com/users/1196389", "pm_score": 0, "selected": false, "text": "public static String toHexString(byte[] bytes) {\n char[] hexArray = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};\n char[] hexChars = new char[bytes.length * 2];\n int v;\n for ( int j = 0; j < bytes.length; j++ ) {\n v = bytes[j] & 0xFF;\n hexChars[j*2] = hexArray[v/16];\n hexChars[j*2 + 1] = hexArray[v%16];\n }\n return new String(hexChars);\n}\n" }, { "answer_id": 18519930, "author": "wbr", "author_id": 1706230, "author_profile": "https://Stackoverflow.com/users/1706230", "pm_score": 0, "selected": false, "text": " StringBuilder builder = new StringBuilder();\n for (byte b : bytes)\n {\n builder.append(Character.forDigit(b/16, 16));\n builder.append(Character.forDigit(b % 16, 16));\n }\n System.out.println(builder.toString());\n" }, { "answer_id": 23263297, "author": "Stan", "author_id": 1811719, "author_profile": "https://Stackoverflow.com/users/1811719", "pm_score": 0, "selected": false, "text": " // Create MD5 Hash\n MessageDigest digest = java.security.MessageDigest.getInstance(\"MD5\");\n digest.update(s.getBytes());\n byte[] md5sum = digest.digest();\n BigInteger bigInt = new BigInteger(1, md5sum);\n String stringMD5 = bigInt.toString(16);\n // Fill to 32 chars\n stringMD5 = String.format(\"%32s\", stringMD5).replace(' ', '0');\n return stringMD5;\n" }, { "answer_id": 28097912, "author": "kichik", "author_id": 492773, "author_profile": "https://Stackoverflow.com/users/492773", "pm_score": 3, "selected": false, "text": "BaseEncoding.base16().encode( bytes );\n byte[] bytes = new byte[] { 0xa, 0xb, 0xc, 0xd, 0xe, 0xf };\nBaseEncoding.base16().lowerCase().withSeparator( \":\", 2 ).encode( bytes );\n// \"0a:0b:0c:0d:0e:0f\"\n" }, { "answer_id": 35467167, "author": "halber", "author_id": 1902794, "author_profile": "https://Stackoverflow.com/users/1902794", "pm_score": 0, "selected": false, "text": "StringWriter sw = new StringWriter();\ncom.sun.corba.se.impl.orbutil.HexOutputStream hex = new com.sun.corba.se.impl.orbutil.HexOutputStream(sw);\nhex.write(byteArray);\nSystem.out.println(sw.toString());\n" }, { "answer_id": 43276993, "author": "Usagi Miyamoto", "author_id": 4899193, "author_profile": "https://Stackoverflow.com/users/4899193", "pm_score": 4, "selected": false, "text": "md5sum = String.format(\"%032x\", new BigInteger(1, md.digest()));\n 0" }, { "answer_id": 53902844, "author": "KumarAnkit", "author_id": 5511336, "author_profile": "https://Stackoverflow.com/users/5511336", "pm_score": 0, "selected": false, "text": "byte[] digest = algorithm.digest();\nStringBuilder byteContet = new StringBuilder();\nfor(byte b: digest){\n byteContent = String.format(\"%02x\",b);\n byteContent.append(byteContent);\n}\n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/332079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25680/" ]
332,102
<p>In Django 1.0, what is the best way to catch and show an error if user enters only whitespace (" ") in a form field?</p> <pre><code>class Item(models.Model): description = models.CharField(max_length=100) class ItemForm(ModelForm): class Meta: model = Item </code></pre> <p>if user enters only whitespace (" ") in description CharField, what change needs to done to class Item or class ItemForm so that form.is_valid() fails and shows an error?</p> <p>After form.is_valid(), I could write the code to check for only whitespaces in description field and raise a validation error but there has to be a better way. Can RegexField be used to specify description entered should not be just whitespaces. Any suggestions?</p>
[ { "answer_id": 332947, "author": "Carl Meyer", "author_id": 3207, "author_profile": "https://Stackoverflow.com/users/3207", "pm_score": 3, "selected": true, "text": "class ItemForm(forms.ModelForm):\n class Meta:\n model = Item\n\n def clean_description(self):\n if not self.cleaned_data['description'].strip():\n raise forms.ValidationError('Your error message here')\n" }, { "answer_id": 334040, "author": "X10", "author_id": 11452, "author_profile": "https://Stackoverflow.com/users/11452", "pm_score": 1, "selected": false, "text": "class ItemForm(ModelForm):\n description = forms.RegexField(regex=r'[^(\\s+)]')\n class Meta:\n model = Item\n description = forms.RegexField(regex=r'[^(\\s+)]', error_message=_(\"Your error message here.\"))\n" }, { "answer_id": 334045, "author": "hasen", "author_id": 35364, "author_profile": "https://Stackoverflow.com/users/35364", "pm_score": 1, "selected": false, "text": "str.strip()" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/332102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11452/" ]
332,109
<p>I have a website that employs a generic mod_rewrite rule to push all requests to the index.php page, with the exception of certain file extensions:</p> <pre><code>RewriteRule !\.(js|ico|gif|jpg|JPG|png|css|php|phtml|pdf|txt|xml)$ index.php </code></pre> <p>What I need to be able to do is also exclude a certain directory (including any files or sub-directories contained within) from this rule - what is the best solution?</p> <p>Here is my full .htaccess file, in case something else within it is intefering:</p> <pre><code>RewriteEngine ON RewriteCond %{HTTP_HOST} !^www\..* RewriteCond %{HTTP_HOST} !^$ RewriteCond %{HTTP_HOST} ^([^.]*)\.(co\.uk) RewriteRule ^.*$ http://www.%1.%2%{REQUEST_URI} [R=permanent,L] AddHandler application/x-httpd-php .phtml RewriteRule !\.(js|ico|gif|jpg|JPG|png|css|php|phtml|pdf|txt|xml)$ index.phtml php_value display_errors "On" </code></pre>
[ { "answer_id": 332185, "author": "stesch", "author_id": 41860, "author_profile": "https://Stackoverflow.com/users/41860", "pm_score": 0, "selected": false, "text": "RewriteCond %{REQUEST_FILENAME} !-f" }, { "answer_id": 332587, "author": "jTresidder", "author_id": 36365, "author_profile": "https://Stackoverflow.com/users/36365", "pm_score": 4, "selected": true, "text": "RewriteRule ^style/ - [L]\n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/332109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29538/" ]
332,111
<p>I need to store a double as a string. I know I can use <code>printf</code> if I wanted to display it, but I just want to store it in a string variable so that I can store it in a map later (as the <em>value</em>, not the <em>key</em>).</p>
[ { "answer_id": 332113, "author": "Darron", "author_id": 22704, "author_profile": "https://Stackoverflow.com/users/22704", "pm_score": 2, "selected": false, "text": "sprintf()" }, { "answer_id": 332124, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 8, "selected": false, "text": "// The C way:\nchar buffer[32];\nsnprintf(buffer, sizeof(buffer), \"%g\", myDoubleVar);\n\n// The C++03 way:\nstd::ostringstream sstream;\nsstream << myDoubleVar;\nstd::string varAsString = sstream.str();\n\n// The C++11 way:\nstd::string varAsString = std::to_string(myDoubleVar);\n\n// The boost way:\nstd::string varAsString = boost::lexical_cast<std::string>(myDoubleVar);\n" }, { "answer_id": 332126, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 5, "selected": false, "text": "sprintf template <typename T>\nstd::string to_string(T const& value) {\n stringstream sstr;\n sstr << value;\n return sstr.str();\n}\n string s = to_string(42.5);\n" }, { "answer_id": 332128, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 2, "selected": false, "text": "string temp = \"\";\nstringstream outStream;\ndouble ratio = (currentImage->width*1.0f)/currentImage->height;\noutStream << \" R: \" << ratio;\ntemp = outStream.str();\n\n/* rest of the code */\n" }, { "answer_id": 332130, "author": "coppro", "author_id": 16855, "author_profile": "https://Stackoverflow.com/users/16855", "pm_score": 4, "selected": false, "text": "sprintf stringstream #include <sstream>\n#include <string>\n\n// In some function:\ndouble d = 453.23;\nstd::ostringstream os;\nos << d;\nstd::string str = os.str();\n #include <boost/lexical_cast.hpp>\n#include <string>\n\n// In some function:\ndouble d = 453.23;\nstd::string str = boost::lexical_cast<string>(d);\n str \"453.23\" stringstream" }, { "answer_id": 332132, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 9, "selected": true, "text": "std::string str = boost::lexical_cast<std::string>(dbl);\n std::ostringstream strs;\nstrs << dbl;\nstd::string str = strs.str();\n #include <sstream>" }, { "answer_id": 8014533, "author": "kennytm", "author_id": 224671, "author_profile": "https://Stackoverflow.com/users/224671", "pm_score": 7, "selected": false, "text": "#include <string>\n\nauto str = std::to_string(42.5); \n to_string stod \"%f\" snprintf ostringstream" }, { "answer_id": 23000995, "author": "Alexis Sánchez Tello", "author_id": 3521560, "author_profile": "https://Stackoverflow.com/users/3521560", "pm_score": 0, "selected": false, "text": "std::string number_in_string;\n\ndouble number_in_double;\n\nstd::ostringstream output;\n\nnumber_in_string = (dynamic_cast< std::ostringstream*>(&(output << number_in_double <<\n\nstd::endl)))->str(); \n" }, { "answer_id": 30713709, "author": "DannyK", "author_id": 969968, "author_profile": "https://Stackoverflow.com/users/969968", "pm_score": 3, "selected": false, "text": "#include <strtk.hpp>\n\ndouble pi = M_PI;\nstd::string pi_as_string = strtk::type_to_string<double>( pi );\n" }, { "answer_id": 33844603, "author": "Ingo", "author_id": 2278668, "author_profile": "https://Stackoverflow.com/users/2278668", "pm_score": 2, "selected": false, "text": "/* gcvt example */\n#include <stdio.h>\n#include <stdlib.h>\n\nmain ()\n{\n char buffer [20];\n gcvt (1365.249,6,buffer);\n puts (buffer);\n gcvt (1365.249,3,buffer);\n puts (buffer);\n return 0;\n}\n\nOutput:\n1365.25\n1.37e+003 \n void double_to_char(double f,char * buffer){\n gcvt(f,10,buffer);\n}\n" }, { "answer_id": 35345398, "author": "Hossein", "author_id": 2736559, "author_profile": "https://Stackoverflow.com/users/2736559", "pm_score": 1, "selected": false, "text": "to_string() #include <iostream> \n#include <string> \n\nusing namespace std;\nint main ()\n{\n string pi = \"pi is \" + to_string(3.1415926);\n cout<< \"pi = \"<< pi << endl;\n\n return 0;\n}\n string to_string (int val);\nstring to_string (long val);\nstring to_string (long long val);\nstring to_string (unsigned val);\nstring to_string (unsigned long val);\nstring to_string (unsigned long long val);\nstring to_string (float val);\nstring to_string (double val);\nstring to_string (long double val);\n" }, { "answer_id": 40968111, "author": "Sam Mokari", "author_id": 3401653, "author_profile": "https://Stackoverflow.com/users/3401653", "pm_score": 0, "selected": false, "text": "template<class T = std::string, class U>\nT to(U a) {\n std::stringstream ss;\n T ret;\n ss << a;\n ss >> ret;\n return ret;\n};\n std::string str = to(2.5);\ndouble d = to<double>(\"2.5\");\n" }, { "answer_id": 43046632, "author": "Yochai Timmer", "author_id": 536086, "author_profile": "https://Stackoverflow.com/users/536086", "pm_score": 5, "selected": false, "text": "double d = 3.0;\nstd::string str = std::to_string(d);\n" }, { "answer_id": 67448948, "author": "Erik Bongers", "author_id": 1311434, "author_profile": "https://Stackoverflow.com/users/1311434", "pm_score": 2, "selected": false, "text": "#include <sstream>\n#include <math.h>\n#include <iostream>\n#include <iomanip>\n\nint main()\n{\n std::ostringstream sout;\n sout << M_PI << '\\n';\n sout << std::setprecision(99) << M_PI << '\\n';\n sout << std::setprecision(3) << M_PI << '\\n';\n sout << std::fixed; //now the setprecision() value will look at the decimal part only.\n sout << std::setprecision(3) << M_PI << '\\n';\n std::cout << sout.str();\n}\n 3.14159 \n3.141592653589793115997963468544185161590576171875 \n3.14 \n3.142 \n" }, { "answer_id": 73457683, "author": "Marek R", "author_id": 1387438, "author_profile": "https://Stackoverflow.com/users/1387438", "pm_score": 0, "selected": false, "text": "std::to_chars_result to_chars( char* first, char* last, float value,\n std::chars_format fmt, int precision );\nstd::to_chars_result to_chars( char* first, char* last, double value,\n std::chars_format fmt, int precision );\nstd::to_chars_result to_chars( char* first, char* last, long double value,\n std::chars_format fmt, int precision );\n template< class... Args >\nstd::string format( /*format_string<Args...>*/ fmt, Args&&... args );\n\ntemplate< class... Args >\nstd::wstring format( /*wformat_string<Args...>*/ fmt, Args&&... args );\n\ntemplate< class... Args >\nstd::string format( const std::locale& loc,\n /*format_string<Args...>*/ fmt, Args&&... args );\n\ntemplate< class... Args >\nstd::wstring format( const std::locale& loc,\n /*wformat_string<Args...>*/ fmt, Args&&... args );\n sprintf" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/332111", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1288/" ]
332,117
<p>I need to be able to embed and control the playback of an AVI file in a WinForms app, using C#. The video needs to be embedded in the form, not launched in a separate media player window.</p> <p>What's the best approach to do this? I found the System.Media namespace, which sounded promising, but it appears that is only useful for sound.</p> <p>Do I use DirectX to do this? MCI? Or some other approach?</p>
[ { "answer_id": 10728660, "author": "Andres A.", "author_id": 170945, "author_profile": "https://Stackoverflow.com/users/170945", "pm_score": 3, "selected": false, "text": "axWindowsMediaPlayer1.URL = \n @\"http://go.microsoft.com/fwlink/?LinkId=95772\";\n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/332117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1338/" ]
332,120
<p>I'm trying to build a video recorder without jailbreaking my iPhone (i've a Developer license). I began using PhotoLibrary private framework, but i can only reach 2ftp (too slow). Cycoder app have a fps of 15, i think it uses a different approach. I tried to create a bitmap from the previewView of the CameraController, but it always returns e black bitmap.</p> <p>I wonder if there's a way to directly access the video buffer, maybe with IOKit framework.</p> <p>Thanks Marco</p>
[ { "answer_id": 498936, "author": "Marco", "author_id": 42240, "author_profile": "https://Stackoverflow.com/users/42240", "pm_score": 1, "selected": false, "text": "image = [window _createCGImageRefRepresentationInFrame:rectToCapture];\n" }, { "answer_id": 602093, "author": "Marco", "author_id": 42240, "author_profile": "https://Stackoverflow.com/users/42240", "pm_score": 1, "selected": false, "text": "void (*setter)(id, SEL, BOOL); \nint i; \nsetter = (void (*)(id, SEL, BOOL))[target methodForSelector:@selector(setFilled:)]; \nfor ( i = 0; i < 1000, i++ ) \nsetter(targetList[i], @selector(setFilled:), YES); \"\n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/332120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42240/" ]
332,122
<p>I'm trying to embed my Subversion revision number in a C++ project and am having problems setting up GNU make to do so. My makefile currently looks something like this:</p> <pre><code>check-svnversion: ../shared/update-svnversion-h.pl ../shared/svnversion.h: check-svnversion shared/svnversion.o: ../shared/svnversion.h .PHONY: check-svnversion </code></pre> <p><code>svnversion.o</code> depends on <code>svnversion.cpp</code> (via a pattern rule) and <code>svnversion.h</code> (listed explicitly because dependency checking isn't picking it up for some reason). <code>svnversion.h</code> is created and maintained by the <code>update-svnversion-h.pl</code> script (which basically just runs <code>svnversion</code> and munges the output into a C++ file).</p> <p>Currently, I have to run <code>make</code> twice to get the file up to date. The first time, <code>make</code> runs <code>update-svnversion-h.pl</code> (since it's listed as a prerequisite) but does not check the timestamp of <code>svnversion.h</code> afterwards to see that it was changed by <code>update-svnversion-h.pl</code>, so it does not remake <code>svnversion.o</code>. The second time, it does check the timestamp, runs <code>update-svnversion-h.pl</code> anyway (which doesn't do anything this time, since <code>svnversion.h</code> is up to date), then recompiles <code>svnversion.cpp</code> to make <code>svnversion.o</code>.</p> <p>Is there a way to tell GNU make to evaluate a single prerequisite twice or to delay checking the timestamp on a prerequisite until after that prerequisite's commands are finished?</p> <p>Alternatively, is there a better way to embed a revision number in my source code? (For the sake of speed, I'm trying to avoid solutions that would require recompilation on every build.)</p>
[ { "answer_id": 332191, "author": "coppro", "author_id": 16855, "author_profile": "https://Stackoverflow.com/users/16855", "pm_score": 1, "selected": false, "text": "svn:keywords Rev $Rev$ $Rev: #$ #" }, { "answer_id": 332756, "author": "CesarB", "author_id": 28258, "author_profile": "https://Stackoverflow.com/users/28258", "pm_score": 2, "selected": false, "text": "remake-hdr.am %CONFIG_H%: %STAMP%\n## Recover from removal of CONFIG_HEADER\n @if test ! -f $@; then \\\n rm -f %STAMP%; \\\n $(MAKE) $(AM_MAKEFLAGS) %STAMP%; \\\n else :; fi\n\n\n%STAMP%: %CONFIG_H_DEPS% $(top_builddir)/config.status\n @rm -f %STAMP%\n cd $(top_builddir) && $(SHELL) ./config.status %CONFIG_H_PATH%\n config.status" }, { "answer_id": 335237, "author": "Josh Kelley", "author_id": 25507, "author_profile": "https://Stackoverflow.com/users/25507", "pm_score": 2, "selected": true, "text": "../shared/svnversion.h: check-svnversion\n\ncheck-svnversion:\n ../shared/update-svnversion-h.pl\n @#Force recreation of svnversion.o. Otherwise, make won't notice that\n @#svnversion.h has changed until the next time it's invoked.\n @if [ ../shared/svnversion.h -nt shared/svnversion.o ] ; then rm shared/svnversion.o ; fi\n\nshared/svnversion.o: ../shared/svnversion.h\n\n.PHONY: check-svnversion\n" }, { "answer_id": 1487460, "author": "Jamie", "author_id": 32836, "author_profile": "https://Stackoverflow.com/users/32836", "pm_score": 2, "selected": false, "text": "##\n## on every build, record the working copy revision string\n##\nsvn_version.c: $(C_SRC:.c=.o) Makefile\n @echo -n 'const char* build_date(void);\\n' > $@\n @echo -n 'const char* build_date(void)\\n{ static const char* build_date = __DATE__ ; ' >> $@\n @echo 'return build_date; }\\n' >> $@\n @echo -n 'const char* build_time(void);\\n' >> $@\n @echo -n 'const char* build_time(void)\\n{ static const char* build_time = __TIME__ ; ' >> $@\n @echo 'return build_time; }\\n' >> $@\n @echo -n 'const char* svnid_build(void);\\n' >> $@\n @echo -n 'const char* svnid_build(void)\\n{ static const char* SVN_Version = \"\\\\n<SVN_PID>' >> $@\n @svnversion -cn . >> $@\n @echo '</svn_pid>\\\\n\"; return SVN_Version; }\\n' >> $@\n @echo -n 'const char* svnid_build_str_only(void);\\n' >> $@\n @echo -n 'const char* svnid_build_str_only(void)\\n{ static const char* SVN_Version = \"' >> $@\n @svnversion -cn . >> $@\n @echo '\"; return SVN_Version; }\\n' >> $@\n @$(CC) $(CFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -c -o $(@:.c=.o) $@\n final-target: svn_version.c\n $(CC) $(C_SRC:.c=.o) $(<:.c=.o) -o $@\n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/332122", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25507/" ]
332,129
<p>What is the most appropriate media type (formally MIME type) to use when sending data structured with YAML over HTTP and why?</p> <p>There is no registered <a href="http://www.iana.org/assignments/media-types/application/" rel="noreferrer">application type</a> or <a href="http://www.iana.org/assignments/media-types/text/" rel="noreferrer">text type</a> that I can see.</p> <p>Example:</p> <pre><code>&gt; GET /example.yaml &lt; Content-Type: ???? &lt; &lt; --- # Favorite movies &lt; - Casablanca &lt; - North by Northwest &lt; - Notorious </code></pre> <p>Possible options:</p> <ul> <li>text/x-yaml</li> <li>text/yaml</li> <li>text/yml</li> <li>application/x-yaml</li> <li>application/x-yml</li> <li>application/yaml</li> <li>application/yml</li> </ul>
[ { "answer_id": 332159, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 8, "selected": true, "text": "application/x-yaml text/yaml" }, { "answer_id": 332163, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 4, "selected": false, "text": "text/x-yaml text application x-yaml yaml" }, { "answer_id": 38000954, "author": "djb", "author_id": 21352, "author_profile": "https://Stackoverflow.com/users/21352", "pm_score": 5, "selected": false, "text": "text/vnd.yaml\n text/yaml\ntext/x-yaml\napplication/x-yaml\n" }, { "answer_id": 58766053, "author": "The Godfather", "author_id": 1657819, "author_profile": "https://Stackoverflow.com/users/1657819", "pm_score": 0, "selected": false, "text": "text/yaml" }, { "answer_id": 62429124, "author": "Giulio", "author_id": 1468274, "author_profile": "https://Stackoverflow.com/users/1468274", "pm_score": 4, "selected": false, "text": "application/yaml text/yaml" }, { "answer_id": 72362686, "author": "Roberto Polli", "author_id": 4473111, "author_profile": "https://Stackoverflow.com/users/4473111", "pm_score": 2, "selected": false, "text": "application/yaml +yaml text/yaml" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/332129", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5343/" ]
332,161
<p>Someone within my organization has started pushing for us to pilot the CMU SEI's TSP process (see website <a href="http://www.sei.cmu.edu/tsp/" rel="nofollow noreferrer">here</a>). I have an instinctual aversion to any attempts to cure software development illnesses with alphabet soup, but I would like to know if anyone has experience with this process and can provide tangible facts.</p>
[ { "answer_id": 332159, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 8, "selected": true, "text": "application/x-yaml text/yaml" }, { "answer_id": 332163, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 4, "selected": false, "text": "text/x-yaml text application x-yaml yaml" }, { "answer_id": 38000954, "author": "djb", "author_id": 21352, "author_profile": "https://Stackoverflow.com/users/21352", "pm_score": 5, "selected": false, "text": "text/vnd.yaml\n text/yaml\ntext/x-yaml\napplication/x-yaml\n" }, { "answer_id": 58766053, "author": "The Godfather", "author_id": 1657819, "author_profile": "https://Stackoverflow.com/users/1657819", "pm_score": 0, "selected": false, "text": "text/yaml" }, { "answer_id": 62429124, "author": "Giulio", "author_id": 1468274, "author_profile": "https://Stackoverflow.com/users/1468274", "pm_score": 4, "selected": false, "text": "application/yaml text/yaml" }, { "answer_id": 72362686, "author": "Roberto Polli", "author_id": 4473111, "author_profile": "https://Stackoverflow.com/users/4473111", "pm_score": 2, "selected": false, "text": "application/yaml +yaml text/yaml" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/332161", "https://Stackoverflow.com", "https://Stackoverflow.com/users/327/" ]
332,167
<p>Is it possible to change a sql server instance name? Or is it something that can only be set during installation?</p>
[ { "answer_id": 463464, "author": "Stuart Helwig", "author_id": 5019, "author_profile": "https://Stackoverflow.com/users/5019", "pm_score": 1, "selected": false, "text": "sp_dropserver 'oldname', 'droplogins'\n sp_addserver 'newname', local\n use msdb\ngo\n\nupdate sysjobs set originating_server = 'newname'\n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/332167", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39677/" ]
332,178
<p>What is the best method of hiding php errors from being displayed on the browser?</p> <p>Would it be to use the following:</p> <pre><code>ini_set("display_errors", 1); </code></pre> <p>Any best practice tips would be appreciated as well!</p> <p>I am logging the errors, I just want to make sure that setting the display_errors value to off (or 0) will not prevent errors from being logged.</p>
[ { "answer_id": 332206, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 7, "selected": true, "text": "ini_set(\"display_errors\", 0);\nini_set(\"log_errors\", 1);\n\n//Define where do you want the log to go, syslog or a file of your liking with\nini_set(\"error_log\", \"syslog\"); // or ini_set(\"error_log\", \"/path/to/syslog/file\");\n" }, { "answer_id": 332481, "author": "Luis Melgratti", "author_id": 17032, "author_profile": "https://Stackoverflow.com/users/17032", "pm_score": 2, "selected": false, "text": "<IfModule mod_php5.c>\n php_flag display_errors Off\n php_flag log_errors On\n php_value error_log logs/errors\n</IfModule>\n" }, { "answer_id": 333139, "author": "staticsan", "author_id": 28832, "author_profile": "https://Stackoverflow.com/users/28832", "pm_score": 1, "selected": false, "text": "error_reporting = E_ALL display_errors = On display_errors = off log_errors" }, { "answer_id": 335060, "author": "farzad", "author_id": 9394, "author_profile": "https://Stackoverflow.com/users/9394", "pm_score": 2, "selected": false, "text": "if ( isset($_ENV['MY_APP_MODE']) && ($_ENV['MY_APP_MODE'] == 'devel') ) {\n error_reporting(E_ALL);\n} else {\n error_reporting(0);\n}\n" }, { "answer_id": 54618475, "author": "Magnus", "author_id": 930640, "author_profile": "https://Stackoverflow.com/users/930640", "pm_score": 2, "selected": false, "text": " ini_set('display_errors', 'Off');\n ini_set('log_errors', 'On');\n ini_set(\"error_log\", \"/absolute/path/to/my/error_log\");\n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/332178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42135/" ]
332,193
<p>Is there any way to do it? I only have client access and no access to the server. Is there a command I've missed or some software that I can install locally that can connect and find a file by filename?</p>
[ { "answer_id": 332609, "author": "Martin v. Löwis", "author_id": 33006, "author_profile": "https://Stackoverflow.com/users/33006", "pm_score": 0, "selected": false, "text": " cvs rls -Rde <modulename>\n foo:\n/x.py/1.2/Mon Dec 1 23:33:51 2008//\n/y.py/1.1/Mon Dec 1 23:33:31 2008//\nD/bar////\n\nfoo/bar:\n/xxx/1.1/Mon Dec 1 23:36:38 2008//\n" }, { "answer_id": 333685, "author": "Oliver Giesen", "author_id": 9784, "author_profile": "https://Stackoverflow.com/users/9784", "pm_score": 3, "selected": true, "text": "cvs rlog -Nh .\n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/332193", "https://Stackoverflow.com", "https://Stackoverflow.com/users/543/" ]
332,207
<p>I have an OpenGl program in which I am displaying an image using textures. I want to be able to load a new image to be displayed. </p> <p>In my Init function I call:</p> <pre><code>Gl.glGenTextures(1, mTextures); </code></pre> <p>Since only one image will be displayed at time, I am using the same texture name for each image. </p> <p>Each time a new image is loaded I call the following:</p> <pre><code>Gl.glBindTexture(Gl.GL_TEXTURE_2D, mTexture[0]); Gl.glTexImage2D(Gl.GL_TEXTURE_2D, 0, Gl.GL_LUMINANCE, mTexSizeX, mTexSizeY, 0, Gl.GL_LUMINANCE, Gl.GL_UNSIGNED_SHORT, mTexBuffer); Gl.glTexParameteri(Gl.GL_TEXTURE_2D, Gl.GL_TEXTURE_MIN_FILTER, Gl.GL_LINEAR); Gl.glTexParameteri(Gl.GL_TEXTURE_2D, Gl.GL_TEXTURE_MAG_FILTER, Gl.GL_LINEAR); </code></pre> <p>The first image will display as expected. However, all images load after the first, display as all black.</p> <p>What am I doing wrong?</p>
[ { "answer_id": 333233, "author": "unwind", "author_id": 28169, "author_profile": "https://Stackoverflow.com/users/28169", "pm_score": 0, "selected": false, "text": "glTextImage2D glBindTexture()" }, { "answer_id": 1584431, "author": "Bahbar", "author_id": 148383, "author_profile": "https://Stackoverflow.com/users/148383", "pm_score": 1, "selected": false, "text": "glTexImage2D glTexImage2D" }, { "answer_id": 4105637, "author": "borislav", "author_id": 498278, "author_profile": "https://Stackoverflow.com/users/498278", "pm_score": 1, "selected": false, "text": "glDisable GL_TEXTURE_2D glColor4f(1,1,1,1);" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/332207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/55638/" ]
332,229
<p>Suppose you have a method that should create and return an array of some sort. What if the array doesn't get populated. Do you return an empty array or null/nothing?</p>
[ { "answer_id": 332247, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 1, "selected": false, "text": "Collection.size() == 0" }, { "answer_id": 332248, "author": "Greg Beech", "author_id": 13552, "author_profile": "https://Stackoverflow.com/users/13552", "pm_score": 5, "selected": false, "text": "NullReferenceException IEnumerable<T> Collection<T> ReadOnlyCollection<T> ICollection<T> IList<T>" }, { "answer_id": 332324, "author": "Daniel Earwicker", "author_id": 27423, "author_profile": "https://Stackoverflow.com/users/27423", "pm_score": 0, "selected": false, "text": "public static class ArrayUtil<TElement> \n{\n public static readonly Empty = new TElement[0];\n}\n ArrayUtil<int>.Empty" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/332229", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28146/" ]
332,230
<p>I am looking for a way to get the essence or the most important aspect of a webpage? If I provide a URL, is there any external service which can accomplish this? I am not looking for snap.com like service as it provides a snapshot.</p> <p>I might be willing to even implement such a system on my own. For beginning I do not want to put excessive effort, but rather would love to able to get some basic results. Are there any thoughts on how I may approach this problem?</p>
[ { "answer_id": 599504, "author": "Ramesh", "author_id": 30594, "author_profile": "https://Stackoverflow.com/users/30594", "pm_score": 1, "selected": false, "text": "select * from contentanalysis.analyze where url='http://www.cnn.com/2011/11/11/world/europe/greece-main/index.html'; \n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/332230", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29653/" ]
332,254
<p>I have a spreadsheet with a dataset of a number of transactions, each of which is composed of substeps, each of which has the time that it occurred. There can be a variable number and order of steps.</p> <p>I'd like to find the duration of each transaction. If I can do this in Excel then great, as it's already in that format. If there isn't a straight-forward way to do this in Excel, I'll load it into a database and do the analysis with SQL. If there is an Excel way round this it'll save a few hours setup though :)</p> <p>A simplified example of my data is as follows:</p> <p>TransID, Substep, Time<br> 1, step A, 15:00:00<br> 1, step B, 15:01:00<br> 1, step C, 15:02:00<br> 2, step B, 15:03:00<br> 2, step C, 15:04:00<br> 2, step E, 15:05:00<br> 2, step F, 15:06:00<br> 3, step C, 15:07:00<br> 3, step D, 15:08:00<br> etc.</p> <p>I'd like to produce a result set as follows:</p> <p>TransID, Duration<br> 1, 00:02:00<br> 2, 00:03:00<br> 3, 00:01:00<br> etc.</p> <p>My initial try was with an extra column with a formula subtracting end time from start time, but without a repeating number of steps, or the same start and end steps I'm having difficulty seeing how this formula would work.</p> <p>I've also tried creating a pivot table based on this data with ID as the rows and Time as the data. I can change the field settings on the time data to return grouped values such as count or max, but am struggling to see how this can be setup to show max(time) - min(time) for each ID, hence why I'm thinking about heading to SQL. If anyone can point out anything obvious I'm missing though, I'd be very grateful.</p> <p>As suggested by Hobbo, I've now used a pivot table with TransID as the rows and twice added Time as the data. After setting the field settings on the Time to Max on the first and Min on the second, a formula can be added just outside the pivot table to calculate the differences. One thing I'd been overlooking here is that the same value can be added to the data section more than once!</p> <p>A follow-on problem was that the formula I add is of the form =GETPIVOTDATA("Max of Time",$A$4,"ID",1)-GETPIVOTDATA("Min of Time",$A$4,"ID",1), whici doesn't then increment when copying and pasting. Solutions to this are to either use the pivot table toolbar to turn off GETPIVOTDATA formulae, or rather than clicking on the pivot table when selecting cells in the formula, type the cell references instead (e.g. =H4-G4)</p>
[ { "answer_id": 332296, "author": "Kibbee", "author_id": 1862, "author_profile": "https://Stackoverflow.com/users/1862", "pm_score": 1, "selected": false, "text": "SELECT TransID, DateDiff(mi, Min(Time),Max(Time)) AS Duration\nFROM MyTable\nGROUP BY TrandID\n" }, { "answer_id": 332381, "author": "Fionnuala", "author_id": 2548, "author_profile": "https://Stackoverflow.com/users/2548", "pm_score": 1, "selected": false, "text": "'From: http://support.microsoft.com/kb/246335 '\n\nstrFile = Workbooks(1).FullName\nstrCon = \"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\" & strFile _\n & \";Extended Properties=\"\"Excel 8.0;HDR=Yes;IMEX=1\"\";\"\n\nSet cn = CreateObject(\"ADODB.Connection\")\nSet rs = CreateObject(\"ADODB.Recordset\")\n\ncn.Open strCon\n\nstrSQL = \"SELECT TransID, DateDiff('n', Min([MyTime]),Max([MyTime])) AS Duration \" _\n & \"FROM [Sheet1$] GROUP BY TransID\"\n\nrs.Open strSQL, cn\n\n'Write out to another sheet '\nWorksheets(2).Cells(2, 1).CopyFromRecordset rs\n" }, { "answer_id": 332382, "author": "Oddthinking", "author_id": 8014, "author_profile": "https://Stackoverflow.com/users/8014", "pm_score": 0, "selected": false, "text": "=IF(B2=B3, // if this row's TransId is the same as the next one\n \"\", // leave this field blank\n C3- // else find the difference between the last timestamp and...\n VLOOKUP( // look for the first value\n A2, // matching this TransId\n A:C, // within the entire table,\n 3) // Return the value in the third column - i.e. timestamp\n )\n" }, { "answer_id": 333523, "author": "wakingrufus", "author_id": 37847, "author_profile": "https://Stackoverflow.com/users/37847", "pm_score": 1, "selected": false, "text": " A B C\n1 1, step A, 15:00:00\n2 1, step B, 15:01:00\n3 1, step C, 15:02:00\n4 2, step B, 15:03:00\n5 2, step C, 15:04:00\n6 2, step E, 15:05:00\n7 2, step F, 15:06:00\n8 3, step C, 15:07:00\n9 3, step D, 15:08:00\n\n11 1, =max(if($A$1:$A$9=$A11,$C$1:$C$9,\"\")-min(if($A$1:$A$9=$A11,$C$1:$C$9,\"\")\n12 2, =max(if($A$1:$A$9=$A12,$C$1:$C$9,\"\")-min(if($A$1:$A$9=$A12,$C$1:$C$9,\"\")\n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/332254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42234/" ]
332,255
<p>I know <code>class foo(object)</code> is an old school way of defining a class. But I would like to understand in more detail the difference between these two.</p>
[ { "answer_id": 332290, "author": "Brian C. Lane", "author_id": 27461, "author_profile": "https://Stackoverflow.com/users/27461", "pm_score": 4, "selected": false, "text": "class foo(object):" }, { "answer_id": 332575, "author": "muhuk", "author_id": 42188, "author_profile": "https://Stackoverflow.com/users/42188", "pm_score": 3, "selected": false, "text": "object" }, { "answer_id": 332815, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 6, "selected": false, "text": "__mro__ __new__" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/332255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
332,269
<p>Hello I am compiling a program with make but I get the error of No such file or directory but the file is in a directory of the path.</p> <p>I have this #include "genetic.h", that file is in a directory called /home/myuser/toolbox/lib/genalg and in the PATH I have ...:/home/myuser/toolbox/lib/genalg, so I do not why make cannot find the library. Any ideas?. Thanks</p>
[ { "answer_id": 332290, "author": "Brian C. Lane", "author_id": 27461, "author_profile": "https://Stackoverflow.com/users/27461", "pm_score": 4, "selected": false, "text": "class foo(object):" }, { "answer_id": 332575, "author": "muhuk", "author_id": 42188, "author_profile": "https://Stackoverflow.com/users/42188", "pm_score": 3, "selected": false, "text": "object" }, { "answer_id": 332815, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 6, "selected": false, "text": "__mro__ __new__" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/332269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39160/" ]
332,273
<p>I'm trying to setup the Entity Framework with SQL Server 2008. I'm using Guids for the keys on my tables. Is there a way to set it up so the keys are automatically generated by the database? I tried setting "RowGuid" to true and also set the column's default value to be "(newid())". Either way the mapped class still needs me to give it a Guid on the C# side. Any ideas?</p>
[ { "answer_id": 332342, "author": "Corbin March", "author_id": 7625, "author_profile": "https://Stackoverflow.com/users/7625", "pm_score": 2, "selected": false, "text": "private Guid _identifier = Guid.NewGuid();\n" }, { "answer_id": 6867868, "author": "Jeff", "author_id": 868596, "author_profile": "https://Stackoverflow.com/users/868596", "pm_score": 2, "selected": false, "text": "void OgaraEntities_SavingChanges(object sender, EventArgs e)\n{\n foreach (ObjectStateEntry entry in\n ((ObjectContext)sender).ObjectStateManager.GetObjectStateEntries(\n EntityState.Added ))\n {\n if (!entry.IsRelationship){\n string keyFieldName = entry.EntitySet.ElementType.KeyMembers[0].Name;\n object entity = entry.Entity;\n PropertyInfo pi = entity.GetType().GetProperty(keyFieldName);\n pi.SetValue(entity, Guid.NewGuid(), null);\n }\n } \n}\n" }, { "answer_id": 9863051, "author": "mihanik", "author_id": 1185204, "author_profile": "https://Stackoverflow.com/users/1185204", "pm_score": 1, "selected": false, "text": "public partial class SomeEntity\n{\n public static SomeEntity Create()\n {\n return new SomeEntity() { Id = Guid.NewGuid(); }\n }\n}\n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/332273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/632/" ]
332,276
<p>I have a ton of repeating code in my class that looks like the following:</p> <pre><code>NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; </code></pre> <p>The problem with asynchronous requests is when you have various requests going off, and you have a delegate assigned to treat them all as one entity, a lot of branching and ugly code begins to formulate going:</p> <p>What kind of data are we getting back? If it contains this, do that, else do other. It would be useful I think to be able to tag these asynchronous requests, kind of like you're able to tag views with IDs. </p> <p>I was curious what strategy is most efficient for managing a class that handles multiple asynchronous requests.</p>
[ { "answer_id": 332483, "author": "Matt Gallagher", "author_id": 36103, "author_profile": "https://Stackoverflow.com/users/36103", "pm_score": 7, "selected": true, "text": "connectionToInfoMapping =\n CFDictionaryCreateMutable(\n kCFAllocatorDefault,\n 0,\n &kCFTypeDictionaryKeyCallBacks,\n &kCFTypeDictionaryValueCallBacks);\n CFDictionaryAddValue(\n connectionToInfoMapping,\n connection,\n [NSMutableDictionary\n dictionaryWithObject:[NSMutableData data]\n forKey:@\"receivedData\"]);\n - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data\n{\n NSMutableDictionary *connectionInfo =\n CFDictionaryGetValue(connectionToInfoMapping, connection);\n [[connectionInfo objectForKey:@\"receivedData\"] appendData:data];\n}\n" }, { "answer_id": 523926, "author": "mfazekas", "author_id": 27048, "author_profile": "https://Stackoverflow.com/users/27048", "pm_score": 1, "selected": false, "text": "NSMutableDictionary NSURLConnection NSURLConnections NSMutableDictionary NSValue valueWithNonretainedObject] NSMutableDictionary* dict = [NSMutableDictionary dictionary];\nNSValue *key = [NSValue valueWithNonretainedObject:aConnection]\n/* store: */\n[dict setObject:connInfo forKey:key];\n/* lookup: */\n[dict objectForKey:key];\n" }, { "answer_id": 3190757, "author": "petershine", "author_id": 259765, "author_profile": "https://Stackoverflow.com/users/259765", "pm_score": 3, "selected": false, "text": "(NSString *)description setObject:forKey NSURLRequest NSURLConnection -(void)connectionDidFinishLoading:(NSURLConnection *)connection, it can be removed from the dictionary.\n\n// This variable must be able to be referenced from - (void)connectionDidFinishLoading:(NSURLConnection *)connection\nNSMutableDictionary *connDictGET = [[NSMutableDictionary alloc] init];\n//...//\n\n// You can use any object that can be referenced from - (void)connectionDidFinishLoading:(NSURLConnection *)connection\n[connDictGET setObject:anyObjectThatCanBeReferencedFrom forKey:[aConnectionInstanceJustInitiated description]];\n//...//\n\n// At the delegate method, evaluate if the passed connection is the specific one which needs to be handled differently\nif ([[connDictGET objectForKey:[connection description]] isEqual:anyObjectThatCanBeReferencedFrom]) {\n// Do specific work for connection //\n\n}\n//...//\n\n// When the connection is no longer needed, use (NSString *)description as key to remove object\n[connDictGET removeObjectForKey:[connection description]];\n" }, { "answer_id": 4786710, "author": "jbarnhart", "author_id": 588084, "author_profile": "https://Stackoverflow.com/users/588084", "pm_score": 4, "selected": false, "text": "\n- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {\n if (connection == self.savingConnection) {\n [self.savingReturnedData appendData:data];\n }\n else {\n [self.sharingReturnedData appendData:data];\n }\n}\n" }, { "answer_id": 13371408, "author": "Chris Slade", "author_id": 564825, "author_profile": "https://Stackoverflow.com/users/564825", "pm_score": 0, "selected": false, "text": "@interface DataController : NSObject\n\n@property (strong, nonatomic)NSManagedObjectContext *context;\n@property (strong, nonatomic)NSString *accessToken;\n\n+(DataController *)sharedDataController;\n\n-(void)generateAccessTokenWith:(NSString *)email password:(NSString *)password delegate:(id)delegate;\n\n@end\n\n@protocol DataControllerDelegate <NSObject>\n\n-(void)dataFailedtoLoadWithMessage:(NSString *)message;\n-(void)dataFinishedLoading;\n\n@end\n -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {\n NSURLConnectionWithDelegate *customConnection = (NSURLConnectionWithDelegate *)connection;\n NSLog(@\"DidReceiveResponse from %@\", customConnection.tag);\n [[customConnection receivedData] setLength:0];\n}\n\n-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {\n NSURLConnectionWithDelegate *customConnection = (NSURLConnectionWithDelegate *)connection;\n NSLog(@\"DidReceiveData from %@\", customConnection.tag);\n [customConnection.receivedData appendData:data];\n\n}\n\n-(void)connectionDidFinishLoading:(NSURLConnection *)connection {\n NSURLConnectionWithDelegate *customConnection = (NSURLConnectionWithDelegate *)connection;\n NSLog(@\"connectionDidFinishLoading from %@\", customConnection.tag);\n NSLog(@\"Data: %@\", customConnection.receivedData);\n [customConnection.dataDelegate dataFinishedLoading];\n}\n\n-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {\n NSURLConnectionWithDelegate *customConnection = (NSURLConnectionWithDelegate *)connection;\n NSLog(@\"DidFailWithError with %@\", customConnection.tag);\n NSLog(@\"Error: %@\", [error localizedDescription]);\n [customConnection.dataDelegate dataFailedtoLoadWithMessage:[error localizedDescription]];\n}\n [[NSURLConnectionWithDelegate alloc] initWithRequest:request delegate:self startImmediately:YES tag:@\"Login\" dataDelegate:delegate]; @interface NSURLConnectionWithDelegate : NSURLConnection\n\n@property (strong, nonatomic) NSString *tag;\n@property id <DataControllerDelegate> dataDelegate;\n@property (strong, nonatomic) NSMutableData *receivedData;\n\n-(id)initWithRequest:(NSURLRequest *)request delegate:(id)delegate startImmediately:(BOOL)startImmediately tag:(NSString *)tag dataDelegate:(id)dataDelegate;\n\n@end\n #import \"NSURLConnectionWithDelegate.h\"\n\n@implementation NSURLConnectionWithDelegate\n\n-(id)initWithRequest:(NSURLRequest *)request delegate:(id)delegate startImmediately:(BOOL)startImmediately tag:(NSString *)tag dataDelegate:(id)dataDelegate {\n self = [super initWithRequest:request delegate:delegate startImmediately:startImmediately];\n if (self) {\n self.tag = tag;\n self.dataDelegate = dataDelegate;\n self.receivedData = [[NSMutableData alloc] init];\n }\n return self;\n}\n\n@end\n" }, { "answer_id": 13850886, "author": "Yariv Nissim", "author_id": 1220642, "author_profile": "https://Stackoverflow.com/users/1220642", "pm_score": 2, "selected": false, "text": "sendAsynchronousRequest:queue:completionHandler:" }, { "answer_id": 13920755, "author": "Pat Niemeyer", "author_id": 74975, "author_profile": "https://Stackoverflow.com/users/74975", "pm_score": 4, "selected": false, "text": "// DataURLConnection.h\n#import <Foundation/Foundation.h>\n@interface DataURLConnection : NSURLConnection\n@property(nonatomic, strong) NSMutableData *data;\n@end\n\n// DataURLConnection.m\n#import \"DataURLConnection.h\"\n@implementation DataURLConnection\n@synthesize data;\n@end\n - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {\n ((DataURLConnection *)connection).data = [[NSMutableData alloc] init];\n}\n\n- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {\n [((DataURLConnection *)connection).data appendData:data];\n}\n // Add to DataURLConnection.h/.m\n@property(nonatomic, copy) void (^onComplete)();\n DataURLConnection *con = [[DataURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];\ncon.onComplete = ^{\n [self myMethod:con];\n};\n[con start];\n - (void)connectionDidFinishLoading:(NSURLConnection *)connection {\n ((DataURLConnection *)connection).onComplete();\n}\n" }, { "answer_id": 20741560, "author": "eold", "author_id": 683660, "author_profile": "https://Stackoverflow.com/users/683660", "pm_score": 0, "selected": false, "text": "// Make Request\nNSURLRequest *request = [NSURLRequest requestWithURL:url];\nNSURLConnection *c = [[NSURLConnection alloc] initWithRequest:request delegate:self];\n\n// Append Stuffs \nNSMutableDictionary *myStuff = [[NSMutableDictionary alloc] init];\n[myStuff setObject:@\"obj\" forKey:@\"key\"];\nNSNumber *connectionKey = [NSNumber numberWithInt:c.hash];\n\n[connectionDatas setObject:myStuff forKey:connectionKey];\n\n[c start];\n - (void)connectionDidFinishLoading:(NSURLConnection *)connection\n{\n NSLog(@\"Received %d bytes of data\",[responseData length]);\n\n NSNumber *connectionKey = [NSNumber numberWithInt:connection.hash];\n\n NSMutableDictionary *myStuff = [[connectionDatas objectForKey:connectionKey]mutableCopy];\n [connectionDatas removeObjectForKey:connectionKey];\n}\n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/332276", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40882/" ]
332,284
<p>We want to allow "normal" href links to other webpages, but we don't want to allow anyone to sneak in client-side scripting.</p> <p>Is searching for "javascript:" within the HREF and onclick/onmouseover/etc. events good enough? Or are there other things to check?</p>
[ { "answer_id": 332338, "author": "Timothy Khouri", "author_id": 11917, "author_profile": "https://Stackoverflow.com/users/11917", "pm_score": 0, "selected": false, "text": "<img src=\"nosuchimage.blahblah\" onerror=\"alert('Haxored!!!');\" />\n <a href=\"about:blank;\" onclick=\"alert('Haxored again!!!');\">click meh</a>\n" }, { "answer_id": 332409, "author": "Ed Marty", "author_id": 36007, "author_profile": "https://Stackoverflow.com/users/36007", "pm_score": 0, "selected": false, "text": "[url=\"xxx\"]yyy[/url] <a href=\"xxx\">yyy</a> &quot;" }, { "answer_id": 332673, "author": "Kent Brewster", "author_id": 1151280, "author_profile": "https://Stackoverflow.com/users/1151280", "pm_score": 0, "selected": false, "text": "strip_tags strip_attributes strip_tags" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/332284", "https://Stackoverflow.com", "https://Stackoverflow.com/users/337/" ]
332,289
<p>How do I change the size of figure drawn with Matplotlib?</p>
[ { "answer_id": 332311, "author": "tatwright", "author_id": 40849, "author_profile": "https://Stackoverflow.com/users/40849", "pm_score": 9, "selected": false, "text": "pylab matplotlib.pyplot from pylab import rcParams\nrcParams['figure.figsize'] = 5, 10\n" }, { "answer_id": 334462, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 6, "selected": false, "text": "'matplotlib figure size' test[1-3].png #!/usr/bin/env python\n\"\"\"\nThis is a small demo file that helps teach how to adjust figure sizes\nfor matplotlib\n\n\"\"\"\n\nimport matplotlib\nprint \"using MPL version:\", matplotlib.__version__\nmatplotlib.use(\"WXAgg\") # do this before pylab so you don'tget the default back end.\n\nimport pylab\nimport numpy as np\n\n# Generate and plot some simple data:\nx = np.arange(0, 2*np.pi, 0.1)\ny = np.sin(x)\n\npylab.plot(x,y)\nF = pylab.gcf()\n\n# Now check everything with the defaults:\nDPI = F.get_dpi()\nprint \"DPI:\", DPI\nDefaultSize = F.get_size_inches()\nprint \"Default size in Inches\", DefaultSize\nprint \"Which should result in a %i x %i Image\"%(DPI*DefaultSize[0], DPI*DefaultSize[1])\n# the default is 100dpi for savefig:\nF.savefig(\"test1.png\")\n# this gives me a 797 x 566 pixel image, which is about 100 DPI\n\n# Now make the image twice as big, while keeping the fonts and all the\n# same size\nF.set_size_inches( (DefaultSize[0]*2, DefaultSize[1]*2) )\nSize = F.get_size_inches()\nprint \"Size in Inches\", Size\nF.savefig(\"test2.png\")\n# this results in a 1595x1132 image\n\n# Now make the image twice as big, making all the fonts and lines\n# bigger too.\n\nF.set_size_inches( DefaultSize )# resetthe size\nSize = F.get_size_inches()\nprint \"Size in Inches\", Size\nF.savefig(\"test3.png\", dpi = (200)) # change the dpi\n# this also results in a 1595x1132 image, but the fonts are larger.\n using MPL version: 0.98.1\nDPI: 80\nDefault size in Inches [ 8. 6.]\nWhich should result in a 640 x 480 Image\nSize in Inches [ 16. 12.]\nSize in Inches [ 16. 12.]\n" }, { "answer_id": 638443, "author": "Jouni K. Seppänen", "author_id": 26575, "author_profile": "https://Stackoverflow.com/users/26575", "pm_score": 11, "selected": false, "text": "figure from matplotlib.pyplot import figure\n\nfigure(figsize=(8, 6), dpi=80)\n figure(figsize=(1,1))" }, { "answer_id": 4306340, "author": "Pete", "author_id": 349043, "author_profile": "https://Stackoverflow.com/users/349043", "pm_score": 10, "selected": false, "text": "figure.set_size_inches fig = matplotlib.pyplot.gcf()\nfig.set_size_inches(18.5, 10.5)\nfig.savefig('test2png.png', dpi=100)\n forward=True fig.set_size_inches(18.5, 10.5, forward=True)\n figure.set_dpi fig.set_dpi(100)\n" }, { "answer_id": 22399608, "author": "Renaud", "author_id": 125617, "author_profile": "https://Stackoverflow.com/users/125617", "pm_score": 6, "selected": false, "text": "fig = ... import numpy as np\nimport matplotlib.pyplot as plt\n\nN = 50\nx = np.random.rand(N)\ny = np.random.rand(N)\narea = np.pi * (15 * np.random.rand(N))**2\n\nfig = plt.figure(figsize=(18, 18))\nplt.scatter(x, y, s=area, alpha=0.5)\nplt.show()\n" }, { "answer_id": 23903662, "author": "Blairg23", "author_id": 1224827, "author_profile": "https://Stackoverflow.com/users/1224827", "pm_score": 5, "selected": false, "text": "from matplotlib import pyplot as plt\n\nF = plt.gcf()\nSize = F.get_size_inches()\nF.set_size_inches(Size[0]*2, Size[1]*2, forward=True) # Set forward to True to resize window along with plot in figure.\nplt.show() # Or plt.imshow(z_array) if using an animation, where z_array is a matrix or NumPy array\n" }, { "answer_id": 26601247, "author": "wilywampa", "author_id": 752720, "author_profile": "https://Stackoverflow.com/users/752720", "pm_score": 4, "selected": false, "text": "matplotlib.pyplot.get_current_fig_manager().resize(width_px, height_px)\n" }, { "answer_id": 26650785, "author": "psihodelia", "author_id": 215571, "author_profile": "https://Stackoverflow.com/users/215571", "pm_score": 4, "selected": false, "text": "N = 2\nparams = pl.gcf()\nplSize = params.get_size_inches()\nparams.set_size_inches((plSize[0]*N, plSize[1]*N))\n" }, { "answer_id": 38750738, "author": "Franck Dernoncourt", "author_id": 395857, "author_profile": "https://Stackoverflow.com/users/395857", "pm_score": 4, "selected": false, "text": "def cm2inch(*tupl):\n inch = 2.54\n if isinstance(tupl[0], tuple):\n return tuple(i/inch for i in tupl[0])\n else:\n return tuple(i/inch for i in tupl)\n plt.figure(figsize=cm2inch(21, 29.7))\n" }, { "answer_id": 39770939, "author": "Kris", "author_id": 2123555, "author_profile": "https://Stackoverflow.com/users/2123555", "pm_score": 8, "selected": false, "text": "df['some_column'].plot(figsize=(10, 5))\n df fig, ax = plt.subplots(figsize=(10, 5))\ndf['some_column'].plot(ax=ax)\n import matplotlib\n\nmatplotlib.rc('figure', figsize=(10, 5))\n pd.DataFrame.plot" }, { "answer_id": 41717533, "author": "G M", "author_id": 2132157, "author_profile": "https://Stackoverflow.com/users/2132157", "pm_score": 9, "selected": false, "text": "plt.plot() import matplotlib.pyplot as plt\nplt.rcParams[\"figure.figsize\"] = (20,3)\n plt.rcParams[\"figure.figsize\"] = plt.rcParamsDefault[\"figure.figsize\"]\n figsize" }, { "answer_id": 47018826, "author": "River", "author_id": 3745896, "author_profile": "https://Stackoverflow.com/users/3745896", "pm_score": 6, "selected": false, "text": "fig.set_size_inches(width,height)\n forward True fig.set_figwidth(val) fig.set_figheight(val) forward=True set_figwidth set_figheight forward" }, { "answer_id": 59108174, "author": "loved.by.Jesus", "author_id": 4428520, "author_profile": "https://Stackoverflow.com/users/4428520", "pm_score": 4, "selected": false, "text": "sizefactor import matplotlib.pyplot as plt\n\n# Here goes your code\n\nfig_size = plt.gcf().get_size_inches() # Get current size\nsizefactor = 0.8 # Set a zoom factor\n# Modify the current size by the factor\nplt.gcf().set_size_inches(sizefactor * fig_size) \n plt.subplots_adjust(left=0.16, bottom=0.19, top=0.82)\n" }, { "answer_id": 64490245, "author": "Luguecos", "author_id": 11050547, "author_profile": "https://Stackoverflow.com/users/11050547", "pm_score": 2, "selected": false, "text": "x_inches = 150*(1/25.4) # [mm]*constant\ny_inches = x_inches*(0.8)\ndpi = 96\n\nfig = plt.figure(1, figsize = (x_inches,y_inches), dpi = dpi, constrained_layout = True)\n constrained_layout True" }, { "answer_id": 64767170, "author": "Ciro Santilli OurBigBook.com", "author_id": 895245, "author_profile": "https://Stackoverflow.com/users/895245", "pm_score": 5, "selected": false, "text": "savefig #!/usr/bin/env python3\n\nimport sys\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\n\nfig, ax = plt.subplots()\nprint('fig.dpi = {}'.format(fig.dpi))\nprint('fig.get_size_inches() = ' + str(fig.get_size_inches())\nt = np.arange(-10., 10., 1.)\nplt.plot(t, t, '.')\nplt.plot(t, t**2, '.')\nax.text(0., 60., 'Hello', fontdict=dict(size=25))\nplt.savefig('base.png', format='png')\n ./base.py\nidentify base.png\n fig.dpi = 100.0\nfig.get_size_inches() = [6.4 4.8]\nbase.png PNG 640x480 640x480+0+0 8-bit sRGB 13064B 0.000u 0:00.000\n plt.savefig(dpi=h/fig.get_size_inches()[1] #!/usr/bin/env python3\n\nimport sys\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\n\nheight = int(sys.argv[1])\nfig, ax = plt.subplots()\nt = np.arange(-10., 10., 1.)\nplt.plot(t, t, '.')\nplt.plot(t, t**2, '.')\nax.text(0., 60., 'Hello', fontdict=dict(size=25))\nplt.savefig(\n 'get_size.png',\n format='png',\n dpi=height/fig.get_size_inches()[1]\n)\n ./get_size.py 431\n get_size.png PNG 574x431 574x431+0+0 8-bit sRGB 10058B 0.000u 0:00.000\n ./get_size.py 1293\n main.png PNG 1724x1293 1724x1293+0+0 8-bit sRGB 46709B 0.000u 0:00.000\n plt.savefig(bbox_inches='tight' bbox_inches='tight' plt.tight_layout(pad=1)\nplt.savefig(...\n set_aspect set_aspect plt.tight_layout plt.savefig(dpi=h/fig.get_size_inches()[1] #!/usr/bin/env python3\n\nimport sys\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\n\nh = int(sys.argv[1])\nw = int(sys.argv[2])\nfig, ax = plt.subplots()\nwi, hi = fig.get_size_inches()\nfig.set_size_inches(hi*(w/h), hi)\nt = np.arange(-10., 10., 1.)\nplt.plot(t, t, '.')\nplt.plot(t, t**2, '.')\nax.text(0., 60., 'Hello', fontdict=dict(size=25))\nplt.savefig(\n 'width.png',\n format='png',\n dpi=h/hi\n)\n ./width.py 431 869\n width.png PNG 869x431 869x431+0+0 8-bit sRGB 10965B 0.000u 0:00.000\n ./width.py 431 869\n width.png PNG 211x431 211x431+0+0 8-bit sRGB 6949B 0.000u 0:00.000\n 100 plt.tight_layout(pad=1)\n width.png PNG 211x431 211x431+0+0 8-bit sRGB 7134B 0.000u 0:00.000\n tight_layout dpi fig.set_size_inches plt.savefig(dpi= #!/usr/bin/env python3\n\nimport sys\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\n\nmagic_height = 300\nw = int(sys.argv[1])\nh = int(sys.argv[2])\ndpi = 80\nfig, ax = plt.subplots(dpi=dpi)\nfig.set_size_inches(magic_height*w/(h*dpi), magic_height/dpi)\nt = np.arange(-10., 10., 1.)\nplt.plot(t, t, '.')\nplt.plot(t, t**2, '.')\nax.text(0., 60., 'Hello', fontdict=dict(size=25))\nplt.savefig(\n 'magic.png',\n format='png',\n dpi=h/magic_height*dpi,\n)\n ./magic.py 431 231\n magic.png PNG 431x231 431x231+0+0 8-bit sRGB 7923B 0.000u 0:00.000\n ./magic.py 1291 693\n magic.png PNG 1291x693 1291x693+0+0 8-bit sRGB 25013B 0.000u 0:00.000\n magic_height set_size_inches #!/usr/bin/env python3\n\nimport sys\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\n\nw = int(sys.argv[1])\nh = int(sys.argv[2])\nfig, ax = plt.subplots()\nfig.set_size_inches(w/fig.dpi, h/fig.dpi)\nt = np.arange(-10., 10., 1.)\nplt.plot(t, t, '.')\nplt.plot(t, t**2, '.')\nax.text(\n 0,\n 60.,\n 'Hello',\n # Keep font size fixed independently of DPI.\n # https://stackoverflow.com/questions/39395616/matplotlib-change-figsize-but-keep-fontsize-constant\n fontdict=dict(size=10*h/fig.dpi),\n)\nplt.savefig(\n 'set_size_inches.png',\n format='png',\n)\n ./set_size_inches.py 431 231\n set_size_inches.png PNG 430x231 430x231+0+0 8-bit sRGB 8078B 0.000u 0:00.000\n ./set_size_inches.py 1291 693\n set_size_inches.png PNG 1291x693 1291x693+0+0 8-bit sRGB 19798B 0.000u 0:00.000\n #!/usr/bin/env python3\n\nimport sys\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\n\nheight = int(sys.argv[1])\nfig, ax = plt.subplots()\nt = np.arange(-10., 10., 1.)\nplt.plot(t, t, '.')\nplt.plot(t, t**2, '.')\nax.text(0., 60., 'Hello', fontdict=dict(size=25))\nplt.savefig(\n 'get_size_svg.svg',\n format='svg',\n dpi=height/fig.get_size_inches()[1]\n)\n ./get_size_svg.py 431\n <svg height=\"345.6pt\" version=\"1.1\" viewBox=\"0 0 460.8 345.6\" width=\"460.8pt\"\n get_size_svg.svg SVG 614x461 614x461+0+0 8-bit sRGB 17094B 0.000u 0:00.000\n inkscape -h 431 get_size_svg.svg -b FFF -e get_size_svg.png\n convert -density <img height=\"\"" }, { "answer_id": 66315574, "author": "circassia_ai", "author_id": 7302404, "author_profile": "https://Stackoverflow.com/users/7302404", "pm_score": 4, "selected": false, "text": "plt.figure(figsize=(width,height))\n width height rcParams[\"figure.figsize\"] = [6.4, 4.8]" }, { "answer_id": 66638878, "author": "Shahriar Kabir Khan", "author_id": 9453613, "author_profile": "https://Stackoverflow.com/users/9453613", "pm_score": 4, "selected": false, "text": "plt.figure(figsize=(20,10)) plt.plot(x,y) plt.pie() import matplotlib.pyplot as plt\nplt.figure(figsize=(20, 10))\nplt.plot(x,y) # This is your plot\nplt.show()\n" }, { "answer_id": 67180265, "author": "iacob", "author_id": 9067615, "author_profile": "https://Stackoverflow.com/users/9067615", "pm_score": 3, "selected": false, "text": "figsize import matplotlib.pyplot as plt\nfig = plt.figure(figsize=(w,h))\n set_size_inches() fig.set_size_inches(w,h)\n rc plt.rc('figure', figsize=(w,h))\n" }, { "answer_id": 68002660, "author": "Ali Muhammad Khowaja", "author_id": 15663611, "author_profile": "https://Stackoverflow.com/users/15663611", "pm_score": 3, "selected": false, "text": "import matplotlib.pyplot as plt\nfrom matplotlib.pyplot import figure\n\nfigure(figsize=(16, 8), dpi=80)\nplt.plot(x_test, color = 'red', label = 'Predicted Price')\nplt.plot(y_test, color = 'blue', label = 'Actual Price')\nplt.title('Dollar to PKR Prediction')\nplt.xlabel('Predicted Price')\nplt.ylabel('Actual Dollar Price')\nplt.legend()\nplt.show()\n" }, { "answer_id": 69768472, "author": "nizarhamood", "author_id": 12349230, "author_profile": "https://Stackoverflow.com/users/12349230", "pm_score": 2, "selected": false, "text": "import matplotlib.pyplot as plt\n\ndata = [2,5,8,10,15] # Random data, can use existing data frame column\n\nfig, axs = plt.subplots(figsize = (20,6)) # This is your answer to resize the figure\n\n# The below will help you expand on your question and resize individual elements within your figure. Experiement with the below parameters.\naxs.set_title(\"Data\", fontsize = 17.5)\naxs.tick_params(axis = 'x', labelsize = 14)\naxs.set_xlabel('X Label Here', size = 15)\naxs.tick_params(axis = 'y', labelsize =14)\naxs.set_ylabel('Y Label Here', size = 15)\n\nplt.plot(data)\n" }, { "answer_id": 71933465, "author": "Derrick Kuria", "author_id": 13186690, "author_profile": "https://Stackoverflow.com/users/13186690", "pm_score": 3, "selected": false, "text": "import matplotlib as mpl\nimport matplotlib.pyplot as plt\nmpl.rcParams['figure.figsize'] = (8, 6)\nmpl.rcParams['axes.grid'] = False\n" }, { "answer_id": 74303614, "author": "pplonski", "author_id": 5605919, "author_profile": "https://Stackoverflow.com/users/5605919", "pm_score": 1, "selected": false, "text": "dpi dpi figsize dpi from matplotlib import pyplot as plt\n\nplt.figure(figsize=(3, 3), dpi=144)\n_ = plt.plot([3, 4, 2, 5])\n set_figwidth set_figheight set_size_inches set_dpi # create figure\nf = plt.figure()\n\n# set width, height, dpi\nf.set_figwidth(4)\nf.set_figheight(2)\nf.set_dpi(142)\n\n# plot\n_ = plt.plot([3,4,2,5])\n dpi dpi # set figsize and dpi for all figures\nplt.rcParams[\"figure.figsize\"] = (4,2)\nplt.rcParams[\"figure.dpi\"] = 144\n rcParams" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/332289", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40849/" ]
332,291
<p>What is the best way to build a loopback URL for an AJAX call? Say I have a page at</p> <pre><code>http://www.mydomain.com/some/subdir/file.php </code></pre> <p>that I want to load with an AJAX call. In Firefox, using jQuery this works fine:</p> <pre><code>$.post('/some/subdir/file.php', ...); </code></pre> <p>Safari/WebKit tries to interpret this as a location on the local filesystem (so it ends up translating to 'file://some/subdir/file.php'). Not only does this not point to anything useful, it also results in a security error.</p> <p>Is there a way to accomplish this without hard-coding the domain into the URL? I'd like to make this as domain-independent as possible.</p> <p><strong>Update</strong></p> <p>I ended up parsing out the base url from location.href and throwing it into an accessible jQuery function like this:</p> <pre><code>/** * Retrieves the current root URL. * * @return string the root URL */ $.fn.rootUrl = function() { var url = location.href; return url.substring(0, url.indexOf('/', 7)); }; </code></pre>
[ { "answer_id": 332311, "author": "tatwright", "author_id": 40849, "author_profile": "https://Stackoverflow.com/users/40849", "pm_score": 9, "selected": false, "text": "pylab matplotlib.pyplot from pylab import rcParams\nrcParams['figure.figsize'] = 5, 10\n" }, { "answer_id": 334462, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 6, "selected": false, "text": "'matplotlib figure size' test[1-3].png #!/usr/bin/env python\n\"\"\"\nThis is a small demo file that helps teach how to adjust figure sizes\nfor matplotlib\n\n\"\"\"\n\nimport matplotlib\nprint \"using MPL version:\", matplotlib.__version__\nmatplotlib.use(\"WXAgg\") # do this before pylab so you don'tget the default back end.\n\nimport pylab\nimport numpy as np\n\n# Generate and plot some simple data:\nx = np.arange(0, 2*np.pi, 0.1)\ny = np.sin(x)\n\npylab.plot(x,y)\nF = pylab.gcf()\n\n# Now check everything with the defaults:\nDPI = F.get_dpi()\nprint \"DPI:\", DPI\nDefaultSize = F.get_size_inches()\nprint \"Default size in Inches\", DefaultSize\nprint \"Which should result in a %i x %i Image\"%(DPI*DefaultSize[0], DPI*DefaultSize[1])\n# the default is 100dpi for savefig:\nF.savefig(\"test1.png\")\n# this gives me a 797 x 566 pixel image, which is about 100 DPI\n\n# Now make the image twice as big, while keeping the fonts and all the\n# same size\nF.set_size_inches( (DefaultSize[0]*2, DefaultSize[1]*2) )\nSize = F.get_size_inches()\nprint \"Size in Inches\", Size\nF.savefig(\"test2.png\")\n# this results in a 1595x1132 image\n\n# Now make the image twice as big, making all the fonts and lines\n# bigger too.\n\nF.set_size_inches( DefaultSize )# resetthe size\nSize = F.get_size_inches()\nprint \"Size in Inches\", Size\nF.savefig(\"test3.png\", dpi = (200)) # change the dpi\n# this also results in a 1595x1132 image, but the fonts are larger.\n using MPL version: 0.98.1\nDPI: 80\nDefault size in Inches [ 8. 6.]\nWhich should result in a 640 x 480 Image\nSize in Inches [ 16. 12.]\nSize in Inches [ 16. 12.]\n" }, { "answer_id": 638443, "author": "Jouni K. Seppänen", "author_id": 26575, "author_profile": "https://Stackoverflow.com/users/26575", "pm_score": 11, "selected": false, "text": "figure from matplotlib.pyplot import figure\n\nfigure(figsize=(8, 6), dpi=80)\n figure(figsize=(1,1))" }, { "answer_id": 4306340, "author": "Pete", "author_id": 349043, "author_profile": "https://Stackoverflow.com/users/349043", "pm_score": 10, "selected": false, "text": "figure.set_size_inches fig = matplotlib.pyplot.gcf()\nfig.set_size_inches(18.5, 10.5)\nfig.savefig('test2png.png', dpi=100)\n forward=True fig.set_size_inches(18.5, 10.5, forward=True)\n figure.set_dpi fig.set_dpi(100)\n" }, { "answer_id": 22399608, "author": "Renaud", "author_id": 125617, "author_profile": "https://Stackoverflow.com/users/125617", "pm_score": 6, "selected": false, "text": "fig = ... import numpy as np\nimport matplotlib.pyplot as plt\n\nN = 50\nx = np.random.rand(N)\ny = np.random.rand(N)\narea = np.pi * (15 * np.random.rand(N))**2\n\nfig = plt.figure(figsize=(18, 18))\nplt.scatter(x, y, s=area, alpha=0.5)\nplt.show()\n" }, { "answer_id": 23903662, "author": "Blairg23", "author_id": 1224827, "author_profile": "https://Stackoverflow.com/users/1224827", "pm_score": 5, "selected": false, "text": "from matplotlib import pyplot as plt\n\nF = plt.gcf()\nSize = F.get_size_inches()\nF.set_size_inches(Size[0]*2, Size[1]*2, forward=True) # Set forward to True to resize window along with plot in figure.\nplt.show() # Or plt.imshow(z_array) if using an animation, where z_array is a matrix or NumPy array\n" }, { "answer_id": 26601247, "author": "wilywampa", "author_id": 752720, "author_profile": "https://Stackoverflow.com/users/752720", "pm_score": 4, "selected": false, "text": "matplotlib.pyplot.get_current_fig_manager().resize(width_px, height_px)\n" }, { "answer_id": 26650785, "author": "psihodelia", "author_id": 215571, "author_profile": "https://Stackoverflow.com/users/215571", "pm_score": 4, "selected": false, "text": "N = 2\nparams = pl.gcf()\nplSize = params.get_size_inches()\nparams.set_size_inches((plSize[0]*N, plSize[1]*N))\n" }, { "answer_id": 38750738, "author": "Franck Dernoncourt", "author_id": 395857, "author_profile": "https://Stackoverflow.com/users/395857", "pm_score": 4, "selected": false, "text": "def cm2inch(*tupl):\n inch = 2.54\n if isinstance(tupl[0], tuple):\n return tuple(i/inch for i in tupl[0])\n else:\n return tuple(i/inch for i in tupl)\n plt.figure(figsize=cm2inch(21, 29.7))\n" }, { "answer_id": 39770939, "author": "Kris", "author_id": 2123555, "author_profile": "https://Stackoverflow.com/users/2123555", "pm_score": 8, "selected": false, "text": "df['some_column'].plot(figsize=(10, 5))\n df fig, ax = plt.subplots(figsize=(10, 5))\ndf['some_column'].plot(ax=ax)\n import matplotlib\n\nmatplotlib.rc('figure', figsize=(10, 5))\n pd.DataFrame.plot" }, { "answer_id": 41717533, "author": "G M", "author_id": 2132157, "author_profile": "https://Stackoverflow.com/users/2132157", "pm_score": 9, "selected": false, "text": "plt.plot() import matplotlib.pyplot as plt\nplt.rcParams[\"figure.figsize\"] = (20,3)\n plt.rcParams[\"figure.figsize\"] = plt.rcParamsDefault[\"figure.figsize\"]\n figsize" }, { "answer_id": 47018826, "author": "River", "author_id": 3745896, "author_profile": "https://Stackoverflow.com/users/3745896", "pm_score": 6, "selected": false, "text": "fig.set_size_inches(width,height)\n forward True fig.set_figwidth(val) fig.set_figheight(val) forward=True set_figwidth set_figheight forward" }, { "answer_id": 59108174, "author": "loved.by.Jesus", "author_id": 4428520, "author_profile": "https://Stackoverflow.com/users/4428520", "pm_score": 4, "selected": false, "text": "sizefactor import matplotlib.pyplot as plt\n\n# Here goes your code\n\nfig_size = plt.gcf().get_size_inches() # Get current size\nsizefactor = 0.8 # Set a zoom factor\n# Modify the current size by the factor\nplt.gcf().set_size_inches(sizefactor * fig_size) \n plt.subplots_adjust(left=0.16, bottom=0.19, top=0.82)\n" }, { "answer_id": 64490245, "author": "Luguecos", "author_id": 11050547, "author_profile": "https://Stackoverflow.com/users/11050547", "pm_score": 2, "selected": false, "text": "x_inches = 150*(1/25.4) # [mm]*constant\ny_inches = x_inches*(0.8)\ndpi = 96\n\nfig = plt.figure(1, figsize = (x_inches,y_inches), dpi = dpi, constrained_layout = True)\n constrained_layout True" }, { "answer_id": 64767170, "author": "Ciro Santilli OurBigBook.com", "author_id": 895245, "author_profile": "https://Stackoverflow.com/users/895245", "pm_score": 5, "selected": false, "text": "savefig #!/usr/bin/env python3\n\nimport sys\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\n\nfig, ax = plt.subplots()\nprint('fig.dpi = {}'.format(fig.dpi))\nprint('fig.get_size_inches() = ' + str(fig.get_size_inches())\nt = np.arange(-10., 10., 1.)\nplt.plot(t, t, '.')\nplt.plot(t, t**2, '.')\nax.text(0., 60., 'Hello', fontdict=dict(size=25))\nplt.savefig('base.png', format='png')\n ./base.py\nidentify base.png\n fig.dpi = 100.0\nfig.get_size_inches() = [6.4 4.8]\nbase.png PNG 640x480 640x480+0+0 8-bit sRGB 13064B 0.000u 0:00.000\n plt.savefig(dpi=h/fig.get_size_inches()[1] #!/usr/bin/env python3\n\nimport sys\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\n\nheight = int(sys.argv[1])\nfig, ax = plt.subplots()\nt = np.arange(-10., 10., 1.)\nplt.plot(t, t, '.')\nplt.plot(t, t**2, '.')\nax.text(0., 60., 'Hello', fontdict=dict(size=25))\nplt.savefig(\n 'get_size.png',\n format='png',\n dpi=height/fig.get_size_inches()[1]\n)\n ./get_size.py 431\n get_size.png PNG 574x431 574x431+0+0 8-bit sRGB 10058B 0.000u 0:00.000\n ./get_size.py 1293\n main.png PNG 1724x1293 1724x1293+0+0 8-bit sRGB 46709B 0.000u 0:00.000\n plt.savefig(bbox_inches='tight' bbox_inches='tight' plt.tight_layout(pad=1)\nplt.savefig(...\n set_aspect set_aspect plt.tight_layout plt.savefig(dpi=h/fig.get_size_inches()[1] #!/usr/bin/env python3\n\nimport sys\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\n\nh = int(sys.argv[1])\nw = int(sys.argv[2])\nfig, ax = plt.subplots()\nwi, hi = fig.get_size_inches()\nfig.set_size_inches(hi*(w/h), hi)\nt = np.arange(-10., 10., 1.)\nplt.plot(t, t, '.')\nplt.plot(t, t**2, '.')\nax.text(0., 60., 'Hello', fontdict=dict(size=25))\nplt.savefig(\n 'width.png',\n format='png',\n dpi=h/hi\n)\n ./width.py 431 869\n width.png PNG 869x431 869x431+0+0 8-bit sRGB 10965B 0.000u 0:00.000\n ./width.py 431 869\n width.png PNG 211x431 211x431+0+0 8-bit sRGB 6949B 0.000u 0:00.000\n 100 plt.tight_layout(pad=1)\n width.png PNG 211x431 211x431+0+0 8-bit sRGB 7134B 0.000u 0:00.000\n tight_layout dpi fig.set_size_inches plt.savefig(dpi= #!/usr/bin/env python3\n\nimport sys\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\n\nmagic_height = 300\nw = int(sys.argv[1])\nh = int(sys.argv[2])\ndpi = 80\nfig, ax = plt.subplots(dpi=dpi)\nfig.set_size_inches(magic_height*w/(h*dpi), magic_height/dpi)\nt = np.arange(-10., 10., 1.)\nplt.plot(t, t, '.')\nplt.plot(t, t**2, '.')\nax.text(0., 60., 'Hello', fontdict=dict(size=25))\nplt.savefig(\n 'magic.png',\n format='png',\n dpi=h/magic_height*dpi,\n)\n ./magic.py 431 231\n magic.png PNG 431x231 431x231+0+0 8-bit sRGB 7923B 0.000u 0:00.000\n ./magic.py 1291 693\n magic.png PNG 1291x693 1291x693+0+0 8-bit sRGB 25013B 0.000u 0:00.000\n magic_height set_size_inches #!/usr/bin/env python3\n\nimport sys\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\n\nw = int(sys.argv[1])\nh = int(sys.argv[2])\nfig, ax = plt.subplots()\nfig.set_size_inches(w/fig.dpi, h/fig.dpi)\nt = np.arange(-10., 10., 1.)\nplt.plot(t, t, '.')\nplt.plot(t, t**2, '.')\nax.text(\n 0,\n 60.,\n 'Hello',\n # Keep font size fixed independently of DPI.\n # https://stackoverflow.com/questions/39395616/matplotlib-change-figsize-but-keep-fontsize-constant\n fontdict=dict(size=10*h/fig.dpi),\n)\nplt.savefig(\n 'set_size_inches.png',\n format='png',\n)\n ./set_size_inches.py 431 231\n set_size_inches.png PNG 430x231 430x231+0+0 8-bit sRGB 8078B 0.000u 0:00.000\n ./set_size_inches.py 1291 693\n set_size_inches.png PNG 1291x693 1291x693+0+0 8-bit sRGB 19798B 0.000u 0:00.000\n #!/usr/bin/env python3\n\nimport sys\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\n\nheight = int(sys.argv[1])\nfig, ax = plt.subplots()\nt = np.arange(-10., 10., 1.)\nplt.plot(t, t, '.')\nplt.plot(t, t**2, '.')\nax.text(0., 60., 'Hello', fontdict=dict(size=25))\nplt.savefig(\n 'get_size_svg.svg',\n format='svg',\n dpi=height/fig.get_size_inches()[1]\n)\n ./get_size_svg.py 431\n <svg height=\"345.6pt\" version=\"1.1\" viewBox=\"0 0 460.8 345.6\" width=\"460.8pt\"\n get_size_svg.svg SVG 614x461 614x461+0+0 8-bit sRGB 17094B 0.000u 0:00.000\n inkscape -h 431 get_size_svg.svg -b FFF -e get_size_svg.png\n convert -density <img height=\"\"" }, { "answer_id": 66315574, "author": "circassia_ai", "author_id": 7302404, "author_profile": "https://Stackoverflow.com/users/7302404", "pm_score": 4, "selected": false, "text": "plt.figure(figsize=(width,height))\n width height rcParams[\"figure.figsize\"] = [6.4, 4.8]" }, { "answer_id": 66638878, "author": "Shahriar Kabir Khan", "author_id": 9453613, "author_profile": "https://Stackoverflow.com/users/9453613", "pm_score": 4, "selected": false, "text": "plt.figure(figsize=(20,10)) plt.plot(x,y) plt.pie() import matplotlib.pyplot as plt\nplt.figure(figsize=(20, 10))\nplt.plot(x,y) # This is your plot\nplt.show()\n" }, { "answer_id": 67180265, "author": "iacob", "author_id": 9067615, "author_profile": "https://Stackoverflow.com/users/9067615", "pm_score": 3, "selected": false, "text": "figsize import matplotlib.pyplot as plt\nfig = plt.figure(figsize=(w,h))\n set_size_inches() fig.set_size_inches(w,h)\n rc plt.rc('figure', figsize=(w,h))\n" }, { "answer_id": 68002660, "author": "Ali Muhammad Khowaja", "author_id": 15663611, "author_profile": "https://Stackoverflow.com/users/15663611", "pm_score": 3, "selected": false, "text": "import matplotlib.pyplot as plt\nfrom matplotlib.pyplot import figure\n\nfigure(figsize=(16, 8), dpi=80)\nplt.plot(x_test, color = 'red', label = 'Predicted Price')\nplt.plot(y_test, color = 'blue', label = 'Actual Price')\nplt.title('Dollar to PKR Prediction')\nplt.xlabel('Predicted Price')\nplt.ylabel('Actual Dollar Price')\nplt.legend()\nplt.show()\n" }, { "answer_id": 69768472, "author": "nizarhamood", "author_id": 12349230, "author_profile": "https://Stackoverflow.com/users/12349230", "pm_score": 2, "selected": false, "text": "import matplotlib.pyplot as plt\n\ndata = [2,5,8,10,15] # Random data, can use existing data frame column\n\nfig, axs = plt.subplots(figsize = (20,6)) # This is your answer to resize the figure\n\n# The below will help you expand on your question and resize individual elements within your figure. Experiement with the below parameters.\naxs.set_title(\"Data\", fontsize = 17.5)\naxs.tick_params(axis = 'x', labelsize = 14)\naxs.set_xlabel('X Label Here', size = 15)\naxs.tick_params(axis = 'y', labelsize =14)\naxs.set_ylabel('Y Label Here', size = 15)\n\nplt.plot(data)\n" }, { "answer_id": 71933465, "author": "Derrick Kuria", "author_id": 13186690, "author_profile": "https://Stackoverflow.com/users/13186690", "pm_score": 3, "selected": false, "text": "import matplotlib as mpl\nimport matplotlib.pyplot as plt\nmpl.rcParams['figure.figsize'] = (8, 6)\nmpl.rcParams['axes.grid'] = False\n" }, { "answer_id": 74303614, "author": "pplonski", "author_id": 5605919, "author_profile": "https://Stackoverflow.com/users/5605919", "pm_score": 1, "selected": false, "text": "dpi dpi figsize dpi from matplotlib import pyplot as plt\n\nplt.figure(figsize=(3, 3), dpi=144)\n_ = plt.plot([3, 4, 2, 5])\n set_figwidth set_figheight set_size_inches set_dpi # create figure\nf = plt.figure()\n\n# set width, height, dpi\nf.set_figwidth(4)\nf.set_figheight(2)\nf.set_dpi(142)\n\n# plot\n_ = plt.plot([3,4,2,5])\n dpi dpi # set figsize and dpi for all figures\nplt.rcParams[\"figure.figsize\"] = (4,2)\nplt.rcParams[\"figure.dpi\"] = 144\n rcParams" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/332291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5291/" ]
332,295
<p>I am working on a simple CAD program which uses OpenGL to handle on-screen rendering. Every shape drawn on the screen is constructed entirely out of simple line segments, so even a simple drawing ends up processing thousands of individual lines.</p> <p>What is the best way to communicate changes in this collection of lines between my application and OpenGL? Is there a way to update only a certain subset of the lines in the OpenGL buffers?</p> <p>I'm looking for a conceptual answer here. No need to get into the actual source code, just some recommendations on data structure and communication.</p>
[ { "answer_id": 332439, "author": "Branan", "author_id": 13894, "author_profile": "https://Stackoverflow.com/users/13894", "pm_score": 3, "selected": false, "text": "glBufferSubData()" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/332295", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33686/" ]
332,297
<p>I want have to have a single imageList used by multiple forms in a project. That is to say, multiple controls use the same image list.</p> <p><em>Note: Ideally multiple projects in a single solution will use the same image list - but I don't want to ask too much of Microsoft at once.</em></p> <p>Some controls are listview, some are treeviews, some are custom controls, some are controls that do custom paint cycles.</p> <p>How can I point multiple ListViews and TreeViews to the same image list component?</p> <p>Some of the issues involved are:</p> <ul> <li>Where do I put the image list component? It has to sit on some sort of form</li> <li>How do I convince the IDE to show imagelist controls in the "SmallImageList" that are on different forms as the listview?</li> <li>If I instead construct the imagelist at runtime, how do I design the images that appear in the image list?</li> </ul> <p><strong>Note:</strong> This was easy in Delphi. You'd drop an ImageList component as you normally do, and it just appeared in the list of available image lists under the "SmallImageList" property in the Properties window.</p> <p><strong>Note:</strong> It's okay to say that it can't be done in Visual Studio. If the answer is that it cannot be done then that will be the accepted answer.</p>
[ { "answer_id": 3771603, "author": "Ivan Ferrer Villa", "author_id": 382515, "author_profile": "https://Stackoverflow.com/users/382515", "pm_score": 0, "selected": false, "text": " Shared shoImageList As New ImageList\n Public Sub New()\n If shoImageList.Images.Count = 0 Then\n shoImageList = ImageList1 \n 'or may be a For Each loop here'\n End If\n myTreeView.ImageList = shoImageList\n ImageList1 = Nothing\n End Sub\n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/332297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12597/" ]
332,300
<p>Is there a measurable performance difference between using INT vs. VARCHAR as a primary key in MySQL? I'd like to use VARCHAR as the primary key for reference lists (think US States, Country Codes) and a coworker won't budge on the INT AUTO_INCREMENT as a primary key for all tables. </p> <p>My argument, as detailed <a href="http://database-programmer.blogspot.com/2008/01/database-skills-sane-approach-to.html#rule1" rel="noreferrer">here</a>, is that the performance difference between INT and VARCHAR is negligible, since every INT foreign key reference will require a JOIN to make sense of the reference, a VARCHAR key will directly present the information.</p> <p>So, does anyone have experience with this particular use-case and the performance concerns associated with it?</p>
[ { "answer_id": 332346, "author": "LeppyR64", "author_id": 16592, "author_profile": "https://Stackoverflow.com/users/16592", "pm_score": 3, "selected": false, "text": "ex.\nid value\n1 A\n2 B\n3 C\n\nUpdate 3 to D\nid value\n1 A\n2 B\n3 D\n\nUpdate 2 to C\nid value\n1 A\n2 C\n3 D\n\nUpdate 3 to B\nid value\n1 A\n2 C\n3 B\n" }, { "answer_id": 23914746, "author": "Diego Duarte", "author_id": 1286522, "author_profile": "https://Stackoverflow.com/users/1286522", "pm_score": 2, "selected": false, "text": "+----------+ +---------+\n| Accident |>--------<| Vehicle |\n+-----v----+ 1 * +----v----+\n 1| |1\n | +----------+ |\n +---<| Casualty |>---+\n * +----------+ *\n" }, { "answer_id": 34169436, "author": "Rick James", "author_id": 1766831, "author_profile": "https://Stackoverflow.com/users/1766831", "pm_score": 2, "selected": false, "text": "AUTO_INCREMENT CREATE TABLE map (\n id ... AUTO_INCREMENT,\n foo_id ...,\n bar_id ...,\n PRIMARY KEY(id),\n UNIQUE(foo_id, bar_id),\n INDEX(bar_id) );\n CREATE TABLE map (\n # No surrogate\n foo_id ...,\n bar_id ...,\n PRIMARY KEY(foo_id, bar_id),\n INDEX (bar_id, foo_id) );\n id country_id INT ...\n-- versus\ncountry_code CHAR(2) CHARACTER SET ascii\n INT" }, { "answer_id": 48583244, "author": "Jan Żankowski", "author_id": 128734, "author_profile": "https://Stackoverflow.com/users/128734", "pm_score": 7, "selected": false, "text": "create table jan_int (data1 varchar(255), data2 int(10), myindex tinyint(4)) ENGINE=InnoDB;\ncreate table jan_int_index (data1 varchar(255), data2 int(10), myindex tinyint(4), INDEX (myindex)) ENGINE=InnoDB;\ncreate table jan_char (data1 varchar(255), data2 int(10), myindex char(6)) ENGINE=InnoDB;\ncreate table jan_char_index (data1 varchar(255), data2 int(10), myindex char(6), INDEX (myindex)) ENGINE=InnoDB;\ncreate table jan_varchar (data1 varchar(255), data2 int(10), myindex varchar(63)) ENGINE=InnoDB;\ncreate table jan_varchar_index (data1 varchar(255), data2 int(10), myindex varchar(63), INDEX (myindex)) ENGINE=InnoDB;\n $pdo = get_pdo();\n\n$keys = [ 'alabam', 'massac', 'newyor', 'newham', 'delawa', 'califo', 'nevada', 'texas_', 'florid', 'ohio__' ];\n\nfor ($k = 0; $k < 10; $k++) {\n for ($j = 0; $j < 1000; $j++) {\n $val = '';\n for ($i = 0; $i < 1000; $i++) {\n $val .= '(\"' . generate_random_string() . '\", ' . rand (0, 10000) . ', \"' . ($keys[rand(0, 9)]) . '\"),';\n }\n $val = rtrim($val, ',');\n $pdo->query('INSERT INTO jan_char VALUES ' . $val);\n }\n echo \"\\n\" . ($k + 1) . ' millon(s) rows inserted.';\n}\n int ($keys[rand(0, 9)]) rand(0, 9) varchar generate_random_string() SET SESSION query_cache_type=0; jan_int SELECT count(*) FROM jan_int WHERE myindex = 5; SELECT BENCHMARK(1000000000, (SELECT count(*) FROM jan_int WHERE myindex = 5)); myindex = 'califo' char myindex = 'california' varchar BENCHMARK show table status from janperformancetest; |-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| Name | Engine | Version | Row_format | Rows | Avg_row_length | Data_length | Max_data_length | Index_length | Data_free | Auto_increment | Collation |\n|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| jan_int | InnoDB | 10 | Dynamic | 9739094 | 43 | 422510592 | 0 | 0 | 4194304 | NULL | utf8mb4_unicode_520_ci | \n| jan_int_index | InnoDB | 10 | Dynamic | 9740329 | 43 | 420413440 | 0 | 132857856 | 7340032 | NULL | utf8mb4_unicode_520_ci | \n| jan_char | InnoDB | 10 | Dynamic | 9726613 | 51 | 500170752 | 0 | 0 | 5242880 | NULL | utf8mb4_unicode_520_ci | \n| jan_char_index | InnoDB | 10 | Dynamic | 9719059 | 52 | 513802240 | 0 | 202342400 | 5242880 | NULL | utf8mb4_unicode_520_ci | \n| jan_varchar | InnoDB | 10 | Dynamic | 9722049 | 53 | 521142272 | 0 | 0 | 7340032 | NULL | utf8mb4_unicode_520_ci | \n| jan_varchar_index | InnoDB | 10 | Dynamic | 9738381 | 49 | 486539264 | 0 | 202375168 | 7340032 | NULL | utf8mb4_unicode_520_ci | \n|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/332300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/302/" ]
332,309
<p>I've developed an application at working using MySQL 5, that uses Views to access the major pieces of data. It turns out that our production server uses MySQL 4, which does not have Views included.</p> <p>Does anybody have a quick and dirty way to deal with this that doesn't involve rewriting all my code? </p>
[ { "answer_id": 332366, "author": "derobert", "author_id": 27727, "author_profile": "https://Stackoverflow.com/users/27727", "pm_score": 2, "selected": false, "text": "CREATE VIEW foo AS\n SELECT a, b, c FROM real_table WHERE fooable = 1;\n\nSELECT * FROM foo;\n SELECT v1.* FROM (\n SELECT a, b, c FROM real_table WHERE fooable = 1\n) v1;\n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/332309", "https://Stackoverflow.com", "https://Stackoverflow.com/users/655/" ]
332,353
<p>This is making me kind of crazy: I did a mysqldump of a partitioned table on one server, moved the resulting SQL dump to another server, and attempted to run the insert. It fails, but I'm having difficulty figuring out why. Google and the MySQL forums and docs have not been much help.</p> <p>The failing query looks like this (truncated for brevity and clarity, names changed to protect the innocent):</p> <pre><code>CREATE TABLE `my_precious_table` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `somedata` varchar(20) NOT NULL, `aTimeStamp` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`id`,`aTimeStamp`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 DATA DIRECTORY='/opt/data/data2/data_foo/' INDEX DIRECTORY='/opt/data/data2/idx_foo/' /*!50100 PARTITION BY RANGE (year(aTimeStamp)) SUBPARTITION BY HASH ( TO_DAYS(aTimeStamp)) (PARTITION p0 VALUES LESS THAN (2007) (SUBPARTITION foo0 DATA DIRECTORY = '/opt/data/data2/data_foo' INDEX DIRECTORY = '/opt/data/data2/idx_foo' ENGINE = MyISAM), PARTITION p1 VALUES LESS THAN (2008) (SUBPARTITION foo1 DATA DIRECTORY = '/opt/data/data2/data_foo' INDEX DIRECTORY = '/opt/data/data2/idx_foo' ENGINE = MyISAM), PARTITION p2 VALUES LESS THAN (2009) (SUBPARTITION foo2 DATA DIRECTORY = '/opt/data/data2/data_foo' INDEX DIRECTORY = '/opt/data/data2/idx_foo' ENGINE = MyISAM), PARTITION p3 VALUES LESS THAN MAXVALUE (SUBPARTITION foo3 DATA DIRECTORY = '/opt/data/data2/data_foo' INDEX DIRECTORY = '/opt/data/data2/idx_foo' ENGINE = MyISAM)) */; </code></pre> <p>The error is:</p> <blockquote> <p>ERROR 1 (HY000): Can't create/write to file '/opt/data/data2/idx_foo/my_precious_table#P#p0#SP#foo0.MYI' (Errcode: 13)</p> </blockquote> <p>"Can't create/write to file" looked like a permissions issue to me, but permissions on the targeted folders look thus:</p> <pre><code>drwxrwxrwx 2 mysql mysql 4096 Dec 1 16:24 data_foo drwxrwxrwx 2 mysql mysql 4096 Dec 1 16:25 idx_foo </code></pre> <p>For kicks, I've tried chowning to root:root and myself. This did not fix the issue.</p> <p>Source MySQL server is version 5.1.22-rc-log. Destination server is 5.1.29-rc-community. Both are running on recent CentOS installations.</p> <p><strong>Edit:</strong> A little more research shows that Errcode 13 is, in fact, a permissions error. But how can I get that on <code>rwxrwxrwx</code>?</p> <p><strong>Edit:</strong> Bill Karwin's excellent suggestion didn't pan out. I'm working as the root user, and have all privilege flags set.</p> <p><strong>Edit:</strong> Creating the table WITHOUT specifying data directories for the individual partitions works - but I need to put these partitions on a larger disk than the one on which this MySQL instance puts tables by default. And I can't just specify the DATA/INDEX DIRECTORY at the table level - that's not legit in the version of MySQL I'm using (5.1.29-rc-community).</p> <p><strong>Edit:</strong> Finally came across the answer, thanks to the MySQL mailing list and internal IT staff. See below.</p>
[ { "answer_id": 1314642, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "vi /etc/apparmor.d/usr.sbin.mysql\n /etc/init.d/apparmor stop\n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/332353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40093/" ]
332,364
<p>Is it possible to embed the Windows Explorer file/folder browser view in a WPF or a WinForms window?</p> <p>I basically want to host the file/folder browser as part of my app window. I don't want to re-implement what the shell provides, especially the shell extensions such as TortoiseSVN.</p>
[ { "answer_id": 335490, "author": "Enrico Campidoglio", "author_id": 26396, "author_profile": "https://Stackoverflow.com/users/26396", "pm_score": 3, "selected": false, "text": "<Window x:Class=\"Samples.FilesystemBrowser\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:wf=\"clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms\"\n Title=\"Filesystem Browser\">\n <StackPanel>\n <WindowsFormsHost>\n <wf:WebBrowser Url=\"C:\\\" />\n </WindowsFormsHost>\n </StackPanel>\n</Window>\n <Window x:Class=\"Samples.FilesystemBrowser\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n Title=\"Filesystem Browser\">\n <StackPanel>\n <WebBrowser Source=\"C:\\\" />\n </StackPanel>\n</Window>\n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/332364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
332,365
<p>Just looking at:</p> <p><img src="https://i.stack.imgur.com/G0ifh.png" alt="XKCD Strip" title="Her daughter is named Help I&#39;m trapped in a driver&#39;s license factory."> <em>(Source: <a href="https://xkcd.com/327/" rel="noreferrer">https://xkcd.com/327/</a>)</em></p> <p>What does this SQL do:</p> <pre><code>Robert'); DROP TABLE STUDENTS; -- </code></pre> <p>I know both <code>'</code> and <code>--</code> are for comments, but doesn't the word <code>DROP</code> get commented as well since it is part of the same line?</p>
[ { "answer_id": 332367, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 11, "selected": true, "text": "q = \"INSERT INTO Students VALUES ('\" + FNMName.Text + \"', '\" + LName.Text + \"')\";\n Robert'); DROP TABLE STUDENTS; -- Derper INSERT INTO Students VALUES ('Robert'); DROP TABLE Students; --', 'Derper')\n --', 'Derper') '" }, { "answer_id": 332373, "author": "Jorn", "author_id": 8681, "author_profile": "https://Stackoverflow.com/users/8681", "pm_score": 4, "selected": false, "text": "');" }, { "answer_id": 332375, "author": "Rockcoder", "author_id": 5290, "author_profile": "https://Stackoverflow.com/users/5290", "pm_score": 4, "selected": false, "text": "'" }, { "answer_id": 332379, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 4, "selected": false, "text": "sql = \"SELECT * FROM STUDENTS WHERE (STUDENT_NAME = '\" + student_name + \"') AND other stuff\";\nexecute(sql);\n" }, { "answer_id": 332380, "author": "sinoth", "author_id": 42224, "author_profile": "https://Stackoverflow.com/users/42224", "pm_score": 9, "selected": false, "text": "$Name INSERT INTO Students VALUES ( '$Name' )\n INSERT INTO Students VALUES ( 'Robert' ); DROP TABLE STUDENTS; --' )\n --" }, { "answer_id": 332385, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 4, "selected": false, "text": "' $sql = \"INSERT INTO `Students` (FirstName, LastName) VALUES ('\" . $fname . \"', '\" . $lname . \"')\";\n ' ; --" }, { "answer_id": 332387, "author": "Dan Vinton", "author_id": 21849, "author_profile": "https://Stackoverflow.com/users/21849", "pm_score": 5, "selected": false, "text": "void createStudent(String name) {\n database.execute(\"INSERT INTO students (name) VALUES ('\" + name + \"')\");\n}\n Robert'); DROP TABLE STUDENTS; -- INSERT INTO students (name) VALUES ('Robert'); DROP TABLE STUDENTS --')\n" }, { "answer_id": 332401, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 6, "selected": false, "text": "' INSERT INTO 'students' ('first_name', 'last_name') VALUES ('$firstName', '$lastName');\n $xxx $firstName Robert'); DROP TABLE students; -- INSERT INTO 'students' ('first_name', 'last_name') VALUES ('Robert'); DROP TABLE students; --', 'XKCD');\n" }, { "answer_id": 332408, "author": "CodeAndCats", "author_id": 26335, "author_profile": "https://Stackoverflow.com/users/26335", "pm_score": 5, "selected": false, "text": "Select *\nFrom Students\nWhere (Name = '<NameGetsInsertedHere>')\n Select *\nFrom Students\nWhere (Name = 'Robert'); DROP TABLE STUDENTS; --')\n-- ^-------------------------------^\n select drop" }, { "answer_id": 7414582, "author": "Johannes Fahrenkrug", "author_id": 171933, "author_profile": "https://Stackoverflow.com/users/171933", "pm_score": 7, "selected": false, "text": "'); mysqli_multi_query $query=\"SELECT * FROM users WHERE username='\" . $_REQUEST['user'] . \"' and (password='\".$_REQUEST['pass'].\"')\";\n$result=mysql_query($query);\n peter secret SELECT * FROM users WHERE username='peter' and (password='secret')\n ' OR '1'='1\n SELECT * FROM users WHERE username='peter' and (password='' OR '1'='1')\n" }, { "answer_id": 7560848, "author": "bwDraco", "author_id": 681231, "author_profile": "https://Stackoverflow.com/users/681231", "pm_score": 5, "selected": false, "text": "foobar DROP TABLE INSERT mysql_real_escape_string" }, { "answer_id": 20325769, "author": "Noname", "author_id": 2427249, "author_profile": "https://Stackoverflow.com/users/2427249", "pm_score": 3, "selected": false, "text": "Robert'); DROP TABLE STUDENTS; --\n String query=\"Select * from student where username='\"+student_name+\"'\";\n\nstatement.executeQuery(query); //Rest of the code follows\n Select * from student where username='Robert'); DROP TABLE STUDENTS; --\n Select * from student where username='Robert'); \n\nDROP TABLE STUDENTS; --\n" }, { "answer_id": 57280641, "author": "DevWL", "author_id": 2179965, "author_profile": "https://Stackoverflow.com/users/2179965", "pm_score": 3, "selected": false, "text": "<a href=\"/show?id=1\">show something</a>\n http://yoursite.com/show?id=1;TRUNCATE table_name\n \"SELECT * FROM page WHERE id = 4;TRUNCATE page\"\n <?php\n...\n$id = $_GET['id'];\n\n$pdo = new PDO($database_dsn, $database_user, $database_pass);\n$query = \"SELECT * FROM page WHERE id = {$id}\";\n$stmt = $pdo->query($query);\n$data = $stmt->fetch(); \n/************* You have lost your data!!! :( *************/\n...\n <?php\n...\n$id = $_GET['id'];\n\n$query = 'SELECT * FROM page WHERE id = :idVal';\n$stmt = $pdo->prepare($query);\n$stmt->bindParam('idVal', $id, PDO::PARAM_INT);\n$stmt->execute();\n$data = $stmt->fetch();\n/************* Your data is safe! :) *************/\n...\n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/332365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39677/" ]
332,370
<p>In C#, the questions of what types to create, what members they should have, and what namespaces should hold them, are questions of OO design. They are not the questions I'm interested in here.</p> <p>Instead, I want to ask how you store these in disk artifacts. Here are some example rules:</p> <ul> <li><p>Put all of an assembly's types in a single source file. One friend who did this said "files are an archiac code organization tool; today I use classview and Collapse to Definitions to browse my code".</p></li> <li><p>Put all your code in one assembly. Makes deployment &amp; versioning simpler.</p></li> <li><p>Directory structure reflects namespace structure. </p></li> <li><p>Each namespace gets its own assembly.</p></li> <li><p>Each type goes in its own assembly. (Listed as an extreme example.)</p></li> <li><p>Each type gets its own source file. </p></li> <li><p>Each member gets its own file; each type gets its own directory. (Listed as an extreme example.)</p></li> </ul>
[ { "answer_id": 332372, "author": "Jay Bazuzi", "author_id": 5314, "author_profile": "https://Stackoverflow.com/users/5314", "pm_score": 3, "selected": false, "text": "partial // ------ C.cs\n\npublic partial class C : IFoo\n{\n // ...\n}\n\n// ------ C.Nested.cs\npartial class C\n{\n public class Nested\n {\n // ...\n }\n}\n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/332370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5314/" ]
332,384
<p>I'm working on a page using jQuery's <a href="http://docs.jquery.com/UI/Accordion" rel="nofollow noreferrer">accordion UI element</a>. I modeled my HTML on that example, except that inside the <code>&lt;li&gt;</code> elements, I have some unordered lists of links. Like this:</p> <pre><code> $(document).ready(function() { $(&quot;.ui-accordion-container&quot;).accordion( {active: &quot;a.default&quot;, alwaysOpen: true, autoHeight: false} ); }); &lt;ul class=&quot;ui-accordion-container&quot;&gt; &lt;li&gt; &lt;!-- Start accordion section --&gt; &lt;a href='#' class=&quot;accordion-label&quot;&gt;A Group of Links&lt;/a&gt; &lt;ul class=&quot;linklist&quot;&gt; &lt;li&gt;&lt;a href=&quot;http://example.com&quot;&gt;Example Link&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;http://example.com&quot;&gt;Example Link&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;!--and of course there's another group --&gt; </code></pre> <h2>Problem: Links don't work</h2> <p>In all browsers I've tested, the links in those accordion menus cause <strong>the accordion section to collapse</strong> instead of taking you to the linked page. (I can still right-click and go to the linked site.)</p> <p>Could this be some kind of click binding issue?</p>
[ { "answer_id": 332502, "author": "Pim Jager", "author_id": 35197, "author_profile": "https://Stackoverflow.com/users/35197", "pm_score": -1, "selected": false, "text": " navigation: true\n" }, { "answer_id": 332533, "author": "Matthew Crumley", "author_id": 2214, "author_profile": "https://Stackoverflow.com/users/2214", "pm_score": 4, "selected": true, "text": "headers $(\".ui-accordion-container\").accordion(\n { active: \"a.default\", ..., header: \"a.accordion-label\" }\n);\n" }, { "answer_id": 1195529, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": " $('.stats a').click(function(){\nexpander.accordion('disable');\nwindow.open($(this).attr('href'));\n\nsetTimeout ( function() {\n expander.accordion('enable');\n}, 250 );\n" }, { "answer_id": 1195645, "author": "egyamado", "author_id": 66493, "author_profile": "https://Stackoverflow.com/users/66493", "pm_score": 0, "selected": false, "text": "<body id=\"body\">\n <h2>Accordian</h2>\n <div id=\"accordion\" class=\"\">\n\n <div class=\"toggle_all\">\n <ul class=\"links\">\n <li><a class=\"openall\" href=\"#\"><span>Open All</span></a></li>\n <li>|</li>\n <li><a class=\"closeall\" href=\"#\"><span>Close All</span></a></li>\n </ul>\n </div>\n\n <!-- toggleAll ends -->\n <div class=\"accordion\">\n <div class=\"section_title_accordion design-gray\">\n <h3><a href=\"#\" class=\"open\"><span>Lorem ipsum</span></a></h3>\n </div>\n <!-- section_title_accordion ends -->\n <div class=\"accordion_content\"> <span class=\"content\">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</span> </div>\n\n <!-- accordion_content ends -->\n </div>\n <!-- accordion ends -->\n <div class=\"accordion\">\n <div class=\"section_title_accordion design-gray\">\n <h3><a href=\"#\" class=\"open\"><span>Lorem ipsum</span></a></h3>\n </div>\n <!-- section_title_accordion ends -->\n\n <div class=\"accordion_content\"> <span class=\"content\">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</span> </div>\n <!-- accordion_content ends -->\n </div>\n <!-- accordion ends -->\n <div class=\"accordion\">\n <div class=\"section_title_accordion design-gray\">\n <h3><a href=\"#\" class=\"open\"><span>Lorem ipsum</span></a></h3>\n\n </div>\n <!-- section_title_accordion ends -->\n <div class=\"accordion_content\"> <span class=\"content\">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</span> </div>\n <!-- accordion_content ends -->\n </div>\n <!-- accordion ends -->\n </div>\n\n <!-- #accordion ends -->\n</body>\n <style type=\"text/css\" >\n#body { margin-left:20%; font:12px verdana; }\n.accordion { width:500px; }\nh3 { margin:0; padding:0; }\n.section_title_accordion { float:left; width:500px; margin:2px 0 0; }\n.section_title_accordion h3 span { margin:0; float:left; color:#fff; padding:2px 0 3px 10px; }\n.section_title_accordion a span { padding-left:20px; }\n.accordion_content { border-bottom:1px solid #666666; border-left:1px solid #666666; border-right:1px solid #666666; float:left; padding:5px 3px; }\n.accordion_content span.content { margin:5px 0 0; }\n.design-gray { background:#003366; }\n.design-gray a { color:#fff; float:left; width:100%; height:22px; background:#003366; text-decoration:none; }\n.design-gray a:hover { text-decoration:underline;}\n.on .design-gray a { color:#fff; float:left; width:100%; height:22px; background:#003366;}\n.accordion_content_hover { background:#ffffcc; color:#000099; }\n.toggle_all { padding:20px 0; width:500px; margin-bottom:5px; }\n.toggle_all ul { padding:0; margin:0; }\n.toggle_all ul li { list-style-type:none; }\n.toggle_all .links li { float:left; padding-left:5px; }\n.toggle_all .links li a, .toggleAll .links span { color:#666666; }\n</style>\n <script language=\"javascript\" type=\"text/javascript\">\n\n$(document).ready(function() {\n $(\".accordion_content\").hide();\n $(\"a.open\").click(function() {\n $(this).parents(\".accordion\").find(\".accordion_content\").toggle();\n $(this).parents(\".accordion\").toggleClass('on'); \n return false;\n }); \n\n $(\".accordion_content\").mouseover(function() {\n $(this).addClass('accordion_content_hover');\n return false; \n });\n\n $(\".accordion_content\").mouseout(function() {\n $(this).removeClass('accordion_content_hover');\n return false; \n });\n\n $(\"a.openall\").click(function() {\n $(\".accordion_content\").show();\n $(this).parents(\"#accordion\").find(\".accordion\").addClass('on');\n return false;\n });\n $(\"a.closeall\").click(function() {\n $(\".accordion_content\").hide();\n $(this).parents(\"#accordion\").find(\".accordion\").removeClass('on');\n return false;\n });\n});\n</script>\n" }, { "answer_id": 17682174, "author": "Daniel Sokolowski", "author_id": 913223, "author_profile": "https://Stackoverflow.com/users/913223", "pm_score": 3, "selected": false, "text": "...\n<a href='#' onclick=\"event.stopPropagation()\" class=\"accordion-label\">A Group of Links</a>\n...\n $(\".toggle-title a\").click(function(event){ event.stopPropagation()})\n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/332384", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4376/" ]
332,390
<p>I'd like to serialize some LINQ generated objects and store them in a table as a binary field (Never you mind why). I'd like to be able to write some code that looks something like this:</p> <pre><code>SerialTestDataContext db = new SerialTestDataContext(); relation_table row = db.relation_tables.First(); MemoryStream memStream = new MemoryStream(); BinaryFormatter bin = new BinaryFormatter(); bin.Serialize(memStream, row); Console.WriteLine("Serilized successfully"); TestTable tt = new testTable(); tt.data = new System.Data.Linq.Binary(memStream.ToArray()); db.testTables.InsertOnSubmit(tt); db.SubmitChanges(); Console.WriteLine("Inserted successfully"); </code></pre> <p>Currently that fails even though I've marked the generated classes as [Serializable] because one of the LINQ inherited classes is not. Is it even possible to do this?</p>
[ { "answer_id": 332421, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "public partial class User : ISerializable\n{\n // implement GetObjectData here\n}\n" }, { "answer_id": 332471, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 5, "selected": true, "text": "<Database ... Serialization=\"Unidirectional\">...\n" }, { "answer_id": 334331, "author": "Mykroft", "author_id": 2191, "author_profile": "https://Stackoverflow.com/users/2191", "pm_score": 3, "selected": false, "text": "relation_table row = db.relation_tables.First();\n\nMemoryStream memStream = new MemoryStream();\nNetDataContractSerializer ndcs = new NetDataContractSerializer();\nndcs.Serialize(memStream, row);\n\nbyte[] stuff = memStream.toArray();\n\nmemStream = new MemoryStream(stuff);\nrow = ndcs.Deserialize(memStream);\n\ndb.relation_tables.Attach(row);\nConsole.WriteLine(row.data_table1.somedata + \": \" + row.more_data);\n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/332390", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2191/" ]
332,397
<p>My function is pretty much a standard search function... I've included it below.</p> <p>In the function I have 1 line of code responsible for weeding out Repart NTFS points. </p> <pre><code>if (attributes.ToString().IndexOf("ReparsePoint") == -1) </code></pre> <p>The problem is now I am getting an error <code>Access to the path 'c:\System Volume Information' is denied.</code></p> <p>I debugged the code and the only attributes at run time for this directory are : </p> <pre><code> System.IO.FileAttributes.Hidden | System.IO.FileAttributes.System | System.IO.FileAttributes.Directory </code></pre> <p>I'm executing this code on a windows 2008 server machine, any ideas what I can do to cure this failing?</p> <pre><code>public void DirSearch(string sDir) { foreach (string d in Directory.GetDirectories(sDir)) { DirectoryInfo dInfo = new DirectoryInfo(d); FileAttributes attributes = dInfo.Attributes; if (attributes.ToString().IndexOf("ReparsePoint") == -1) { foreach (string f in Directory.GetFiles(d, searchString)) { //lstFilesFound.Items.Add(f); ListViewItem lvi; ListViewItem.ListViewSubItem lvsi; lvi = new ListViewItem(); lvi.Text = f; lvi.ImageIndex = 1; lvi.Tag = "tag"; lvsi = new ListViewItem.ListViewSubItem(); lvsi.Text = "sub bugger"; lvi.SubItems.Add(lvsi); lvsi = new ListViewItem.ListViewSubItem(); lvsi.Text = d;//"C:\\Users\\Administrator\\Downloads\\MediaMonkey.GOLD.EDITION.v.3.0.2.1134.[Darkside].[Demonoid].[Grim.Reaper]"; lvi.SubItems.Add(lvsi); listView1.Items.Add(lvi); } DirSearch(d); } } } </code></pre>
[ { "answer_id": 332412, "author": "Greg Beech", "author_id": 13552, "author_profile": "https://Stackoverflow.com/users/13552", "pm_score": 4, "selected": false, "text": "if (attributes.ToString().IndexOf(\"ReparsePoint\") == -1)\n if ((attributes & FileAttributes.ReparsePoint) == 0)\n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/332397", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41291/" ]
332,422
<p>Is there a <strong>JavaScript</strong> equivalent of <strong>Java</strong>'s <code>class.getName()</code>?</p>
[ { "answer_id": 332429, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 12, "selected": true, "text": "class.getName() class Foo {} Foo.name thing thing thing.constructor.name name (2).constructor.name \"Number\" Object.prototype.getName = function() { \n var funcNameRegex = /function (.{1,})\\(/;\n var results = (funcNameRegex).exec((this).constructor.toString());\n return (results && results.length > 1) ? results[1] : \"\";\n};\n getName() FF3 IE7 constructor object constructor object constructor var myArray = [1,2,3];\n(myArray.constructor == Array); // true\n function Thingy() {\n}\nThingy.prototype = {\n method1: function() {\n },\n method2: function() {\n }\n};\n Objects new Thingy constructor Object Thingy constructor function a() { this.foo = 1;}\nfunction b() { this.bar = 2; }\nb.prototype = new a(); // b inherits from a\n var f = new b(); // instantiate a new object with the b constructor\n(f.constructor == b); // false\n(f.constructor == a); // true\n object object prototype constructor .constructor window constructor iframe.contentWindow.Array === Array // false\n instanceof instanceof object constructor var myArray = [1,2,3];\n(myArray instanceof Array); // true\n(myArray instanceof Object); // true\n instanceof Objects 3 instanceof Number // false\n'abc' instanceof String // false\ntrue instanceof Boolean // false\n Object instanceof new Number(3) instanceof Number // true\n .constructor . 3..constructor === Number // true\n'abc'.constructor === String // true\ntrue.constructor === Boolean // true\n instanceof constructor name constructor constructor myObjectInstance.constructor.name constructor constructor if (Function.prototype.name === undefined && Object.defineProperty !== undefined) {\n Object.defineProperty(Function.prototype, 'name', {\n get: function() {\n var funcNameRegex = /function\\s+([^\\s(]+)\\s*\\(/;\n var results = (funcNameRegex).exec((this).toString());\n return (results && results.length > 1) ? results[1] : \"\";\n },\n set: function(value) {}\n });\n}\n if (Function.prototype.name === undefined && Object.defineProperty !== undefined) {\n Object.defineProperty(Function.prototype, 'name', {\n get: function() {\n var funcNameRegex = /function\\s([^(]{1,})\\(/;\n var results = (funcNameRegex).exec((this).toString());\n return (results && results.length > 1) ? results[1].trim() : \"\";\n },\n set: function(value) {}\n });\n}\n Object.prototype.toString toString Object.prototype.toString.call('abc') // [object String]\nObject.prototype.toString.call(/abc/) // [object RegExp]\nObject.prototype.toString.call([1,2,3]) // [object Array]\n function type(obj){\n return Object.prototype.toString.call(obj).slice(8, -1);\n}\n type('abc') // String\n Object // using a named function:\nfunction Foo() { this.a = 1; }\nvar obj = new Foo();\n(obj instanceof Object); // true\n(obj instanceof Foo); // true\n(obj.constructor == Foo); // true\n(obj.constructor.name == \"Foo\"); // true\n\n// let's add some prototypical inheritance\nfunction Bar() { this.b = 2; }\nFoo.prototype = new Bar();\nobj = new Foo();\n(obj instanceof Object); // true\n(obj instanceof Foo); // true\n(obj.constructor == Foo); // false\n(obj.constructor.name == \"Foo\"); // false\n\n\n// using an anonymous function:\nobj = new (function() { this.a = 1; })();\n(obj instanceof Object); // true\n(obj.constructor == obj.constructor); // true\n(obj.constructor.name == \"\"); // true\n\n\n// using an anonymous function assigned to a variable\nvar Foo = function() { this.a = 1; };\nobj = new Foo();\n(obj instanceof Object); // true\n(obj instanceof Foo); // true\n(obj.constructor == Foo); // true\n(obj.constructor.name == \"\"); // true\n\n\n// using object literal syntax\nobj = { foo : 1 };\n(obj instanceof Object); // true\n(obj.constructor == Object); // true\n(obj.constructor.name == \"Object\"); // true\n typeof object typeof" }, { "answer_id": 332434, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 3, "selected": false, "text": "instanceof" }, { "answer_id": 332445, "author": "Ewen Cartwright", "author_id": 41595, "author_profile": "https://Stackoverflow.com/users/41595", "pm_score": 7, "selected": false, "text": "<<Object instance>>.constructor.name\n function MyObject() {}\nvar myInstance = new MyObject();\n myInstance.constructor.name \"MyObject\"" }, { "answer_id": 332447, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 2, "selected": false, "text": "typeof constructor" }, { "answer_id": 335025, "author": "farzad", "author_id": 9394, "author_profile": "https://Stackoverflow.com/users/9394", "pm_score": 2, "selected": false, "text": "function Circle (x,y,radius) {\n this._x = x;\n this._y = y;\n this._radius = raduius;\n}\nvar c1 = new Circle(10,20,5);\n Circle() typeof typeof toString() toString() Object.prototype.toString.apply(myObject);\n" }, { "answer_id": 6379334, "author": "Daniel Szabo", "author_id": 183624, "author_profile": "https://Stackoverflow.com/users/183624", "pm_score": 5, "selected": false, "text": "function Square(){\n this.className = \"Square\";\n this.corners = 4;\n}\n\nvar MySquare = new Square();\nconsole.log(MySquare.className); // \"Square\"\n" }, { "answer_id": 7045453, "author": "defrex", "author_id": 6007, "author_profile": "https://Stackoverflow.com/users/6007", "pm_score": 3, "selected": false, "text": "constructor.name Function.prototype.getName = function(){\n if (typeof this.name != 'undefined')\n return this.name;\n else\n return /function (.+)\\(/.exec(this.toString())[1];\n};\n" }, { "answer_id": 7222025, "author": "Saul", "author_id": 426379, "author_profile": "https://Stackoverflow.com/users/426379", "pm_score": 4, "selected": false, "text": "object Object.prototype.getConstructorName = function () {\n var str = (this.prototype ? this.prototype.constructor : this.constructor).toString();\n var cname = str.match(/function\\s(\\w*)/)[1];\n var aliases = [\"\", \"anonymous\", \"Anonymous\"];\n return aliases.indexOf(cname) > -1 ? \"Function\" : cname;\n}\n\nnew Array().getConstructorName(); // returns \"Array\"\n(function () {})().getConstructorName(); // returns \"Function\"\n if (!Object.prototype.getClassName) {\n Object.prototype.getClassName = function () {\n return Object.prototype.toString.call(this).match(/^\\[object\\s(.*)\\]$/)[1];\n }\n}\n\nvar test = [1,2,3,4,5];\n\nalert(test.getClassName()); // returns Array\n" }, { "answer_id": 9568515, "author": "Eli", "author_id": 1247107, "author_profile": "https://Stackoverflow.com/users/1247107", "pm_score": 3, "selected": false, "text": "function getType(o) {\n return Object.prototype.toString.call(o).match(/^\\[object\\s(.*)\\]$/)[1];\n}\nfunction isInstance(obj, type) {\n var ret = false,\n isTypeAString = getType(type) == \"String\",\n functionConstructor, i, l, typeArray, context;\n if (!isTypeAString && getType(type) != \"Function\") {\n throw new TypeError(\"type argument must be a string or function\");\n }\n if (obj !== undefined && obj !== null && obj.constructor) {\n //get the Function constructor\n functionConstructor = obj.constructor;\n while (functionConstructor != functionConstructor.constructor) {\n functionConstructor = functionConstructor.constructor;\n }\n //get the object's window\n context = functionConstructor == Function ? self : functionConstructor(\"return window\")();\n //get the constructor for the type\n if (isTypeAString) {\n //type is a string so we'll build the context (window.Array or window.some.Type)\n for (typeArray = type.split(\".\"), i = 0, l = typeArray.length; i < l && context; i++) {\n context = context[typeArray[i]];\n }\n } else {\n //type is a function so execute the function passing in the object's window\n //the return should be a constructor\n context = type(context);\n }\n //check if the object is an instance of the constructor\n if (context) {\n ret = obj instanceof context;\n if (!ret && (type == \"Number\" || type == \"String\" || type == \"Boolean\")) {\n ret = obj.constructor == context\n }\n }\n }\n return ret;\n}\n isInstance([], \"Array\"); //true\nisInstance(\"some string\", \"String\"); //true\nisInstance(new Object(), \"Object\"); //true\n\nfunction Animal() {}\nfunction Dog() {}\nDog.prototype = new Animal();\n\nisInstance(new Dog(), \"Dog\"); //true\nisInstance(new Dog(), \"Animal\"); //true\nisInstance(new Dog(), \"Object\"); //true\nisInstance(new Animal(), \"Dog\"); //false\n //\"Arguments\" type check\nvar args = (function() {\n return arguments;\n}());\n\nisInstance(args, function(w) {\n return w.Function(\"return arguments.constructor\")();\n}); //true\n\n//\"NodeList\" type check\nvar nl = document.getElementsByTagName(\"*\");\n\nisInstance(nl, function(w) {\n return w.document.getElementsByTagName(\"bs\").constructor;\n}); //true\n" }, { "answer_id": 9851746, "author": "Gaurav Ramanan", "author_id": 950039, "author_profile": "https://Stackoverflow.com/users/950039", "pm_score": 4, "selected": false, "text": "Object.prototype.toString.call('abc') // [object String]\nObject.prototype.toString.call(/abc/) // [object RegExp]\nObject.prototype.toString.call([1,2,3]) // [object Array]\n function type(obj){\n return Object.prototype.toString.call(obj]).match(/\\s\\w+/)[0].trim()\n}\n\nreturn [object String] as String\nreturn [object Number] as Number\nreturn [object Object] as Object\nreturn [object Undefined] as Undefined\nreturn [object Function] as Function\n" }, { "answer_id": 19545464, "author": "mikemaccana", "author_id": 123671, "author_profile": "https://Stackoverflow.com/users/123671", "pm_score": 3, "selected": false, "text": "var kind = function(item) {\n var getPrototype = function(item) {\n return Object.prototype.toString.call(item).slice(8, -1);\n };\n var kind, Undefined;\n if (item === null ) {\n kind = 'null';\n } else {\n if ( item === Undefined ) {\n kind = 'undefined';\n } else {\n var prototype = getPrototype(item);\n if ( ( prototype === 'Number' ) && isNaN(item) ) {\n kind = 'NaN';\n } else {\n kind = prototype;\n }\n }\n }\n return kind;\n };\n kind(37) === 'Number'\nkind(3.14) === 'Number'\nkind(Math.LN2) === 'Number'\nkind(Infinity) === 'Number'\nkind(Number(1)) === 'Number'\nkind(new Number(1)) === 'Number'\n kind(NaN) === 'NaN'\n kind('') === 'String'\nkind('bla') === 'String'\nkind(String(\"abc\")) === 'String'\nkind(new String(\"abc\")) === 'String'\n kind(true) === 'Boolean'\nkind(false) === 'Boolean'\nkind(new Boolean(true)) === 'Boolean'\n kind([1, 2, 4]) === 'Array'\nkind(new Array(1, 2, 3)) === 'Array'\n kind({a:1}) === 'Object'\nkind(new Object()) === 'Object'\n kind(new Date()) === 'Date'\n kind(function(){}) === 'Function'\nkind(new Function(\"console.log(arguments)\")) === 'Function'\nkind(Math.sin) === 'Function'\n kind(undefined) === 'undefined'\n kind(null) === 'null'\n" }, { "answer_id": 20441656, "author": "Mahdi", "author_id": 1658526, "author_profile": "https://Stackoverflow.com/users/1658526", "pm_score": 3, "selected": false, "text": "var TypeOf = function ( thing ) {\n\n var typeOfThing = typeof thing;\n\n if ( 'object' === typeOfThing ) {\n\n typeOfThing = Object.prototype.toString.call( thing );\n\n if ( '[object Object]' === typeOfThing ) {\n\n if ( thing.constructor.name ) {\n return thing.constructor.name;\n } \n\n else if ( '[' === thing.constructor.toString().charAt(0) ) {\n typeOfThing = typeOfThing.substring( 8,typeOfThing.length - 1 );\n } \n\n else {\n\n typeOfThing = thing.constructor.toString().match( /function\\s*(\\w+)/ );\n\n if ( typeOfThing ) { \n return typeOfThing[1];\n } \n\n else {\n return 'Function';\n }\n }\n } \n\n else {\n typeOfThing = typeOfThing.substring( 8,typeOfThing.length - 1 );\n }\n }\n\n return typeOfThing.charAt(0).toUpperCase() + typeOfThing.slice(1);\n}\n" }, { "answer_id": 25014589, "author": "Daniel Jankowski", "author_id": 1884947, "author_profile": "https://Stackoverflow.com/users/1884947", "pm_score": 0, "selected": false, "text": "Object.defineProperty(Object.prototype, \"getClassName\", {\n value: function() {\n var funcNameRegex = /function (.{1,})\\(/;\n var results = (funcNameRegex).exec((this).constructor.toString());\n return (results && results.length > 1) ? results[1] : \"\";\n }\n});\n" }, { "answer_id": 32767035, "author": "Guy", "author_id": 172815, "author_profile": "https://Stackoverflow.com/users/172815", "pm_score": 0, "selected": false, "text": " // Mixin for identifying a Javascript Object\n\n _.mixin({\n 'identify' : function(object) {\n var output;\n var isMethods = ['isArguments', 'isArray', 'isArguments', 'isBoolean', 'isDate', 'isArguments', \n 'isElement', 'isError', 'isFunction', 'isNaN', 'isNull', 'isNumber', \n 'isPlainObject', 'isRegExp', 'isString', 'isTypedArray', 'isUndefined', 'isEmpty', 'isObject']\n\n this.each(isMethods, function (method) {\n if (this[method](object)) {\n output = method;\n return false;\n }\n }.bind(this));\n return output;\n }\n });\n console.log(_.identify('hello friend')); // isString\n" }, { "answer_id": 34368411, "author": "elydelacruz", "author_id": 437498, "author_profile": "https://Stackoverflow.com/users/437498", "pm_score": 0, "selected": false, "text": "classOf = classOfIs = defineSubClass = classOf classOf sjl.classOfIs var SomeCustomClass = sjl.package.stdlib.Extendable.extend({\n constructor: function SomeCustomClass () {},\n // ...\n}),\n\nHelloIterator = sjl.ns.stdlib.Iterator.extend( \n function HelloIterator () {}, \n { /* ... methods here ... */ },\n { /* ... static props/methods here ... */ }\n),\n\nhelloIt = new HelloIterator();\n\nsjl.classOfIs(new SomeCustomClass(), SomeCustomClass) === true; // `true`\nsjl.classOfIs(helloIt, HelloIterator) === true; // `true`\n\nvar someString = 'helloworld';\n\nsjl.classOfIs(someString, String) === true; // `true`\n\nsjl.classOfIs(99, Number) === true; // true\n\nsjl.classOf(NaN) === 'NaN'; // true\n\nsjl.classOf(new Map()) === 'Map';\nsjl.classOf(new Set()) === 'Set';\nsjl.classOfIs([1, 2, 4], Array) === true; // `true`\n\n// etc..\n\n// Also optionally the type you want to check against could be the type's name\nsjl.classOfIs(['a', 'b', 'c'], 'Array') === true; // `true`!\nsjl.classOfIs(helloIt, 'HelloIterator') === true; // `true`!\n" }, { "answer_id": 41457071, "author": "Gili", "author_id": 14731, "author_profile": "https://Stackoverflow.com/users/14731", "pm_score": 3, "selected": false, "text": "/**\n * Describes the type of a variable.\n */\nclass VariableType\n{\n type;\n name;\n\n /**\n * Creates a new VariableType.\n *\n * @param {\"undefined\" | \"null\" | \"boolean\" | \"number\" | \"bigint\" | \"array\" | \"string\" | \"symbol\" |\n * \"function\" | \"class\" | \"object\"} type the name of the type\n * @param {null | string} [name = null] the name of the type (the function or class name)\n * @throws {RangeError} if neither <code>type</code> or <code>name</code> are set. If <code>type</code>\n * does not have a name (e.g. \"number\" or \"array\") but <code>name</code> is set.\n */\n constructor(type, name = null)\n {\n switch (type)\n {\n case \"undefined\":\n case \"null\":\n case \"boolean\" :\n case \"number\" :\n case \"bigint\":\n case \"array\":\n case \"string\":\n case \"symbol\":\n if (name !== null)\n throw new RangeError(type + \" may not have a name\");\n }\n this.type = type;\n this.name = name;\n }\n\n /**\n * @return {string} the string representation of this object\n */\n toString()\n {\n let result;\n switch (this.type)\n {\n case \"function\":\n case \"class\":\n {\n result = \"a \";\n break;\n }\n case \"object\":\n {\n result = \"an \";\n break;\n }\n default:\n return this.type;\n }\n result += this.type;\n if (this.name !== null)\n result += \" named \" + this.name;\n return result;\n }\n}\n\nconst functionNamePattern = /^function\\s+([^(]+)?\\(/;\nconst classNamePattern = /^class(\\s+[^{]+)?{/;\n\n/**\n * Returns the type information of a value.\n *\n * <ul>\n * <li>If the input is undefined, returns <code>(type=\"undefined\", name=null)</code>.</li>\n * <li>If the input is null, returns <code>(type=\"null\", name=null)</code>.</li>\n * <li>If the input is a primitive boolean, returns <code>(type=\"boolean\", name=null)</code>.</li>\n * <li>If the input is a primitive number, returns <code>(type=\"number\", name=null)</code>.</li>\n * <li>If the input is a primitive or wrapper bigint, returns\n * <code>(type=\"bigint\", name=null)</code>.</li>\n * <li>If the input is an array, returns <code>(type=\"array\", name=null)</code>.</li>\n * <li>If the input is a primitive string, returns <code>(type=\"string\", name=null)</code>.</li>\n * <li>If the input is a primitive symbol, returns <code>(type=\"symbol\", null)</code>.</li>\n * <li>If the input is a function, returns <code>(type=\"function\", name=the function name)</code>. If the\n * input is an arrow or anonymous function, its name is <code>null</code>.</li>\n * <li>If the input is a function, returns <code>(type=\"function\", name=the function name)</code>.</li>\n * <li>If the input is a class, returns <code>(type=\"class\", name=the name of the class)</code>.\n * <li>If the input is an object, returns\n * <code>(type=\"object\", name=the name of the object's class)</code>.\n * </li>\n * </ul>\n *\n * Please note that built-in types (such as <code>Object</code>, <code>String</code> or <code>Number</code>)\n * may return type <code>function</code> instead of <code>class</code>.\n *\n * @param {object} value a value\n * @return {VariableType} <code>value</code>'s type\n * @see <a href=\"http://stackoverflow.com/a/332429/14731\">http://stackoverflow.com/a/332429/14731</a>\n * @see isPrimitive\n */\nfunction getTypeInfo(value)\n{\n if (value === null)\n return new VariableType(\"null\");\n const typeOfValue = typeof (value);\n const isPrimitive = typeOfValue !== \"function\" && typeOfValue !== \"object\";\n if (isPrimitive)\n return new VariableType(typeOfValue);\n const objectToString = Object.prototype.toString.call(value).slice(8, -1);\n // eslint-disable-next-line @typescript-eslint/ban-types\n const valueToString = value.toString();\n if (objectToString === \"Function\")\n {\n // A function or a constructor\n const indexOfArrow = valueToString.indexOf(\"=>\");\n const indexOfBody = valueToString.indexOf(\"{\");\n if (indexOfArrow !== -1 && (indexOfBody === -1 || indexOfArrow < indexOfBody))\n {\n // Arrow function\n return new VariableType(\"function\");\n }\n // Anonymous and named functions\n const functionName = functionNamePattern.exec(valueToString);\n if (functionName !== null && typeof (functionName[1]) !== \"undefined\")\n {\n // Found a named function or class constructor\n return new VariableType(\"function\", functionName[1].trim());\n }\n const className = classNamePattern.exec(valueToString);\n if (className !== null && typeof (className[1]) !== \"undefined\")\n {\n // When running under ES6+\n return new VariableType(\"class\", className[1].trim());\n }\n // Anonymous function\n return new VariableType(\"function\");\n }\n if (objectToString === \"Array\")\n return new VariableType(\"array\");\n\n const classInfo = getTypeInfo(value.constructor);\n return new VariableType(\"object\", classInfo.name);\n}\n\n \nfunction UserFunction()\n{\n}\n\nfunction UserClass()\n{\n}\n\nlet anonymousFunction = function()\n{\n};\n\nlet arrowFunction = i => i + 1;\n\nconsole.log(\"getTypeInfo(undefined): \" + getTypeInfo(undefined));\nconsole.log(\"getTypeInfo(null): \" + getTypeInfo(null));\nconsole.log(\"getTypeInfo(true): \" + getTypeInfo(true));\nconsole.log(\"getTypeInfo(5): \" + getTypeInfo(5));\nconsole.log(\"getTypeInfo(\\\"text\\\"): \" + getTypeInfo(\"text\"));\nconsole.log(\"getTypeInfo(userFunction): \" + getTypeInfo(UserFunction));\nconsole.log(\"getTypeInfo(anonymousFunction): \" + getTypeInfo(anonymousFunction));\nconsole.log(\"getTypeInfo(arrowFunction): \" + getTypeInfo(arrowFunction));\nconsole.log(\"getTypeInfo(userObject): \" + getTypeInfo(new UserClass()));\nconsole.log(\"getTypeInfo(nativeObject): \" + getTypeInfo(navigator.mediaDevices.getUserMedia));" }, { "answer_id": 45469531, "author": "Big Sam", "author_id": 7922114, "author_profile": "https://Stackoverflow.com/users/7922114", "pm_score": 2, "selected": false, "text": "var obj; Object.prototype.toString.call(obj).split(' ')[1].replace(']', '');\n" }, { "answer_id": 52066485, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "somevar.constructor.name \n const getVariableType = a => a.constructor.name.toLowerCase();\n\n const d = new Date();\n const res1 = getVariableType(d); // 'date'\n const num = 5;\n const res2 = getVariableType(num); // 'number'\n const fn = () => {};\n const res3 = getVariableType(fn); // 'function'\n\n console.log(res1); // 'date'\n console.log(res2); // 'number'\n console.log(res3); // 'function'" }, { "answer_id": 55402706, "author": "qwertzguy", "author_id": 965176, "author_profile": "https://Stackoverflow.com/users/965176", "pm_score": -1, "selected": false, "text": "class.name function.name class TestA {}\nconsole.log(TestA.name); // \"TestA\"\n\nfunction TestB() {}\nconsole.log(TestB.name); // \"TestB\"\n" }, { "answer_id": 61634891, "author": "ZenG", "author_id": 13402335, "author_profile": "https://Stackoverflow.com/users/13402335", "pm_score": 0, "selected": false, "text": "function getType(entity){\n var x = Object.prototype.toString.call(entity)\n return x.split(\" \")[1].split(']')[0].toLowerCase()\n}\n function checkType(entity, type){\n return getType(entity) === type\n}\n" }, { "answer_id": 66132297, "author": "rodo", "author_id": 4762454, "author_profile": "https://Stackoverflow.com/users/4762454", "pm_score": 1, "selected": false, "text": "const getTypeName = (thing) => {\n const name = typeof thing\n if (name !== 'object') return name\n if (thing instanceof Error) return 'error'\n if (!thing) return 'null'\n return ({}).toString.call(thing).match(/\\s([a-zA-Z]+)/)[1].toLowerCase()\n}\n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/332422", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41595/" ]
332,431
<p>Lets say you need to attach some JavaScript functionality to an ASP.NET User Control of which there might be multiple instances on any given page. Because JavaScript has shared global state, what techniques can you use to keep the client state and behavior for each instance of a control separate?</p>
[ { "answer_id": 332517, "author": "John MacIntyre", "author_id": 29043, "author_profile": "https://Stackoverflow.com/users/29043", "pm_score": 0, "selected": false, "text": "function <%=this.ClientID %>_myButton_onclick()\n{\n DoSomething();\n}\n <button id=\"myButton\" onclick=\"<%=this.ClientID %>_myButton_onclick()\">\n" }, { "answer_id": 9840040, "author": "ps.", "author_id": 212469, "author_profile": "https://Stackoverflow.com/users/212469", "pm_score": 0, "selected": false, "text": " this.Page.ClientScript.RegisterClientScriptInclude(\"searchcontrol.js\",\"includes/searchcontrol.js\");\n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/332431", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4541/" ]
332,441
<p>I was at an interview for a C position in which they presented me with an idiom that I haven't previously encountered. This is a trick that simplifies implementation of various algorithms involving linked lists and I'm wondering if anybody else has encountered this.</p> <p>Say we have a linked list record defined so:</p> <pre><code>typedef struct _record { char* value; struct _record* next; } record; </code></pre> <p>We need a function that inserts a new record so that the entire list remains sorted with respect to the value's in the records. The following implementation is simpler than anything I would have used, albeit less readable.</p> <pre><code>void insert_sorted(record** r, const char* value) { record* newrec = NULL; while(*r &amp;&amp; strcmp(value, (*r)-&gt;value) &gt; 0) r = &amp;((*r)-&gt;next); /* move r to point to the next field of the record */ newrec = malloc(sizeof(record)); newrec-&gt;value = strdup(value); newrec-&gt;next = *r; *r = newrec; } </code></pre> <p>When the function is called, r points to the head pointer of the list. During the while loop, r is updated to point to the <code>next</code> field of the record that comes just before the point where we want to put the new record in. The last line of the function either updates the head pointer of the list (if the insertion happens at the beginning) or the <code>next</code> field of the previous record, which is quite cool.</p> <p>A couple of questions:</p> <ul> <li><p>Does this idiom have a name or is it mentioned in any literature?</p></li> <li><p>Are there others like it in the C language?</p></li> </ul> <p>I thought I knew C pretty well and had pointers and indirection pretty well figured out, but this one took me a while to fully understand.</p>
[ { "answer_id": 332470, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 2, "selected": false, "text": "x -> prev -> next = y\ny -> next = x\ny -> prev = x -> prev\nx -> prev = y\n x -> prev -> next = x -> next\nx -> next -> prev = x -> prev\nfree x\n n = head -> next\nwhile n != tail\n process n\n n = n -> next\n" }, { "answer_id": 332519, "author": "Greg Rogers", "author_id": 5963, "author_profile": "https://Stackoverflow.com/users/5963", "pm_score": 1, "selected": false, "text": "record* insert_sorted(const record* head, const char* value)\n" }, { "answer_id": 332553, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "void insertIntoSorted(Element *&head, Element *newOne)\n{\n Element **pp = &head;\n Element *curr;\n while ((curr = *pp) != NULL && less(curr, newOne)) {\n pp = &(pp->next);\n }\n newOne->next = *pp;\n *pp = newOne;\n}\n // returns deleted element or NULL when key not found\nElement *deleteFromList(Element *&head, const ElementKey &key)\n{\n Element **pp = &head;\n Element *curr;\n while ((curr = *pp) != NULL && !keyMatches(curr, key)) {\n pp = &(pp->next);\n }\n if (curr == NULL) return NULL;\n *pp = (*pp)->next; // here is the actual delete\n return curr;\n}\n" }, { "answer_id": 332626, "author": "Evan Teran", "author_id": 13430, "author_profile": "https://Stackoverflow.com/users/13430", "pm_score": 4, "selected": true, "text": "NULL *it = new_node(); NULL" }, { "answer_id": 18559676, "author": "cmaster - reinstate monica", "author_id": 2445184, "author_profile": "https://Stackoverflow.com/users/2445184", "pm_score": 0, "selected": false, "text": "Element** previous = &firstElement, *current;\nwhile((current = *previous)) {\n if(shouldRemove(current)) {\n *previous = current->next; //delete\n } else {\n previous = &current->next; //point to next\n }\n}\n" }, { "answer_id": 21513619, "author": "pepero", "author_id": 448839, "author_profile": "https://Stackoverflow.com/users/448839", "pm_score": 0, "selected": false, "text": "void insert_sorted(record** head, const char* value)\n{\n record** r = head;\n bool isSameHead = false;\n record* newrec = NULL;\n while(*r && strcmp(value, (*r)->value) > 0) {\n r = &((*r)->next); isSameHead = true; }\n newrec = malloc(sizeof(record));\n newrec->value = strdup(value);\n newrec->next = *r;\n *r = newrec;\n if (!isSameHead) *head = newrec;\n}\n void insert_sorted(record** head, const char* value)\n {\n record dummyHead;\n dummyHead.next = *head;\n record* r = &dummyHead;\n while(r->next) {\n if(strcmp(value, r->next->value) < 0) \n break;\n r = r->next;}\n newrec = malloc(sizeof(record));\n newrec->value = strdup(value);\n newrec->next = r->next;\n r->next = newrec;\n *head = dummyHead.next;\n }\n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/332441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15109/" ]
332,448
<h2>Update</h2> <p>I am making this a community wiki, for three reasons:</p> <ul> <li>I don't feel like I got a definitive answer, but</li> <li>I have long since stopped needing an answer, because I rolled my own accordion function</li> <li>this question gets tons of views, so clearly lots of people are still interested</li> </ul> <p>So if anybody wants to change/clarify this question and make it a definitive guide, be my guest.</p> <hr> <p>I'm working on a page using jQuery's <a href="http://docs.jquery.com/UI/Accordion" rel="noreferrer">accordion UI element</a>. I modeled my HTML on that example, except that inside the <code>&lt;li&gt;</code> elements, I have some unordered lists of links. Like this:</p> <pre><code> $(document).ready(function() { $(".ui-accordion-container").accordion( {active: "a.default", alwaysOpen: true, autoHeight: false} ); }); &lt;ul class="ui-accordion-container"&gt; &lt;li&gt; &lt;!-- Start accordion section --&gt; &lt;a href='#' class="accordion-label"&gt;A Group of Links&lt;/a&gt; &lt;ul class="linklist"&gt; &lt;li&gt;&lt;a href="http://example.com"&gt;Example Link&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="http://example.com"&gt;Example Link&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;!--and of course there's another group --&gt; </code></pre> <h3>Problem: IE Animation stinks</h3> <p>Although IE7 animates the documentation's example accordion menu just fine, it has problems with mine. Specifically, one accordion menu on the page moves jerkily and has flashes of content. <strong>I know that it's not a CSS issue because the same thing happens if I don't include my CSS files.</strong></p> <p>The other accordion menu on the page opens the first section you click and, after that, won't open any of them.</p> <p>Both of these problems are IE-specific, and both go away if I use the option <code>animated: false</code>. But I'd like to keep the default <code>slide</code> animation, since it helps the user understand what the menu is doing.</p> <p>Is there another way?</p>
[ { "answer_id": 332485, "author": "Pim Jager", "author_id": 35197, "author_profile": "https://Stackoverflow.com/users/35197", "pm_score": 0, "selected": false, "text": " navigation: true\n" }, { "answer_id": 332739, "author": "Darko", "author_id": 32943, "author_profile": "https://Stackoverflow.com/users/32943", "pm_score": 3, "selected": false, "text": "var accordion = function(toggleEl, accEl) {\n toggleEl.click(function() {\n accEl.slideToggle(function() { });\n return false;\n });\n}\n $(document).ready(function() {\n new accordion($(\"a.accordion-label\"), $(\"ul. linklist\")); \n});\n var accordion = function(toggleEl, accEl, callback) {\n toggleEl.click(function() {\n accEl.slideToggle(callback);\n return false;\n });\n}\n\n$(document).ready(function() {\n new accordion($(\"a.accordion-label\"), $(\"ul. linklist\"), function() { /* some callback */ }); \n});\n" }, { "answer_id": 486337, "author": "Tyler", "author_id": 5642, "author_profile": "https://Stackoverflow.com/users/5642", "pm_score": 4, "selected": false, "text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n" }, { "answer_id": 504019, "author": "Schulty", "author_id": 61591, "author_profile": "https://Stackoverflow.com/users/61591", "pm_score": 2, "selected": false, "text": "$().ready(function(){\n $(\".ui-accordion-header\").click(function() {\n $(this).next().fadeIn();\n });\n)};\n" }, { "answer_id": 937619, "author": "Ben", "author_id": 115727, "author_profile": "https://Stackoverflow.com/users/115727", "pm_score": 2, "selected": false, "text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\" >\n" }, { "answer_id": 1176087, "author": "nedlud", "author_id": 51882, "author_profile": "https://Stackoverflow.com/users/51882", "pm_score": 0, "selected": false, "text": "<!DOCTYPE html>" }, { "answer_id": 1640926, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<div id=\"accordion\">\n\n <h3 class=\"oneLine\">Asylum</h3>\n\n <div class=\"serviceBlockContent\">\n <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque sed augue a enim convallis facilisis. Aenean eu ullamcorper nulla. Ut id urna quis augue bibendum commodo et a quam.</p>\n </div>\n\n</div>\n" }, { "answer_id": 1942028, "author": "sebastien", "author_id": 236282, "author_profile": "https://Stackoverflow.com/users/236282", "pm_score": 0, "selected": false, "text": "autoHeight: false autoHeight: true min-height" }, { "answer_id": 2239870, "author": "Menachem Almog", "author_id": 270573, "author_profile": "https://Stackoverflow.com/users/270573", "pm_score": 0, "selected": false, "text": "{active: \"a.default\", alwaysOpen: \"true\", autoHeight: \"false\"}\n {active: \"a.default\", alwaysOpen: true, autoHeight: false}\n" }, { "answer_id": 2570555, "author": "andy", "author_id": 308186, "author_profile": "https://Stackoverflow.com/users/308186", "pm_score": 1, "selected": false, "text": "<!DOCTYPE html>\n" }, { "answer_id": 5130623, "author": "IanI", "author_id": 237705, "author_profile": "https://Stackoverflow.com/users/237705", "pm_score": 3, "selected": false, "text": "autoHeight: \"false\" clearStyle: \"true\" if ( $.browser.msie && $.browser.version < 8 ) {\n //ie<8 version\n}\nelse {\n //version for the good browsers\n}\n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/332448", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4376/" ]
332,454
<p>I want to do this C# code in F#</p> <pre><code> string[] a = new string[5]; string b = string.Empty; a[0] = "Line 1"; a[2] = "Line 2"; foreach (string c in a) { b = c + Environment.NewLine; } </code></pre>
[ { "answer_id": 332527, "author": "Juliet", "author_id": 40516, "author_profile": "https://Stackoverflow.com/users/40516", "pm_score": 5, "selected": true, "text": "open System\nlet a = [| \"Line 1\"; null; \"Line 2\"; null; null;|] \nlet b = String.Join(Environment.NewLine, a)\n" }, { "answer_id": 6979613, "author": "Dmitrii Lobanov", "author_id": 100110, "author_profile": "https://Stackoverflow.com/users/100110", "pm_score": 2, "selected": false, "text": "concat System let a = [| \"Line 1\"; null; \"Line 2\"; null; null;|] \nlet b = String.concat System.Environment.NewLine a\n System String module String class" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/332454", "https://Stackoverflow.com", "https://Stackoverflow.com/users/72123/" ]
332,460
<p>Is their a way to use a non-member non-friend function on an object using the same "dot" notation as member functions?</p> <p>Can I pull a (any) member out of a class, and have users use it in the same way they always have?</p> <p>Longer Explanation:</p> <p><a href="http://www.ddj.com/cpp/184401197" rel="nofollow noreferrer">Scott Meyers</a>, Herb Sutter, et all, argue that non-member non-friend functions are a part of an object's interface, and can improve encapsulation. I agree with them.</p> <p>However, after recently reading this article: <a href="http://www.gotw.ca/gotw/084.htm" rel="nofollow noreferrer">http://www.gotw.ca/gotw/084.htm</a> I find myself questioning the syntax implications.</p> <p>In that article, Herb proposes having a single <code>insert</code>, <code>erase</code>, and <code>replace</code> member, and several non-member non-friend functions of the same name.</p> <p>Does this mean, as I think it does, that Herb thinks some functions should be used with the dot notation, and others as a global function?</p> <pre><code>std::string s("foobar"); s.insert( ... ); /* One like this */ insert( s , ...); /* Others like this */ </code></pre> <p>Edit:</p> <p>Thanks everyone for your very useful answers, however, I think the point of my question has been overlooked.</p> <p>I specifically did not mention the specific case of operators, and how they retain the "natural" notation. Nor that you should wrap everything in a namespace. These things are written in the article I linked to.</p> <p><strong>The question itself was:</strong></p> <p>In the article, Herb suggests that one insert() method be a member, while the rest are non-member non-friend functions.</p> <p>This implies that to use one form of insert() you have to use dot notation, while for the others, you do not.</p> <p><strong>Is it just me, or does that sound crazy?</strong></p> <p>I have a hunch that perhaps you can use a single syntax. (Im thinking how Boost::function can take a *this parameter for mem_fun).</p>
[ { "answer_id": 332524, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 2, "selected": false, "text": "void T::doSomething(int value) ; // method\nvoid doSomething(T & t, int value) ; // non-member non-friend function\n T & operator += (T & lhs, const T & rhs) ;\n{\n // do something like lhs.value += rhs.value\n return lhs ;\n}\n\nT & T::operator += (const T & rhs) ;\n{\n // do something like this->value += rhs.value\n return *this ;\n}\n void doSomething(T & a, T & b)\n{\n a += b ;\n}\n class IntegerMethod\n{\n public :\n IntegerMethod(const int p_iValue) : m_iValue(p_iValue) {}\n int getValue() const { return this->m_iValue ; }\n void setValue(const int p_iValue) { this->m_iValue = p_iValue ; }\n\n IntegerMethod & operator += (const IntegerMethod & rhs)\n {\n this->m_iValue += rhs.getValue() ;\n return *this ;\n }\n\n IntegerMethod operator + (const IntegerMethod & rhs) const\n {\n return IntegerMethod (this->m_iValue + rhs.getValue()) ;\n }\n\n std::string toString() const\n {\n std::stringstream oStr ;\n oStr << this->m_iValue ;\n return oStr.str() ;\n }\n\n private :\n int m_iValue ;\n} ;\n class IntegerFunction\n{\n public :\n IntegerFunction(const int p_iValue) : m_iValue(p_iValue) {}\n int getValue() const { return this->m_iValue ; }\n void setValue(const int p_iValue) { this->m_iValue = p_iValue ; }\n\n private :\n int m_iValue ;\n} ;\n\nIntegerFunction & operator += (IntegerFunction & lhs, const IntegerFunction & rhs)\n{\n lhs.setValue(lhs.getValue() + rhs.getValue()) ;\n return lhs ;\n}\n\nIntegerFunction operator + (const IntegerFunction & lhs, const IntegerFunction & rhs)\n{\n return IntegerFunction(lhs.getValue() + rhs.getValue()) ;\n}\n\nstd::string toString(const IntegerFunction & p_oInteger)\n{\n std::stringstream oStr ;\n oStr << p_oInteger.getValue() ;\n return oStr.str() ;\n}\n void doSomething()\n{\n {\n IntegerMethod iMethod(25) ;\n iMethod += 35 ;\n std::cout << \"iMethod : \" << iMethod.toString() << std::endl ;\n\n IntegerMethod result(0), lhs(10), rhs(20) ;\n result = lhs + 20 ;\n // result = 10 + rhs ; // WON'T COMPILE\n result = 10 + 20 ;\n result = lhs + rhs ;\n }\n\n {\n IntegerFunction iFunction(125) ;\n iFunction += 135 ;\n std::cout << \"iFunction : \" << toString(iFunction) << std::endl ;\n\n IntegerFunction result(0), lhs(10), rhs(20) ;\n result = lhs + 20 ;\n result = 10 + rhs ;\n result = 10 + 20 ;\n result = lhs + rhs ;\n }\n}\n" }, { "answer_id": 332557, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 1, "selected": false, "text": "<algorithm> main.cpp" }, { "answer_id": 332796, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 1, "selected": false, "text": "size // joe writes this container class:\nnamespace mylib {\n class container { \n // ... loads of stuff ...\n public:\n std::size_t size() const { \n // do something and return\n }\n };\n\n std::size_t size(container const& c) {\n return c.size();\n } \n}\n\n// another programmer decides to write another container...\nnamespace bar {\n class container {\n // again, lots of stuff...\n public:\n std::size_t size() const {\n // do something and return\n }\n };\n\n std::size_t size(container const& c) {\n return c.size();\n } \n}\n\n// we want to get the size of arrays too\ntemplate<typename T, std::size_t n>\nstd::size_t size(T (&)[n]) {\n return n;\n}\n int main() {\n mylib::container c;\n std::size_t c_size = size(c);\n\n char data[] = \"some string\";\n std::size_t data_size = size(data);\n}\n size(object) begin end boost::range" }, { "answer_id": 333349, "author": "Andreas Magnusson", "author_id": 5811, "author_profile": "https://Stackoverflow.com/users/5811", "pm_score": 2, "selected": true, "text": "mystring s;\ninsert(s, \"hello\");\ninsert(s, other_s.begin(), other_s.end());\ninsert(s, 10, '.');\n" }, { "answer_id": 334177, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 1, "selected": false, "text": "template<typename DERIVED, typename T>\nstruct OtherInsertFunctions {\n void insertUpsideDown(T t) {\n DERIVED *self = static_cast<DERIVED*>(this);\n self->insert(t.turnUpsideDown());\n }\n void insertBackToFront(T t) // etc.\n void insert(T t, Orientation o) // this one is tricksy because it's an\n // overload, so requires the 'using' declaration\n};\n\ntemplate<typename T>\nclass MyCollection : public OtherInsertFunctions<MyCollection,T> {\npublic:\n // using declaration, to prevent hiding of base class overloads\n using OtherInsertFunctions<MyCollection,T>::insert;\n void insert(T t);\n // and the rest of the class goes here\n};\n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/332460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29701/" ]
332,473
<p>I've created a DLL project in VS 2005 for native Win32/unmanaged C++, call it myProj.dll. It depends on a 3rd-party commercial DLL that in turn depends on msvcr90.dll (I assume it was built from a VS 2008 project). I'll call it thirdParty.dll.</p> <p>My DLL project builds just fine in VS2005. I've built a test app (again, VS 2005 Win32 C++) that links to myProj.lib. (As an aside, judging by the small size of the .lib, and by the fact that, at run-time, the app must locate myProj.dll, I'm guessing that the .lib is just a wrapper for a call to loadLibrary() that loads the actual DLL; is that close?)</p> <p>My problem is that, at run-time, the test app cannot locate msvcr90.dll (nor msvcp90.dll), the dependency on which stems from the thirdParty.dll.</p> <p>I've installed Microsoft's redist package, and so have all the std (9.0) C++ libraries in c:\WINDOWS\WinSxS\x86_Microsoft.VC90.CRT_... . What's more, if I point the dependency walker at thirdParty.dll, it happily resolves the references to that location.</p> <p>But, if I point depends.exe at my test app (.exe) or myProj.dll, msvcr90.dll and msvcp90.dll are not found.</p> <p>I'm guessing there's something I need to configure in VS2005 so that the .exe or myProj.dll are aware of the location of the 9.0 versions of the std C++ libraries (presumably where the redist package installed them in C:\WINDOWS\WinSxS), but I can't seem to figure out what it is. Am I on the right track?</p> <p>I note that, if I simply copy the msvc*90.dll files to my app directory, then the dependency is resolved, but I get the run-time error about improper loading of std c++ DLLs, etc.</p> <p>Thanks immensely in advance.</p>
[ { "answer_id": 332545, "author": "jussij", "author_id": 14738, "author_profile": "https://Stackoverflow.com/users/14738", "pm_score": 3, "selected": false, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<assembly xmlns=\"urn:schemas-microsoft-com:asm.v1\" manifestVersion=\"1.0\">\n <assemblyIdentity\n name=\"Xidicone.Windows.Zeus for Windows\"\n version=\"3.9.6.69\"\n processorArchitecture=\"X86\"\n type=\"win32\" />\n\n <description>Zeus for Windows</description>\n\n <dependency>\n <dependentAssembly>\n <assemblyIdentity\n type=\"win32\"\n name=\"Microsoft.VC80.CRT\"\n version=\"8.0.50608.0\"\n processorArchitecture=\"x86\"\n publicKeyToken=\"1fc8b3b9a1e18e3b\" />\n </dependentAssembly>\n </dependency>\n\n <dependency>\n <dependentAssembly>\n <assemblyIdentity\n type=\"win32\"\n name=\"Microsoft.Windows.Common-Controls\"\n version=\"6.0.0.0\"\n processorArchitecture=\"X86\"\n publicKeyToken=\"6595b64144ccf1df\"\n language=\"*\" />\n </dependentAssembly>\n </dependency>\n</assembly>\n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/332473", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
332,477
<p>I need to revoke an authentication cookie if the user no longer exists (or some other condition), after the forms authentication mechanism already have received the authentication cookie from the browser and have validated it. I.e. here is the use scenario:</p> <ol> <li>The user have been authenticated, and granted non-expiring auth cookie.</li> <li><p>In a few days, the user tries to access my web app again, and as the cookie is valid, the forms authentication mechanism will grant access.</p></li> <li><p>Now I want to perform a second check (whatever condition I want), and decide if I want to let the user continue, or to revoke the authentication.</p></li> </ol> <p>The question is - is there an official automated way for this? So far I have come with some possibilities, but I do not know which one is better. I can capture the Authenticate event in global.asax, check whatever I want, and to revoke I clear the cookie, and then one of these:</p> <ol> <li><p>Redirect again to same url - this should work, as this time the forms authentication will fail, and it will redirect to logon page.</p></li> <li><p>Throw some exception ??? which one to make the redirect happen w/o me specifying anything?</p></li> <li><p>Somehow to get the logon page url from the config file (any ideas how/which config handler to use) and redirect directly?</p></li> <li><p>Some FormsAuthentication class/method I have overlooked, which is designed for this?</p></li> <li><p>Any other idea?</p></li> </ol>
[ { "answer_id": 332644, "author": "marto", "author_id": 29555, "author_profile": "https://Stackoverflow.com/users/29555", "pm_score": 3, "selected": true, "text": "FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(\n 1, // Ticket version\n name, // Username associated with ticket\n DateTime.Now, // Date/time issued\n DateTime.Now.AddMonths(1), // Date/time to expire\n true, // \"true\" for a persistent user cookie\n DateTime.Now.ToUniversalTime(), // last time the users was checked\n FormsAuthentication.FormsCookiePath);// Path cookie valid for\n\n // Encrypt the cookie using the machine key for secure transport\n string hash = FormsAuthentication.Encrypt(ticket);\n HttpCookie cookie = new HttpCookie(\n FormsAuthentication.FormsCookieName, // Name of auth cookie\n hash); // Hashed ticket\n\n cookie.HttpOnly = true;\n\n // Set the cookie's expiration time to the tickets expiration time\n if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;\n //cookie.Secure = FormsAuthentication.RequireSSL;\n Response.Cookies.Add(cookie);\n public void FormsAuthentication_OnAuthenticate(object sender, \n FormsAuthenticationEventArgs args)\n {\n if (FormsAuthentication.CookiesSupported)\n {\n if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)\n {\n try\n {\n FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(\n Request.Cookies[FormsAuthentication.FormsCookieName].Value);\n\n DateTime lastCheckedTime = DateTime.TryParse(ticket.UserData);\n TimeSpan elapsed = DateTime.Now - lastCheckedTime;\n if (elapsed.TotalMinutes > 10)//Get 10 from the config\n {\n //Check if user exists in the database. \n if (CheckIfUserIsValid())\n {\n //Reset the last checked time\n // and set the authentication cookie again\n }\n else\n {\n FormsAuthentication.SignOut();\n FormsAuthentication.RedirectToLoginPage();\n return;\n }\n }\n\n }\n catch (Exception e)\n {\n // Decrypt method failed.\n }\n }\n }\n }\n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/332477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8220/" ]
332,479
<p>i get this error </p> <pre><code>{"Method 'System.DateTime ConvertTimeFromUtc(System.DateTime, System.TimeZoneInfo)' has no supported translation to SQL."} </code></pre> <p>when i try to execute this linq to sql</p> <pre><code>var query = from p in db.Posts let categories = GetCategoriesByPostId(p.PostId) let comments = GetCommentsByPostId(p.PostId) select new Subnus.MVC.Data.Model.Post { Categories = new LazyList&lt;Category&gt;(categories), Comments = new LazyList&lt;Comment&gt;(comments), PostId = p.PostId, Slug = p.Slug, Title = p.Title, CreatedBy = p.CreatedBy, CreatedOn = TimeZoneInfo.ConvertTimeFromUtc(p.CreatedOn, TimeZoneInfo.FindSystemTimeZoneById("Romance Standard Time")), Body = p.Body }; return query; </code></pre> <p>is there another place i can convert the date to right format currently i have a macro i my _global.spark fil but that seems wrong </p> <pre><code>&lt;macro name="DateAndTime" Date="DateTime"&gt; # Date = TimeZoneInfo.ConvertTimeFromUtc(Date, TimeZoneInfo.FindSystemTimeZoneById("Romance Standard Time")); ${Date.ToString("MMMM d, yyyy")} at ${Date.ToString("hh:mm")} &lt;/macro&gt; &lt;macro name="Date" Date="DateTime"&gt; # Date = TimeZoneInfo.ConvertTimeFromUtc(Date, TimeZoneInfo.FindSystemTimeZoneById("Romance Standard Time")); ${Date.ToString("MMMM d, yyyy")} &lt;/macro&gt; </code></pre> <p><strong>Update:</strong> i now understand where the code does not work but when i remove it i get then same error for this code</p> <pre><code> public IQueryable&lt;Subnus.MVC.Data.Model.Comment&gt; GetCommentsByPostId(int postId) { var query = from c in db.Comments where c.PostId == postId select new Subnus.MVC.Data.Model.Comment { Body = c.Body, EMail = c.EMail, Date = c.CreatedOn, WebSite = c.Website, Name = c.Name }; return query; } </code></pre>
[ { "answer_id": 332490, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": true, "text": "[Function] ...\n CreatedOn = ctx.MapDate(p.CreatedOn)\n ....\n [Function] ....\n dbo.MapDate(t2.CreatedOn)\n....\n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/332479", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31296/" ]
332,486
<p>How can I programmatically change my browser's default home page with C#?</p>
[ { "answer_id": 332496, "author": "EBGreen", "author_id": 1358, "author_profile": "https://Stackoverflow.com/users/1358", "pm_score": 4, "selected": true, "text": "HKCU\\Software\\Microsoft\\Internet Explorer\\Main\\Start Page\n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/332486", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33185/" ]
332,492
<p>I'm seeing conflicting references in <a href="http://download.oracle.com/docs/cd/B19306_01/server.102/b14220/datatype.htm#i16209" rel="noreferrer">Oracles documentation</a>. Is there any difference between how decimals are stored in a FLOAT and a NUMBER types in the database?</p> <p>As I recall from C, et al, a float has accuracy limitations that an int doesn't have. R.g., For 'float's, 0.1(Base 10) is approximated as 0.110011001100110011001101(Base 2) which equals roughtly something like 0.100000001490116119384765625 (Base 10). However, for 'int's, 5(Base 10) is exactly 101(Base 2).</p> <p>Which is why the following won't terminate as expected in C:</p> <pre><code>float i; i = 0; for (i=0; i != 10; ) { i += 0.1 } </code></pre> <p>However I see <a href="http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/sql_elements001.htm#i45441" rel="noreferrer">elsewhere in Oracle's documentation</a> that FLOAT has been defined as a NUMBER. And as I understand it, Oracle's implementation of the NUMBER type does not run into the same problem as C's float.</p> <p>So, what's the real story here? Has Oracle deviated from the norm of what I expect to happen with floats/FLOATs?</p> <p>(I'm sure it's a bee-fart-in-a-hurricane of difference for what I'll be using them for, but I know I'm going to have questions if 0.1*10 comes out to 1.00000000000000001)</p>
[ { "answer_id": 332520, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 6, "selected": true, "text": "BINARY_FLOAT FLOAT" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/332492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/685/" ]
332,522
<p>I've been trying to run a jar file - let's call it test.jar - that uses the Sybase jconn3.jar on a Unix system.</p> <p>I have created a MANIFEST.MF file that has the following:</p> <pre><code>Class-Path: $SYBASE/jConnect-6_0/classes/jconn3.jar commons-net-1.3.0.jar </code></pre> <p>This gives a ClassNotFoundError. $SYBASE is the system variable that points to /opt/sybase13; I've also tried the following:</p> <pre><code>Class-Path: /opt/sybase13/jConnect-6_0/classes/jconn3.jar commons-net-1.3.0.jar </code></pre> <p>and</p> <pre><code>Class-Path: opt/sybase13/jConnect-6_0/classes/jconn3.jar commons-net-1.3.0.jar </code></pre> <p>However, if I copy the jconn3.jar file from the $SYBASE/jConnect-6_0/classes to the same directory as test.jar, and update my MANIFEST.MF to read as follows:</p> <pre><code>Class-Path: jconn3.jar commons-net-1.3.0.jar </code></pre> <p>The application runs as expected.</p> <p>Now, I've been able to verify the jconn3.jar file works by copying it locally; my MANIFEST.MF file includes the path to my Main-Class, so that's not at issue here.</p> <p>What do you think could be the problem? I've been looking at this thing for too long now. Thanks!</p>
[ { "answer_id": 332543, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 5, "selected": true, "text": "file:/opt/sybase13/... file:" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/332522", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
332,528
<p>Let's say that I want to merge from a release branch to the master branch and there are some commits in the release branch that I don't want to include in the master branch. Is there a way to do the merge so that one or more of those commits will not be merged?</p> <p>My strategy so far is to do the following (in master):</p> <pre><code>git merge --no-commit release-branch # Resolve conflicts and apply reverse patch of the commits that I don't want included git commit # Edit commit message so that it lists the commits that have been reverse-patched </code></pre> <p>Is there a better way to do this?</p>
[ { "answer_id": 3970442, "author": "fcurella", "author_id": 3914, "author_profile": "https://Stackoverflow.com/users/3914", "pm_score": 7, "selected": false, "text": "config.php .gitattributes config.php merge=ours .gitattributes" }, { "answer_id": 7203170, "author": "Maze", "author_id": 549635, "author_profile": "https://Stackoverflow.com/users/549635", "pm_score": 1, "selected": false, "text": "git checkout partlyMergedFrom\ngit whatchanged\n--> find the commit hash up to where you want to merge\ngit checkout partlyMergedInto\ngit merge e40a0e384f58409fe3c864c655a8d252b6422bfc\ngit whatchanged\n--> check that you really got all the changes you want to have\n" }, { "answer_id": 23392048, "author": "Tobias Schulte", "author_id": 969, "author_profile": "https://Stackoverflow.com/users/969", "pm_score": 5, "selected": false, "text": " C---D*---E---F* support\n /\nA---B---G---H*---I master\n git checkout master\ngit merge C\ngit merge D -s ours\ngit merge E\ngit merge F -s ours\n -s ours --record-only -------------C---D*---E---F* support\n / \\ \\ \\ \\\nA---B---G---H*---I---J---K----L---M master\n git checkout master\ngit merge support -s ours --no-commit\ngit cherry-pick C E --no-commit\ngit commit -m 'merged support into master'\n C---D*---E---F* support\n / \\\nA---B---G---H*---I---J master\n git checkout master\ngit merge support -s ours --no-commit\nfor id in `git log support --reverse --not HEAD --format=\"%H [%an] %s\" |\n grep -v \"bump version\" |\n sed \"s/\\(\\w*\\)\\s.*/\\1/g\"`\ndo\n git cherry-pick --no-commit $id\ndone\ngit commit -m 'merged support into master'\n" }, { "answer_id": 74397048, "author": "Cedriga", "author_id": 5784834, "author_profile": "https://Stackoverflow.com/users/5784834", "pm_score": 0, "selected": false, "text": "git config --global merge.ours.driver true .env merge=ours \n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/332528", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4883/" ]
332,534
<p>Please advise if you can.</p> <p>I am building an SMS web service API that will allow people to send SMS to their desired cellphone numbers. A request will be sent to the interface, we then process that request based on the account details provided and credits available on their account.</p> <p>We have two proposed XML structures for the interface request and I would like you to advise which one is better as we are going at each others throats about it.</p> <p>Interface A</p> <pre><code>print("&lt;?xml version = "1.0" encoding="UTF-8" standalone="yes"?&gt; &lt;Message version="1.0"&gt; &lt;ClientID&gt;11111&lt;/ClientID&gt; &lt;PassPhrase&gt;shjfkh&lt;/PassPhrase&gt; &lt;Request Type="sms" Refno="10" ToAddress="27732687745332"&gt; &lt;Content&gt; hello world &lt;/Content&gt; &lt;/Request&gt; &lt;/Message&gt; "); </code></pre> <p>Interface B</p> <pre><code> print("&lt;?xml version = "1.0" encoding="UTF-8" standalone="yes"?&gt; &lt;Message&gt; &lt;mmtag name="Version"&gt;1.0&lt;/mmtag&gt; &lt;mmtag name="ClientID"&gt;1001&lt;/mmtag&gt; &lt;mmtag name="RefNO"&gt;120&lt;/mmtag&gt; &lt;mmtag name="Encoding"&gt;base64&lt;/mmtag&gt; &lt;mmtag name="Type"&gt;SMS&lt;/mmtag&gt; &lt;mmtag name="Content"&gt;hello world&lt;/mmtag&gt; &lt;mmtag name="MSISDN"&gt;27781010102&lt;/mmtag&gt; &lt;/Message&gt;"); </code></pre> <p>Now, looking at the two examples, which do you think would be best-suited for our API interface, regardless of the technology in the back end. Please support your answer should you pick one.</p>
[ { "answer_id": 332548, "author": "dacracot", "author_id": 13930, "author_profile": "https://Stackoverflow.com/users/13930", "pm_score": 2, "selected": false, "text": "<Message version=\"1.0\" clientID=\"11111\" passPhrase=\"shjfkh\">\n <Request Type=\"sms\" Refno=\"10\" ToAddress=\"27732687745332\">hello world</Request>\n</Message>\n <Message version=\"1.0\" clientID=\"11111\" passPhrase=\"shjfkh\">\n <Request Type=\"sms\" Refno=\"10\" ToAddress=\"27732687745332\">hello john</Request>\n <Request Type=\"sms\" Refno=\"11\" ToAddress=\"12345678901234\">hello jane</Request>\n</Message>\n" }, { "answer_id": 332562, "author": "dacracot", "author_id": 13930, "author_profile": "https://Stackoverflow.com/users/13930", "pm_score": 2, "selected": false, "text": "<Message version=\"1.0\" clientID=\"11111\" passPhrase=\"shjfkh\">\n <Request Type=\"sms\" Refno=\"10\" ToAddress=\"27732687745332\"><![CDATA[hello john]]></Request>\n <Request Type=\"sms\" Refno=\"11\" ToAddress=\"12345678901234\"><![CDATA[hello jane]]></Request>\n</Message>\n" }, { "answer_id": 332634, "author": "Torsten Marek", "author_id": 9567, "author_profile": "https://Stackoverflow.com/users/9567", "pm_score": 2, "selected": false, "text": "mmtag" }, { "answer_id": 332769, "author": "Lawrence Dol", "author_id": 8946, "author_profile": "https://Stackoverflow.com/users/8946", "pm_score": 1, "selected": false, "text": "<Request Type=\"sms\" Refno=\"10\">\n <To>27732687745332</To>\n <To>1234567890</To>\n <Content>Hello world</Content>\n </Request>\n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/332534", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16092/" ]
332,554
<p>I don't understand how GCC works under Linux. In a source file, when I do a:</p> <pre><code>#include &lt;math.h&gt; </code></pre> <p>Does the compiler extract the appropriate binary code and insert it into the compiled executable OR does the compiler insert a reference to an external binary file (a-la Windows DLL?)</p> <p>I guess a generic version of this question is: Is there an equivalent concept to Windows DLLs under *nix?</p>
[ { "answer_id": 332572, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 6, "selected": true, "text": "math.h test.c test.o Relocation section '.rel.text' at offset 0x308 contains 1 entries:\n Offset Info Type Sym.Value Sym. Name\n0000001c 00000902 R_386_PC32 00000000 bar\n 9: 00000000 0 NOTYPE GLOBAL DEFAULT UND bar\n test.o libm.so so .dll test.o libm.a readelf -d ./test Dynamic section at offset 0x498 contains 22 entries:\n Tag Type Name/Value\n 0x00000001 (NEEDED) Shared library: [libm.so.6]\n 0x00000001 (NEEDED) Shared library: [libc.so.6]\n ... ... ...\n ld.so" }, { "answer_id": 332573, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 3, "selected": false, "text": "libcurl.a gcc codefile.c -lcurl\ngcc codefile.c /path/to/libcurl.a\n libcurl.a gcc .dll .lib .so ld binutils" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/332554", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11760/" ]
332,558
<p>I have a database where I store objects. I have the following (simplified) schema</p> <pre><code>CREATE TABLE MyObjects ( UniqueIdentifier Id; BigInt GenerationId; BigInt Value; Bit DeleteAction; ) </code></pre> <p>Each object has a unique identifier ("Id"), and a (set of) property ("Value"). Each time the value of the property for an object is changed, I enter a new row into this table with a new generation id ("GenerationId", which is monotonically increasing). If an object is deleted, then I record this fact by setting the "DeleteAction" bit to true.</p> <p><strong>At any point in time (generation), I would like to retrieve the state of all of my active objects!</strong></p> <p>Here's an example:</p> <pre><code>Id GenerationId Value DeleteAction 1 1 99 false 2 1 88 false 1 2 77 false 2 3 88 true </code></pre> <p>Objects in generations are:</p> <pre><code> 1: 1 {99}, 2 {88} 2: 1 {77}, 2 {88} 3: 1 {77} </code></pre> <p>The key is: how can I find out the row for each unique object who's <strong>generation id is closest (but not exceeding) to a given generation id</strong>? I can then do a post-filter step to remove all rows where the DeleteAction field is true.</p>
[ { "answer_id": 332584, "author": "Martin v. Löwis", "author_id": 33006, "author_profile": "https://Stackoverflow.com/users/33006", "pm_score": 0, "selected": false, "text": " select GenerationId,Value,DeleteAction from MyObjects \n where Id=1 and GenerationId < 3 \n order by GenerationId\n limit 1;\n" }, { "answer_id": 333504, "author": "Johan Buret", "author_id": 15366, "author_profile": "https://Stackoverflow.com/users/15366", "pm_score": 2, "selected": false, "text": "SELECT id,value\nFROM Myobjects\nINNER JOIN ( \n SELECT id, max(GenerationID) as LastGen \n FROM MyObjects\n WHERE GenerationID <= @Wantedgeneration\n Group by ID)\n On GenerationID = LastGen\nWHERE DelectedAction = false\n" }, { "answer_id": 334273, "author": "bortzmeyer", "author_id": 15625, "author_profile": "https://Stackoverflow.com/users/15625", "pm_score": 2, "selected": false, "text": "SELECT O.id,generation,value FROM \n MyObjects O, \n (SELECT id,max(generation) AS max_generation FROM MyObjects \n WHERE generation <= $GENERATION_ID GROUP BY id) AS TheMax WHERE \n TheMax.max_generation = generation AND O.deleted is False\n ORDER BY generation DESC;\n CREATE OR REPLACE FUNCTION generation_objects(INTEGER) RETURNS SETOF MyObjects AS\n 'SELECT O.id,generation,value,deleted FROM \n MyObjects O, \n (SELECT id,max(generation) AS max_generation FROM MyObjects \n WHERE generation <= $1 GROUP BY id) AS TheMax WHERE \n TheMax.max_generation = generation AND O.deleted is False;'\n LANGUAGE SQL;\n > SELECT * FROM MyObjects; \n id | generation | value | deleted \n----+------------+-------+---------\n 1 | 1 | 99 | f\n 2 | 2 | 88 | f\n 1 | 3 | 77 | f\n 2 | 4 | 88 | t\n 3 | 5 | 33 | f\n 4 | 6 | 22 | f\n 3 | 7 | 11 | f\n 2 | 8 | 11 | f\n > SELECT * FROM generation_objects(1) ORDER by generation DESC;\n id | generation | value | deleted \n----+------------+-------+---------\n 1 | 1 | 99 | f\n\n> SELECT * FROM generation_objects(2) ORDER by generation DESC;\n id | generation | value | deleted \n----+------------+-------+---------\n 2 | 2 | 88 | f\n 1 | 1 | 99 | f\n\n> SELECT * FROM generation_objects(3) ORDER by generation DESC;\n id | generation | value | deleted \n----+------------+-------+---------\n 1 | 3 | 77 | f\n 2 | 2 | 88 | f\n > SELECT * FROM generation_objects(4) ORDER by generation DESC;\n id | generation | value | deleted \n----+------------+-------+---------\n 1 | 3 | 77 | f\n" }, { "answer_id": 345619, "author": "Philipp Schmid", "author_id": 33272, "author_profile": "https://Stackoverflow.com/users/33272", "pm_score": 2, "selected": true, "text": "SELECT MyObjects.Id,Value\nFROM Myobjects\nINNER JOIN \n( \n SELECT Id, max(GenerationId) as LastGen\n FROM MyObjects\n WHERE GenerationId <= @TargetGeneration\n Group by Id\n) T1\nON MyObjects.Id = T1.Id AND MyObjects.GenerationId = LastGen\nWHERE DeleteAction = 'False'\n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/332558", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33272/" ]
332,574
<p>I dictate SQL using speech recognition, and lining things up is a pain. If I could see where the tab stops are it would save me a lot of time.</p>
[ { "answer_id": 332577, "author": "Keith Walton", "author_id": 22448, "author_profile": "https://Stackoverflow.com/users/22448", "pm_score": 4, "selected": true, "text": "Windows Registry Editor Version 5.00\n\n[HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Microsoft SQL Server\\90\\Tools\\Shell\\Text Editor]\n\"Guides\"=\"RGB(128,0,0) 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 96\"\n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/332574", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22448/" ]
332,580
<p>Is there an easy way in either language to generate a large set of random data quickly so far all the functions I've tried haven't worked too well when I need to generate a group of say 500,000 characters :( Any ideas?</p>
[ { "answer_id": 332598, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 2, "selected": false, "text": "System.Random Dim buffer As Byte() = Nothing\nArray.Resize(buffer, 500000)\nCall New Random().NextBytes(buffer)\nMy.Computer.FileSystem.WriteAllBytes(\"filename\", buffer, False)\n" }, { "answer_id": 333895, "author": "RS Conley", "author_id": 7890, "author_profile": "https://Stackoverflow.com/users/7890", "pm_score": 0, "selected": false, "text": "Public Function FillRandomCol() as Collection\n Dim C As Collection\n Dim I As Long\n Set C = New Collection\n Randomize Timer\n For I = 1 To 500000\n C.Add RandomChar\n Next I\n Set FillRandomCol = C\nEnd Sub\n\nPublic Function Random(ByVal Number As Integer) As Integer\n Random = CLng(Rnd * 1000000) Mod Number + 1\nEnd Function\n\nPublic Function RandomChar() As String\n Const AlphaNum = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n RandomChar = Mid$(AlphaNum, Random(36), 1)\nEnd Function\n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/332580", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
332,585
<p>It was a long holiday weekend, so I got the coding bug again and started playing around:</p> <p><a href="http://gfilter.net/junk/tileengine.jpg" rel="nofollow noreferrer">Mario http://gfilter.net/junk/tileengine.jpg</a></p> <p>I wrote a basic tile engine, but having never attempted this before, I am really struggling with handling sprite collision detection and implementing realistic physics for gravity.</p> <p>For any other game hobby writers, can you point me towards some walkthroughs on the best way to approach this?</p> <p><strong>Update:</strong></p> <p>I thought I'd share a progress report:</p> <p><a href="http://www.youtube.com/watch?v=-RKNQ2UiiLY" rel="nofollow noreferrer">http://www.youtube.com/watch?v=-RKNQ2UiiLY</a> &lt;-- Game in Action</p> <p>Its still really buggy, but collision detection is mostly working, I've started working on some other features (such as bumping the blocks (notice the bug) and interacting with the enemies).</p> <p>Mario still walks like he is on the moon, I'm using these constants, any advice for tweaking them for more realism?</p> <pre><code> const float AirDrag = 1.00f; const float GroundFriction = .97f; const float Gravity = 0.8f; </code></pre>
[ { "answer_id": 332785, "author": "Hugh Allen", "author_id": 15069, "author_profile": "https://Stackoverflow.com/users/15069", "pm_score": 2, "selected": false, "text": "const gravity = ... ; // pixels per timestep (eg. video frame) squared\n// while in freefall, each timestep:\ny_velocity += gravity;\ny_pos += y_velocity;\n" }, { "answer_id": 11877147, "author": "Nikunj Patel", "author_id": 815108, "author_profile": "https://Stackoverflow.com/users/815108", "pm_score": 0, "selected": false, "text": " UIGraphicsBeginImageContext(images.size);\n CGContextRef context = UIGraphicsGetCurrentContext();\n UIColor *color = [UIColor whiteColor];\n [color setFill];\n\n CGContextTranslateCTM(context, 1, images.size.height);\n CGContextScaleCTM(context, 1.0, -1.0);\n CGContextSetBlendMode(context, kCGBlendModeDestinationOver);\n CGRect rect = CGRectMake(0.0, 0.0, images.size.width, images.size.height);\n CGContextDrawImage(context, rect, images.CGImage);\n CGContextClipToMask(context, rect, images.CGImage);\n CGContextAddRect(context, rect);\n CGContextDrawPath(context, kCGPathFill);\n images = UIGraphicsGetImageFromCurrentImageContext();\n UIGraphicsEndImageContext();\n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/332585", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ]
332,592
<p>I have a set of divs that I want to make <code>collapsible/expandable</code> using jQuery's <code>slideToggle()</code> method. How do I make all of these divs collapsed by default? I'd like to avoid explicitly calling <code>slideToggle()</code> on each element during/after page rendering.</p>
[ { "answer_id": 332596, "author": "Anne Porosoff", "author_id": 28701, "author_profile": "https://Stackoverflow.com/users/28701", "pm_score": 4, "selected": false, "text": "$(document).ready(function(){\n $('div').hide();\n});\n" }, { "answer_id": 332600, "author": "netadictos", "author_id": 31791, "author_profile": "https://Stackoverflow.com/users/31791", "pm_score": 7, "selected": true, "text": "<style type=\"text/css\">\n .text{display:none}\n</style>\n\n<script type=\"text/javascript\">\n $(document).ready(function() { \n $('span.more').click(function() {\n $('p:eq(0)').slideToggle();\n $(this).hide();\n });\n });\n</script>\n\n<body> \n <p class=\"text\">\n I am using jquery <br/>\n I am using jquery <br/>\n I am using jquery <br/>\n I am using jquery <br/>\n I am using jquery <br/>\n I am using jquery <br/> \n </p>\n <span class=\"more\">show</span>\n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/332592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3488/" ]
332,602
<p>Let's say I have a table that represents a super class, <strong>students</strong>. And then I have N tables that represent subclasses of that object (<strong>athletes</strong>, <strong>musicians</strong>, etc). How can I express a constraint such that a student must be modeled in one (not more, not less) subclass?</p> <p>Clarifications regarding comments:</p> <ul> <li>This is being maintained manually, not through an ORM package.</li> <li>The project this relates to sits atop SQL Server (but it would be nice to see a generic solution)</li> <li>This may not have been the best example. There are a couple scenarios we can consider regarding subclassing, and I just happened to invent this student/athlete example.</li> </ul> <p>A) In true object-oriented fashion, it's possible that the superclass can exist by itself and need not be modeled in any subclasses.</p> <p>B) In real life, any object or student can have multiple roles.</p> <p>C) The particular scenario I was trying to illustrate was requiring that every object be implemented in exactly one subclass. Think of the superclass as an abstract implementation, or just commonalities factored out of otherwise disparate object classes/instances.</p> <p>Thanks to all for your input, especially Bill.</p>
[ { "answer_id": 332615, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 3, "selected": true, "text": "CHECK student_id CREATE TABLE athletes (\n student_id INT NOT NULL PRIMARY KEY,\n FOREIGN KEY (student_id) REFERENCES students(student_id),\n CHECK (student_id NOT IN (SELECT student_id FROM musicians \n UNION SELECT student_id FROM slackers \n UNION ...)) \n);\n students CREATE TABLE athletes (\n student_id INT NOT NULL PRIMARY KEY,\n student_type CHAR(4) NOT NULL CHECK (student_type = 'ATHL'),\n FOREIGN KEY (student_id, student_type) REFERENCES students(student_id, student_type)\n);\n student_type CHECK" }, { "answer_id": 333916, "author": "Dave Markle", "author_id": 24995, "author_profile": "https://Stackoverflow.com/users/24995", "pm_score": 2, "selected": false, "text": "CREATE TABLE Student (\n StudentID INT NOT NULL IDENTITY PRIMARY KEY,\n SubClass CHAR(1) NOT NULL,\n Name VARCHAR(200) NOT NULL,\n CONSTRAINT UQ_Student UNIQUE (StudentID, SubClass)\n);\n\nCREATE TABLE Athlete (\n StudentID INT NOT NULL PRIMARY KEY,\n SubClass CHAR(1) NOT NULL,\n Sport VARCHAR(200) NOT NULL,\n CONSTRAINT CHK_Jock CHECK (SubClass = 'A'),\n CONSTRAINT FK_Student_Athlete FOREIGN KEY (StudentID, Subclass) REFERENCES Student(StudentID, Subclass)\n);\n\nCREATE TABLE Musician (\n StudentID INT NOT NULL PRIMARY KEY,\n SubClass CHAR(1) NOT NULL,\n Instrument VARCHAR(200) NOT NULL,\n CONSTRAINT CHK_Band_Nerd CHECK (SubClass = 'M'),\n CONSTRAINT FK_Student_Musician FOREIGN KEY (StudentID, Subclass) REFERENCES Student(StudentID, Subclass)\n);\n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/332602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40725/" ]
332,603
<p>When I get AuthenticationStatus.Authenticated (DotNetOpenId library) response from myopenid provider, i'd like to redirect user from login page to another one using MVC Redirect(myurl). But unfortunately, instead of getting to myurl, user is redirected to empty page:</p> <p>myurl?token=AWSe9PSLwx0RnymcW0q.... (+ several kilobytes of myopenid-specific query string)</p> <p>I also tried FormsAuthentication.RedirectFromLoginPage(), but it redirects to original login page again instead of the myurl.</p> <p>Could anybody suggest proper redirection to myurl?</p> <p>Thanks</p>
[ { "answer_id": 550709, "author": "zihotki", "author_id": 66591, "author_profile": "https://Stackoverflow.com/users/66591", "pm_score": 1, "selected": false, "text": "FormsAuth.SetAuthCookie(UserName, RememberMe);\n return RedirectToAction(actionName, controllerName);\n return Redirect(url);\n" }, { "answer_id": 573944, "author": "JarrettV", "author_id": 16340, "author_profile": "https://Stackoverflow.com/users/16340", "pm_score": 0, "selected": false, "text": " FormsAuthentication.SetAuthCookie(openid.Response.ClaimedIdentifier, false);\n //FormsAuthentication.RedirectFromLoginPage(openid.Response.ClaimedIdentifier, false); <-- doesn't work\n //send back to the right page\n string returnUrl = ctx.Request.QueryString[\"ReturnUrl\"];\n if (!string.IsNullOrEmpty(returnUrl))\n {\n returnUrl = HttpUtility.UrlDecode(returnUrl);\n ctx.Response.Redirect(returnUrl);\n }\n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/332603", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
332,623
<p>I would like to implement a search engine which should crawl a set of web sites, extract specific information from the pages and create full-text index of that specific information.</p> <p>It seems to me that Xapian could be a good choice for the search engine library.</p> <p>What are the options for a crawler/parser to integrate with Xapian?</p> <p>Would Solr be a better choice than Xapian to integrate with open source crawlers/parsers?</p>
[ { "answer_id": 550709, "author": "zihotki", "author_id": 66591, "author_profile": "https://Stackoverflow.com/users/66591", "pm_score": 1, "selected": false, "text": "FormsAuth.SetAuthCookie(UserName, RememberMe);\n return RedirectToAction(actionName, controllerName);\n return Redirect(url);\n" }, { "answer_id": 573944, "author": "JarrettV", "author_id": 16340, "author_profile": "https://Stackoverflow.com/users/16340", "pm_score": 0, "selected": false, "text": " FormsAuthentication.SetAuthCookie(openid.Response.ClaimedIdentifier, false);\n //FormsAuthentication.RedirectFromLoginPage(openid.Response.ClaimedIdentifier, false); <-- doesn't work\n //send back to the right page\n string returnUrl = ctx.Request.QueryString[\"ReturnUrl\"];\n if (!string.IsNullOrEmpty(returnUrl))\n {\n returnUrl = HttpUtility.UrlDecode(returnUrl);\n ctx.Response.Redirect(returnUrl);\n }\n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/332623", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19808/" ]
332,629
<p>I've <code>rm</code>'ed a 2.5gb log file - but it doesn't seemed to have freed any space.</p> <p>I did:</p> <pre><code>rm /opt/tomcat/logs/catalina.out </code></pre> <p>then this:</p> <pre><code>df -hT </code></pre> <p>and <code>df</code> reported my <code>/opt</code> mount still at 100% used.</p> <p>Any suggestions?</p>
[ { "answer_id": 332657, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 3, "selected": false, "text": "catalina.out catalina.sh catalina.out swallowOutput catalina.out" }, { "answer_id": 332676, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 5, "selected": false, "text": "lsof /opt/tomcat/logs/catalina.out\n" }, { "answer_id": 332776, "author": "Jay", "author_id": 20840, "author_profile": "https://Stackoverflow.com/users/20840", "pm_score": 3, "selected": false, "text": "cp /dev/null /opt/tomcat/logs/catalina.out\n > /opt/tomcat/logs/catalina.out\n" }, { "answer_id": 21272566, "author": "Siwei", "author_id": 445908, "author_profile": "https://Stackoverflow.com/users/445908", "pm_score": 3, "selected": false, "text": "$ echo '' > huge_file.log \n rm log_file.log echo '' > log_file.log" }, { "answer_id": 48945282, "author": "Javeed Shakeel", "author_id": 8295551, "author_profile": "https://Stackoverflow.com/users/8295551", "pm_score": 2, "selected": false, "text": " $ sudo lsof | grep deleted\n $ sudo kill <pid>\n$ df -h\n # cd /\n# du --threshold=(SIZE)\n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/332629", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3966/" ]
332,630
<p>Let's say I have an existing System.Threading.Timer instance and I'd like to call Change on it to push it's firing time back:</p> <pre><code>var timer = new Timer(DelayCallback, null, 10000, Timeout.Infinite); // ... (sometime later but before DelayCallback has executed) timer.Change(20000, Timeout.Infinite); </code></pre> <p>I'm using this timer to perform an "idle callback" after a period of no activity. ("Idle" and "no activity" are application-defined conditions in this case...the specifics aren't terribly important.) Every time I perform an "action", I want to reset the timer so that it is always set to fire 10 seconds after that.</p> <p>However, there is an inherent race condition because when I call Change, I can't tell if the Timer has already fired based on its old settings. (I can, of course, tell if my callback has happened but I can't tell if the CLR's internal timer thread has queued my callback to the threadpool and its execution is imminent.)</p> <p>Now I know I can call Dispose on the timer instance and re-create it each time I need to "push it back". but this <em>seems</em> less efficient than just changing the existing timer. Of course it <em>may</em> not be...I'll run some micro-benchmarks in a bit and let you all know.</p> <p>Alternatively, I can always keep track of the expected firing time (via DateTime.Now.AddSeconds(10)) and, if the original Timer fires, ignore it by checking DateTime.Now in the callback. (I have a nagging concern that this may not be 100% reliable on account of the Timer using TimeSpan and my check using DateTime...this may not be an issue but I'm not completely comfortable with it for some reason...)</p> <p>My questions are:</p> <ol> <li>Is there a good way for me to call Timer.Change and be able to know whether I managed to change it before the callback was queued to the threadpool? (I don't think so, but it doesn't hurt to ask...)</li> <li>Has anyone else implemented (what I term) a "pushback timer" like this? If so, I'd love to hear how you tackled the problem.</li> </ol> <p>This question is somewhat hypothetical in nature since I already have a couple of working solutions (based on Dispose and based on DateTime.Now)...I'm mainly interested in hearing performance-related suggestions (as I'll be "pushing back" the Timer VERY frequently).</p> <p>Thanks!</p>
[ { "answer_id": 332677, "author": "Timothy Khouri", "author_id": 11917, "author_profile": "https://Stackoverflow.com/users/11917", "pm_score": 0, "selected": false, "text": "while (sleepyTime > 0)\n{\n int temp = sleepyTime;\n sleepyTime = 0;\n Thread.Sleep(temp);\n}\n\n// here's where your actual code is.\n" }, { "answer_id": 332775, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 1, "selected": false, "text": "System.Windows.Forms.Application.Idle\n" }, { "answer_id": 335884, "author": "notso", "author_id": 41884, "author_profile": "https://Stackoverflow.com/users/41884", "pm_score": 1, "selected": false, "text": "public delegate void IdleCallback();\npublic interface IdleNotifier\n{\n // Called by threadpool when more than IdleTimeSpanBeforeCallback \n // has passed since last call on ActionOccured.\n IdleCallback Callback { set; }\n TimeSpan IdleTimeSpanBeforeCallback { set; }\n void ActionOccured();\n}\n public class IdleNotifierTimerImplementation : IdleNotifier\n{\n private readonly object SyncRoot = new object();\n private readonly Timer m_Timer;\n\n private IdleCallback m_IdleCallback = null;\n private TimeSpan m_IdleTimeSpanBeforeEvent = TimeSpan.Zero;\n\n // Null means there has been no action since last idle notification.\n private DateTime? m_LastActionTime = null;\n\n public IdleNotifierTimerImplementation()\n {\n m_Timer = new Timer(OnTimer);\n }\n\n private void OnTimer(object unusedState)\n {\n lock (SyncRoot)\n {\n if (m_LastActionTime == null)\n {\n m_Timer.Change(m_IdleTimeSpanBeforeEvent, TimeSpan.Zero);\n return;\n }\n TimeSpan timeSinceLastUpdate = DateTime.UtcNow - m_LastActionTime.Value;\n if (timeSinceLastUpdate > TimeSpan.Zero)\n {\n // We are no idle yet.\n m_Timer.Change(timeSinceLastUpdate, TimeSpan.Zero);\n return;\n }\n m_LastActionTime = null;\n m_Timer.Change(m_IdleTimeSpanBeforeEvent, TimeSpan.Zero);\n }\n if (m_IdleCallback != null)\n {\n m_IdleCallback();\n }\n }\n\n // IdleNotifier implementation below\n\n public void ActionOccured()\n {\n lock (SyncRoot)\n {\n m_LastActionTime = DateTime.UtcNow;\n }\n }\n\n public IdleCallback Callback\n {\n set\n {\n lock (SyncRoot)\n {\n m_IdleCallback = value;\n }\n }\n }\n\n public TimeSpan IdleTimeSpanBeforeCallback\n {\n set\n {\n lock (SyncRoot)\n {\n m_IdleTimeSpanBeforeEvent = value;\n // Run OnTimer immediately\n m_Timer.Change(TimeSpan.Zero, TimeSpan.Zero);\n }\n }\n }\n}\n" } ]
2008/12/01
[ "https://Stackoverflow.com/questions/332630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42286/" ]
332,651
<p>I know how to set up a local webserver using xampp on windows... I enter my alias and target on the hosts file (c:\windows\system32\drivers\etc\hosts) and then add a respective entry on my apache vhosts config file. This way, assuming that my webserver is listening to port 80, I can for example map <code>example.com</code> to my local webserver.</p> <p>I've always entered the whole domain name (that is e.g. example.com) in my hosts file and any requests on that name would be directed to localhost.</p> <p>Now I was wondering if there's a way to <strong>only forward example.com on a certain port</strong> (for example only example.com:8080) to the local webserver, and leave example.com (on the default port 80) alone, so that it would still go to my live production website.</p> <p>As far as I understand this might not be possible using only the hosts file (I tried adding the port :8080 to my domain names - didn't seem work ;-) )...</p> <p>I really don't know much on this topic so any ideas, insights, links, reading material, tools are welcome. </p> <p>Edit: Arnout's reply answers the question I've asked above but doesn't solve my actual problem. Rerouting example.com:8080 to localhost:80 does work and if I access example.com it loads up the frontpage of my local version, but all links on that page of course don't know about the port number and therefore point to the production version... The actual solution to my problem seems to be to bite into the sour apple and <em>fix</em> my application (following Rob's suggestion) and remove all hardcoded urls, so that it works on any domain...</p>
[ { "answer_id": 333552, "author": "Arnout", "author_id": 3496, "author_profile": "https://Stackoverflow.com/users/3496", "pm_score": 3, "selected": true, "text": "example.com:8080 localhost:80 . .\n sforward.ini forwardfile junkbstr.ini" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/332651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5005/" ]
332,653
<p>I'm trying to figure out a method of connecting from C# code to a digital scale. The particular scale is an Ohaus SP202 digital scale which comes with a USB connection. I would like to read the weight measured on the scale programmatically. I don't have the scale yet, I'm just doing the research before hand.</p> <p>Has anyone done this before? I've been doing research on the internet and didn't find anything worth mentioning yet.</p>
[ { "answer_id": 66222210, "author": "Christian Findlay", "author_id": 1878141, "author_profile": "https://Stackoverflow.com/users/1878141", "pm_score": 0, "selected": false, "text": "using Device.Net;\nusing Device.Net.Windows;\nusing Microsoft.Extensions.Logging;\nusing Microsoft.Extensions.Logging.Abstractions;\nusing Microsoft.Win32.SafeHandles;\nusing System;\nusing System.IO;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace SerialPort.Net.Windows\n{\n public class WindowsSerialPortDevice : DeviceBase, IDevice\n {\n #region Fields\n private readonly int _BaudRate;\n private readonly byte _ByteSize;\n private bool disposed;\n private readonly Parity _Parity;\n private SafeFileHandle _ReadSafeFileHandle;\n private readonly StopBits _StopBits;\n private ushort ReadBufferSize { get; }\n #endregion\n\n #region Public Properties\n public bool IsInitialized => _ReadSafeFileHandle != null && !_ReadSafeFileHandle.IsInvalid;\n /// <summary>\n /// TODO: No need to implement this. The property probably shouldn't exist at the base level\n /// </summary>\n public IApiService ApiService { get; }\n public ConnectedDeviceDefinition ConnectedDeviceDefinition { get; private set; }\n #endregion\n\n #region Constructor\n public WindowsSerialPortDevice(\n string deviceId,\n int baudRate = 9600,\n StopBits stopBits = StopBits.One,\n Parity parity = Parity.None,\n byte byteSize = 8,\n ushort readBufferSize = 1024,\n ILoggerFactory loggerFactory = null,\n IApiService apiService = null) : base(\n deviceId,\n loggerFactory,\n (loggerFactory ?? NullLoggerFactory.Instance).CreateLogger<WindowsSerialPortDevice>())\n {\n ApiService = apiService ?? new ApiService(null);\n\n ConnectedDeviceDefinition = new ConnectedDeviceDefinition(DeviceId, DeviceType.SerialPort);\n\n if ((byteSize == 5 && stopBits == StopBits.Two) || (stopBits == StopBits.OnePointFive && byteSize > 5))\n throw new ArgumentException(Messages.ErrorInvalidByteSizeAndStopBitsCombo);\n\n if (byteSize is < 5 or > 8)\n throw new ArgumentOutOfRangeException(nameof(byteSize), Messages.ErrorByteSizeMustBeFiveToEight);\n\n if (baudRate is < 110 or > 256000)\n throw new ArgumentOutOfRangeException(nameof(baudRate), Messages.ErrorBaudRateInvalid);\n\n if (stopBits == StopBits.None)\n throw new ArgumentException(Messages.ErrorMessageStopBitsMustBeSpecified, nameof(stopBits));\n\n ReadBufferSize = readBufferSize;\n _BaudRate = baudRate;\n _ByteSize = byteSize;\n _StopBits = stopBits;\n _Parity = parity;\n }\n #endregion\n\n #region Public Methods\n public Task InitializeAsync(CancellationToken cancellationToken = default) => Task.Run(Initialize, cancellationToken);\n\n private uint Write(byte[] data) => data == null ? 0 : ApiService.AWriteFile(_ReadSafeFileHandle, data, data.Length, out var bytesWritten, 0) ? (uint)bytesWritten : 0;\n\n public override Task<uint> WriteAsync(byte[] data, CancellationToken cancellationToken = default)\n {\n ValidateConnection();\n return Task.Run(() =>\n {\n var bytesWritten = Write(data);\n Logger.LogDataTransfer(new Trace(false, data));\n return bytesWritten;\n }, cancellationToken);\n }\n\n public override Task<TransferResult> ReadAsync(CancellationToken cancellationToken = default)\n {\n ValidateConnection();\n\n return Task.Run(() =>\n {\n var buffer = new byte[ReadBufferSize];\n var bytesRead = Read(buffer);\n var transferResult = new TransferResult(buffer, bytesRead);\n Logger.LogDataTransfer(new Trace(false, transferResult));\n return transferResult;\n }, cancellationToken);\n }\n\n public override Task Flush(CancellationToken cancellationToken = default)\n {\n ValidateConnection();\n\n return Task.Run(() => ApiService.APurgeComm(_ReadSafeFileHandle, APICalls.PURGE_RXCLEAR | APICalls.PURGE_TXCLEAR),\n cancellationToken);\n }\n\n public override void Dispose()\n {\n if (disposed)\n {\n Logger.LogWarning(Messages.WarningMessageAlreadyDisposed, DeviceId);\n return;\n }\n\n disposed = true;\n\n Logger.LogInformation(Messages.InformationMessageDisposingDevice, DeviceId);\n\n if (_ReadSafeFileHandle != null)\n {\n _ReadSafeFileHandle.Dispose();\n _ReadSafeFileHandle = new SafeFileHandle((IntPtr)0, true);\n }\n\n base.Dispose();\n }\n\n public void Close() => Dispose();\n #endregion\n\n #region Private Methods\n private void Initialize()\n {\n _ReadSafeFileHandle = ApiService.CreateReadConnection(DeviceId, FileAccessRights.GenericRead | FileAccessRights.GenericWrite);\n\n if (_ReadSafeFileHandle.IsInvalid) return;\n\n var dcb = new Dcb();\n\n var isSuccess = ApiService.AGetCommState(_ReadSafeFileHandle, ref dcb);\n\n _ = WindowsHelpers.HandleError(isSuccess, Messages.ErrorCouldNotGetCommState, Logger);\n\n dcb.ByteSize = _ByteSize;\n dcb.fDtrControl = 1;\n dcb.BaudRate = (uint)_BaudRate;\n dcb.fBinary = 1;\n dcb.fTXContinueOnXoff = 0;\n dcb.fAbortOnError = 0;\n\n dcb.fParity = 1;\n#pragma warning disable IDE0010 // Add missing cases\n dcb.Parity = _Parity switch\n {\n Parity.Even => 2,\n Parity.Mark => 3,\n Parity.Odd => 1,\n Parity.Space => 4,\n Parity.None => 0,\n _ => 0\n };\n\n dcb.StopBits = _StopBits switch\n {\n StopBits.One => 0,\n StopBits.OnePointFive => 1,\n StopBits.Two => 2,\n StopBits.None => throw new ArgumentException(Messages.ErrorMessageStopBitsMustBeSpecified),\n _ => throw new ArgumentException(Messages.ErrorMessageStopBitsMustBeSpecified),\n };\n#pragma warning restore IDE0010 // Add missing cases\n\n isSuccess = ApiService.ASetCommState(_ReadSafeFileHandle, ref dcb);\n _ = WindowsHelpers.HandleError(isSuccess, Messages.ErrorCouldNotSetCommState, Logger);\n\n var timeouts = new CommTimeouts\n {\n WriteTotalTimeoutConstant = 0,\n ReadIntervalTimeout = 1,\n WriteTotalTimeoutMultiplier = 0,\n ReadTotalTimeoutMultiplier = 0,\n ReadTotalTimeoutConstant = 0\n };\n\n isSuccess = ApiService.ASetCommTimeouts(_ReadSafeFileHandle, ref timeouts);\n _ = WindowsHelpers.HandleError(isSuccess, Messages.ErrorCouldNotSetCommTimeout, Logger);\n\n Logger.LogInformation(\"Serial Port device initialized successfully. Port: {port}\", DeviceId);\n }\n\n private uint Read(byte[] data)\n =>\n ApiService.AReadFile(_ReadSafeFileHandle, data, data.Length, out var bytesRead, 0)\n ? bytesRead\n : throw new IOException(Messages.ErrorMessageRead);\n\n\n private void ValidateConnection()\n {\n if (!IsInitialized)\n {\n throw new InvalidOperationException(Messages.ErrorMessageNotInitialized);\n }\n }\n #endregion\n }\n}\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/332653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
332,668
<p>How to figure out if a table is in use in SQL (on any type database)? if somebody is already using it, or have it "open" then its in use.</p>
[ { "answer_id": 341881, "author": "igorgue", "author_id": 29253, "author_profile": "https://Stackoverflow.com/users/29253", "pm_score": 1, "selected": true, "text": "select spid\n from master..sysprocesses\n where dbid = db_id('Works') and spid <> @@spid\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/332668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29253/" ]
332,681
<p>Greetings!</p> <p>I'm calling a Web service from Javascript when a user clicks on a link. I need to get the coordinates where the user clicked so that I can display a DIV in an appropriate location. My client-side script looks like the following:</p> <pre><code>var g_event; function DoWork(event, theId) { if (IsIE()) g_event = window.event; else g_event = event; Acme.WebServices.Worker.GetInformation(theId, DoWorkSuccess); } function DoWorkSuccess(result) { var l_elemDiv = document.getElementById("content-area-div"); DisplayAreaDiv(g_event, l_elemDiv, result); } </code></pre> <p>It's used like this:</p> <pre><code>&lt;a href="" onclick="DoWork(event, "help");"&gt;Help&lt;/a&gt; </code></pre> <p>This works great in Firefox, Safari, and Opera. In IE7, not so much. For example, if I place the following code at the end of both the DoWork() and DoWorkSuccess() functions:</p> <pre><code>alert(g_event.clientX + ", " + g_event.clientY); </code></pre> <p>In IE, I'll get two alerts; the first one has correct coordinates, but the second one (which displays on top of the first one) is simply "[object]". Since that "[object]" one is the last one, my DIV is incorrectly displayed in the top left of the browser window. Is there a way I can prevent IE from giving me a second "bad" event? Thanks.</p>
[ { "answer_id": 332843, "author": "Nathaniel Reinhart", "author_id": 41122, "author_profile": "https://Stackoverflow.com/users/41122", "pm_score": 0, "selected": false, "text": "window.event.cancelBubble = true" }, { "answer_id": 332879, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 2, "selected": true, "text": "var client_x;\nvar client_y;\n\nfunction DoWork(event, theId) \n{\n var g_event;\n if (IsIE())\n g_event = window.event;\n else\n g_event = event;\n\n client_x = g_event.clientX;\n client_y = g_event.clientY;\n\n Acme.WebServices.Worker.GetInformation(theId, DoWorkSuccess);\n}\n\nfunction DoWorkSuccess(result) \n{\n var l_elemDiv = document.getElementById(\"content-area-div\");\n DisplayAreaDiv( { clientX : client_x, clientY : client_y }, l_elemDiv, result);\n}\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/332681", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27870/" ]
332,697
<p><strong>This problem has been solved thanks to your suggestions.</strong> See the bottom for details. Thanks very much for your help!</p> <p>Our ASP.NET website is accessed from several specific and highly secure international locations. It has been operating fine, but we have added another client location which is exhibiting very strange behaviour.</p> <p>In particular, when the user enters search criteria and clicks the search button the result list returns empty. It doesn't even show the '0 results returned' text, so it is as if the Repeater control did not bind at all. Similar behaviour appears in some, but not all, other parts of the site. The user is able to log in to the site fine and their profile information is displayed. </p> <p>I have logged in to the site locally using exactly the same credentials as them and the site works well from here. We have gone through the steps carefully so I am confident it is not a user issue.</p> <p>I bind the search results in the Page_Load of the search results page the first time it is loaded (the criteria is in the query string). i.e.</p> <pre><code>if (!IsPostBack) { BindResults(); } </code></pre> <p>I can replicate exactly the same behaviour locally by commenting out the BindResults() method call. </p> <p>Does anybody know how the value of IsPostBack is calculated? Is it possible that their highly-secure firewall setup would cause IsPostBack to always return true, even when it is a redirect from another page? That could be a red herring as the problem might be elsewhere. It does exactly replicate the result though.</p> <p>I have no access to the site, so troubleshooting is restricted to giving them instructions and asking for them to tell me the result.</p> <p>Thanks for your time!</p> <p>Appended info: Client is behind a Microsoft ISA 2006 firewall running default rules. The site has been added to the Internet Explorer trusted sites list and tried in FireFox and Google Chrome, all with the same result.</p> <p><strong>SOLUTION</strong>: The winner for me was the suggestion to use Fiddler. What an excellent tool that no web developer should be without. Using this I was able to strip various headers from the request until I reproduced the problem. There were actually two factors that caused this bug, as is so often the case with such confusing issues.</p> <p>Factor one – Where possible the web application uses GZIP compression as supported by all major browsers. The firewall was stripping off the header that specifies GZIP decompression support (Accept-Encoding: gzip, deflate). </p> <p>Factor two – A bug in my code meant that some processing was bypassed when the content was being sent uncompressed. This problem was not noticed before because the application is used by a limited audience, all of which supported GZIP decompression.</p>
[ { "answer_id": 334130, "author": "Turnkey", "author_id": 13144, "author_profile": "https://Stackoverflow.com/users/13144", "pm_score": 1, "selected": false, "text": "foreach (string key in Request.Form)\n{\n Response.Write(\"<br>\" + key + \"=\" + Request.Form[key]);\n}\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/332697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20118/" ]
332,700
<p>I've got a whole host of values stored in a .net 2.0 hashtable. What I would really like to find is a way to, essentially, do a SQL select statement on the table.</p> <p>Meaning, I'd like to get a list of keys whose associated values match a very simple text pattern (along the lines of "starts with a number".)</p> <p>The final goal will be to remove these records from the hashtable for further processing.</p> <p>I've been beating my head against this for a while now, and I can't seem to come up with anything.</p> <p>Any ideas?</p> <p>(On the off chance this matters: due to the realities of this project, any 3rd party widgets or upgrading to a more recent version of .net are off the table.)</p>
[ { "answer_id": 332706, "author": "Nathan W", "author_id": 6335, "author_profile": "https://Stackoverflow.com/users/6335", "pm_score": 3, "selected": true, "text": " static void Main(string[] args)\n {\n Hashtable myhashtable = new Hashtable();\n myhashtable.Add(\"Teststring\", \"Hello\");\n myhashtable.Add(\"1TestString1\", \"World\");\n myhashtable.Add(\"2TestString2\", \"Test\");\n\n List<String> newht = new List<String>;\n\n //match all strings with a number at the front\n Regex rx = new Regex(\"^[1-9]\");\n foreach (string key in myhashtable.Keys)\n {\n if (rx.IsMatch(key) == true)\n {\n newht.Add(key);\n }\n }\n\n //Loop through all the keys in the new collection and remove them from\n //them from the main hashtable.\n foreach (string key in newht)\n {\n myhashtable.Remove(key);\n }\n }\n Hashtable myhashtable = new Hashtable();\n myhashtable.Add(\"Teststring\", \"Hello\");\n myhashtable.Add(\"1TestString1\", \"World\");\n myhashtable.Add(\"2TestString2\", \"Test\");\n\n Regex rx = new Regex(\"^[1-9]\");\n var k = (from string key in myhashtable.Keys\n where rx.IsMatch(key)\n select key).ToList();\n\n k.ForEach(s => myhashtable.Remove(s));\n" }, { "answer_id": 332774, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 2, "selected": false, "text": " List<string> keysToRemove = new List<string>( myhashtable.Count );\n foreach (string key in myhashtable.Keys)\n {\n if (char.IsDigit(key[0])\n {\n keysToRemove.Add(key);\n }\n }\n\n foreach (string key in keysToRemove)\n {\n myhashtable.Remove(key);\n }\n" }, { "answer_id": 332807, "author": "Stefan", "author_id": 19307, "author_profile": "https://Stackoverflow.com/users/19307", "pm_score": 1, "selected": false, "text": "Dim myhashtable As New Hashtable\n myhashtable.Add(\"Teststring\", \"Hello\")\n myhashtable.Add(\"1TestString1\", \"World\")\n myhashtable.Add(\"2TestString2\", \"Test\")\n\nFor Each i As String In From Element In myhashtable.Cast(Of DictionaryEntry)() Let k = DirectCast(Element.Value, String) Where k.StartsWith(\"W\") Select DirectCast(Element.Key, String)\n MsgBox(\"This key has a matching value:\" & i)\n Next\n Dim d = New Dictionary(Of String, String)()\n d.Add(\"Teststring\", \"Hello\")\n d.Add(\"1TestString1\", \"World\")\n d.Add(\"2TestString2\", \"Test\")\n\n For Each i As String In From element In d Where element.Value.StartsWith(\"W\") Select element.Key\n MsgBox(\"This key has a matching value:\" & i)\n Next\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/332700", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19074/" ]
332,701
<p>I'm dealing with a large group of entities that store locations. They are displayed on a map. I'm trying to come up with an efficient way to group near located entities into one entity when viewed from a higher location. So, for example, if you are very high, when looking down, you will see one entity that represents a group of closely located entities in an area. Zooming in close enough would split that entity out into its contained entities.</p> <p>Is there an efficient algorithm for doing this? I thought about just griding off the view based on height and dropping entities into grid boxes based on location then rendering the box point. My only concern is if all the entities are in the upper right of that box, the entity rendered to represent them might be centered in the middle instead of the location of the group of entities.</p> <p>Any thoughts or ideas?</p>
[ { "answer_id": 332706, "author": "Nathan W", "author_id": 6335, "author_profile": "https://Stackoverflow.com/users/6335", "pm_score": 3, "selected": true, "text": " static void Main(string[] args)\n {\n Hashtable myhashtable = new Hashtable();\n myhashtable.Add(\"Teststring\", \"Hello\");\n myhashtable.Add(\"1TestString1\", \"World\");\n myhashtable.Add(\"2TestString2\", \"Test\");\n\n List<String> newht = new List<String>;\n\n //match all strings with a number at the front\n Regex rx = new Regex(\"^[1-9]\");\n foreach (string key in myhashtable.Keys)\n {\n if (rx.IsMatch(key) == true)\n {\n newht.Add(key);\n }\n }\n\n //Loop through all the keys in the new collection and remove them from\n //them from the main hashtable.\n foreach (string key in newht)\n {\n myhashtable.Remove(key);\n }\n }\n Hashtable myhashtable = new Hashtable();\n myhashtable.Add(\"Teststring\", \"Hello\");\n myhashtable.Add(\"1TestString1\", \"World\");\n myhashtable.Add(\"2TestString2\", \"Test\");\n\n Regex rx = new Regex(\"^[1-9]\");\n var k = (from string key in myhashtable.Keys\n where rx.IsMatch(key)\n select key).ToList();\n\n k.ForEach(s => myhashtable.Remove(s));\n" }, { "answer_id": 332774, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 2, "selected": false, "text": " List<string> keysToRemove = new List<string>( myhashtable.Count );\n foreach (string key in myhashtable.Keys)\n {\n if (char.IsDigit(key[0])\n {\n keysToRemove.Add(key);\n }\n }\n\n foreach (string key in keysToRemove)\n {\n myhashtable.Remove(key);\n }\n" }, { "answer_id": 332807, "author": "Stefan", "author_id": 19307, "author_profile": "https://Stackoverflow.com/users/19307", "pm_score": 1, "selected": false, "text": "Dim myhashtable As New Hashtable\n myhashtable.Add(\"Teststring\", \"Hello\")\n myhashtable.Add(\"1TestString1\", \"World\")\n myhashtable.Add(\"2TestString2\", \"Test\")\n\nFor Each i As String In From Element In myhashtable.Cast(Of DictionaryEntry)() Let k = DirectCast(Element.Value, String) Where k.StartsWith(\"W\") Select DirectCast(Element.Key, String)\n MsgBox(\"This key has a matching value:\" & i)\n Next\n Dim d = New Dictionary(Of String, String)()\n d.Add(\"Teststring\", \"Hello\")\n d.Add(\"1TestString1\", \"World\")\n d.Add(\"2TestString2\", \"Test\")\n\n For Each i As String In From element In d Where element.Value.StartsWith(\"W\") Select element.Key\n MsgBox(\"This key has a matching value:\" & i)\n Next\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/332701", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9450/" ]
332,703
<p>I have a 3-leveled hierarchy of entities: Customer-Order-Line, which I would like to retrieve in entirety for a given customer, using ISession.Get(id). I have the following XML fragments:</p> <p>customer.hbm.xml:</p> <pre><code>&lt;bag name="Orders" cascade="all-delete-orphan" inverse="false" fetch="join"&gt; &lt;key column="CustomerID" /&gt; &lt;one-to-many class="Order" /&gt; &lt;/bag&gt; </code></pre> <p>order.hbm.xml:</p> <pre><code>&lt;bag name="Lines" cascade="all-delete-orphan" inverse="false" fetch="join"&gt; &lt;key column="OrderID" /&gt; &lt;one-to-many class="Line" /&gt; &lt;/bag&gt; </code></pre> <p>I have used the fetch="join" attribute to indicate that I want to fetch the child entities for each parent, and this has constructed the correct SQL:</p> <pre><code>SELECT customer0_.ID AS ID8_2_, customer0_.Name AS Name8_2_, orders1_.CustomerID AS CustomerID__4_, orders1_.ID AS ID4_, orders1_.ID AS ID9_0_, orders1_.PostalAddress AS PostalAd2_9_0_, orders1_.OrderDate AS OrderDate9_0_, lines2_.OrderID AS OrderID__5_, lines2_.ID AS ID5_, lines2_.ID AS ID10_1_, lines2_.[LineNo] AS column2_10_1_, lines2_.Quantity AS Quantity10_1_, lines2_.ProductID AS ProductID10_1_ FROM Customer customer0_ LEFT JOIN [Order] orders1_ ON customer0_.ID=orders1_.CustomerID LEFT JOIN Line lines2_ ON orders1_.ID=lines2_.OrderID WHERE customer0_.ID=1 </code></pre> <p>So far, this looks good - SQL returns the correct set of records (with only one distinct orderid), but when I run a test to confirm the correct number of entities (from NH) for Orders and Lines, I get the wrong results</p> <p>I <em>should</em> be getting (from my test data), 1xOrder and 4xLine, however, I am getting 4xOrder and 4xLine. It appears that NH is not recognising the 'repeating' group of Order information in the result set, nor correctly 'reusing' the Order entity.</p> <p>I am using all integer IDs (PKs), and I've tried implementing IComparable of T and IEquatable of T using this ID, in the hope that NH will see the equality of these entities. I've also tried overridding Equals and GetHashCode to use the ID. Neither of these 'attempts' have succeeded.</p> <p>Is "multiple leveled fetch" a supported operation for NH, and if so, is there an XML setting required (or some other mechanism) to support it?</p> <hr> <p>NB: I used sirocco's solution with a few changes to my own code to finally solve this one. the xml needs to be changed from bag to set, for all collections, and the entitities themselves were changed to implement IComparable&lt;>, which is a requirement of a set for uniqueness to be established.</p> <pre><code>public class BaseEntity : IComparable&lt;BaseEntity&gt; { ... private Guid _internalID { get; set; } public virtual Guid ID { get; set; } public BaseEntity() { _internalID = Guid.NewGuid(); } #region IComparable&lt;BaseEntity&gt; Members public int CompareTo( BaseEntity other ) { if ( ID == Guid.Empty || other.ID == Guid.Empty ) return _internalID.CompareTo( other._internalID ); return ID.CompareTo( other.ID ); } #endregion ... } </code></pre> <p>Note the use of an InternalID field. This is required for new (transient) entities, other wise they won't have an ID initially (my model has them supplied when saved).</p>
[ { "answer_id": 333382, "author": "Tigraine", "author_id": 21699, "author_profile": "https://Stackoverflow.com/users/21699", "pm_score": 3, "selected": false, "text": "session.CreateCriteria(typeof(Post))\n .SetFetchMode(\"Comments\", FetchMode.Eager)\n .List();\n" }, { "answer_id": 368259, "author": "sirrocco", "author_id": 5246, "author_profile": "https://Stackoverflow.com/users/5246", "pm_score": 5, "selected": true, "text": ".SetResultTransformer(new DistinctRootEntityResultTransformer())\n" }, { "answer_id": 1280239, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "public override IEnumerable<Baseline> GetAll()\n{\n var baselines = Session.CreateQuery(@\" from Baseline b\n left join fetch b.BaselineMilestones bm\n left join fetch bm.BaselineMilestonePrevious \")\n .SetResultTransformer(Transformers.DistinctRootEntity)\n .List<Baseline>();\n return baselines;\n}\n" }, { "answer_id": 8263587, "author": "Mark Foreman", "author_id": 120297, "author_profile": "https://Stackoverflow.com/users/120297", "pm_score": 1, "selected": false, "text": "var temp = session.CreateCriteria( typeof( Order ) )\n .SetFetchMode( \"Lines\", NHibernate.FetchMode.Eager )\n .Add( Expression.Eq( \"Customer.ID\", id ) )\n .List();\n\nvar customer = session.CreateCriteria( typeof( Customer ) )\n .SetFetchMode( \"Orders\", NHibernate.FetchMode.Eager )\n .Add( Expression.Eq( \"ID\", id ) )\n .UniqueResult();\n" } ]
2008/12/02
[ "https://Stackoverflow.com/questions/332703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2918/" ]