qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
369,994
<p>I would like to log changes made to all fields in a table to another table. This will be used to keep a history of all the changes made to that table (Your basic change log table).</p> <p>What is the best way to do it in SQL Server 2005?</p> <p>I am going to assume the logic will be placed in some Triggers.</p> <p>What is a good way to loop through all the fields checking for a change without hard coding all the fields? </p> <p>As you can see from my questions, example code would be veeery much appreciated.</p> <p>I noticed SQL Server 2008 has a new feature called Change Data Capture (CDC). (Here is a nice <a href="http://channel9.msdn.com/posts/ashishjaiman/CDC-Change-Data-Capture-SQL-Server-2008/" rel="nofollow noreferrer">Channel9</a> video on CDC). This is similar to what we are looking for except we are using SQL Server 2005, already have a Log Table layout in-place and are also logging the user that made the changes. I also find it hard to justify writing out the before and after image of the whole record when one field might change. </p> <p>Our current log file structure in place has a column for the Field Name, Old Data, New Data.</p> <p>Thanks in advance and have a nice day.</p> <p><strong>Updated 12/22/08:</strong> I did some more research and found these two answers on <a href="http://qna.live.com/" rel="nofollow noreferrer">Live Search QnA</a></p> <ol> <li><p>You can create a trigger to do this. See <a href="http://web.archive.org/web/20071006100909/http://sqlserver2000.databases.aspfaq.com:80/how-do-i-audit-changes-to-sql-server-data.html" rel="nofollow noreferrer">How do I audit changes to sq​l server data</a>.</p></li> <li><p>You can use triggers to log the data changes into the log tables. You can also purchase Log Explorer from <a href="http://www.lumigent.com" rel="nofollow noreferrer">www.lumigent.com</a> and use that to read the transaction log to see what user made the change. The database needs to be in full recovery for this option however.</p></li> </ol> <p><strong>Updated 12/23/08:</strong> I also wanted a clean way to compare what changed and this looked like the reverse of a PIVOT, which I found out in SQL is called UNPIVOT. I am now leaning towards a Trigger using UNPIVOT on the INSERTED and DELETED tables. I was curious if this was already done so I am going through a search on "<a href="http://www.google.com/search?hl=en&amp;sa=X&amp;oi=spell&amp;resnum=1&amp;ct=result&amp;cd=1&amp;q=unpivot+deleted+inserted&amp;spell=1" rel="nofollow noreferrer">unpivot deleted inserted</a>".</p> <ol> <li>Posting <a href="http://social.msdn.microsoft.com/forums/en-US/sqlgetstarted/thread/2910645b-82b2-4dec-8286-553ae5eaa1cc/" rel="nofollow noreferrer">Using update function from an after trigger</a> had some different ideas but I still believe UNPIVOT is going to be the route to go.</li> </ol>
[ { "answer_id": 370049, "author": "NotMe", "author_id": 2424, "author_profile": "https://Stackoverflow.com/users/2424", "pm_score": 2, "selected": false, "text": "INSERT INTO mytable(description, phone)\nOUTPUT INSERTED.description, INSERTED.phone INTO #TempTable\nVALUES('blah', '1231231234')\n" } ]
2008/12/15
[ "https://Stackoverflow.com/questions/369994", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4964/" ]
370,001
<p>The docs for <a href="http://msdn.microsoft.com/en-us/library/bb347013.aspx" rel="noreferrer">Dictionary.TryGetValue</a> say:</p> <blockquote> <p>When this method returns, [the value argument] contains the value associated with the specified key, if the key is found; otherwise, the <strong>default value for the type of the value parameter</strong>. This parameter is passed uninitialized.</p> </blockquote> <p>I need to mimic this in my class. <em>How do I find the default value for type T?</em></p> <hr> <p>How can this question be modified to make it show up in the search?</p> <p>Exact duplicate of <a href="https://stackoverflow.com/questions/367378/returning-a-default-value-c">Returning a default value. (C#)</a></p>
[ { "answer_id": 370006, "author": "Szymon Rozga", "author_id": 7583, "author_profile": "https://Stackoverflow.com/users/7583", "pm_score": 4, "selected": false, "text": "default(T);\n" }, { "answer_id": 370009, "author": "Nathan W", "author_id": 6335, "author_profile": "https://Stackoverflow.com/users/6335", "pm_score": 8, "selected": true, "text": "default(T);\n public T Foo<T>(T Bar)\n{\n return default(T);\n}\n" }, { "answer_id": 370012, "author": "Darin Dimitrov", "author_id": 29407, "author_profile": "https://Stackoverflow.com/users/29407", "pm_score": 3, "selected": false, "text": "T t = default(T)\n" } ]
2008/12/15
[ "https://Stackoverflow.com/questions/370001", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1343/" ]
370,004
<p>Using Java, I need to encode a Map&lt;String, String&gt; of name value pairs to store into a String, and be able to decode it again. These will be stored in a database column, and will probably usually be short and simple, so the common case should produce a simple nice looking line, but shouldn't corrupt the data, even if it contains unexpected characters, etc.</p> <p>How would you choose to do it such that:</p> <ul> <li>The encoded form is a single, human readable line</li> <li>It doesn't require a big library or much context to encode / decode</li> <li>Any delimeters are properly escaped</li> </ul> <p>Url encoding? JSON? Do it yourself? Please specify any helper libraries or methods you'd use.</p> <p>(Edited to specify more context and requirements as requested.)</p>
[ { "answer_id": 370039, "author": "Dan Vinton", "author_id": 21849, "author_profile": "https://Stackoverflow.com/users/21849", "pm_score": 3, "selected": false, "text": "Map<String, String> key1|value1|key2|value2\n { first_key => first_value, \n second_key => second_value }\n <map>\n <entry key='foo' value='bar'/>\n <entry key='this' value='that'/>\n</map>\n CREATE TABLE StringMaps \n(\n map_id NUMBER NOT NULL, -- ditch this if you only store one map...\n key VARCHAR2 NOT NULL,\n value VARCHAR2\n);\n" }, { "answer_id": 372083, "author": "alepuzio", "author_id": 45745, "author_profile": "https://Stackoverflow.com/users/45745", "pm_score": 0, "selected": false, "text": "key1+SEPARATOR+value1+SEPARATOR+key2 etc key1+SEPARATOR_KEY_AND_VALUE+value1+SEPARATOR_KEY(n)_AND_KEY(N+1)+key2 etc" }, { "answer_id": 1512328, "author": "corlettk", "author_id": 69224, "author_profile": "https://Stackoverflow.com/users/69224", "pm_score": 0, "selected": false, "text": "name=\"value\" name=\"value\" name=\"value\"\n String xmlString += \"<arbitraryAttributes\" + arbitraryAttributesString + \" />\"\n" } ]
2008/12/15
[ "https://Stackoverflow.com/questions/370004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3093/" ]
370,013
<p>Using jQuery, how do I delete all rows in a table except the first? This is my first attempt at using index selectors. If I understand the examples correctly, the following should work:</p> <pre><code>$(some table selector).remove("tr:gt(0)"); </code></pre> <p>which I would read as "Wrap some table in a jQuery object, then remove all 'tr' elements (rows) where the element index of such rows is greater than zero". In reality, it executes without generating an error, but doesn't remove any rows from the table.</p> <p>What am I missing, and how do I fix this? Of course, I could use straight javascript, but I'm having so much fun with jQuery that I'd like to solve this using jQuery.</p>
[ { "answer_id": 370031, "author": "Strelok", "author_id": 2788, "author_profile": "https://Stackoverflow.com/users/2788", "pm_score": 10, "selected": true, "text": "$(document).ready(function() {\n $(\"someTableSelector\").find(\"tr:gt(0)\").remove();\n});\n" }, { "answer_id": 370041, "author": "CMPalmer", "author_id": 14894, "author_profile": "https://Stackoverflow.com/users/14894", "pm_score": 5, "selected": false, "text": "$(\"#tableID tr:gt(0)\").remove();\n" }, { "answer_id": 370069, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 7, "selected": false, "text": "$('someTableSelector').children( 'tr:not(:first)' ).remove();\n $(\"someTableSelector > tbody:last\").children().remove();\n" }, { "answer_id": 371478, "author": "Dave Ward", "author_id": 60, "author_profile": "https://Stackoverflow.com/users/60", "pm_score": 5, "selected": false, "text": "$('someTableSelector tr:not(:first)').remove();\n" }, { "answer_id": 8053924, "author": "jpmorin", "author_id": 1036025, "author_profile": "https://Stackoverflow.com/users/1036025", "pm_score": 6, "selected": false, "text": "<table id=\"tableId\">\n<thead>\n <tr><th>Col1</th><th>Col2</th></tr>\n</thead>\n<tbody>\n <tr><td>some</td><td>content</td></tr>\n <tr><td>to be</td><td>removed</td></tr>\n</tbody>\n</table>\n $(\"#tableId > tbody\").empty();\n" }, { "answer_id": 9645112, "author": "Sanket Utekar", "author_id": 1257221, "author_profile": "https://Stackoverflow.com/users/1257221", "pm_score": 3, "selected": false, "text": "tbl $('#tbl tr:not(:first)').remove();\n" }, { "answer_id": 17292870, "author": "Makubex", "author_id": 811902, "author_profile": "https://Stackoverflow.com/users/811902", "pm_score": 4, "selected": false, "text": "$('#table tr').slice(1).remove();\n" }, { "answer_id": 34064840, "author": "Biki", "author_id": 411714, "author_profile": "https://Stackoverflow.com/users/411714", "pm_score": 2, "selected": false, "text": "$(\"#dataTable tr:gt(1)\").remove();" }, { "answer_id": 40684951, "author": "PodTech.io", "author_id": 1842743, "author_profile": "https://Stackoverflow.com/users/1842743", "pm_score": 0, "selected": false, "text": "function remove_rows(tablename) { \n $(tablename).find(\"tr:gt(0)\").remove(); \n}\n remove_rows('#table1');\nremove_rows('#table2');\n" }, { "answer_id": 48659591, "author": "Aslam Kakkove", "author_id": 5561190, "author_profile": "https://Stackoverflow.com/users/5561190", "pm_score": 0, "selected": false, "text": "$(\"#myTable tbody\").children( 'tr:not(:first)' ).html(\"\");\n" }, { "answer_id": 50371216, "author": "saadk", "author_id": 2078007, "author_profile": "https://Stackoverflow.com/users/2078007", "pm_score": 0, "selected": false, "text": "$(\"#compositeTable\").find(\"tr:gt(1)\").remove();\n" }, { "answer_id": 56290227, "author": "Pytholabs", "author_id": 10695725, "author_profile": "https://Stackoverflow.com/users/10695725", "pm_score": 1, "selected": false, "text": "$(\"#mytable\").find($(\"tr\")).slice(1).remove()\n" } ]
2008/12/15
[ "https://Stackoverflow.com/questions/370013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26671/" ]
370,024
<p>I have a SQL Server 2005 database that I'm trying to access as a limited user account, using Windows authentication. I've got BUILTIN\Users added as a database user (before I did so, I couldn't even open the database). I'm working under the assumption that everybody is supposed to have permissions for the "public" role applied to them, so I didn't do anything with role assignment. Under tblFoo, I can use the SSMS Properties dialog (Permissions page) to add "public", then set explicit permissions. Among these is "Grant" for SELECT. But running</p> <pre><code>SELECT * from tblFoo; </code></pre> <p>as a limited (BUILTIN\Users) account gives me an error "Select permission denied on object 'tblFoo', database 'bar', schema 'dbo'". In the properties dialog, there's an "Effective Permissions button, but it's greyed out.</p> <p>Further, I tried creating a non-priv account called "UserTest", adding that at the server level, then mapping it down to the "bar" database. This let me add UserTest to the "Users or Roles" list, which let me run "Effective Permissions" for the account. No permissions are listed at all -- this doesn't seem right. The account must be in public, and public grants (among other things) Select on tblFoo, so why doesn't the UserTest account show an effective permission? I feel like I'm going a bit crazy here.</p> <p>ASIDE: I am aware that many people don't like using the "public" role to set permissions. This is just my tinkering time; in final design I'm sure we'll have several flexible (custom) database roles. I'm just trying to figure out the behavior I'm seeing, so please no "don't do that!" answers.</p> <p>UPDATE: Apparently I know just enough SQL Server to be a danger to myself and others. In setting permissions (as I said, "among others"), I had DENY CONTROL. When I set this permission, I think I tried to look up what it did, had a vague idea, and decided on DENY. I cannot currently recall why this seemed the thing to do, but it would appear that that was the reason I was getting permission failures. So I'm updating my question: can anyone explain the "CONTROL" permission, as it pertains to tables?</p>
[ { "answer_id": 370127, "author": "Nathan Griffiths", "author_id": 46239, "author_profile": "https://Stackoverflow.com/users/46239", "pm_score": 0, "selected": false, "text": "EXEC MASTER.dbo.xp_logininfo 'Domain\\UserTest', 'all'\n account name type privilege mapped login name permission path\ndomain\\usertest user user domain\\usertest BUILTIN\\Users\n" }, { "answer_id": 370498, "author": "gbn", "author_id": 27535, "author_profile": "https://Stackoverflow.com/users/27535", "pm_score": 2, "selected": true, "text": "GRANT SELECT ON dbo.tblFoo to public" } ]
2008/12/15
[ "https://Stackoverflow.com/questions/370024", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26286/" ]
370,030
<p>I have just start using git and i can't get it to remember my passphrase I'm using cmd.exe elevated and my git host is github and i have create a ssh key like that guide on github</p> <p>but i still get </p> <pre><code>*\subnus.mvc&gt;git push origin master Enter passphrase for key '/c/Users/Subnus/.ssh/id_rsa': </code></pre>
[ { "answer_id": 3932378, "author": "hwjp", "author_id": 366221, "author_profile": "https://Stackoverflow.com/users/366221", "pm_score": 3, "selected": false, "text": "git cat .ssh/id_rsa.pub | ssh git@GIT_MASTER_IP 'cat >> .ssh/authorized_keys'\n ~/.ssh/authorized_keys" }, { "answer_id": 4356869, "author": "RobertB", "author_id": 388702, "author_profile": "https://Stackoverflow.com/users/388702", "pm_score": 9, "selected": true, "text": "start-ssh-agent" }, { "answer_id": 25432319, "author": "Alex Essilfie", "author_id": 117870, "author_profile": "https://Stackoverflow.com/users/117870", "pm_score": 4, "selected": false, "text": "PATH git-credential-winstore -i C:\\Path\\To\\Git.exe" }, { "answer_id": 38591484, "author": "tarikakyol", "author_id": 862474, "author_profile": "https://Stackoverflow.com/users/862474", "pm_score": 1, "selected": false, "text": "ssh-add -k ~/.ssh/id_rsa\n" }, { "answer_id": 49617235, "author": "Guy Avraham", "author_id": 1971003, "author_profile": "https://Stackoverflow.com/users/1971003", "pm_score": 6, "selected": false, "text": "eval `ssh-agent -s`\nssh-add ~/.ssh/*_rsa\n" }, { "answer_id": 49638778, "author": "Alexander Goncharov", "author_id": 3654176, "author_profile": "https://Stackoverflow.com/users/3654176", "pm_score": 2, "selected": false, "text": ".bashrc C:/Users/youruser env=~/.ssh/agent.env\n\nagent_load_env () { test -f \"$env\" && . \"$env\" >| /dev/null ; }\n\nagent_start () {\n (umask 077; ssh-agent >| \"$env\")\n . \"$env\" >| /dev/null ; }\n\nagent_load_env\n\n# agent_run_state: 0=agent running w/ key; 1=agent w/o key; 2= agent not running\nagent_run_state=$(ssh-add -l >| /dev/null 2>&1; echo $?)\n\nif [ ! \"$SSH_AUTH_SOCK\" ] || [ $agent_run_state = 2 ]; then\n agent_start\n ssh-add\nelif [ \"$SSH_AUTH_SOCK\" ] && [ $agent_run_state = 1 ]; then\n ssh-add\nfi\n\nunset env\n git-bash .bash_profile .bashrc .bashrc copy .bashrc .bash_profile\n" }, { "answer_id": 58784438, "author": "d3r3kk", "author_id": 895739, "author_profile": "https://Stackoverflow.com/users/895739", "pm_score": 8, "selected": false, "text": "OpenSSH Authentication Agent Version 10.0.19042.867 ssh-add $ENV:GIT_SSH=C:\\Windows\\System32\\OpenSSH\\ssh.exe ver ~/.ssh/id_rsa OpenSSH Authentication Agent OpenSSH Authentication Agent Startup type: Automatic Start Running OK ssh-agent ssh-agent ssh-add git clone git@github.com:octocat/Spoon-Knife Enter passphrase for key '/c/Users/your_user_name/.ssh/id_rsa':\n GIT_SSH ssh-agent GIT_SSH ssh.exe $Env:GIT_SSH=$((Get-Command -Name ssh).Source) GIT_SSH Variable name: Variable value: C:\\Windows\\System32\\OpenSSH\\ssh.exe" }, { "answer_id": 59441543, "author": "Nikolay Kotlyarov", "author_id": 3210423, "author_profile": "https://Stackoverflow.com/users/3210423", "pm_score": 3, "selected": false, "text": "ssh-agent ssh-add ssh-agent ssh-agent eval $(ssh-agent -s) .bashrc default-cache-ttl ssh-agent ssh-add ~/.bashrc ~/.profile ~/.bash_profile ~ C:\\Users\\Username cd ~ pwd ### Start ssh-agent\n\nenv=~/.ssh/agent.env\n\nagent_load_env () { test -f \"$env\" && . \"$env\" >| /dev/null ; }\n\nagent_start () {\n (umask 077; ssh-agent >| \"$env\") # use -t here for timeout\n . \"$env\" >| /dev/null ; }\n\nagent_load_env\n\n# agent_run_state: 0=agent running w/ key; 1=agent w/o key; 2= agent not running\nagent_run_state=$(ssh-add -l >| /dev/null 2>&1; echo $?)\n\nif [ ! \"$SSH_AUTH_SOCK\" ] || [ $agent_run_state = 2 ]; then\n agent_start\nfi\n\nunset env\n ~/.ssh/config AddKeysToAgent # GitHub.com\nHost github.com\n Preferredauthentications publickey\n IdentityFile ~/.ssh/id_ed25519_github\n AddKeysToAgent yes\n\n# GitLab.com\nHost gitlab.com\n Preferredauthentications publickey\n IdentityFile ~/.ssh/id_ed25519_gitlab\n AddKeysToAgent yes\n ssh-agent -t (umask 077; ssh-agent -t 30m >| \"$env\")\n" }, { "answer_id": 68638309, "author": "JBSnorro", "author_id": 308451, "author_profile": "https://Stackoverflow.com/users/308451", "pm_score": 0, "selected": false, "text": "~/.ssh/config UseKeychain yes ssh-add ssh-agent" }, { "answer_id": 73001913, "author": "dominik andreas", "author_id": 3461463, "author_profile": "https://Stackoverflow.com/users/3461463", "pm_score": 0, "selected": false, "text": "⊞ Win powershell ctr shift enter PATH setx PATH \"c:/Windows/System32/OpenSSH/;$Env:PATH;\" \n # enable automatic start\nGet-Service ssh-agent | Set-Service -StartupType Automatic\n\n# start it now\nStart-Service ssh-agent\n Get-Service ssh-agent\n ssh-add $env:USERPROFILE/.ssh/id_rsa\n" } ]
2008/12/15
[ "https://Stackoverflow.com/questions/370030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31296/" ]
370,047
<p>Or more generally, how do I remove an item from a colon-separated list in a Bash environment variable?</p> <p>I thought I had seen a simple way to do this years ago, using the more advanced forms of Bash variable expansion, but if so I've lost track of it. A quick search of Google turned up surprisingly few relevant results and none that I would call "simple" or "elegant". For example, two methods using sed and awk, respectively:</p> <pre><code>PATH=$(echo $PATH | sed -e 's;:\?/home/user/bin;;' -e 's;/home/user/bin:\?;;') PATH=!(awk -F: '{for(i=1;i&lt;=NF;i++){if(!($i in a)){a[$i];printf s$i;s=":"}}}'&lt;&lt;&lt;$PATH) </code></pre> <p>Does nothing straightforward exist? Is there anything analogous to a split() function in Bash?</p> <p><strong>Update:</strong><br/> It looks like I need to apologize for my intentionally-vague question; I was less interested in solving a specific use-case than in provoking good discussion. Fortunately, I got it!</p> <p>There are some very clever techniques here. In the end, I've added the following three functions to my toolbox. The magic happens in path_remove, which is based largely on Martin York's clever use of <code>awk</code>'s RS variable.</p> <pre><code>path_append () { path_remove $1; export PATH="$PATH:$1"; } path_prepend () { path_remove $1; export PATH="$1:$PATH"; } path_remove () { export PATH=`echo -n $PATH | awk -v RS=: -v ORS=: '$0 != "'$1'"' | sed 's/:$//'`; } </code></pre> <p>The only real cruft in there is the use of <code>sed</code> to remove the trailing colon. Considering how straightforward the rest of Martin's solution is, though, I'm quite willing to live with it!</p> <hr> <p>Related question: <A href="https://stackoverflow.com/questions/273909/how-do-i-manipulate-path-elements-in-shell-scripts"><a href="https://stackoverflow.com/questions/273909/how-do-i-manipulate-path-elements-in-shell-scripts">How do I manipulate $PATH elements in shell scripts?</a></A></p>
[ { "answer_id": 370056, "author": "mat", "author_id": 42083, "author_profile": "https://Stackoverflow.com/users/42083", "pm_score": 2, "selected": false, "text": "PATH=${PATH/:\\/home\\/user\\/bin/}\n" }, { "answer_id": 370135, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 6, "selected": false, "text": "echo ${PATH} > t1\nvi t1\nexport PATH=$(cat t1)\n" }, { "answer_id": 370154, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 2, "selected": false, "text": "echo $PATH | tr ':' '\\n' | awk '$0 != \"/bin\"' | paste -sd:\n echo $PATH | tr ':' '\\n' | \n awk '$0 != \"/bin\"; $0 == \"/bin\" { print \"/bar\" }' | paste -sd:\n echo $PATH | tr ':' '\\n' | awk '$0 == \"/bin\" { print \"/bar\"; next } 1' | paste -sd:\n" }, { "answer_id": 370192, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 7, "selected": true, "text": "# Strip all paths with SDE in them.\n#\nexport PATH=`echo ${PATH} | awk -v RS=: -v ORS=: '/SDE/ {next} {print}'`\n $ export a=\"/a/b/c/d/e:/a/b/c/d/g/k/i:/a/b/c/d/f:/a/b/c/g:/a/b/c/d/g/i\"\n$ echo ${a}\n/a/b/c/d/e:/a/b/c/d/f:/a/b/c/g:/a/b/c/d/g/i\n\n## Remove multiple (any directory with a: all of them)\n$ echo ${a} | awk -v RS=: -v ORS=: '/a/ {next} {print}'\n## Works fine all removed\n\n## Remove multiple including last two: (any directory with g)\n$ echo ${a} | awk -v RS=: -v ORS=: '/g/ {next} {print}'\n/a/b/c/d/e:/a/b/c/d/f:\n## Works fine: Again!\n export PATH=$(echo ${PATH} | awk -v RS=: -v ORS=: '/SDE/ {next} {print}' | sed 's/:*$//')\n ." }, { "answer_id": 370198, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 0, "selected": false, "text": "bash $IFS $1 $2 set -- $(IFS=\":\"; echo \"$PATH\")\n clnpath" }, { "answer_id": 370255, "author": "nicerobot", "author_id": 23056, "author_profile": "https://Stackoverflow.com/users/23056", "pm_score": 5, "selected": false, "text": "#!/bin/bash\nIFS=:\n# convert it to an array\nt=($PATH)\nunset IFS\n# perform any array operations to remove elements from the array\nt=(${t[@]%%*usr*})\nIFS=:\n# output the new array\necho \"${t[*]}\"\n $PATH PATH=$(IFS=':';t=($PATH);n=${#t[*]};a=();for ((i=0;i<n;i++)); do p=\"${t[i]%%*usr*}\"; [ \"${p}\" ] && a[i]=\"${p}\"; done;echo \"${a[*]}\");\n IFS=':'\nt=($PATH)\nn=${#t[*]}\na=()\nfor ((i=0;i<n;i++)); do\n p=\"${t[i]%%*usr*}\"\n [ \"${p}\" ] && a[i]=\"${p}\"\ndone\necho \"${a[*]}\"\n" }, { "answer_id": 370345, "author": "Norman Ramsey", "author_id": 41661, "author_profile": "https://Stackoverflow.com/users/41661", "pm_score": 0, "selected": false, "text": "$PATH #!/bin/bash\n#\n# remove_from_path dirname\n#\n# removes $1 from user's $PATH\n\nif [ $# -ne 1 ]; then\n echo \"Usage: $0 pathname\" 1>&2; exit 1;\nfi\n\ndelendum=\"$1\"\nNEWPATH=\nxxx=\"$IFS\"\nIFS=\":\"\nfor i in $PATH ; do\n IFS=\"$xxx\"\n case \"$i\" in\n \"$delendum\") ;; # do nothing\n *) [ -z \"$NEWPATH\" ] && NEWPATH=\"$i\" || NEWPATH=\"$NEWPATH:$i\" ;;\n esac\ndone\n\nPATH=\"$NEWPATH\"\necho \"$PATH\"\n" }, { "answer_id": 372481, "author": "J. A. Faucett", "author_id": 18503, "author_profile": "https://Stackoverflow.com/users/18503", "pm_score": 0, "selected": false, "text": "PATH=`perl -e '$a=shift;$_=$ENV{PATH};s#:$a(:)|^$a:|:$a$#$1#;print' /home/usr/bin`\n $a s print $_" }, { "answer_id": 2053814, "author": "ongoto", "author_id": 249429, "author_profile": "https://Stackoverflow.com/users/249429", "pm_score": 0, "selected": false, "text": "#!/bin/bash\n#\n######################################################################################\n#\n# Allows a list of additions to PATH with no dupes\n# \n# Patch code below into your $HOME/.bashrc file or where it\n# will be seen at login.\n#\n# Can also be made executable and run as-is.\n#\n######################################################################################\n\n# add2path=($HOME/bin .) ## uncomment space separated list \nif [ $add2path ]; then ## skip if list empty or commented out\nfor nodup in ${add2path[*]}\ndo\n case $PATH in ## case block thanks to MIKE511\n $nodup:* | *:$nodup:* | *:$nodup ) ;; ## if found, do nothing\n *) PATH=$PATH:$nodup ## else, add it to end of PATH or\n esac ## *) PATH=$nodup:$PATH prepend to front\ndone\nexport PATH\nfi\n## debug add2path\necho\necho \" PATH == $PATH\"\necho\n" }, { "answer_id": 2103886, "author": "carlo", "author_id": 255150, "author_profile": "https://Stackoverflow.com/users/255150", "pm_score": 0, "selected": false, "text": "# delete all /opt/local paths in PATH\nshopt -s extglob \nprintf \"%s\\n\" \"${PATH}\" | tr ':' '\\n' | nl\nprintf \"%s\\n\" \"${PATH//+(\\/opt\\/local\\/)+([^:])?(:)/}\" | tr ':' '\\n' | nl \n\nman bash | less -p extglob\n" }, { "answer_id": 2108332, "author": "carlo", "author_id": 255668, "author_profile": "https://Stackoverflow.com/users/255668", "pm_score": 0, "selected": false, "text": "path_remove () { shopt -s extglob; PATH=\"${PATH//+(${1})+([^:])?(:)/}\"; export PATH=\"${PATH%:}\"; shopt -u extglob; return 0; } \n path_remove () { shopt -s extglob; declare escArg=\"${1//\\//\\\\/}\"; PATH=\"${PATH//+(${escArg})+([^:])?(:)/}\"; export PATH=\"${PATH%:}\"; shopt -u extglob; return 0; } \n" }, { "answer_id": 2108540, "author": "Andrew Aylett", "author_id": 24762, "author_profile": "https://Stackoverflow.com/users/24762", "pm_score": 6, "selected": false, "text": "# PATH => /bin:/opt/a dir/bin:/sbin\nWORK=:$PATH:\n# WORK => :/bin:/opt/a dir/bin:/sbin:\nREMOVE='/opt/a dir/bin'\nWORK=${WORK/:$REMOVE:/:}\n# WORK => :/bin:/sbin:\nWORK=${WORK%:}\nWORK=${WORK#:}\nPATH=$WORK\n# PATH => /bin:/sbin\n" }, { "answer_id": 2112399, "author": "cyrill", "author_id": 256143, "author_profile": "https://Stackoverflow.com/users/256143", "pm_score": 1, "selected": false, "text": "path_remove () { \n declare i newPATH\n newPATH=\"${PATH}:\"\n for ((i=1; i<=${#@}; i++ )); do\n #echo ${@:${i}:1}\n newPATH=\"${newPATH//${@:${i}:1}:/}\" \n done\n export PATH=\"${newPATH%:}\" \n return 0; \n} \n\npath_remove_all () {\n declare i newPATH\n shopt -s extglob\n newPATH=\"${PATH}:\"\n for ((i=1; i<=${#@}; i++ )); do\n newPATH=\"${newPATH//+(${@:${i}:1})*([^:]):/}\" \n #newPATH=\"${newPATH//+(${@:${i}:1})*([^:])+(:)/}\" \n done\n shopt -u extglob \n export PATH=\"${newPATH%:}\" \n return 0 \n} \n\npath_remove /opt/local/bin /usr/local/bin\n\npath_remove_all /opt/local /usr/local \n" }, { "answer_id": 2119255, "author": "proxxy", "author_id": 256962, "author_profile": "https://Stackoverflow.com/users/256962", "pm_score": 0, "selected": false, "text": "path_remove () { \n declare i newPATH\n # put a colon at the beginning & end AND double each colon in-between\n newPATH=\":${PATH//:/::}:\" \n for ((i=1; i<=${#@}; i++)); do\n #echo ${@:${i}:1}\n newPATH=\"${newPATH//:${@:${i}:1}:/}\" # s/:\\/fullpath://g\n done\n newPATH=\"${newPATH//::/:}\"\n newPATH=\"${newPATH#:}\" # remove leading colon\n newPATH=\"${newPATH%:}\" # remove trailing colon\n unset PATH \n PATH=\"${newPATH}\" \n export PATH\n return 0 \n} \n\n\npath_remove_all () {\n declare i newPATH extglobVar\n extglobVar=0\n # enable extended globbing if necessary\n [[ ! $(shopt -q extglob) ]] && { shopt -s extglob; extglobVar=1; }\n newPATH=\":${PATH}:\"\n for ((i=1; i<=${#@}; i++ )); do\n newPATH=\"${newPATH//:+(${@:${i}:1})*([^:])/}\" # s/:\\/path[^:]*//g\n done\n newPATH=\"${newPATH#:}\" # remove leading colon\n newPATH=\"${newPATH%:}\" # remove trailing colon\n # disable extended globbing if it was enabled in this function\n [[ $extglobVar -eq 1 ]] && shopt -u extglob\n unset PATH \n PATH=\"${newPATH}\" \n export PATH\n return 0 \n} \n\npath_remove /opt/local/bin /usr/local/bin\n\npath_remove_all /opt/local /usr/local \n" }, { "answer_id": 2119551, "author": "marius", "author_id": 256994, "author_profile": "https://Stackoverflow.com/users/256994", "pm_score": 0, "selected": false, "text": "-newPATH=\"${newPATH//:+(${@:${i}:1})*([^:])/}\" \n+newPATH=\"${newPATH//:${@:${i}:1}*([^:])/}\" # s/:\\/path[^:]*//g \n" }, { "answer_id": 5049015, "author": "MestreLion", "author_id": 624066, "author_profile": "https://Stackoverflow.com/users/624066", "pm_score": 1, "selected": false, "text": "if ! $( echo \"$PATH\" | tr \":\" \"\\n\" | grep -qx \"$folder\" ) ; then PATH=$PATH:$folder ; fi\n" }, { "answer_id": 6446697, "author": "mjc", "author_id": 19881, "author_profile": "https://Stackoverflow.com/users/19881", "pm_score": 0, "selected": false, "text": "PATH=\"/usr/lib/ccache:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games\"\nREMOVE=\"ccache\" # whole or part of a path :)\nexport PATH=$(IFS=':';p=($PATH);unset IFS;p=(${p[@]%%$REMOVE});IFS=':';echo \"${p[*]}\";unset IFS)\necho $PATH # outputs /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games\n" }, { "answer_id": 9154644, "author": "jimeh", "author_id": 42146, "author_profile": "https://Stackoverflow.com/users/42146", "pm_score": 0, "selected": false, "text": "path_remove () {\n if [[ \":$PATH:\" == *\":$1:\"* ]]; then\n local dirs=\":$PATH:\"\n dirs=${dirs/:$1:/:}\n export PATH=\"$(__path_clean $dirs)\"\n fi\n}\n__path_clean () {\n local dirs=${1%?}\n echo ${dirs#?}\n}\n path_add_before path_add_after" }, { "answer_id": 9626498, "author": "Mr. Wacky", "author_id": 316161, "author_profile": "https://Stackoverflow.com/users/316161", "pm_score": 3, "selected": false, "text": "/etc/profile $ rpm -ql bash-doc |grep pathfunc\n/usr/share/doc/bash-4.2.20/examples/functions/pathfuncs\n$ cat $(!!)\ncat $(rpm -ql bash-doc |grep pathfunc)\n#From: \"Simon J. Gerraty\" <sjg@zen.void.oz.au>\n#Message-Id: <199510091130.VAA01188@zen.void.oz.au>\n#Subject: Re: a shell idea?\n#Date: Mon, 09 Oct 1995 21:30:20 +1000\n\n\n# NAME:\n# add_path.sh - add dir to path\n#\n# DESCRIPTION:\n# These functions originated in /etc/profile and ksh.kshrc, but\n# are more useful in a separate file.\n#\n# SEE ALSO:\n# /etc/profile\n#\n# AUTHOR:\n# Simon J. Gerraty <sjg@zen.void.oz.au>\n\n# @(#)Copyright (c) 1991 Simon J. Gerraty\n#\n# This file is provided in the hope that it will\n# be of use. There is absolutely NO WARRANTY.\n# Permission to copy, redistribute or otherwise\n# use this file is hereby granted provided that\n# the above copyright notice and this notice are\n# left intact.\n\n# is $1 missing from $2 (or PATH) ?\nno_path() {\n eval \"case :\\$${2-PATH}: in *:$1:*) return 1;; *) return 0;; esac\"\n}\n# if $1 exists and is not in path, append it\nadd_path () {\n [ -d ${1:-.} ] && no_path $* && eval ${2:-PATH}=\"\\$${2:-PATH}:$1\"\n}\n# if $1 exists and is not in path, prepend it\npre_path () {\n [ -d ${1:-.} ] && no_path $* && eval ${2:-PATH}=\"$1:\\$${2:-PATH}\"\n}\n# if $1 is in path, remove it\ndel_path () {\n no_path $* || eval ${2:-PATH}=`eval echo :'$'${2:-PATH}: |\n sed -e \"s;:$1:;:;g\" -e \"s;^:;;\" -e \"s;:\\$;;\"`\n}\n" }, { "answer_id": 10052060, "author": "TriangleTodd", "author_id": 1318638, "author_profile": "https://Stackoverflow.com/users/1318638", "pm_score": 1, "selected": false, "text": "pathrm () { \n local IFS=':' \n local newpath \n local dir \n local pathvar=${2:-PATH} \n for dir in ${!pathvar} ; do \n if [ \"$dir\" != \"$1\" ] ; then \n newpath=${newpath:+$newpath:}$dir \n fi \n done \n export $pathvar=\"$newpath\" \n}\n\npathprepend () { \n pathrm $1 $2 \n local pathvar=${2:-PATH} \n export $pathvar=\"$1${!pathvar:+:${!pathvar}}\" \n}\n\npathappend () { \n pathrm $1 $2 \n local pathvar=${2:-PATH} \n export $pathvar=\"${!pathvar:+${!pathvar}:}$1\" \n} \n" }, { "answer_id": 11926946, "author": "GreenFox", "author_id": 1594168, "author_profile": "https://Stackoverflow.com/users/1594168", "pm_score": 3, "selected": false, "text": "function __path_remove(){ \n local D=\":${PATH}:\"; \n [ \"${D/:$1:/:}\" != \"$D\" ] && PATH=\"${D/:$1:/:}\"; \n PATH=\"${PATH/#:/}\"; \n export PATH=\"${PATH/%:/}\"; \n} \n" }, { "answer_id": 13135333, "author": "sschuberth", "author_id": 1127485, "author_profile": "https://Stackoverflow.com/users/1127485", "pm_score": 4, "selected": false, "text": "export PATH=$(p=$(echo $PATH | tr \":\" \"\\n\" | grep -v \"/cygwin/\" | tr \"\\n\" \":\"); echo ${p%:})\n" }, { "answer_id": 19587970, "author": "Mark Booth", "author_id": 42473, "author_profile": "https://Stackoverflow.com/users/42473", "pm_score": 3, "selected": false, "text": "function path_remove {\n # Delete path by parts so we can never accidentally remove sub paths\n PATH=${PATH//\":$1:\"/\":\"} # delete any instances in the middle\n PATH=${PATH/#\"$1:\"/} # delete any instance at the beginning\n PATH=${PATH/%\":$1\"/} # delete any instance at the end\n}\n" }, { "answer_id": 23703317, "author": "Coroos", "author_id": 269604, "author_profile": "https://Stackoverflow.com/users/269604", "pm_score": 0, "selected": false, "text": "path_remove () {\n PATH=\"$(echo -n $PATH | awk -v RS=: -v ORS= '$0 != \"'$1'\"{print s _ $0;s=\":\"}')\"\n}\n" }, { "answer_id": 25984499, "author": "jwfearn", "author_id": 10559, "author_profile": "https://Stackoverflow.com/users/10559", "pm_score": 1, "selected": false, "text": ". .. ~ rm_from_path() {\n pattern=\"${1}\"\n dir=''\n [ -d \"${pattern}\" ] && dir=\"$(cd ${pattern} && pwd)\" # resolve to absolute path\n\n new_path=''\n IFS0=${IFS}\n IFS=':'\n for segment in ${PATH}; do\n if [[ ${segment} == ${pattern} ]]; then # string match\n continue\n elif [[ -n ${dir} && -d ${segment} ]]; then\n segment=\"$(cd ${segment} && pwd)\" # resolve to absolute path\n if [[ ${segment} == ${dir} ]]; then # logical directory match\n continue\n fi\n fi\n new_path=\"${new_path}${IFS}${segment}\"\n done\n new_path=\"${new_path/#${IFS}/}\" # remove leading colon, if any\n IFS=${IFS0}\n\n export PATH=${new_path}\n}\n $ mkdir -p ~/foo/bar/baz ~/foo/bar/bif ~/foo/boo/bang\n$ PATH0=${PATH}\n$ PATH=~/foo/bar/baz/.././../boo/././../bar:${PATH} # add dir with special names\n$ rm_from_path ~/foo/boo/../bar/. # remove same dir with different special names\n$ [ ${PATH} == ${PATH0} ] && echo 'PASS' || echo 'FAIL'\n" }, { "answer_id": 26515188, "author": "Eugene", "author_id": 4170732, "author_profile": "https://Stackoverflow.com/users/4170732", "pm_score": 0, "selected": false, "text": "PATH=`echo $PATH | sed 's/:[^:]*$1[^:]*//g'`\n PATH=`echo $PATH | tr \":\" \"\\n\" | grep -v $1 | tr \"\\n\" \":\"`\n PATH=$(echo $PATH | sed 's/:[^:]*$1[^:]*//g')\n\nPATH=$(echo $PATH | tr \":\" \"\\n\" | grep -v $1 | tr \"\\n\" \":\")\n" }, { "answer_id": 29159378, "author": "robinbb", "author_id": 649126, "author_profile": "https://Stackoverflow.com/users/649126", "pm_score": 4, "selected": false, "text": "IFS PATH" }, { "answer_id": 33853577, "author": "kevinarpe", "author_id": 257299, "author_profile": "https://Stackoverflow.com/users/257299", "pm_score": 2, "selected": false, "text": "/etc/profile # Functions to help us manage paths. Second argument is the name of the\n# path variable to be modified (default: PATH)\npathremove () {\n local IFS=':'\n local NEWPATH\n local DIR\n local PATHVARIABLE=${2:-PATH}\n for DIR in ${!PATHVARIABLE} ; do\n if [ \"$DIR\" != \"$1\" ] ; then\n NEWPATH=${NEWPATH:+$NEWPATH:}$DIR\n fi\n done\n export $PATHVARIABLE=\"$NEWPATH\"\n}\n\npathprepend () {\n pathremove $1 $2\n local PATHVARIABLE=${2:-PATH}\n export $PATHVARIABLE=\"$1${!PATHVARIABLE:+:${!PATHVARIABLE}}\"\n}\n\npathappend () {\n pathremove $1 $2\n local PATHVARIABLE=${2:-PATH}\n export $PATHVARIABLE=\"${!PATHVARIABLE:+${!PATHVARIABLE}:}$1\"\n}\n\nexport -f pathremove pathprepend pathappend\n" }, { "answer_id": 34621068, "author": "Cary Millsap", "author_id": 66184, "author_profile": "https://Stackoverflow.com/users/66184", "pm_score": 2, "selected": false, "text": "path_append () { path_remove $1 $2; export $1=\"${!1}:$2\"; }\npath_prepend () { path_remove $1 $2; export $1=\"$2:${!1}\"; }\npath_remove () { export $1=\"`echo -n ${!1} | awk -v RS=: -v ORS=: '$1 != \"'$2'\"' | sed 's/:$//'`\"; }\n path_prepend PATH /usr/local/bin\npath_append PERL5LIB \"$DEVELOPMENT_HOME/p5/src/perlmods\"\n" }, { "answer_id": 38292214, "author": "Russia Must Remove Putin", "author_id": 541136, "author_profile": "https://Stackoverflow.com/users/541136", "pm_score": 2, "selected": false, "text": "path_remove () { export PATH=`echo -n $PATH | awk -v RS=: -v ORS=: '$0 != \"'$1'\"' | sed 's/:$//'`; \n PATH=\"$(echo \"$PATH\" | python -c \"import sys; path = sys.stdin.read().split(':'); del path[0]; print(':'.join(path))\")\"\n echo os.getenv['PATH'] PATH=\"$(echo \"$PATH\" | python -c \"import sys; path = sys.stdin.read().split(':'); del path[-1]; print(':'.join(path))\")\"\n strip_path_first () {\n PATH=\"$(echo \"$PATH\" | \n python -c \"import sys; path = sys.stdin.read().split(':'); del path[0]; print(':'.join(path))\")\"\n}\n\nstrip_path_last () {\n PATH=\"$(echo \"$PATH\" | \n python -c \"import sys; path = sys.stdin.read().split(':'); del path[-1]; print(':'.join(path))\")\"\n}\n" }, { "answer_id": 50752013, "author": "Lance E.T. Compte", "author_id": 9206667, "author_profile": "https://Stackoverflow.com/users/9206667", "pm_score": 1, "selected": false, "text": "set _resolve = `eval echo $2`\nsetenv $1 `eval echo -n \\$$1 | awk -v RS=: -v ORS=: '$1 != \"'${_resolve}'\"' | sed 's/:$//'`;\nunset _resolve\n source ~/bin/_path_remove.csh $1 $2\nset _base = `eval echo \\$$1`\nset _resolve = `eval echo $2`\nsetenv $1 ${_base}:${_resolve}\nunset _base _resolve\n source ~/bin/_path_remove.csh $1 $2\nset _base = `eval echo \\$$1`\nset _resolve = `eval echo $2`\nsetenv $1 ${_resolve}:${_base}\nunset _base _resolve\n …\nalias path_remove \"source ~/bin/_path_remove.csh '\\!:1' '\\!:2'\"\nalias path_append \"source ~/bin/_path_append.csh '\\!:1' '\\!:2'\"\nalias path_prepend \"source ~/bin/_path_prepend.csh '\\!:1' '\\!:2'\"\n…\n %(csh)> path_append MODULEPATH ${HOME}/modulefiles\n" }, { "answer_id": 55889522, "author": "spike83", "author_id": 11358409, "author_profile": "https://Stackoverflow.com/users/11358409", "pm_score": -1, "selected": false, "text": "PATH=${PATH/something/nope/}\n set PATH=%PATH:something=nope%\n" }, { "answer_id": 70087010, "author": "Tulcas Anathar", "author_id": 17491780, "author_profile": "https://Stackoverflow.com/users/17491780", "pm_score": 0, "selected": false, "text": "PATH=${PATH/${PATH/#$DIR:*/$DIR:}/}${PATH/${PATH/*:$DIR*/:$DIR}/}" } ]
2008/12/15
[ "https://Stackoverflow.com/questions/370047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/46387/" ]
370,055
<p>How would one change the view on the screen programmatically in an iPhone app?</p> <p>I've been able to create navigation view's and programmatically push/pop them to produce this behaviour, but if I wanted to simply change the current view (not using a UINavigation controller object), what is the neatest way to achieve this?</p> <p>A simple example, imagine an application with a single button, when pressed will display a new view, or possibly one of multiple views depending on some internal state variable.</p> <p>I have yet to see any examples that attempt to do this, and I don't seem to understand enough about the relationships and initialisation procedure between UIViewController/UIView objects to achieve this programmatically.</p>
[ { "answer_id": 370148, "author": "Ben Gottlieb", "author_id": 6694, "author_profile": "https://Stackoverflow.com/users/6694", "pm_score": 2, "selected": false, "text": "-[UIView addSubview:] -[UIView removeFromSuperview] UIView" }, { "answer_id": 370390, "author": "davidavr", "author_id": 8247, "author_profile": "https://Stackoverflow.com/users/8247", "pm_score": 4, "selected": true, "text": "presentModalViewController:animated: UIViewController dismissModalViewControllerAnimated: [[self parentViewController] dismissModalViewControllerAnimated:YES];\n" }, { "answer_id": 3912625, "author": "Wolfgang Schreurs", "author_id": 250164, "author_profile": "https://Stackoverflow.com/users/250164", "pm_score": 0, "selected": false, "text": "@interface BaseView : UIView {}\n@property (nonatomic, assign) UIViewController *parentViewController;\n@end\n @implementation BaseView\n@synthesize parentViewController;\n\n- (id)initWithFrame:(CGRect)frame {\n if ((self = [super initWithFrame:frame])) {\n // Initialization code\n }\n return self;\n}\n\n- (void)dealloc {\n [self setParentViewController:nil];\n [super dealloc];\n}\n\n@end\n @implementation FirstView\n\n- (id)initWithFrame:(CGRect)frame {\n if ((self = [super initWithFrame:frame])) {\n [self setBackgroundColor:[UIColor yellowColor]];\n\n UIButton *button1 = [[UIButton alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 200.0f, 30.0f)];\n [button1 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];\n [button1 setBackgroundColor:[UIColor whiteColor]];\n [button1 setCenter:CGPointMake(160.0f, 360.0f)];\n [button1 setTitle:@\"Show Second View\" forState:UIControlStateNormal];\n [button1 addTarget:self action:@selector(switchView:) forControlEvents:UIControlEventTouchUpInside];\n [self addSubview:button1];\n [button1 release]; \n\n UIButton *button2 = [[UIButton alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 200.0f, 30.0f)];\n [button2 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];\n [button2 setBackgroundColor:[UIColor whiteColor]];\n [button2 setCenter:CGPointMake(160.0f, 120.0f)];\n [button2 setTitle:@\"Show Sub View\" forState:UIControlStateNormal];\n [button2 addTarget:self action:@selector(showView:) forControlEvents:UIControlEventTouchUpInside];\n [self addSubview:button2];\n [button2 release]; \n }\n\n return self;\n}\n\n- (void)showView:(id)sender {\n if (viewController == nil) {\n viewController = [[SubViewController alloc] initWithNibName:nil bundle:nil]; \n }\n\n [self addSubview:viewController.view];\n}\n\n- (void)switchView:(id)sender {\n SecondView *secondView = [[SecondView alloc] initWithFrame:self.frame];\n [self.parentViewController performSelector:@selector(switchView:) withObject:secondView];\n [secondView release];\n}\n\n- (void)dealloc {\n [viewController release];\n [super dealloc];\n}\n\n@end\n @implementation ViewController\n\n- (void)loadView {\n FirstView *firstView = [[FirstView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 480.0f)]; \n [firstView setParentViewController:self];\n [self setView:firstView];\n [firstView release];\n}\n\n- (void)switchView:(BaseView *)newView {\n [newView setParentViewController:self];\n [self retain];\n [self setView:newView];\n [self release];\n}\n\n- (void)didReceiveMemoryWarning {\n [super didReceiveMemoryWarning];\n}\n\n- (void)viewDidUnload {\n [super viewDidUnload];\n} \n\n- (void)dealloc {\n [super dealloc];\n}\n\n@end\n" } ]
2008/12/15
[ "https://Stackoverflow.com/questions/370055", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40175/" ]
370,060
<p>I'm using ASP.NET MVC and I have a partial control that needs a particular CSS &amp; JS file included. Is there a way to make the parent page render the <code>script</code> and <code>link</code> tags in the 'head' section of the page, rather than just rendering them inline in the partial contol?</p> <p>To clarify the control that I want to include the files from is being rendered from a View with <code>Html.RenderPartial</code> and so cannot have server-side content controls on it. I want to be able to include the files in the html <code>head</code> section so as to avoid validation issues.</p>
[ { "answer_id": 370085, "author": "Todd Smith", "author_id": 31624, "author_profile": "https://Stackoverflow.com/users/31624", "pm_score": -1, "selected": false, "text": "<head runat=\"server>\n <asp:ContentPlaceHolder ID=\"head\" runat=\"server\" />\n</head>\n <asp:Content ID=\"head\" runat=\"server\">\n <script src=\"something.js\"></script>\n</asp:Content>\n" }, { "answer_id": 530922, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 3, "selected": false, "text": "if (false) <% if (false) { %>\n <link href=...\n <script type=...\n<% } %>\n" }, { "answer_id": 531064, "author": "Franci Penov", "author_id": 17028, "author_profile": "https://Stackoverflow.com/users/17028", "pm_score": 0, "selected": false, "text": "google.load()" }, { "answer_id": 533248, "author": "Pita.O", "author_id": 40406, "author_profile": "https://Stackoverflow.com/users/40406", "pm_score": 2, "selected": false, "text": "@import <style type=\"text/css>\n @import url(cssPath.css);\n</style>\n Content" } ]
2008/12/15
[ "https://Stackoverflow.com/questions/370060", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2975/" ]
370,075
<p>Is there a script to display a simple world clock (time in various places around the world) on a *nix terminal?</p> <p>I was thinking of writing a quick Python script, but I have a feeling that's gonna be more work than I think (e.g. due to config and output format) - not to mention reinventing the wheel...</p>
[ { "answer_id": 370105, "author": "Dustin", "author_id": 39975, "author_profile": "https://Stackoverflow.com/users/39975", "pm_score": 5, "selected": false, "text": "#!/bin/sh\n\nPT=`env TZ=US/Pacific date`\nCT=`env TZ=US/Central date`\nAT=`env TZ=Australia/Melbourne date`\n\necho \"Santa Clara $PT\"\necho \"Central $CT\"\necho \"Melbourne $AT\"\n" }, { "answer_id": 370121, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 3, "selected": false, "text": "#!/bin/sh\n# Command-line world clock\n\n: ${WORLDCLOCK_ZONES:=$HOME/etc/worldclock.zones}\n: ${WORLDCLOCK_FORMAT:='+%Y-%m-%d %H:%M:%S %Z'}\n\nwhile read zone\ndo echo $zone '!' $(TZ=$zone date \"$WORLDCLOCK_FORMAT\")\ndone < $WORLDCLOCK_ZONES |\nawk -F '!' '{ printf \"%-20s %s\\n\", $1, $2;}'\n US/Pacific\nEurope/London\nEurope/Paris\nAsia/Kolkatta\nAfrica/Johannesburg\nAsia/Tokyo\nAsia/Shanghai\n US/Pacific 2008-12-15 15:58:57 PST\nEurope/London 2008-12-15 23:58:57 GMT\nEurope/Paris 2008-12-16 00:58:57 CET\nAsia/Kolkatta 2008-12-15 23:58:57 GMT\nAfrica/Johannesburg 2008-12-16 01:58:57 SAST\nAsia/Tokyo 2008-12-16 08:58:57 JST\nAsia/Shanghai 2008-12-16 07:58:57 CST\n America/St_Johns Asia/Katmandu US/Pacific 2020-01-09 06:17:40 PST\nEurope/London 2020-01-09 14:17:40 GMT\nEurope/Paris 2020-01-09 15:17:40 CET\nAsia/Kolkata 2020-01-09 19:47:40 IST\nAfrica/Johannesburg 2020-01-09 16:17:40 SAST\nAsia/Tokyo 2020-01-09 23:17:40 JST\nAsia/Shanghai 2020-01-09 22:17:40 CST\nAmerica/St_Johns 2020-01-09 10:47:40 NST\nAsia/Katmandu 2020-01-09 20:02:40 +0545\n US/Pacific America/Los_Angeles sort -b -r -k2,2 -k3,3 -b Pacific/Honolulu Pacific/Kwajalein Pacific/Kiritimati Pacific/Kiritimati 2020-01-10 04:33:25 +14\nPacific/Kwajalein 2020-01-10 02:33:25 +12\nAsia/Tokyo 2020-01-09 23:33:25 JST\nAsia/Shanghai 2020-01-09 22:33:25 CST\nAsia/Katmandu 2020-01-09 20:18:25 +0545\nAsia/Kolkata 2020-01-09 20:03:25 IST\nAfrica/Johannesburg 2020-01-09 16:33:25 SAST\nEurope/Paris 2020-01-09 15:33:25 CET\nEurope/London 2020-01-09 14:33:25 GMT\nAmerica/St_Johns 2020-01-09 11:03:25 NST\nUS/Pacific 2020-01-09 06:33:25 PST\nPacific/Honolulu 2020-01-09 04:33:25 HST\n #!/bin/sh\n# Command-line world clock\n\n: ${WORLDCLOCK_ZONES:=$HOME/etc/worldclock.zones}\n: ${WORLDCLOCK_FORMAT:='+%Y-%m-%d %H:%M:%S %Z'}\n\nwhile read zone\ndo echo $zone '!' $(TZ=$zone date \"$WORLDCLOCK_FORMAT\")\ndone < $WORLDCLOCK_ZONES |\nawk -F '!' '{ printf \"%-20s %s\\n\", $1, $2;}' |\nsort -b -r -k2,2 -k3,3\n worldclock.zones US/Pacific\nEurope/London\nEurope/Paris\nAsia/Kolkata\nAfrica/Johannesburg\nAsia/Tokyo\nAsia/Shanghai\nAmerica/St_Johns\nAsia/Katmandu\nPacific/Honolulu\nPacific/Kwajalein\nPacific/Kiritimati\nPacific/Pago_Pago\nUTC-12\n Pacific/Pago_Pago FarEast-12 FarWest+12 US/Pacific\nEurope/London\nEurope/Paris\nAsia/Kolkata\nAfrica/Johannesburg\nAsia/Tokyo\nAsia/Shanghai\nAmerica/St_Johns\nAsia/Katmandu\nPacific/Honolulu\nPacific/Kwajalein\nPacific/Kiritimati\nPacific/Pago_Pago\nFarEast-12\nFarWest+12\nUS/Eastern\nUS/Central\nUS/Mountain\nUS/Alaska\nAsia/Vladivostok\nPacific/Noumea\nPacific/Enderbury\nAsia/Bangkok\nAsia/Thimphu\nAsia/Aqtau\nAsia/Dubai\nAfrica/Addis_Ababa\nAtlantic/Cape_Verde\nAtlantic/South_Georgia\nAmerica/Santiago\nAmerica/Halifax\n Pacific/Kiritimati 2020-01-10 05:24:10 +14\nPacific/Enderbury 2020-01-10 04:24:10 +13\nPacific/Kwajalein 2020-01-10 03:24:10 +12\nFarEast-12 2020-01-10 03:24:10 FarEast\nPacific/Noumea 2020-01-10 02:24:10 +11\nAsia/Vladivostok 2020-01-10 01:24:10 +10\nAsia/Tokyo 2020-01-10 00:24:10 JST\nAsia/Shanghai 2020-01-09 23:24:10 CST\nAsia/Bangkok 2020-01-09 22:24:10 +07\nAsia/Thimphu 2020-01-09 21:24:10 +06\nAsia/Katmandu 2020-01-09 21:09:10 +0545\nAsia/Kolkata 2020-01-09 20:54:10 IST\nAsia/Aqtau 2020-01-09 20:24:10 +05\nAsia/Dubai 2020-01-09 19:24:10 +04\nAfrica/Addis_Ababa 2020-01-09 18:24:10 EAT\nAfrica/Johannesburg 2020-01-09 17:24:10 SAST\nEurope/Paris 2020-01-09 16:24:10 CET\nEurope/London 2020-01-09 15:24:10 GMT\nAtlantic/Cape_Verde 2020-01-09 14:24:10 -01\nAtlantic/South_Georgia 2020-01-09 13:24:10 -02\nAmerica/Santiago 2020-01-09 12:24:10 -03\nAmerica/St_Johns 2020-01-09 11:54:10 NST\nAmerica/Halifax 2020-01-09 11:24:10 AST\nUS/Eastern 2020-01-09 10:24:10 EST\nUS/Central 2020-01-09 09:24:10 CST\nUS/Mountain 2020-01-09 08:24:10 MST\nUS/Pacific 2020-01-09 07:24:10 PST\nUS/Alaska 2020-01-09 06:24:10 AKST\nPacific/Honolulu 2020-01-09 05:24:10 HST\nPacific/Pago_Pago 2020-01-09 04:24:10 SST\nFarWest+12 2020-01-09 03:24:10 FarWest\n" }, { "answer_id": 618313, "author": "mivk", "author_id": 111036, "author_profile": "https://Stackoverflow.com/users/111036", "pm_score": 2, "selected": false, "text": "#!/bin/sh\n\n# Show date and time in other time zones\n\nsearch=$1\n\nzoneinfo=/usr/share/zoneinfo/posix/\nformat='%a %F %T'\n\nfind -L $zoneinfo -type f \\\n | grep -i \"$search\" \\\n | while read z\n do\n d=$(TZ=$z date +\"$format\")\n printf \"%-34s %23s\\n\" ${z#$zoneinfo} \"$d\"\n done\n $ /usr/local/bin/wdate bang\nAfrica/Bangui Fri 2009-03-06 11:04:24\nAsia/Bangkok Fri 2009-03-06 17:04:24\n systemd timedatectl list-timezones #!/bin/sh\n\n# Show date and time in other time zones\n\nsearch=$1\nformat='%a %F %T'\n\ntimedatectl list-timezones \\\n| grep -i \"$search\" \\\n| while read z\n do\n d=$(TZ=$z date +\"$format\")\n printf \"%-34s %23s\\n\" \"$z\" \"$d\"\n done\n find timedatectl #!/bin/sh\n\n# Show date and time in other time zones\n\nsearch=$1\n\nzoneinfo=/usr/share/zoneinfo/posix/\nformat='%a %F %T'\n\nif command -v timedatectl >/dev/null; then\n tzlist=$(timedatectl list-timezones)\nelse\n tzlist=$(find -L $zoneinfo -type f)\nfi\n\n\ngrep -i \"$search\" <<< \"$tzlist\" \\\n| while read z\n do\n d=$(TZ=$z date +\"$format\")\n printf \"%-34s %23s\\n\" ${z#$zoneinfo} \"$d\"\n done\n" }, { "answer_id": 31997386, "author": "delta99", "author_id": 5224983, "author_profile": "https://Stackoverflow.com/users/5224983", "pm_score": 0, "selected": false, "text": "#!/usr/bin/env bash \n\n# Show date and time in other time zones, with multiple args \n\n\nelements=$@\n\nzoneinfo=/usr/share/zoneinfo\nformat='%a %F %T'\n\nfor search in ${elements[@]}; do\n\n find $zoneinfo -type f \\\n | grep -i \"$search\" \\\n | while read z\n do\n d=$(TZ=$z date +\"$format\")\n printf \"%-34s %23s\\n\" ${z#$zoneinfo} \"$d\"\n done\ndone\n /usr/local/bin/wdate Sydney Stockholm\n/Australia/Sydney Fri 2015-08-14 05:54:26\n/Europe/Stockholm Thu 2015-08-13 21:54:26" }, { "answer_id": 32000263, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 1, "selected": false, "text": "tclock.c curses $ TZ=Europe/Paris python tclock.py\n" }, { "answer_id": 53093555, "author": "Bart Schuijt", "author_id": 2811537, "author_profile": "https://Stackoverflow.com/users/2811537", "pm_score": 1, "selected": false, "text": "TIME_ZONES=\"Europe/Amsterdam America/Los_Angeles Europe/Dublin\"\nOUTPUT=\"\"\n\nfor loc in $TIME_ZONES; do\n CITY=`echo $loc | sed 's/\\// /g' | awk '{ print $2 }'`\n CUR_TIME=`TZ=${loc} date | awk '{ print $2 \" \" $3 \" \" $5 }'`\n TEMP=`awk -v l=\"$CITY\" -v t=\"$CUR_TIME\" 'BEGIN { print l \"\\t\" t }'`\n OUTPUT=\"${OUTPUT}\\n${TEMP}\"\ndone\n\necho $OUTPUT | column -t\n Amsterdam 1 Nov 01:03:30\nLos_Angeles 31 Oct 17:03:30\nDublin 1 Nov 00:03:30\n" } ]
2008/12/15
[ "https://Stackoverflow.com/questions/370075", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
370,079
<p>I'm trying to write some C# code that calls a method from an unmanaged DLL. The prototype for the function in the dll is:</p> <pre><code>extern "C" __declspec(dllexport) char *foo(void); </code></pre> <p>In C#, I first used:</p> <pre><code>[DllImport(_dllLocation)] public static extern string foo(); </code></pre> <p>It seems to work on the surface, but I'm getting memory corruption errors during runtime. I think I'm pointing to memory that happens to be correct, but has already been freed.</p> <p>I tried using a PInvoke code gen utility called "P/Invoke Interop Assistant". It gave me the output:</p> <pre><code>[System.Runtime.InteropServices.DLLImportAttribute(_dllLocation, EntryPoint = "foo")] public static extern System.IntPtr foo(); </code></pre> <p>Is this correct? If so, how do I convert this IntPtr to a string in C#?</p>
[ { "answer_id": 370093, "author": "Strelok", "author_id": 2788, "author_profile": "https://Stackoverflow.com/users/2788", "pm_score": 5, "selected": false, "text": "IntPtr ptr = foo();\nstring str = Marshal.PtrToStringAuto(ptr);\n" }, { "answer_id": 370519, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 7, "selected": true, "text": "foo() CoTaskMemFree(...)" }, { "answer_id": 61120111, "author": "Shpand", "author_id": 4531734, "author_profile": "https://Stackoverflow.com/users/4531734", "pm_score": 3, "selected": false, "text": "//extern \"C\" __declspec(dllexport) uint32_t foo(/*[out]*/ char* lpBuffer, /*[in]*/ uint32_t uSize)\nuint32_t __stdcall foo(/*[out]*/ char* lpBuffer, /*[in]*/ uint32_t uSize)\n{\n const char szReturnString[] = \"Hello World\";\n const uint32_t uiStringLength = strlen(szReturnString);\n\n if (uSize >= (uiStringLength + 1))\n {\n strcpy(lpBuffer, szReturnString);\n // Return the number of characters copied.\n return uiStringLength;\n }\n else\n {\n // Return the required size\n // (including the terminating NULL character).\n return uiStringLength + 1;\n }\n}\n [DllImport(_dllLocation, CallingConvention=CallingConvention.StdCall, CharSet=CharSet.Ansi)]\nprivate static extern uint foo(IntPtr lpBuffer, uint uiSize);\n\nprivate static string foo()\n{\n // First allocate a buffer of 1 byte.\n IntPtr lpBuffer = Marshal.AllocHGlobal(1);\n // Call the API. If the size of the buffer\n // is insufficient, the return value in\n // uiRequiredSize will indicate the required\n // size.\n uint uiRequiredSize = foo(lpBuffer, 1);\n\n if (uiRequiredSize > 1)\n {\n // The buffer pointed to by lpBuffer needs to be of a\n // greater size than the current capacity.\n // This required size is the returned value in \"uiRequiredSize\"\n // (including the terminating NULL character).\n lpBuffer = Marshal.ReAllocHGlobal(lpBuffer, (IntPtr)uiRequiredSize);\n // Call the API again.\n foo(lpBuffer, uiRequiredSize);\n }\n\n // Convert the characters inside the buffer\n // into a managed string.\n string str = Marshal.PtrToStringAnsi(lpBuffer);\n\n // Free the buffer.\n Marshal.FreeHGlobal(lpBuffer);\n lpBuffer = IntPtr.Zero;\n\n // Display the string.\n Console.WriteLine(\"GetString return string : [\" + str + \"]\");\n\n return str;\n}\n [DllImport(\"TestDLL.dll\", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)]\nprivate static extern uint foo(StringBuilder lpBuffer, UInt32 uiSize);\n\nprivate static string foo()\n{\n StringBuilder sbBuffer = new StringBuilder(1);\n uint uiRequiredSize = foo(sbBuffer, (uint)sbBuffer.Capacity);\n\n if (uiRequiredSize > sbBuffer.Capacity)\n {\n // sbBuffer needs to be of a greater size than current capacity.\n // This required size is the returned value in \"uiRequiredSize\"\n // (including the terminating NULL character).\n sbBuffer.Capacity = (int)uiRequiredSize;\n // Call the API again.\n foo(sbBuffer, (uint)sbBuffer.Capacity);\n }\n\n return sbBuffer.ToString();\n}\n" } ]
2008/12/15
[ "https://Stackoverflow.com/questions/370079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5959/" ]
370,086
<p>I'm loading the XML in, and I'm able to read the XML nodes into text fields in my flash. It is also loading the URL, but the last one from the loop. It's not loading the one that I click on. I tried using <code>event.target</code>, but that is not working. I'm pretty close to figuring it out, I'm just not sure where to look.</p> <pre><code>// loads xml var xml:XML = new XML(); var loader:URLLoader = new URLLoader(); loader.load(new URLRequest(audioPlaylist)); loader.addEventListener(Event.COMPLETE, onComplete); function onComplete(evt:Event):void { xml = XML(evt.target.data); xmlList = xml.children(); trace(xmlList); trackLength = xmlList.children().children().length(); trace(trackLength); for(var i:int = 0; i &lt; trackLength; i++) { trace(i); var track:Playlist_item = new Playlist_item(); track.y = i * 28; track.playlist_text.text = xmlList.children().track[i].toString(); trackURL = xmlList.children().track[i].@rel.toString(); trace(trackURL); playlist_container.addChild(track); track.buttonMode = true; track.mouseChildren=false; track.addEventListener(MouseEvent.MOUSE_OVER, onCarHover); track.addEventListener(MouseEvent.MOUSE_OUT, onCarOut); track.addEventListener(MouseEvent.CLICK, onClickLoadData); } } function onCarHover(event:MouseEvent):void { event.target.gotoAndStop(6); } function onCarOut(event:MouseEvent):void { event.target.gotoAndStop(10); } function onClickLoadData(event:MouseEvent):void { ns.play(trackURL); } </code></pre> <hr> <p>I'm getting closer, I managed to create an array, with an index value - so now I can choose different URLs from the array to play, but I'm still unsure how to target the one that I'm clicking directly on and have that play.</p> <p>Here is my updated code:</p> <pre><code>// xml variables var xmlList:XMLList; var trackLength:Number; var trackURL; var trackNum:Number = -1; var tracksArray:Array = new Array(); // loads xml var xml:XML = new XML(); var loader:URLLoader = new URLLoader(); loader.load(new URLRequest(audioPlaylist)); loader.addEventListener(Event.COMPLETE, onComplete); function onComplete(evt:Event):void { xml = XML(evt.target.data); xmlList = xml.children(); trace(xmlList); trackLength = xmlList.children().children().length(); while (trackNum &lt; trackLength) { trackNum = trackNum + 1; trace(trackNum); var track:Playlist_item = new Playlist_item(); track.y = trackNum * 28; playlist_container.addChild(track); track.buttonMode = true; track.mouseChildren=false; track.playlist_text.text = xmlList.children().track[trackNum].toString(); //trackURL = xmlList.children().track[trackNum].@rel.toString(); tracksArray[trackNum] = xmlList.children().track[trackNum].@rel.toString(); track.addEventListener(MouseEvent.MOUSE_OVER, onCarHover); track.addEventListener(MouseEvent.MOUSE_OUT, onCarOut); track.addEventListener(MouseEvent.CLICK, onClickLoadData); } } function onCarHover(event:MouseEvent):void { event.target.gotoAndStop(6); } function onCarOut(event:MouseEvent):void { event.target.gotoAndStop(10); } function onClickLoadData(event:MouseEvent):void { trace(tracksArray[5]); trace(event.target.trackNum); ns.play(tracksArray[5]); } </code></pre>
[ { "answer_id": 372090, "author": "jrutter", "author_id": 28454, "author_profile": "https://Stackoverflow.com/users/28454", "pm_score": 0, "selected": false, "text": "trackNum event.target.name // xml variables\nvar xmlList:XMLList;\nvar trackLength:Number;\nvar trackURL;\nvar trackNum:Number = -1;\nvar tracksArray:Array = new Array();\n\n\n// loads xml \nvar xml:XML = new XML();\nvar loader:URLLoader = new URLLoader();\nloader.load(new URLRequest(audioPlaylist));\nloader.addEventListener(Event.COMPLETE, onComplete);\n\nfunction onComplete(evt:Event):void {\n xml = XML(evt.target.data);\n xmlList = xml.children();\n trace(xmlList);\n trackLength = xmlList.children().children().length();\n\n while (trackNum < trackLength) {\n trackNum = trackNum + 1;\n\n var track:Playlist_item = new Playlist_item();\n track.y = trackNum * 28;\n playlist_container.addChild(track);\n track.name = \"track\" + [trackNum];\n\n trace(track);\n\n track.buttonMode = true;\n track.mouseChildren=false;\n\n track.playlist_text.text = xmlList.children().track[trackNum].toString();\n //trackURL = xmlList.children().track[trackNum].@rel.toString();\n\n tracksArray[trackNum] = xmlList.children().track[trackNum].@rel.toString();\n\n track.addEventListener(MouseEvent.MOUSE_OVER, onCarHover);\n track.addEventListener(MouseEvent.MOUSE_OUT, onCarOut);\n track.addEventListener(MouseEvent.CLICK, onClickLoadData);\n\n } \n\n}\n\nfunction onCarHover(event:MouseEvent):void {\n event.target.gotoAndStop(6);\n}\n\nfunction onCarOut(event:MouseEvent):void {\n event.target.gotoAndStop(10);\n}\n\nfunction onClickLoadData(event:MouseEvent):void {\n\n //trace(tracksArray[5]);\n\n trace(event.target.name.substr(5));\n\n ns.play(tracksArray[event.target.name.substr(5)]);\n}\n" }, { "answer_id": 379221, "author": "Brian Hodge", "author_id": 20628, "author_profile": "https://Stackoverflow.com/users/20628", "pm_score": 2, "selected": true, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<xml>\n <item title=\"Song 1\" path=\"audio/song1.mp3\" />\n <item title=\"Song 2\" path=\"audio/song2.mp3\" />\n <item title=\"Song 3\" path=\"audio/song3.mp3\" />\n <item title=\"Song 4\" path=\"audio/song4.mp3\" />\n <item title=\"Song 5\" path=\"audio/song5.mp3\" />\n <item title=\"Song 6\" path=\"audio/song6.mp3\" />\n</xml>\n package\n{\n import flash.display.Sprite;\n import flash.events.Event;\n import flash.events.MouseEvent;\n import flash.net.URLLoader;\n import flash.net.URLRequest;\n\n public class DocumentClass extends Sprite\n {\n private var _urlLoader:URLLoader;\n private var _urlRequest:URLRequest;\n private var _xml:XML;\n private var _xmlList:XMLList;\n\n public function DocumentClass():void\n {\n _urlLoader = new URLLoader();\n _urlRequest = new URLRequest();\n _urlRequest.url = 'path/to/playlist.xml';\n\n _urlLoader.addEventListener(Event.COMPLETE, onXMLLoaded);\n _urlLoader.load(_urlRequest);\n }\n private function onXMLLoaded(e:Event):void\n {\n _xml = new XML(e.target.data);\n _xmlList = new XMLList(_xml.item);\n\n //We use the index in the XML object as its ID. (The XML object/List is an array);\n for(var i:int = 0; i < _xmlList.length(); i++)\n {\n var s:MovieClip = new MovieClip();\n addChild(s);\n s.mouseChildren = false;\n\n var tf:TextField = new TextField();\n tf.text = _xmlList[i].@title;\n tf.y = i * 12 + 20; //Seperates the textfields by 12 px starting at y:20;\n s.path = _xmlList[i].@path;\n s.addChild(tf);\n s.addEventListener(MouseEvent.MOUSE_DOWN, onSDown);\n }\n }\n private var onSDown(e:MouseEvent):void\n {\n var s:Sound = new Sound(new URLRequest(e.target.path));\n s.play();\n }\n }\n}\n" } ]
2008/12/15
[ "https://Stackoverflow.com/questions/370086", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28454/" ]
370,087
<p>I currently have an INSERT TRIGGER which in Oracle 10g runs a custom defined function that generates a funky alpha-numeric code that is used as part of the insert.</p> <p>I really need to make sure that the function (or even trigger) is thread safe so that if two users activate the trigger at once, the function used within the trigger does NOT return the same code for both users.</p> <p>The flow in the trigger is as follows:</p> <p>START</p> <ol> <li>determine if we need to continue based on business logic</li> <li>run the custom function to get new code</li> <li>use the returned code as an insert into a different table</li> </ol> <p>END</p> <p>The main issue is if while step 2 is running, a separate thread fires the trigger, which also gets into step 2, and returns the same code as the first thread. (I understand that this is a very tight situation, but we need to handle it).</p> <p>I have thought of two main ways of doing this:</p> <p>The currently best way that I have thought of so far is to lock the table used in the trigger in "exclusive mode" at the very start of the trigger, and <strong>do not</strong> specify the NOWAIT attribute of the lock. This way each subsequent activation of the trigger will sort of "stop and wait" for the lock to be available and hence wait for other threads to finish with the trigger.</p> <p>I would love to lock the table any deny reading of the table, but I could seem to find out how to do this in Oracle.</p> <p>My idea is not ideal, but it should work, however i would love to hear from anyone who may have better ideas that this!</p> <p>Thanks a lot for any help given.</p> <p>Cheers, Mark</p>
[ { "answer_id": 370107, "author": "BQ.", "author_id": 4632, "author_profile": "https://Stackoverflow.com/users/4632", "pm_score": 3, "selected": false, "text": "select sys_guid() from dual;\n sys_guid()" } ]
2008/12/15
[ "https://Stackoverflow.com/questions/370087", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26310/" ]
370,108
<p>I'd love to use PHP variables in my CSS files but I don't want to load up the whole Symfony stack for each file load. Any one have any best practices and/or plugins to manage their CSS files in Symfony?</p>
[ { "answer_id": 483310, "author": "deresh", "author_id": 11851, "author_profile": "https://Stackoverflow.com/users/11851", "pm_score": 4, "selected": true, "text": "<link rel=\"stylesheet\" type=\"text/css\" media=\"screen\" href=\"/css/mycss.php\" />\n" } ]
2008/12/15
[ "https://Stackoverflow.com/questions/370108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/46443/" ]
370,113
<pre><code>SaveFileDialog savefileDialog1 = new SaveFileDialog(); DialogResult result = savefileDialog1.ShowDialog(); switch(result == DialogResult.OK) case true: //do something case false: MessageBox.Show("are you sure?","",MessageBoxButtons.YesNo,MessageBoxIcon.Question); </code></pre> <p>How to show the messagebox over the savedialog box after clicking "Cancel" on the SaveDialog box i.e. the Save Dialog box should be present on the background.</p>
[ { "answer_id": 370132, "author": "lubos hasko", "author_id": 275, "author_profile": "https://Stackoverflow.com/users/275", "pm_score": 1, "selected": false, "text": "SaveFileDialog" }, { "answer_id": 370235, "author": "Patrick Desjardins", "author_id": 13913, "author_profile": "https://Stackoverflow.com/users/13913", "pm_score": 0, "selected": false, "text": " private void Form1_Load(object sender, EventArgs e)\n {\n DialogResult result = showDialog();\n if (result == DialogResult.OK)\n {\n //Ok\n }\n else\n {\n DialogResult r = MessageBox.Show(\"Are you sure?\", \"Sure?\", MessageBoxButtons.YesNo);\n if(r.ToString()==\"No\")\n {\n showDialog();\n }\n }\n }\n\n public DialogResult showDialog()\n {\n SaveFileDialog savefileDialog1 = new SaveFileDialog();\n DialogResult result = savefileDialog1.ShowDialog();\n return result;\n }\n" }, { "answer_id": 370248, "author": "RobH", "author_id": 21255, "author_profile": "https://Stackoverflow.com/users/21255", "pm_score": 3, "selected": true, "text": "// lead-up code\n\nSaveFileDialog sft = new SaveFileDialog();\nBOOL bDone;\ndo\n{\n if (DialogResult.OK == sft.ShowDialog())\n bDone = true;\n else\n {\n DialogResult result = MessageBox.Show(\"Are you sure you don't want to save the changed file?\", \"\", MessageBoxButtons.YesNo, MessageBoxIcon.Question);\n bDone = (result == Yes) ? true : false;\n }\n} while (!bDone);\n\n// carry on\n" }, { "answer_id": 1246128, "author": "jay_t55", "author_id": 152598, "author_profile": "https://Stackoverflow.com/users/152598", "pm_score": 0, "selected": false, "text": "SaveFileDialog saveFileDialog1 = new SaveFileDialog();\n\nif( saveFileDialog1.ShowDialog() == DialogResult.OK )\n{\n // Code here...\n} else Application.DoEvents();\n" } ]
2008/12/15
[ "https://Stackoverflow.com/questions/370113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42564/" ]
370,114
<p>How would one go about adding a submenu item to the windows explorer context menu (like for example 7-Zip does) for a Java application?</p>
[ { "answer_id": 370130, "author": "Jayden", "author_id": 44873, "author_profile": "https://Stackoverflow.com/users/44873", "pm_score": 5, "selected": true, "text": "HKEY_CLASSES_ROOT\\<file type>\\shell\\<display text>\\command\n <file type> <display text> HKEY_CLASSES_ROOT\\*\\shell\\MS Access 2000\\command\n\"C:\\Program Files\\Microsoft Office\\Office\\MSACCESS.EXE\" \"%1\"\n" } ]
2008/12/15
[ "https://Stackoverflow.com/questions/370114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14955/" ]
370,124
<p>Are there any pre-written component-like Silverlight web widgets like there are for Flash? </p> <p>Flash examples:<br> <a href="http://musicplayer.sourceforge.net/" rel="nofollow noreferrer">XSPF Web Music Player</a><br> <a href="http://wpaudioplayer.com/" rel="nofollow noreferrer">WordPress Audio Player</a><br> <a href="http://www.flamplayer.com/flamplayer_demo/pages/demo.html" rel="nofollow noreferrer">FLAMPlayer</a><br> <a href="http://www.aflax.org/demos.htm" rel="nofollow noreferrer">Aflax</a> </p> <p>Clarification: I don't mean controls to use in your IDE to write something custom.<br> See <a href="http://altnetpodcast.com/" rel="nofollow noreferrer">ALTNET Podcast</a><br> I think they use the WordPress Audio Player.</p>
[ { "answer_id": 370130, "author": "Jayden", "author_id": 44873, "author_profile": "https://Stackoverflow.com/users/44873", "pm_score": 5, "selected": true, "text": "HKEY_CLASSES_ROOT\\<file type>\\shell\\<display text>\\command\n <file type> <display text> HKEY_CLASSES_ROOT\\*\\shell\\MS Access 2000\\command\n\"C:\\Program Files\\Microsoft Office\\Office\\MSACCESS.EXE\" \"%1\"\n" } ]
2008/12/15
[ "https://Stackoverflow.com/questions/370124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36590/" ]
370,165
<p>I am having trouble retrieving results from my datareader in visual studio 2008. I have several stored Procs in the same database. I am able to retrieve values from those that dont receive input parameters. However, when i use the executreReader() method on a stored proc with input parameters i get an empty datareader. Upon examining the result collection the message "IEnumerable returned no results" appears. I am baffled as I can execute the stored procs within sql server and return result sets. I was previously able to retrieve rows from these stored procedures within Visual Studio but apparently it just stopped working one day.</p> <p>I have tried using a dataadapter to fill a dataset with my results and using the executereader() method to get a sqldatareader and Still I get no results. No exceptions are thrown either. My parameters are all named properly but I should be able to call these stored procs with no parameters and have that return an unfiltered result set. The code im currently using is the following:</p> <pre><code>string connStr = ConfigurationManager.ConnectionStrings["MyConnectionString"] .ConnectionString; SqlConnection connCactus = new SqlConnection(connStr); SqlCommand cmdPopulateFilterDropDowns = new SqlCommand( "dbo.MyStoredProc", connCactus); SqlDataReader rdrFilterSearch = null; cmdPopulateFilterDropDowns.CommandType = CommandType.StoredProcedure; connCactus.Open(); rdrFilterSearch = cmdPopulateFilterDropDowns .ExecuteReader(CommandBehavior.CloseConnection); return (rdrFilterSearch); </code></pre> <p>Please Help!</p>
[ { "answer_id": 370177, "author": "Kevin Tighe", "author_id": 39461, "author_profile": "https://Stackoverflow.com/users/39461", "pm_score": 0, "selected": false, "text": "rdrFilterSearch.GetString(0);\n" }, { "answer_id": 370256, "author": "BFree", "author_id": 15861, "author_profile": "https://Stackoverflow.com/users/15861", "pm_score": 3, "selected": false, "text": "cmdPopulateFilterDropDowns.Parameters.AddWithValue(...);\n" }, { "answer_id": 1859630, "author": "Henriette", "author_id": 226319, "author_profile": "https://Stackoverflow.com/users/226319", "pm_score": 1, "selected": false, "text": "mySqlParam.Direction = ParameterDirection.ReturnValue;\n SqlParameter mySqlParam = new SqlParameter();\n mySqlParam.ParameterName = \"@ID\";\n mySqlParam.SqlDbType = SqlDbType.int;\n mySqlParam.Direction = ParameterDirection.ReturnValue;\n\n SqlParameter mySqlParam = new SqlParameter();\n mySqlParam.ParameterName = \"@Name\";\n mySqlParam.SqlDbType = SqlDbType.NVarChar;\n mySqlParam.Direction = ParameterDirection.ReturnValue;\n\n\n SqlParameter mySqlParam = new SqlParameter();\n mySqlParam.ParameterName = \"@Address\";\n mySqlParam.SqlDbType = SqlDbType.NVarChar;\n mySqlParam.Direction = ParameterDirection.ReturnValue;\n mySqlParam.ParameterName int.Parse(dataReader[\"ID\"]);\ndataReader[\"name\"].ToString();\ndataReader[\"address\"].ToString();\n dataReader[\"\"].ToString();" }, { "answer_id": 4087302, "author": "Biju", "author_id": 495932, "author_profile": "https://Stackoverflow.com/users/495932", "pm_score": 0, "selected": false, "text": "reader.ExecuteNonQuery() \n" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370165", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
370,174
<p>I've got several function where I need to do a one-to-many join, using count(), group_by, and order_by. I'm using the sqlalchemy.select function to produce a query that will return me a set of id's, which I then iterate over to do an ORM select on the individual records. What I'm wondering is if there is a way to do what I need using the ORM in a single query so that I can avoid having to do the iteration.</p> <p>Here's an example of what I'm doing now. In this case the entities are Location and Guide, mapped one-to-many. I'm trying get a list of the top locations sorted by how many guides they are related to.</p> <pre><code>def popular_world_cities(self): query = select([locations.c.id, func.count(Guide.location_id).label('count')], from_obj=[locations, guides], whereclause="guides.location_id = locations.id AND (locations.type = 'city' OR locations.type = 'custom')", group_by=[Location.id], order_by='count desc', limit=10) return map(lambda x: meta.Session.query(Location).filter_by(id=x[0]).first(), meta.engine.execute(query).fetchall()) </code></pre> <p><strong>Solution</strong></p> <p>I've found the best way to do this. Simply supply a <code>from_statement</code> instead of a <code>filter_by</code> or some such. Like so:</p> <pre><code>meta.Session.query(Location).from_statement(query).all() </code></pre>
[ { "answer_id": 468869, "author": "Joshua Kifer", "author_id": 45076, "author_profile": "https://Stackoverflow.com/users/45076", "pm_score": 1, "selected": true, "text": "from_statement filter_by meta.Session.query(Location).from_statement(query).all()\n" }, { "answer_id": 679479, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "group_by order_by group_by()" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45076/" ]
370,183
<p>I'm trying to achieve a 50px space at the bottom of my page, below the main content area so that no matter what text size the user is at, or how much content happens to be inside the page - there is always a proceeding 50px space after the content area which will make either the container div(transparent) or body show.</p> <p>It sounds fairly simple, and I've fiddled about setting margins and padding to my container div and the body tag etc, but I'm having no luck what so ever. The increase in size or content pushes past whatever space I manage to create.</p> <p>Is there a general, clean approach of producing this effect?</p>
[ { "answer_id": 370197, "author": "Logan Serman", "author_id": 29595, "author_profile": "https://Stackoverflow.com/users/29595", "pm_score": 0, "selected": false, "text": "height: 50px;\nwidth: 100%;\nposition: fixed;\nbottom: 0;\n" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370183", "https://Stackoverflow.com", "https://Stackoverflow.com/users/46502/" ]
370,186
<p>This is on the Mac:</p> <p>If I have two filenames /foo/foo and /foo/FOO they may refer to the same file or the may be different files depending on the file system. How do I figure out if they are both pointing to the same file? And if they are, how do I get the correct representation of the filename?</p> <p>My problem is caused by links. A link might point to /foo/FOO but the actual directory is named /foo/foo.</p> <p>Is there any function that will follow a link and give me the the full path of the linked file? [NSFileManager pathContentOfSymbolicLinkAtPath] gives relative paths that might be in the incorrect case.</p> <p>Ultimately what I'm try to do is cache info for files. But if I have two different paths for the same file, my cache can get out of sync.</p> <p>Thanks</p>
[ { "answer_id": 370295, "author": "Boaz Stuller", "author_id": 1464654, "author_profile": "https://Stackoverflow.com/users/1464654", "pm_score": 3, "selected": false, "text": "FSPathMakeRef() FSCompareFSRefs() FSRefMakePath() NSFileManager's displayNameAtPath:" }, { "answer_id": 370684, "author": "TALlama", "author_id": 5657, "author_profile": "https://Stackoverflow.com/users/5657", "pm_score": 5, "selected": true, "text": "NSAutoreleasePool long getInode(NSString* path) {\n NSFileManager* fm = [NSFileManager defaultManager];\n NSError* error;\n NSDictionary* info = [fm attributesOfItemAtPath:path error:&error];\n NSNumber* inode = [info objectForKey:NSFileSystemFileNumber];\n return [inode longValue];\n}\n NSString* getActualPath(NSString* path) {\n FSRef ref;\n OSStatus sts;\n UInt8* actualPath;\n \n //first get an FSRef for the path\n sts = FSPathMakeRef((const UInt8 *)[path UTF8String], &ref, NULL);\n if (sts) return [NSString stringWithFormat:@\"Error #%d making ref.\", sts];\n \n //then get a path from the FSRef\n actualPath = malloc(sizeof(UInt8)*MAX_PATH_LENGTH);\n sts = FSRefMakePath(&ref, actualPath, MAX_PATH_LENGTH);\n if (sts) return [NSString stringWithFormat:@\"Error #%d making path.\", sts];\n \n return [NSString stringWithUTF8String:(const char*)actualPath];\n}\n NSString* getDisplayPath(NSString* path) {\n NSFileManager* fm = [NSFileManager defaultManager];\n NSString* mine = [fm displayNameAtPath:path];\n NSString* parentPath = [path stringByDeletingLastPathComponent];\n NSString* parents = [@\"/\" isEqualToString:parentPath]\n ? @\"\"\n : getDisplayPath(parentPath);\n return [NSString stringWithFormat:@\"%@/%@\", parents, mine];\n}\n NSString* fileInfoString(NSString* path) {\n long inode = getInode(path);\n return [NSString stringWithFormat:\n @\"\\t%@ [inode #%d]\\n\\t\\tis actually %@\\n\\t\\tand displays as %@\",\n path,\n inode,\n getActualPath(path),\n getDisplayPath(path)];\n}\n\nint main (int argc, const char * argv[]) {\n NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];\n\n if (argc < 2) {\n NSLog(@\"Usage: %s <path1> [<path2>]\", argv[0]);\n return -1;\n }\n\n NSString* path1 = [NSString stringWithCString:argv[1]];\n NSString* path2 = argc > 2\n ? [NSString stringWithCString:argv[1]]\n : [path1 uppercaseString];\n \n long inode1 = getInode(path1);\n long inode2 = getInode(path2);\n \n NSString* prefix = [NSString stringWithFormat:\n @\"Comparing Files:\\n%@\\n%@\", \n fileInfoString(path1), \n fileInfoString(path2)];\n \n int retval = 0;\n if (inode1 == inode2) {\n NSLog(@\"%@\\nSame file.\", prefix);\n } else {\n NSLog(@\"%@\\nDifferent files.\", prefix);\n retval = 1;\n }\n \n [pool drain];\n return retval;\n}\n" }, { "answer_id": 7276822, "author": "Dimitri", "author_id": 45080, "author_profile": "https://Stackoverflow.com/users/45080", "pm_score": 0, "selected": false, "text": "void checkForCapsIssues(NSString* compiledPath)\n{\n\nNSArray* validFilePaths = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[[compiledPath stringByDeletingLastPathComponent] stringByResolvingSymlinksInPath] error:nil];\nNSString* lastPathComponent = [compiledPath lastPathComponent];\nfor (NSString* fileName in validFilePaths) {\n if([fileName isEqualToString:lastPathComponent])\n {\n return;\n }\n if([[fileName lowercaseString] isEqualToString:[lastPathComponent lowercaseString]])\n {\n NSLog(@\"Warning! Caps Problem Found! %@\", compiledPath);\n return;\n }\n}\n\n}\n" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39138/" ]
370,195
<p>I know that the compiler will sometimes initialize memory with certain patterns such as <code>0xCD</code> and <code>0xDD</code>. What I want to know is <strong>when</strong> and <strong>why</strong> this happens.</p> <p><H2>When</H2></p> <p>Is this specific to the compiler used?</p> <p>Do <code>malloc/new</code> and <code>free/delete</code> work in the same way with regard to this?</p> <p>Is it platform specific?</p> <p>Will it occur on other operating systems, such as <code>Linux</code> or <code>VxWorks</code>?</p> <p><H2>Why</H2></p> <p>My understanding is this only occurs in <code>Win32</code> debug configuration, and it is used to detect memory overruns and to help the compiler catch exceptions.</p> <p>Can you give any practical examples as to how this initialization is useful?</p> <p>I remember reading something (maybe in Code Complete 2) saying that it is good to initialize memory to a known pattern when allocating it, and certain patterns will trigger interrupts in <code>Win32</code> which will result in exceptions showing in the debugger.</p> <p>How portable is this?</p>
[ { "answer_id": 370217, "author": "Martin Beckett", "author_id": 10897, "author_profile": "https://Stackoverflow.com/users/10897", "pm_score": 3, "selected": false, "text": "malloc" }, { "answer_id": 370229, "author": "FryGuy", "author_id": 28776, "author_profile": "https://Stackoverflow.com/users/28776", "pm_score": 2, "selected": false, "text": "class Foo\n{\npublic:\n void SomeFunction()\n {\n cout << _obj->value << endl;\n }\n\nprivate:\n SomeObject *_obj;\n}\n Foo SomeFunction 0xCDCDCDCD" }, { "answer_id": 370231, "author": "Airsource Ltd", "author_id": 18017, "author_profile": "https://Stackoverflow.com/users/18017", "pm_score": 2, "selected": false, "text": "...\n bool error; // uninitialised value\n if(something)\n {\n error = true;\n }\n return error;\n" }, { "answer_id": 370266, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 2, "selected": false, "text": "0xdeadbeef" }, { "answer_id": 370362, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 9, "selected": true, "text": "Value Name Description \n------ -------- -------------------------\n0xCD Clean Memory Allocated memory via malloc or new but never \n written by the application. \n\n0xDD Dead Memory Memory that has been released with delete or free. \n It is used to detect writing through dangling pointers. \n\n0xED or Aligned Fence 'No man's land' for aligned allocations. Using a \n0xBD different value here than 0xFD allows the runtime\n to detect not only writing outside the allocation,\n but to also identify mixing alignment-specific\n allocation/deallocation routines with the regular\n ones.\n\n0xFD Fence Memory Also known as \"no mans land.\" This is used to wrap \n the allocated memory (surrounding it with a fence) \n and is used to detect indexing arrays out of \n bounds or other accesses (especially writes) past\n the end (or start) of an allocated block.\n\n0xFD or Buffer slack Used to fill slack space in some memory buffers \n0xFE (unused parts of `std::string` or the user buffer \n passed to `fread()`). 0xFD is used in VS 2005 (maybe \n some prior versions, too), 0xFE is used in VS 2008 \n and later.\n\n0xCC When the code is compiled with the /GZ option,\n uninitialized variables are automatically assigned \n to this value (at byte level). \n\n\n// the following magic values are done by the OS, not the C runtime:\n\n0xAB (Allocated Block?) Memory allocated by LocalAlloc(). \n\n0xBAADF00D Bad Food Memory allocated by LocalAlloc() with LMEM_FIXED,but \n not yet written to. \n\n0xFEEEFEEE OS fill heap memory, which was marked for usage, \n but wasn't allocated by HeapAlloc() or LocalAlloc(). \n Or that memory just has been freed by HeapFree(). \n /*\n * The following values are non-zero, constant, odd, large, and atypical\n * Non-zero values help find bugs assuming zero filled data.\n * Constant values are good, so that memory filling is deterministic\n * (to help make bugs reproducible). Of course, it is bad if\n * the constant filling of weird values masks a bug.\n * Mathematically odd numbers are good for finding bugs assuming a cleared\n * lower bit.\n * Large numbers (byte values at least) are less typical and are good\n * at finding bad addresses.\n * Atypical values (i.e. not too often) are good since they typically\n * cause early detection in code.\n * For the case of no man's land and free blocks, if you store to any\n * of these locations, the memory integrity checker will detect it.\n *\n * _bAlignLandFill has been changed from 0xBD to 0xED, to ensure that\n * 4 bytes of that (0xEDEDEDED) would give an inaccessible address under 3gb.\n */\n\nstatic unsigned char _bNoMansLandFill = 0xFD; /* fill no-man's land with this */\nstatic unsigned char _bAlignLandFill = 0xED; /* fill no-man's land for aligned routines */\nstatic unsigned char _bDeadLandFill = 0xDD; /* fill free objects with this */\nstatic unsigned char _bCleanLandFill = 0xCD; /* fill new objects with this */\n std::string fread() _SECURECRT_FILL_BUFFER_PATTERN crtdefs.h 0xFD 0xFE fread() 0xFD" }, { "answer_id": 382035, "author": "Anthony Giorgio", "author_id": 9816, "author_profile": "https://Stackoverflow.com/users/9816", "pm_score": 1, "selected": false, "text": "-Wc,'initauto(deadbeef,word)'" }, { "answer_id": 40695192, "author": "Adrian McCarthy", "author_id": 1386054, "author_profile": "https://Stackoverflow.com/users/1386054", "pm_score": 2, "selected": false, "text": "int 3" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22489/" ]
370,202
<p>I'm using Grails to send a large number of HTML emails. I use the SimpleTemplateEngine to create my email bodies in this fashion:</p> <pre><code>def ccIdToEmailMap = [:] def emailTemplateFile = Utilities.retrieveFile("email${File.separator}emailTemplate.gtpl") def engine = new SimpleTemplateEngine() def clientContacts = ClientContact.list() for(ClientContact cc in clientContactList) { def binding = [clientContact : cc] //STOPS (FREEZES) EITHER HERE OR.... def template = template = engine.createTemplate(emailTemplateFile).make(binding) //OR STOPS (FREEZES) HERE def body = template.toString() def email = [text: body, to: cc.emailAddress] ccIdToEmailMap.put(cc.id, email) println "added to map" } return ccIdToEmailMap </code></pre> <p>Here is the template I'm trying to render for each email body:</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Happy Holidays from google Partners&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;table width="492" cellpadding="0" cellspacing="0" style="border:2px solid #acacac;margin:8px auto;" align="center"&gt; &lt;tr&gt; &lt;td colspan="5" bgcolor="#c1e0f3"&gt;&lt;img src="http://www.google.com/holiday2008/cardbg.gif" width="492" height="10" border="0"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td width="6" bgcolor="#c1e0f3"&gt;&lt;img src="http://www.google.com/holiday2008/sidebgl.gif" width="6" height="453" border="0"&gt;&lt;/td&gt; &lt;td style="background:#fff;border:1px solid #acacac;padding:2px;" width="228"&gt; &lt;div style="width:208px;margin:4px 8px 0px 8px; color:#515151;"&gt; &lt;font face="Times New Roman" size="2"&gt; &lt;span style="font:14px 'Times New Roman',times,serif;"&gt;Static text that is the same for each email &lt;br&gt;&amp;nbsp;&lt;br&gt; More text &lt;br&gt;&amp;nbsp;&lt;br&gt; We wish you health and happiness during the holidays and a year of growth in 2009. &lt;/span&gt; &lt;/font&gt; &lt;/div&gt; &lt;/td&gt; &lt;td style="background:#c9f4fe;border-top:1px solid #acacac;border-bottom:1px solid #acacac;" width="5"&gt;&lt;img src="http://www.google.com/holiday2008/vertbg.gif" border="0" height="453" width="5"&gt;&lt;/td&gt; &lt;td width="247" style="background:#fff;border:1px solid #acacac;"&gt;&lt;img src="http://www.google.com/holiday2008/snowing.gif" width="247" height="453" border="0"&gt;&lt;/td&gt; &lt;td width="6" bgcolor="#c1e0f3"&gt;&lt;img src="http://www.google.com/holiday2008/sidebgr.gif" width="6" height="453" border="0"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td width="6" bgcolor="#c1e0f3"&gt;&lt;img src="http://www.google.com/holiday2008/sidebgr.gif" width="6" height="38" border="0"&gt;&lt;/td&gt; &lt;td colspan="3" style="border:1px solid #acacac;" align="center"&gt;&lt;img src="http://www.google.com/holiday2008/happyholidays.gif" width="480" height="38" alt="Happy Holidays" border="0"&gt;&lt;/td&gt; &lt;td width="6" bgcolor="#c1e0f3"&gt;&lt;img src="http://www.google.com/holiday2008/sidebgr.gif" width="6" height="38" border="0"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td width="6" bgcolor="#c1e0f3"&gt;&lt;img src="http://www.google.com/holiday2008/sidebgr.gif" width="6" height="120" border="0"&gt;&lt;/td&gt; &lt;td colspan="3" style="background-color#fff;border:1px solid #acacac;padding:2px;" valign="top"&gt; &lt;img src="http://www.google.com/holiday2008/gogl_logo_card.gif" width="140" height="40" alt="google partners" border="0" align="right" hspace="4" vspace="4" /&gt; &lt;font face="Times New Roman" size="2"&gt; &lt;div style="padding:4px;font:12pt 'Times New Roman',serif;color:#515151;"&gt; &lt;span style="font-size:10pt"&gt;&lt;i&gt;from:&lt;/i&gt;&lt;/span&gt; &lt;div style="padding:2px 4px;"&gt; &lt;% clientContact.owners.eachWithIndex { it, i -&gt; %&gt; &lt;% if(i &lt; (clientContact.owners.size() - 1)) { %&gt; ${it.toString()}, &lt;% }else { %&gt; ${it.toString()} &lt;% } %&gt; &lt;% } %&gt; &lt;/div&gt; &lt;/div&gt; &lt;/font&gt; &lt;/td&gt; &lt;td width="6" bgcolor="#c1e0f3"&gt;&lt;img src="http://www.google.com/holiday2008/sidebgr.gif" width="6" height="120" border="0"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td colspan="5" bgcolor="#c1e0f3"&gt;&lt;img src="http://www.google.com/holiday2008/cardbg.gif" width="492" height="10" border="0"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Once this methods returns the ccIdToEmail map, I send out all of my emails. For some reason, preparing this map of clientContactIds and email bodies causes my application to freeze at either of the two lines listed above. I can successfully prepare/send ~140 emails before it freezes. This happens very consistently.</p> <p>Does anyone know why this would work but then stop working after a ~140 email bodies are created from a template? I haven't been able to find anything online about other peope having trouble with this.</p> <p>Andrew</p>
[ { "answer_id": 370727, "author": "Siegfried Puchbauer", "author_id": 46301, "author_profile": "https://Stackoverflow.com/users/46301", "pm_score": 1, "selected": false, "text": " def ccIdToEmailMap = [:]\n def emailTemplateFile = Utilities.retrieveFile(\"email${File.separator}emailTemplate.gtpl\")\n def engine = new SimpleTemplateEngine()\n def template = engine.createTemplate(emailTemplateFile)\n def clientContacts = ClientContact.list()\n for(ClientContact cc in clientContactList)\n {\n def binding = [clientContact : cc]\n def body = template.make(binding).toString()\n def email = [text: body, to: cc.emailAddress]\n ccIdToEmailMap.put(cc.id, email)\n println \"added to map\"\n }\n return ccIdToEmailMap\n" }, { "answer_id": 373095, "author": "anschoewe", "author_id": 21832, "author_profile": "https://Stackoverflow.com/users/21832", "pm_score": 1, "selected": true, "text": " def emailTemplateFile = null\n def ccIdToEmailMap = [:]\n\n emailTemplateFile = Utilities.retrieveFile(\"email${File.separator}emailTemplate.gtpl\")\n def engine = new SimpleTemplateEngine()\n def template = engine.createTemplate(emailTemplateFile)\n for(ClientContact cc in clientContactList)\n {\n //there was a locking problem when we tried to create the template for too many client contacts\n //i believe it was caused by lazy-fetching of the person/owners. So, I fetch them before we bind\n //and make the email body.\n def criteria = ClientContact.createCriteria()\n cc = criteria.get {\n eq(\"id\", cc.id)\n fetchMode('relationship', FM.EAGER)\n fetchMode('relationship.person', FM.EAGER)\n }\n def binding = [clientContact : cc]\n def body = template.make(binding).toString()\n def email = [text: body, to: cc.emailAddress]\n ccIdToEmailMap.put(cc.id, email)\n }\n\n return ccIdToEmailMap\n" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370202", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21832/" ]
370,204
<p>Is there a way to run a specific Ant task via the keyboard? I have a rsync to dev task that I run a lot and running to the mouse to double-click is a pain.</p>
[ { "answer_id": 370609, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 5, "selected": true, "text": "\"Run Last Launched External Tool\"" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/46443/" ]
370,211
<p>I wanna stop the reading of my text input file when the word "synonyms" appears. I'm using ifstream and I don't know how to break the loop. I tried using a stringstream "synonyms" but it ended up junking my bst. I included the complete project files below in case you wanna avoid typing. </p> <p>Important part:</p> <pre><code> for(;;) /*here, I wanna break the cycle when it reads "synonyms"*/ { inStream &gt;&gt; word; if (inStream.eof()) break; wordTree.insert(word); } wordTree.graph(cout); </code></pre> <p>dictionary.txt</p> <pre><code> 1 cute 2 hello 3 ugly 4 easy 5 difficult 6 tired 7 beautiful synonyms 1 7 7 1 antonyms 1 3 3 1 7 4 5 5 4 7 3 </code></pre> <p>Project.cpp</p> <pre><code>#include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;string&gt; #include &lt;sstream&gt; #include "MiBST.h" using namespace std; class WordInfo{ public: //--id accesor int id ()const {return myId; } /* myId is the number that identifies each word*/ //--input function void read (istream &amp;in) { in&gt;&gt;myId&gt;&gt;word; } //--output function void print(ostream &amp;out) { out&lt;&lt;myId&lt;&lt;" "&lt;&lt;word; } //--- equals operator bool operator==(const WordInfo &amp; otherword) const { return myId == otherword.myId; } //--- less-than operator bool operator&lt;(const WordInfo &amp; otherword) const { return myId &lt; otherword.myId; } private: int myId; string word; }; //--- Definition of input operator istream &amp; operator&gt;&gt;(istream &amp; in, WordInfo &amp; word) { word.read(in); } //---Definition of output operator ostream &amp; operator &lt;&lt;(ostream &amp;out, WordInfo &amp;word) { word.print(out); } int main(){ // Open stream to file of ids and words string wordFile; cout &lt;&lt; "Enter name of dictionary file: "; getline(cin, wordFile); ifstream inStream(wordFile.data()); if (!inStream.is_open()) { cerr &lt;&lt; "Cannot open " &lt;&lt; wordFile &lt;&lt; "\n"; exit(1); } // Build the BST of word records BST&lt;WordInfo&gt; wordTree; // BST of word records WordInfo word; // a word record for(;;) /*here, I wanna break the cycle when it reads "synonyms"*/ { inStream &gt;&gt; word; if (inStream.eof()) break; wordTree.insert(word); } wordTree.graph(cout); //wordTree.inorder(cout); system ("PAUSE"); return 0; } </code></pre> <p>MiBST.h (in case you wanna run it)</p> <pre><code>#include &lt;iostream&gt; #include &lt;iomanip&gt; #ifndef BINARY_SEARCH_TREE #define BINARY_SEARCH_TREE template &lt;typename DataType&gt; class BST { public: /***** Function Members *****/ BST(); bool empty() const; bool search(const DataType &amp; item) const; void insert(const DataType &amp; item); void remove(const DataType &amp; item); void inorder(std::ostream &amp; out) const; void graph(std::ostream &amp; out) const; private: /***** Node class *****/ class BinNode { public: DataType data; BinNode * left; BinNode * right; // BinNode constructors // Default -- data part is default DataType value; both links are null. BinNode() : left(0), right(0) {} // Explicit Value -- data part contains item; both links are null. BinNode(DataType item) : data(item), left(0), right(0) {} }; //end inner class typedef BinNode * BinNodePointer; /***** Private Function Members *****/ void search2(const DataType &amp; item, bool &amp; found, BinNodePointer &amp; locptr, BinNodePointer &amp; parent) const; /*------------------------------------------------------------------------ Locate a node containing item and its parent. Precondition: None. Postcondition: locptr points to node containing item or is null if not found, and parent points to its parent.#include &lt;iostream&gt; ------------------------------------------------------------------------*/ void inorderAux(std::ostream &amp; out, BST&lt;DataType&gt;::BinNodePointer subtreePtr) const; /*------------------------------------------------------------------------ Inorder traversal auxiliary function. Precondition: ostream out is open; subtreePtr points to a subtree of this BST. Postcondition: Subtree with root pointed to by subtreePtr has been output to out. ------------------------------------------------------------------------*/ void graphAux(std::ostream &amp; out, int indent, BST&lt;DataType&gt;::BinNodePointer subtreeRoot) const; /*------------------------------------------------------------------------ Graph auxiliary function. Precondition: ostream out is open; subtreePtr points to a subtree of this BST. Postcondition: Graphical representation of subtree with root pointed to by subtreePtr has been output to out, indented indent spaces. ------------------------------------------------------------------------*/ /***** Data Members *****/ BinNodePointer myRoot; }; // end of class template declaration //--- Definition of constructor template &lt;typename DataType&gt; inline BST&lt;DataType&gt;::BST() : myRoot(0) {} //--- Definition of empty() template &lt;typename DataType&gt; inline bool BST&lt;DataType&gt;::empty() const { return myRoot == 0; } //--- Definition of search() template &lt;typename DataType&gt; bool BST&lt;DataType&gt;::search(const DataType &amp; item) const { typename BST&lt;DataType&gt;::BinNodePointer locptr = myRoot; typename BST&lt;DataType&gt;::BinNodePointer parent =0; /* BST&lt;DataType&gt;::BinNodePointer locptr = myRoot; parent = 0; */ //falta el typename en la declaracion original bool found = false; while (!found &amp;&amp; locptr != 0) { if (item &lt; locptr-&gt;data) // descend left locptr = locptr-&gt;left; else if (locptr-&gt;data &lt; item) // descend right locptr = locptr-&gt;right; else // item found found = true; } return found; } //--- Definition of insert() template &lt;typename DataType&gt; inline void BST&lt;DataType&gt;::insert(const DataType &amp; item) { typename BST&lt;DataType&gt;::BinNodePointer locptr = myRoot, // search pointer parent = 0; // pointer to parent of current node bool found = false; // indicates if item already in BST while (!found &amp;&amp; locptr != 0) { parent = locptr; if (item &lt; locptr-&gt;data) // descend left locptr = locptr-&gt;left; else if (locptr-&gt;data &lt; item) // descend right locptr = locptr-&gt;right; else // item found found = true; } if (!found) { // construct node containing item locptr = new typename BST&lt;DataType&gt;::BinNode(item); if (parent == 0) // empty tree myRoot = locptr; else if (item &lt; parent-&gt;data ) // insert to left of parent parent-&gt;left = locptr; else // insert to right of parent parent-&gt;right = locptr; } else std::cout &lt;&lt; "Item already in the tree\n"; } //--- Definition of remove() template &lt;typename DataType&gt; void BST&lt;DataType&gt;::remove(const DataType &amp; item) { bool found; // signals if item is found typename BST&lt;DataType&gt;::BinNodePointer x, // points to node to be deleted parent; // " " parent of x and xSucc search2(item, found, x, parent); if (!found) { std::cout &lt;&lt; "Item not in the BST\n"; return; } //else if (x-&gt;left != 0 &amp;&amp; x-&gt;right != 0) { // node has 2 children // Find x's inorder successor and its parent typename BST&lt;DataType&gt;::BinNodePointer xSucc = x-&gt;right; parent = x; while (xSucc-&gt;left != 0) // descend left { parent = xSucc; xSucc = xSucc-&gt;left; } // Move contents of xSucc to x and change x // to point to successor, which will be removed. x-&gt;data = xSucc-&gt;data; x = xSucc; } // end if node has 2 children // Now proceed with case where node has 0 or 2 child typename BST&lt;DataType&gt;::BinNodePointer subtree = x-&gt;left; // pointer to a subtree of x if (subtree == 0) subtree = x-&gt;right; if (parent == 0) // root being removed myRoot = subtree; else if (parent-&gt;left == x) // left child of parent parent-&gt;left = subtree; else // right child of parent parent-&gt;right = subtree; delete x; } //--- Definition of inorder() template &lt;typename DataType&gt; inline void BST&lt;DataType&gt;::inorder(std::ostream &amp; out) const { inorderAux(out, myRoot); } //--- Definition of graph() template &lt;typename DataType&gt; inline void BST&lt;DataType&gt;::graph(std::ostream &amp; out) const { graphAux(out, 0, myRoot); } //--- Definition of search2() template &lt;typename DataType&gt; void BST&lt;DataType&gt;::search2(const DataType &amp; item, bool &amp; found, BST&lt;DataType&gt;::BinNodePointer &amp; locptr, BST&lt;DataType&gt;::BinNodePointer &amp; parent) const { locptr = myRoot; parent = 0; found = false; while (!found &amp;&amp; locptr != 0) { if (item &lt; locptr-&gt;data) // descend left { parent = locptr; locptr = locptr-&gt;left; } else if (locptr-&gt;data &lt; item) // descend right { parent = locptr; locptr = locptr-&gt;right; } else // item found found = true; } } //--- Definition of inorderAux() template &lt;typename DataType&gt; void BST&lt;DataType&gt;::inorderAux(std::ostream &amp; out, BST&lt;DataType&gt;::BinNodePointer subtreeRoot) const { if (subtreeRoot != 0) { inorderAux(out, subtreeRoot-&gt;left); // L operation out &lt;&lt; subtreeRoot-&gt;data &lt;&lt; " "; // V operation inorderAux(out, subtreeRoot-&gt;right); // R operation } } //--- Definition of graphAux() template &lt;typename DataType&gt; void BST&lt;DataType&gt;::graphAux(std::ostream &amp; out, int indent, BST&lt;DataType&gt;::BinNodePointer subtreeRoot) const { if (subtreeRoot != 0) { graphAux(out, indent + 8, subtreeRoot-&gt;right); out &lt;&lt; std::setw(indent) &lt;&lt; " " &lt;&lt; subtreeRoot-&gt;data &lt;&lt; std::endl; graphAux(out, indent + 8, subtreeRoot-&gt;left); } } #endif </code></pre>
[ { "answer_id": 370225, "author": "SoapBox", "author_id": 36384, "author_profile": "https://Stackoverflow.com/users/36384", "pm_score": 2, "selected": false, "text": "if ( word == \"synonyms\" ) break;\n" }, { "answer_id": 370236, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 3, "selected": true, "text": "/* here, it stops when reading \"synonyms\" or when failing to extract a word. */\nwhile(inStream >> word && word != \"synonym\") {\n wordTree.insert(word);\n}\nwordTree.graph(cout);\n .eof(); 1 house 2 garden 3 tree\n if(inStream)" }, { "answer_id": 370249, "author": "andandandand", "author_id": 45963, "author_profile": "https://Stackoverflow.com/users/45963", "pm_score": 0, "selected": false, "text": " //--- equals operator for String\n bool operator==(const string & aString) const\n { return word == aString; } // word is the WordInfo string field for 'real' word\n for(;;)\n {\n\n\n inStream >> word;\n if (word==\"synonyms\") break;\n\n wordTree.insert(word);\n }\n \"Item already in the tree\"\n dict2.txt\n" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45963/" ]
370,215
<p>I am trying to process an uploaded file in a Perl program, using CGI::Application. I need to get the content type of the uploaded file. From what I read, the following should work, but it doesn't for me:</p> <pre><code>my $filename = $q-&gt;param("file"); my $contenttype = $q-&gt;uploadInfo($filename)-&gt;{'Content-Type'}; </code></pre> <p>As it turns out, <code>$q-&gt;uploadInfo($filename)</code> returns <code>undef</code>. So does <code>$q-&gt;uploadInfo("file")</code>.</p> <p>Any ideas?</p> <p>Thanks!</p>
[ { "answer_id": 370342, "author": "ysth", "author_id": 17389, "author_profile": "https://Stackoverflow.com/users/17389", "pm_score": 4, "selected": true, "text": "chomp(my $mime_type = qx!file -i $uploaded!);\n$mime_type =~ s/^.*?: //;\n$mime_type =~ s/;.*//;\n" }, { "answer_id": 370611, "author": "AmbroseChapel", "author_id": 242241, "author_profile": "https://Stackoverflow.com/users/242241", "pm_score": 1, "selected": false, "text": "$filename $cgi->cgi_error()" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370215", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4257/" ]
370,218
<p>I'm trying to setup a second ruby install in my home directory (a different version of ruby for testing). I've compiled ruby into <code>~/bin/</code> and everything is working until I try to install rubygems.</p> <p>I have <code>GEM_HOME</code> set to <code>~/gems</code> directory and <code>GEM_PATH</code> set to the same. Then I try to install rubygems with</p> <pre><code>~/bin/ruby setup.rb </code></pre> <p>The installation appears to succeed but ruby can't find rubygems after the install. </p> <pre><code>$~/bin/irb irb(main):001:0&gt; require 'rubygems' LoadError: no such file to load -- rubygems from (irb):1:in `require' from (irb):1 </code></pre> <p>Anyone have any idea why ruby can't find rubygems?</p>
[ { "answer_id": 370355, "author": "Gordon Wilson", "author_id": 23071, "author_profile": "https://Stackoverflow.com/users/23071", "pm_score": 3, "selected": true, "text": "GEM_HOME config $ export GEM_HOME=/home/mygemrepository\n$ ruby setup.rb config --prefix=/home/mystuff\n$ ruby setup.rb setup\n$ ruby setup.rb install\n" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370218", "https://Stackoverflow.com", "https://Stackoverflow.com/users/46505/" ]
370,222
<p>How can instantiated classes <strong>access the Document class?</strong></p> <p>Even after I <strong>name the Document class</strong> using the Properties bar in Flash, attempting to access it from other classes usually fails, saying <em>"attempting to access an undefined property...</em></p> <p>One solution is always <strong>casting the Document class to itself!</strong> eg.</p> <pre><code>Main(Main).globalMethod(); </code></pre> <p>But sometimes even this stellar gotcha fails, and then there's usually no way out, apart from <strong>the obvious!</strong></p> <pre><code>class Other{ var parentClass:Main; public function Other(parent:Main){ parentClass = parent; // pointer to the Main class in a local var! Main(parentClass).globalMethod(); } } </code></pre>
[ { "answer_id": 371625, "author": "Matt W", "author_id": 32396, "author_profile": "https://Stackoverflow.com/users/32396", "pm_score": 2, "selected": false, "text": "stage.getChildAt( 0 );" }, { "answer_id": 373591, "author": "aaaidan", "author_id": 26331, "author_profile": "https://Stackoverflow.com/users/26331", "pm_score": 6, "selected": true, "text": "Main public class Main extends Sprite {\n private static var _instance:Main;\n public static function get instance():Main { return _instance; }\n\n public function Main() {\n _instance = this;\n // etc...\n }\n\n // etc...\n}\n Main public class Other {\n public function Other() {\n Main.instance.usefulInstanceMethod();\n }\n}\n" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41021/" ]
370,258
<p>I've been reading about the <a href="http://en.wikipedia.org/wiki/Open/closed_principle" rel="noreferrer">OCP principle</a> and how to use the strategy pattern to accomplish this.</p> <p>I was going to try and explain this to a couple of people, but the only example I can think of is using different validation classes based on what status an &quot;order&quot; is.</p> <p>I've read a couple of articles online, but these don't usually describe a real alike reason to use the strategy, like generating reports/bills/validation, etc...</p> <p>Are there any real-world examples where you think a strategy pattern is common?</p>
[ { "answer_id": 370270, "author": "OscarRyz", "author_id": 20654, "author_profile": "https://Stackoverflow.com/users/20654", "pm_score": 7, "selected": false, "text": " File file = getFile();\n Cipher c = CipherFactory.getCipher( file.size() );\n c.performAction();\n\n\n\n// implementations:\ninterface Cipher {\n public void performAction();\n}\n\nclass InMemoryCipherStrategy implements Cipher { \n public void performAction() {\n // load in byte[] ....\n }\n}\n\nclass SwaptToDiskCipher implements Cipher { \n public void performAction() {\n // swapt partial results to file.\n }\n\n}\n Cipher c = CipherFactory.getCipher( file.size() );\n" }, { "answer_id": 370502, "author": "Alan", "author_id": 17205, "author_profile": "https://Stackoverflow.com/users/17205", "pm_score": 1, "selected": false, "text": "public interface CollectibleElephant { \n long getId();\n String getName();\n long getTagId();\n}\n\npublic class Elephant implements CollectibleElephant { ... }\npublic class BabyElephant implements CollectibleElephant { ... }\n CollectibleElephant Elephant CollectibleElephant" }, { "answer_id": 471233, "author": "grootjans", "author_id": 30971, "author_profile": "https://Stackoverflow.com/users/30971", "pm_score": 2, "selected": false, "text": "order.Ship();\n" }, { "answer_id": 2043042, "author": "Fabian Steeg", "author_id": 18154, "author_profile": "https://Stackoverflow.com/users/18154", "pm_score": 4, "selected": false, "text": "List<String> names = Arrays.asList(\"Anne\", \"Joe\", \"Harry\");\nCollections.sort(names, new Comparator<String>() {\n public int compare(String o1, String o2) {\n return o1.length() - o2.length();\n }\n});\nAssert.assertEquals(Arrays.asList(\"Joe\", \"Anne\", \"Harry\"), names);\n List<Document> set = db.query(new Predicate<Document>() {\n public boolean match(Document candidate) {\n return candidate.getSource().contains(source);\n }\n});\n" }, { "answer_id": 12740332, "author": "Gui Prá", "author_id": 180581, "author_profile": "https://Stackoverflow.com/users/180581", "pm_score": 3, "selected": false, "text": "A B C B C A rollbackStrategy.reportSuccessA(...);\nrollbackStrategy.reportFailureB(...);\n\nif (rollbackStrategy.mustAbort()) {\n rollbackStrategy.rollback(); // rollback whatever is needed based on reports\n return false;\n}\n QuitterStrategy MaximizeDeliveryToAStrategy A B C" }, { "answer_id": 21165199, "author": "Céryl Wiltink", "author_id": 1535282, "author_profile": "https://Stackoverflow.com/users/1535282", "pm_score": 6, "selected": false, "text": "public interface IRule {\n bool IsApproved(Assignment assignment); \n }\n IsApproved public OvertimeRule : IRule\n{\n public bool IsApproved(Assignment assignment) //Interface method\n {\n if (assignment.Person.Timesheet >= 40)\n {\n return false;\n }\n return true;\n }\n}\n\npublic InternRule : IRule\n{\n public bool IsApproved(Assignment assignment) //Interface method\n {\n if (assignment.Person.Title == \"Intern\")\n {\n return false;\n }\n return true;\n }\n}\n" }, { "answer_id": 21208803, "author": "anomal", "author_id": 1112765, "author_profile": "https://Stackoverflow.com/users/1112765", "pm_score": 2, "selected": false, "text": "android.text.format.Time java.util.Calendar public interface DatetimeMath { \n public Object createDatetime(int year, int month, int day);\n\n public int getDayOfWeek(Object datetime);\n\n public void increment(Object datetime);\n}\n public class TimeMath implements DatetimeMath {\n @Override\n public Object createDatetime(int year, int month, int day) {\n Time t = new Time();\n t.set(day, month, year);\n t.normalize(false);\n return t;\n }\n\n @Override\n public int getDayOfWeek(Object o) {\n Time t = (Time)o;\n return t.weekDay;\n } \n\n @Override\n public void increment(Object o) {\n Time t = (Time)o;\n t.set(t.monthDay + 1, t.month, t.year);\n t.normalize(false);\n }\n}\n public class OrdinalDayOfWeekCalculator { \n private DatetimeMath datetimeMath;\n\n public OrdinalDayOfWeekCalculator(DatetimeMath m) {\n datetimeMath = m;\n }\n\n public Object getDate(int year, int month, int dayOfWeek, int ordinal) {\n Object datetime = datetimeMath.createDatetime(year, month, 1);\n if (datetimeMath.getDayOfWeek(datetime) == dayOfWeek) {\n return datetime;\n } \n int xDayCount = 0;\n while (xDayCount != ordinal) {\n datetimeMath.increment(datetime);\n if (datetimeMath.getDayOfWeek(datetime) == dayOfWeek) {\n xDayCount++;\n }\n }\n return datetime;\n }\n}\n OrdinalDayOfWeekCalculator odowc = \n new OrdinalDayOfWeekCalculator(new TimeMath());\nTime canadianThanksgiving = (Time)odowc.getDate(\n year, Calendar.OCTOBER, Time.MONDAY, 2);\n java.util.Calendar OrdinalDayOfWeekCalculator odowc2 = \n new OrdinalDayOfWeekCalculator(new CalendarMath());\nCalendar canadianThanksgivingCal = (Calendar)odowc2.getDate(\n year, Calendar.OCTOBER, Calendar.MONDAY, 2);\n" }, { "answer_id": 31291537, "author": "Jatinder Pal", "author_id": 5060478, "author_profile": "https://Stackoverflow.com/users/5060478", "pm_score": 3, "selected": false, "text": "enum Speed {\n SLOW, MEDIUM, FAST;\n}\n\nclass Sorter {\n public void sort(int[] input, Speed speed) {\n SortStrategy strategy = null;\n switch (speed) {\n case SLOW:\n strategy = new SlowBubbleSortStrategy();\n break;\n case MEDIUM:\n strategy = new MediumInsertationSortStrategy();\n break;\n\n case FAST:\n strategy = new FastQuickSortStrategy();\n break;\n default:\n strategy = new MediumInsertationSortStrategy();\n }\n strategy.sort(input);\n }\n\n}\n\ninterface SortStrategy {\n\n public void sort(int[] input);\n}\n\nclass SlowBubbleSortStrategy implements SortStrategy {\n\n public void sort(int[] input) {\n for (int i = 0; i < input.length; i++) {\n for (int j = i + 1; j < input.length; j++) {\n if (input[i] > input[j]) {\n int tmp = input[i];\n input[i] = input[j];\n input[j] = tmp;\n }\n }\n }\n System.out.println(\"Slow sorting is done and the result is :\");\n for (int i : input) {\n System.out.print(i + \",\");\n }\n }\n\n }\n\nclass MediumInsertationSortStrategy implements SortStrategy {\n\npublic void sort(int[] input) {\n for (int i = 0; i < input.length - 1; i++) {\n int k = i + 1;\n int nxtVal = input[k];\n while (input[k - 1] > nxtVal) {\n input[k] = input[k - 1];\n k--;\n if (k == 0)\n break;\n }\n input[k] = nxtVal;\n }\n System.out.println(\"Medium sorting is done and the result is :\");\n for (int i : input) {\n System.out.print(i + \",\");\n }\n\n }\n\n}\n\nclass FastQuickSortStrategy implements SortStrategy {\n\npublic void sort(int[] input) {\n sort(input, 0, input.length-1);\n System.out.println(\"Fast sorting is done and the result is :\");\n for (int i : input) {\n System.out.print(i + \",\");\n }\n}\n\nprivate void sort(int[] input, int startIndx, int endIndx) {\n int endIndexOrig = endIndx;\n int startIndexOrig = startIndx;\n if( startIndx >= endIndx)\n return;\n int pavitVal = input[endIndx];\n while (startIndx <= endIndx) {\n while (input[startIndx] < pavitVal)\n startIndx++;\n while (input[endIndx] > pavitVal)\n endIndx--;\n if( startIndx <= endIndx){\n int tmp = input[startIndx];\n input[startIndx] = input[endIndx];\n input[endIndx] = tmp;\n startIndx++;\n endIndx--;\n }\n }\n sort(input, startIndexOrig, endIndx);\n sort(input, startIndx, endIndexOrig);\n }\n\n} \n public class StrategyPattern {\n public static void main(String[] args) {\n Sorter sorter = new Sorter();\n int[] input = new int[] {7,1,23,22,22,11,0,21,1,2,334,45,6,11,2};\n System.out.print(\"Input is : \");\n for (int i : input) {\n System.out.print(i + \",\");\n }\n System.out.println();\n sorter.sort(input, Speed.SLOW);\n }\n\n}\n" }, { "answer_id": 35180265, "author": "Ravindra babu", "author_id": 4999394, "author_profile": "https://Stackoverflow.com/users/4999394", "pm_score": 5, "selected": false, "text": "import java.util.*;\n\n/* Interface for Strategy */\ninterface OfferStrategy {\n public String getName();\n public double getDiscountPercentage();\n}\n/* Concrete implementation of base Strategy */\nclass NoDiscountStrategy implements OfferStrategy{\n public String getName(){\n return this.getClass().getName();\n }\n public double getDiscountPercentage(){\n return 0;\n }\n}\n/* Concrete implementation of base Strategy */\nclass QuarterDiscountStrategy implements OfferStrategy{\n public String getName(){\n return this.getClass().getName();\n }\n public double getDiscountPercentage(){\n return 0.25;\n }\n}\n/* Context is optional. But if it is present, it acts as single point of contact\n for client. \n\n Multiple uses of Context\n 1. It can populate data to execute an operation of strategy\n 2. It can take independent decision on Strategy creation. \n 3. In absence of Context, client should be aware of concrete strategies. Context acts a wrapper and hides internals\n 4. Code re-factoring will become easy\n*/\nclass StrategyContext {\n double price; // price for some item or air ticket etc.\n Map<String,OfferStrategy> strategyContext = new HashMap<String,OfferStrategy>();\n StrategyContext(double price){\n this.price= price;\n strategyContext.put(NoDiscountStrategy.class.getName(),new NoDiscountStrategy());\n strategyContext.put(QuarterDiscountStrategy.class.getName(),new QuarterDiscountStrategy()); \n }\n public void applyStrategy(OfferStrategy strategy){\n /* \n Currently applyStrategy has simple implementation. You can use Context for populating some more information,\n which is required to call a particular operation \n */\n System.out.println(\"Price before offer :\"+price);\n double finalPrice = price - (price*strategy.getDiscountPercentage());\n System.out.println(\"Price after offer:\"+finalPrice);\n }\n public OfferStrategy getStrategy(int monthNo){\n /*\n In absence of this Context method, client has to import relevant concrete Strategies everywhere.\n Context acts as single point of contact for the Client to get relevant Strategy\n */\n if ( monthNo < 6 ) {\n return strategyContext.get(NoDiscountStrategy.class.getName());\n }else{\n return strategyContext.get(QuarterDiscountStrategy.class.getName());\n }\n\n }\n}\npublic class StrategyDemo{ \n public static void main(String args[]){\n StrategyContext context = new StrategyContext(100);\n System.out.println(\"Enter month number between 1 and 12\");\n int month = Integer.parseInt(args[0]);\n System.out.println(\"Month =\"+month);\n OfferStrategy strategy = context.getStrategy(month);\n context.applyStrategy(strategy);\n }\n\n}\n Enter month number between 1 and 12\nMonth =1\nPrice before offer :100.0\nPrice after offer:100.0\n\nEnter month number between 1 and 12\nMonth =7\nPrice before offer :100.0\nPrice after offer:75.0\n" }, { "answer_id": 44125911, "author": "Vivek Goel", "author_id": 2629440, "author_profile": "https://Stackoverflow.com/users/2629440", "pm_score": 2, "selected": false, "text": "public class StrategyDemo {\n public static void main(String[] args) {\n ShoppingCart cart = new ShoppingCart();\n\n Item item1 = new Item(\"1234\", 10);\n Item item2 = new Item(\"5678\", 40);\n\n cart.addItem(item1);\n cart.addItem(item2);\n\n // pay by paypal\n cart.pay(new PaypalStrategy(\"myemail@example.com\", \"mypwd\"));\n\n // pay by credit card\n cart.pay(new CreditCardStrategy(\"Pankaj Kumar\", \"1234567890123456\", \"786\", \"12/15\"));\n }\n}\n\ninterface PaymentStrategy {\n public void pay(int amount);\n}\n\nclass CreditCardStrategy implements PaymentStrategy {\n\n private String name;\n private String cardNumber;\n private String cvv;\n private String dateOfExpiry;\n\n public CreditCardStrategy(String nm, String ccNum, String cvv, String expiryDate) {\n this.name = nm;\n this.cardNumber = ccNum;\n this.cvv = cvv;\n this.dateOfExpiry = expiryDate;\n }\n\n @Override\n public void pay(int amount) {\n System.out.println(amount + \" paid with credit/debit card\");\n }\n\n}\n\nclass PaypalStrategy implements PaymentStrategy {\n\n private String emailId;\n private String password;\n\n public PaypalStrategy(String email, String pwd) {\n this.emailId = email;\n this.password = pwd;\n }\n\n @Override\n public void pay(int amount) {\n System.out.println(amount + \" paid using Paypal.\");\n }\n\n}\n\nclass Item {\n\n private String upcCode;\n private int price;\n\n public Item(String upc, int cost) {\n this.upcCode = upc;\n this.price = cost;\n }\n\n public String getUpcCode() {\n return upcCode;\n }\n\n public int getPrice() {\n return price;\n }\n\n}\n\nclass ShoppingCart {\n\n // List of items\n List<Item> items;\n\n public ShoppingCart() {\n this.items = new ArrayList<Item>();\n }\n\n public void addItem(Item item) {\n this.items.add(item);\n }\n\n public void removeItem(Item item) {\n this.items.remove(item);\n }\n\n public int calculateTotal() {\n int sum = 0;\n for (Item item : items) {\n sum += item.getPrice();\n }\n return sum;\n }\n\n public void pay(PaymentStrategy paymentMethod) {\n int amount = calculateTotal();\n paymentMethod.pay(amount);\n }\n}\n" }, { "answer_id": 50753926, "author": "bharanitharan", "author_id": 358099, "author_profile": "https://Stackoverflow.com/users/358099", "pm_score": 0, "selected": false, "text": "Shape redCircle = new RedCircle(); // Without stretegy Pattern\nShaped redCircle = new Shape(\"red\",\"circle\"); // With Strategy pattern\n" }, { "answer_id": 63184989, "author": "Cédric S", "author_id": 12325896, "author_profile": "https://Stackoverflow.com/users/12325896", "pm_score": 0, "selected": false, "text": "interface FightingStategy{\n public void fight();\n}\npublic Defense implements FightingStrategy{\n public void figth(){\n ... hide behind wall to shoot\n }\n}\npublic Berserker implements FightingStrategy{\n public void fight(){\n ... run towards you, headrolls and shoots\n }\n}\npublic Dead implements FightingStrategy{\n public void fight(){\n ... is dead, doesn't move\n }\n}\n\npublic AiShooter{\n\n FightingStrategy fightingStrategy;\n\n public AiShooter(){\n fightStrategy = new Berserker();\n }\n\n public void fight(){\n this.fightingStrategy.fight();\n }\n\n public void changeStrategy(FightingStrategy f){\n this.fightingStrategy = f;\n }\n}\n\npublic static void main(){\n\n ... create list of AiShooters...\n while (condition){\n list.forEach(shooter -> shooter.fight());\n }\n ... you shoot back\n list.ForEach(shooter -> shooter.changeStrategy(new \nDefense()));\n\n ... you kill one\n list.get(n).changeStrategy(new Dead());\n}\n" }, { "answer_id": 67968630, "author": "Kuldeep", "author_id": 3759227, "author_profile": "https://Stackoverflow.com/users/3759227", "pm_score": 1, "selected": false, "text": "public interface TaxCalculation {\n\n public Double calculateTax(Double price); \n}\n public class FivePercentage implements TaxCalculation {\n\n @Override\n public Double calculateTax(Double price) {\n \n Double dbl = (price*5)/100;\n return dbl;\n }\n\n}\n public class EighteenPercentage implements TaxCalculation {\n\n @Override\n public Double calculateTax(Double price) {\n Double dbl = (price*18)/100;\n return dbl;\n }\n\n}\n public class Item {\n\n public String name;\n public Double price;\n public int taxRate;\n public Double totalTax;\n \n public Item(String name, Double price, int taxRate) {\n super();\n this.name = name;\n this.price = price;\n this.taxRate = taxRate;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n public Double getPrice() {\n return price;\n }\n public void setPrice(Double price) {\n this.price = price;\n }\n public int getTaxRate() {\n return taxRate;\n }\n\n public void setTaxRate(int taxRate) {\n this.taxRate = taxRate;\n }\n\n public Double getTotalTax() {\n return totalTax;\n }\n\n public void setTotalTax(Double totalTax) {\n this.totalTax = totalTax;\n }\n\n public void calculateTax(TaxCalculation taxcalulation, Double price) {\n this.totalTax = taxcalulation.calculateTax(price);\n }\n \n @Override\n public String toString() {\n return \"Items [name=\" + name + \", price=\" + price + \", taxRate=\" + taxRate + \", totalTax=\" + totalTax + \"]\";\n }\n \n}\n public class CalculateTax {\n\n public static void main(String[] args) {\n \n List<Item> itemList = new ArrayList<>();\n \n Item item1 = new Item(\"Engine Oil\", 320.0, 5);\n Item item2 = new Item(\"Painting\", 3500.00, 18);\n \n itemList.add(item1);\n itemList.add(item2);\n \n itemList.stream().forEach(x-> {\n if(x.getTaxRate() == 5) {\n x.calculateTax(new FivePercentage(), x.getPrice());\n } else if(x.getTaxRate() == 18) {\n x.calculateTax(new EighteenPercentage(), x.getPrice());\n }\n });\n \n itemList.stream().forEach(x-> {\n System.out.println(x.toString());\n });\n }\n}\n" }, { "answer_id": 67997973, "author": "Mazhar MIK", "author_id": 6841676, "author_profile": "https://Stackoverflow.com/users/6841676", "pm_score": 0, "selected": false, "text": "#include<iostream>\nusing namespace std;\n\n/*\n Where it is applicable?\n The selection of an algorithm is required from a family of algorithms.\n To avoid multiple conditional statements for selection of algorithms\n and to hide its algorithm data structures and complexity from client.\n*/\n\nclass Fly {\npublic:\n virtual void fly() = 0;\n};\n\n//concrete Fly : rocketFly\nclass rocketFly : public Fly {\npublic:\n void fly() {\n cout <<\"rocketFly::fly()\" << endl;\n }\n};\n\n//concrete Fly : normalFly\nclass normalFly : public Fly {\npublic:\n void fly() {\n cout <<\"normalFly::fly()\" << endl;\n }\n};\n\n//Duck \"HAS A\" relationship with Fly\nclass Duck {\nprivate:\n //Duck has a Fly behavour\n Fly* flyObj;\npublic:\n Duck(Fly* obj) : flyObj(obj) {\n \n }\n\n void DuckFly() {\n flyObj->fly();\n }\n};\n\nint main() {\n rocketFly* rObj = new rocketFly;\n Duck wildDuck(rObj);\n wildDuck.DuckFly();\n\n normalFly* nObj = new normalFly;\n Duck cityDuck(nObj);\n cityDuck.DuckFly();\n\n /*\n I didn't have to create classes like wildDuck which inherits from Duck and they implement their own\n fly, quack etc behaviour. There will be code duplication.\n So, instead of that, create an interface of fly, make concrete fly classes with different\n fly behaviour. Use objects to any of these concrete classes to inject to one generic duck\n class which will automatically call correct fly behaviour.\n */\n\nreturn 0;\n}\n" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370258", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
370,259
<p>I've been working with Swing for a while now but the whole model/structure of <code>JFrame</code>s, <code>paint()</code>, <code>super</code>, etc is all murky in my mind. I need a clear explanation or link that will explain how the whole GUI system is organized.</p>
[ { "answer_id": 370284, "author": "OscarRyz", "author_id": 20654, "author_profile": "https://Stackoverflow.com/users/20654", "pm_score": 5, "selected": true, "text": "JLabel LabelUI ui.update" }, { "answer_id": 371815, "author": "coobird", "author_id": 17172, "author_profile": "https://Stackoverflow.com/users/17172", "pm_score": 2, "selected": false, "text": "JFrame JFrame JFrame ContentPane RootPane GlassPane" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/51518/" ]
370,265
<p>Newbie question.</p> <p>I have a NSMutableArray that holds multiple objects (objects that stores Bezier paths and related variables e.g. path colour etc.) These are properly released whenever the relevant <code>-dealloc</code> method is called. Each object is instantiated with <code>+alloc/-init</code> and added to the array. After adding them to the array I <code>release</code> the object and hence their retainCount=1 (due to the array). Thus, when the array is released, the objects are also properly <code>dealloc</code>ated.</p> <p>But, I'm also implementing an undo/redo mechanism that removes/adds these objects from/to the NSMutable array. </p> <p>My question is, when an undo removes the object from the array, they are not released (otherwise redo will not work) so if redo is never called, how do you properly release these object?</p> <p>Hope that makes sense! Thanks!</p>
[ { "answer_id": 370438, "author": "Marc Charbonneau", "author_id": 35136, "author_profile": "https://Stackoverflow.com/users/35136", "pm_score": 3, "selected": true, "text": "registerUndoWithTarget: dealloc" }, { "answer_id": 370607, "author": "Ashley Clark", "author_id": 4556, "author_profile": "https://Stackoverflow.com/users/4556", "pm_score": 0, "selected": false, "text": "-removeAllActions -removeAllActionsWithTarget:" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370265", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41880/" ]
370,267
<p>This may seem like a stupid question, so here goes:</p> <p>Other than parsing the string of FileInfo.FullPath for the drive letter to then use DriveInfo("c") etc to see if there is enough space to write this file. Is there a way to get the drive letter from FileInfo?</p>
[ { "answer_id": 370279, "author": "Joel Martinez", "author_id": 5416, "author_profile": "https://Stackoverflow.com/users/5416", "pm_score": -1, "selected": false, "text": "FullPath.Substring(0,1);\n" }, { "answer_id": 370287, "author": "BFree", "author_id": 15861, "author_profile": "https://Stackoverflow.com/users/15861", "pm_score": 7, "selected": true, "text": "FileInfo f = new FileInfo(path); \nstring drive = Path.GetPathRoot(f.FullName);\n" }, { "answer_id": 3066845, "author": "Dan Tao", "author_id": 105570, "author_profile": "https://Stackoverflow.com/users/105570", "pm_score": 5, "selected": false, "text": "FileInfo file = new FileInfo(path);\nDriveInfo drive = new DriveInfo(file.Directory.Root.FullName);\n public static DriveInfo GetDriveInfo(this FileInfo file)\n{\n return new DriveInfo(file.Directory.Root.FullName);\n}\n DriveInfo drive = new FileInfo(path).GetDriveInfo();\n" }, { "answer_id": 10010667, "author": "Jayesh Sorathia", "author_id": 1282729, "author_profile": "https://Stackoverflow.com/users/1282729", "pm_score": -1, "selected": false, "text": "foreach (DriveInfo objDrive in DriveInfo.GetDrives())\n {\n Response.Write(\"</br>Drive Type : \" + objDrive.Name);\n Response.Write(\"</br>Drive Type : \" + objDrive.DriveType.ToString());\n Response.Write(\"</br>Available Free Space : \" + objDrive.AvailableFreeSpace.ToString() + \"(bytes)\");\n Response.Write(\"</br>Drive Format : \" + objDrive.DriveFormat);\n Response.Write(\"</br>Total Free Space : \" + objDrive.TotalFreeSpace.ToString() + \"(bytes)\");\n Response.Write(\"</br>Total Size : \" + objDrive.TotalSize.ToString() + \"(bytes)\");\n Response.Write(\"</br>Volume Label : \" + objDrive.VolumeLabel);\n Response.Write(\"</br></br>\");\n\n }\n" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28717/" ]
370,268
<p>Is this</p> <pre><code>... T1 join T2 using(ID) where T2.VALUE=42 ... </code></pre> <p>the same as</p> <pre><code>... T1 join T2 on(T1.ID=T2.ID) where T2.VALUE=42 ... </code></pre> <p>for all types of joins?</p> <p>My understanding of <code>using(ID)</code> is that it's just shorthand for <code>on(T1.ID=T2.ID)</code>. Is this true?</p> <p><br /> Now for another question:</p> <p>Is the above the same as</p> <pre><code>... T1 join T2 on(T1.ID=T2.ID and T2.VALUE=42) ... </code></pre> <p>This I don't think is true, but why? How does conditions in the on clause interact with the join vs if its in the where clause?</p>
[ { "answer_id": 370317, "author": "Cebjyre", "author_id": 1612, "author_profile": "https://Stackoverflow.com/users/1612", "pm_score": 5, "selected": true, "text": "T1 JOIN T2 USING(id) JOIN T3 USING(id_2)\n T1 JOIN T2 ON(T1.id=T2.id) JOIN T3 ON(T1.id_2=T3.id_2 AND T2.id_2=T3.id_2)\n T1 JOIN T2 ON(T1.id=T2.id) JOIN T3 ON(T2.id_2=T3.id_2)\n SELECT T1.ID, T2.ID, T2.VALUE FROM T1 LEFT OUTER JOIN T2 ON(T1.ID=T2.ID) WHERE T2.VALUE=42\n SELECT T1.ID, T2.ID, T2.VALUE FROM T1 LEFT OUTER JOIN T2 ON(T1.ID=T2.ID AND T2.VALUE=42)\n 1, NULL, NULL\n" }, { "answer_id": 370332, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 4, "selected": false, "text": "USING A JOIN B USING (column1)\n\nA JOIN B ON A.column1=B.column1\n A JOIN B USING (column1, column2)\n\nA JOIN B ON A.column1=B.column1 AND A.column2=B.column2\n USING (<columnlist>) ON <expr> <expr> INNER JOIN OUTER JOIN WHERE" }, { "answer_id": 41995730, "author": "Mark Reed", "author_id": 797049, "author_profile": "https://Stackoverflow.com/users/797049", "pm_score": 3, "selected": false, "text": " JOIN ... ON t1.common = t2.common\n common t1.common t2.common common JOIN ... USING (common)\n common t1.common t2.common" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21838/" ]
370,273
<p>I have a whole bunch of POV-RAY files from a molecular dynamics simulation with the general name "frameXX.pov" where "XX" is the number of the frame. I want to render them all but I have like 500 so I really don't wanna do it by hand. I'm sure there is a way to do this from the command line or a batch file...what would be the best way to do it? Thanks for the help :)</p>
[ { "answer_id": 558266, "author": "stevenvh", "author_id": 66056, "author_profile": "https://Stackoverflow.com/users/66056", "pm_score": 3, "selected": true, "text": "Input_File_Name=somegreatscene.pov\n\n; these are the default values\nInitial_Clock=0.000\nFinal_CLock=1.000\n\n; usually you'll start with Frame 0...\nInitial_Frame=50\nFinal_Frame=100\n\nHeight=640\nWidth=480\n ; render the first half of frames 50 to 100\nSubset_Start_Frame=50\nSubset_End_Frame=75\n" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41718/" ]
370,283
<p>I noticed C++ will not compile the following:</p> <pre><code>class No_Good { static double const d = 1.0; }; </code></pre> <p>However it will happily allow a variation where the double is changed to an int, unsigned, or any integral type:</p> <pre><code>class Happy_Times { static unsigned const u = 1; }; </code></pre> <p>My solution was to alter it to read:</p> <pre><code>class Now_Good { static double d() { return 1.0; } }; </code></pre> <p>and figure that the compiler will be smart enough to inline where necessary... but it left me curious.</p> <p>Why would the C++ designer(s) allow me to static const an int or unsigned, but not a double?</p> <p>Edit: I am using visual studio 7.1 (.net 2003) on Windows XP.</p> <p>Edit2:</p> <p>Question has been answered, but for completion, the error I was seeing:</p> <pre><code>error C2864: 'd' : only const static integral data members can be initialized inside a class or struct </code></pre>
[ { "answer_id": 370293, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 2, "selected": false, "text": "class Now_Better\n{\n static double const d;\n};\n double const Now_Better::d = 1.0;\n" }, { "answer_id": 370311, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 7, "selected": true, "text": "-O0 -O1 -O1 -O0 // File a.h\nclass X\n{\n public:\n static const double d = 1.0;\n};\n\nvoid foo(void);\n\n// File a.cc\n#include <stdio.h>\n\n#include \"a.h\"\n\nint main(void)\n{\n foo();\n printf(\"%g\\n\", X::d);\n\n return 0;\n}\n\n// File b.cc\n#include <stdio.h>\n\n#include \"a.h\"\n\nvoid foo(void)\n{\n printf(\"foo: %g\\n\", X::d);\n}\n g++ a.cc b.cc -O0 -o a # Linker error: ld: undefined symbols: X::d\ng++ a.cc b.cc -O1 -o a # Succeeds\n" }, { "answer_id": 370337, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 4, "selected": false, "text": "struct type {\n static const double value = 3.14;\n};\n constexpr struct type {\n static constexpr double value = 3.14;\n static constexpr double value_as_function() { return 3.14; }\n};\n type::value std::numeric_limits struct type {\n static double value() { return 3.14; }\n};\n Floating-point constant expressions" }, { "answer_id": 370433, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 3, "selected": false, "text": "class Curious {\n static const int c1 = 7; // ok, but remember definition\n static int c2 = 11; // error: not const\n const int c3 = 13; // error: not static\n static const int c4 = f(17); // error: in-class initializer not constant\n static const float c5 = 7.0; // error: in-class not integral\n // ...\n};\n const int Curious::c1; // necessary, but don't repeat initializer here\n class X {\n enum { c1 = 7, c2 = 11, c3 = 13, c4 = 17 };\n // ...\n};\n" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370283", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29703/" ]
370,286
<p>The code below pretty much sums up what I want to achieve. </p> <p>We have a solution which comprises many different projects however we have a need to be able to call methods in projects from projects which are not referenced (would cause circular reference).</p> <p>I have posted previous questions and the code below is pretty much what I have come up with using interfaces. I still do not know how I can call a method that resides in a different project that is not referenced.</p> <p>I cannot create an instance of the interface, it has to be a class. But how can I create an instance of a class that is not referenced. I do not want to use reflection for this. </p> <p>Code is C# 2.0</p> <p>Any help is appreciated.</p> <p>What code do I need to place in "GeneralMethod" (Class Raise) to be able to execute the "Update" method in Class "Listen" ?</p> <pre><code>// Link Project namespace Stack.Link { public class Interface { public interface Update { void Update(); } } } // Project A // References Link only namespace Stack.ProjA { public class Raise { public void GeneralMethod() { // I want to place code in here to be able to execute // "Update" method in ProjB. // Keep in mind that ProjA and ProjB only reference // Link Project } } } // Project B // References Link only namespace Stack.ProjB { public class Listen : Stack.Link.Interface.Update { public void Update() { // Do something here that is executed from ProjA Console.Write("Executed Method in ProjB"); } } } </code></pre> <p>I should probably clarify the motivation behind needing to do this. Perhaps there is a better way ....</p> <p>We have a baseform from which all other projects are referenced. As an example we pass an object which contains various settings to the project when it is loaded (from the baseform).</p> <p>If for example, the settings object has some variables change (settings object populated in baseform), we would like the loaded project to listen for this change and obtain a new settings object.</p> <p>Because the baseform references all the other projects, we need to have the projects "listen" for events in the baseform.</p> <p>Clear as mud :-)</p>
[ { "answer_id": 370302, "author": "Andrew Kennan", "author_id": 22506, "author_profile": "https://Stackoverflow.com/users/22506", "pm_score": 1, "selected": false, "text": "public interface IThing { void Update(); }\n\npublic static class ThingRegistry {\n public static void RegisterThing<T>() where T : IThing { ... }\n\n public static T CreateThing<T>() where T : IThing { ... }\n}\n internal class Thing : IThing { public void Update() { ... } }\n public class Listen { \n public void UpdateThing() {\n ThingRegistry.CreateThing<IThing>().Update();\n }\n}\n" }, { "answer_id": 370412, "author": "JoshBerke", "author_id": 26160, "author_profile": "https://Stackoverflow.com/users/26160", "pm_score": 0, "selected": false, "text": "public class EventBroadcaster {\n //use your singleton pattern of choice. This is not what I would reocmmend but its short\n private static EventBroadcaster Instance=new EventBroadcaster;\n\n public void RegisterForEvent(string key,Delegate del)\n {\n //Store the delegate in a dictionary<string,del>\n //You can also use multicast delegates so if your settings object changes notify all people who need it\n }\n\n public void FireEvent(string key,EventArgs e)\n {\n //Get the item and execute it. \n }\n}\n" }, { "answer_id": 372219, "author": "Marcus Erickson", "author_id": 38373, "author_profile": "https://Stackoverflow.com/users/38373", "pm_score": 2, "selected": false, "text": "Activator.CreateInstance public interface IRemote\n{\n void Update();\n}\n private void\n DoRemoteUpdate( string assemblyPath, string className )\n{ \n Assembly assembly = Assembly.Load(assemblyPath); \n Type objectType = assembly.GetType(className); \n\n remoteAssembly = (IRemote)Activator.CreateInstance(objectType); \n remoteAssembly.Update(); \n}\n" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370286", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
370,291
<p>I'm deserializing a class called <code>Method</code> using .NET Serialization. <code>Method</code> contains a list of objects implementing <code>IAction</code>. I originally used the <a href="http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlincludeattribute.aspx" rel="nofollow noreferrer"><code>[XmlInclude]</code></a> attribute to specify all classes which implement <code>IAction</code>. </p> <p>But now, I'd like to change my program to load all the dll's in a directory and strip out the classes which implement <code>IAction</code>. Then users can deserialize files which contain their actions implementing <code>IAction</code>. </p> <p>I don't control the classes which implement <code>IAction</code> anymore, therefore I can't use <a href="http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlincludeattribute.aspx" rel="nofollow noreferrer"><code>[XmlInclude]</code></a>.</p> <p>Is there a way to set this attribute at runtime? Or have a similar attribute set for the implementing class?</p> <pre><code>public class Method { public List&lt;Actions.IAction&gt; Actions = new List&lt;Actions.IAction&gt;(); } public interface IAction { void DoExecute(); } public static Type[] LoadActionPlugins(string pluginDirectoryPath) { List&lt;Type&gt; pluginTypes = new List&lt;Type&gt;(); string[] filesInDirectory = Directory.GetFiles(pluginDirectoryPath, "*.dll", SearchOption.TopDirectoryOnly); foreach (string pluginPath in filesInDirectory) { System.Reflection.Assembly actionPlugin = System.Reflection.Assembly.LoadFrom(pluginPath); Type[] assemblyTypes = actionPlugin.GetTypes(); foreach (Type type in assemblyTypes) { Type foundInterface = type.GetInterface("IAction"); if (foundInterface != null) { pluginTypes.Add(type); } } } return pluginTypes.Count == 0 ? null : pluginTypes.ToArray(); } </code></pre>
[ { "answer_id": 370395, "author": "David Norman", "author_id": 34502, "author_profile": "https://Stackoverflow.com/users/34502", "pm_score": 4, "selected": true, "text": "public XmlSerializer(\n Type type,\n Type[] extraTypes\n);\n" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/165305/" ]
370,292
<p>Is it worth changing my code to be "more portable" and able to deal with the horror of magic quotes, or should I just make sure that it's always off via a .htaccess file?</p> <pre><code>if (get_magic_quotes_gpc()) { $var = stripslashes($_POST['var']); } else { $var = $_POST['var']; } </code></pre> <p>Versus</p> <pre><code>php_flag magic_quotes_gpc off </code></pre>
[ { "answer_id": 370339, "author": "Zan Lynx", "author_id": 13422, "author_profile": "https://Stackoverflow.com/users/13422", "pm_score": 2, "selected": false, "text": "get_magic_quotes_gpc()" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370292", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9021/" ]
370,310
<p>I have a JPanel full of JTextFields...</p> <pre><code>for (int i=0; i&lt;maxPoints; i++) { JTextField textField = new JTextField(); points.add(textField); } </code></pre> <p>How do I later get the JTextFields in that JPanel? Like if I want their values with </p> <pre><code>TextField.getText(); </code></pre> <p>Thanks</p>
[ { "answer_id": 370341, "author": "OscarRyz", "author_id": 20654, "author_profile": "https://Stackoverflow.com/users/20654", "pm_score": 5, "selected": true, "text": "List<JTextField> list = new ArrayLists<JTextField>();\n\n// your code...\nfor (int i=0; i<maxPoints; i++) { \n JTextField textField = new JTextField();\n points.add(textField);\n list.add( textField ); // keep a reference to those fields.\n}\n for( JTextField f : list ) { \n System.out.println( f.getText() ) ;\n}\n public List<JTextField> getFields();\n public List<String> getTexts(); // get them from the textfields ... \n" }, { "answer_id": 15990375, "author": "cardaba713", "author_id": 1789358, "author_profile": "https://Stackoverflow.com/users/1789358", "pm_score": 2, "selected": false, "text": " //una forma de recorer todos los elementos dentro de un jpanel\n Component[] components = jPanelX.getComponents();\n\n for (int i = 0; i < components.length; i++) {\n\n if(components[i].getClass().getName().toString().equals(\"javax.swing.JTextField\")){\n components[i].setEnabled(false);\n }\n }\n" }, { "answer_id": 33826431, "author": "Akros", "author_id": 4367955, "author_profile": "https://Stackoverflow.com/users/4367955", "pm_score": 3, "selected": false, "text": "List<JTextField> list = new ArrayLists<JTextField>();\nComponent[] components = panel.getComponents();\n\nfor (Component component : components) {\n if (component.getClass().equals(JTextField.class)) {\n list.add((JTextField)component);\n }\n}\n" }, { "answer_id": 44747174, "author": "Deepeshkumar", "author_id": 1780667, "author_profile": "https://Stackoverflow.com/users/1780667", "pm_score": 0, "selected": false, "text": "for(int i=1 ; i<=maxpoints ;i++){\n System.out.println(\"JTextField tf\"+i+\" = new JTextField()\"+\";\");\n System.out.println(\"points.add(tf\"+i+\")\"+\";\");\n}\n for(int i=1 ; i<=maxpoints ;i++){\n System.out.println(\"String s\"+i+\" = JTextField tf\"+i+\".getText()\"+\";\");\n}\n" }, { "answer_id": 46694303, "author": "NetCollector", "author_id": 4425304, "author_profile": "https://Stackoverflow.com/users/4425304", "pm_score": 2, "selected": false, "text": "private void ClearAllFields(Container myContainer) {\n\n Component myComps[] = myContainer.getComponents();\n\n for (int i=0; i<myComps.length; i++) {\n if(myComps[i] instanceof JPanel) {\n JPanel myPanel = (JPanel) myComps[i];\n ClearAllFields(myPanel);\n }\n if(myComps[i] instanceof JTextField) {\n JTextField myTextField = (JTextField) myComps[i];\n myTextField.setText(\"\");\n }\n } \n}\n ClearAllFields([jdialog or jframe etc].getContentPane());\n" }, { "answer_id": 54051567, "author": "Nico", "author_id": 10290516, "author_profile": "https://Stackoverflow.com/users/10290516", "pm_score": 2, "selected": false, "text": " Component[] components = panel.getComponents();\n for (Component component: components) {\n var name = component.getName(); \n if(name != null){ \n if(name.equals(\"textfield 1\")){\n var field = (JTextField)component;\n field.setText(\"whatever you want / same for options and other components\")\n }\n }\n\n }\n" }, { "answer_id": 72998785, "author": "Manoj Bhakar PCM", "author_id": 5307634, "author_profile": "https://Stackoverflow.com/users/5307634", "pm_score": 0, "selected": false, "text": "public Component getComponentByName(Container parent,String name) {\n java.util.List<Component> clist = new ArrayList<>();\n listAllComponentsIn(parent,clist);\n for (Component c : clist) {\n System.out.println(c.getName());\n String s = c.getName();\n if(s!=null){\n if(s.equals(name)){\n return c;\n }\n }\n }\n return null;\n }\n public void listAllComponentsIn(Container parent,java.util.List<Component> components)\n {\n for (Component c : parent.getComponents()) {\n components.add(c);\n if (c instanceof Container) {\n listAllComponentsIn((Container) c,components);\n }\n }\n }\n searchBar.setVisible(true);\n JTextField jTextField = (JTextField) getComponentByName(searchBar,\"txt_search_box\");\n if(jTextField!=null){\n jTextField.requestFocusInWindow();\n } \n" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370310", "https://Stackoverflow.com", "https://Stackoverflow.com/users/51518/" ]
370,322
<p>How can I remove the very first "1" from any string if that string starts with a "1"?</p> <pre><code>"1hello world" =&gt; "hello world" "112345" =&gt; "12345" </code></pre> <p>I'm thinking of doing</p> <pre><code>string.sub!('1', '') if string =~ /^1/ </code></pre> <p>but I' wondering there's a better way. Thanks!</p>
[ { "answer_id": 370331, "author": "Zach Langley", "author_id": 45230, "author_profile": "https://Stackoverflow.com/users/45230", "pm_score": 7, "selected": true, "text": "sub! string.sub!(/^1/, '')\n" }, { "answer_id": 370334, "author": "Gordon Wilson", "author_id": 23071, "author_profile": "https://Stackoverflow.com/users/23071", "pm_score": 3, "selected": false, "text": "string.sub!(%r{^1},\"\")\n %r{} %r!^1!" }, { "answer_id": 370782, "author": "a2800276", "author_id": 27408, "author_profile": "https://Stackoverflow.com/users/27408", "pm_score": 2, "selected": false, "text": "sub!(/^1/,'') /^1/ nil sub" }, { "answer_id": 28071592, "author": "cyrilchampier", "author_id": 1248264, "author_profile": "https://Stackoverflow.com/users/1248264", "pm_score": 1, "selected": false, "text": "string[0] = '' if string[0] == '1'" }, { "answer_id": 39195658, "author": "Joost Baaij", "author_id": 235411, "author_profile": "https://Stackoverflow.com/users/235411", "pm_score": 0, "selected": false, "text": "^ string.sub!(/\\A1/, '')\n" }, { "answer_id": 46976376, "author": "SRack", "author_id": 4055042, "author_profile": "https://Stackoverflow.com/users/4055042", "pm_score": 5, "selected": false, "text": "\"1hello world\".delete_prefix(\"1\") 'invisible'.delete_prefix('in') #=> \"visible\"\n'pink'.delete_prefix('in') #=> \"pink\"\n 'worked'.delete_suffix('ed') #=> \"work\"\n'medical'.delete_suffix('ed') #=> \"medical\"\n" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370322", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
370,325
<p>I have a .NET DLL and application. The DLL is written in C++/CLI and it's "mixed", i.e., partially managed code and partially native. </p> <p>I have two goals:<br/> 1. Obfuscate all the managed code so it can't be disassembled<br/> 2. Obfuscate the public methods/classes of the mixed DLL so no one can use the DLL in their own applications, i.e., scramble the public names.</p> <p>Yes, I understand obfuscation isn't perfect and people can still figure it out and blah blah. The two goals are a management requirement. The only app I've found that can handle this appears to be the Dotfuscator Professional Edition. Unfortunately it is one of those incredibly annoying apps where you have to beg a salesman to tell you the price. Does anyone know of a another solution, or know of a good place to buy a cheap, legal copy? </p> <p>Don't tell me to rewrite the DLL in managed code, that would take a month of work and I'd never get approval. :-)</p> <p>Note that I'm not particularly paranoid about how <em>good</em> the obfuscation is. Anything that scrambles the names of all the methods and classes in the app is probably good enough.</p> <p>Here are the other obfuscators I have tried:</p> <ul> <li><p>Dotfuscator Community Edition comes with Visual Studio 2008 but doesn't support mixed assemblies.</p></li> <li><p>Eazfuscator .NET is simple and free but doesn't support mixed assemblies.</p></li> <li><p>{smartassembly} is $500 for a single license. It has some interesting features, but it doesn't support mixed assemblies.</p></li> <li><p>Salamander is $800. Claims to fully support mixed assemblies, but whenever I tried to use the obfuscated dll, the application crashed</p></li> <li><p>.NET Reactor is $180 for a single developer license. It supports "partial" obfuscation of mixed DLLs. Unfortunately if you obfuscate the <em>public</em> types on the DLL it doesn't work, the .exe can't find the classes. It has the ability to merge/pack DLLs into an .exe but when you do it with a mixed DLL it doesn't work (the exe can't find the DLL's assembly, even though it's part of the .exe)</p></li> <li><p>Skater is $300 for a single license. I don't see anything on their website claiming it supports mixed assemblies and I'm tired of trying apps only to be disappointed so I'm going to assume it doesn't.</p></li> </ul> <p>I have also tried Microsoft's ILMerge to see if I could merge the DLL with the .exe and then obfuscate, but it appears that also chokes on mixed DLLs.</p> <p>Any suggestions for an alternative to Dotfuscator or a good place to buy a legitimate copy? I found a couple of no-name sites claiming to sell it cheap but I assume those are Russian pirated versions.</p>
[ { "answer_id": 370429, "author": "faulty", "author_id": 20007, "author_profile": "https://Stackoverflow.com/users/20007", "pm_score": -1, "selected": false, "text": "[assembly:SecurityPermission(SecurityAction::RequestMinimum, UnmanagedCode = true)];\n" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24267/" ]
370,340
<p>Say I wanted to have a project, and one-to-many with to-do items, and wanted to re-order the to-do items arbitrarily? </p> <p>In the past, I've added a numbered order field, and when someone wants to change the order, had to update all the items with their new order numbers. This is probably the worst approach, since it's not atomic &amp; required several updates.</p> <p>I notice Django has a multi-valued CommaSeparatedIntegerField which could contain the order by storing the ordered keys to the items in the to-do items table right in one field of the project table.</p> <p>I've pondered a dewey decimal system where if I wanted to take item 3 and put it between 1 and 2 I would change it's order number to 1.5.</p> <p>Something tells me there's an easier option that I'm missing though...</p> <p>How would you give order to a one-to-many relationship?</p>
[ { "answer_id": 375370, "author": "Peter Rowell", "author_id": 17017, "author_profile": "https://Stackoverflow.com/users/17017", "pm_score": 4, "selected": true, "text": "{% extends 'admin/change_form.html' %}\n\n{% block form_top %}{% endblock %}\n{% block extrahead %}{{ block.super }}\n<script type=\"text/javascript\" src=\"/media/js/jquery.js\"></script>\n<script type=\"text/javascript\" src=\"/media/js/interface.js\"></script>\n<script>\n$(document).ready(\n function () {\n $('ol.articles').Sortable(\n {\n accept : 'sortableitem',\n helperclass : 'sorthelper',\n activeclass : 'sortableactive',\n hoverclass : 'sortablehover',\n opacity: 0.8,\n fx: 200,\n axis: 'vertically',\n opacity: 0.4,\n revert: true,\n trim: 'art_',\n onchange:\n function(list){\n var arts = list[0].o[list[0].id];\n var vals = new Array();\n var a;\n for (a in arts) {\n vals[a] = arts[a].replace(/article./, '');\n }\n $('#id_article_order').attr('value', vals.join(','));\n }\n });\n }\n);\n</script>\n{% endblock %}\n\n{% block after_related_objects %}\n{% if original.articles %}\n<style>\n.sortableitem {\n cursor:move;\n width: 300px;\n list-style-type: none;\n }\n</style>\n\n<h4>Associated Articles</h4>\n<ol class=\"articles\" id=\"article_list\">\n{% for art in original.articles %}\n <li id=\"article.{{art.id}}\" class=\"sortableitem\">{{art.title}}</li>\n\n{% endfor %}\n</ol>\n{% endif %}\n{% endblock %}\n" }, { "answer_id": 12926809, "author": "jondykeman", "author_id": 1406860, "author_profile": "https://Stackoverflow.com/users/1406860", "pm_score": 2, "selected": false, "text": "class Form(models.Model):\n FormName = models.CharField(verbose_name=\"Form Name:\", max_length=40)\n VariableOrder = models.CommaSeparatedIntegerField(default=\"[]\", editable=False)\n\n def __unicode__(self):\n return \"%s\" % (self.FormName)\n\nclass Variable(models.Model):\n FormID = models.ForeignKey(Form, default=0, editable=False, related_name=\"Variable\")\n VarName = models.CharField(max_length=32, verbose_name=\"Name of variable in the database:\") \n\n def __unicode__(self):\n return \"%s\" % self.VarName\n <ul id=\"sortable\">\n\n{% for Variable in VarList %}\n <li id=\"{{ Variable.id }}\">{{ Variable }}</li>\n{% endfor %}\n\n</ul>\n $(function() {\n $(\"#sortable\" ).sortable({\n placeholder: \"ui-state-highlight\",\n update: function(event, ui){\n $.ajax({\n type:\"POST\",\n url:\"{% url builder.views.variableorder %}\",\n data: {Order: JSON.stringify($('#sortable').sortable('toArray')) },\n success: function(data){\n // Do stuff here - I don't do anything.\n }\n });\n }\n });\n $( \"#sortable\" ).disableSelection();\n});\n def variableorder(request):\n if request.is_ajax():\n Order = request.POST['Order']\n updateOrder = request.session['FormID']\n updateOrder.VariableOrder = newOrder\n updateOrder.save()\n request.session['FormID'] = Form.objects.get(id=updateOrder.id)\n return HttpResponse(\"Order changed.\")\n else:\n pass\n aForm = Form.objects.get(id=1)\ncurrentOrder = aForm.VariableOrder\ncurrentOrder = eval(currentOrder)\nnewVar = Variable(stuff in here)\nnewVar.save()\ncurrentOrder.append(newVar.id)\naForm.VariableOrder = currentOrder\naForm.save()\n aForm = Form.objects.get(id=1)\ncurrentOrder = aForm.VariableOrder\ncurrentOrder = eval(currentOrder)\n# Variable ID that we want to delete = 3\ncurrentOrder.remove(3)\naForm.VariableOrder = currentOrder\naForm.save()\n aForm = Form.objects.get(id=1)\ncurrentOrder = aForm.VariableOrder\ncurrentOrder = eval(currentOrder)\nVarList = []\nfor i in currentOrder:\n VarList.append(Variable.objects.get(id=i))\n def getVarOrder(self):\n return eval(self.VariableOrder)\n" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370340", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35922/" ]
370,353
<p>I'm refactoring some client-server code and it uses the terms Response, Result &amp; Reply for the same thing (an answer from the server). And although its not really that important it's become hard to guess which word to use while writing new code, so I'd like to unify the three terms into one and do the appropriate refactoring, but I'm not sure which word is the "best", if there is such a thing.</p> <p>Any suggestions based on precedence and standards towards naming for this case?</p>
[ { "answer_id": 2602641, "author": "Carl Manaster", "author_id": 82118, "author_profile": "https://Stackoverflow.com/users/82118", "pm_score": 2, "selected": false, "text": "Response Result Reply Response" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15124/" ]
370,357
<p>The following code works as expected in both Python 2.5 and 3.0:</p> <pre><code>a, b, c = (1, 2, 3) print(a, b, c) def test(): print(a) print(b) print(c) # (A) #c+=1 # (B) test() </code></pre> <p>However, when I uncomment line <strong>(B)</strong>, I get an <code>UnboundLocalError: 'c' not assigned</code> at line <strong>(A)</strong>. The values of <code>a</code> and <code>b</code> are printed correctly. I don't understand:</p> <ol> <li><p>Why is there a runtime error raised at line <strong>(A)</strong> because of a later statement on line <strong>(B)</strong>?</p> </li> <li><p>Why are variables <code>a</code> and <code>b</code> printed as expected, while <code>print(c)</code> raises an error?</p> </li> </ol> <p>The only explanation I can come up with is that the assignment <code>c+=1</code> creates a <strong>local</strong> variable <code>c</code>, which takes precedence over the global <code>c</code>. But how can a variable &quot;steal&quot; scope before it exists? Why is <code>c</code> apparently local here?</p> <hr /> <p><sub>See also <a href="https://stackoverflow.com/questions/423379/">Using global variables in a function</a> for questions that are simply about how to reassign a global variable from within a function, and <a href="https://stackoverflow.com/questions/8447947">Is it possible to modify variable in python that is in outer, but not global, scope?</a> for reassigning from an enclosing function (closure). See <a href="https://stackoverflow.com/questions/4693120">Why isn&#39;t the &#39;global&#39; keyword needed to access a global variable?</a> for cases where OP <em>expected</em> an error but <em>didn't</em> get one, from simply accessing a global without the <code>global</code> keyword.</sub></p>
[ { "answer_id": 370363, "author": "recursive", "author_id": 44743, "author_profile": "https://Stackoverflow.com/users/44743", "pm_score": 9, "selected": true, "text": "c c c = 3 global c\n nonlocal c\n c" }, { "answer_id": 370364, "author": "Mongoose", "author_id": 46523, "author_profile": "https://Stackoverflow.com/users/46523", "pm_score": 4, "selected": false, "text": "global test() def test():\n global c\n print(a)\n print(b)\n print(c) # (A)\n c+=1 # (B)\n c c" }, { "answer_id": 370380, "author": "Charlie Martin", "author_id": 35092, "author_profile": "https://Stackoverflow.com/users/35092", "pm_score": 6, "selected": false, "text": "print(a) print(b) c+=1 c=c+1 global c c c+=1\n SYMBOL(c) OPERATOR(+=) DIGIT(1)\n" }, { "answer_id": 370830, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 6, "selected": false, "text": ">>> def f():\n... print a\n... print b\n... a = 1\n\n>>> import dis\n>>> dis.dis(f)\n\n 2 0 LOAD_FAST 0 (a)\n 3 PRINT_ITEM\n 4 PRINT_NEWLINE\n\n 3 5 LOAD_GLOBAL 0 (b)\n 8 PRINT_ITEM\n 9 PRINT_NEWLINE\n\n 4 10 LOAD_CONST 1 (1)\n 13 STORE_FAST 0 (a)\n 16 LOAD_CONST 0 (None)\n 19 RETURN_VALUE\n LOAD_FAST LOAD_GLOBAL print a" }, { "answer_id": 476123, "author": "alsuren", "author_id": 58477, "author_profile": "https://Stackoverflow.com/users/58477", "pm_score": 2, "selected": false, "text": "a += b a = a + b a func(a) a = a + b a a a += b a = a + b\n a.__iadd__(b)\n a a a a def copy_on_write(a):\n a = a + a\ndef inplace_add(a):\n a += a\na = [1]\ncopy_on_write(a)\nprint a # [1]\ninplace_add(a)\nprint a # [1, 1]\nb = 1\ncopy_on_write(b)\nprint b # [1]\ninplace_add(b)\nprint b # 1\n" }, { "answer_id": 1745180, "author": "mcdon", "author_id": 135280, "author_profile": "https://Stackoverflow.com/users/135280", "pm_score": 3, "selected": false, "text": ">>> a, b, c = (1, 2, 3)\n>>> print (a, b, c)\n(1, 2, 3)\n>>> def test (a, b, c):\n... print (a)\n... print (b)\n... print (c)\n... c += 1\n... return a, b, c\n...\n>>> a, b, c = test (a, b, c)\n1\n2\n3\n>>> print (a, b ,c)\n(1, 2, 4)\n" }, { "answer_id": 24035261, "author": "Sahil kalra", "author_id": 1731648, "author_profile": "https://Stackoverflow.com/users/1731648", "pm_score": 3, "selected": false, "text": "bar = 42\ndef foo():\n print bar\n if False:\n bar = 0\n foo() UnboundLocalError bar=0 foo bar" }, { "answer_id": 34153129, "author": "Harun ERGUL", "author_id": 4104008, "author_profile": "https://Stackoverflow.com/users/4104008", "pm_score": 1, "selected": false, "text": "class Employee:\n counter=0\n\n def __init__(self):\n Employee.counter+=1\n" }, { "answer_id": 40409182, "author": "Colegram", "author_id": 2392540, "author_profile": "https://Stackoverflow.com/users/2392540", "pm_score": 2, "selected": false, "text": "c+=1 c global nonlocal nonlocal my_variables = { # a mutable object\n 'c': 3\n}\n\ndef test():\n my_variables['c'] +=1\n\ntest()\n" }, { "answer_id": 71914016, "author": "JGFMK", "author_id": 495157, "author_profile": "https://Stackoverflow.com/users/495157", "pm_score": 0, "selected": false, "text": "def teams():\n ...\n\ndef some_other_method():\n teams = teams()\n teams() get_teams() def teams():\n ...\n\ndef some_other_method():\n teams = get_teams()\n" }, { "answer_id": 72633950, "author": "izilotti", "author_id": 221781, "author_profile": "https://Stackoverflow.com/users/221781", "pm_score": 0, "selected": false, "text": "del" }, { "answer_id": 73661023, "author": "Karl Knechtel", "author_id": 523612, "author_profile": "https://Stackoverflow.com/users/523612", "pm_score": 2, "selected": false, "text": "eval exec SyntaxError global nonlocal LOAD_CONST LOAD_FAST LOAD_DEREF nonlocal LOAD_CLOSURE LOAD_GLOBAL NameError UnboundLocalError NameError y = 1\ndef x():\n return y # local!\n if False:\n y = 0\n y = []\ndef x():\n y += [1] # local, even though it would modify `y` in-place with `global`\n __getitem__ y = [0]\ndef x():\n print(y) # global now! No error occurs.\n y[0] = 1\n y = 1\ndef x():\n return y # local!\n for y in []:\n pass\n y = 1\ndef x():\n return y # local!\n del y\n dis global nonlocal nonlocal +=" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370357", "https://Stackoverflow.com", "https://Stackoverflow.com/users/46521/" ]
370,359
<p>I'm creating HTML with a loop that has a column for Action. That column is a Hyperlink that when the user clicks calls a JavaScript function and passes the parameters...</p> <p>example:</p> <pre><code>&lt;a href="#" OnClick="DoAction(1,'Jose');" &gt; Click &lt;/a&gt; &lt;a href="#" OnClick="DoAction(2,'Juan');" &gt; Click &lt;/a&gt; &lt;a href="#" OnClick="DoAction(3,'Pedro');" &gt; Click &lt;/a&gt; ... &lt;a href="#" OnClick="DoAction(n,'xxx');" &gt; Click &lt;/a&gt; </code></pre> <p>I want that function to call an Ajax jQuery function with the correct parameters.</p> <p>Any help?</p>
[ { "answer_id": 370391, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 8, "selected": true, "text": "function DoAction( id, name )\n{\n $.ajax({\n type: \"POST\",\n url: \"someurl.php\",\n data: \"id=\" + id + \"&name=\" + name,\n success: function(msg){\n alert( \"Data Saved: \" + msg );\n }\n });\n}\n function DoAction( id, name )\n{\n $.ajax({\n type: \"GET\",\n url: \"someurl.php\",\n data: \"id=\" + id + \"&name=\" + name,\n success: function(msg){\n alert( \"Data Saved: \" + msg );\n }\n });\n}\n <a href=\"/someurl.php?id=1&name=Jose\" class=\"ajax-link\"> Click </a>\n<a href=\"/someurl.php?id=2&name=Juan\" class=\"ajax-link\"> Click </a>\n<a href=\"/someurl.php?id=3&name=Pedro\" class=\"ajax-link\"> Click </a>\n...\n<a href=\"/someurl.php?id=n&name=xxx\" class=\"ajax-link\"> Click </a>\n\n<script type=\"text/javascript\">\n$(function() {\n $('.ajax-link').click( function() {\n $.get( $(this).attr('href'), function(msg) {\n alert( \"Data Saved: \" + msg );\n });\n return false; // don't follow the link!\n });\n});\n</script>\n" }, { "answer_id": 373129, "author": "Leandro Ardissone", "author_id": 42565, "author_profile": "https://Stackoverflow.com/users/42565", "pm_score": 0, "selected": false, "text": "function DoAction (id, name ) {\n // ...\n // do anything you want here\n alert (\"id: \"+id+\" - name: \"+name);\n //...\n}\n" }, { "answer_id": 413767, "author": "tanathos", "author_id": 51295, "author_profile": "https://Stackoverflow.com/users/51295", "pm_score": 3, "selected": false, "text": "function DoAction(id, name) \n{ \n // your code\n return false;\n}\n" }, { "answer_id": 2082937, "author": "Roko Mise", "author_id": 252821, "author_profile": "https://Stackoverflow.com/users/252821", "pm_score": 0, "selected": false, "text": "#vote_links a <script type=\"text/javascript\">\n\n jQuery(document).ready(function() {\n jQuery(\\'#vote_links a\\').click(function() {// alert(\\'vote clicked\\');\n var det = jQuery(this).get(0).id.split(\"-\");// alert(jQuery(this).get(0).id);\n var votes_id = det[0];\n\n\n $(\"#about-button\").css({\n opacity: 0.3\n });\n $(\"#contact-button\").css({\n opacity: 0.3\n });\n\n $(\"#page-wrap div.button\").click(function(){\n" }, { "answer_id": 8551187, "author": "Dhiral Pandya", "author_id": 884778, "author_profile": "https://Stackoverflow.com/users/884778", "pm_score": 0, "selected": false, "text": "<script type=\"text/javascript\" src=\"jquery.js\">\n</script>\n\n <script type=\"text/javascript\">\n\n function omtCallFromAjax(urlVariable)\n{ \n alert(\"omt:\"+urlVariable);\n $(\"#omtDiv\").load(\"omtt.php?\"+urlVariable);\n}\n\n </script>\n" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/46522/" ]
370,366
<p>I noticed for a while now the following syntax in some of our code:</p> <pre><code>if( NULL == var){ //... } </code></pre> <p>or</p> <pre><code>if( 0 == var){ //... } </code></pre> <p>and similar things.</p> <p>Can someone please explain why did the person who wrote this choose this notation instead of the common <code>var == 0</code> way)?</p> <p>Is it a matter of style, or does it somehow affect performance?</p>
[ { "answer_id": 370370, "author": "jpoh", "author_id": 4368, "author_profile": "https://Stackoverflow.com/users/4368", "pm_score": 3, "selected": false, "text": "if (var = NULL)\n" }, { "answer_id": 370373, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 6, "selected": true, "text": "if ( var = NULL ) {\n // ...\n}\n if ( NULL = var ) { // not legal, won't compile\n // ...\n}\n gcc -Wall warning: suggest parentheses around assignment used as truth value\n" }, { "answer_id": 370384, "author": "Kieveli", "author_id": 15852, "author_profile": "https://Stackoverflow.com/users/15852", "pm_score": 4, "selected": false, "text": "if ( var = NULL )\n if ( var == NULL )\n if ( NULL == var )\n if ( NULL = var )\n" }, { "answer_id": 370388, "author": "Charlie Martin", "author_id": 35092, "author_profile": "https://Stackoverflow.com/users/35092", "pm_score": 1, "selected": false, "text": "if( x = 0){\n" }, { "answer_id": 370510, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "\nif (!x) {\n" }, { "answer_id": 370523, "author": "Ates Goral", "author_id": 23501, "author_profile": "https://Stackoverflow.com/users/23501", "pm_score": 3, "selected": false, "text": "const const int val = 42;\n\nif (val = 43) {\n ...\n}\n" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370366", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14587/" ]
370,369
<p>I have a <code>JTable</code> with a custom <code>TableModel</code> called <code>DataTableModel</code>. I initialized the table with a set of column names and no data as follows:</p> <pre><code>books = new JTable(new DataTableModel(new Vector&lt;Vector&lt;String&gt;&gt;(), title2)); JScrollPane scroll1 = new JScrollPane(books); scroll1.setEnabled(true); scroll1.setVisible(true); JSplitPane jsp1 = new JSplitPane(JSplitPane.VERTICAL_SPLIT, scroll1, scroll2); JSplitPane jsp2 = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, inventory, jsp1); myPanel.add(jsp2, BorderLayout.CENTER); </code></pre> <p>I later want to update books with a set of data, and use the following:</p> <pre><code>DataTableModel d = (DataTableModel)books.getModel(); d.setValues(bookList); books.setModel(d); </code></pre> <p>where bookList is a <code>Vector&lt;Vector&lt;String&gt;&gt;</code> that definitely has data. However, although all this code is being executed, it is not displaying on the screen. The code for the <code>setValues()</code> method is:</p> <pre><code>public void setValues(Vector&lt;Vector&lt;String&gt;&gt; v) { values = v; fireTableDataChanged(); } </code></pre> <p>Am I missing something here?</p> <p>The class and methods for my DataTableModel are (these methods are all implemented to return correct results):</p> <pre><code>public class DataTableModel extends AbstractTableModel { public DataTableModel(Vector&lt;Vector&lt;String&gt;&gt; v, Vector&lt;String&gt; c) {} public int getColumnCount() { if (values != null &amp;&amp; values.size() &gt; 0) return values.elementAt(0).size(); else return 0; } public int getRowCount() { if (values != null &amp;&amp; values.size() &gt; 0) return values.size(); else return 0; } public Object getValueAt(int arg0, int arg1) {} public void setValues(Vector&lt;Vector&lt;String&gt;&gt; v) {} public Vector&lt;Vector&lt;String&gt;&gt; getValues() {} public void setColumnNames(Vector&lt;String&gt; columns) {} public String getColumnName(int col) {} } </code></pre>
[ { "answer_id": 370565, "author": "Daniel Hiller", "author_id": 16193, "author_profile": "https://Stackoverflow.com/users/16193", "pm_score": 2, "selected": true, "text": "TableModel TableModel getRowCount() getColumnCount() return 0 AbstractTableModel DefaultTableModel fireTableStructureChanged fireTabeDataChanged() 0 getColumnCount() getColumnCount() fireTabeDataChanged() fireTableStructureChanged()" }, { "answer_id": 370700, "author": "Rastislav Komara", "author_id": 22068, "author_profile": "https://Stackoverflow.com/users/22068", "pm_score": 0, "selected": false, "text": "DataTableModel TableModel DataTableModel" }, { "answer_id": 29503700, "author": "Hatem Badawi", "author_id": 4749531, "author_profile": "https://Stackoverflow.com/users/4749531", "pm_score": -1, "selected": false, "text": "Binding b = bindingGroup.getBindings().get(0);\nb.unbind();\nb.bind();\n" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370369", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23249/" ]
370,379
<p>If php code like below how it's like as mysql stored procedure equivalent. If any links tutorial on advance stored procedure mysql please put.</p> <pre><code>$sql = " SELECT a,b FROM j "; $result = mysql_query($sql); if(mysql_num_rows($result) &gt; 0) { while($row = mysql_fetch_array($result)) { $sql_update = "UPDATE b set a=" . $row['a'] . "'"; mysql_query($sql_update); } } </code></pre>
[ { "answer_id": 370423, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 1, "selected": false, "text": "mysqli mysql mysqli mysqli_multi_query()" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
370,401
<p>been searching for a quick example of sorting a IQueryable (Using Linq To SQL) using a Aggregate value.</p> <p>I basically need to calculate a few derived values (Percentage difference between two values etc) and sort the results by this.</p> <p>i.e.</p> <p>return rows.OrderBy(Function(s) CalcValue(s.Visitors, s.Clicks))</p> <p>I want to call an external function to calculate the Aggregate. Should this implement IComparer? or IComparable?</p> <p>thanks</p> <p>[EDIT] Have tried to use:</p> <pre><code>Public Class SortByCPC : Implements IComparer(Of Statistic) Public Function Compare(ByVal x As Statistic, ByVal y As Statistic) As Integer Implements System.Collections.Generic.IComparer(Of Statistic).Compare Dim xCPC = x.Earnings / x.Clicks Dim yCPC = y.Earnings / y.Clicks Return yCPC - xCPC End Function End Class </code></pre> <p>LINQ to SQL doesn't like me using IComparer</p>
[ { "answer_id": 370409, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 0, "selected": false, "text": "rows Dim keySelector As Func(Of Double, RowClass) = _\n Func( s As RowClass) CalcValue( s.Visitors, s.Clicks )\n\nreturn rows.OrderBy( keySelector )\n" }, { "answer_id": 370587, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 2, "selected": false, "text": "Dim stats = From x in db.Statistics\n Where (something, if you want filtering)\n Order By x.Earnings / x.Clicks;\n" }, { "answer_id": 373808, "author": "Andrew Harry", "author_id": 30576, "author_profile": "https://Stackoverflow.com/users/30576", "pm_score": 1, "selected": true, "text": "Dim stats = rows.OrderBy(Function(s) If(s.Visitors > 0, s.Clicks / s.Visitors, 0))\n" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30576/" ]
370,425
<p>Does anyone know of any gotachs or problems when writing multithreaded Perl applications using the Oracle DBI? Each thread would have it's own connection to Oracle.</p> <p>For the longest time I was told multithreading was not supported in Perl with Oracle.</p>
[ { "answer_id": 370653, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 3, "selected": false, "text": "$dbh" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21357/" ]
370,427
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/710288/where-are-the-best-explanations-of-memory-management-for-iphone">Where are the best explanations of memory management for iPhone?</a> </p> </blockquote> <p>I come from a web development background. I'm good at XHTML, CSS, JavaScript, PHP and MySQL, because I use all of those technologies at my day job.</p> <p>Recently I've been tinkering with Obj-C in Xcode in the evenings and on weekends. I've written code for both the iPhone and Mac OS X, but I can't wrap my head around the practicalities of memory management. I understand the high-level concepts but am unclear how that plays out in implementation. Web developers typically don't have to worry about these sorts of things, so it is pretty new to me.</p> <p>I've tried adding memory management to my projects, but things usually end up crashing. Any suggestions of how to learn? Any suggestions are appreciated.</p>
[ { "answer_id": 565355, "author": "Georg Schölly", "author_id": 24587, "author_profile": "https://Stackoverflow.com/users/24587", "pm_score": 2, "selected": false, "text": "[[NSObject alloc] init] autorelease // make sure it gets properly released\n// autorelease releases the object at a later time.\nNSObject *instance = [[[NSObject alloc] init] autorelease];\n NSString *test = [NSString stringWithFormat:@\"%i\", 4];\n [instance retain];\n [instance release];\n retains releases @property(retain, readwrite) NSString *text; - (NSString *)text {\n return text; // I don't like calling variables _test\n}\n\n- (void)setText:(NSString *)newText {\n [newText retain];\n [text release];\n text = newText;\n}\n [self setVariable:…] - (id)init {\n if (self = [super init]) {\n [self setText:@\"Lorem ipsum dolor sit amet.\"];\n // …\n }\n return self;\n}\n\n- (void)dealloc {\n // make sure text is set to nil and the old value gets released.\n [self setText:nil];\n}\n [NSObject alloc] [instance retain] [instance release] [instance copy]" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
370,428
<p>I am getting into strange situation regarding the RSS viewer on SharePoint</p> <p>I have two environments of SharePoint (production &amp; testing)</p> <p>I was showing a specific RSS news (ABC) on both of them , and it was working after setting the proxies and other stuff.</p> <p>Suddenly (may be due to some changes done on the production without testing), the RSS viewer on the production is not showing the RSS news it is showing protocol error, while it is still working fine on the testing environment.</p> <p>Now the strange part is if I change the RSS of the one our management wants and put BBC or CNN news these works well on both the production and the test environment.</p> <p>But the one we want it to work (which was working fine on both) do not work on the production and works fine on testing.</p> <p>Any suggestions of how can I figure it out?</p>
[ { "answer_id": 565355, "author": "Georg Schölly", "author_id": 24587, "author_profile": "https://Stackoverflow.com/users/24587", "pm_score": 2, "selected": false, "text": "[[NSObject alloc] init] autorelease // make sure it gets properly released\n// autorelease releases the object at a later time.\nNSObject *instance = [[[NSObject alloc] init] autorelease];\n NSString *test = [NSString stringWithFormat:@\"%i\", 4];\n [instance retain];\n [instance release];\n retains releases @property(retain, readwrite) NSString *text; - (NSString *)text {\n return text; // I don't like calling variables _test\n}\n\n- (void)setText:(NSString *)newText {\n [newText retain];\n [text release];\n text = newText;\n}\n [self setVariable:…] - (id)init {\n if (self = [super init]) {\n [self setText:@\"Lorem ipsum dolor sit amet.\"];\n // …\n }\n return self;\n}\n\n- (void)dealloc {\n // make sure text is set to nil and the old value gets released.\n [self setText:nil];\n}\n [NSObject alloc] [instance retain] [instance release] [instance copy]" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/247597/" ]
370,432
<p>I have a div called NAV and inside of NAV I have an UL with 5 li which I float to the left, the li's that is but when I do that the NAV collapses. I know this because I put a border around NAV to see if it collapses and it does. Here is the example.</p> <p><a href="http://img401.imageshack.us/img401/8867/collapsedze4.png" rel="noreferrer">collapsed http://img401.imageshack.us/img401/8867/collapsedze4.png</a></p> <p><a href="http://img71.imageshack.us/img71/879/nocollapsedkx7.png" rel="noreferrer">no collapsed http://img71.imageshack.us/img71/879/nocollapsedkx7.png</a></p> <p>as you can see in the first image, the links in the NAV div are floated left and that black border ontop is the actual div called NAV.</p> <p>in this image you can see how it has top and bottom border and it not collapsed.</p> <p>here is some of the html and css I used.</p> <p><a href="http://img301.imageshack.us/img301/5514/codejc8.png" rel="noreferrer">alt text http://img301.imageshack.us/img301/5514/codejc8.png</a></p> <pre><code>#nav #ulListNavi a { float: left; } </code></pre>
[ { "answer_id": 370439, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<div style=\"clear: both\"></div> \n" }, { "answer_id": 370442, "author": "Abram Simon", "author_id": 46204, "author_profile": "https://Stackoverflow.com/users/46204", "pm_score": 4, "selected": false, "text": "<div id=\"nav\">\n <ul id=\"ulListNavi\">\n <li><a href=\"#\">Home</a></li>\n <li><a href=\"#\">Search</a></li>\n <li><a href=\"#\">Flowers</a></li>\n <li><a href=\"#\">My Account</a></li>\n <li><a href=\"#\">Contact Us</a></li>\n </ul>\n <div style=\"clear:both;\"></div>\n</div>\n" }, { "answer_id": 1770867, "author": "Ken", "author_id": 20074, "author_profile": "https://Stackoverflow.com/users/20074", "pm_score": 5, "selected": false, "text": "overflow visible div#nav { overflow:auto; }\n width div#nav { width: 100%; overflow:auto; }\n" }, { "answer_id": 1770919, "author": "Chris", "author_id": 121363, "author_profile": "https://Stackoverflow.com/users/121363", "pm_score": 0, "selected": false, "text": "#nav\n{\n width: 100%;\n overflow: auto;\n border: solid 1px red;\n}\n#ulListNavi\n{\n margin: 0;\n padding: 0;\n list-style: none;\n}\n#nav #ulListNavi li\n{\n float: left;\n}\n#nav #ulListNavi li a\n{\n margin-left: 5px;\n}\n" }, { "answer_id": 1771017, "author": "Doug", "author_id": 212978, "author_profile": "https://Stackoverflow.com/users/212978", "pm_score": 2, "selected": false, "text": "#nav {\n float: left;\n}\n" }, { "answer_id": 8503862, "author": "Mark Nielsen", "author_id": 923815, "author_profile": "https://Stackoverflow.com/users/923815", "pm_score": 2, "selected": false, "text": "<A> <LI> LI <LI> <A> <LI> #nav #ulListNavi li {\n float: left;\n}\n" }, { "answer_id": 14988174, "author": "Rima Gerhard", "author_id": 2092727, "author_profile": "https://Stackoverflow.com/users/2092727", "pm_score": 1, "selected": false, "text": "#nav{overflow:hidden;}\n" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370432", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36682/" ]
370,449
<p>I'm trying to add a feature to my AIR app that can listen for (configurable) global keyboard events even when the app is minimized. Ex: CTRL-ALT-SHIFT-F12 to grab a screenshot.</p> <p>I can't find any way to register a keyboard hook, and listening for keyboard events only captures them when the app has focus. Suggestions?</p>
[ { "answer_id": 381409, "author": "Robin Rodricks", "author_id": 41021, "author_profile": "https://Stackoverflow.com/users/41021", "pm_score": 1, "selected": false, "text": "stage.addEventListener(KeyboardEvent.KEY_DOWN,KeyHandler); \n\nfunction KeyHandler(e:KeyboardEvent){\n trace (\"Key Code: \" + e.keyCode); \n trace (\"Control? \" + e.ctrlKey); \n trace (\"Shift? \" + e.shiftKey); \n trace (\"Alt? \" + e.altKey); \n}\n" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
370,451
<p>In my app I have 2 divs, one with a long list of products that can be dragged into another div (shopping cart). The product div has the overflow but it breaks prototype draggable elements. The prototype hacks are very obtrusive and not compatible with all browsers.</p> <p>So I am taking a different approach, is it possible to have a scrollable div without using CSS <code>overflow:auto</code>? </p>
[ { "answer_id": 370462, "author": "fasih.rana", "author_id": 46024, "author_profile": "https://Stackoverflow.com/users/46024", "pm_score": 3, "selected": true, "text": "<div style=\"width:100px;height:100px;overflow:scroll\">\n</div>\n" }, { "answer_id": 3067789, "author": "Nicolas", "author_id": 370060, "author_profile": "https://Stackoverflow.com/users/370060", "pm_score": 0, "selected": false, "text": "\"width:100px;scrollable:auto\" function makeDraggable(container,tag) {\n\n if(!container || !tag) { return false; }\n $(container).select(tag).each( function(o) {\n new Draggable(o,{\n starteffect: function(e){makeDragVisible(container,e);},\n endeffect: function(e){e.setStyle({'position':'','width':'','cursor':''});},\n zindex: 1000\n // , revert: ... // the other options\n });\n });\n\n}\n\nfunction makeDragVisible(container,element) {\n\n if(!container || !element) { return false; }\n var i=$(container).getStyle('width');\n i=i.replace('px','');\n i=Math.round(i-20)+'px';\n element.setStyle({'width':i,'z-index':1000,'position':'absolute','cursor':'move'});\n // \n $(container).setStyle({});\n\n}\n 'starteffect'" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10258/" ]
370,454
<p>I need to include or exclude a subreport based on a condition. I'm using iReport to create JasperReports. I.e., if a subreport has values, I need to include that subreport, otherwise not. Can anyone please send a sample or tell me how to resolve this.</p>
[ { "answer_id": 388097, "author": "Jamie Love", "author_id": 27308, "author_profile": "https://Stackoverflow.com/users/27308", "pm_score": 3, "selected": false, "text": "new Boolean($F{TOTAL_STATS}.intValue() != 0)\n" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370454", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
370,499
<p>I have been trying to do a fill using the open source <a href="http://srecord.sourceforge.net/" rel="nofollow noreferrer">Srecord</a> Program. I need to do a fill that is <code>0xC2AF00</code>. It appears the program can only do fills that are a byte long (ex: <code>0xff</code>). If this is not possible with the <a href="http://srecord.sourceforge.net/" rel="nofollow noreferrer">Srecord</a> program, then how would I go about writing my own algorithm to do what I want? </p> <p>I am not quite sure how to determine what needs a fill and then how I would proceed to go about doing the fill that is needed. And on the off chance that someone could answer the same question for a Tektronix file, that would be just as good or better than how to do what I am asking for on the Intel hex file.</p>
[ { "answer_id": 370777, "author": "Sparr", "author_id": 13675, "author_profile": "https://Stackoverflow.com/users/13675", "pm_score": 4, "selected": true, "text": "srec_cat -Output -Intel -generate 0x10 0x20 -repeat-data 0xC2 0xAF 0x00\n" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34531/" ]
370,500
<p>Is it possible to inherit from both ViewPage and ViewPage&lt;T&gt;?? Or do I have to implement both. Currently this is what I have for ViewPage. Do i need to repeat myself and do the same for ViewPage&lt;T&gt;??</p> <pre><code> public class BaseViewPage : ViewPage { public bool LoggedIn { get { if (ViewContext.Controller is BaseController) return ((BaseController)ViewContext.Controller).LoggedOn; else return false; } } } </code></pre>
[ { "answer_id": 370579, "author": "Todd Smith", "author_id": 31624, "author_profile": "https://Stackoverflow.com/users/31624", "pm_score": 3, "selected": true, "text": "public class BaseViewPage : ViewPage\n{\n // put your custom code here\n}\n\npublic class BaseViewPage<TModel> : BaseViewPage where TModel : class\n{\n // code borrowed from MVC source\n\n private ViewDataDictionary<TModel> _viewData;\n\n [System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Usage\", \"CA2227:CollectionPropertiesShouldBeReadOnly\")]\n public new ViewDataDictionary<TModel> ViewData {\n get {\n if (_viewData == null) {\n SetViewData(new ViewDataDictionary<TModel>());\n }\n return _viewData;\n }\n set {\n SetViewData(value);\n }\n }\n\n protected override void SetViewData(ViewDataDictionary viewData) {\n _viewData = new ViewDataDictionary<TModel>(viewData);\n\n base.SetViewData(_viewData);\n }\n}\n public class MyCustomView : BaseViewPage\n{\n}\n\nor\n\npublic class MyCustomView : BaseViewPage<MyCustomViewData>\n{\n}\n" }, { "answer_id": 370794, "author": "Simon Farrow", "author_id": 35047, "author_profile": "https://Stackoverflow.com/users/35047", "pm_score": 1, "selected": false, "text": "ViewContext.HttpContext.Request.IsAuthenticated\n" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29376/" ]
370,504
<p>I'm implementing a math library in C++. The library will be compiled to a DLL so those who use it will only need the header files the classes' definitions.</p> <p>The users of my classes will be people who are new to the language. However, there are some objects that might be referenced in several parts of their programs. Since I don't expect them to do the memory management, I'd like to do it myself. Therefore, I have to implement reference counting (garbage collection is not a possibility).</p> <p>I want to make that reference counting as transparent as possible, for example...</p> <pre><code>// Define a Bézier curve CVecList pts; pts.Add(Vector(0,0,0)); pts.Add(Vector(0,0,100)); pts.Add(Vector(0,100,0)); pts.Add(Vector(0,100,100)); CCurve* c1 = new CBezier(pts); // Define a 3rd order B-Spline curve pts.Clear(); pts.Add(Vector(0,0,0)); pts.Add(Vector(0,200,100)); pts.Add(Vector(0,200,200)); pts.Add(Vector(0,-200,100)); pts.Add(Vector(0,-200,200)); pts.Add(Vector(0,0,0)); CCurve* c2 = new CBSpline(pts,3); // The Bézier curve object must be deleted automatically // because the only reference to it has been released // Similar to IUnknown::Release() in COM c1 = c2; </code></pre> <p>Things get a little bit more tricky when I define surface objects, because some surfaces are defined in terms of two curves:</p> <pre><code>CVecList pts; // ... CCurve* f = new CBezier(pts); pts.Clear(); // ... CCurve* g = new CBezier(pts); // Mixed surface: S(u,v) = (1-v)*f(u) + v*g(u) CSurface* s = new CMixed(f,g); // There are two references to the first Bézier curve, // the first one is f // the second one is hidden in a member of CMixed // Something similar applies to the second Bézier curve </code></pre> <p>I thought that overriding <code>operator =</code> for pointers could have helped:</p> <pre><code>// This is what I tried, but it's illegal: typedef CReferenceCounted* PRC; PRC&amp; operator =(PRC&amp; dest, PRC&amp; source) { if (source) source-&gt;AddRef(); if (dest) dest-&gt;Release(); memcpy(&amp;dest,&amp;source,sizeof(PRC)); return dest; } </code></pre> <p>... but then I found that <code>operator =</code> is not valid unless it is as a non-static member of a class.</p> <p>Could anybody possible help me?</p>
[ { "answer_id": 370520, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 4, "selected": false, "text": "boost::shared_ptr boost::shared_ptr<CCurve> c1(new CBezier(pts));\n CVecList pts;\n// ...\nboost::shared_ptr<CCurve> f(new CBezier(pts));\n\npts.Clear();\n// ...\nboost::shared_ptr<CCurve> g(new CBezier(pts));\n\n// Mixed surface: S(u,v) = (1-v)f(u) + vg(u)\nboost::shared_ptr<CSurface> s(new CMixed(f,g)); \n shared_ptr /* ---- wrapper in header file bezier.hpp */\n\nstruct CBezier {\n CBezier(CVecList const& list);\n void do_calc();\n // ...\n\nprivate:\n struct CBezierImpl;\n boost::shared_ptr<CBezierImpl> p;\n};\n\n/* ---- implementation file bezier.cpp */\n\n// private implementation\nstruct CBezier::CBezierImpl {\n CBezierImpl(CVecList const& list);\n void do_calc();\n // ...\n};\n\n\nCBezier::CBezier(CVecList const& list)\n:p(new CBezierImpl(list)) {\n\n}\n\nvoid CBezier::do_calc() {\n // delegate to pimpl\n p->do_calc();\n}\n\n// ...\n" }, { "answer_id": 370714, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": 1, "selected": false, "text": "std::vector<math::point3d> pts;\npts.push_back(math::point3d(0,0,0));\npts.push_back(math::point3d(110,0,0));\npts.push_back(math::point3d(0,100,0));\npts.push_back(math::point3d(0,0,100));\nCCurve c1 = make_bezier(pts);\n" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
370,512
<p>I'm guessing the StackOverflow code has something along the lines of a UsersController that defines a function like this:</p> <pre><code>public ActionResult Profile(string id, string username, string sort) { } </code></pre> <p>From what I can tell, there's two ways to go about implementing the Profile function. One is to use a switch statement on the sort parameter and render a different view based on what is being displayed (e.g. stats, recent, responses). These views would then render a partial user control to handle the display of the top half of the profile page (gravatar, username, last seen, etc).</p> <p>The other way I could see implementing this would be to always render one view and have the logic for showing / hiding its different sections based on the sort. This would lead to a pretty monstrous view page, but it should work as well.</p> <p>Are there any other ways of implementing the StackOverflow profile page that I'm missing? The reason I ask is because my current ASP.NET MVC page has a similar profile page and I want to make sure I'm not going about this the wrong way.</p>
[ { "answer_id": 370562, "author": "Todd Smith", "author_id": 31624, "author_profile": "https://Stackoverflow.com/users/31624", "pm_score": 0, "selected": false, "text": "<% RenderPartial(sort + \"View\") %>\n" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370512", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1574/" ]
370,518
<p>I'm new to this SCM, but since SVN is gaining popularity I was going to give it a try.</p> <p>Things I noticed:</p> <ol> <li>SVN is only the backbone of the SCM, no front-end?</li> <li>Why is there several versions of Windows Binaries? Tigris? SlikSVN? VisualSVN?</li> <li>Do I need a Web Server like Apache in order to use SVN?</li> <li>There's dozens of front-end, Tortoise, WinSVN, etc... Which one is recommended?</li> </ol> <p>The whole thing is rather confusing and I got no idea where to start. I'm using Delphi and would like to use it to store my source files.</p> <p>Update 1: Seems I got it working using the "file:///" protocol, thanks. Now, how do I configure it as a server with client PCs.</p>
[ { "answer_id": 370528, "author": "Mick", "author_id": 12458, "author_profile": "https://Stackoverflow.com/users/12458", "pm_score": 5, "selected": true, "text": "svn Commit svn Diff svn Modifications svn Update \"c:/program files/tortoisesvn/bin/tortoiseproc.exe\" /command:%1 /path:%2 /notempfile\n c:\\windows\\system32\\cmd.exe /C C:\\SvnPas\\Utils\\Batch\\SvnCmd.Bat diff $EDNAME $SAVEALL" }, { "answer_id": 370734, "author": "Miel", "author_id": 17336, "author_profile": "https://Stackoverflow.com/users/17336", "pm_score": 1, "selected": false, "text": "svnserve.conf conf [general]\nanon-access = none\nauth-access = write\npassword-db = passwd\nrealm = My Projects\n[sasl]\n" }, { "answer_id": 371193, "author": "Bert Huijben", "author_id": 2094, "author_profile": "https://Stackoverflow.com/users/2094", "pm_score": 1, "selected": false, "text": "2. Why is there several versions of Windows Binaries? Tigris? SlikSVN? VisualSVN? \n" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370518", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30787/" ]
370,547
<p>How can I get a record id after saving it into database. Which I mean is actually something like that.</p> <p>I have Document class (which is entity tho from DataBase) and I create an instance like </p> <pre><code>Document doc = new Document() {title="Math",name="Important"}; dataContext.Documents.InsertOnSubmit(doc); dataContext.SubmitChanges(); </code></pre> <p>than what I want is to retrieve it's id value (docId) which is located in database and it's primary key also automatic number. One thing, there will be lots of users on the system and submits tons of records like that.</p> <p>Thanks in advance everybody :)</p>
[ { "answer_id": 370577, "author": "Nathan W", "author_id": 6335, "author_profile": "https://Stackoverflow.com/users/6335", "pm_score": 3, "selected": false, "text": "Document doc = new Document() {title=\"Math\",name=\"Important\"};\ndataContext.Documents.InsertOnSubmit(doc);\ndataContext.SubmitChanges();\n int ID = doc.docId;\n" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44852/" ]
370,548
<p>I have a row of divs that must all be the same height, but I have no way of knowing what that height might be ahead of time (the content comes from an external source). I initially tried placing the divs in an enclosing div and floated them left. I then set their height to be "100%", but this had no perceptible effect. By setting the height on the enclosing div to a fixed-height I could then get the floated divs to expand, but only up to the fixed height of the container. When the content in one of the divs exceeded the fixed height, it spilled over; the floated divs refused to expand.</p> <p>I Googled this floated-divs-of-the-same-height problem and apparently there's no way to do it using CSS. So now I am trying to use a combination of relative and absolute positioning instead of floats. This is the CSS:</p> <pre><code>&lt;style type="text/css"&gt; div.container { background: #ccc; position: relative; min-height: 10em; } div.a { background-color: #aaa; position: absolute; top: 0px; left: 0px; bottom: 0px; width: 40%; } div.b { background-color: #bbb; position: absolute; top: 0px; left: 41%; bottom: 0px; width: 40%; } &lt;/style&gt; </code></pre> <p>This is a simplified version of the HTML:</p> <pre><code> &lt;div class="container"&gt; &lt;div class="a"&gt;Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Integer pretium dui sit amet felis. Integer sit amet diam. Phasellus ultrices viverra velit.&lt;/div&gt; &lt;div class="b"&gt;Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Integer pretium dui sit amet felis. Integer sit amet diam. Phasellus ultrices viverra velit. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Integer pretium dui sit amet felis. Integer sit amet diam. Phasellus ultrices viverra velit.&lt;/div&gt; &lt;/div&gt; </code></pre> <p>This works, unless you change the min-height to something like 5em (demonstranting what happens when the content exceeds the minimum height), and you can see that while the text doesn't get cutoff, the divs still refuse to expand. Now I am at a lose. Is there any way to do this using CSS?</p>
[ { "answer_id": 370576, "author": "alex", "author_id": 31671, "author_profile": "https://Stackoverflow.com/users/31671", "pm_score": 1, "selected": false, "text": "display: table-cell" }, { "answer_id": 374237, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "$$('div.container').each(function (element) {\n var longest = 0;\n\n element.descendants().each(function (child) {\n if (child.getHeight() > longest)\n longest = child.getHeight();\n });\n\n element.descendants().each(function (child) {\n child.style.height = longest + 'px';\n });\n});\n" }, { "answer_id": 374247, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<div id=\"wrapper\">\n <div class=\"content\" id='one>\n <div class=\"content\" id=\"two>\n <div class=\"content\" id=\"three>\n <div class=\"background\" id=\"back-one\">\n <div class=\"background\" id=\"back-two\">\n <div class=\"background\" id=\"back-three\">\n</div>\n" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370548", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
370,549
<p>I have a static library *.lib created using MSVC on windows. The size of library is say 70KB. Then I have an application which links this library. But now the size of the final executable (*.exe) is 29KB, less than the library. What i want to know is :</p> <ol> <li><p>Since the library is statically linked, I was thinking it should add directly to the executable size and the final exe size should be more than that? Does windows exe format also do some compression of the binary data? </p></li> <li><p>How is it for linux systems, that is how do sizes of library on linux (*.a/*.la file) relate with size of linux executable (*.out) ? </p></li> </ol> <p>-AD</p>
[ { "answer_id": 370608, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 4, "selected": true, "text": ".lib .lib .exe" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2759376/" ]
370,557
<p>In Jackrabbit I have experienced two ways to save my POJOs into repository nodes for storage in the Jackrabbit JCR: </p> <ol> <li>writing my own layer and </li> <li>using Apache Graffito </li> </ol> <p>Writing my own code has proven time consuming and labor intensive (had to write and run a lot of ugly automated tests) though quite flexible. </p> <p>Using Graffito has been a disappointment because it seems to be a "dead" project <a href="http://incubator.apache.org/graffito/news.html" rel="noreferrer">stuck in 2006</a></p> <p>What are some better alternatives?</p>
[ { "answer_id": 371152, "author": "Alexander Klimetschek", "author_id": 2709, "author_profile": "https://Stackoverflow.com/users/2709", "pm_score": 5, "selected": true, "text": "javax.jcr.Node" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31892/" ]
370,571
<p>I am creating a pdf document using C# code in my process. I need to protect the docuemnt with some standard password like "123456" or some account number. I need to do this without any reference dlls like pdf writer.</p> <p>I am generating the PDF file using SQL Reporting services reports.</p> <p>Is there are easiest way.</p>
[ { "answer_id": 370888, "author": "Darin Dimitrov", "author_id": 29407, "author_profile": "https://Stackoverflow.com/users/29407", "pm_score": 6, "selected": true, "text": "using (Stream input = new FileStream(\"test.pdf\", FileMode.Open, FileAccess.Read, FileShare.Read))\nusing (Stream output = new FileStream(\"test_encrypted.pdf\", FileMode.Create, FileAccess.Write, FileShare.None))\n{\n PdfReader reader = new PdfReader(input);\n PdfEncryptor.Encrypt(reader, output, true, \"secret\", \"secret\", PdfWriter.ALLOW_PRINTING);\n}\n" }, { "answer_id": 10374961, "author": "Bobrovsky", "author_id": 249690, "author_profile": "https://Stackoverflow.com/users/249690", "pm_score": 1, "selected": false, "text": "public static void protectWithPassword(string input, string output)\n{\n using (PdfDocument doc = new PdfDocument(input))\n {\n // set owner password (a password required to change permissions)\n doc.OwnerPassword = \"pass\";\n\n // set empty user password (this will allow anyone to\n // view document without need to enter password)\n doc.UserPassword = \"\";\n\n // setup encryption algorithm\n doc.Encryption = PdfEncryptionAlgorithm.Aes128Bit;\n\n // [optionally] setup permissions\n doc.Permissions.CopyContents = false;\n doc.Permissions.ExtractContents = false;\n\n doc.Save(output);\n }\n}\n" }, { "answer_id": 50281758, "author": "David Graham", "author_id": 3237681, "author_profile": "https://Stackoverflow.com/users/3237681", "pm_score": 0, "selected": false, "text": " private string password = \"@d45235fewf\";\n private const string pdfFile = @\"C:\\Temp\\Old.pdf\";\n private const string pdfFileOut = @\"C:\\Temp\\New.pdf\";\n\npublic void DecryptPdf()\n{\n //Set reader properties and password\n ReaderProperties rp = new ReaderProperties();\n rp.SetPassword(new System.Text.UTF8Encoding().GetBytes(password));\n\n //Read the PDF and write to new pdf\n using (PdfReader reader = new PdfReader(pdfFile, rp))\n {\n reader.SetUnethicalReading(true);\n PdfDocument pdf = new PdfDocument(reader, new PdfWriter(pdfFileOut));\n pdf.GetFirstPage(); // Get at the very least the first page\n } \n} \n" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370571", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22162/" ]
370,578
<p>One doubt in MSSQL. There are two tables in a databases.</p> <p>Table 1 named Property contain fields PRPT_Id(int),PRPT_Name(varchar), PRPT_Status(bit) </p> <p>Table 2 named PropertyImages contain fields PIMG_Id(int),PIMG_ImageName(varchar),PRPT_Id(int),PIMG_Status(bit)</p> <p>These two tables follow a one-to-many relationship. That means the each Property can have zero, one or more PropertyImages corresponding to it.</p> <p>What is required is a query to display</p> <p>PRPT_Id, PRPT_Name, ImageCount(Count of all images corresponding to a PRPT_Id where PIMG_Status is true. o if there arent any images), FirstImageName(if there are n images, the name of the first image in the image table corresponding to the PRPT_Id with PIMG_Status true. if there aren't any images we fill that with whitespace/blank) . another condition is that PRPT_Status should be true.</p> <p>Edit Note - Both the tables are having autoincremented integers as primary key. So first Image name will be the name with MIN(PIMG_Id), isn't that so?</p> <p>I want the PIMG_ImageName corresponding to the MIN(PIMG_ID) in the resultset</p>
[ { "answer_id": 370589, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "SELECT PRPT_Id, COUNT(PIMG_Id) AS PRPT_ImageCount, MIN(PIMG_Id) AS PRPT_MinImage\nFROM PropertyImages\nGROUP BY PRPT_Id\n SELECT Properties.*, PRPT_ImageCount, PRPT_MinImage\nFROM Properties LEFT JOIN (\nSELECT PRPT_Id, COUNT(PIMG_Id) AS PRPT_ImageCount, MIN(PIMG_Id) AS PRPT_MinImage\nFROM PropertyImages\nGROUP BY PRPT_Id ) Temp ON ( Properties.PRPT_Id = Temp.PRPT_Id )\n SELECT Properties.*,\n PRPT_ImageCount,\n PRPT_MinImage,\n PIMG_ImageName\nFROM ( Properties LEFT JOIN\n ( SELECT PRPT_Id,\n COUNT(PIMG_Id) AS PRPT_ImageCount,\n MIN(PIMG_Id) AS PRPT_MinImage\n FROM PropertyImages\n GROUP BY PRPT_Id ) Temp1\n ON ( Properties.PRPT_Id = Temp1.PRPT_Id ) ) Temp2 LEFT JOIN\n PropertyImages ON ( PropertyImages.PIMG_Id = Temp2.PRPT_MinImage )\n" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17447/" ]
370,586
<p>Why is the following?:</p> <pre><code> const int i0 = 5; //int i1 = const_cast&lt;int&gt;(i0); // compilation error int i2 = (int)i0; // okay int i3 = 5; //const int i4 = const_cast&lt;const int&gt;(i3); // compilation error const int i5 = (const int)i3; // okay </code></pre>
[ { "answer_id": 370591, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 4, "selected": false, "text": " const int i0 = 5;\n//int i1 = const_cast<int>(i0); // compilation error\n int i2 = (int)i0; // okay\n\n int i3 = 5;\n//const int i4 = const_cast<const int>(i3); // compilation error\n const int i5 = (const int)i3; // okay\n int i1 = i0;\nconst int i4 = i3;\n const T* const T T* T T& const T& const int i0 = 5;\n//int & i1 = const_cast<int&>(i0); // okay (but dangerous)\n int & i2 = (int&)i0; // okay (but dangerous)\n\n int i3 = 5;\n//const int&i4 = const_cast<const int&>(i3); // ok now and valid!\n const int&i5 = (const int&)i3; // okay too!\n" }, { "answer_id": 370610, "author": "Rob Kennedy", "author_id": 33732, "author_profile": "https://Stackoverflow.com/users/33732", "pm_score": 3, "selected": false, "text": "const_cast const_cast" }, { "answer_id": 62984912, "author": "tartaruga_casco_mole", "author_id": 2287311, "author_profile": "https://Stackoverflow.com/users/2287311", "pm_score": 0, "selected": false, "text": "/* lvalue can be converted to lvalue or rvalue references */\nint& test1 = const_cast<int&>(var); // lvalue to l-ref; same works for class type\nint&& test2 = const_cast<int&&>(var); // lvalue to r-ref; same works for class type\n/* prvalues: restriction on built-in types to allow some compiler optimization */\n//int&& test5 = const_cast<int&&>(1); // prvalue of built-in not allowed\nA&& test6 = const_cast<A&&>(A()); // prvalue of class type allowed\n/* xvalue can be converted to rvalue references */\nint&& test8 = const_cast<int&&>(std::move(var)); //xvalue of built-in\nA&& test8 = const_cast<A&&>(std::move(A())); // xvalue of class\n" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
370,601
<p>In a bunch o' places in my code, I have something like this: </p> <pre><code>public Class mySpecialMethod() { return MySpecialClass.class; } </code></pre> <p>which causes the warning </p> <blockquote> <p>Class is a raw type. References to generic type Class should be parameterized.</p> </blockquote> <p>But, if I replace </p> <p><code>Class</code> </p> <p>with </p> <p><code>Class&lt;? extends Object&gt;</code></p> <p>the warning goes away. </p> <p>Is this simple practice ok, or could it cause trouble later?</p>
[ { "answer_id": 370674, "author": "Guillaume", "author_id": 23704, "author_profile": "https://Stackoverflow.com/users/23704", "pm_score": 3, "selected": false, "text": "public Class<MySpecialClass> mySpecialMethod() {\n return MySpecialClass.class;\n}\n" }, { "answer_id": 370686, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 2, "selected": false, "text": "Class<MySpecialClass> Class<Bar> Class<Foo> Class class Mine { }\n\nclass Vara {\n public static void main(String... args) {\n { // works. translated to Mine m = (Mine) c.newInstance();\n Class<Mine> c = Mine.class;\n Mine m = c.newInstance();\n }\n { // doesn't work. need a cast: Mine m = (Mine) c.newInstance();\n Class c = Mine.class; // also Class<?> or Class<? extends Object>\n Object o = c.newInstance(); // but this works. pointing to a Mine\n Mine m = (Mine) c.newInstance(); // needs a manual cast\n }\n }\n}\n Class<?> Class<? extends Object> T Object" }, { "answer_id": 370690, "author": "Joachim Sauer", "author_id": 40342, "author_profile": "https://Stackoverflow.com/users/40342", "pm_score": 5, "selected": true, "text": "Class<?> Class<? extends Object>" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370601", "https://Stackoverflow.com", "https://Stackoverflow.com/users/46277/" ]
370,622
<p>I have written a simple C++ program like this:</p> <pre><code>#include &lt;iostream&gt; using namespace std; int main() { cout &lt;&lt; "Hello."; return 0; } </code></pre> <p>Now I want to debug it. So what will be the command for it so my control goes to every line?</p>
[ { "answer_id": 370627, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 5, "selected": false, "text": "gdb $ gdb hello\n gdb next" }, { "answer_id": 370642, "author": "Salvatore Dario Minonne", "author_id": 10170, "author_profile": "https://Stackoverflow.com/users/10170", "pm_score": 4, "selected": false, "text": "g++ -g helloWorld.cc gdb ./a.out" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
370,624
<p>I'm learning C# by writing a home library manager.</p> <p>I have a BookController that will store the books in a data structure and perform operations on them.</p> <p>Does C# have a way of saving the data in the dictionary to a local file perhaps in an XML fashion to load later, or am I going to have to write it myself?</p> <p>What is the best method of saving and loading this data available to C#? Just need pointed in a good direction.</p>
[ { "answer_id": 370676, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 6, "selected": true, "text": "XmlSerializer BinaryFormatter DataContractSerializer BinaryFormatter XmlSerializer DataContractSerializer XmlSerializer XmlSerializer ser = new XmlSerializer(typeof(Foo));\n // write\n using (var stream = File.Create(\"foo.xml\"))\n {\n ser.Serialize(stream, foo); // your instance\n }\n // read\n using (var stream = File.OpenRead(\"foo.xml\"))\n {\n Foo newFoo = (Foo)ser.Deserialize(stream);\n }\n" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370624", "https://Stackoverflow.com", "https://Stackoverflow.com/users/46534/" ]
370,632
<p>Is it possible to use Mark of the Web in XML file which is parsed by a local XSL file?</p> <p>When I insert MOTW mark:</p> <pre><code>&lt;!-- saved from url=(0014)about:internet --&gt; </code></pre> <p>i get following message:<br> Access is Denied. Error Processing Resource.</p> <hr> <p>Ok, I see that I was trying to do it wrong - I wanted to insert this comment into XML.</p> <p>I have three files: XML with data, XSL to transform the data into html, and JS file with JavaScript functions. As you said, I want to get rid of the Internet Explorer orange bar.</p> <p>Putting everything on IIS or Apache is good way, but I want to open these files localy.</p> <p>I tried to insert xml:comment tag, but nothing happened (the bar is still showing).</p>
[ { "answer_id": 372540, "author": "scunliffe", "author_id": 6144, "author_profile": "https://Stackoverflow.com/users/6144", "pm_score": 0, "selected": false, "text": "<xsl:comment> saved from url=(0014)about:internet </xsl:comment>\n" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22174/" ]
370,641
<p>I have a client and server program (both in Obj-C) and I am transferring files between two devices using the programs.</p> <p>The transferring is working fine, but I would like to display to the user what transfer rate they are getting.</p> <p>So I know the total size of the file, and how much of the file has been transferred, is there a way to figure out the transfer rate from this information, and if not, what information do I need to calculate the transfer rate?</p> <p>Thanks</p>
[ { "answer_id": 370651, "author": "Marc Novakowski", "author_id": 27020, "author_profile": "https://Stackoverflow.com/users/27020", "pm_score": 5, "selected": true, "text": "transfer_speed = bytes_transferred / ( current_time - start_time)\n NSTimeInterval start = [NSDate timeIntervalSinceReferenceDate];\n double speed = bytesTransferred / ([NSDate timeIntervalSinceReferenceDate] - start);\n" }, { "answer_id": 372734, "author": "Peter Hosey", "author_id": 30461, "author_profile": "https://Stackoverflow.com/users/30461", "pm_score": 5, "selected": false, "text": "bytes_downloaded / (now - start_time)" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370641", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26728/" ]
370,664
<p>I have a two classes:</p> <pre><code>public class Question { public IList&lt;Answer&gt; Answers { get; set; } } public class Answer { .. } </code></pre> <p>In my Linq2Sql designer, there's two L2S objects on designer, with the correct 0&lt;->many arrow between them. Kewl.</p> <p>I'm not sure how i can retrieve these questions/answers in a single call and populate my POCO objects .. </p> <p>this is what i've got ... can someone fill in the blanks?</p> <pre><code>public IQueryable&lt;Question&gt; GetQuestions() { return from q in _db.Questions select new Question { Title = q.Title, Answers = ???????? // &lt;-- HALP! :) }; } </code></pre> <p>thoughts?</p> <h2>Update : War of the POCO</h2> <p>Thanks for the replies but it's not 100% there yet.</p> <p>Firstly, i'm returning a POCO class, not the Linq2Sql context class. This is why i'm doing...</p> <pre><code>select new Question { .. }; </code></pre> <p>that class is POCO, not the linq2sql.</p> <p>Secondly, I like the answers that point to doing Answers = q.Answers.ToList() but this also will not work because it's trying to set a Linq2Sql class to a POCO class.</p>
[ { "answer_id": 370671, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 4, "selected": true, "text": "return from q in _db.Questions\n select new Question\n {\n Title = q.Title,\n Answers = q.Answers.ToList(),\n }\n IQueryable<T> return from q in _db.Questions\n select new Question\n {\n Title = q.Title,\n Answers = (from a in q.Answers\n select new Answer { ... }).ToList(),\n }\n" }, { "answer_id": 370682, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "EntitySet<T> DataLoadOptions LoadWith() Northwnd db = new Northwnd(@\"c:\\northwnd.mdf\");\nDataLoadOptions dlo = new DataLoadOptions();\ndlo.LoadWith<Customer>(c => c.Orders);\ndb.LoadOptions = dlo;\n\nvar londonCustomers =\n from cust in db.Customers\n where cust.City == \"London\"\n select cust;\n\nforeach (var custObj in londonCustomers)\n{\n Console.WriteLine(custObj.CustomerID);\n}\n LoadWith Customer Orders Customer" }, { "answer_id": 370689, "author": "AndreasKnudsen", "author_id": 36465, "author_profile": "https://Stackoverflow.com/users/36465", "pm_score": 0, "selected": false, "text": "return (from q in _db.Questions\n select q).ToList();\n" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30674/" ]
370,667
<p>Does anyone know how to remove the extra branding on the google custom search? </p> <p>they've added a button and other things like text that says "gadgets powered by google".</p> <p>there has to be a way to pipe the CSE data into a normal form, right?</p> <p><a href="http://www.google.com/coop/cse/" rel="nofollow noreferrer">http://www.google.com/coop/cse/</a></p>
[ { "answer_id": 26536827, "author": "coddiwomplefrog", "author_id": 3005071, "author_profile": "https://Stackoverflow.com/users/3005071", "pm_score": 2, "selected": false, "text": "input.gsc-input {\n font-size: 11px; \n height: 16px !important;\n background: none !important;\n}\n .gsc-completion-container table {\n font-size: 11px;\n}\n .gsc-input-box {\n border-radius: 3px !important;\n}\n .gsc-adBlockVertical, .gsc-adBlock { /* this hides both the top and right ad blocks*/\n display:none;\n}\n.gsc-thinWrapper { /* this gives you use of the whole block, as opposed to 69% google gives*/\n width: 100%;\n}\n" }, { "answer_id": 60678467, "author": "Jay", "author_id": 751570, "author_profile": "https://Stackoverflow.com/users/751570", "pm_score": 0, "selected": false, "text": "<head>\n <style>\n .gcsc-find-more-on-google-branding {\n display: none!important;\n }\n .gsc-adBlock {\n display: none!important;\n }\n </style>\n</head>\n" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42589/" ]
370,678
<p>I just have started to learn Haskell and combine reading books and tutorials with solving problems from Project Euler. I have stuck on <a href="http://projecteuler.net/index.php?section=problems&amp;id=27" rel="nofollow noreferrer">Problem 27</a> because I get "C stack overflow" error using this code: </p> <p><strong>euler.hs</strong></p> <pre><code>divisors n = [x | x &lt;- [1..n `div` 2], n `mod` x == 0] ++ [n] is_prime n = divisors n == [1, n] f a b = [n^2 + a * n + b | n &lt;- [0..]] primes_from_zero a b = length(takeWhile is_prime (f a b)) </code></pre> <p><strong>command window</strong></p> <p>this command gives Euler's coefficients 1 and 41 (40 primes in row)</p> <pre><code>foldr (max) (0, 0, 0) [(primes_from_zero a b, a, b) | a &lt;- [0..10], b &lt;- [0..50]] </code></pre> <p>this one fails with "C stack overflow" (I wanted to obtain coefficients -79 and 1601 also mentioned in the problem definition):</p> <pre><code>foldr (max) (0, 0, 0) [(primes_from_zero a b, a, b) | a &lt;- [-100..0], b &lt;- [1500..1700]] </code></pre> <p>Would you tell me, please, why does the error arise and how to resolve it? Thank you!</p> <p>I use WinHugs.</p>
[ { "answer_id": 371568, "author": "Chris Conway", "author_id": 1412, "author_profile": "https://Stackoverflow.com/users/1412", "pm_score": 4, "selected": true, "text": "foldl f x (y:ys) = foldl f (f x y) ys\n foldr foldr f x (y:ys) = f y (foldr f x ys)\n foldr foldl foldl (f x y) foldl f foldl' foldl' f x (y:ys) = (foldl' f $! f x y) ys\n $!" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370678", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11256/" ]
370,694
<p>I am working on some batch file. I need to read name from some text file. Let me explain it</p> <p>I have one file <code>File.txt</code>, which has entry like <code>FirstName=John</code>. Now my batch file should read text <code>John</code> from the file and I should be able store <code>John</code> in some variable too.</p> <p>But with following code, if I use <code>delims==</code>,I can get <code>FirstName</code> text stored in some variable but not <code>John</code>.</p> <pre><code>for /F "delims==" %%I in (File.txt) do set Title=%%I echo %Title% </code></pre> <p>Is there any way where I can get <code>John</code> from my <code>File.txt</code> and store it with in my <code>for</code> loop ?</p>
[ { "answer_id": 370715, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 2, "selected": false, "text": "@echo off\nsetlocal\nfor /F \"tokens=1,2 delims==\" %%a in (File.txt) do set Title=%%b\necho %Title%\n Title Firstname @echo off\nsetlocal\nfor /F \"tokens=1,2 delims==\" %%a in (File.txt) do (\n set t=%t% %%b\n)\necho %t:Firstname=%\n" }, { "answer_id": 375681, "author": "Philibert Perusse", "author_id": 7984, "author_profile": "https://Stackoverflow.com/users/7984", "pm_score": 0, "selected": false, "text": "John Firstname tokens=2 %%I %%J %%K tokens=2* I J K" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370694", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
370,695
<p>I have a java class which fires custom java events. The structure of the code is the following:</p> <pre><code>public class AEvent extends EventObject { ... } public interface AListener extends EventListener { public void event1(AEvent event); } public class A { public synchronized void addAListener(AListener l) { .. } public synchronized void removeAListener(AListener l) { .. } protected void fireAListenerEvent1(AEvent event) { .. } } </code></pre> <p>Everything works correctly, but I'd like to create a new subclass of A (call it B), which may fire a new event. I'm thinking of the following modification:</p> <pre><code>public class BEvent extends AEvent { ... } public interface BListener extends AListener { public void event2(BEvent event); } public class B extends A { public synchronized void addBListener(BListener l) { .. } public synchronized void removeBListener(BListener l) { .. } protected void fireBListenerEvent2(AEvent event) { .. } } </code></pre> <p>Is this the correct approach? I was searching the web for examples, but couldn't find any.</p> <p>There are a few things I don't like in this solution:</p> <ol> <li><code>BListener</code> has two methods one uses <code>AEvent</code> the other uses <code>BEvent</code> as a parameter.</li> <li><code>B</code> class both has <code>addAListener</code> and <code>addBListener</code> methods. Should I hide addAListener with private keyword? <strong>[UPDATE: it's not possible to hide with private keyword]</strong></li> <li>Similar problem with <code>fireAListenerEvent1</code> and <code>fireBListenerEvent1</code> methods.</li> </ol> <p>I'm using Java version 1.5.</p>
[ { "answer_id": 370703, "author": "Joachim Sauer", "author_id": 40342, "author_profile": "https://Stackoverflow.com/users/40342", "pm_score": 5, "selected": true, "text": "BListener AListener B event1() addAListener() fire*()" }, { "answer_id": 371331, "author": "Yoni Roit", "author_id": 34161, "author_profile": "https://Stackoverflow.com/users/34161", "pm_score": 2, "selected": false, "text": "class AEvent {}\nclass BEvent extends Event{}\n\ninterface EventListner<E extends AEvent>\n{\n onEvent(E e);\n}\n\nclass ListenerManager<E extends AEvent>{\n addListner(EventListener<? extends E>){}\n removeListner(EventListener<? extends E>){}\n fire(E e);\n}\n\nclass A extends ListenerManager<AEvent>\n{\n}\n\nclass B extends ListenerManager<BEvent>\n{\n A delegatorA;\n\n @Override addListener(EventListener<? extends BEvent> l)\n {\n super.addListner(l);\n delegatorA.addListener(l);\n } \n\n @Override removeListener(EventListener<? extends BEvent> l)\n {\n super.removeListner(l);\n delegatorA.removeListener(l);\n } \n\n @Override fire(BEvent b)\n {\n super.fire(b);\n a.fire(b)\n }\n\n}\n" }, { "answer_id": 483650, "author": "Slartibartfast", "author_id": 4433, "author_profile": "https://Stackoverflow.com/users/4433", "pm_score": 1, "selected": false, "text": "public class BEvent extends AEvent {\n...\n}\n\npublic interface BListener extends AListener {\n\n public void event2(BEvent event);\n}\n public class B extends A {\n\n @Override\n public synchronized void addAListener(AListener l) {\n if (l instanceof BListener) {\n ...\n } else {\n super.addAListener(l);\n }\n }\n ...\n}\n" }, { "answer_id": 490422, "author": "OscarRyz", "author_id": 20654, "author_profile": "https://Stackoverflow.com/users/20654", "pm_score": 2, "selected": false, "text": " if( whichEvent instanceof SpecificEvent ) { \n SpecificEvent s = ( SpecificEvent ) whichEvent;\n // Do something specific here...\n }\n import java.util.*;\nclass A { \n\n // All the listener will be kept here. No matter if basic or specific.\n private List<Listener> listeners = new ArrayList<Listener>();\n\n\n public void add( Listener listener ) { \n listeners.add( listener );\n }\n public void remove( Listener listener ) { \n listeners.remove( listener );\n }\n\n\n // In normal work, this class just perform a basic operation.\n public void normalWork(){\n performBasicOperation();\n }\n\n // Firing is just firing. The creation work and the \n // operation should go elsewhere.\n public void fireEvent( Event e ) { \n for( Listener l : listeners ) { \n l.eventHappened( e );\n }\n }\n\n // A basic operation creates a basic event\n public void performBasicOperation() { \n Event e = new BasicEvent();\n fireEvent( e );\n }\n}\n\n// Specialized version of A.\n// It may perform some basic operation, but also under some special circumstances\n// it may perform an specific operation too\nclass B extends A { \n\n // This is a new functionality added by this class.\n // Hence an specifi event is fired.\n public void performSpecificOperation() {\n Event e = new SpecificEvent();\n // No need to fire in different way\n // an event is an event and that's it.\n fireEvent( e );\n }\n\n // If planets are aligned, I will perform \n // an specific operation.\n public void normalWork(){\n if( planetsAreAligned() ) { \n performSpecificOperation();\n } else { \n performBasicOperation();\n }\n }\n private boolean planetsAreAligned() { \n //return new Random().nextInt() % 3 == 0;\n return true;\n }\n}\n\n// What's an event? Something from where you can get event info?\ninterface Event{\n public Object getEventInfo();\n}\n\n// This is the basic event.\nclass BasicEvent implements Event{\n public Object getEventInfo() {\n // Too basic I guess.\n return \"\\\"Doh\\\"\";\n }\n}\n// This is an specific event. In this case, an SpecificEvent IS-A BasicEvent.\n// So , the event info is the same as its parent. \"Doh\".\n// But, since this is an SpecificEvent, it also has some \"Specific\" features.\nclass SpecificEvent extends BasicEvent {\n\n // This method is something more specific.\n // There is no need to overload or create \n // different interfaces. Just add the new specific stuff\n public Object otherMethod() {\n return \"\\\"All I can say is , this was an specific event\\\"\";\n }\n}\n\n// Hey something just happened.\ninterface Listener { \n public void eventHappened( Event whichEvent );\n}\n\n// The basic listner gets information \n// from the basic event. \nclass BasicEventListener implements Listener { \n public void eventHappened( Event e ) {\n System.out.println(this.getClass().getSimpleName() + \": getting basic functionality: \" + e.getEventInfo());\n }\n}\n\n\n// But the specific listner may handle both.\n// basic and specific events.\nclass SpecificListener extends BasicEventListener { \n public void eventHappened( Event whichEvent ) {\n // Let the base to his work\n super.eventHappened( whichEvent );\n\n\n // ONLY if the event if of interest to THIS object\n // it will perform something extra ( that's why it is specific )\n if( whichEvent instanceof SpecificEvent ) { \n SpecificEvent s = ( SpecificEvent ) whichEvent;\n System.out.println(this.getClass().getSimpleName() + \": aaand getting specific functionality too: \" + s.otherMethod() );\n // do something specific with s \n }\n }\n}\n\n// See it run. \n// Swap from new A() to new B() and see what happens.\nclass Client { \n public static void main( String [] args ) { \n A a = new B();\n //A a = new A();\n\n a.add( new BasicEventListener() );\n a.add( new SpecificListener() );\n\n a.normalWork();\n }\n}\n BasicEventListener: getting basic functionality: \"Doh\"\nSpecificListener: getting basic functionality: \"Doh\"\nSpecificListener: aaand getting specific functionality too: \"All I can say is , this was an specific event\"\n" }, { "answer_id": 492011, "author": "Zach Scrivena", "author_id": 20029, "author_profile": "https://Stackoverflow.com/users/20029", "pm_score": 1, "selected": false, "text": "A B BListener AListener BListener BEvent AEvent B public class MovableMouseEvent extends EventObject\n\npublic class ClickableMouseEvent extends MovableMouseEvent\n\npublic interface MovableMouseListener extends EventListener\n // mouseMoved(MovableMouseEvent)\n\npublic interface ClickableMouseListener extends MovableMouseListener \n // mouseClicked(ClickableMouseEvent) \n\npublic class MovableMouseWidget\n // {addMovableMouseListener,removeMovableMouseListener}(MovableMouseListener)\n // fireMovableMouseEvent(MovableMouseEvent) \n\npublic class ClickableMouseWidget extends MovableMouseWidget\n // {addClickableMouseListener,removeClickableMouseListener}(ClickableMouseListener)\n // fireClickableMouseEvent(ClickableMouseEvent) \n ClickableMouseListener ClickableMouseWidget public class MouseMoveEvent extends EventObject // note the name change\n\npublic class MouseClickEvent extends EventObject // don't extend MouseMoveEvent \n\npublic interface MouseMoveListener extends EventListener\n // mouseMoved(MouseMoveEvent)\n\npublic interface MouseClickListener extends EventListener // don't extend MouseMoveListener \n // mouseClicked(MouseClickEvent) \n\npublic interface MouseMoveObserver\n // {addMouseMoveListener,removeMouseMoveListener}(MouseMoveListener)\n // fireMouseMoveEvent(MouseMoveEvent)\n\npublic interface MouseClickObserver\n // {addMouseClickListener,removeMouseClickListener}(MouseClickListener)\n // fireMouseClickEvent(MouseClickEvent)\n\npublic class MovableMouseWidget implements MouseMoveObserver\n\npublic class ClickableMouseWidget implements MouseMoveObserver, MouseClickObserver\n" }, { "answer_id": 492190, "author": "Mark Renouf", "author_id": 758, "author_profile": "https://Stackoverflow.com/users/758", "pm_score": 3, "selected": false, "text": "public interface Listener<T> {\n void event(T event);\n}\n public interface EventSource<T> {\n void addListener(Listener<T> listener);\n}\n public abstract class EventDispatcher<T> {\n private List<Listener<T>> listeners = new CopyOnWriteArrayList<T>();\n\n void addListener(Listener<T> listener) {\n listeners.add(listener);\n } \n\n void removeListener(Listener<T> listener) {\n listeners.remove(listener);\n }\n\n void fireEvent(T event) {\n for (Listener<T> listener : listeners) {\n listener.event(event);\n } \n }\n}\n public class Message {\n}\n\npublic class InBox implements EventSource<Message> {\n\n private final EventDispatcher<Message> dispatcher = new EventDispatcher<Message>();\n\n public void addListener(Listener<Message> listener) {\n dispatcher.addListener(listener);\n }\n\n public void removeListener(Listener<Message> listener) {\n dispatcher.removeListener(listener);\n }\n\n public pollForMail() {\n // check for new messages here...\n // pretend we get a new message...\n\n dispatcher.fireEvent(newMessage);\n }\n}\n" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21348/" ]
370,698
<p>I'm researching a bug that looks like some kind of timing issue and so I'm a bit curious about how events work in Delphi 7. What happens is we get some data sent to our application through a COM interface and it gets handled in an event raised from the COM thread. It seems like the event, which has quite a bit of code in it, takes longer and longer to execute and after a while the entire application crashes. There are calls to graphics and stuffing into large arrays inside the event that might affect time. I have been unable to spot any significant increase in memory usage and have not had opportunity to run any profilers to check for leaks yet. Also, the obvious thing to test would be to strip the event of all the code in it just to see if we can run for a longer period of time.</p> <p>Are events serial or parallell in Delphi, that is, if I get a new event while one is executing -what happens? Is it run in parallell on some kind of automatic thread, is it ignored or is it queued up?</p> <p>If it is queued up, how many can I have in the queue before the application crashes?</p> <p>Does indexing into a large array take longer the further into it you are? Even if it's of a fixed size? I don't think it should so I'm looking for leaks and allocations that take time. If I get sent an object through the event, should I dispose of it within the event or in the "calling" code?</p> <p>What things usually do not scale well in Delphi? What can I look for that would increase in execution time?</p> <p>Finally, since this is COM related, any pointers to common pitfalls in COM are appreciated although I realize this is tricky. I do have a grip on co-initialize though.</p>
[ { "answer_id": 972767, "author": "Christer Fahlgren", "author_id": 87476, "author_profile": "https://Stackoverflow.com/users/87476", "pm_score": 0, "selected": false, "text": "CoInitializeEx(nil, COINIT_MULTITHREADED);" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370698", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9077/" ]
370,707
<p>I fail to understand why this code won't compile</p> <pre><code>ExecutorService executor = new ScheduledThreadPoolExecutor(threads); class DocFeeder implements Callable&lt;Boolean&gt; {....} ... List&lt;DocFeeder&gt; list = new LinkedList&lt;DocFeeder&gt;(); list.add(new DocFeeder(1)); ... executor.invokeAll(list); </code></pre> <p>The error msg is: </p> <pre><code>The method invokeAll(Collection&lt;Callable&lt;T&gt;&gt;) in the type ExecutorService is not applicable for the arguments (List&lt;DocFeeder&gt;) </code></pre> <p><code>list</code> is a <code>Collection</code> of <code>DocFeeder</code>, which implements <code>Callable&lt;Boolean&gt;</code> - What is going on?!</p>
[ { "answer_id": 370721, "author": "Joachim Sauer", "author_id": 40342, "author_profile": "https://Stackoverflow.com/users/40342", "pm_score": 3, "selected": false, "text": "list Collection<Callable<Boolean>> list = new LinkedList<Callable<Boolean>>();\n" }, { "answer_id": 370742, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 5, "selected": true, "text": "invokeAll(Collection<Callable<T>> tasks) \n invokeAll(Collection<? extends Callable<T>> tasks) \n List<DocFeeder> Collection<? extends Callable<T>> Collection<Callable<T>> public void addSomething(Collection<Callable<Boolean>> collection)\n{\n collection.add(new SomeCallable<Boolean>());\n}\n addSomething List<DocFeeder> List<Callable<Boolean>> List<DocFeeder>" }, { "answer_id": 754712, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "Collection<Callable<Boolean>> list = new LinkedList<Callable<Boolean>>();\n" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4038/" ]
370,716
<p>I have written jQuery code, in files <code>Main.html</code> and <code>ajax.php</code>. The <code>ajax.php</code> file returns the link of images to <code>Main.html</code>.</p> <p>Now in <code>Main.html</code>, I have Image1, Image2, Image3, etc.</p> <p>My <code>Main.html</code> file:</p> <pre><code>&lt;html&gt; ... # ajax.php Call ... # Return fields from Ajax.php &lt;/html&gt; </code></pre> <p>My ajax.php file</p> <pre><code>echo "&lt;a href='src1'&gt;&lt;img src='src_path1' id='fid1' alt='Name1' /&gt;&lt;/a&gt;Click To View image1\n"; echo "&lt;a href='src2'&gt;&lt;img src='src_path2' id='fid2' alt='Name2' /&gt;&lt;/a&gt;Click To View image2\n"; // etc. </code></pre> <p>So, after executing ajax.php, I get the image locations in Main.html.</p> <p>Now, when I click the Image1 link from Main.html, that corresponding image should display in the same window.</p> <p>So I thought about whether again to use jQuery to view an image on the same page. How can I achieve this?</p>
[ { "answer_id": 370762, "author": "kgiannakakis", "author_id": 24054, "author_profile": "https://Stackoverflow.com/users/24054", "pm_score": 0, "selected": false, "text": "<div id=\"pictureframe\"></div>\n $(\"#pictureframe\").load(image_url);\n" }, { "answer_id": 370764, "author": "Ata", "author_id": 46110, "author_profile": "https://Stackoverflow.com/users/46110", "pm_score": 0, "selected": false, "text": "img <div id=\"imageDivisionHolder\" style=\"disply:none;\">\n <img id=\"imageItemHolder\" src=\"\" alt=\"\" />\n</div>\n ajax.php Title <img src='src_path1' id='fid1' alt='Name1' class='item' Title='src_path1_bigimage' />\n $(document).ready(function(){\n $(\"img.item\").click(function(){\n $(\"#imageItemHolder\").attr(\"src\",$(this).attr(\"title\"));\n $(\"#imageDivisionHolder\").show();\n });\n});\n" }, { "answer_id": 374637, "author": "Ata", "author_id": 46110, "author_profile": "https://Stackoverflow.com/users/46110", "pm_score": 1, "selected": true, "text": "ajax.php <a href=\"#\" class=\"imageLink\" title=\"fid1\"><img src=\"src1\" id=\"fid1\" alt=\"Name1\" style=\"display:none;\" /><span>Click To View image1</span></a> \n<a href=\"#\" class=\"imageLink\" title=\"fid2\"><img src=\"src2\" id=\"fid2\" alt=\"Name2\" style=\"display:none;\" /><span>Click To View image2</span></a> \n<a href=\"#\" class=\"imageLink\" title=\"fid3\"><img src=\"src3\" id=\"fid3\" alt=\"Name3\" style=\"display:none;\" /><span>Click To View image3</span></a> \n $(document).ready(function(){\n $(\"a.imageLink\").click(function(){\n $(\"#\"+$(this).attr(\"title\")).show();\n $(this).find(\"span\").hide();\n });\n});\n" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44984/" ]
370,717
<p>I have a job to enter survey results (in paper form) to excel. I've never written any macro in Office :(</p> <p>Here I what I basically need:</p> <ol> <li>I have predefined columns (|A|B|...|AG|AH|)</li> <li>All surveys are grouped into groups. All surveys from same group have few (like predefined) same columns. It's always same columns that 'define' group</li> <li>All other survey answers are in numerical type [1..10].</li> <li>Columns are not in same order as answers in servey</li> <li>I want macro that will take my input (for example '1575'), and first place predefined values to that 'group' to |A| |B| |C|, and then |E| = 1, |D| = 5, |F| = 7, |G| = 5, and automatically start entering next row.</li> </ol> <p>Anything that will give me a clue how to write this macro in more than welcome</p> <p>Huge thanks for reading this... </p> <p>EDIT1: I suppose question is not clear enough... I need macro that will read my keyboard input ( '1575' ) and write integers '1' '5' '7' and '5' to predefined rows. For now, I have an idea to make a form, but I need event handler that will change focus to next input when I press a key, as I want to avoid pressing TAB all the time...</p>
[ { "answer_id": 371143, "author": "Fionnuala", "author_id": 2548, "author_profile": "https://Stackoverflow.com/users/2548", "pm_score": 3, "selected": true, "text": "Dim LastCol As Integer\nDim CurRow As Integer\n\n\nPrivate Sub UpdateCells()\nDim Col As Variant\nDim ColumnOrder As Range\n\n'Range that specifies data entry order'\nSet ColumnOrder = Range(\"A3:A15\")\n\nLastCol = LastCol + 1\n\nIf LastCol > WorksheetFunction.CountA(ColumnOrder) Then\n LastCol = 1\n CurRow = CurRow + 1\nEnd If\n\nCol = Range(\"A3\").Offset(0, LastCol)\nRange(Col & CurRow) = TextBox1.Value\nTextBox1 = \"\"\n\nEnd Sub\n\nPrivate Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)\nIf KeyCode = 13 Then\n UpdateCells\nEnd If\nEnd Sub\n\nPrivate Sub UserForm_Initialize()\nCurRow = ActiveCell.Row\nEnd Sub\n Function FindLastRow()\n'Assuming that data starts in A1'\nr = ActiveSheet.UsedRange.Rows.Count\nc = ActiveSheet.UsedRange.Columns.Count\nFindLastRow = r\nEnd Function\n Sub LastRow()\nLastRowA = ExecuteExcel4Macro(\"GET.DOCUMENT(10)\")\nLastRowB = ActiveSheet.Cells.SpecialCells(xlCellTypeLastCell).Row\nEnd Sub\n" }, { "answer_id": 372844, "author": "KnomDeGuerre", "author_id": 24233, "author_profile": "https://Stackoverflow.com/users/24233", "pm_score": -1, "selected": false, "text": "=VALUE(MID(Inputs,N,1))\n" }, { "answer_id": 379601, "author": "Dick Kusleika", "author_id": 4280, "author_profile": "https://Stackoverflow.com/users/4280", "pm_score": 1, "selected": false, "text": "Private Sub Worksheet_Change(ByVal Target As Range)\n\n Dim sText As String\n\n Application.EnableEvents = True\n\n If Target.Column = 1 Then 'Four digits entered in col A\n sText = CStr(Target.Value) 'convert to string\n If Len(sText) = 4 Then\n Target.Offset(0, 4).Value = Left$(sText, 1) 'write to E\n Target.Offset(0, 3).Value = Mid$(sText, 2, 1) 'D\n Target.Offset(0, 5).Value = Mid$(sText, 3, 1) 'F\n Target.Offset(0, 6).Value = Mid$(sText, 4, 1) 'G\n End If\n End If\n\n Application.EnableEvents = True\n\nEnd Sub" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35425/" ]
370,718
<p>Is it possible to access a USB drive or Flash card without using the drive letter that Windows assigns it? I thought I read somewhere that the Volume GUID or something can be used but will that allow me to open it up in explorer once I identify it? The reason this is important to me is because there may not be enough drive letters to handle the number of drives so I want to be able to still access them.</p>
[ { "answer_id": 370732, "author": "Chris", "author_id": 43960, "author_profile": "https://Stackoverflow.com/users/43960", "pm_score": 2, "selected": true, "text": "MOUNTVOL C:\\USB: \\\\?\\Volume{ebc79032-5270-11d8-a724-806d6172696f}\\ \n\nOR Winkey+R (Start-Run) \\\\?\\Volume{ebc79032-5270-11d8-a724-806d6172696f}\\ \n" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
370,720
<p>I have the following construction:</p> <pre><code>typedef struct bucket { char *key; ENTRY *data; struct bucket *next; } bucket; typedef struct { size_t size; bucket **table; } hash_table; </code></pre> <p>But I have no idea how to allocate memory for that. I tried: </p> <pre><code>hash_table* ht = malloc(sizeof(hash_table)*101); </code></pre> <p>in order to create a hashtable for 101 entries but it din't work! Can anyone help me? I would really appreciate it!</p>
[ { "answer_id": 370726, "author": "Joachim Sauer", "author_id": 40342, "author_profile": "https://Stackoverflow.com/users/40342", "pm_score": 0, "selected": false, "text": "hash_table sizeof(hash_table) table bucket hash_table* ht = malloc(sizeof(hash_table));\nht->size = 101;\nht->table = malloc(sizeof(bucket*)*ht->size);\n hash_table* ht = alloc_hash_table(101);\n" }, { "answer_id": 370729, "author": "jmucchiello", "author_id": 44065, "author_profile": "https://Stackoverflow.com/users/44065", "pm_score": 1, "selected": true, "text": " hash_table* init_table(size_t size) {\n size_t i;\n hash_table* ht = (hash_table*)malloc(sizeof(hash_table));\n if (ht == NULL) return NULL;\n ht->size = size;\n ht->table = (bucket**)malloc(sizeof(bucket*)*size);\n if (ht->table == NULL) {\n free(ht);\n return NULL;\n }\n for (i = 0; i < size; ++i) {\n ht->table[i] = NULL;\n }\n return ht;\n }\n hash_table* init_table(size_t size) {\n hash_table* ht = (hash_table*)malloc(sizeof(hash_table)+sizeof(bucket)*size);\n if (ht == NULL) return NULL;\n ht->size = size;\n ht->table = (bucket**)(ht+1);\n for (i = 0; i < size; ++i) {\n ht->table[i] = NULL;\n }\n return ht;\n }\n" }, { "answer_id": 370750, "author": "unwind", "author_id": 28169, "author_profile": "https://Stackoverflow.com/users/28169", "pm_score": 3, "selected": false, "text": "hash_table * hash_table_new(size_t capacity)\n{\n size_t i;\n\n hash_table *t = malloc(sizeof *t);\n t->size = capacity;\n t->bucket = malloc(t->size * sizeof *t->bucket);\n for(i = 0; i < t->size; i++)\n t->bucket[i] = NULL;\n return t;\n}\n sizeof malloc()" }, { "answer_id": 572083, "author": "RandomNickName42", "author_id": 67819, "author_profile": "https://Stackoverflow.com/users/67819", "pm_score": 0, "selected": false, "text": "hash_table* ht = (phash_table) malloc(sizeof(hash_table)*101);\n typedef struct _bucket { \n char *key; \n void *data; \n _bucket *next;\n} bucket, *pbucket;\n\ntypedef struct _hash_table { \n size_t size; \n pbucket *table;\n}hash_table, *phash_table;\n" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370720", "https://Stackoverflow.com", "https://Stackoverflow.com/users/43960/" ]
370,722
<p>i'm begginner in java, i have textarea and i have set only verticle scrollbar to that textarea.i'm appending data for every 1 minute to textarea,problem is when new data appends to the textarea scrollbar will move up.To see the new data,every time i have to drag the scroll bar, that is not the requirment.i want scrollbar should not move up it should move down how can i do this? plz help me.</p> <p>thanks for reply</p>
[ { "answer_id": 370726, "author": "Joachim Sauer", "author_id": 40342, "author_profile": "https://Stackoverflow.com/users/40342", "pm_score": 0, "selected": false, "text": "hash_table sizeof(hash_table) table bucket hash_table* ht = malloc(sizeof(hash_table));\nht->size = 101;\nht->table = malloc(sizeof(bucket*)*ht->size);\n hash_table* ht = alloc_hash_table(101);\n" }, { "answer_id": 370729, "author": "jmucchiello", "author_id": 44065, "author_profile": "https://Stackoverflow.com/users/44065", "pm_score": 1, "selected": true, "text": " hash_table* init_table(size_t size) {\n size_t i;\n hash_table* ht = (hash_table*)malloc(sizeof(hash_table));\n if (ht == NULL) return NULL;\n ht->size = size;\n ht->table = (bucket**)malloc(sizeof(bucket*)*size);\n if (ht->table == NULL) {\n free(ht);\n return NULL;\n }\n for (i = 0; i < size; ++i) {\n ht->table[i] = NULL;\n }\n return ht;\n }\n hash_table* init_table(size_t size) {\n hash_table* ht = (hash_table*)malloc(sizeof(hash_table)+sizeof(bucket)*size);\n if (ht == NULL) return NULL;\n ht->size = size;\n ht->table = (bucket**)(ht+1);\n for (i = 0; i < size; ++i) {\n ht->table[i] = NULL;\n }\n return ht;\n }\n" }, { "answer_id": 370750, "author": "unwind", "author_id": 28169, "author_profile": "https://Stackoverflow.com/users/28169", "pm_score": 3, "selected": false, "text": "hash_table * hash_table_new(size_t capacity)\n{\n size_t i;\n\n hash_table *t = malloc(sizeof *t);\n t->size = capacity;\n t->bucket = malloc(t->size * sizeof *t->bucket);\n for(i = 0; i < t->size; i++)\n t->bucket[i] = NULL;\n return t;\n}\n sizeof malloc()" }, { "answer_id": 572083, "author": "RandomNickName42", "author_id": 67819, "author_profile": "https://Stackoverflow.com/users/67819", "pm_score": 0, "selected": false, "text": "hash_table* ht = (phash_table) malloc(sizeof(hash_table)*101);\n typedef struct _bucket { \n char *key; \n void *data; \n _bucket *next;\n} bucket, *pbucket;\n\ntypedef struct _hash_table { \n size_t size; \n pbucket *table;\n}hash_table, *phash_table;\n" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370722", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
370,754
<p>In a C# Windows.Forms project I have a control that does not supply the KeyPressed event (It’s a COM control – ESRI map). </p> <p>It only supplies the KeyUp and KeyDown events, containing the <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.keyeventargs.aspx" rel="noreferrer">KeyEventArgs</a> structure.</p> <p>How can I convert the information in KeyEventArgs to a displayable Unicode character, taking the current active keyboard layout into account, etc.?</p>
[ { "answer_id": 375047, "author": "Itai Bar-Haim", "author_id": 47104, "author_profile": "https://Stackoverflow.com/users/47104", "pm_score": 5, "selected": true, "text": " public class KeyboardHelper\n {\n [DllImport(\"user32.dll\", CharSet = CharSet.Unicode, ExactSpelling = true)]\n private static extern int ToUnicodeEx(\n uint wVirtKey,\n uint wScanCode,\n Keys[] lpKeyState,\n StringBuilder pwszBuff,\n int cchBuff,\n uint wFlags,\n IntPtr dwhkl);\n\n [DllImport(\"user32.dll\", ExactSpelling = true)]\n internal static extern IntPtr GetKeyboardLayout(uint threadId);\n\n [DllImport(\"user32.dll\", ExactSpelling = true)]\n internal static extern bool GetKeyboardState(Keys[] keyStates);\n\n [DllImport(\"user32.dll\", ExactSpelling = true)]\n internal static extern uint GetWindowThreadProcessId(IntPtr hwindow, out uint processId);\n\n public static string CodeToString(int scanCode)\n {\n uint procId;\n uint thread = GetWindowThreadProcessId(Process.GetCurrentProcess().MainWindowHandle, out procId);\n IntPtr hkl = GetKeyboardLayout(thread);\n\n if (hkl == IntPtr.Zero)\n {\n Console.WriteLine(\"Sorry, that keyboard does not seem to be valid.\");\n return string.Empty;\n }\n\n Keys[] keyStates = new Keys[256];\n if (!GetKeyboardState(keyStates))\n return string.Empty;\n\n StringBuilder sb = new StringBuilder(10);\n int rc = ToUnicodeEx((uint)scanCode, (uint)scanCode, keyStates, sb, sb.Capacity, 0, hkl);\n return sb.ToString();\n }\n }\n" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38265/" ]
370,768
<p>Requirements:</p> <ul> <li>Must be able to use C strings as well as C++ strings</li> <li>Fast</li> <li>No maps</li> <li>No templates</li> <li>No direct lookup, i.e. index might be out of bounds.</li> <li>Index is not consecutive</li> <li>Enums and strings contained in one header file</li> <li>Only instantiate what you use.</li> </ul> <p>This is what I have come up with so far:</p> <pre><code>- test.hh - // Generic mapper // // The idea here is to create a map between an integer and a string. // By including it inside a class we prevent every module which // includes this include file from creating their own instance. // struct Mapper_s { int Idx; const char *pStr; }; // Status enum State_t { Running = 1, Jumping = 6, Singing = 12 }; struct State_s { static const Mapper_s *GetpMap(void) { static Mapper_s Map[] = { { Running, "Running" }, { Jumping, "Jumping" }, { Singing, "Singing" }, { 0, 0} }; return Map; }; }; - test.cc - // This is a generic function const char *MapEnum2Str(int Idx, const Mapper_s *pMap) { int i; static const char UnknownStr[] = "Unknown"; for (i = 0; pMap[i].pStr != 0; i++) { if (Idx == pMap[i].Idx) { return pMap[i].pStr; } } return UnknownStr; } int main() { cout &lt;&lt; "State: " &lt;&lt; MapEnum2Str(State, State_s::GetpMap()) &lt;&lt; endl; return 0; } </code></pre> <p>Any suggestions on how to improve this ? </p> <p>I feel that the header file looks slightly cluttered... </p>
[ { "answer_id": 370805, "author": "Patrick", "author_id": 38892, "author_profile": "https://Stackoverflow.com/users/38892", "pm_score": 0, "selected": false, "text": "struct map {\nconst char *mapping[] = { \"Running\", \"Jumping\", \"Singing\" };\nconst int count = 3;\n}\n struct map {\nmap() { \n for( count = 0; strlen( mapping[count] ); ++i )\n}\n\nconst char *mapping[] = { \"Running\", \"Jumping\", \"Singing\", \"\" };\nint count;\n}\n" }, { "answer_id": 472462, "author": "Crashworks", "author_id": 53543, "author_profile": "https://Stackoverflow.com/users/53543", "pm_score": 1, "selected": false, "text": "// Status\nenum State_t\n{\n Running = 1,\n Jumping = 6, \n Singing = 12\n};\n\nconst char *StateToString(State_t state)\n{\n switch(state)\n {\n case Running: return \"Running\";\n case Jumping: return \"Jumping\";\n case Singing: return \"Singing\";\n default: return \"ERROR\"; \n }\n}\n" }, { "answer_id": 472642, "author": "tormod", "author_id": 46583, "author_profile": "https://Stackoverflow.com/users/46583", "pm_score": 2, "selected": true, "text": "struct Mapper_s\n{\n int Idx;\n const char *pStr;\n};\n\n#define ENUM2STR_BEGIN(x) struct x { static const Mapper_s *GetpMap(void) { static const Enum2StrMap_s Map[] = \n#define ENUM2STR_END return Map; }; }\n\nconst char *MapEnum2Str(int Idx, const Mapper_s *pMap);\n #include \"e2str.hh\"\n\nENUM2STR_BEGIN(State_s) \n{\n { Running, \"Running\" },\n { Singing, \"Singing\" },\n { Jumping, \"Jumping\" },\n { 0, 0}\n};\nENUM2STR_END;\n #include \"mapper.hh\"\nint main()\n{\n cout << \"State: \" << MapEnum2Str(State, State_s::GetpMap()) << endl;\n return 0;\n}\n" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370768", "https://Stackoverflow.com", "https://Stackoverflow.com/users/46583/" ]
370,783
<p>My master page has a contentplaceholder in the head tag.</p> <p>Because I want my page's title to represent the function of the current page and because I want the title to be translated in the user's language I have added a title tag in the page's head's contentplaceholder. All jolly and good except that now there appears a second, empty title tag that off course isn't valid.</p> <p>Any ideas how to solve this?</p>
[ { "answer_id": 370827, "author": "Zhaph - Ben Duguid", "author_id": 33051, "author_profile": "https://Stackoverflow.com/users/33051", "pm_score": 3, "selected": false, "text": "<title><%= Html.Encode(ViewData[\"Title\"]) %></title>\n ViewData[\"Title\"] = \"Home\";\n" }, { "answer_id": 611555, "author": "Helephant", "author_id": 13028, "author_profile": "https://Stackoverflow.com/users/13028", "pm_score": 4, "selected": true, "text": "<title visible=\"false\" runat=\"server\"><%-- hack to turn the auto title off --%></title>\n" }, { "answer_id": 2552080, "author": "JamesStuddart", "author_id": 138096, "author_profile": "https://Stackoverflow.com/users/138096", "pm_score": 0, "selected": false, "text": "<%@ Page Title=\"PAGE NAME HERE\" Language=\"C#\" MasterPageFile=\"~/Controls/MasterPage/MasterPage.master\"\nAutoEventWireup=\"true\" CodeFile=\"Default.aspx.cs\" Inherits=\"Default\" %>\n Page.Title = \"Your page title\"\n" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370783", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11333/" ]
370,796
<p>How to use crystal Reports with ASP.Net 2.0. Any Samples/Tutorials/Examples which shows how to deploy Crystal Reports on a production Server.</p>
[ { "answer_id": 945720, "author": "SchwartzE", "author_id": 94382, "author_profile": "https://Stackoverflow.com/users/94382", "pm_score": 0, "selected": false, "text": "'Generate the Report\nDim oRpt As New ReportDocument\nDim reportPath As String = Server.MapPath(\"crtTAL.rpt\")\noRpt.Load(reportPath)\n\noRpt.SetDataSource(dsTAL)\n\nIf Not IO.Directory.Exists(tempLocation) Then\n IO.Directory.CreateDirectory(tempLocation)\nEnd If\n\nIf IO.File.Exists(tempLocation & filename) Then\n IO.File.Delete(tempLocation & filename)\nEnd If\n\n' ********************************\n\n' First we must create a new instance of the diskfiledestinationoptions class and\n' set variable called crExportOptions to the exportoptions class of the reportdocument.\nDim crDiskFileDestinationOptions As New DiskFileDestinationOptions\nDim crExportOptions As ExportOptions = oRpt.ExportOptions\n\n'Export to Word\n\n'append a filename to the export path and set this file as the filename property for\n'the DestinationOptions class\ncrDiskFileDestinationOptions.DiskFileName = tempLocation + filename\n\n'set the required report ExportOptions properties\nWith crExportOptions\n .DestinationOptions = crDiskFileDestinationOptions\n .ExportDestinationType = ExportDestinationType.DiskFile\n .ExportFormatType = ExportFormatType.WordForWindows\nEnd With\n\n'Once the export options have been set for the report, the report can be exported. The Export command\n'does not take any arguments\nTry\n ' Export the report\n oRpt.Export()\n oRpt.Close()\n oRpt.Dispose()\n projectCount = projectCount + 1\nCatch err As Exception\n Response.Write(\"<BR>\")\n Response.Write(err.Message.ToString)\n errorList = errorList & dtrProjects.Item(\"Title\") & \"; \"\nEnd Try\n" }, { "answer_id": 1234569, "author": "Developer", "author_id": 81250, "author_profile": "https://Stackoverflow.com/users/81250", "pm_score": 0, "selected": false, "text": "public partial class _Default : System.Web.UI.Page\n{\n protected void Page_Load(object sender, EventArgs e)\n {\n\n ///create instance of class first\n ReportDocument rpDoc = new ReportDocument();\n ///load the report\n rpDoc.Load(@\"TicketingBasic.rpt\");\n\n ///pass the report to method for dataInfo\n getDBInfo(rpDoc);\n /// et the source for report to be displayed\n CrystalReportViewer1.ReportSource = rpDoc;\n }\n\n protected static void getDBInfo(ReportDocument rpDoc)\n {\n ///Connection Onject\n ConnectionInfo cn = new ConnectionInfo();\n ///DataBase,Table, and Table Logon Info\n Database db;\n Tables tbl;\n TableLogOnInfo tblLOI;\n\n ///Connection Declaration\n cn.ServerName = \"??????\";\n cn.DatabaseName = \"???????\";\n cn.UserID = \"???????\";\n cn.Password = \"????????\";\n\n //table info getting from report\n db = rpDoc.Database;\n tbl = db.Tables;\n\n ///for each loop for all tables to be applied the connection info to\n foreach (Table table in tbl)\n {\n tblLOI = table.LogOnInfo;\n tblLOI.ConnectionInfo = cn;\n table.ApplyLogOnInfo(tblLOI);\n table.Location = \"DBO.\" + table.Location.Substring(table.Location.LastIndexOf(\".\") + 1);\n\n }\n\n db.Dispose();\n tbl.Dispose();\n }\n <CR:CrystalReportViewer \n ID=\"CrystalReportViewer1\" \n runat=\"server\" \n AutoDataBind=\"true\" \n EnableDatabaseLogonPrompt=\"false\"\n />\n" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370796", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
370,801
<p>When reading data from the Input file I noticed that the ¥ symbom was not being read by the StreamReader. Mozilla Firefox showed the input file type as Western (ISO-8859-1).</p> <p>After playing around with the encoding parameters I found it worked successfully for the following values:</p> <pre><code>System.Text.Encoding.GetEncoding(1252) // (western iso 88591) System.Text.Encoding.Default System.Text.Encoding.UTF7 </code></pre> <p>Now I am planning on using the "Default" setting, however I am not very sure if this is the right decision. The existing code did not use any encoding and I am worried I might break something.</p> <p>I know very little (OR rather nothing) about encoding. How do I go about this? Is my decision to use System.Text.Encoding.Default safe? Should I be asking the user to save the files in a particular format ?</p>
[ { "answer_id": 370811, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": true, "text": "Encoding.GetEncoding(28591) Encoding.Default" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370801", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41766/" ]
370,814
<p>I'm getting a NullPointerException in a Class from a 3rd party library. Now I'd like to debug the whole thing and I would need to know from which object the class is held. But it seems to me that I cannot set a breakpoint in a Class from a 3rd party. </p> <p>Does anyone know a way out of my trouble? Of course I'm using Eclipse as my IDE.</p> <p>Update: the library is open-source.</p>
[ { "answer_id": 370819, "author": "Joachim Sauer", "author_id": 40342, "author_profile": "https://Stackoverflow.com/users/40342", "pm_score": 6, "selected": false, "text": "Toggle Method Breakpoint" }, { "answer_id": 372620, "author": "Jared", "author_id": 44757, "author_profile": "https://Stackoverflow.com/users/44757", "pm_score": 6, "selected": true, "text": "lines,source,vars -g" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15108/" ]
370,817
<p>I've thrown myself headfirst into C# and .Net 2.0 using Linq, and I'm having a few problems debugging some of the problems, namely the following:</p> <p>I have a ComboBox control (<code>cmbObjects</code>) I want to populate with a set of objects retrieved using Linq. I've written a helper method to populate a <code>List&lt;T&gt;</code> generic:</p> <pre><code>class ObjectProvider { public static List&lt;T&gt; Get&lt;T&gt;(bool includeNull) where T : class, new() { List&lt;T&gt; list = new List&lt;T&gt;(); LutkeDataClassesDataContext db = ConnectionManager.GetConnection(); IQueryable&lt;T&gt; objects = db.GetTable&lt;T&gt;().AsQueryable(); if (includeNull) list.Add(null); foreach (T o in objects) list.Add(o); return list; } public static List&lt;T&gt; Get&lt;T&gt;() where T : class, new() { return Get&lt;T&gt;(false); } } </code></pre> <p>I verified the results when calling the function with true or false - the <code>List</code> does contain the right values, when passing <code>true</code>, it contains <code>null</code> as the first value, followed by the other objects.</p> <p>When I assign the <code>DataSource</code> to the <code>ComboBox</code> however, the control simply refuses to display any items, including the <code>null</code> value (not selectable):</p> <pre><code>cmbObjects.DataSource = ObjectProvider.Get&lt;Car&gt;(true); </code></pre> <p>Passing in <code>false</code> (or no parameter) does work - it displays all of the objects.</p> <p>Is there a way for me to specify a "null" value for the first object without resorting to magic number objects (like having a bogus entry in the DB just to designate a N/A value)? Something along the lines of a nullable would be ideal, but I'm kind of lost.</p> <p>Also, I've tried adding <code>new T()</code> instead of <code>null</code> to the list, but that only resulted in an <code>OutOfMemoryException</code>.</p>
[ { "answer_id": 374133, "author": "Klemen Slavič", "author_id": 46588, "author_profile": "https://Stackoverflow.com/users/46588", "pm_score": 1, "selected": true, "text": "DataSource null foreach List<>" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370817", "https://Stackoverflow.com", "https://Stackoverflow.com/users/46588/" ]
370,818
<p>I want to build an SQL string to do database manipulation (updates, deletes, inserts, selects, that sort of thing) - instead of the awful string concat method using millions of "+"'s and quotes which is unreadable at best - there must be a better way. </p> <p>I did think of using MessageFormat - but its supposed to be used for user messages, although I think it would do a reasonable job - but I guess there should be something more aligned to SQL type operations in the java sql libraries.</p> <p>Would Groovy be any good?</p>
[ { "answer_id": 370891, "author": "Piotr Kochański", "author_id": 34102, "author_profile": "https://Stackoverflow.com/users/34102", "pm_score": 7, "selected": true, "text": "PreparedStatement stm = c.prepareStatement(\"UPDATE user_table SET name=? WHERE id=?\");\nstm.setString(1, \"the name\");\nstm.setInt(2, 345);\nstm.executeUpdate();\n update_query=UPDATE user_table SET name=? WHERE id=?\n public class Queries {\n\n private static final String propFileName = \"queries.properties\";\n private static Properties props;\n\n public static Properties getQueries() throws SQLException {\n InputStream is = \n Queries.class.getResourceAsStream(\"/\" + propFileName);\n if (is == null){\n throw new SQLException(\"Unable to load property file: \" + propFileName);\n }\n //singleton\n if(props == null){\n props = new Properties();\n try {\n props.load(is);\n } catch (IOException e) {\n throw new SQLException(\"Unable to load property file: \" + propFileName + \"\\n\" + e.getMessage());\n } \n }\n return props;\n }\n\n public static String getQuery(String query) throws SQLException{\n return getQueries().getProperty(query);\n }\n\n}\n PreparedStatement stm = c.prepareStatement(Queries.getQuery(\"update_query\"));\n" }, { "answer_id": 370939, "author": "Bent André Solheim", "author_id": 44380, "author_profile": "https://Stackoverflow.com/users/44380", "pm_score": 3, "selected": false, "text": "int countOfActorsNamedJoe\n = jdbcTemplate.queryForInt(\"select count(0) from t_actors where first_name = ?\", new Object[]{\"Joe\"});\n" }, { "answer_id": 370947, "author": "Ashley Mercer", "author_id": 13065, "author_profile": "https://Stackoverflow.com/users/13065", "pm_score": 4, "selected": false, "text": "public class TestQueries\n{\n public String getUsername(int id)\n {\n String username;\n #sql\n {\n select username into :username\n from users\n where pkey = :id\n };\n return username;\n }\n}\n #sql\n{\n ...\n}\n" }, { "answer_id": 502273, "author": "Natalia", "author_id": 11067, "author_profile": "https://Stackoverflow.com/users/11067", "pm_score": 3, "selected": false, "text": "select app.name as \"App\", \n ${optional(\" app.owner as \"Owner\", \"):showOwner}\n sv.name as \"Server\", sum(act.trans_ct) as \"Trans\"\n from activity_records act, servers sv, applications app\n where act.server_id = sv.id\n and act.app_id = app.id\n and sv.id = ${integer(0,50):serverId}\n and app.id in ${integerList(50):appId}\n group by app.name, ${optional(\" app.owner, \"):showOwner} sv.name\n order by app.name, sv.name\n showOwner: true\nserverId: 20\nappId: 1,2,3,5,7,11,13\n select app.name as \"App\", \n app.owner as \"Owner\", \n sv.name as \"Server\", sum(act.trans_ct) as \"Trans\"\n from activity_records act, servers sv, applications app\n where act.server_id = sv.id\n and act.app_id = app.id\n and sv.id = 20\n and app.id in (1,2,3,5,7,11,13)\n group by app.name, app.owner, sv.name\n order by app.name, sv.name\n" }, { "answer_id": 6992265, "author": "Lukas Eder", "author_id": 521799, "author_profile": "https://Stackoverflow.com/users/521799", "pm_score": 6, "selected": false, "text": "SELECT INSERT UPDATE DELETE TRUNCATE MERGE String sql1 = DSL.using(SQLDialect.MYSQL) \n .select(A, B, C)\n .from(MY_TABLE)\n .where(A.equal(5))\n .and(B.greaterThan(8))\n .getSQL();\n\nString sql2 = DSL.using(SQLDialect.MYSQL) \n .insertInto(MY_TABLE)\n .values(A, 1)\n .values(B, 2)\n .getSQL();\n\nString sql3 = DSL.using(SQLDialect.MYSQL) \n .update(MY_TABLE)\n .set(A, 1)\n .set(B, 2)\n .where(C.greaterThan(5))\n .getSQL();\n" }, { "answer_id": 46627704, "author": "CasualCoder3", "author_id": 4047298, "author_profile": "https://Stackoverflow.com/users/4047298", "pm_score": 2, "selected": false, "text": "@Dao\npublic interface UserDao {\n @Query(\"SELECT * FROM user\")\n List<User> getAll();\n\n @Query(\"SELECT * FROM user WHERE uid IN (:userIds)\")\n List<User> loadAllByIds(int[] userIds);\n\n @Query(\"SELECT * FROM user WHERE first_name LIKE :first AND \"\n + \"last_name LIKE :last LIMIT 1\")\n User findByName(String first, String last);\n\n @Insert\n void insertAll(User... users);\n\n @Delete\n void delete(User user);\n}\n" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5175/" ]
370,820
<p>I have a CheckedListBox, and I want to automatically tick one of the items in it.</p> <p>The <code>CheckedItems</code> collection doesn't allow you to add things to it.</p> <p>Any suggestions?</p>
[ { "answer_id": 370828, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 7, "selected": true, "text": "SetItemChecked CheckedListBox.ObjectCollection" }, { "answer_id": 11567074, "author": "B. Clay Shannon-B. Crow Raven", "author_id": 875317, "author_profile": "https://Stackoverflow.com/users/875317", "pm_score": 5, "selected": false, "text": "private void SelectAllCheckBoxes(bool CheckThem) {\n for (int i = 0; i <= (checkedListBox1.Items.Count - 1); i++) {\n if (CheckThem)\n {\n checkedListBox1.SetItemCheckState(i, CheckState.Checked);\n }\n else\n {\n checkedListBox1.SetItemCheckState(i, CheckState.Unchecked);\n }\n } \n}\n" }, { "answer_id": 28132268, "author": "ePandit", "author_id": 676779, "author_profile": "https://Stackoverflow.com/users/676779", "pm_score": 3, "selected": false, "text": "private void button1_Click(object sender, EventArgs e)\n{\n checkedListBox1.SetItemChecked(itemIndex, true);\n}\n" }, { "answer_id": 28492180, "author": "Adiii", "author_id": 3288890, "author_profile": "https://Stackoverflow.com/users/3288890", "pm_score": 2, "selected": false, "text": "string[] aa = new string[] {\"adiii\", \"yaseen\", \"salman\"};\nforeach (string a in aa)\n{\n checkedListBox1.Items.Add(a);\n}\n private void button5_Click(object sender, EventArgs e)\n{\n for(int a=0; a<checkedListBox1.Items.Count; a++)\n checkedListBox1.SetItemChecked(a, true);\n}\n private void button_Click(object sender, EventArgs e)\n{\n for(int a=0; a<checkedListBox1.Items.Count; a++)\n checkedListBox1.SetItemChecked(a, false);\n}\n" }, { "answer_id": 33903221, "author": "ondrej5834", "author_id": 5601358, "author_profile": "https://Stackoverflow.com/users/5601358", "pm_score": 3, "selected": false, "text": "CheckedListBox.SetItemChecked(CheckedListBox.Items.IndexOf(Item),true);\n string[] ProgramNames = sel_item.SubItems[2].Text.Split(';');\nforeach (string Program in ProgramNames)\n{\n if (edit_mux.CLB_ContainedPrograms.Items.Contains(Program))\n edit_mux.CLB_ContainedPrograms.SetItemChecked(edit_mux.CLB_ContainedPrograms.Items.IndexOf(Program), true);\n}\n" }, { "answer_id": 45727908, "author": "Konstantin Samsonov", "author_id": 6930348, "author_profile": "https://Stackoverflow.com/users/6930348", "pm_score": 2, "selected": false, "text": "public static class CheckedListBoxExtension\n{\n public static void CheckAll(this CheckedListBox listbox)\n {\n Check(listbox, true);\n }\n\n public static void UncheckAll(this CheckedListBox listbox)\n {\n Check(listbox, false);\n }\n\n private static void Check(this CheckedListBox listbox, bool check)\n {\n Enumerable.Range(0, listbox.Items.Count).ToList().ForEach(x => listbox.SetItemChecked(x, check));\n }\n}\n" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26874/" ]
370,831
<p>I have an SVN repository and I need the commits to fail if no description is entered. Is this possible to do, preferably server-side? (The users use several different tools for interacting with the repository; although if this were possible client-side in TortoiseSVN, that would alleviate the problem)</p> <p>Google has not been very helpful, can you give me some pointers?</p> <p>Thanks.</p>
[ { "answer_id": 370842, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 4, "selected": true, "text": "pre-commit.tmpl pre-commit.tmpl pre-commit" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19746/" ]
370,839
<p>I'm using Linq To Sql to fill up a listbox with Segment objects, where Segment is designer created/ORM generated class.</p> <pre><code>&lt;Window x:Class="ICTemplates.Window1" ... xmlns:local="clr-namespace:ICTemplates" Title="Window1" Height="300" Width="300"&gt; &lt;Window.Resources&gt; &lt;DataTemplate x:Key="MyTemplate"&gt; &lt;!-- &lt;DataTemplate DataType="x:Type local:Segment"&gt; --&gt; // some stuff in here &lt;/DataTemplate&gt; &lt;/Window.Resources&gt; &lt;ListView x:Name="tvwSegments" ItemsSource="{Binding}" ItemTemplate="{StaticResource MyTemplate}" MaxHeight="200"/&gt; // code-behind var queryResults = from segment in tblSegments where segment.id &lt;= iTemplateSid select segment; tvwSegments.DataContext = queryResults; </code></pre> <p>This works.</p> <p>However if I used a Typed Data Template (by replacing the x:Key with the DataType attribute on the template, the items all show up with <code>ICTemplates.Segment</code> (the ToString() return value)<br> The concept is that it should pick up the data template automatically if the Type matches. Can someone spot the mistake here?</p>
[ { "answer_id": 372014, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 6, "selected": true, "text": "<DataTemplate DataType=\"x:Type local:Segment\"> <!-- doesn't work -->\n <DataTemplate DataType=\"{x:Type local:Segment}\">\n <DataTemplate x:Key=\"SegTemplate\" DataType=\"{x:Type local:Segment}\"> <!-- doesn't work -->\n <DataTemplate DataType=\"{x:Type local:Segment}\">\n" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1695/" ]
370,840
<p>Silly question, but I'm unable to figure out..</p> <p>I tried the following in Ruby:</p> <pre><code>irb(main):020:0&gt; JSON.load('[1,2,3]').class =&gt; Array </code></pre> <p>This seems to work. While neither</p> <pre><code>JSON.load('1').class </code></pre> <p>nor this </p> <pre><code>JSON.load('{1}').class </code></pre> <p>works. Any ideas?</p>
[ { "answer_id": 370853, "author": "a2800276", "author_id": 27408, "author_profile": "https://Stackoverflow.com/users/27408", "pm_score": 2, "selected": false, "text": ">> JSON.parse(1.to_json)\nJSON::ParserError: A JSON text must at least contain two octets!\n from /opt/local/lib/ruby/gems/1.8/gems/json-1.1.3/lib/json/common.rb:122:in `initialize'\n from /opt/local/lib/ruby/gems/1.8/gems/json-1.1.3/lib/json/common.rb:122:in `new'\n from /opt/local/lib/ruby/gems/1.8/gems/json-1.1.3/lib/json/common.rb:122:in `parse'\n from (irb):7\n" }, { "answer_id": 370894, "author": "a2800276", "author_id": 27408, "author_profile": "https://Stackoverflow.com/users/27408", "pm_score": 4, "selected": true, "text": "1 {1} 1 {\"number\" : 1} a != JSON.parse(JSON.generate(a))\n" }, { "answer_id": 3083181, "author": "Peder", "author_id": 216015, "author_profile": "https://Stackoverflow.com/users/216015", "pm_score": 0, "selected": false, "text": "def set( value ); @data = [value].to_json; end\ndef get; JSON.parse( @data )[0]; end\n" }, { "answer_id": 37211165, "author": "glasz", "author_id": 683728, "author_profile": "https://Stackoverflow.com/users/683728", "pm_score": 2, "selected": false, "text": "var json_string = \"1\";\nvar p = eval('(' + json_string + ')');\nconsole.log(p);\n// => 1\ntypeof p\n// => \"number\"\n ActiveSupport::JSON require 'active_support/json'\np = ActiveSupport::JSON.decode '1'\n# => 1\np.class\n# => Fixnum\n require 'multi_json'\np = MultiJson.load '1'\n# => 1\np.class\n# => Fixnum\n quirks_mode load require 'json'\np = JSON.load '1'\n# => 1\np.class\n# => Fixnum\n" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370840", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44232/" ]
370,850
<p>I have a PHP file, Test.php, and it has two functions:</p> <pre><code>&lt;?php echo displayInfo(); echo displayDetails(); ?&gt; </code></pre> <p>JavaScript:</p> <pre><code>&lt;html&gt; ... &lt;script type="text/javascript"&gt; $.ajax({ type:'POST', url: 'display.php', data:'id='+id , success: function(data){ $("#response").html(data); } }); &lt;/script&gt; ... &lt;div id="response"&gt; &lt;/div&gt; &lt;/html&gt; </code></pre> <p>It returns the response from jQuery. The response shows as <code>&lt;a href=Another.php?&gt;Link&lt;/a&gt;</code>. When I click the Another.php link in <code>test.php</code>, it loads in another window. But I need it to load the same <code>&lt;div&gt; &lt;/div&gt;</code> area without changing the content of <code>test.php</code>, since it has <code>displayInfo(), displayDetails()</code>. Or is it possible to load a PHP page inside <code>&lt;div&gt; &lt;/div&gt;</code> elements?</p> <p>How can I tackle this problem?</p>
[ { "answer_id": 370882, "author": "Klemen Slavič", "author_id": 46588, "author_profile": "https://Stackoverflow.com/users/46588", "pm_score": 4, "selected": true, "text": "a $(\"#mylink\").click(function() {\n $.ajax({ type: \"POST\", url: \"another.php\", data: {id: \"somedata\"}, function(data) {\n $(\"#response\").html(data);\n });\n return false;\n});\n" }, { "answer_id": 372882, "author": "gradbot", "author_id": 17919, "author_profile": "https://Stackoverflow.com/users/17919", "pm_score": 0, "selected": false, "text": "$(\"#mylink\").one('click', function() {\n // ajax call\n return false;\n});\n" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44984/" ]
370,852
<p>Anytime I have to handle dates/times in java it makes me sad </p> <p>I'm trying to parse a string and turn it into a date object to insert in a preparepared statement. I've been trying to get this working but am having no luck. I also get the helpful error message when I go to compile the class.</p> <p>"Exception in thread "main" java.lang.Error: Unresolved compilation problem: The method setDate(int, Date) in the type PreparedStatement is not applicable for the arguments (int, Date)"</p> <p>Eh WTF?</p> <p>Here is the offending code.</p> <pre><code>for(int i = 0; i &lt; flights.size(); i++){ String[] details = flight[i].toString().split(":"); DateFormat formatter ; formatter = new SimpleDateFormat("ddMMyyyy"); Date date = formatter.parse(details[1]); PreparedStatement pstmt = conn.prepareStatement(insertsql); pstmt.setString(1, details[0]); pstmt.setDate(2, date); pstmt.setString(3, details[2] + "00"); pstmt.setString(4, details[3]); pstmt.setString(5, details[4]); pstmt.setString(6, details[5]); pstmt.setString(7, details[6]); pstmt.setString(8, details[7]); pstmt.setString(9, details[8]); pstmt.executeUpdate(); } </code></pre>
[ { "answer_id": 1336222, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "import java.sql.Date;\nimport java.sql.Time;\n\n statement.setDate(4, Date.valueOf(\"2009-08-26\"));\n statement.setTime(5, Time.valueOf(\"12:04:08\"));\n" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370852", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
370,859
<p>The question is in the title, why :</p> <pre><code>return double.IsNaN(0.6d) &amp;&amp; double.IsNaN(x); </code></pre> <p>Instead of</p> <pre><code>return (0.6d).IsNaN &amp;&amp; x.IsNaN; </code></pre> <p>I ask because when implementing custom structs that have a special value with the same meaning as NaN I tend to prefer the second.</p> <p>Additionally the performance of the property is normally better as it avoid copying the struct on the stack to call the IsNaN static method (And as my property isn't virtual there is no risk of auto-boxing). Granted it isn't really an issue for built-in types as the JIT could optimize this easilly.</p> <p>My best guess for now is that as you can't have both the property and the static method with the same name in the double class they favored the java-inspired syntax. (In fact you could have both as one define a get_IsNaN property getter and the other an IsNaN static method but it will be confusing in any .Net language supporting the property syntax)</p>
[ { "answer_id": 370873, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 4, "selected": true, "text": "static bool IsNaN(this double value)\n{\n return double.IsNaN(value);\n}\n\nstatic void Main()\n{\n double x = 123.4;\n bool isNan = x.IsNaN();\n}\n callvirt call" }, { "answer_id": 370951, "author": "Ruben Bartelink", "author_id": 11635, "author_profile": "https://Stackoverflow.com/users/11635", "pm_score": 0, "selected": false, "text": "static static" }, { "answer_id": 370996, "author": "Pop Catalin", "author_id": 4685, "author_profile": "https://Stackoverflow.com/users/4685", "pm_score": 4, "selected": false, "text": "using System;\nusing System.Threading;\n\nnamespace CA64213434234\n{\n class Program \n {\n static void Main(string[] args)\n {\n ManualResetEvent ev = new ManualResetEvent(false);\n Foo bar = new Foo(0);\n Action a = () => bar.Display(ev);\n IAsyncResult ar = a.BeginInvoke(null, null);\n ev.WaitOne();\n bar = new Foo(5);\n ar.AsyncWaitHandle.WaitOne();\n }\n }\n\n public struct Foo\n {\n private readonly int val;\n public Foo(int value)\n {\n val = value;\n }\n public void Display(ManualResetEvent ev)\n {\n Console.WriteLine(val);\n ev.Set();\n Thread.Sleep(2000);\n Console.WriteLine(val);\n }\n }\n}\n" }, { "answer_id": 372821, "author": "Julien Roncaglia", "author_id": 46594, "author_profile": "https://Stackoverflow.com/users/46594", "pm_score": 2, "selected": false, "text": "using System;\nusing System.Threading;\nusing System.Diagnostics;\n\nnamespace ThreadTest\n{\n class Program\n {\n struct SmallMatrix\n {\n double m_a, m_b, m_c, m_d;\n\n public SmallMatrix(double x)\n {\n m_a = x;\n m_b = x;\n m_c = x;\n m_d = x;\n }\n\n public static bool SameValueEverywhere(SmallMatrix m)\n {\n return (m.m_a == m.m_b)\n && (m.m_a == m.m_c)\n && (m.m_a == m.m_d);\n }\n }\n\n static SmallMatrix s_smallMatrix;\n\n static void Watcher()\n {\n while (true)\n Debug.Assert(SmallMatrix.SameValueEverywhere(s_smallMatrix));\n }\n\n static void Main(string[] args)\n {\n (new Thread(Watcher)).Start();\n while (true)\n {\n s_smallMatrix = new SmallMatrix(0);\n s_smallMatrix = new SmallMatrix(1);\n }\n }\n }\n}\n movl someVar print(\"code sample\");\nif (!double.IsNaN(someVar))\n Console.WriteLine(someVar);\n ==" } ]
2008/12/16
[ "https://Stackoverflow.com/questions/370859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/46594/" ]