qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
150,114
<p>I know plenty about the different ways of handling parsing text for information. For parsing integers for example, what kind of performance can be expected. I am wondering if anyone knows of any good stats on this. I am looking for some real numbers from someone who has tested this.</p> <p>Which of these offers the best performance in which situations?</p> <pre><code>Parse(...) // Crash if the case is extremely rare .0001% If (SomethingIsValid) // Check the value before parsing Parse(...) TryParse(...) // Using TryParse try { Parse(...) } catch { // Catch any thrown exceptions } </code></pre>
[ { "answer_id": 150123, "author": "user7116", "author_id": 7116, "author_profile": "https://Stackoverflow.com/users/7116", "pm_score": 7, "selected": true, "text": "Failure Rate Try-Catch TryParse Slowdown\n 0% 00:00:00.0131758 00:00:00.0120421 0.1\n 10% 00:00:00.1540251 00:00:00.0087699 16.6\n 20% 00:00:00.2833266 00:00:00.0105229 25.9\n 30% 00:00:00.4462866 00:00:00.0091487 47.8\n 40% 00:00:00.6951060 00:00:00.0108980 62.8\n 50% 00:00:00.7567745 00:00:00.0087065 85.9\n 60% 00:00:00.7090449 00:00:00.0083365 84.1\n 70% 00:00:00.8179365 00:00:00.0088809 91.1\n 80% 00:00:00.9468898 00:00:00.0088562 105.9\n 90% 00:00:01.0411393 00:00:00.0081040 127.5\n100% 00:00:01.1488157 00:00:00.0078877 144.6\n\n\n/// <param name=\"errorRate\">Rate of errors in user input</param>\n/// <returns>Total time taken</returns>\npublic static TimeSpan TimeTryCatch(double errorRate, int seed, int count)\n{\n Stopwatch stopwatch = new Stopwatch();\n Random random = new Random(seed);\n string bad_prefix = @\"X\";\n\n stopwatch.Start();\n for(int ii = 0; ii < count; ++ii)\n {\n string input = random.Next().ToString();\n if (random.NextDouble() < errorRate)\n {\n input = bad_prefix + input;\n }\n\n int value = 0;\n try\n {\n value = Int32.Parse(input);\n }\n catch(FormatException)\n {\n value = -1; // we would do something here with a logger perhaps\n }\n }\n stopwatch.Stop();\n\n return stopwatch.Elapsed;\n}\n\n/// <param name=\"errorRate\">Rate of errors in user input</param>\n/// <returns>Total time taken</returns>\npublic static TimeSpan TimeTryParse(double errorRate, int seed, int count)\n{\n Stopwatch stopwatch = new Stopwatch();\n Random random = new Random(seed);\n string bad_prefix = @\"X\";\n\n stopwatch.Start();\n for(int ii = 0; ii < count; ++ii)\n {\n string input = random.Next().ToString();\n if (random.NextDouble() < errorRate)\n {\n input = bad_prefix + input;\n }\n\n int value = 0;\n if (!Int32.TryParse(input, out value))\n {\n value = -1; // we would do something here with a logger perhaps\n }\n }\n stopwatch.Stop();\n\n return stopwatch.Elapsed;\n}\n\npublic static void TimeStringParse()\n{\n double errorRate = 0.1; // 10% of the time our users mess up\n int count = 10000; // 10000 entries by a user\n\n TimeSpan trycatch = TimeTryCatch(errorRate, 1, count);\n TimeSpan tryparse = TimeTryParse(errorRate, 1, count);\n\n Console.WriteLine(\"trycatch: {0}\", trycatch);\n Console.WriteLine(\"tryparse: {0}\", tryparse);\n}\n" }, { "answer_id": 150139, "author": "Chris Cudmore", "author_id": 18907, "author_profile": "https://Stackoverflow.com/users/18907", "pm_score": -1, "selected": false, "text": "Option 1: Will throw an exception on bad data.\nOption 2: SomethingIsValid() could be quite expensive - particularly if you are pre-checking a string for Integer parsability.\nOption 3: I like this. You need a null check afterwards, but it's pretty cheap.\nOption 4 is definitely the worst.\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22381/" ]
150,129
<p>Could someone provide a good description of what a Lambda is? We have a tag for them and they're on the secrets of C# question, but I have yet to find a good definition and explanation of what they are in the first place.</p>
[ { "answer_id": 150155, "author": "rfunduk", "author_id": 210, "author_profile": "https://Stackoverflow.com/users/210", "pm_score": 3, "selected": false, "text": "f = lambda { return \"this is a function with no name\" }\nputs f.call\n" }, { "answer_id": 7089352, "author": "cmeub", "author_id": 504032, "author_profile": "https://Stackoverflow.com/users/504032", "pm_score": 2, "selected": false, "text": "x = lambda(){ return \"Hello World\"; }\n\ndoit( 1, 2, lambda(a,b){ return a > b; }, 3 )\n\nx = (lambda(a){ return a+1; }) + 5 // type error, not syntax error\n\n(lambda(a,b){ print(a); log(b); })( 1, 2 ) // () is valid operator here\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150129", "https://Stackoverflow.com", "https://Stackoverflow.com/users/177/" ]
150,150
<p>I have a defined MenuItem that I would like to share between two different menus on one page. The menu contains functionallity that is the same between both menus and I do not want two copies of it. Is there anyway to define a MenuItem in the Page.Resources and reference it in the ContextMenu XAML below?</p> <pre><code>&lt;Page.Resources&gt; &lt;MenuItem x:Key="123"/&gt; &lt;/Page.Resources&gt; &lt;ContextMenu&gt; &lt;MenuItem&gt;Something hardcoded&lt;/MenuItem&gt; &lt;!-- include shared menu here --&gt; &lt;/ContextMenu&gt; </code></pre>
[ { "answer_id": 150706, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 4, "selected": true, "text": "<MenuItem x:Key=\"myMenuItem\" x:Shared=\"False\" />\n <StaticResource ResourceKey=\"myMenuItem\" />\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1514/" ]
150,153
<p>Using NHibernate ICriteria and adding .AddOrder ... I want to sort by a property that is sometimes null with all the populated ones at the top. Will .AddOrder allow me to do this? If not is there an alternative? </p> <p>The sorting options for ILists leave a lot to be desired. </p>
[ { "answer_id": 150168, "author": "wprl", "author_id": 17847, "author_profile": "https://Stackoverflow.com/users/17847", "pm_score": 3, "selected": false, "text": "IList cats = sess.CreateCriteria(typeof(Cat))\n .AddOrder( Order.Desc(\"PropertyName\") )\n .List();\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150153", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4140/" ]
150,161
<p>I have searched but apparently my google foo is weak. What I need is a way to prompt for user input in the console and have the request time out after a period of time and continue executing the script if no input comes in. As near as I can tell, Read-Host does not provide this functionality. Neither does $host.UI.PromptForChoice() nor does $host.UI.RawUI.ReadKey(). Thanks in advance for any pointers.</p> <p>EDIT: Much thanks to Lars Truijens for finding the answer. I have taken the code that he pointed out and encapsulated it into a function. Note that the way that I have implemented it means there could be up to one second of delay between when the user hits a key and when script execution continues.</p> <pre><code>function Pause-Host { param( $Delay = 1 ) $counter = 0; While(!$host.UI.RawUI.KeyAvailable -and ($counter++ -lt $Delay)) { [Threading.Thread]::Sleep(1000) } } </code></pre>
[ { "answer_id": 150326, "author": "Lars Truijens", "author_id": 1242, "author_profile": "https://Stackoverflow.com/users/1242", "pm_score": 5, "selected": true, "text": "$counter = 0\nwhile(!$Host.UI.RawUI.KeyAvailable -and ($counter++ -lt 600))\n{\n [Threading.Thread]::Sleep( 1000 )\n}\n" }, { "answer_id": 29343310, "author": "nathanchere", "author_id": 243557, "author_profile": "https://Stackoverflow.com/users/243557", "pm_score": 3, "selected": false, "text": ". $true $false Function TimedPrompt($prompt,$secondsToWait){ \n Write-Host -NoNewline $prompt\n $secondsCounter = 0\n $subCounter = 0\n While ( (!$host.ui.rawui.KeyAvailable) -and ($count -lt $secondsToWait) ){\n start-sleep -m 10\n $subCounter = $subCounter + 10\n if($subCounter -eq 1000)\n {\n $secondsCounter++\n $subCounter = 0\n Write-Host -NoNewline \".\"\n } \n If ($secondsCounter -eq $secondsToWait) { \n Write-Host \"`r`n\"\n return $false;\n }\n }\n Write-Host \"`r`n\"\n return $true;\n}\n $val = TimedPrompt \"Press key to cancel restore; will begin in 3 seconds\" 3\nWrite-Host $val\n" }, { "answer_id": 50274450, "author": "Elavarasan Muthuvalavan - Lee", "author_id": 1621781, "author_profile": "https://Stackoverflow.com/users/1621781", "pm_score": 2, "selected": false, "text": "Write-Host (\"PowerShell Script to run a loop and exit on pressing 'q'!\")\n$count=0\n$sleepTimer=500 #in milliseconds\n$QuitKey=81 #Character code for 'q' key.\nwhile($count -le 100)\n{\n if($host.UI.RawUI.KeyAvailable) {\n $key = $host.ui.RawUI.ReadKey(\"NoEcho,IncludeKeyUp\")\n if($key.VirtualKeyCode -eq $QuitKey) {\n #For Key Combination: eg., press 'LeftCtrl + q' to quit.\n #Use condition: (($key.VirtualKeyCode -eq $Qkey) -and ($key.ControlKeyState -match \"LeftCtrlPressed\"))\n Write-Host -ForegroundColor Yellow (\"'q' is pressed! Stopping the script now.\")\n break\n }\n }\n #Do your operations\n $count++\n Write-Host (\"Count Incremented to - {0}\" -f $count)\n Write-Host (\"Press 'q' to stop the script!\")\n Start-Sleep -m $sleepTimer\n}\nWrite-Host -ForegroundColor Green (\"The script has stopped.\")\n" }, { "answer_id": 52546471, "author": "crokusek", "author_id": 538763, "author_profile": "https://Stackoverflow.com/users/538763", "pm_score": 2, "selected": false, "text": "$key = GetKeyPress '[ynq]' \"Run step X ([y]/n/q)?\" 5\n\nif ($key -eq $null)\n{\n Write-Host \"No key was pressed.\";\n}\nelse\n{\n Write-Host \"The key was '$($key)'.\"\n}\n Function GetKeyPress([string]$regexPattern='[ynq]', [string]$message=$null, [int]$timeOutSeconds=0)\n{\n $key = $null\n\n $Host.UI.RawUI.FlushInputBuffer() \n\n if (![string]::IsNullOrEmpty($message))\n {\n Write-Host -NoNewLine $message\n }\n\n $counter = $timeOutSeconds * 1000 / 250\n while($key -eq $null -and ($timeOutSeconds -eq 0 -or $counter-- -gt 0))\n {\n if (($timeOutSeconds -eq 0) -or $Host.UI.RawUI.KeyAvailable)\n { \n $key_ = $host.UI.RawUI.ReadKey(\"NoEcho,IncludeKeyDown,IncludeKeyUp\")\n if ($key_.KeyDown -and $key_.Character -match $regexPattern)\n {\n $key = $key_ \n }\n }\n else\n {\n Start-Sleep -m 250 # Milliseconds\n }\n } \n\n if (-not ($key -eq $null))\n {\n Write-Host -NoNewLine \"$($key.Character)\" \n }\n\n if (![string]::IsNullOrEmpty($message))\n {\n Write-Host \"\" # newline\n } \n\n return $(if ($key -eq $null) {$null} else {$key.Character})\n}\n" }, { "answer_id": 66668858, "author": "user15413294", "author_id": 15413294, "author_profile": "https://Stackoverflow.com/users/15413294", "pm_score": 0, "selected": false, "text": "function ReadKeyWithDefault($prompt, $defaultKey, [int]$timeoutInSecond = 5 ) {\n $counter = $timeoutInSecond * 10\n do{\n $remainingSeconds = [math]::floor($counter / 10)\n Write-Host \"`r$prompt (default $defaultKey in $remainingSeconds seconds): \" -NoNewline\n if($Host.UI.RawUI.KeyAvailable){\n $key = $host.UI.RawUI.ReadKey(\"IncludeKeyUp\")\n Write-Host \n return $key\n }\n Start-Sleep -Milliseconds 100\n }while($counter-- -gt 0)\n\n Write-Host $defaultKey\n return $defaultKey\n}\n\n$readKey = ReadKeyWithDefault \"If error auto exit( y/n )\" 'y' 5\n" }, { "answer_id": 68421194, "author": "john v kumpf", "author_id": 4582204, "author_profile": "https://Stackoverflow.com/users/4582204", "pm_score": 1, "selected": false, "text": "timeout.exe 5\n if ($psISE) {\n start -Wait timeout.exe 5\n} else {\n timeout.exe 5\n}\n" }, { "answer_id": 69072089, "author": "Alex from Jitbit", "author_id": 56621, "author_profile": "https://Stackoverflow.com/users/56621", "pm_score": 1, "selected": false, "text": "choice Choice /C yn /D n /t 5 /m \"Are you sure? You have 5 seconds to decide\"\nif ($LASTEXITCODE -eq \"1\") # 1 for \"yes\" 2 for \"no\"\n{\n # do stuff\n}\nelse\n{\n # don't do stuff\n}\n #" }, { "answer_id": 72987575, "author": "Pavman", "author_id": 5633445, "author_profile": "https://Stackoverflow.com/users/5633445", "pm_score": 0, "selected": false, "text": "if ([Console]::KeyAvailable) { $pressedKey = [Console]::ReadKey($true); read-host; break; }\n elseif ($secondsCounter -gt $secondsToWait) { \n Write-Host \"`r`n\"\n return $false;\n }\n" }, { "answer_id": 73733859, "author": "Araminty Whitesell", "author_id": 12313985, "author_profile": "https://Stackoverflow.com/users/12313985", "pm_score": 0, "selected": false, "text": "function keypress_wait {\n param (\n [int]$seconds = 10\n )\n $loops = $seconds*10\n Write-Host \"Press any key within $seconds seconds to continue\"\n for ($i = 0; $i -le $loops; $i++){\n if ([Console]::KeyAvailable) { break; }\n Start-Sleep -Milliseconds 100\n }\nif ([Console]::KeyAvailable) { return [Console]::ReadKey($true); }\nelse { return $null ;}\n}\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150161", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1358/" ]
150,167
<p>How do I list and export a private key from a keystore?</p>
[ { "answer_id": 150181, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": 6, "selected": true, "text": " // Load input stream into keystore\n keystore.load(is, password.toCharArray());\n\n // List the aliases\n Enumeration aliases = keystore.aliases();\n for (; aliases.hasMoreElements(); ) {\n String alias = (String)aliases.nextElement();\n\n // Does alias refer to a private key?\n boolean b = keystore.isKeyEntry(alias);\n\n // Does alias refer to a trusted certificate?\n b = keystore.isCertificateEntry(alias);\n }\n import java.io.FileInputStream;\nimport java.security.Key;\nimport java.security.KeyStore;\nimport sun.misc.BASE64Encoder;\n\npublic class DumpPrivateKey {\n /**\n * Provides the missing functionality of keytool\n * that Apache needs for SSLCertificateKeyFile.\n *\n * @param args <ul>\n * <li> [0] Keystore filename.\n * <li> [1] Keystore password.\n * <li> [2] alias\n * </ul>\n */\n static public void main(String[] args)\n throws Exception {\n if(args.length < 3) {\n throw new IllegalArgumentException(\"expected args: Keystore filename, Keystore password, alias, <key password: default same tha\nn keystore\");\n }\n final String keystoreName = args[0];\n final String keystorePassword = args[1];\n final String alias = args[2];\n final String keyPassword = getKeyPassword(args,keystorePassword);\n KeyStore ks = KeyStore.getInstance(\"jks\");\n ks.load(new FileInputStream(keystoreName), keystorePassword.toCharArray());\n Key key = ks.getKey(alias, keyPassword.toCharArray());\n String b64 = new BASE64Encoder().encode(key.getEncoded());\n System.out.println(\"-----BEGIN PRIVATE KEY-----\");\n System.out.println(b64);\n System.out.println(\"-----END PRIVATE KEY-----\");\n }\n private static String getKeyPassword(final String[] args, final String keystorePassword)\n {\n String keyPassword = keystorePassword; // default case\n if(args.length == 4) {\n keyPassword = args[3];\n }\n return keyPassword;\n }\n}\n javac -classpath .:commons-codec-1.4/commons-codec-1.4.jar DumpPrivateKey.java\n import java.io.FileInputStream;\nimport java.security.Key;\nimport java.security.KeyStore;\n//import sun.misc.BASE64Encoder;\nimport org.apache.commons.codec.binary.Base64;\n\npublic class DumpPrivateKey {\n /**\n * Provides the missing functionality of keytool\n * that Apache needs for SSLCertificateKeyFile.\n *\n * @param args <ul>\n * <li> [0] Keystore filename.\n * <li> [1] Keystore password.\n * <li> [2] alias\n * </ul>\n */\n static public void main(String[] args)\n throws Exception {\n if(args.length < 3) {\n throw new IllegalArgumentException(\"expected args: Keystore filename, Keystore password, alias, <key password: default same tha\nn keystore\");\n }\n final String keystoreName = args[0];\n final String keystorePassword = args[1];\n final String alias = args[2];\n final String keyPassword = getKeyPassword(args,keystorePassword);\n KeyStore ks = KeyStore.getInstance(\"jks\");\n ks.load(new FileInputStream(keystoreName), keystorePassword.toCharArray());\n Key key = ks.getKey(alias, keyPassword.toCharArray());\n //String b64 = new BASE64Encoder().encode(key.getEncoded());\n String b64 = new String(Base64.encodeBase64(key.getEncoded(),true));\n System.out.println(\"-----BEGIN PRIVATE KEY-----\");\n System.out.println(b64);\n System.out.println(\"-----END PRIVATE KEY-----\");\n }\n private static String getKeyPassword(final String[] args, final String keystorePassword)\n {\n String keyPassword = keystorePassword; // default case\n if(args.length == 4) {\n keyPassword = args[3];\n }\n return keyPassword;\n }\n}\n java -classpath .:commons-codec-1.4/commons-codec-1.4.jar DumpPrivateKey $HOME/.keystore changeit tomcat\n" }, { "answer_id": 150195, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 2, "selected": false, "text": "-nocrypt KeyStore keys = ...\nchar[] password = ...\nEnumeration<String> aliases = keys.aliases();\nwhile (aliases.hasMoreElements()) {\n String alias = aliases.nextElement();\n if (!keys.isKeyEntry(alias))\n continue;\n Key key = keys.getKey(alias, password);\n if ((key instanceof PrivateKey) && \"PKCS#8\".equals(key.getFormat())) {\n /* Most PrivateKeys use this format, but check for safety. */\n try (FileOutputStream os = new FileOutputStream(alias + \".key\")) {\n os.write(key.getEncoded());\n os.flush();\n }\n }\n}\n" }, { "answer_id": 5596842, "author": "Donal Fellows", "author_id": 301832, "author_profile": "https://Stackoverflow.com/users/301832", "pm_score": 7, "selected": false, "text": "keytool keytool -importkeystore -srckeystore keystore.jks \\\n -destkeystore intermediate.p12 -deststoretype PKCS12\n openssl pkcs12 -in intermediate.p12 -out extracted.pem -nodes\n" }, { "answer_id": 8308842, "author": "diyism", "author_id": 264181, "author_profile": "https://Stackoverflow.com/users/264181", "pm_score": 2, "selected": false, "text": "keytool.exe -importkeystore -srcstoretype JKS -srckeystore my-release-key.keystore -deststoretype PKCS12 -destkeystore keys.pk12.der\nopenssl.exe pkcs12 -in keys.pk12.der -nodes -out private.rsa.pem\n openssl.exe base64 -d -in private.rsa.pem -out private.rsa.der\n keytool.exe -exportcert -keystore my-release-key.keystore -storepass <KEYSTORE_PASSWORD> -alias alias_name -file public.x509.der\n java -jar SignApk.jar public.x509.der private.rsa.der input.apk output.apk\n" }, { "answer_id": 9105021, "author": "jrk", "author_id": 543416, "author_profile": "https://Stackoverflow.com/users/543416", "pm_score": 3, "selected": false, "text": "import java.security.Key\nimport java.security.KeyStore\n\nif (args.length < 3)\n throw new IllegalArgumentException('Expected args: <Keystore file> <Keystore format> <Keystore password> <alias> <key password>')\n\ndef keystoreName = args[0]\ndef keystoreFormat = args[1]\ndef keystorePassword = args[2]\ndef alias = args[3]\ndef keyPassword = args[4]\n\ndef keystore = KeyStore.getInstance(keystoreFormat)\nkeystore.load(new FileInputStream(keystoreName), keystorePassword.toCharArray())\ndef key = keystore.getKey(alias, keyPassword.toCharArray())\n\nprintln \"-----BEGIN PRIVATE KEY-----\"\nprintln key.getEncoded().encodeBase64()\nprintln \"-----END PRIVATE KEY-----\"\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150167", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1310/" ]
150,177
<p>I was helping out some colleagues of mine with an SQL problem. Mainly they wanted to move all the rows from table A to table B (both tables having the same columns (names and types)). Although this was done in Oracle 11g I don't think it really matters.</p> <p>Their initial naive implementation was something like </p> <pre><code>BEGIN INSERT INTO B SELECT * FROM A DELETE FROM A COMMIT; END </code></pre> <p>Their concern was if there were INSERTs made to table A during copying from A to B and the "DELETE FROM A" (or TRUNCATE for what was worth) would cause data loss (having the newer inserted rows in A deleted).</p> <p>Ofcourse I quickly recommended storing the IDs of the copied rows in a temporary table and then deleting just the rows in A that matched the IDS in the temporary table.</p> <p>However for curiosity's sake we put up a little test by adding a wait command (don't remember the PL/SQL syntax) between INSERT and DELETE. THen from a different connection we would insert rows <em>DURING THE WAIT</em>.</p> <p>We observed that was a data loss by doing so. I reproduced the whole context in SQL Server and wrapped it all in a transaction but still the fresh new data was lost too in SQL Server. This made me think there is a systematic error/flaw in the initial approach.</p> <p>However I can't tell if it was the fact that the TRANSACTION was not (somehow?) isolated from the fresh new INSERTs or the fact that the INSERTs came during the WAIT command.</p> <p>In the end it was implemented using the temporary table suggested by me but we couldn't get the answer to "Why the data loss". Do you know why?</p>
[ { "answer_id": 150187, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 1, "selected": false, "text": "begin tran\n....\ncommit\n" }, { "answer_id": 150207, "author": "Guy Starbuck", "author_id": 2194, "author_profile": "https://Stackoverflow.com/users/2194", "pm_score": 3, "selected": false, "text": "INSERT INTO B SELECT * FROM A;\n\nDELETE FROM A WHERE EXISTS (SELECT B.<primarykey> FROM B WHERE B.<primarykey> = A.<primarykey>);\n" }, { "answer_id": 150218, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 3, "selected": false, "text": "Alter session set isolation_level=serializable;\n BEGIN\n EXECUTE IMMEDIATE 'Alter session set isolation_level=serializable';\n ...\nEND;\n" }, { "answer_id": 31817642, "author": "Goyal Vicky", "author_id": 5166587, "author_profile": "https://Stackoverflow.com/users/5166587", "pm_score": 0, "selected": false, "text": " I have written a sample code:-\n\n First run this on Oracle DB:-\n\n\n Create table AccountBalance\n (\n id integer Primary Key,\n acctName varchar2(255) not null,\n acctBalance integer not null,\n bankName varchar2(255) not null\n );\n\n insert into AccountBalance values (1,'Test',50000,'Bank-a');\n\n Now run the below code \n\n\n\n\n\n package com.java.transaction.dirtyread;\n import java.sql.Connection;\n import java.sql.DriverManager;\n import java.sql.SQLException;\n\n public class DirtyReadExample {\n\n /**\n * @param args\n * @throws ClassNotFoundException \n * @throws SQLException \n * @throws InterruptedException \n */\n public static void main(String[] args) throws ClassNotFoundException, SQLException, InterruptedException {\n\n Class.forName(\"oracle.jdbc.driver.OracleDriver\");\n Connection connectionPayment = DriverManager.getConnection(\n \"jdbc:oracle:thin:@localhost:1521:xe\", \"hr\",\n \"hr\");\n Connection connectionReader = DriverManager.getConnection(\n \"jdbc:oracle:thin:@localhost:1521:xe\", \"hr\",\n \"hr\");\n\n try {\n connectionPayment.setAutoCommit(false);\n connectionPayment.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);\n\n\n } catch (SQLException e) {\n e.printStackTrace();\n }\n\n\n Thread pymtThread=new Thread(new PaymentRunImpl(connectionPayment));\n Thread readerThread=new Thread(new ReaderRunImpl(connectionReader));\n\n pymtThread.start();\n Thread.sleep(2000);\n readerThread.start();\n\n }\n\n }\n\n\n\n package com.java.transaction.dirtyread;\n\n import java.sql.Connection;\n import java.sql.PreparedStatement;\n import java.sql.ResultSet;\n import java.sql.SQLException;\n\n public class ReaderRunImpl implements Runnable{\n\n private Connection conn;\n\n private static final String QUERY=\"Select acctBalance from AccountBalance where id=1\";\n\n public ReaderRunImpl(Connection conn){\n this.conn=conn;\n }\n\n @Override\n public void run() {\n PreparedStatement stmt =null; \n ResultSet rs =null;\n\n try {\n stmt = conn.prepareStatement(QUERY);\n System.out.println(\"In Reader thread --->Statement Prepared\");\n rs = stmt.executeQuery();\n System.out.println(\"In Reader thread --->executing\");\n while (rs.next()){\n\n System.out.println(\"Balance is:\" + rs.getDouble(1));\n\n }\n System.out.println(\"In Reader thread --->Statement Prepared\");\n Thread.sleep(5000);\n stmt.close();\n rs.close();\n stmt = conn.prepareStatement(QUERY);\n rs = stmt.executeQuery();\n System.out.println(\"In Reader thread --->executing\");\n while (rs.next()){\n\n System.out.println(\"Balance is:\" + rs.getDouble(1));\n\n }\n stmt.close();\n rs.close();\n stmt = conn.prepareStatement(QUERY);\n rs = stmt.executeQuery();\n System.out.println(\"In Reader thread --->executing\");\n while (rs.next()){\n\n System.out.println(\"Balance is:\" + rs.getDouble(1));\n\n }\n } catch (SQLException | InterruptedException e) {\n e.printStackTrace();\n }finally{\n try {\n stmt.close();\n rs.close();\n } catch (SQLException e) {\n e.printStackTrace();\n } \n }\n }\n\n }\n\n package com.java.transaction.dirtyread;\n import java.sql.Connection;\n import java.sql.PreparedStatement;\n import java.sql.SQLException;\n\n public class PaymentRunImpl implements Runnable{\n\n private Connection conn;\n\n private static final String QUERY1=\"Update AccountBalance set acctBalance=40000 where id=1\";\n private static final String QUERY2=\"Update AccountBalance set acctBalance=30000 where id=1\";\n private static final String QUERY3=\"Update AccountBalance set acctBalance=20000 where id=1\";\n private static final String QUERY4=\"Update AccountBalance set acctBalance=10000 where id=1\";\n\n public PaymentRunImpl(Connection conn){\n this.conn=conn;\n }\n\n @Override\n public void run() {\n PreparedStatement stmt = null;\n\n try { \n stmt = conn.prepareStatement(QUERY1);\n stmt.execute();\n System.out.println(\"In Payment thread --> executed\");\n Thread.sleep(3000);\n stmt = conn.prepareStatement(QUERY2);\n stmt.execute();\n System.out.println(\"In Payment thread --> executed\");\n Thread.sleep(3000);\n stmt = conn.prepareStatement(QUERY3);\n stmt.execute();\n System.out.println(\"In Payment thread --> executed\");\n stmt = conn.prepareStatement(QUERY4);\n stmt.execute();\n System.out.println(\"In Payment thread --> executed\");\n\n Thread.sleep(5000);\n //case 1\n conn.rollback();\n System.out.println(\"In Payment thread --> rollback\");\n //case 2\n //conn.commit();\n // System.out.println(\"In Payment thread --> commit\");\n } catch (SQLException e) {\n e.printStackTrace();\n } catch (InterruptedException e) { \n e.printStackTrace();\n }finally{\n try {\n stmt.close();\n } catch (SQLException e) {\n e.printStackTrace();\n }\n }\n }\n\n }\n\n Output:-\n In Payment thread --> executed\n In Reader thread --->Statement Prepared\n In Reader thread --->executing\n Balance is:50000.0\n In Reader thread --->Statement Prepared\n In Payment thread --> executed\n In Payment thread --> executed\n In Payment thread --> executed\n In Reader thread --->executing\n Balance is:50000.0\n In Reader thread --->executing\n Balance is:50000.0\n In Payment thread --> rollback\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150177", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1796/" ]
150,186
<p>I'm trying to build a new .NET C++ project from scratch. I am planning to mix managed and unmanaged code in this project.</p> <p>this forum thread <a href="http://www.daniweb.com/forums/thread29742.html" rel="nofollow noreferrer">IDataObject : ambiguous symbol error</a> answers a problem I've seen multiple times.</p> <p>Post #4 states "Move all 'using namespace XXXX' from .h to .cpp"</p> <p>this looks like a good idea but now in my header files I need to reference parameters from the .NET Framework like</p> <pre><code>void loadConfigurations(String^ pPathname); </code></pre> <p>How am I supposed to move using statements in the .cpp file and use the according namespaces in the .h file?</p>
[ { "answer_id": 150245, "author": "itsmatt", "author_id": 7862, "author_profile": "https://Stackoverflow.com/users/7862", "pm_score": 0, "selected": false, "text": "namespace TestClassNS\n{\n class TestClass;\n}\n" }, { "answer_id": 150249, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": true, "text": "using #include using void loadConfigurations(SomeNamespace::String^ pPathname);\n using" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6367/" ]
150,192
<p>Even nowadays I often see underscores in Java variables and methods. An example are member variables (like &quot;m_count&quot; or &quot;_count&quot;). As far as I remember, to use underscores in these cases is called bad style by <a href="https://en.wikipedia.org/wiki/Sun_Microsystems" rel="nofollow noreferrer">Sun</a>.</p> <p>The only place they should be used is in constants (like in &quot;public final static int IS_OKAY = 1;&quot;), because constants should be all upper case and not <a href="https://en.wikipedia.org/wiki/Camel_case" rel="nofollow noreferrer">camel case</a>. Here, the underscore should make the code more readable.</p> <p>Do you think using underscores in Java is bad style? If so (or not), why?</p>
[ { "answer_id": 150226, "author": "Chris Cudmore", "author_id": 18907, "author_profile": "https://Stackoverflow.com/users/18907", "pm_score": 2, "selected": false, "text": "setBar( int bar)\n{\n _bar = bar;\n}\n setBar( int bar)\n{\n this.bar = bar;\n}\n" }, { "answer_id": 150291, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "public class TestClass {\n int var1;\n\n public void func1(int var1) {\n System.out.println(\"Which one is it?: \" + var1);\n }\n}" }, { "answer_id": 150489, "author": "Steve B.", "author_id": 19479, "author_profile": "https://Stackoverflow.com/users/19479", "pm_score": 3, "selected": false, "text": "private int _my_int;\npublic int myInt;? _my_int? )\n" }, { "answer_id": 11396147, "author": "Vladimir Miller", "author_id": 1512109, "author_profile": "https://Stackoverflow.com/users/1512109", "pm_score": 3, "selected": false, "text": "_name __name" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13209/" ]
150,201
<p>My client wants me to enable a "Remember Me" checkbox when the user logs in. I am encrypting and storing both the username and password in a cookie.</p> <p>However, you cannot write to a textbox when it's in password mode.</p> <p>I've seen this done numerous times, so how are they doing it?</p> <p>thanks in advance!</p>
[ { "answer_id": 150280, "author": "Chris Cudmore", "author_id": 18907, "author_profile": "https://Stackoverflow.com/users/18907", "pm_score": 2, "selected": false, "text": "Page_Load( ...)\n {\n ... process cookie ...\n if (cookie is good) Response.Redirect(\"content.aspx\");\n }\n" }, { "answer_id": 210438, "author": "spmason", "author_id": 5793, "author_profile": "https://Stackoverflow.com/users/5793", "pm_score": 1, "selected": false, "text": "<input type=\"text\" name=\"username\" value=\"<%=decryptedUsername%>\" />\n<input type=\"password\" value=\"<%=decryptedPassword%>\" />\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150201", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23576/" ]
150,208
<p>Is there a free third-party or .NET class that will convert HTML to RTF (for use in a rich-text enabled Windows Forms control)?</p> <p>The "free" requirement comes from the fact that I'm only working on a prototype and can just load the BrowserControl and just render HTML if need be (even if it is slow) and that Developer Express is going to be releasing their own such control soon-ish.</p> <p>I don't want to learn to write RTF by hand, and I already know HTML, so I figure this is the quickest way to get some demonstrable code out the door quickly.</p>
[ { "answer_id": 155112, "author": "Andrew", "author_id": 20118, "author_profile": "https://Stackoverflow.com/users/20118", "pm_score": 2, "selected": false, "text": "public static string ConvertHtmlToText(string source) {\n\n string result;\n\n // Remove HTML Development formatting\n // Replace line breaks with space\n // because browsers inserts space\n result = source.Replace(\"\\r\", \" \");\n // Replace line breaks with space\n // because browsers inserts space\n result = result.Replace(\"\\n\", \" \");\n // Remove step-formatting\n result = result.Replace(\"\\t\", string.Empty);\n // Remove repeating speces becuase browsers ignore them\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"( )+\", \" \");\n\n // Remove the header (prepare first by clearing attributes)\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"<( )*head([^>])*>\", \"<head>\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"(<( )*(/)( )*head( )*>)\", \"</head>\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n result = System.Text.RegularExpressions.Regex.Replace(result,\n \"(<head>).*(</head>)\", string.Empty,\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n\n // remove all scripts (prepare first by clearing attributes)\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"<( )*script([^>])*>\", \"<script>\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"(<( )*(/)( )*script( )*>)\", \"</script>\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n //result = System.Text.RegularExpressions.Regex.Replace(result, \n // @\"(<script>)([^(<script>\\.</script>)])*(</script>)\",\n // string.Empty, \n // System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"(<script>).*(</script>)\", string.Empty,\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n\n // remove all styles (prepare first by clearing attributes)\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"<( )*style([^>])*>\", \"<style>\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"(<( )*(/)( )*style( )*>)\", \"</style>\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n result = System.Text.RegularExpressions.Regex.Replace(result,\n \"(<style>).*(</style>)\", string.Empty,\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n\n // insert tabs in spaces of <td> tags\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"<( )*td([^>])*>\", \"\\t\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n\n // insert line breaks in places of <BR> and <LI> tags\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"<( )*br( )*>\", \"\\r\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"<( )*li( )*>\", \"\\r\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n\n // insert line paragraphs (double line breaks) in place\n // if <P>, <DIV> and <TR> tags\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"<( )*div([^>])*>\", \"\\r\\r\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"<( )*tr([^>])*>\", \"\\r\\r\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"<( )*p([^>])*>\", \"\\r\\r\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n\n // Remove remaining tags like <a>, links, images,\n // comments etc - anything thats enclosed inside < >\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"<[^>]*>\", string.Empty,\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n\n // replace special characters:\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"&nbsp;\", \" \",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"&bull;\", \" * \",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"&lsaquo;\", \"<\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"&rsaquo;\", \">\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"&trade;\", \"(tm)\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"&frasl;\", \"/\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"<\", \"<\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\">\", \">\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"&copy;\", \"(c)\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"&reg;\", \"(r)\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n // Remove all others. More can be added, see\n // http://hotwired.lycos.com/webmonkey/reference/special_characters/\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"&(.{2,6});\", string.Empty,\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n\n\n // make line breaking consistent\n result = result.Replace(\"\\n\", \"\\r\");\n\n // Remove extra line breaks and tabs:\n // replace over 2 breaks with 2 and over 4 tabs with 4. \n // Prepare first to remove any whitespaces inbetween\n // the escaped characters and remove redundant tabs inbetween linebreaks\n result = System.Text.RegularExpressions.Regex.Replace(result,\n \"(\\r)( )+(\\r)\", \"\\r\\r\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n result = System.Text.RegularExpressions.Regex.Replace(result,\n \"(\\t)( )+(\\t)\", \"\\t\\t\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n result = System.Text.RegularExpressions.Regex.Replace(result,\n \"(\\t)( )+(\\r)\", \"\\t\\r\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n result = System.Text.RegularExpressions.Regex.Replace(result,\n \"(\\r)( )+(\\t)\", \"\\r\\t\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n // Remove redundant tabs\n result = System.Text.RegularExpressions.Regex.Replace(result,\n \"(\\r)(\\t)+(\\r)\", \"\\r\\r\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n // Remove multible tabs followind a linebreak with just one tab\n result = System.Text.RegularExpressions.Regex.Replace(result,\n \"(\\r)(\\t)+\", \"\\r\\t\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n // Initial replacement target string for linebreaks\n string breaks = \"\\r\\r\\r\";\n // Initial replacement target string for tabs\n string tabs = \"\\t\\t\\t\\t\\t\";\n for (int index = 0; index < result.Length; index++) {\n result = result.Replace(breaks, \"\\r\\r\");\n result = result.Replace(tabs, \"\\t\\t\\t\\t\");\n breaks = breaks + \"\\r\";\n tabs = tabs + \"\\t\";\n }\n\n // Thats it.\n return result;\n\n }\n" }, { "answer_id": 4854628, "author": "Spartaco", "author_id": 565927, "author_profile": "https://Stackoverflow.com/users/565927", "pm_score": 6, "selected": true, "text": "var webBrowser = new WebBrowser();\nwebBrowser.CreateControl(); // only if needed\nwebBrowser.DocumentText = *yourhtmlstring*;\nwhile (_webBrowser.DocumentText != *yourhtmlstring*)\n Application.DoEvents();\nwebBrowser.Document.ExecCommand(\"SelectAll\", false, null);\nwebBrowser.Document.ExecCommand(\"Copy\", false, null);\n*yourRichTextControl*.Paste(); \n" }, { "answer_id": 5034601, "author": "cjbarth", "author_id": 271351, "author_profile": "https://Stackoverflow.com/users/271351", "pm_score": 3, "selected": false, "text": " Using reportWebBrowser As New WebBrowser\n reportWebBrowser.CreateControl()\n reportWebBrowser.DocumentText = sbHTMLDoc.ToString\n While reportWebBrowser.DocumentText <> sbHTMLDoc.ToString\n Application.DoEvents()\n End While\n reportWebBrowser.Document.ExecCommand(\"SelectAll\", False, Nothing)\n reportWebBrowser.Document.ExecCommand(\"Copy\", False, Nothing)\n\n Using reportRichTextBox As New RichTextBox\n reportRichTextBox.Paste()\n reportRichTextBox.SaveFile(DocumentFileName)\n End Using\n End Using\n" }, { "answer_id": 56733740, "author": "Jacek Krawczyk", "author_id": 1960514, "author_profile": "https://Stackoverflow.com/users/1960514", "pm_score": 1, "selected": false, "text": "pandoc filename.html -f html -t rtf -s -o filename.rtf\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/549/" ]
150,213
<p>I'm trying to chart the number of registrations per day in our registration system. I have an Attendee table in sql server that has a smalldatetime field A_DT, which is the date and time the person registered.</p> <p>I started with this:</p> <pre><code>var dailyCountList = (from a in showDC.Attendee let justDate = new DateTime(a.A_DT.Year, a.A_DT.Month, a.A_DT.Day) group a by justDate into DateGroup orderby DateGroup.Key select new RegistrationCount { EventDateTime = DateGroup.Key, Count = DateGroup.Count() }).ToList(); </code></pre> <p>That works great, but it won't include the dates where there were no registrations, because there are no attendee records for those dates. I want every date to be included, and when there is no data for a given date, the count should just be zero.</p> <p>So this is my current working solution, but I KNOW THAT IT IS TERRIBLE. I added the following to the code above:</p> <pre><code>// Create a new list of data ranging from the beginning to the end of the first list, specifying 0 counts for missing data points (days with no registrations) var allDates = new List&lt;RegistrationCount&gt;(); for (DateTime date = (from dcl in dailyCountList select dcl).First().EventDateTime; date &lt;= (from dcl in dailyCountList select dcl).Last().EventDateTime; date = date.AddDays(1)) { DateTime thisDate = date; // lexical closure issue - see: http://www.managed-world.com/2008/06/13/LambdasKnowYourClosures.aspx allDates.Add(new RegistrationCount { EventDateTime = date, Count = (from dclInner in dailyCountList where dclInner.EventDateTime == thisDate select dclInner).DefaultIfEmpty(new RegistrationCount { EventDateTime = date, Count = 0 }).Single().Count }); } </code></pre> <p>So I created ANOTHER list, and loop through a sequence of dates I generate based on the first and last registrations in the query, and for each item in the sequence of dates, I QUERY the results of my first QUERY for the information regarding the given date, and supply a default if nothing comes back. So I end up doing a subquery here and I want to avoid this.</p> <p>Can anyone thing of an elegant solution? Or at least one that is less embarrassing?</p>
[ { "answer_id": 150334, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 2, "selected": true, "text": " if (!dailyCountList.Any())\n return;\n\n //make a dictionary to provide O(1) lookups for later\n\n Dictionary<DateTime, RegistrationCount> lookup = dailyCountList.ToDictionary(r => r.EventDateTime);\n\n DateTime minDate = dailyCountList[0].EventDateTime;\n DateTime maxDate = dailyCountList[dailyCountList.Count - 1].EventDateTime;\n\n int DayCount = 1 + (int) (maxDate - minDate).TotalDays;\n\n // I have the days now.\n IEnumerable<DateTime> allDates = Enumerable\n .Range(0, DayCount)\n .Select(x => minDate.AddDays(x));\n\n //project the days into RegistrationCounts, making up the missing ones.\n List<RegistrationCount> result = allDates\n .Select(d => lookup.ContainsKey(d) ? lookup[d] :\n new RegistrationCount(){EventDateTime = d, Count = 0})\n .ToList();\n" }, { "answer_id": 150438, "author": "Codewerks", "author_id": 17729, "author_profile": "https://Stackoverflow.com/users/17729", "pm_score": 0, "selected": false, "text": "var query =\n from cal in dataContext.Calendar\n from reg in cal.Registrations.DefaultIfEmpty()\n select new\n {\n cal.DateID,\n reg.Something\n };\n" }, { "answer_id": 150964, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 0, "selected": false, "text": "var allDailyCountList =\n from d in Range(dc[0].EventDateTime, dc[dc.Count - 1].EventDateTime) \n // since you already ordered by DateTime, we don't have to search the entire List\n join dc in dailyCountList on\n d equals dc.EventDateTime\n into rcGroup\n from rc in rcGroup.DefaultIfEmpty(\n new RegistrationCount()\n {\n EventDateTime = d,\n Count = 0\n }\n ) // gives us a left join\n select rc;\n\npublic static IEnumerable<DateTime> Range(DateTime start, DateTime end) {\n for (DateTime date = start, date <= end; date = date.AddDays(1)) {\n yield return date;\n }\n}\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150213", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13700/" ]
150,250
<p>I was recently tasked with debugging a strange problem within an e-commerce application. After an application upgrade the site started to hang from time to time and I was sent in to debug. After checking the event log I found that the SQL-server wrote ~200 000 events in a couple of minutes with the message saying that a constraint had failed. After much debugging and some tracing I found the culprit. I've removed some unnecessary code and cleaned it up a bit but essentially this is it</p> <pre><code>WHILE EXISTS (SELECT * FROM ShoppingCartItem WHERE ShoppingCartItem.PurchID = @PurchID) BEGIN SELECT TOP 1 @TmpGFSID = ShoppingCartItem.GFSID, @TmpQuantity = ShoppingCartItem.Quantity, @TmpShoppingCartItemID = ShoppingCartItem.ShoppingCartItemID, FROM ShoppingCartItem INNER JOIN GoodsForSale on ShoppingCartItem.GFSID = GoodsForSale.GFSID WHERE ShoppingCartItem.PurchID = @PurchID EXEC @ErrorCode = spGoodsForSale_ReverseReservations @TmpGFSID, @TmpQuantity IF @ErrorCode &lt;&gt; 0 BEGIN Goto Cleanup END DELETE FROM ShoppingCartItem WHERE ShoppingCartItem.ShoppingCartItemID = @TmpShoppingCartItemID -- @@ROWCOUNT is 1 after this END </code></pre> <p>Facts:</p> <ol> <li>There's only one or two records matching the first select-clause</li> <li>RowCount from the DELETE statement indicates that it has been removed</li> <li>The WHILE-clause will loop forever</li> </ol> <p>The procedure has been rewritten to select the rows that should be deleted into a temporary in-memory table instead so the immediate problem is solved but this really sparked my curiosity.</p> <p>Why does it loop forever?</p> <p><strong>Clarification</strong>: The delete doesn't fail (@@rowcount is 1 after the delete stmt when debugged) <strong>Clarification 2</strong>: It shouldn't matter whether or not the SELECT TOP ... clause is ordered by any specific field since the record with the returned id will be deleted so in the next loop it should get another record.</p> <p><strong>Update</strong>: After checking the subversion logs I found the culprit commit that made this stored procedure to go haywire. The only real difference that I can find is that there previously was no join in the SELECT TOP 1 statement i.e. without that join it worked without any transaction statements surrounding the delete. It appears to be the introduction of the join that made SQL server more picky.</p> <p><strong>Update clarification</strong>: <a href="https://stackoverflow.com/questions/150250/while-clause-in-t-sql-that-loops-forever#150400">brien</a> pointed out that there's no need for the join but we actually do use some fields from the GoodsForSale table but I've removed them to keep the code simply so that we can concentrate on the problem at hand</p>
[ { "answer_id": 150297, "author": "brien", "author_id": 4219, "author_profile": "https://Stackoverflow.com/users/4219", "pm_score": 3, "selected": true, "text": "WHILE EXISTS (SELECT * FROM ShoppingCartItem WHERE ShoppingCartItem.PurchID = @PurchID)\nBEGIN\n SELECT TOP 1 \n @TmpGFSID = ShoppingCartItem.GFSID, \n @TmpQuantity = ShoppingCartItem.Quantity,\n @TmpShoppingCartItemID = ShoppingCartItem.ShoppingCartItemID,\n FROM\n ShoppingCartItem INNER JOIN GoodsForSale on ShoppingCartItem.GFSID = GoodsForSale.GFSID\n WHERE ShoppingCartItem.PurchID = @PurchID\n\n EXEC @ErrorCode = spGoodsForSale_ReverseReservations @TmpGFSID, @TmpQuantity\n IF @ErrorCode <> 0\n BEGIN\n Goto Cleanup \n END\n\n BEGIN TRANSACTION delete\n\n DELETE FROM ShoppingCartItem WHERE ShoppingCartItem.ShoppingCartItemID = @TmpShoppingCartItemID\n -- @@ROWCOUNT is 1 after this\n\n COMMIT TRANSACTION delete\nEND\n" }, { "answer_id": 150534, "author": "devio", "author_id": 21336, "author_profile": "https://Stackoverflow.com/users/21336", "pm_score": 0, "selected": false, "text": "DECLARE Old@ShoppingCartItemID INT\n\nSET @OldShoppingCartItemID = 0\n\nWHILE EXISTS (SELECT ... WHERE ShoppingCartItemID > @ShoppingCartItemID)\n\nSELECT TOP 1 WHERE ShoppingCartItemID > @OldShoppingCartItemID ORDER BY ShoppingCartItemID \n\nSET @OldShoppingCartItemID = @TmpShoppingCartItemID\n" }, { "answer_id": 150883, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 2, "selected": false, "text": "FROM\n ShoppingCartItem\n INNER JOIN\n GoodsForSale\n on ShoppingCartItem.GFSID = GoodsForSale.GFSID\n SELECT TOP 1\n @TmpGFSID = ShoppingCartItem.GFSID,\n @TmpQuantity = ShoppingCartItem.Quantity,\n @TmpShoppingCartItemID =\n ShoppingCartItem.ShoppingCartItemID\n SELECT\n @TmpGFSID = null,\n @TmpQuantity = null,\n @TmpShoppingCartItemID = null\n" }, { "answer_id": 193889, "author": "Sam Saffron", "author_id": 17174, "author_profile": "https://Stackoverflow.com/users/17174", "pm_score": 0, "selected": false, "text": "(SELECT * FROM ShoppingCartItem WHERE JOIN GoodsForSale on ShoppingCartItem.GFSID = GoodsForSale.GFSID where ShoppingCartItem.PurchID = @PurchID)\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2114/" ]
150,284
<p>I understand that these methods are for pickling/unpickling and have no relation to the reduce built-in function, but what's the difference between the 2 and why do we need both?</p>
[ { "answer_id": 150309, "author": "Adriano Varoli Piazza", "author_id": 22184, "author_profile": "https://Stackoverflow.com/users/22184", "pm_score": 6, "selected": true, "text": "__reduce__() __reduce__ __reduce_ex__ __reduce__ __reduce_ex__ __reduce__ __reduce__ __reduce_ex__" }, { "answer_id": 150318, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 3, "selected": false, "text": "__reduce_ex__ __reduce__ __reduce_ex__ __reduce__" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150284", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3051/" ]
150,294
<p>I'd like my program to read the cache line size of the CPU it's running on in C++.</p> <p>I know that this can't be done portably, so I will need a solution for Linux and another for Windows (Solutions for other systems could be usefull to others, so post them if you know them).</p> <p>For Linux I could read the content of /proc/cpuinfo and parse the line begining with cache_alignment. Maybe there is a better way involving a call to an API.</p> <p>For Windows I simply have no idea.</p>
[ { "answer_id": 150300, "author": "Nick", "author_id": 1490, "author_profile": "https://Stackoverflow.com/users/1490", "pm_score": 5, "selected": true, "text": "GetLogicalProcessorInformation SYSTEM_LOGICAL_PROCESSOR_INFORMATION CACHE_DESCRIPTOR" }, { "answer_id": 150328, "author": "rami", "author_id": 9629, "author_profile": "https://Stackoverflow.com/users/9629", "pm_score": 0, "selected": false, "text": "NtQuerySystemInformation ntdll.dll" }, { "answer_id": 39466518, "author": "Researcher", "author_id": 5933020, "author_profile": "https://Stackoverflow.com/users/5933020", "pm_score": 2, "selected": false, "text": "#include <Windows.h>\n#include <iostream>\n\nusing std::cout; using std::endl;\n\nint main()\n{\n SYSTEM_INFO systemInfo;\n GetSystemInfo(&systemInfo);\n cout << \"Page Size Is: \" << systemInfo.dwPageSize;\n getchar();\n}\n" }, { "answer_id": 62044882, "author": "metablaster", "author_id": 12091999, "author_profile": "https://Stackoverflow.com/users/12091999", "pm_score": 2, "selected": false, "text": "#include <new>\n#include <iostream>\n#include <Windows.h>\n\n\nvoid ShowCacheSize()\n{\n using CPUInfo = SYSTEM_LOGICAL_PROCESSOR_INFORMATION;\n DWORD len = 0;\n CPUInfo* buffer = nullptr;\n\n // Determine required length of a buffer\n if ((GetLogicalProcessorInformation(buffer, &len) == FALSE) && (GetLastError() == ERROR_INSUFFICIENT_BUFFER))\n {\n // Allocate buffer of required size\n buffer = new (std::nothrow) CPUInfo[len]{ };\n\n if (buffer == nullptr)\n {\n std::cout << \"Buffer allocation of \" << len << \" bytes failed\" << std::endl;\n }\n else if (GetLogicalProcessorInformation(buffer, &len) != FALSE)\n {\n for (DWORD i = 0; i < len; ++i)\n {\n // This will be true for multiple returned caches, we need just one\n if (buffer[i].Relationship == RelationCache)\n {\n std::cout << \"Cache line size is: \" << buffer[i].Cache.LineSize << \" bytes\" << std::endl;\n break;\n }\n }\n }\n else\n {\n std::cout << \"ERROR: \" << GetLastError() << std::endl;\n }\n\n delete[] buffer;\n }\n}\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5861/" ]
150,329
<p>I recently migrated a website to a new CMS (Umbraco). A lot of the links have changed, but they can be easily corrected by searching for patters in the url, so I would like to write something that will redirect to the correct page if the old one is not found. That part isn't a problem. </p> <p>How can I obtain the requested URL after the browser is redirected to my custom 404 page. I tried using:</p> <pre><code>request.ServerVariables("HTTP_REFERER") 'sorry i corrected the typo from system to server. </code></pre> <p>But that didn't work.</p> <p>Any Ideas?</p> <p>The site is on IIS 6.0. We did consider using 301 redirects, but we don't have any way of knowing what pages people have bookmarked and there are a few hundred pages, so no one is keen on spending the time to create the 301's.</p>
[ { "answer_id": 150336, "author": "Kev", "author_id": 419, "author_profile": "https://Stackoverflow.com/users/419", "pm_score": 0, "selected": false, "text": "Request.QueryString(\"aspxerrorpath\")\n Request.QueryString[\"aspxerrorpath\"];\n" }, { "answer_id": 150337, "author": "LordHits", "author_id": 8088, "author_profile": "https://Stackoverflow.com/users/8088", "pm_score": 2, "selected": false, "text": "Request.ServerVariables(\"HTTP_REFERER\");\n" }, { "answer_id": 150350, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": 2, "selected": false, "text": "# $1 will contain the contents of (.*) - everything after new-dir/\nRewriteRule /new-dir/(.*) /find_old_page.asp?code=$1 \n" }, { "answer_id": 150460, "author": "DougN", "author_id": 7442, "author_profile": "https://Stackoverflow.com/users/7442", "pm_score": 3, "selected": true, "text": "//did the error go to a .ASP page? If so, append x (for .aspx) and \n//issue a 301 permanently moved\n//when we get an error, the querystring will be \"404;<complete original URL>\"\nstring targetPage = Request.RawUrl.Substring(Request.FilePath.Length);\n\nif((null == targetPage) || (targetPage.Length == 0))\n targetPage = \"[home page]\";\nelse\n{\n //find the original URL\n if(targetPage[0] == '?')\n {\n if(-1 != targetPage.IndexOf(\"?aspxerrorpath=\"))\n targetPage = targetPage.Substring(15); // ?aspxerrorpath=\n else\n targetPage = targetPage.Substring(5); // ?404;\n }\n else\n {\n if(-1 != targetPage.IndexOf(\"errorpath=\"))\n targetPage = targetPage.Substring(14); // aspxerrorpath=\n else\n targetPage = targetPage.Substring(4); // 404;\n }\n } \n\n string upperTarget = targetPage.ToUpper();\n if((-1 == upperTarget.IndexOf(\".ASPX\")) && (-1 != upperTarget.IndexOf(\".ASP\")))\n {\n //this is a request for an .ASP page - permanently redirect to .aspx\n targetPage = upperTarget.Replace(\".ASP\", \".ASPX\");\n //issue 301 redirect\n Response.Status = \"301 Moved Permanently\"; \n Response.AddHeader(\"Location\",targetPage);\n Response.End();\n }\n\n if(-1 != upperTarget.IndexOf(\"ORDER\"))\n {\n //going to old order page -- forward to new page\n Response.Redirect(WebRoot + \"/order.aspx\");\n Response.End();\n }\n" }, { "answer_id": 150525, "author": "Herb Caudill", "author_id": 239663, "author_profile": "https://Stackoverflow.com/users/239663", "pm_score": 1, "selected": false, "text": "Dim AttemptedUrl As String = Request.QueryString(\"aspxerrorpath\")\nIf Len(AttemptedUrl) = 0 Then AttemptedUrl = Request.Url.Query\nAttemptedUrl = LCase(AttemptedUrl)\nCheckForRedirects(AttemptedUrl)\n" }, { "answer_id": 239867, "author": "James Green", "author_id": 31736, "author_profile": "https://Stackoverflow.com/users/31736", "pm_score": 1, "selected": false, "text": "\\config\\UrlRewriting.config\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150329", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20483/" ]
150,332
<p>If I have variable of type <code>IEnumerable&lt;List&lt;string&gt;&gt;</code> is there a LINQ statement or lambda expression I can apply to it which will combine the lists returning an <code>IEnumerable&lt;string&gt;</code>? </p>
[ { "answer_id": 150343, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 6, "selected": true, "text": " IEnumerable<List<string>> someList = ...;\n IEnumerable<string> all = someList.SelectMany(x => x);\n static IEnumerable<TResult> SelectMany<TSource, TResult>(\n this IEnumerable<TSource> source,\n Func<TSource, IEnumerable<TResult>> selector) {\n\n foreach(TSource item in source) {\n foreach(TResult result in selector(item)) {\n yield return result;\n }\n }\n}\n" }, { "answer_id": 150348, "author": "Greg Beech", "author_id": 13552, "author_profile": "https://Stackoverflow.com/users/13552", "pm_score": 2, "selected": false, "text": "var concatenated = from list in lists from item in list select item;\n IEnumerable<List<string>> IEnumerable<string> SelectMany" }, { "answer_id": 150388, "author": "VVS", "author_id": 21038, "author_profile": "https://Stackoverflow.com/users/21038", "pm_score": 0, "selected": false, "text": "IEnumerable<string> GetStrings(IEnumerable<List<string>> lists)\n{\n foreach (List<string> list in lists)\n foreach (string item in list)\n {\n yield return item;\n }\n }\n" }, { "answer_id": 150402, "author": "Jarrett Meyer", "author_id": 5834, "author_profile": "https://Stackoverflow.com/users/5834", "pm_score": 0, "selected": false, "text": "IEnumerable<string> myList = from a in (from b in myBigList\n select b)\n select a;\n b IEnumerable<string> a string" }, { "answer_id": 150427, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 0, "selected": false, "text": "IEnumerable<string> myStrings =\n from a in mySource\n from b in a\n select b;\n" }, { "answer_id": 150456, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 3, "selected": false, "text": "myStrings.SelectMany(x => x)\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150332", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
150,333
<p>We need to remotely create an Exchange 2007 distribution list from Asp.Net.</p> <p>Near as I can tell, the only way to create a distribution list in the GAL is via the exchange management tools. Without installing this on our web server, is there any way to create a distribution list remotely? There are some third party components that allow you to create personal distribution lists, but these only live in a users Contacts folder and are not available to all users within the company.</p> <p>Ideally there would be some kind of web services call to exchange or an API we could work with. The Exchange SDK provides the ability to managing Exchange data (e.g. emails, contacts, calendars etc.). There doesn't appear to be an Exchange management API.</p> <p>It looks like the distribution lists are stored in AD as group objects with a special Exchange attributes, but there doesn't seem to be any documentation on how they are supposed to work. </p> <p>Edit: We could reverse engineer what Exchange is doing with AD, but my concern is that with the next service pack of Exchange this will all break. </p> <p>Is there an API that I can use to manage the distribution lists in Active Directory without going through Exchange? </p>
[ { "answer_id": 150343, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 6, "selected": true, "text": " IEnumerable<List<string>> someList = ...;\n IEnumerable<string> all = someList.SelectMany(x => x);\n static IEnumerable<TResult> SelectMany<TSource, TResult>(\n this IEnumerable<TSource> source,\n Func<TSource, IEnumerable<TResult>> selector) {\n\n foreach(TSource item in source) {\n foreach(TResult result in selector(item)) {\n yield return result;\n }\n }\n}\n" }, { "answer_id": 150348, "author": "Greg Beech", "author_id": 13552, "author_profile": "https://Stackoverflow.com/users/13552", "pm_score": 2, "selected": false, "text": "var concatenated = from list in lists from item in list select item;\n IEnumerable<List<string>> IEnumerable<string> SelectMany" }, { "answer_id": 150388, "author": "VVS", "author_id": 21038, "author_profile": "https://Stackoverflow.com/users/21038", "pm_score": 0, "selected": false, "text": "IEnumerable<string> GetStrings(IEnumerable<List<string>> lists)\n{\n foreach (List<string> list in lists)\n foreach (string item in list)\n {\n yield return item;\n }\n }\n" }, { "answer_id": 150402, "author": "Jarrett Meyer", "author_id": 5834, "author_profile": "https://Stackoverflow.com/users/5834", "pm_score": 0, "selected": false, "text": "IEnumerable<string> myList = from a in (from b in myBigList\n select b)\n select a;\n b IEnumerable<string> a string" }, { "answer_id": 150427, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 0, "selected": false, "text": "IEnumerable<string> myStrings =\n from a in mySource\n from b in a\n select b;\n" }, { "answer_id": 150456, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 3, "selected": false, "text": "myStrings.SelectMany(x => x)\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23583/" ]
150,339
<p>I am about to add a section to an ASP.NET app (VB.NET codebehind) that will allow a user to get data returned to them as an Excel file, which I will generate based on database data. While there are several ways of doing this, each has its own drawbacks. How would <em>you</em> return the data? I'm looking for something that's as clean and straightforward as possible.</p>
[ { "answer_id": 150364, "author": "SpoiledTechie.com", "author_id": 7644, "author_profile": "https://Stackoverflow.com/users/7644", "pm_score": 4, "selected": false, "text": "public static void DataTabletoXLS(DataTable DT, string fileName)\n{\n HttpContext.Current.Response.Clear();\n HttpContext.Current.Response.Charset = \"utf-16\";\n HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding(\"windows-1250\");\n HttpContext.Current.Response.AddHeader(\"content-disposition\", string.Format(\"attachment; filename={0}.xls\", fileName));\n HttpContext.Current.Response.ContentType = \"application/ms-excel\";\n\n string tab = \"\";\n foreach (DataColumn dc in DT.Columns)\n {\n HttpContext.Current.Response.Write(tab + dc.ColumnName.Replace(\"\\n\", \"\").Replace(\"\\t\", \"\"));\n tab = \"\\t\";\n }\n HttpContext.Current.Response.Write(\"\\n\");\n\n int i;\n foreach (DataRow dr in DT.Rows)\n {\n tab = \"\";\n for (i = 0; i < DT.Columns.Count; i++)\n {\n HttpContext.Current.Response.Write(tab + dr[i].ToString().Replace(\"\\n\", \"\").Replace(\"\\t\", \"\"));\n tab = \"\\t\";\n }\n HttpContext.Current.Response.Write(\"\\n\");\n }\n HttpContext.Current.Response.End();\n}\n public static void GridviewtoXLS(GridView gv, string fileName)\n{\n int DirtyBit = 0;\n int PageSize = 0;\n if (gv.AllowPaging == true)\n {\n DirtyBit = 1;\n PageSize = gv.PageSize;\n gv.AllowPaging = false;\n gv.DataBind();\n }\n\n HttpContext.Current.Response.Clear();\n HttpContext.Current.Response.Charset = \"utf-8\";\n HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding(\"windows-1250\");\n HttpContext.Current.Response.AddHeader(\n \"content-disposition\", string.Format(\"attachment; filename={0}.xls\", fileName));\n HttpContext.Current.Response.ContentType = \"application/ms-excel\";\n\n using (StringWriter sw = new StringWriter())\n using (HtmlTextWriter htw = new HtmlTextWriter(sw))\n {\n // Create a table to contain the grid\n Table table = new Table();\n\n // include the gridline settings\n table.GridLines = gv.GridLines;\n\n // add the header row to the table\n if (gv.HeaderRow != null)\n {\n Utilities.Export.PrepareControlForExport(gv.HeaderRow);\n table.Rows.Add(gv.HeaderRow);\n }\n\n // add each of the data rows to the table\n foreach (GridViewRow row in gv.Rows)\n {\n Utilities.Export.PrepareControlForExport(row);\n table.Rows.Add(row);\n }\n\n // add the footer row to the table\n if (gv.FooterRow != null)\n {\n Utilities.Export.PrepareControlForExport(gv.FooterRow);\n table.Rows.Add(gv.FooterRow);\n }\n\n // render the table into the htmlwriter\n table.RenderControl(htw);\n\n // render the htmlwriter into the response\n HttpContext.Current.Response.Write(sw.ToString().Replace(\"£\", \"\"));\n HttpContext.Current.Response.End();\n }\n\n if (DirtyBit == 1)\n {\n gv.PageSize = PageSize;\n gv.AllowPaging = true;\n gv.DataBind();\n }\n}\n\nprivate static void PrepareControlForExport(Control control)\n{\n for (int i = 0; i < control.Controls.Count; i++)\n {\n Control current = control.Controls[i];\n if (current is LinkButton)\n {\n control.Controls.Remove(current);\n control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));\n }\n else if (current is ImageButton)\n {\n control.Controls.Remove(current);\n control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));\n }\n else if (current is HyperLink)\n {\n control.Controls.Remove(current);\n control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));\n }\n else if (current is DropDownList)\n {\n control.Controls.Remove(current);\n control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));\n }\n else if (current is CheckBox)\n {\n control.Controls.Remove(current);\n control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? \"True\" : \"False\"));\n }\n\n if (current.HasControls())\n {\n Utilities.Export.PrepareControlForExport(current);\n }\n }\n}\n" }, { "answer_id": 150368, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 5, "selected": false, "text": ".xls .xlsx SpreadSheetML <?xml version=\"1.0\"?>\n<?mso-application progid=\"Excel.Sheet\"?> \n<Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"\n xmlns:o=\"urn:schemas-microsoft-com:office:office\"\n xmlns:x=\"urn:schemas-microsoft-com:office:excel\"\n xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\"\n xmlns:html=\"http://www.w3.org/TR/REC-html40\">\n<DocumentProperties xmlns=\"urn:schemas-microsoft-com:office:office\">\n <Author>Your_name_here</Author>\n <LastAuthor>Your_name_here</LastAuthor>\n <Created>20080625</Created>\n <Company>ABC Inc</Company>\n <Version>10.2625</Version>\n</DocumentProperties>\n<ExcelWorkbook xmlns=\"urn:schemas-microsoft-com:office:excel\">\n <WindowHeight>6135</WindowHeight>\n <WindowWidth>8445</WindowWidth>\n <WindowTopX>240</WindowTopX>\n <WindowTopY>120</WindowTopY>\n <ProtectStructure>False</ProtectStructure>\n <ProtectWindows>False</ProtectWindows>\n</ExcelWorkbook>\n\n<Styles>\n <Style ss:ID=\"Default\" ss:Name=\"Normal\">\n <Alignment ss:Vertical=\"Bottom\" />\n <Borders />\n <Font />\n <Interior />\n <NumberFormat />\n <Protection />\n </Style>\n</Styles>\n\n<Worksheet ss:Name=\"Sample Sheet 1\">\n<Table ss:ExpandedColumnCount=\"2\" x:FullColumns=\"1\" x:FullRows=\"1\" ID=\"Table1\">\n<Column ss:Width=\"150\" />\n<Column ss:Width=\"200\" />\n<Row>\n <Cell><Data ss:Type=\"Number\">1</Data></Cell>\n <Cell><Data ss:Type=\"Number\">2</Data></Cell>\n</Row>\n<Row>\n <Cell><Data ss:Type=\"Number\">3</Data></Cell>\n <Cell><Data ss:Type=\"Number\">4</Data></Cell>\n</Row>\n<Row>\n <Cell><Data ss:Type=\"Number\">5</Data></Cell>\n <Cell><Data ss:Type=\"Number\">6</Data></Cell>\n</Row>\n<Row>\n <Cell><Data ss:Type=\"Number\">7</Data></Cell>\n <Cell><Data ss:Type=\"Number\">8</Data></Cell>\n</Row>\n</Table>\n</Worksheet>\n\n<Worksheet ss:Name=\"Sample Sheet 2\">\n<Table ss:ExpandedColumnCount=\"2\" x:FullColumns=\"1\" x:FullRows=\"1\" ID=\"Table2\">\n<Column ss:Width=\"150\" />\n<Column ss:Width=\"200\" />\n<Row>\n <Cell><Data ss:Type=\"String\">A</Data></Cell>\n <Cell><Data ss:Type=\"String\">B</Data></Cell>\n</Row>\n<Row>\n <Cell><Data ss:Type=\"String\">C</Data></Cell>\n <Cell><Data ss:Type=\"String\">D</Data></Cell>\n</Row>\n<Row>\n <Cell><Data ss:Type=\"String\">E</Data></Cell>\n <Cell><Data ss:Type=\"String\">F</Data></Cell>\n</Row>\n<Row>\n <Cell><Data ss:Type=\"String\">G</Data></Cell>\n <Cell><Data ss:Type=\"String\">H</Data></Cell>\n</Row>\n</Table>\n</Worksheet>\n</Workbook> \n" }, { "answer_id": 150370, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 2, "selected": false, "text": "Response.Clear();\nResponse.AddHeader(\"Content-Disposition\", \"attachment; filename=\" + fi.Name);\nResponse.AddHeader(\"Content-Length\", fi.Length.ToString());\nResponse.ContentType = \"application/octet-stream\";\nResponse.WriteFile(fi.FullName);\nResponse.End();\n" }, { "answer_id": 150377, "author": "Eduardo Campañó", "author_id": 12091, "author_profile": "https://Stackoverflow.com/users/12091", "pm_score": 1, "selected": false, "text": " Public Sub ExportToExcel(ByVal fileName As String, ByVal gv As GridView)\n\n HttpContext.Current.Response.Clear()\n HttpContext.Current.Response.AddHeader(\"content-disposition\", String.Format(\"attachment; filename={0}\", fileName))\n HttpContext.Current.Response.ContentType = \"application/ms-excel\"\n\n Dim sw As StringWriter = New StringWriter\n Dim htw As HtmlTextWriter = New HtmlTextWriter(sw)\n Dim table As Table = New Table\n\n table.GridLines = gv.GridLines\n\n If (Not (gv.HeaderRow) Is Nothing) Then\n PrepareControlForExport(gv.HeaderRow)\n table.Rows.Add(gv.HeaderRow)\n End If\n\n For Each row As GridViewRow In gv.Rows\n PrepareControlForExport(row)\n table.Rows.Add(row)\n Next\n\n If (Not (gv.FooterRow) Is Nothing) Then\n PrepareControlForExport(gv.FooterRow)\n table.Rows.Add(gv.FooterRow)\n End If\n\n table.RenderControl(htw)\n\n HttpContext.Current.Response.Write(sw.ToString)\n HttpContext.Current.Response.End()\n\n End Sub\n\n\n Private Sub PrepareControlForExport(ByVal control As Control)\n\n Dim i As Integer = 0\n\n Do While (i < control.Controls.Count)\n\n Dim current As Control = control.Controls(i)\n\n If (TypeOf current Is LinkButton) Then\n control.Controls.Remove(current)\n control.Controls.AddAt(i, New LiteralControl(CType(current, LinkButton).Text))\n\n ElseIf (TypeOf current Is ImageButton) Then\n control.Controls.Remove(current)\n control.Controls.AddAt(i, New LiteralControl(CType(current, ImageButton).AlternateText))\n\n ElseIf (TypeOf current Is HyperLink) Then\n control.Controls.Remove(current)\n control.Controls.AddAt(i, New LiteralControl(CType(current, HyperLink).Text))\n\n ElseIf (TypeOf current Is DropDownList) Then\n control.Controls.Remove(current)\n control.Controls.AddAt(i, New LiteralControl(CType(current, DropDownList).SelectedItem.Text))\n\n ElseIf (TypeOf current Is CheckBox) Then\n control.Controls.Remove(current)\n control.Controls.AddAt(i, New LiteralControl(CType(current, CheckBox).Checked))\n\n End If\n\n If current.HasControls Then\n PrepareControlForExport(current)\n End If\n\n i = i + 1\n\n Loop\n\n End Sub\n" }, { "answer_id": 153384, "author": "Dan Coates", "author_id": 18009, "author_profile": "https://Stackoverflow.com/users/18009", "pm_score": 3, "selected": false, "text": " Dim uiTable As HtmlTable = GetUiTable(groupedSumData)\n\n Response.Clear()\n\n Response.ContentType = \"application/vnd.ms-excel\"\n Response.AddHeader(\"Content-Disposition\", String.Format(\"inline; filename=OSSummery{0:ddmmssf}.xls\", DateTime.Now))\n\n Dim writer As New System.IO.StringWriter()\n Dim htmlWriter As New HtmlTextWriter(writer)\n uiTable.RenderControl(htmlWriter)\n Response.Write(writer.ToString)\n\n Response.End()\n" }, { "answer_id": 153518, "author": "Nasir", "author_id": 16522, "author_profile": "https://Stackoverflow.com/users/16522", "pm_score": 0, "selected": false, "text": " Workbook workbook = new Workbook();\n\n //Load workbook from disk.\n workbook.LoadFromFile(@\"Data\\EditSheetSample.xls\");\n //Initailize worksheet\n Worksheet sheet = workbook.Worksheets[0];\n\n //Writes string\n sheet.Range[\"B1\"].Text = \"Hello,World!\";\n //Writes number\n sheet.Range[\"B2\"].NumberValue = 1234.5678;\n //Writes date\n sheet.Range[\"B3\"].DateTimeValue = System.DateTime.Now;\n //Writes formula\n sheet.Range[\"B4\"].Formula = \"=1111*11111\";\n\n workbook.SaveToFile(\"Sample.xls\");\n" }, { "answer_id": 153613, "author": "WACM161", "author_id": 12255, "author_profile": "https://Stackoverflow.com/users/12255", "pm_score": 2, "selected": false, "text": "Response.ContentType = \"application/vnd.ms-excel\"\n Response.Charset = \"\"\n Response.AddHeader(\"content-disposition\", \"fileattachment;filename=YOURFILENAME.xls\")\n Me.EnableViewState = False\n Dim sw As System.IO.StringWriter = New System.IO.StringWriter\n Dim hw As HtmlTextWriter = New HtmlTextWriter(sw)\n ClearControls(grid)\n grid.RenderControl(hw)\n Response.Write(sw.ToString())\n Response.End()\n 'needed to export grid to excel to remove link button control and represent as text\nPrivate Sub ClearControls(ByVal control As Control)\n Dim i As Integer\n For i = control.Controls.Count - 1 To 0 Step -1\n ClearControls(control.Controls(i))\n Next i\n\n If TypeOf control Is System.Web.UI.WebControls.Image Then\n control.Parent.Controls.Remove(control)\n End If\n\n If (Not TypeOf control Is TableCell) Then\n If Not (control.GetType().GetProperty(\"SelectedItem\") Is Nothing) Then\n Dim literal As New LiteralControl\n control.Parent.Controls.Add(literal)\n Try\n literal.Text = CStr(control.GetType().GetProperty(\"SelectedItem\").GetValue(control, Nothing))\n Catch\n End Try\n control.Parent.Controls.Remove(control)\n Else\n If Not (control.GetType().GetProperty(\"Text\") Is Nothing) Then\n Dim literal As New LiteralControl\n control.Parent.Controls.Add(literal)\n literal.Text = CStr(control.GetType().GetProperty(\"Text\").GetValue(control, Nothing))\n control.Parent.Controls.Remove(control)\n End If\n End If\n End If\n Return\nEnd Sub\n" }, { "answer_id": 296948, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "oSheet.Cells(2, 1).copyfromrecordset(rst1)\n ‘Calls stored proc in SQL Server 2000 and puts data in Excel and ‘formats it\n\nPrivate Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click\n\n Dim cnn As ADODB.Connection\n cnn = New ADODB.Connection\n cnn.Open(\"Provider=SQLOLEDB;data source=xxxxxxx;\" & _\n \"database=xxxxxxxx;Trusted_Connection=yes;\")\n\n Dim cmd As New ADODB.Command\n\n\n cmd.ActiveConnection = cnn\n\n\n cmd.CommandText = \"[sp_TomTepley]\"\n cmd.CommandType = ADODB.CommandTypeEnum.adCmdStoredProc\n cmd.CommandTimeout = 0\n cmd.Parameters.Refresh()\n\n\n Dim rst1 As ADODB.Recordset\n rst1 = New ADODB.Recordset\n rst1.Open(cmd)\n\n Dim oXL As New Excel.Application\n Dim oWB As Excel.Workbook\n Dim oSheet As Excel.Worksheet\n\n 'oXL = CreateObject(\"excel.application\")\n oXL.Visible = True\n oWB = oXL.Workbooks.Add\n oSheet = oWB.ActiveSheet\n\n Dim Column As Integer\n Column = 1\n\n Dim fld As ADODB.Field\n For Each fld In rst1.Fields\n\n oXL.Workbooks(1).Worksheets(1).Cells(1, Column).Value = fld.Name\n oXL.Workbooks(1).Worksheets(1).cells(1, Column).Interior.ColorIndex = 15\n Column = Column + 1\n\n Next fld\n\n oXL.Workbooks(1).Worksheets(1).name = \"Tom Tepley Report\"\n oSheet.Cells(2, 1).copyfromrecordset(rst1)\n oXL.Workbooks(1).Worksheets(1).Cells.EntireColumn.AutoFit()\n\n\n oXL.Visible = True\n oXL.UserControl = True\n\n rst1 = Nothing\n\n cnn.Close()\n Beep()\n\n End Sub\n" }, { "answer_id": 1275554, "author": "Justin R.", "author_id": 4593, "author_profile": "https://Stackoverflow.com/users/4593", "pm_score": 0, "selected": false, "text": "public static void ExportToExcel(DataTable data, HttpResponse response, string fileName)\n{\n response.Charset = \"utf-8\";\n response.ContentEncoding = System.Text.Encoding.GetEncoding(\"windows-1250\");\n response.Cache.SetCacheability(HttpCacheability.NoCache);\n response.ContentType = \"text/csv\";\n response.AddHeader(\"Content-Disposition\", \"attachment; filename=\" + fileName);\n\n for (int i = 0; i < data.Columns.Count; i++)\n {\n response.Write(data.Columns[i].ColumnName);\n response.Write(i == data.Columns.Count - 1 ? \"\\n\" : \",\");\n } \n foreach (DataRow row in data.Rows)\n {\n for (int i = 0; i < data.Columns.Count; i++)\n {\n response.Write(String.Format(\"\\\"{0}\\\"\", row[i].ToString()));\n response.Write(i == data.Columns.Count - 1 ? \"\\n\" : \",\");\n }\n }\n\n response.End();\n}\n" }, { "answer_id": 16849646, "author": "Steve D Sousa", "author_id": 2438910, "author_profile": "https://Stackoverflow.com/users/2438910", "pm_score": -1, "selected": false, "text": " public void ExportFileFromSPData(string filename, DataTable dt)\n {\n HttpResponse response = HttpContext.Current.Response;\n\n //clean up the response.object\n response.Clear();\n response.Buffer = true;\n response.Charset = \"\";\n\n // set the response mime type for html so you can see what are you printing \n //response.ContentType = \"text/html\";\n //response.AddHeader(\"Content-Disposition\", \"attachment;filename=test.html\");\n\n // set the response mime type for excel\n response.ContentType = \"application/vnd.ms-excel\";\n response.AddHeader(\"Content-Disposition\", \"attachment;filename=\\\"\" + filename + \"\\\"\");\n response.ContentEncoding = System.Text.Encoding.UTF8;\n response.BinaryWrite(System.Text.Encoding.UTF8.GetPreamble());\n\n //style to format numbers to string\n string style = @\"<style> .text { mso-number-format:\\@; } </style>\";\n response.Write(style);\n\n // create a string writer\n using (StringWriter sw = new StringWriter())\n {\n using (HtmlTextWriter htw = new HtmlTextWriter(sw))\n {\n // instantiate a datagrid\n GridView dg = new GridView();\n dg.DataSource = dt;\n dg.DataBind();\n\n foreach (GridViewRow datarow in dg.Rows)\n {\n //format specific cell to be text \n //to avoid 1.232323+E29 to get 1232312312312312124124\n datarow.Cells[0].Attributes.Add(\"class\", \"text\");\n }\n\n dg.RenderControl(htw);\n response.Write(sw.ToString());\n response.End();\n }\n }\n }\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18009/" ]
150,341
<p>How do people approach mocking out TcpClient (or things like TcpClient)?</p> <p>I have a service that takes in a TcpClient. Should I wrap that in something else more mockable? How should I approach this?</p>
[ { "answer_id": 150480, "author": "Doron Yaacoby", "author_id": 3389, "author_profile": "https://Stackoverflow.com/users/3389", "pm_score": 6, "selected": true, "text": "public interface ITcpClient\n{\n Stream GetStream(); \n // Anything you need here \n}\npublic class TcpClientAdapter: ITcpClient\n{\n private TcpClient wrappedClient;\n public TcpClientAdapter(TcpClient client)\n {\n wrappedClient = client;\n }\n\n public Stream GetStream()\n {\n return wrappedClient.GetStream();\n }\n}\n" }, { "answer_id": 150592, "author": "casademora", "author_id": 5619, "author_profile": "https://Stackoverflow.com/users/5619", "pm_score": 3, "selected": false, "text": " [Test]\n public void TestInput(){\n\n NetworkInputSource mockInput = mocks.CreateMock<NetworkInputSource>();\n Consumer c = new Consumer(mockInput);\n\n c.ReadAll();\n // c.Read();\n // c.ReadLine();\n\n }\n\n public class TcpClientAdapter : NetworkInputSource\n {\n private TcpClient _client;\n public string ReadAll()\n { \n return new StreamReader(_tcpClient.GetStream()).ReadToEnd();\n }\n\n public string Read() { ... }\n public string ReadLine() { ... }\n }\n\n public interface NetworkInputSource\n {\n public string ReadAll(); \n public string Read();\n public string ReadLine();\n }\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150341", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3285/" ]
150,355
<p>Is there a way to determine how many cores a machine has from C/C++ in a platform-independent way? If no such thing exists, what about determining it per-platform (Windows/*nix/Mac)?</p>
[ { "answer_id": 150393, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 8, "selected": false, "text": "#include <thread>\n\nunsigned int nthreads = std::thread::hardware_concurrency();\n #include <boost/thread.hpp>\n\nunsigned int nthreads = boost::thread::hardware_concurrency();\n hardware_concurrency()" }, { "answer_id": 150394, "author": "Evan Teran", "author_id": 13430, "author_profile": "https://Stackoverflow.com/users/13430", "pm_score": 2, "selected": false, "text": "sysconf(_SC_NPROCESSORS_CONF)\n sysconf(_SC_NPROCESSORS_ONLN)\n" }, { "answer_id": 150971, "author": "oz10", "author_id": 14069, "author_profile": "https://Stackoverflow.com/users/14069", "pm_score": 11, "selected": true, "text": "#include <thread>\n\n//may return 0 when not able to detect\nconst auto processor_count = std::thread::hardware_concurrency();\n #ifdef SYSTEM_INFO sysinfo;\nGetSystemInfo(&sysinfo);\nint numCPU = sysinfo.dwNumberOfProcessors;\n int numCPU = sysconf(_SC_NPROCESSORS_ONLN);\n int mib[4];\nint numCPU;\nstd::size_t len = sizeof(numCPU); \n\n/* set the mib for hw.ncpu */\nmib[0] = CTL_HW;\nmib[1] = HW_AVAILCPU; // alternatively, try HW_NCPU;\n\n/* get the number of CPUs from the system */\nsysctl(mib, 2, &numCPU, &len, NULL, 0);\n\nif (numCPU < 1) \n{\n mib[1] = HW_NCPU;\n sysctl(mib, 2, &numCPU, &len, NULL, 0);\n if (numCPU < 1)\n numCPU = 1;\n}\n int numCPU = mpctl(MPC_GETNUMSPUS, NULL, NULL);\n int numCPU = sysconf(_SC_NPROC_ONLN);\n NSUInteger a = [[NSProcessInfo processInfo] processorCount];\nNSUInteger b = [[NSProcessInfo processInfo] activeProcessorCount];\n" }, { "answer_id": 197200, "author": "macbirdie", "author_id": 5049, "author_profile": "https://Stackoverflow.com/users/5049", "pm_score": 6, "selected": false, "text": "int omp_get_num_procs();\n" }, { "answer_id": 197917, "author": "Constantin", "author_id": 20310, "author_profile": "https://Stackoverflow.com/users/20310", "pm_score": 3, "selected": false, "text": "NUMBER_OF_PROCESSORS printf(\"%d\\n\", atoi(getenv(\"NUMBER_OF_PROCESSORS\")));\n" }, { "answer_id": 3006416, "author": "Dirk-Jan Kroon", "author_id": 362493, "author_profile": "https://Stackoverflow.com/users/362493", "pm_score": 5, "selected": false, "text": "#ifdef _WIN32\n#include <windows.h>\n#elif MACOS\n#include <sys/param.h>\n#include <sys/sysctl.h>\n#else\n#include <unistd.h>\n#endif\n\nint getNumCores() {\n#ifdef WIN32\n SYSTEM_INFO sysinfo;\n GetSystemInfo(&sysinfo);\n return sysinfo.dwNumberOfProcessors;\n#elif MACOS\n int nm[2];\n size_t len = 4;\n uint32_t count;\n\n nm[0] = CTL_HW; nm[1] = HW_AVAILCPU;\n sysctl(nm, 2, &count, &len, NULL, 0);\n\n if(count < 1) {\n nm[1] = HW_NCPU;\n sysctl(nm, 2, &count, &len, NULL, 0);\n if(count < 1) { count = 1; }\n }\n return count;\n#else\n return sysconf(_SC_NPROCESSORS_ONLN);\n#endif\n}\n" }, { "answer_id": 5382362, "author": "Chris", "author_id": 385711, "author_profile": "https://Stackoverflow.com/users/385711", "pm_score": 3, "selected": false, "text": "grep processor /proc/cpuinfo | wc -l\n" }, { "answer_id": 12239411, "author": "sezero", "author_id": 1642354, "author_profile": "https://Stackoverflow.com/users/1642354", "pm_score": 3, "selected": false, "text": "sysconf(_SC_NPROCESSORS_ONLN) HW_AVAILCPU/sysctl()" }, { "answer_id": 24127920, "author": "P.P", "author_id": 1275169, "author_profile": "https://Stackoverflow.com/users/1275169", "pm_score": 2, "selected": false, "text": "_SC_NPROCESSORS_ONLN _SC_NPROCESSORS_ONLN These values also exist, but may not be standard.\n\n [...] \n\n - _SC_NPROCESSORS_CONF\n The number of processors configured. \n - _SC_NPROCESSORS_ONLN\n The number of processors currently online (available).\n /proc/stat /proc/cpuinfo #include<unistd.h>\n#include<stdio.h>\n\nint main(void)\n{\nchar str[256];\nint procCount = -1; // to offset for the first entry\nFILE *fp;\n\nif( (fp = fopen(\"/proc/stat\", \"r\")) )\n{\n while(fgets(str, sizeof str, fp))\n if( !memcmp(str, \"cpu\", 3) ) procCount++;\n}\n\nif ( procCount == -1) \n{ \nprintf(\"Unable to get proc count. Defaulting to 2\");\nprocCount=2;\n}\n\nprintf(\"Proc Count:%d\\n\", procCount);\nreturn 0;\n}\n /proc/cpuinfo #include<unistd.h>\n#include<stdio.h>\n\nint main(void)\n{\nchar str[256];\nint procCount = 0;\nFILE *fp;\n\nif( (fp = fopen(\"/proc/cpuinfo\", \"r\")) )\n{\n while(fgets(str, sizeof str, fp))\n if( !memcmp(str, \"processor\", 9) ) procCount++;\n}\n\nif ( !procCount ) \n{ \nprintf(\"Unable to get proc count. Defaulting to 2\");\nprocCount=2;\n}\n\nprintf(\"Proc Count:%d\\n\", procCount);\nreturn 0;\n}\n grep -c ^processor /proc/cpuinfo\n grep -c ^cpu /proc/stat # subtract 1 from the result\n" }, { "answer_id": 44247223, "author": "Matthias", "author_id": 1731200, "author_profile": "https://Stackoverflow.com/users/1731200", "pm_score": 3, "selected": false, "text": "size_t NumberOfPhysicalCores() noexcept {\n\n DWORD length = 0;\n const BOOL result_first = GetLogicalProcessorInformationEx(RelationProcessorCore, nullptr, &length);\n assert(GetLastError() == ERROR_INSUFFICIENT_BUFFER);\n\n std::unique_ptr< uint8_t[] > buffer(new uint8_t[length]);\n const PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX info = \n reinterpret_cast< PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX >(buffer.get());\n\n const BOOL result_second = GetLogicalProcessorInformationEx(RelationProcessorCore, info, &length);\n assert(result_second != FALSE);\n\n size_t nb_physical_cores = 0;\n size_t offset = 0;\n do {\n const PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX current_info =\n reinterpret_cast< PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX >(buffer.get() + offset);\n offset += current_info->Size;\n ++nb_physical_cores;\n } while (offset < length);\n \n return nb_physical_cores;\n}\n NumberOfPhysicalCores GetLogicalProcessorInformation GetLogicalProcessorInformationEx GetLogicalProcessorInformation GetLogicalProcessorInformationEx size_t NumberOfSystemCores() noexcept {\n SYSTEM_INFO system_info;\n ZeroMemory(&system_info, sizeof(system_info));\n \n GetSystemInfo(&system_info);\n \n return static_cast< size_t >(system_info.dwNumberOfProcessors);\n}\n" }, { "answer_id": 69214269, "author": "Arran Cudbard-Bell", "author_id": 2117998, "author_profile": "https://Stackoverflow.com/users/2117998", "pm_score": 0, "selected": false, "text": "#include <stdint.h>\n\n#if defined(__APPLE__) || defined(__FreeBSD__)\n#include <sys/sysctl.h>\n\nuint32_t num_physical_cores(void)\n{\n uint32_t num_cores = 0;\n size_t num_cores_len = sizeof(num_cores);\n\n sysctlbyname(\"hw.physicalcpu\", &num_cores, &num_cores_len, 0, 0);\n\n return num_cores;\n}\n#elif defined(__linux__)\n#include <unistd.h>\n#include <stdio.h>\nuint32_t num_physical_cores(void)\n{\n uint32_t lcores = 0, tsibs = 0;\n\n char buff[32];\n char path[64];\n\n for (lcores = 0;;lcores++) {\n FILE *cpu;\n\n snprintf(path, sizeof(path), \"/sys/devices/system/cpu/cpu%u/topology/thread_siblings_list\", lcores);\n\n cpu = fopen(path, \"r\");\n if (!cpu) break;\n\n while (fscanf(cpu, \"%[0-9]\", buff)) {\n tsibs++;\n if (fgetc(cpu) != ',') break;\n }\n\n fclose(cpu);\n }\n\n return lcores / (tsibs / lcores);\n}\n#else\n#error Unrecognized operating system\n#endif\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5066/" ]
150,359
<p>I'm trying to use Exchange Web Services to update a calendar item. I'm creating an ItemChangeType, and then an ItemIdType. I have a unique ID to use for ItemIdType.Id, but I have nothing to use for the ChangeKey. When I leave it out, I get an ErrorChangeKeyRequiredForWriteOperations. But when i try to just put something in there, I get an ErrorInvalidChangeKey. </p> <p>What can I use for this to get it to work?</p> <p>I'm also trying to determine what is the best implementation of BaseItemIdType to use for ItemChangeType.Item. So far, I'm using ItemIdType, and I'm guessing that's correct, but I haven't been able to find any particularly helpful documentation on this.</p>
[ { "answer_id": 289684, "author": "Hauge", "author_id": 17368, "author_profile": "https://Stackoverflow.com/users/17368", "pm_score": 2, "selected": false, "text": "ItemIdType.ChangeKey" }, { "answer_id": 1286796, "author": "Ivan G.", "author_id": 80858, "author_profile": "https://Stackoverflow.com/users/80858", "pm_score": 1, "selected": false, "text": " private FolderIdType GetFullFolderID(string folderID)\n {\n GetFolderType request = new GetFolderType();\n request.FolderIds = new BaseFolderIdType[1];\n\n FolderIdType id = new FolderIdType();\n id.Id = folderID;\n request.FolderIds[0] = id;\n\n request.FolderShape = new FolderResponseShapeType();\n request.FolderShape.BaseShape = DefaultShapeNamesType.IdOnly;\n\n GetFolderResponseType response = _binding.GetFolder(request);\n\n FailOnError(response);\n\n FolderInfoResponseMessageType firmt = (FolderInfoResponseMessageType)response.ResponseMessages.Items[0];\n FolderType ft = (FolderType)firmt.Folders[0];\n id.ChangeKey = ft.FolderId.ChangeKey;\n\n return id;\n }\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3018/" ]
150,375
<p>What do you insert into Python source code to have it break into pdb (when execution gets to that spot)? </p>
[ { "answer_id": 150376, "author": "Daryl Spitzer", "author_id": 4766, "author_profile": "https://Stackoverflow.com/users/4766", "pm_score": 6, "selected": true, "text": "import pdb; pdb.set_trace()\n" }, { "answer_id": 59365802, "author": "Adam Baxter", "author_id": 229631, "author_profile": "https://Stackoverflow.com/users/229631", "pm_score": 4, "selected": false, "text": "breakpoint()" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4766/" ]
150,384
<p>I have a website in which I provide tool-tips for certain things using a hidden <code>&lt;span&gt;</code> tag and JavaScript to track various mouse events. It works excellently. This site somewhat caters towards people with vision issues, so I try to make things degrade as well as possible if there is no JavaScript or CSS and generally I would say that it is successful in this regard.</p> <p>So my question is, is it possible for these <code>&lt;span&gt;</code> to only exist if CSS is being used? I have thought about writing out the tool-tips in JavaScript on document load. But I was wondering if there is a better solution.</p>
[ { "answer_id": 150391, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 3, "selected": true, "text": "<span>" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150384", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13430/" ]
150,404
<p>The examples I've seen online seem much more complex than I expected <em>(manually parsing &amp;/?/= into pairs, using regular expressions, etc).</em> We're using asp.net ajax <em>(don't see anything in their client side reference)</em> and would consider adding jQuery if it would really help.</p> <p>I would think there is a more elegant solution out there - so far <a href="http://www.bloggingdeveloper.com/post/JavaScript-QueryString-ParseGet-QueryString-with-Client-Side-JavaScript.aspx" rel="noreferrer">this is the best code I've found</a> but I would love to find something more along the lines of the HttpRequest.QueryString object <em>(asp.net server side)</em>. Thanks in advance,</p> <p>Shane</p>
[ { "answer_id": 403463, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "window.location.search.parseQuery();\n" }, { "answer_id": 3388168, "author": "Chris Jacob", "author_id": 114140, "author_profile": "https://Stackoverflow.com/users/114140", "pm_score": 2, "selected": false, "text": "// Parse URL, deserializing query string into an object.\n// http://www.example.com/foo.php?a=1&b=2&c=hello#test\n// search is set to ?a=1&b=2&c=hello\n// myObj is set to { a:\"1\", b:\"2\", c:\"hello\" }\nvar search = window.location.search;\nvar myObj = $.deparam.querystring( search );\n" }, { "answer_id": 3388227, "author": "Amr Elgarhy", "author_id": 20126, "author_profile": "https://Stackoverflow.com/users/20126", "pm_score": 3, "selected": false, "text": "function getQueryVariable(variable) {\n var query = window.location.search.substring(1);\n var vars = query.split(\"&\");\n for (var i = 0; i < vars.length; i++) {\n var pair = vars[i].split(\"=\");\n if (pair[0] == variable) {\n return pair[1];\n }\n }\n return null;\n}\n" }, { "answer_id": 11844910, "author": "Sunil Marwaha", "author_id": 1581795, "author_profile": "https://Stackoverflow.com/users/1581795", "pm_score": 1, "selected": false, "text": " *$(document).ready(function () {\n $(\"#a\").click(function () {\n window.location.href = \"secondpage.aspx?id='0' & name='sunil'& add='asr' & phone='1234'\";\n });\n });*\n\n\n**then read the query string parameters on another using split method . Here as follows:**\n\n\n *$(document).ready(function () {\n var a = decodeURI(window.location.search);\n var id = window.location.search = \"id=\" + $().val();\n var name = a.split(\"name=\")[1].split(\"&\")[0].split(\"'\")[1];\n var phone = a.split(\"phone=\")[1].split(\"&\")[0].split(\"'\")[1];\n var add = a.split(\"add=\")[1].split(\"&\")[0].split(\"'\")[1];\n alert(id+','+name+','+add+','+phone); \n });*\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150404", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21261/" ]
150,416
<p>With our next major release we are looking to globalize our ASP.Net application and I was asked to think of a way to keep track of what code has been already worked on in this effort. </p> <p>My thought was to use a custom Attribute and place it on all classes that have been "fixed".</p> <p>What do you think? </p> <p>Does anyone have a better idea?</p>
[ { "answer_id": 188774, "author": "Jason Z", "author_id": 2470, "author_profile": "https://Stackoverflow.com/users/2470", "pm_score": 0, "selected": false, "text": "foreach (System.Web.UI.Control c in Page.Controls)\n{\n //Do work here\n}\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150416", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5551/" ]
150,423
<p>What's the accepted way of storing quoted data in XML?</p> <p>For example, for a node, which is correct?</p> <ul> <li>(a) &lt;name&gt;Jesse "The Body" Ventura&lt;/name&gt;</li> <li>(b) &lt;name&gt;Jesse \"The Body\" Ventura&lt;/name&gt;</li> <li>(c) &lt;name&gt;Jesse &amp;quot;The Body&amp;quot; Ventura&lt;/name&gt;</li> <li>(d) none of the above (please specify)</li> </ul> <p>If (a), what do you do for attributes? If (c), is it really appropriate to mix HTML &amp; XML? Similarly, how do you handle single and curly quotes?</p>
[ { "answer_id": 150441, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 5, "selected": false, "text": "\" > < & ' \" \" ' \" '" }, { "answer_id": 150537, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 0, "selected": false, "text": "<name>\n <given>Jesse</given>\n <family>Ventura</family>\n <nickName>the Body</nickName>\n</name>\n" }, { "answer_id": 150634, "author": "Robert Rossney", "author_id": 19403, "author_profile": "https://Stackoverflow.com/users/19403", "pm_score": 3, "selected": false, "text": "&quot; &quot;" }, { "answer_id": 150748, "author": "Pete Kirkham", "author_id": 1527, "author_profile": "https://Stackoverflow.com/users/1527", "pm_score": 2, "selected": false, "text": "<foo attribute=\"'ok'\" attribute2='\"also-ok\"' attribute3=\"&quot;needed&quot;\"/>\n <xsl:value-of select=\"person[@name = 'bob']\"/>\n <xsl:value-of select=\"person[@name = &apos;bob&apos;\"/>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150423", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
150,446
<p>I want to react when somebody shakes the iPhone. I don't particularly care how they shake it, just that it was waved vigorously about for a split second. Does anyone know how to detect this?</p>
[ { "answer_id": 159610, "author": "millenomi", "author_id": 6061, "author_profile": "https://Stackoverflow.com/users/6061", "pm_score": 7, "selected": false, "text": "// Ensures the shake is strong enough on at least two axes before declaring it a shake.\n// \"Strong enough\" means \"greater than a client-supplied threshold\" in G's.\nstatic BOOL L0AccelerationIsShaking(UIAcceleration* last, UIAcceleration* current, double threshold) {\n double\n deltaX = fabs(last.x - current.x),\n deltaY = fabs(last.y - current.y),\n deltaZ = fabs(last.z - current.z);\n\n return\n (deltaX > threshold && deltaY > threshold) ||\n (deltaX > threshold && deltaZ > threshold) ||\n (deltaY > threshold && deltaZ > threshold);\n}\n\n@interface L0AppDelegate : NSObject <UIApplicationDelegate> {\n BOOL histeresisExcited;\n UIAcceleration* lastAcceleration;\n}\n\n@property(retain) UIAcceleration* lastAcceleration;\n\n@end\n\n@implementation L0AppDelegate\n\n- (void)applicationDidFinishLaunching:(UIApplication *)application {\n [UIAccelerometer sharedAccelerometer].delegate = self;\n}\n\n- (void) accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {\n\n if (self.lastAcceleration) {\n if (!histeresisExcited && L0AccelerationIsShaking(self.lastAcceleration, acceleration, 0.7)) {\n histeresisExcited = YES;\n\n /* SHAKE DETECTED. DO HERE WHAT YOU WANT. */\n\n } else if (histeresisExcited && !L0AccelerationIsShaking(self.lastAcceleration, acceleration, 0.2)) {\n histeresisExcited = NO;\n }\n }\n\n self.lastAcceleration = acceleration;\n}\n\n// and proper @synthesize and -dealloc boilerplate code\n\n@end\n" }, { "answer_id": 278523, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {\n if (self.lastAcceleration) {\n if ([self AccelerationIsShakingLast:self.lastAcceleration current:acceleration threshold:0.7] && shakeCount >= 9) {\n //Shaking here, DO stuff.\n shakeCount = 0;\n } else if ([self AccelerationIsShakingLast:self.lastAcceleration current:acceleration threshold:0.7]) {\n shakeCount = shakeCount + 5;\n }else if (![self AccelerationIsShakingLast:self.lastAcceleration current:acceleration threshold:0.2]) {\n if (shakeCount > 0) {\n shakeCount--;\n }\n }\n }\n self.lastAcceleration = acceleration;\n}\n\n- (BOOL) AccelerationIsShakingLast:(UIAcceleration *)last current:(UIAcceleration *)current threshold:(double)threshold {\n double\n deltaX = fabs(last.x - current.x),\n deltaY = fabs(last.y - current.y),\n deltaZ = fabs(last.z - current.z);\n\n return\n (deltaX > threshold && deltaY > threshold) ||\n (deltaX > threshold && deltaZ > threshold) ||\n (deltaY > threshold && deltaZ > threshold);\n}\n [[UIAccelerometer sharedAccelerometer] setUpdateInterval:(1.0 / 15)];\n" }, { "answer_id": 671623, "author": "Benjamin Ortuzar", "author_id": 71560, "author_profile": "https://Stackoverflow.com/users/71560", "pm_score": 3, "selected": false, "text": "#define kAccelerationThreshold 2.2\n\n#pragma mark -\n#pragma mark UIAccelerometerDelegate Methods\n - (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration \n { \n if (fabsf(acceleration.x) > kAccelerationThreshold || fabsf(acceleration.y) > kAccelerationThreshold || fabsf(acceleration.z) > kAccelerationThreshold) \n [self myShakeMethodGoesHere]; \n }\n" }, { "answer_id": 1111983, "author": "Kendall Helmstetter Gelner", "author_id": 6330, "author_profile": "https://Stackoverflow.com/users/6330", "pm_score": 9, "selected": true, "text": "@implementation ShakingView\n\n- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event\n{\n if ( event.subtype == UIEventSubtypeMotionShake )\n {\n // Put in code here to handle shake\n }\n\n if ( [super respondsToSelector:@selector(motionEnded:withEvent:)] )\n [super motionEnded:motion withEvent:event];\n}\n\n- (BOOL)canBecomeFirstResponder\n{ return YES; }\n\n@end\n - (void) viewWillAppear:(BOOL)animated\n{\n [shakeView becomeFirstResponder];\n [super viewWillAppear:animated];\n}\n- (void) viewWillDisappear:(BOOL)animated\n{\n [shakeView resignFirstResponder];\n [super viewWillDisappear:animated];\n}\n" }, { "answer_id": 1294476, "author": "Newtz", "author_id": 158522, "author_profile": "https://Stackoverflow.com/users/158522", "pm_score": 3, "selected": false, "text": "viewDidLoad [view becomeFirstResponder] becomeFirstResponder resignFirstResponder self" }, { "answer_id": 1351486, "author": "Joe D'Andrea", "author_id": 126660, "author_profile": "https://Stackoverflow.com/users/126660", "pm_score": 7, "selected": false, "text": "MotionWindow : UIWindow - (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {\n if (event.type == UIEventTypeMotion && event.subtype == UIEventSubtypeMotionShake) {\n [[NSNotificationCenter defaultCenter] postNotificationName:@\"DeviceShaken\" object:self];\n }\n}\n @\"DeviceShaken\" [[NSNotificationCenter defaultCenter] addObserver:self\nselector:@selector(deviceShaken) name:@\"DeviceShaken\" object:nil];\n [[NSNotificationCenter defaultCenter] removeObserver:self];\n" }, { "answer_id": 2405692, "author": "Eran Talmor", "author_id": 2944908, "author_profile": "https://Stackoverflow.com/users/2944908", "pm_score": 7, "selected": false, "text": "\n - (void)applicationDidFinishLaunching:(UIApplication *)application {\n\n application.applicationSupportsShakeToEdit = YES;\n\n [window addSubview:viewController.view];\n [window makeKeyAndVisible];\n}\n \n-(BOOL)canBecomeFirstResponder {\n return YES;\n}\n\n-(void)viewDidAppear:(BOOL)animated {\n [super viewDidAppear:animated];\n [self becomeFirstResponder];\n}\n\n- (void)viewWillDisappear:(BOOL)animated {\n [self resignFirstResponder];\n [super viewWillDisappear:animated];\n}\n \n- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event\n{\n if (motion == UIEventSubtypeMotionShake)\n {\n // your code\n }\n}\n" }, { "answer_id": 12895399, "author": "Himanshu Mahajan", "author_id": 1624283, "author_profile": "https://Stackoverflow.com/users/1624283", "pm_score": 3, "selected": false, "text": " -(BOOL) canBecomeFirstResponder\n {\n /* Here, We want our view (not viewcontroller) as first responder \n to receive shake event message */\n\n return YES;\n }\n\n -(void) motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event\n {\n if(event.subtype==UIEventSubtypeMotionShake)\n {\n // Code at shake event\n\n UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@\"Motion\" message:@\"Phone Vibrate\"delegate:self cancelButtonTitle:@\"OK\" otherButtonTitles: nil];\n [alert show];\n [alert release];\n\n [self.view setBackgroundColor:[UIColor redColor]];\n }\n }\n - (void)viewDidAppear:(BOOL)animated\n {\n [super viewDidAppear:animated];\n [self becomeFirstResponder]; // View as first responder \n }\n" }, { "answer_id": 14998702, "author": "Mashhadi", "author_id": 339171, "author_profile": "https://Stackoverflow.com/users/339171", "pm_score": 1, "selected": false, "text": "- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event{\n- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event{\n- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event{\n" }, { "answer_id": 24713067, "author": "mxcl", "author_id": 6444, "author_profile": "https://Stackoverflow.com/users/6444", "pm_score": 2, "selected": false, "text": "@implementation OMGWindow : UIWindow\n\n- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {\n if (event.type == UIEventTypeMotion && motion == UIEventSubtypeMotionShake) {\n // via notification or something \n }\n}\n@end\n - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {\n self.window = [[OMGWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];\n //…\n}\n" }, { "answer_id": 29035489, "author": "Dennis", "author_id": 1770453, "author_profile": "https://Stackoverflow.com/users/1770453", "pm_score": 3, "selected": false, "text": "- (BOOL)canBecomeFirstResponder {\n return YES;\n}\n\n- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event\n{\n if (motion == UIEventSubtypeMotionShake) {\n // Shake detected.\n }\n}\n" }, { "answer_id": 29759696, "author": "nhgrif", "author_id": 2792531, "author_profile": "https://Stackoverflow.com/users/2792531", "pm_score": 4, "selected": false, "text": "motionBegan motionEnded class ViewController: UIViewController {\n override func motionBegan(motion: UIEventSubtype, withEvent event: UIEvent) {\n println(\"started shaking!\")\n }\n\n override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent) {\n println(\"ended shaking!\")\n }\n}\n" }, { "answer_id": 46138429, "author": "user3069232", "author_id": 3069232, "author_profile": "https://Stackoverflow.com/users/3069232", "pm_score": 1, "selected": false, "text": "override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) {\n if ( event?.subtype == .motionShake )\n {\n print(\"stop shaking me!\")\n }\n}\n" }, { "answer_id": 46246551, "author": "Mike", "author_id": 3132984, "author_profile": "https://Stackoverflow.com/users/3132984", "pm_score": -1, "selected": false, "text": "@implementation UIWindow (Utils)\n\n- (BOOL)canBecomeFirstResponder\n{\n return YES;\n}\n\n- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event\n{\n if (motion == UIEventSubtypeMotionShake) {\n // Do whatever you want here...\n }\n}\n\n@end\n" }, { "answer_id": 65879592, "author": "Amit Baderia", "author_id": 1737989, "author_profile": "https://Stackoverflow.com/users/1737989", "pm_score": 0, "selected": false, "text": "override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) {\n if motion == .motionShake \n {\n print(\"shaking\")\n }\n}\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150446", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7944/" ]
150,454
<p>In light of Michael Carman's comment, I have decided to rewrite the question. Note that 11 comments appear before this edit, and give credence to Michael's observation that I did not write the question in a way that made it clear what I was asking. <hr/> <em>Question:</em> What is the standard--or <em>cleanest</em> way--to fake the special status that <code>$a</code> and <code>$b</code> have in regard to strict by simply importing a module? </p> <p>First of all some setup. The following works: </p> <pre><code>#!/bin/perl use strict; print "\$a=$a\n"; print "\$b=$b\n"; </code></pre> <p>If I add one more line: </p> <pre><code>print "\$c=$c\n"; </code></pre> <p>I get an error at compile time, which means that none of my <em>dazzling</em> print code gets to run. </p> <p>If I comment out <code>use strict;</code> it runs fine. Outside of strictures, <code>$a</code> and <code>$b</code> are mainly special in that <code>sort</code> passes the two values to be compared with those names. </p> <pre><code>my @reverse_order = sort { $b &lt;=&gt; $a } @unsorted; </code></pre> <p>Thus the main <em>functional</em> difference about <code>$a</code> and <code>$b</code>--even though Perl "knows their names"--is that you'd better know this when you sort, or use some of the functions in <a href="http://search.cpan.org/module?List::Util" rel="nofollow noreferrer">List::Util</a>. </p> <p>It's only when you use strict, that <code>$a</code> and <code>$b</code> become special variables in a whole new way. They are the only variables that strict will pass over without complaining that they are not declared.</p> <p><em>:</em> Now, I like strict, but it strikes me that if TIMTOWTDI (There is more than one way to do it) is Rule #1 in Perl, this is not very TIMTOWDI. It says that <code>$a</code> and <code>$b</code> are special and that's it. If you want to use variables you don't have to declare <code>$a</code> and <code>$b</code> are your guys. If you want to have three variables by adding <code>$c</code>, suddenly there's a whole other way to do it.</p> <p>Nevermind that in manipulating hashes <code>$k</code> and <code>$v</code> might make more sense:</p> <pre><code>my %starts_upper_1_to_25 = skim { $k =~ m/^\p{IsUpper}/ &amp;&amp; ( 1 &lt;= $v &amp;&amp; $v &lt;= 25 ) } %my_hash ;` </code></pre> <p>Now, I use and I like strict. But I just want <code>$k</code> and <code>$v</code> to be visible to <code>skim</code> for the most compact syntax. And I'd like it to be visible simply by </p> <pre><code>use Hash::Helper qw&lt;skim&gt;; </code></pre> <p>I'm not asking this question to know how to black-magic it. My "answer" below, should let you know that I know enough Perl to be dangerous. I'm asking if there is a way to make strict accept other variables, or what is the <em>cleanest</em> solution. The answer could well be no. If that's the case, it simply does not seem very TIMTOWTDI. </p>
[ { "answer_id": 150483, "author": "moritz", "author_id": 14132, "author_profile": "https://Stackoverflow.com/users/14132", "pm_score": 1, "selected": false, "text": "$a $b $k $v use strict;\nour ($k, $v);\n $k $v" }, { "answer_id": 150485, "author": "dsm", "author_id": 7780, "author_profile": "https://Stackoverflow.com/users/7780", "pm_score": 2, "selected": false, "text": "use vars qw($a $b); # Pre-5.6\n our ($a, $b); # 5.6 +\n" }, { "answer_id": 150523, "author": "zigdon", "author_id": 4913, "author_profile": "https://Stackoverflow.com/users/4913", "pm_score": 3, "selected": false, "text": "Because of their special use by sort(), the variables $a and $b are \nexempted from this check.\n" }, { "answer_id": 150527, "author": "runrig", "author_id": 10415, "author_profile": "https://Stackoverflow.com/users/10415", "pm_score": 2, "selected": false, "text": "our ($k, $v);\n use vars qw($k $v);\n my %hash;\nmy ($k,$v);\nwhile (<>) {\n /^KEY=(.*)/ and $k = $1 and next;\n /^VALUE=(.*)/ and $v = $1;\n $hash{$k} = $v;\n print \"$k $v\\n\";\n}\n\n__END__\nKEY=a\nVALUE=1\nKEY=b\nVALUE=2\n $main::k=\"foo\";\n$main::v=\"bar\";\n%main::hash{$k}=$v;\n" }, { "answer_id": 150612, "author": "zigdon", "author_id": 4913, "author_profile": "https://Stackoverflow.com/users/4913", "pm_score": -1, "selected": false, "text": "use strict;\n\npackage Test; \nuse Exporter;\n\nmy @ISA = qw/Exporter/; \nmy $c = 3; \nmy @EXPORT = qw/$c/; \n\npackage main; \nprint $c;\n" }, { "answer_id": 150997, "author": "Dave Sherohman", "author_id": 18914, "author_profile": "https://Stackoverflow.com/users/18914", "pm_score": 2, "selected": false, "text": "package SpecialK;\n\nuse strict;\n\nuse base 'Exporter';\nBEGIN {\n our @EXPORT = qw( $k );\n}\n\nour $k;\n\n1;\n" }, { "answer_id": 151042, "author": "Eevee", "author_id": 17875, "author_profile": "https://Stackoverflow.com/users/17875", "pm_score": 1, "selected": false, "text": "List::MoreUtils use strict;\nmy @a = (1, 2);\nmy @b = (3, 4);\nmy @x = pairwise { $a + $b } @a, @b;\n pairwise List::MoreUtils $a $b" }, { "answer_id": 151045, "author": "Axeman", "author_id": 11289, "author_profile": "https://Stackoverflow.com/users/11289", "pm_score": 1, "selected": false, "text": "package Special;\nuse base qw<Exporter>;\n# use staging; -> commented out, my module for development\nour $c;\n\nour @EXPORT = qw<manip_c>;\n\nsub import { \n *{caller().'::c'} = *c;\n my $import_sub = Exporter->can( 'import' );\n goto &$import_sub;\n } \n package main;\nuse feature 'say';\nuse strict;\nuse Special;\nuse strict;\nsay \"In main: \\$c=$c\";\n\nmanip_c( 'f', sub {\n say \"In anon sub: \\$c=$c\\n\"; # In anon sub: $c=f\n});\n\nsay \"In main: \\$c=$c\";\n" }, { "answer_id": 151200, "author": "draegtun", "author_id": 12195, "author_profile": "https://Stackoverflow.com/users/12195", "pm_score": 1, "selected": false, "text": "use strict;\nuse warnings;\nuse feature qw/say/;\n\nsub hash_baz (&@) {\n my $code = shift; \n my $caller = caller;\n my %hash = (); \n use vars qw($k $v);\n\n no strict 'refs';\n local *{ $caller . '::k' } = \\my $k;\n local *{ $caller . '::v' } = \\my $v;\n\n while ( @_ ) {\n $k = shift;\n $v = shift;\n $hash{ $k } = $code->() || $v;\n }\n\n return %hash;\n}\n\nmy %hash = ( \n blue_cat => 'blue', \n purple_dog => 'purple', \n ginger_cat => 'ginger', \n purple_cat => 'purple' );\n\nmy %new_hash = hash_baz { uc $v if $k =~ m/purple/ } %hash;\n\nsay \"@{[ %new_hash ]}\";\n\n# => purple_dog PURPLE ginger_cat ginger purple_cat PURPLE blue_cat blue\n" }, { "answer_id": 153717, "author": "Michael Carman", "author_id": 8233, "author_profile": "https://Stackoverflow.com/users/8233", "pm_score": 3, "selected": true, "text": "package Foo;\nuse strict;\nuse warnings;\n\nrequire Exporter;\nour @ISA = qw(Exporter);\nour @EXPORT = qw(*k *v hashmap);\nour ($k, $v);\n\nsub hashmap(&\\%) {\n my $code = shift;\n my $hash = shift;\n\n while (local ($k, $v) = each %$hash) {\n $code->();\n }\n}\n *k *v $k $v local hashmap k v %k @v use Foo; # exports $k and $v\n\nmy %h = (a => 1, b => 2, c => 3);\n\nhashmap { print \"$k => $v\\n\" } %h;\n\n__END__\nc => 3\na => 1\nb => 2\n" }, { "answer_id": 155708, "author": "Sam Kington", "author_id": 6832, "author_profile": "https://Stackoverflow.com/users/6832", "pm_score": 1, "selected": false, "text": " DB<1> @foo = sort { $b cmp $a } qw(foo bar baz wibble);\n\n DB<2> x @foo\n0 'wibble'\n1 'foo'\n2 'baz'\n3 'bar'\n DB<3> x $a\n0 undef\n DB<4> x $b\n0 undef\n my %starts_upper_1_to_25 \n = skim { $k =~ m/^\\p{IsUpper}/ && ( 1 <= $v && $v <= 25 ) } %my_hash\n;\n my %starts_upper_1_to_25\n = map { my $k = $_; my $v = $my_hash{$v};\n $k =~ m/^\\p{IsUpper}/ && ( 1 <= $v && $v <=> 25 ) } keys %my_hash\n;\n" }, { "answer_id": 161129, "author": "ysth", "author_id": 17389, "author_profile": "https://Stackoverflow.com/users/17389", "pm_score": 0, "selected": false, "text": "use vars use vars our() sub lccmp($$) { lc($_[0]) cmp lc($_[1]) }\nprint join ' ', sort lccmp\n qw/I met this guy and he looked like he might have been a hat-check clerk/;\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150454", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11289/" ]
150,471
<p>I have a DataGridView whose DataSource is a DataTable. This DataTable has a boolean column, which is interpreted as a checkbox in the DataGridView.</p> <pre><code>employeeSelectionTable.Columns.Add("IsSelected", typeof(bool)); ... employeeSelectionTable.RowChanged += selectionTableRowChanged; dataGridViewSelectedEmployees.DataSource = employeeSelectionTable; ... private void selectionTableRowChanged(object sender, DataRowChangeEventArgs e) { if ((bool)e.Row["IsSelected"]) { Console.Writeline("Is Selected"); } else { Console.Writeline("Is Not Selected"); } break; } </code></pre> <p>When the user single-clicks on a checkbox, it gets checked, and selectionTableRowChanged will output "Is Selected."</p> <p>Similarly, when the user checks it again, the box gets cleared, and selectionTableRowChanged outputs "Is Not Selected."</p> <p>Here's where I have the problem:</p> <p>When the user double-clicks on the checkbox, the checkbox gets checked, the RowChanged event gets called ("Is Selected"), and then the checkbox is cleared, and no corresponding RowChanged event gets called. Now the subscriber to the the RowChanged event is out of sync.</p> <p>My solution right now is to subclass DataGridView and override WndProc to eat WM_LBUTTONDBLCLICK, so any double-clicking on the control is ignored. Is there a better solution?</p>
[ { "answer_id": 150549, "author": "Vivek", "author_id": 7418, "author_profile": "https://Stackoverflow.com/users/7418", "pm_score": 1, "selected": false, "text": "private void dgv_CellContentClick(object sender, DataGridViewCellEventArgs e)\n{\n if(e.ColumnIndex == <columnIndex of IsSelected>)\n {\n string value = dgv[e.ColumnIndex, e.RowIndex].EditedFormattedValue;\n if( value == null || Convert.ToBoolean(value) == false)\n {\n //push false to employeeSelectionTable\n }\n else\n {\n //push true to employeeSelectionTable\n }\n\n }\n}\n" }, { "answer_id": 150889, "author": "ManiacZX", "author_id": 18148, "author_profile": "https://Stackoverflow.com/users/18148", "pm_score": 2, "selected": false, "text": "using System;\nusing System.Windows.Forms;\n\nnamespace TestApp\n{\n class DGV : DataGridView\n {\n private string test = \"\";\n\n protected override void OnDoubleClick(EventArgs e)\n {\n MessageBox.Show(test + \"OnDoubleClick\");\n }\n\n protected override void OnCellMouseDoubleClick(System.Windows.Forms.DataGridViewCellMouseEventArgs e)\n {\n MessageBox.Show(test + \"OnCellMouseDoubleClick\");\n }\n\n protected override void OnCellMouseClick(System.Windows.Forms.DataGridViewCellMouseEventArgs e)\n {\n if (e.Clicks == 1)\n {\n // Had to do this with a variable as using a MessageBox\n // here would block us from pulling off a double click\n test = \"1 click \";\n base.OnCellMouseClick(e);\n }\n else\n {\n MessageBox.Show(\"OnCellMouseClick\");\n }\n }\n }\n}\n" }, { "answer_id": 263102, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "** _RefreshTimer = new Timer();\n _RefreshTimer.Tick += new EventHandler(RefreshTimer_Tick);\n _RefreshTimer.Interval = 100;\n _RefreshTimer.Start();\n\n }\n }\n\n }\n\n void RefreshTimer_Tick(object sender, EventArgs e)\n {\n dgv.Refresh();\n _RefreshTimer.Stop();\n _RefreshTimer = null;\n }**\n" }, { "answer_id": 377544, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "DataGridViewCheckBoxCell checkBoxCell = new MyDataGridViewCheckBoxCell();\n...\nDataGridViewColumn col = new DataGridViewColumn(checkBoxCell);\n...\ncol.Name = \"colCheckBox\";\n...\nthis.dgItems.Columns.Add(col);\n protected override void OnContentDoubleClick(DataGridViewCellEventArgs e)\n{\n //This the trick to keep the checkbox in sync with other actions.\n //base.OnContentDoubleClick(e);\n}\n" }, { "answer_id": 1363636, "author": "Rob Smith", "author_id": 896691, "author_profile": "https://Stackoverflow.com/users/896691", "pm_score": 2, "selected": false, "text": "private void dgv_CellDoubleClick(object sender, DataGridViewCellEventArgs e)\n{\n dgv_CellClick(sender, e);\n}\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150471", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
150,479
<p>Is there an official C# guideline for the order of items in terms of class structure?</p> <p>Does it go:</p> <ul> <li>Public Fields</li> <li>Private Fields</li> <li>Properties</li> <li>Constructors</li> <li>Methods<br> ?</li> </ul> <p>I'm curious if there is a hard and fast rule about the order of items? I'm kind of all over the place. I want to stick with a particular standard so I can do it everywhere.</p> <p>The real problem is my more complex properties end up looking a lot like methods and they feel out of place at the top before the constructor.</p> <p>Any tips/suggestions?</p>
[ { "answer_id": 150516, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 3, "selected": false, "text": "public class myClass\n{\n#region Private Members\n\n#endregion\n#region Public Properties\n\n#endregion\n\n#region Constructors\n\n#endregion\n#region Public Methods\n\n#endregion\n}\n" }, { "answer_id": 27997842, "author": "bright", "author_id": 90291, "author_profile": "https://Stackoverflow.com/users/90291", "pm_score": 5, "selected": false, "text": "using using" }, { "answer_id": 41209042, "author": "Aluan Haddad", "author_id": 1915893, "author_profile": "https://Stackoverflow.com/users/1915893", "pm_score": 3, "selected": false, "text": "public methods\npublic events\npublic properties\n\nprotected methods\nprotected events\nprotected properties\n\nprivate methods\nprivate events\nprivate properties\nprivate fields\n\npublic delegates\npublic interfaces\npublic classes\npublic structs\n\nprotected delegates\nprotected interfaces\nprotected classes\nprotected structs\n\nprivate delegates\nprivate interfaces\nprivate classes\nprivate structs\n" }, { "answer_id": 47689464, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "// Some where in the fields section\nprivate int someVariable;\n\n// I also refrain from\n// declaring variables outside of the constructor\n\n// and some where in the properties section I do\npublic int SomeVariable\n{\n get { return someVariable; }\n set { someVariable = value; }\n}\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150479", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2635/" ]
150,505
<p>I am currently defining regular expressions in order to capture parameters in a URL, as described in the tutorial. How do I access parameters from the URL as part the <code>HttpRequest</code> object?</p> <p>My <code>HttpRequest.GET</code> currently returns an empty <code>QueryDict</code> object.</p> <p>I'd like to learn how to do this without a library, so I can get to know Django better.</p>
[ { "answer_id": 150518, "author": "camflan", "author_id": 22445, "author_profile": "https://Stackoverflow.com/users/22445", "pm_score": 11, "selected": true, "text": "domain/search/?q=haha request.GET.get('q', '') q '' q URLconf regex (r'^user/(?P<username>\\w{0,50})/$', views.profile_page,),\n views.py def profile_page(request, username):\n # Rest of the method\n" }, { "answer_id": 152349, "author": "jamting", "author_id": 2639, "author_profile": "https://Stackoverflow.com/users/2639", "pm_score": 3, "selected": false, "text": "query_strings templates" }, { "answer_id": 157295, "author": "akaihola", "author_id": 15770, "author_profile": "https://Stackoverflow.com/users/15770", "pm_score": 9, "selected": false, "text": "url(regex=r'^user/(?P<username>\\w{1,50})/$', view='views.profile_page') http://domain/user/thaiyoshi/?message=Hi \"user/thaiyoshi/\" message=Hi QueryDict request.GET def profile_page(request, username=None):\n user = User.objects.get(username=username)\n message = request.GET.get('message')\n \"GET\" \"POST\" request.method /blog/post/15/ /blog/posts/?id=15 /blog/post/15/?show_comments=1 /blog/posts/2008/?sort_by=date&direction=desc /blog/post/2008/09/30/django-urls/" }, { "answer_id": 4218313, "author": "Kevin", "author_id": 512577, "author_profile": "https://Stackoverflow.com/users/512577", "pm_score": 5, "selected": false, "text": "def some_view(request, *args, **kwargs):\n if kwargs.get('q', None):\n # Do something here ..\n" }, { "answer_id": 14699001, "author": "DrKaoliN", "author_id": 1410452, "author_profile": "https://Stackoverflow.com/users/1410452", "pm_score": 4, "selected": false, "text": "urls.py url(r'^(?P<username>\\w+)/$', views.profile_page,),\n www.example.com/<username> User matching query does not exist." }, { "answer_id": 28062342, "author": "Dadaso Zanzane", "author_id": 3056905, "author_profile": "https://Stackoverflow.com/users/3056905", "pm_score": 6, "selected": false, "text": "request.GET[\"id\"]\n request.POST[\"id\"]\n" }, { "answer_id": 43806831, "author": "Ole Henrik Skogstrøm", "author_id": 900271, "author_profile": "https://Stackoverflow.com/users/900271", "pm_score": 5, "selected": false, "text": "request request.parser_context['kwargs']['your_param']" }, { "answer_id": 46564448, "author": "Bartłomiej", "author_id": 7665326, "author_profile": "https://Stackoverflow.com/users/7665326", "pm_score": 5, "selected": false, "text": "https://domain/method/?a=x&b=y\n key_a = request.GET['a']\n a request.GET.get('a')\n try: except: HttpResponseBadRequest()" }, { "answer_id": 50714430, "author": "Eric Andrews", "author_id": 8350321, "author_profile": "https://Stackoverflow.com/users/8350321", "pm_score": 6, "selected": false, "text": "domain/search/?q=CA\n urlpatterns = [\n path('domain/search/', views.CityListView.as_view()),\n]\n request.GET.get('q', None).\n class CityListView(generics.ListAPIView):\n serializer_class = CityNameSerializer\n\n def get_queryset(self):\n if self.request.method == 'GET':\n queryset = City.objects.all()\n state_name = self.request.GET.get('q', None)\n if state_name is not None:\n queryset = queryset.filter(state__name=state_name)\n return queryset\n http://servername:port/domain/search/?q=CA\n http://servername:port/domain/search/?q=\"CA\"\n" }, { "answer_id": 57148306, "author": "mdcg", "author_id": 10235468, "author_profile": "https://Stackoverflow.com/users/10235468", "pm_score": 4, "selected": false, "text": "http://myserver:port/resource/?status=1\n request.query_params.get('status', None) => 1\n request.data.get('role', None)\n" }, { "answer_id": 60892217, "author": "sachi", "author_id": 13137216, "author_profile": "https://Stackoverflow.com/users/13137216", "pm_score": 3, "selected": false, "text": "urlpatterns = [path('runreport/<str:queryparams>', views.get)]\n list2 = queryparams.split(\"&\")\n" }, { "answer_id": 63423068, "author": "Martín De la Fuente", "author_id": 6535374, "author_profile": "https://Stackoverflow.com/users/6535374", "pm_score": 3, "selected": false, "text": "view.kwargs.get('url_param')\n request.resolver_match.kwargs.get('url_param')\n" }, { "answer_id": 64200327, "author": "Ahmed Shehab", "author_id": 8404743, "author_profile": "https://Stackoverflow.com/users/8404743", "pm_score": 3, "selected": false, "text": "# for example\nrequest.META['QUERY_STRING']\n\n# or to avoid any exceptions provide a fallback\n\nrequest.META.get('QUERY_STRING', False)\n\n url(r'^project_config/(?P<product>\\w+)/$', views.foo),\n\n" }, { "answer_id": 65666694, "author": "Arseniy Lebedev", "author_id": 9826267, "author_profile": "https://Stackoverflow.com/users/9826267", "pm_score": 3, "selected": false, "text": "request.GET.keys() dict(request.GET)" }, { "answer_id": 68829899, "author": "Omar Magdy", "author_id": 14819065, "author_profile": "https://Stackoverflow.com/users/14819065", "pm_score": 2, "selected": false, "text": "from rest_framework.response import Response\n\ndef update_product(request, pk):\n return Response({\"pk\":pk})\n from products.views import update_product\nfrom django.urls import path\n\nurlpatterns = [\n ...,\n path('update/products/<int:pk>', update_product)\n]\n" }, { "answer_id": 71331889, "author": "Odiljon Djamalov", "author_id": 8532138, "author_profile": "https://Stackoverflow.com/users/8532138", "pm_score": 0, "selected": false, "text": "request.query_params" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150505", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1227001/" ]
150,509
<p>I've got a C# program that's supposed to play audio files. I've figured out how to play any sound file for which Windows has a codec by using DirectShow, but now I want to properly fill in the file type filter box on the Open dialog. I'd like to automatically list any file format for which Windows has a codec. If some random user installs a codec for an obscure format, its associated extension(s) and file type description(s) need to show up in the list.</p> <p>Any ideas?</p>
[ { "answer_id": 216938, "author": "Mark Heath", "author_id": 7532, "author_profile": "https://Stackoverflow.com/users/7532", "pm_score": 0, "selected": false, "text": "AcmDriver" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9837/" ]
150,513
<p>I have a form in HTML where our users fill in the data and then print it. The data isn't saved anywhere. These forms come from outside our company and are built as html pages to resemble the original as closely as possible and then stuffed away and forgotten in a folder on the intranet. Normally another developer does them, but I have to do a few while he's out. Looking through his code, all his forms have a bunch of server-side code to take the inputs and re-write the page with only the contents. It seems like there should be a better way.</p> <p>I want to just style the text inputs using a media selector so that when it prints you can see the text, but nothing of the box surrounding it. Any thoughts?</p>
[ { "answer_id": 150521, "author": "Wayne", "author_id": 8236, "author_profile": "https://Stackoverflow.com/users/8236", "pm_score": 2, "selected": false, "text": "<input type=\"text\" style=\"border: 0; background-color: #fff;\" />\n" }, { "answer_id": 150530, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 3, "selected": false, "text": "<input type=\"text\" class=\"print-clean\" .../>\n <link rel=\"stylesheet\" type=\"text/css\" media=\"print\" href=\"/css/print.css\" />\n .print-clean {\n border: none;\n background: transparent;\n}\n" }, { "answer_id": 150536, "author": "Maciej", "author_id": 2631856, "author_profile": "https://Stackoverflow.com/users/2631856", "pm_score": 5, "selected": true, "text": "<link rel=\"stylsheet\" type=\"text/css\" media=\"print\" href=\"print.css\">\n <head> input{border: 0px}" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3043/" ]
150,514
<p>In the database I have a field named 'body' that has an XML in it. The method I created in the model looks like this:</p> <pre><code>def self.get_personal_data_module(person_id) person_module = find_by_person_id(person_id) item_module = Hpricot(person_module.body) personal_info = Array.new personal_info = {:studies =&gt; (item_module/"studies").inner_html, :birth_place =&gt; (item_module/"birth_place").inner_html, :marrital_status =&gt; (item_module/"marrital_status").inner_html} return personal_info end </code></pre> <p>I want the function to return an object instead of an array. So I can use Module.studies instead of Model[:studies].</p>
[ { "answer_id": 150587, "author": "Atiaxi", "author_id": 2555346, "author_profile": "https://Stackoverflow.com/users/2555346", "pm_score": 3, "selected": true, "text": "class PersonalData\n attr_accessor :studies\n attr_accessor :birth_place\n attr_accessor :marital_status\n\n def initialize(studies,birth_place,marital_status)\n @studies = studies\n @birth_place = birth_place\n @marital_status = marital_status\n end\nend\n def self.get_personal_data_module(person_id) \n person_module = find_by_person_id(person_id) \n item_module = Hpricot(person_module.body) \n personal_info = PersonalData.new((item_module/\"studies\").inner_html,\n (item_module/\"birth_place\").inner_html,\n (item_module/\"marital_status\").innner_html)\n return personal_info \nend\n" }, { "answer_id": 151636, "author": "jtbandes", "author_id": 23649, "author_profile": "https://Stackoverflow.com/users/23649", "pm_score": 2, "selected": false, "text": "class Hash\n def to_obj\n self.inject(Object.new) do |obj, ary| # ary is [:key, \"value\"]\n obj.instance_variable_set(\"@#{ary[0]}\", ary[1])\n class << obj; self; end.instance_eval do # do this on obj's metaclass\n attr_reader ary[0].to_sym # add getter method for this ivar\n end\n obj # return obj for next iteration\n end\n end\nend\n h = {:foo => \"bar\", :baz => \"wibble\"}\no = h.to_obj # => #<Object:0x30bf38 @foo=\"bar\", @baz=\"wibble\">\no.foo # => \"bar\"\no.baz # => \"wibble\"\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3718/" ]
150,517
<p>This is an almost-duplicate of <a href="https://stackoverflow.com/questions/68477/send-file-using-post-from-a-python-script">Send file using POST from a Python script</a>, but I'd like to add a caveat: I need something that properly handles the encoding of fields and attached files. The solutions I've been able to find blow up when you throw unicode strings containing non-ascii characters into the mix. Also, most of the solutions don't base64-encode data to keep things 7-bit clean.</p>
[ { "answer_id": 151642, "author": "Dan Lenski", "author_id": 20789, "author_profile": "https://Stackoverflow.com/users/20789", "pm_score": 3, "selected": false, "text": "from urllib2 import Request, urlopen\nfrom binascii import b2a_base64\n\ndef b64open(url, postdata):\n req = Request(url, b2a_base64(postdata), headers={'Content-Transfer-Encoding': 'base64'})\n return urlopen(req)\n\nconn = b64open(\"http://www.whatever.com/script.cgi\", u\"Liberté Égalité Fraternité\")\n# returns a file-like object\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23582/" ]
150,522
<p>Using Restlet I needed to serve some simple static content in the same context as my web service. I've configured the component with a <code>Directory</code>, but in testing, I've found it will only serve 'index.html', everything else results in a 404.</p> <pre><code>router.attach("/", new Directory(context, new Reference(baseRef, "./content")); </code></pre> <p>So... <a href="http://service" rel="nofollow noreferrer">http://service</a> and <a href="http://service/index.html" rel="nofollow noreferrer">http://service/index.html</a> both work, </p> <p>but <a href="http://service/other.html" rel="nofollow noreferrer">http://service/other.html</a> gives me a 404</p> <p>Can anyone shed some light on this? I want any file within the ./content directory to be available.</p> <p>PS: I eventually plan to use a reverse proxy and serve all static content off another web server, but for now I need this to work as is.</p>
[ { "answer_id": 151642, "author": "Dan Lenski", "author_id": 20789, "author_profile": "https://Stackoverflow.com/users/20789", "pm_score": 3, "selected": false, "text": "from urllib2 import Request, urlopen\nfrom binascii import b2a_base64\n\ndef b64open(url, postdata):\n req = Request(url, b2a_base64(postdata), headers={'Content-Transfer-Encoding': 'base64'})\n return urlopen(req)\n\nconn = b64open(\"http://www.whatever.com/script.cgi\", u\"Liberté Égalité Fraternité\")\n# returns a file-like object\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150522", "https://Stackoverflow.com", "https://Stackoverflow.com/users/758/" ]
150,532
<p>Similar to <a href="https://stackoverflow.com/questions/5415/convert-bytes-to-floating-point-numbers-in-python">this</a> question, I am trying to read in an ID3v2 tag header and am having trouble figuring out how to get individual bytes in python.</p> <p>I first read all ten bytes into a string. I then want to parse out the individual pieces of information.</p> <p>I can grab the two version number chars in the string, but then I have no idea how to take those two chars and get an integer out of them.</p> <p>The struct package seems to be what I want, but I can't get it to work.</p> <p>Here is my code so-far (I am very new to python btw...so take it easy on me):</p> <pre><code>def __init__(self, ten_byte_string): self.whole_string = ten_byte_string self.file_identifier = self.whole_string[:3] self.major_version = struct.pack('x', self.whole_string[3:4]) #this self.minor_version = struct.pack('x', self.whole_string[4:5]) # and this self.flags = self.whole_string[5:6] self.len = self.whole_string[6:10] </code></pre> <p>Printing out any value except is obviously crap because they are not formatted correctly.</p>
[ { "answer_id": 150541, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 2, "selected": false, "text": "struct self.major_version = struct.unpack('H', self.whole_string[3:5])\n pack() unpack()" }, { "answer_id": 150584, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 5, "selected": true, "text": ">>> s = '\\0\\x02'\n>>> struct.unpack('>H', s)\n(2,)\n >>> a,b,c = struct.unpack('>HHi', some_string)\n ident, major, minor, flags, len = struct.unpack('>3sBBBI', ten_byte_string)\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2598/" ]
150,535
<p>How do you remove the jagged edges from a wide button in internet explorer? For example:</p> <p><img src="https://i.stack.imgur.com/em5K0.gif" alt="alt text"></p>
[ { "answer_id": 150545, "author": "brad", "author_id": 208, "author_profile": "https://Stackoverflow.com/users/208", "pm_score": 2, "selected": false, "text": "input.button {\n padding: 0 .25em;\n width: 0; /* for IE only */\n overflow: visible;\n}\n\ninput.button[class] { /* IE ignores [class] */\n width: auto;\n}\n $(function(){\n $('input[type=button]').addClass('button');\n});\n" }, { "answer_id": 150557, "author": "Ron Savage", "author_id": 12476, "author_profile": "https://Stackoverflow.com/users/12476", "pm_score": 2, "selected": false, "text": "/**************************************************************************\n Nav Button format settings\n**************************************************************************/\n.navButtons\n{\n font-size: 9px;\n font-family: Verdana, sans-serif;\n width: 80;\n height: 20; \n position: relative; \n border-style: solid; \n border-width: 1;\n}\n" }, { "answer_id": 150617, "author": "cllpse", "author_id": 20946, "author_profile": "https://Stackoverflow.com/users/20946", "pm_score": 4, "selected": true, "text": "background-color border-color background-color: black;\ncolor: white;\nborder-color: red green blue yellow;\n" }, { "answer_id": 541113, "author": "Paul D. Waite", "author_id": 20578, "author_profile": "https://Stackoverflow.com/users/20578", "pm_score": 2, "selected": false, "text": "overflow: visible; display:block; display:inline; width: 0;" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150535", "https://Stackoverflow.com", "https://Stackoverflow.com/users/208/" ]
150,539
<p>I've used asp.net profiles (using the AspNetSqlProfileProvider) for holding small bits of information about my users. I started to wonder how it would handle a robust profile for a large number of users. Does anyone have experience using this on a large website with large numbers of simultaneous users? What are the performance implications? How about maintenance?</p>
[ { "answer_id": 150545, "author": "brad", "author_id": 208, "author_profile": "https://Stackoverflow.com/users/208", "pm_score": 2, "selected": false, "text": "input.button {\n padding: 0 .25em;\n width: 0; /* for IE only */\n overflow: visible;\n}\n\ninput.button[class] { /* IE ignores [class] */\n width: auto;\n}\n $(function(){\n $('input[type=button]').addClass('button');\n});\n" }, { "answer_id": 150557, "author": "Ron Savage", "author_id": 12476, "author_profile": "https://Stackoverflow.com/users/12476", "pm_score": 2, "selected": false, "text": "/**************************************************************************\n Nav Button format settings\n**************************************************************************/\n.navButtons\n{\n font-size: 9px;\n font-family: Verdana, sans-serif;\n width: 80;\n height: 20; \n position: relative; \n border-style: solid; \n border-width: 1;\n}\n" }, { "answer_id": 150617, "author": "cllpse", "author_id": 20946, "author_profile": "https://Stackoverflow.com/users/20946", "pm_score": 4, "selected": true, "text": "background-color border-color background-color: black;\ncolor: white;\nborder-color: red green blue yellow;\n" }, { "answer_id": 541113, "author": "Paul D. Waite", "author_id": 20578, "author_profile": "https://Stackoverflow.com/users/20578", "pm_score": 2, "selected": false, "text": "overflow: visible; display:block; display:inline; width: 0;" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150539", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2757/" ]
150,543
<p>In C, is it possible to forward the invocation of a variadic function? As in,</p> <pre><code>int my_printf(char *fmt, ...) { fprintf(stderr, "Calling printf with fmt %s", fmt); return SOMEHOW_INVOKE_LIBC_PRINTF; } </code></pre> <p>Forwarding the invocation in the manner above obviously isn't strictly necessary in this case (since you could log invocations in other ways, or use vfprintf), but the codebase I'm working on requires the wrapper to do some actual work, and doesn't have (and can't have added) a helper function akin to vfprintf.</p> <p>[Update: there seems to be some confusion based on the answers that have been supplied so far. To phrase the question another way: in general, can you wrap some arbitrary variadic function <i>without modifying that function's definition</i>.]</p>
[ { "answer_id": 150560, "author": "Greg Rogers", "author_id": 5963, "author_profile": "https://Stackoverflow.com/users/5963", "pm_score": 2, "selected": false, "text": "int my_printf(char *fmt, ...) {\n va_list va;\n int ret;\n\n va_start(va, fmt);\n ret = vfprintf(stderr, fmt, va);\n va_end(va);\n return ret;\n}\n" }, { "answer_id": 150571, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 4, "selected": false, "text": "<stdarg.h> #include <stdarg.h>\nint my_printf(char *format, ...)\n{\n va_list args;\n va_start(args, format);\n int r = vprintf(format, args);\n va_end(args);\n return r;\n}\n vprintf printf va_list" }, { "answer_id": 150578, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 2, "selected": false, "text": "my_print() varargs printf() my_printf() va_start() vfprintf()" }, { "answer_id": 150616, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 8, "selected": true, "text": "vfprintf va_list void myfun(const char *fmt, va_list argp) {\n vfprintf(stderr, fmt, argp);\n}\n" }, { "answer_id": 150626, "author": "CB Bailey", "author_id": 19563, "author_profile": "https://Stackoverflow.com/users/19563", "pm_score": 6, "selected": false, "text": "varargs printf vprintf #include <stdarg.h>\n\nint m_printf(char *fmt, ...)\n{\n int ret;\n\n /* Declare a va_list type variable */\n va_list myargs;\n\n /* Initialise the va_list variable with the ... after fmt */\n\n va_start(myargs, fmt);\n\n /* Forward the '...' to vprintf */\n ret = vprintf(fmt, myargs);\n\n /* Clean up the va_list */\n va_end(myargs);\n\n return ret;\n}\n" }, { "answer_id": 150633, "author": "Commodore Jaeger", "author_id": 4659, "author_profile": "https://Stackoverflow.com/users/4659", "pm_score": 6, "selected": false, "text": "#define my_printf(format, ...) \\\n do { \\\n fprintf(stderr, \"Calling printf with fmt %s\\n\", format); \\\n some_other_variadac_function(format, ##__VA_ARGS__); \\\n } while(0)\n" }, { "answer_id": 150854, "author": "user10146", "author_id": 10146, "author_profile": "https://Stackoverflow.com/users/10146", "pm_score": 1, "selected": false, "text": "#include <stdio.h>\n#include <stdarg.h>\n\nint old_variadic_function(int n, ...)\n{\n va_list args;\n int i = 0;\n\n va_start(args, n);\n\n if(i++<n) printf(\"arg %d is 0x%x\\n\", i, va_arg(args, int));\n if(i++<n) printf(\"arg %d is %g\\n\", i, va_arg(args, double));\n if(i++<n) printf(\"arg %d is %g\\n\", i, va_arg(args, double));\n\n va_end(args);\n\n return n;\n}\n\nint old_variadic_function_wrapper(int n, ...)\n{\n va_list args;\n int a1;\n int a2;\n int a3;\n int a4;\n int a5;\n int a6;\n int a7;\n int a8;\n\n /* Do some work, possibly with another va_list to access arguments */\n\n /* Work done */\n\n va_start(args, n);\n\n a1 = va_arg(args, int);\n a2 = va_arg(args, int);\n a3 = va_arg(args, int);\n a4 = va_arg(args, int);\n a5 = va_arg(args, int);\n a6 = va_arg(args, int);\n a7 = va_arg(args, int);\n\n va_end(args);\n\n return old_variadic_function(n, a1, a2, a3, a4, a5, a6, a7, a8);\n}\n\nint main(void)\n{\n printf(\"Call 1: 1, 0x123\\n\");\n old_variadic_function(1, 0x123);\n printf(\"Call 2: 2, 0x456, 1.234\\n\");\n old_variadic_function(2, 0x456, 1.234);\n printf(\"Call 3: 3, 0x456, 4.456, 7.789\\n\");\n old_variadic_function(3, 0x456, 4.456, 7.789);\n printf(\"Wrapped call 1: 1, 0x123\\n\");\n old_variadic_function_wrapper(1, 0x123);\n printf(\"Wrapped call 2: 2, 0x456, 1.234\\n\");\n old_variadic_function_wrapper(2, 0x456, 1.234);\n printf(\"Wrapped call 3: 3, 0x456, 4.456, 7.789\\n\");\n old_variadic_function_wrapper(3, 0x456, 4.456, 7.789);\n\n return 0;\n}\n" }, { "answer_id": 16777608, "author": "coltox", "author_id": 1147819, "author_profile": "https://Stackoverflow.com/users/1147819", "pm_score": 4, "selected": false, "text": "#ifndef _VA_ARGS_WRAPPER_H\n#define _VA_ARGS_WRAPPER_H\n#include <limits.h>\n#include <stdint.h>\n#include <alloca.h>\n#include <inttypes.h>\n#include <string.h>\n\n/* This macros allow wrapping variadic functions.\n * Currently we don't care about floating point arguments and\n * we assume that the standard calling conventions are used.\n *\n * The wrapper function has to start with VA_WRAP_PROLOGUE()\n * and the original function can be called by\n * VA_WRAP_CALL(function, ret), whereas the return value will\n * be stored in ret. The caller has to provide ret\n * even if the original function was returning void.\n */\n\n#define __VA_WRAP_CALL_FUNC __attribute__ ((noinline))\n\n#define VA_WRAP_CALL_COMMON() \\\n uintptr_t va_wrap_this_bp,va_wrap_old_bp; \\\n va_wrap_this_bp = va_wrap_get_bp(); \\\n va_wrap_old_bp = *(uintptr_t *) va_wrap_this_bp; \\\n va_wrap_this_bp += 2 * sizeof(uintptr_t); \\\n size_t volatile va_wrap_size = va_wrap_old_bp - va_wrap_this_bp; \\\n uintptr_t *va_wrap_stack = alloca(va_wrap_size); \\\n memcpy((void *) va_wrap_stack, \\\n (void *)(va_wrap_this_bp), va_wrap_size);\n\n\n#if ( __WORDSIZE == 64 )\n\n/* System V AMD64 AB calling convention */\n\nstatic inline uintptr_t __attribute__((always_inline)) \nva_wrap_get_bp()\n{\n uintptr_t ret;\n asm volatile (\"mov %%rbp, %0\":\"=r\"(ret));\n return ret;\n}\n\n\n#define VA_WRAP_PROLOGUE() \\\n uintptr_t va_wrap_ret; \\\n uintptr_t va_wrap_saved_args[7]; \\\n asm volatile ( \\\n \"mov %%rsi, (%%rax)\\n\\t\" \\\n \"mov %%rdi, 0x8(%%rax)\\n\\t\" \\\n \"mov %%rdx, 0x10(%%rax)\\n\\t\" \\\n \"mov %%rcx, 0x18(%%rax)\\n\\t\" \\\n \"mov %%r8, 0x20(%%rax)\\n\\t\" \\\n \"mov %%r9, 0x28(%%rax)\\n\\t\" \\\n : \\\n :\"a\"(va_wrap_saved_args) \\\n );\n\n#define VA_WRAP_CALL(func, ret) \\\n VA_WRAP_CALL_COMMON(); \\\n va_wrap_saved_args[6] = (uintptr_t)va_wrap_stack; \\\n asm volatile ( \\\n \"mov (%%rax), %%rsi \\n\\t\" \\\n \"mov 0x8(%%rax), %%rdi \\n\\t\" \\\n \"mov 0x10(%%rax), %%rdx \\n\\t\" \\\n \"mov 0x18(%%rax), %%rcx \\n\\t\" \\\n \"mov 0x20(%%rax), %%r8 \\n\\t\" \\\n \"mov 0x28(%%rax), %%r9 \\n\\t\" \\\n \"mov $0, %%rax \\n\\t\" \\\n \"call *%%rbx \\n\\t\" \\\n : \"=a\" (va_wrap_ret) \\\n : \"b\" (func), \"a\" (va_wrap_saved_args) \\\n : \"%rcx\", \"%rdx\", \\\n \"%rsi\", \"%rdi\", \"%r8\", \"%r9\", \\\n \"%r10\", \"%r11\", \"%r12\", \"%r14\", \\\n \"%r15\" \\\n ); \\\n ret = (typeof(ret)) va_wrap_ret;\n\n#else\n\n/* x86 stdcall */\n\nstatic inline uintptr_t __attribute__((always_inline))\nva_wrap_get_bp()\n{\n uintptr_t ret;\n asm volatile (\"mov %%ebp, %0\":\"=a\"(ret));\n return ret;\n}\n\n#define VA_WRAP_PROLOGUE() \\\n uintptr_t va_wrap_ret;\n\n#define VA_WRAP_CALL(func, ret) \\\n VA_WRAP_CALL_COMMON(); \\\n asm volatile ( \\\n \"mov %2, %%esp \\n\\t\" \\\n \"call *%1 \\n\\t\" \\\n : \"=a\"(va_wrap_ret) \\\n : \"r\" (func), \\\n \"r\"(va_wrap_stack) \\\n : \"%ebx\", \"%ecx\", \"%edx\" \\\n ); \\\n ret = (typeof(ret))va_wrap_ret;\n#endif\n\n#endif\n int __VA_WRAP_CALL_FUNC wrap_printf(char *str, ...)\n{\n VA_WRAP_PROLOGUE();\n int ret;\n VA_WRAP_CALL(printf, ret);\n printf(\"printf returned with %d \\n\", ret);\n return ret;\n}\n" }, { "answer_id": 21741002, "author": "Johannes", "author_id": 536874, "author_profile": "https://Stackoverflow.com/users/536874", "pm_score": 1, "selected": false, "text": "#include <stdio.h>\n#include <stdarg.h>\n\n#define Option_VariadicMacro(f, ...)\\\n printf(\"printing using format: %s\", f);\\\n printf(f, __VA_ARGS__)\n\nint Option_ResolveVariadicAndPassOn(const char * f, ... )\n{\n int r;\n va_list args;\n\n printf(\"printing using format: %s\", f);\n va_start(args, f);\n r = vprintf(f, args);\n va_end(args);\n return r;\n}\n\nvoid main()\n{\n const char * f = \"%s %s %s\\n\";\n const char * a = \"One\";\n const char * b = \"Two\";\n const char * c = \"Three\";\n printf(\"---- Normal Print ----\\n\");\n printf(f, a, b, c);\n printf(\"\\n\");\n printf(\"---- Option_VariadicMacro ----\\n\");\n Option_VariadicMacro(f, a, b, c);\n printf(\"\\n\");\n printf(\"---- Option_ResolveVariadicAndPassOn ----\\n\");\n Option_ResolveVariadicAndPassOn(f, a, b, c);\n printf(\"\\n\");\n}\n" }, { "answer_id": 61545433, "author": "SSpoke", "author_id": 414521, "author_profile": "https://Stackoverflow.com/users/414521", "pm_score": 0, "selected": false, "text": "static BOOL(__cdecl *OriginalVarArgsFunction)(BYTE variable1, char* format, ...)(0x12345678); //TODO: change address lolz\n\nBOOL __cdecl HookedVarArgsFunction(BYTE variable1, char* format, ...)\n{\n BOOL res;\n\n va_list vl;\n va_start(vl, format);\n\n // Get variable arguments count from disasm. -2 because of existing 'format', 'variable1'\n uint32_t argCount = *((uint8_t*)_ReturnAddress() + 2) / sizeof(void*) - 2;\n printf(\"arg count = %d\\n\", argCount);\n\n // ((int( __cdecl* )(const char*, ...))&oldCode)(fmt, ...);\n __asm\n {\n mov eax, argCount\n test eax, eax\n je noLoop\n mov edx, vl\n loop1 :\n push dword ptr[edx + eax * 4 - 4]\n sub eax, 1\n jnz loop1\n noLoop :\n push format\n push variable1\n //lea eax, [oldCode] // oldCode - original function pointer\n mov eax, OriginalVarArgsFunction\n call eax\n mov res, eax\n mov eax, argCount\n lea eax, [eax * 4 + 8] //+8 because 2 parameters (format and variable1)\n add esp, eax\n }\n return res;\n}\n" }, { "answer_id": 61545790, "author": "Nate Eldredge", "author_id": 634919, "author_profile": "https://Stackoverflow.com/users/634919", "pm_score": 4, "selected": false, "text": "__builtin_apply #include <stdio.h>\n\nint my_printf(const char *fmt, ...) {\n void *args = __builtin_apply_args();\n printf(\"Hello there! Format string is %s\\n\", fmt);\n void *ret = __builtin_apply((void (*)())printf, args, 1000);\n __builtin_return(ret);\n}\n\nint main(void) {\n my_printf(\"%d %f %s\\n\", -37, 3.1415, \"spam\");\n return 0;\n}\n" }, { "answer_id": 62043871, "author": "Bert Regelink", "author_id": 1239858, "author_profile": "https://Stackoverflow.com/users/1239858", "pm_score": 1, "selected": false, "text": "#include <stdio.h>\n#include <stdarg.h>\n\nint my_printf(char *fmt, ...)\n{\n if (fmt == NULL) {\n /* Invalid format pointer */\n return -1;\n } else {\n va_list args;\n int len;\n\n /* Initialize a variable argument list */\n va_start(args, fmt);\n\n /* Get length of format including arguments */\n len = vsnprintf(NULL, 0, fmt, args);\n\n /* End using variable argument list */\n va_end(args);\n \n if (len < 0) {\n /* vsnprintf failed */\n return -1;\n } else {\n /* Declare a character buffer for the formatted string */\n char formatted[len + 1];\n\n /* Initialize a variable argument list */\n va_start(args, fmt);\n \n /* Write the formatted output */\n vsnprintf(formatted, sizeof(formatted), fmt, args);\n \n /* End using variable argument list */\n va_end(args);\n\n /* Call the wrapped function using the formatted output and return */\n fprintf(stderr, \"Calling printf with fmt %s\", fmt);\n return printf(\"%s\", formatted);\n }\n }\n}\n\nint main()\n{\n /* Expected output: Test\n * Expected error: Calling printf with fmt Test\n */\n my_printf(\"Test\\n\");\n //printf(\"Test\\n\");\n\n /* Expected output: Test\n * Expected error: Calling printf with fmt %s\n */\n my_printf(\"%s\\n\", \"Test\");\n //printf(\"%s\\n\", \"Test\");\n\n /* Expected output: %s\n * Expected error: Calling printf with fmt %s\n */\n my_printf(\"%s\\n\", \"%s\");\n //printf(\"%s\\n\", \"%s\");\n\n return 0;\n}\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150543", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23600/" ]
150,544
<p>In C# code can you catch a native exception thrown from deep in some unmanaged library? If so do you need to do anything differently to catch it or does a standard try...catch get it?</p>
[ { "answer_id": 150550, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": -1, "selected": false, "text": "try\n{\n\n}\ncatch(Exception ex)\n{\n\n}\n" }, { "answer_id": 150551, "author": "Curt Hagenlocher", "author_id": 533, "author_profile": "https://Stackoverflow.com/users/533", "pm_score": 4, "selected": false, "text": "catch (Exception)" }, { "answer_id": 150596, "author": "Vivek", "author_id": 7418, "author_profile": "https://Stackoverflow.com/users/7418", "pm_score": 6, "selected": true, "text": "// http://support.microsoft.com/kb/186550\nconst int ERROR_FILE_NOT_FOUND = 2;\nconst int ERROR_ACCESS_DENIED = 5;\nconst int ERROR_NO_APP_ASSOCIATED = 1155; \n\nvoid OpenFile(string filePath)\n{\n Process process = new Process();\n\n try\n {\n // Calls native application registered for the file type\n // This may throw native exception\n process.StartInfo.FileName = filePath;\n process.StartInfo.Verb = \"Open\";\n process.StartInfo.CreateNoWindow = true;\n process.Start();\n }\n catch (Win32Exception e)\n {\n if (e.NativeErrorCode == ERROR_FILE_NOT_FOUND || \n e.NativeErrorCode == ERROR_ACCESS_DENIED ||\n e.NativeErrorCode == ERROR_NO_APP_ASSOCIATED)\n {\n MessageBox.Show(this, e.Message, \"Error\", \n MessageBoxButtons.OK, \n MessageBoxIcon.Exclamation);\n }\n }\n}\n" }, { "answer_id": 150602, "author": "Michael Damatov", "author_id": 23372, "author_profile": "https://Stackoverflow.com/users/23372", "pm_score": 3, "selected": false, "text": "try {\n ...\n} catch(Exception e) {\n ...\n} catch {\n ...\n}\n" }, { "answer_id": 150675, "author": "trampster", "author_id": 78561, "author_profile": "https://Stackoverflow.com/users/78561", "pm_score": 4, "selected": false, "text": "try\n{\n\n}\ncatch\n{\n\n}\n" }, { "answer_id": 151329, "author": "nedruod", "author_id": 5504, "author_profile": "https://Stackoverflow.com/users/5504", "pm_score": 2, "selected": false, "text": "try \n{\n ...\n}\ncatch (Exception e)\n{\n ...\n}\n try\n{\n ...\n}\ncatch\n{\n ...\n}\n" }, { "answer_id": 70616409, "author": "JumpingJezza", "author_id": 345659, "author_profile": "https://Stackoverflow.com/users/345659", "pm_score": 2, "selected": false, "text": "try \n{\n //call native code method\n} \ncatch (Exception ex) \n{\n //do stuff\n} \n private static void Main()\n{\n AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;\n try \n {\n //call native code method\n } \n catch (Exception ex) \n {\n //unhandled exception from native code WILL NOT BE CAUGHT HERE\n } \n}\n\nprivate static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)\n{\n var exception = e.ExceptionObject as Exception;\n //do stuff\n}\n try \n{\n //call native code method\n} \ncatch (Exception ex) \n{\n //do stuff\n} \ncatch \n{\n //do same stuff but without any exception detail\n}\n [HandleProcessCorruptedStateExceptions] \n[SecurityCritical]\nprivate static void Main() \n{ \n try \n {\n //call native code method\n } \n catch (Exception ex) \n {\n //do stuff\n } \n}\n <configuration> \n <runtime> \n <legacyCorruptedStateExceptionsPolicy enabled=\"true\" /> \n </runtime> \n</configuration> \n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17693/" ]
150,548
<p>Despite the rather clear <a href="http://www.adobe.com/support/flash/action_scripts/actionscript_dictionary/actionscript_dictionary620.html" rel="noreferrer">documentation</a> which says that <a href="http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/package.html#parseFloat()" rel="noreferrer">parseFloat()</a> can return NaN as a value, when I write a block like:</p> <pre><code>if ( NaN == parseFloat(input.text) ) { errorMessage.text = "Please enter a number." } </code></pre> <p>I am warned that the comparison will always be false. And testing shows the warning to be correct.</p> <p>Where is the corrected documentation, and how can I write this to work with AS3?</p>
[ { "answer_id": 183596, "author": "Matt W", "author_id": 4969, "author_profile": "https://Stackoverflow.com/users/4969", "pm_score": 2, "selected": false, "text": "if( number != number )\n{\n //Is NaN \n}\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150548", "https://Stackoverflow.com", "https://Stackoverflow.com/users/459/" ]
150,552
<p>I will preface this question by saying, I do not think it is solvable. I also have a workaround, I can create a stored procedure with an OUTPUT to accomplish this, it is just easier to code the sections where I need this checksum using a function.</p> <p>This code will not work because of the <code>Exec SP_ExecuteSQL @SQL</code> calls. Anyone know how to execute dynamic SQL in a function? (and once again, I do not think it is possible. If it is though, I'd love to know how to get around it!)</p> <pre><code>Create Function Get_Checksum ( @DatabaseName varchar(100), @TableName varchar(100) ) RETURNS FLOAT AS BEGIN Declare @SQL nvarchar(4000) Declare @ColumnName varchar(100) Declare @i int Declare @Checksum float Declare @intColumns table (idRecord int identity(1,1), ColumnName varchar(255)) Declare @CS table (MyCheckSum bigint) Set @SQL = 'Insert Into @IntColumns(ColumnName)' + Char(13) + 'Select Column_Name' + Char(13) + 'From ' + @DatabaseName + '.Information_Schema.Columns (NOLOCK)' + Char(13) + 'Where Table_Name = ''' + @TableName + '''' + Char(13) + ' and Data_Type = ''int''' -- print @SQL exec sp_executeSql @SQL Set @SQL = 'Insert Into @CS(MyChecksum)' + Char(13) + 'Select ' Set @i = 1 While Exists( Select 1 From @IntColumns Where IdRecord = @i) begin Select @ColumnName = ColumnName From @IntColumns Where IdRecord = @i Set @SQL = @SQL + Char(13) + CASE WHEN @i = 1 THEN ' Sum(Cast(IsNull(' + @ColumnName + ',0) as bigint))' ELSE ' + Sum(Cast(IsNull(' + @ColumnName + ',0) as bigint))' END Set @i = @i + 1 end Set @SQL = @SQL + Char(13) + 'From ' + @DatabaseName + '..' + @TableName + ' (NOLOCK)' -- print @SQL exec sp_executeSql @SQL Set @Checksum = (Select Top 1 MyChecksum From @CS) Return isnull(@Checksum,0) END GO </code></pre>
[ { "answer_id": 154325, "author": "AJD", "author_id": 23601, "author_profile": "https://Stackoverflow.com/users/23601", "pm_score": 0, "selected": false, "text": "sum(cast(BINARY_CHECKSUM(*) as float)) sum(cast(BINARY_CHECKSUM(*) as float))" }, { "answer_id": 12434613, "author": "Praveen Kumar G", "author_id": 1672896, "author_profile": "https://Stackoverflow.com/users/1672896", "pm_score": 2, "selected": false, "text": "Declare @SQLStr varchar(max) \nDECLARE @tmptable table (<columns>)\nset @SQLStr=dbo.function(<parameters>)\ninsert into @tmptable\nExec (@SQLStr)\n\nselect * from @tmptable\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23601/" ]
150,575
<p>If I have an instance of a System.Timers.Timer that has a long interval - say 1 minute, how can I find out if it is started without waiting for the Tick?</p>
[ { "answer_id": 150597, "author": "Ron Savage", "author_id": 12476, "author_profile": "https://Stackoverflow.com/users/12476", "pm_score": 8, "selected": true, "text": "System.Timer.Timer.Enabled" }, { "answer_id": 150615, "author": "Inisheer", "author_id": 2982, "author_profile": "https://Stackoverflow.com/users/2982", "pm_score": 4, "selected": false, "text": "if (timer1.Enabled)\n{\n // Do Something\n}\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ]
150,577
<p>Where can I test HTML 5 functionality today - is there any test build of any rendering engines which would allow testing, or is it to early? I'm aware that much of the spec hasn't been finalised, but some has, and it would be good to try it out!</p>
[ { "answer_id": 1092034, "author": "Rich Bradshaw", "author_id": 16511, "author_profile": "https://Stackoverflow.com/users/16511", "pm_score": 1, "selected": false, "text": "<header> <section> document.createElement('header');\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150577", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16511/" ]
150,606
<p>I have a website laid out in tables. (a long mortgage form)</p> <p>in each table cell is one HTML object. (text box, radio buttons, etc)</p> <p>What can I do so when each table cell is "tabbed" into it highlights the cell with a very light red (not to be obtrusive, but tell the user where they are)?</p>
[ { "answer_id": 150629, "author": "roenving", "author_id": 23142, "author_profile": "https://Stackoverflow.com/users/23142", "pm_score": 0, "selected": false, "text": "<script type=\"text/javascript\">\n//getParent(startElement,\"tagName\");\nfunction getParent(elm,tN){\n var parElm = elm.parentNode;\n while(parElm.tagName.toLowerCase() != tN.toLowerCase())\n parElm = parElm.parentNode;\n return parElm;\n}\n</script>\n\n<tr><td><input type=\"...\" onfocus=\"getParent(this,'td').style.backgroundColor='#400';\" onblur=\"getParent(this,'td').style.backgroundColor='';\"></td></tr>\n" }, { "answer_id": 150776, "author": "Parand", "author_id": 13055, "author_profile": "https://Stackoverflow.com/users/13055", "pm_score": 3, "selected": false, "text": "$('#mytableid input').focus( function() { \n $(this).addClass('highlight'); \n}).blur( function() {\n $(this).removeClass('highlight'); \n});\n input.highlight { background-color: red; }\n" }, { "answer_id": 150813, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 3, "selected": true, "text": "<table id=\"myTable\">\n <tr>\n <td><input type=\"text\" value=\"hello\" /></td>\n <td><input type=\"checkbox\" name=\"foo\" value=\"2\" /></td>\n <td><input type=\"button\" value=\"hi\" /></td>\n </tr>\n</table>\n // here is a cross-browser compatible way of connecting \n// handlers to events, in case you don't have one\nfunction attachEventHandler(element, eventToHandle, eventHandler) {\n if(element.attachEvent) {\n element.attachEvent(eventToHandle, eventHandler);\n } else if(element.addEventListener) {\n element.addEventListener(eventToHandle.replace(\"on\", \"\"), eventHandler, false);\n } else {\n element[eventToHandle] = eventHandler;\n }\n}\nattachEventHandler(window, \"onload\", function() {\n var myTable = document.getElementById(\"myTable\");\n var myTableCells = myTable.getElementsByTagName(\"td\");\n for(var cellIndex = 0; cellIndex < myTableCells.length; cellIndex++) {\n var currentTableCell = myTableCells[cellIndex];\n var originalBackgroundColor = currentTableCell.style.backgroundColor;\n for(var childIndex = 0; childIndex < currentTableCell.childNodes.length; childIndex++) {\n var currentChildNode = currentTableCell.childNodes[childIndex];\n attachEventHandler(currentChildNode, \"onfocus\", function(e) {\n (e.srcElement || e.target).parentNode.style.backgroundColor = \"red\";\n });\n attachEventHandler(currentChildNode, \"onblur\", function(e) {\n (e.srcElement || e.target).parentNode.style.backgroundColor = originalBackgroundColor;\n });\n }\n }\n});\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
150,610
<p>The problem itself is simple, but I can't figure out a solution that does it in one query, and here's my "abstraction" of the problem to allow for a simpler explanation:</p> <p><strong>I will let my original explenation stand, but here's a set of sample data and the result i expect:</strong></p> <p>Ok, so here's some sample data, i separated pairs by a blank line</p> <pre><code>------------- | Key | Col | (Together they from a Unique Pair) -------------- | 1 Foo | | 1 Bar | | | | 2 Foo | | | | 3 Bar | | | | 4 Foo | | 4 Bar | -------------- </code></pre> <p>And the result I would expect, <strong>after running the query once</strong>, it need to be able to select this result set in one query:</p> <pre><code>1 - Foo 2 - Foo 3 - Bar 4 - Foo </code></pre> <p><em>Original explenation:</em></p> <p>I have a table, call it <code>TABLE</code> where I have a two columns say <code>ID</code> and <code>NAME</code> which together form the primary key of the table. Now I want to select something where <code>ID=1</code> and then first checks if it can find a row where <code>NAME</code> has the value "John", if "John" does not exist it should look for a row where <code>NAME</code> is "Bruce" - but only return "John" if both "Bruce" and "John" exists or only "John" exists of course.</p> <p>Also note that it should be able to return several rows per query that match the above criteria but with different ID/Name-combinations of course, and that the above explanation is just a simplification of the real problem.</p> <p>I could be completely blinded by my own code and line of thought but I just can't figure this out. </p>
[ { "answer_id": 150624, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": -1, "selected": false, "text": "SELECT f1.id\n ,f1.col\nFROM foo f1 \nLEFT JOIN foo f2\n ON f1.id = f2.id\n AND f2.col = 'Foo'\nWHERE f1.col = 'Foo' \n OR ( f1.col = 'Bar' AND f2.id IS NULL )\n" }, { "answer_id": 150670, "author": "Mladen", "author_id": 21404, "author_profile": "https://Stackoverflow.com/users/21404", "pm_score": 0, "selected": false, "text": "select top 1 * from (\nSELECT 1 as num, * FROM TABLE WHERE ID = 1 AND NAME = 'John'\nunion \nSELECT 2 as num, * FROM TABLE WHERE ID = 1 AND NAME = 'Bruce'\n) t\norder by num \n" }, { "answer_id": 150672, "author": "Ron Savage", "author_id": 12476, "author_profile": "https://Stackoverflow.com/users/12476", "pm_score": 1, "selected": false, "text": "create table #mytest\n (\n id int,\n Name varchar(20)\n );\ngo\n\ninsert into #mytest values (1,'Foo');\ninsert into #mytest values (1,'Bar');\ninsert into #mytest values (2,'Foo');\ninsert into #mytest values (3,'Bar');\ninsert into #mytest values (4,'Foo');\ninsert into #mytest values (4,'Bar');\ngo\n\nselect distinct\n sc.id,\n isnull(fc.Name, sc.Name) sel_name\nfrom\n #mytest sc\n\n LEFT OUTER JOIN #mytest fc\n on (fc.id = sc.id\n and fc.Name = 'Foo')\n" }, { "answer_id": 150682, "author": "Neall", "author_id": 619, "author_profile": "https://Stackoverflow.com/users/619", "pm_score": -1, "selected": false, "text": "SELECT DISTINCT ON (id) id, name\nFROM mytable\nORDER BY id, name = 'John' DESC;\n SELECT DISTINCT ON (key) key, col\nFROM mytable\nORDER BY key, col = 'Foo' DESC;\n 1 - Foo\n2 - Foo\n3 - Bar\n4 - Foo\n" }, { "answer_id": 150692, "author": "thr", "author_id": 452521, "author_profile": "https://Stackoverflow.com/users/452521", "pm_score": 0, "selected": false, "text": "SELECT *\nFROM users\nWHERE name = \"bruce\"\nOR (\n name = \"john\"\n AND NOT id\n IN (\n SELECT id\n FROM posts\n WHERE name = \"bruce\"\n )\n)\n" }, { "answer_id": 150723, "author": "thr", "author_id": 452521, "author_profile": "https://Stackoverflow.com/users/452521", "pm_score": 0, "selected": false, "text": "-------------\n| Key | Col | (Together they from a Unique Pair)\n--------------\n| 1 Foo |\n| 1 Bar |\n| |\n| 2 Foo |\n| |\n| 3 Bar |\n| |\n| 4 Foo |\n| 4 Bar |\n--------------\n 1 - Foo\n2 - Foo\n3 - Bar\n4 - Foo\n" }, { "answer_id": 150842, "author": "Matt Rogish", "author_id": 2590, "author_profile": "https://Stackoverflow.com/users/2590", "pm_score": 3, "selected": true, "text": "mysql> select * from foo;\n+----+-----+\n| id | col |\n+----+-----+\n| 1 | Bar | \n| 1 | Foo | \n| 2 | Foo | \n| 3 | Bar | \n| 4 | Bar | \n| 4 | Foo | \n+----+-----+\n\nSELECT id\n , col\n FROM foo f1 \n WHERE col = 'Foo' \n OR ( col = 'Bar' AND NOT EXISTS( SELECT * \n FROM foo f2\n WHERE f1.id = f2.id \n AND f2.col = 'Foo' \n ) \n ); \n\n+----+-----+\n| id | col |\n+----+-----+\n| 1 | Foo | \n| 2 | Foo | \n| 3 | Bar | \n| 4 | Foo | \n+----+-----+\n" }, { "answer_id": 164759, "author": "GilM", "author_id": 10192, "author_profile": "https://Stackoverflow.com/users/10192", "pm_score": 0, "selected": false, "text": "CREATE TABLE T (id int, col varchar(10));\n\nINSERT T VALUES (1, 'Foo')\nINSERT T VALUES (1, 'Bar')\nINSERT T VALUES (2, 'Foo')\nINSERT T VALUES (3, 'Bar')\nINSERT T VALUES (4, 'Foo')\nINSERT T VALUES (4, 'Bar')\n\nSELECT id,col\nFROM \n(SELECT id, col,\n ROW_NUMBER() OVER (\n PARTITION BY id \n ORDER BY \n CASE col \n WHEN 'Foo' THEN 1\n WHEN 'Bar' THEN 2 \n ELSE 3 END\n ) AS RowNum \n FROM T\n) AS X\nWHERE RowNum = 1\nORDER BY id\n" }, { "answer_id": 3933626, "author": "Brad", "author_id": 475816, "author_profile": "https://Stackoverflow.com/users/475816", "pm_score": 1, "selected": false, "text": "MAX() group by ... select id, max(col) from foo group by id\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/452521/" ]
150,622
<p>I'm trying to do this</p> <pre><code>SELECT `Name`,`Value` FROM `Constants` WHERE `Name` NOT IN ('Do not get this one'|'or this one'); </code></pre> <p>But it doesn't seem to work.</p> <p>How do I get all the values, except for a select few, without doing this:</p> <pre><code>SELECT `Name`,`Value` FROM `Constants` WHERE `Name` != 'Do not get this one' AND `Name` != 'or this one' </code></pre> <p>The first one works with int values, but doesn't work with varchar, is there a syntax like the first one, that performs like the second query?</p>
[ { "answer_id": 150627, "author": "jkramer", "author_id": 12523, "author_profile": "https://Stackoverflow.com/users/12523", "pm_score": 2, "selected": false, "text": "IN('foo', 'bar')" }, { "answer_id": 150631, "author": "skaffman", "author_id": 21234, "author_profile": "https://Stackoverflow.com/users/21234", "pm_score": 1, "selected": false, "text": "SELECT `Name`,`Value` FROM `Constants` WHERE `Name` NOT IN ('Do not get this one','or this one');\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/144/" ]
150,638
<p>Sometimes it feels that my company is the only company in the world using Ruby but not Ruby on Rails, to the point that Rails has almost become synonymous with Ruby.</p> <p>I'm sure this isn't really true, but it'd be fun to hear some stories about non-Rails Ruby usage out there.</p>
[ { "answer_id": 7800691, "author": "DigitalRoss", "author_id": 140740, "author_profile": "https://Stackoverflow.com/users/140740", "pm_score": 3, "selected": false, "text": "sh(1)," } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150638", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13051/" ]
150,645
<p>The MSDN states that the method returns</p> <blockquote> <p>true if the method is successfully queued; NotSupportedException is thrown if the work item is not queued.</p> </blockquote> <p>For testing purposes how to get the method to return <code>false</code>? Or it is just a "suboptimal" class design?</p>
[ { "answer_id": 150688, "author": "herbrandson", "author_id": 13181, "author_profile": "https://Stackoverflow.com/users/13181", "pm_score": 4, "selected": true, "text": "[MethodImpl(MethodImplOptions.InternalCall)]\nprivate static extern bool AdjustThreadsInPool(uint QueueLength);\n" }, { "answer_id": 150719, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 1, "selected": false, "text": "return false NotSupportedException" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150645", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23372/" ]
150,646
<p>I'm trying to create a new Excel file using jxl, but am having a hard time finding examples in their API documentation and online.</p>
[ { "answer_id": 150713, "author": "Aaron", "author_id": 2628, "author_profile": "https://Stackoverflow.com/users/2628", "pm_score": 5, "selected": true, "text": "try {\n String fileName = \"file.xls\";\n WritableWorkbook workbook = Workbook.createWorkbook(new File(fileName));\n workbook.createSheet(\"Sheet1\", 0);\n workbook.createSheet(\"Sheet2\", 1);\n workbook.createSheet(\"Sheet3\", 2);\n workbook.write();\n workbook.close();\n} catch (WriteException e) {\n\n}\n" }, { "answer_id": 15957747, "author": "Zaheer Astori", "author_id": 2271921, "author_profile": "https://Stackoverflow.com/users/2271921", "pm_score": 2, "selected": false, "text": "try {\n String fileName = \"file.xls\";\n WritableWorkbook workbook = Workbook.createWorkbook(new File(fileName));\n WritableSheet writablesheet1 = workbook.createSheet(\"Sheet1\", 0);\n WritableSheet writablesheet2 = workbook.createSheet(\"Sheet2\", 1);\n WritableSheet writablesheet3 = workbook.createSheet(\"Sheet3\", 2);\n Label label1 = new Label(\"Emp_Name\");\n Label label2 = new Label(\"Emp_FName\");\n Label label3 = new Label(\"Emp_Salary\");\n writablesheet1.addCell(label1);\n writablesheet2.addCell(label2);\n writablesheet3.addCell(label3);\n workbook.write();\n workbook.close();\n} catch (WriteException e) {\n\n}\n" }, { "answer_id": 32281159, "author": "Almir Campos", "author_id": 2457251, "author_profile": "https://Stackoverflow.com/users/2457251", "pm_score": 2, "selected": false, "text": "/**\n *\n * @author Almir Campos\n */\npublic class Write01\n{\n public void test01() throws IOException, WriteException\n {\n // Initial settings\n File file = new File( \"c:/tmp/genexcel.xls\" );\n WorkbookSettings wbs = new WorkbookSettings();\n wbs.setLocale( new Locale( \"en\", \"EN\" ) );\n // Creates the workbook\n WritableWorkbook wwb = Workbook.createWorkbook( file, wbs );\n // Creates the sheet inside the workbook\n wwb.createSheet( \"Report\", 0 );\n // Makes the sheet writable\n WritableSheet ws = wwb.getSheet( 0 );\n // Creates a cell inside the sheet\n //CellView cv = new CellView();\n Number n;\n Label l;\n Formula f;\n for ( int i = 0; i < 10; i++ )\n {\n // A\n n = new Number( 0, i, i );\n ws.addCell( n );\n // B\n l = new Label( 1, i, \"by\" );\n ws.addCell( l );\n // C\n n = new Number( 2, i, i + 1 );\n ws.addCell( n );\n // D\n l = new Label( 3, i, \"is\" );\n ws.addCell( l );\n // E\n f = new Formula(4, i, \"A\" + (i+1) + \"*C\" + (i+1) );\n ws.addCell( f );\n }\n wwb.write();\n wwb.close();\n }\n}\n" }, { "answer_id": 37732850, "author": "Kavos Khajavi", "author_id": 4433550, "author_profile": "https://Stackoverflow.com/users/4433550", "pm_score": -1, "selected": false, "text": "public void exportToExcel() {\n final String fileName = \"TodoList2.xls\";\n\n //Saving file in external storage\n File sdCard = Environment.getExternalStorageDirectory();\n File directory = new File(sdCard.getAbsolutePath() + \"/javatechig.todo\");\n\n //create directory if not exist\n if(!directory.isDirectory()){\n directory.mkdirs();\n }\n\n //file path\n File file = new File(directory, fileName);\n\n WorkbookSettings wbSettings = new WorkbookSettings();\n wbSettings.setLocale(new Locale(\"en\", \"EN\"));\n WritableWorkbook workbook;\n\n\n try {\n workbook = Workbook.createWorkbook(file, wbSettings);\n //Excel sheet name. 0 represents first sheet\n WritableSheet sheet = workbook.createSheet(\"MyShoppingList\", 0);\n\n\n\n Cursor cursor = mydb.rawQuery(\"select * from Contact\", null);\n\n try {\n sheet.addCell(new Label(0, 0, \"id\")); // column and row\n sheet.addCell(new Label(1, 0, \"name\"));\n sheet.addCell(new Label(2,0,\"ff \"));\n sheet.addCell(new Label(3,0,\"uu\"));\n if (cursor.moveToFirst()) {\n do {\n String title =cursor.getString(0) ;\n String desc = cursor.getString(1);\n String name=cursor.getString(2);\n String family=cursor.getString(3);\n\n int i = cursor.getPosition() + 1;\n sheet.addCell(new Label(0, i, title));\n sheet.addCell(new Label(1, i, desc));\n sheet.addCell(new Label(2,i,name));\n sheet.addCell(new Label(3,i,family));\n } while (cursor.moveToNext());\n }\n //closing cursor\n cursor.close();\n } catch (RowsExceededException e) {\n e.printStackTrace();\n } catch (WriteException e) {\n e.printStackTrace();\n }\n workbook.write();\n try {\n workbook.close();\n } catch (WriteException e) {\n e.printStackTrace();\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n}\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150646", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2628/" ]
150,687
<p>I would like to subscribe to the ItemCommand event of a Reorderlist I have on my page. The front end looks like this...</p> <pre><code>&lt;cc1:ReorderList id="ReorderList1" runat="server" CssClass="Sortables" Width="400" OnItemReorder="ReorderList1_ItemReorder" OnItemCommand="ReorderList1_ItemCommand"&gt; ... &lt;asp:ImageButton ID="btnDelete" runat="server" ImageUrl="delete.jpg" CommandName="delete" CssClass="playClip" /&gt; ... &lt;/cc1:ReorderList&gt; </code></pre> <p>in the back-end I have this on Page_Load</p> <pre><code>ReorderList1.ItemCommand += new EventHandler&lt;AjaxControlToolkit.ReorderListCommandEventArgs&gt;(ReorderList1_ItemCommand); </code></pre> <p>and this function defined</p> <pre><code>protected void ReorderList1_ItemCommand(object sender, AjaxControlToolkit.ReorderListCommandEventArgs e) { if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) { if (e.CommandName == "delete") { //do something here that deletes the list item } } } </code></pre> <p>Despite my best efforts though, I can't seem to get this event to fire off. How do you properly subscribe to this events in a ReorderList control?</p>
[ { "answer_id": 151417, "author": "Fung", "author_id": 8280, "author_profile": "https://Stackoverflow.com/users/8280", "pm_score": 1, "selected": false, "text": "CommandName=\"delete\"" }, { "answer_id": 467777, "author": "roman m", "author_id": 3661, "author_profile": "https://Stackoverflow.com/users/3661", "pm_score": 2, "selected": false, "text": "<cc2:ReorderList ID=\"rlEvents\" runat=\"server\" AllowReorder=\"True\" CssClass=\"reorderList\"\n DataKeyField=\"EventId\" DataSourceID=\"odsEvents\" PostBackOnReorder=\"False\"\n SortOrderField=\"EventOrder\" OnDeleteCommand=\"rlEvents_DeleteCommand\">\n...\n<asp:ImageButton ID=\"btnDeleteEvent\" runat=\"server\" CommandName=\"Delete\" CommandArgument='<%# Eval(\"EventId\") %>' ImageUrl=\"~/images/delete.gif\" />\n...\n</cc2:ReorderList>\n protected void rlEvents_DeleteCommand(object sender, AjaxControlToolkit.ReorderListCommandEventArgs e)\n{\n // delete the item\n // this will give you the DataKeyField for the current record -> int.Parse(e.CommandArgument.ToString());\n //rebind the ReorderList\n}\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150687", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
150,690
<p><strong>Problem:</strong></p> <p>Given a list of strings, find the substring which, if subtracted from the beginning of all strings where it matches and replaced by an escape byte, gives the shortest total length.</p> <p><strong>Example:</strong></p> <p><code>"foo"</code>, <code>"fool"</code>, <code>"bar"</code></p> <p>The result is: "foo" as the base string with the strings <code>"\0"</code>, <code>"\0l"</code>, <code>"bar"</code> and a total length of 9 bytes. <code>"\0"</code> is the escape byte. The sum of the length of the original strings is 10, so in this case we only saved one byte.</p> <p><strong>A naive algorithm would look like:</strong></p> <pre><code>for string in list for i = 1, i &lt; length of string calculate total length based on prefix of string[0..i] if better than last best, save it return the best prefix </code></pre> <p>That will give us the answer, but it's something like O((n*m)^2), which is too expensive.</p>
[ { "answer_id": 150729, "author": "nlucaroni", "author_id": 157, "author_profile": "https://Stackoverflow.com/users/157", "pm_score": 4, "selected": true, "text": " f_2 b_1\n / |\n o_2 a_1\n | |\n o_2 r_1\n |\n l_1\n (depth * frequency)" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23423/" ]
150,695
<p>It seems like Sql Reporting Services Server logs information in several places including web server logs and logging tables in the database. Where are all the locations SSRS logs to, and what type of errors are logged in each place?</p>
[ { "answer_id": 150896, "author": "Tomas", "author_id": 23360, "author_profile": "https://Stackoverflow.com/users/23360", "pm_score": 5, "selected": true, "text": "select * from executionlog\n C:\\Program Files\\Microsoft SQL Server\\MSSQL.3\\Reporting Services\\LogFiles\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1644/" ]
150,726
<p>I was wondering how to use <code>cin</code> so that if the user does not enter in any value and just pushes <code>ENTER</code> that <code>cin</code> will recognize this as valid input.</p>
[ { "answer_id": 150761, "author": "CB Bailey", "author_id": 19563, "author_profile": "https://Stackoverflow.com/users/19563", "pm_score": 3, "selected": false, "text": "std::getline // Read a number:\nstd::cout << \"Enter a number:\";\nstd::cin >> my_double;\n\nstd::count << \"Hit enter to continue:\";\nstd::cin >> throwaway_char;\n// Hmmmm, does this work?\n std::getline( std::cin, a_string )" }, { "answer_id": 150768, "author": "Martin Cote", "author_id": 9936, "author_profile": "https://Stackoverflow.com/users/9936", "pm_score": 5, "selected": true, "text": "std::getline #include <iostream>\n#include <string>\n\nstd::string line;\nstd::getline( std::cin, line );\nif( line.empty() ) ...\n" }, { "answer_id": 29024529, "author": "BigAlMoho", "author_id": 4621554, "author_profile": "https://Stackoverflow.com/users/4621554", "pm_score": 2, "selected": false, "text": "char c;\nint num;\n\ncin.get(c); // get a single character\nif (c == 10) return 0; // 10 = ascii linefeed (Enter Key) so exit\nelse cin.putback(c); // else put the character back\ncin >> num; // get user input as expected\n char c;\nint num;\nc = cin.peek(); // read next character without extracting it\nif (c == '\\n') return 0; // linefeed (Enter Key) so exit\ncin >> num; // get user input as expected\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150726", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
150,731
<p>I would like to write some data to a file in Ruby. What is the best way to do that?</p>
[ { "answer_id": 150740, "author": "thesmallprint", "author_id": 12765, "author_profile": "https://Stackoverflow.com/users/12765", "pm_score": -1, "selected": false, "text": "filey = File.new(\"/path/to/the/file\", APPEND)\nfiley.puts \"stuff to write\"\n" }, { "answer_id": 150745, "author": "Alex M", "author_id": 9652, "author_profile": "https://Stackoverflow.com/users/9652", "pm_score": 6, "selected": true, "text": "File.open(\"a_file\", \"w\") do |f|\n f.write \"some data\"\nend\n f << \"some data\" f.puts \"some data\" \"w\" \"a\"" }, { "answer_id": 151610, "author": "jtbandes", "author_id": 23649, "author_profile": "https://Stackoverflow.com/users/23649", "pm_score": 0, "selected": false, "text": "File.open(\"/path/to/file\", \"w\") do |file|\n file.puts \"Hello file!\"\nend\n ri IO" }, { "answer_id": 560727, "author": "alex2k8", "author_id": 62192, "author_profile": "https://Stackoverflow.com/users/62192", "pm_score": 2, "selected": false, "text": "require 'rio'\nrio('foo.txt') < 'bar'\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1681/" ]
150,737
<p>I'm working on a qnx device, and I want to be able to ssh into it. Does anyone have a primer on getting something like openSSH up and running?</p>
[ { "answer_id": 30245089, "author": "Jim McAdams", "author_id": 4721873, "author_profile": "https://Stackoverflow.com/users/4721873", "pm_score": 4, "selected": false, "text": "random -t\nssh-keygen -t rsa -f /etc/ssh/ssh_host_key -b 1024\nssh-keygen -t rsa -f /etc/ssh/ssh_host_rsa_key\nssh-keygen -t dsa -f /etc/ssh/ssh_host_dsa_key\n /etc/group sshd:x:6:user1 /usr/sbin/sshd ssh-keygen -t ecdsa -f /etc/ssh/ssh_host_ecdsa_key\n /var/chroot/sshd/ /etc/ssh/sshd_config Subsystem sftp /usr/libexec/sftp-server ssh/ /etc/ PermitRootLogin yes /etc/ssh/sshd_config" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3575/" ]
150,750
<p>It's clear that a search performance of the generic <code>HashSet&lt;T&gt;</code> class is higher than of the generic <code>List&lt;T&gt;</code> class. Just compare the hash-based key with the linear approach in the <code>List&lt;T&gt;</code> class.</p> <p>However calculating a hash key may itself take some CPU cycles, so for a small amount of items the linear search can be a real alternative to the <code>HashSet&lt;T&gt;</code>.</p> <p>My question: where is the break-even?</p> <p>To simplify the scenario (and to be fair) let's assume that the <code>List&lt;T&gt;</code> class uses the element's <code>Equals()</code> method to identify an item.</p>
[ { "answer_id": 10762995, "author": "innominate227", "author_id": 1418484, "author_profile": "https://Stackoverflow.com/users/1418484", "pm_score": 11, "selected": true, "text": "HashSet<T> List<T> List<T> List<T> List<T> 1 item LIST strs time: 617ms\n1 item HASHSET strs time: 1332ms\n\n2 item LIST strs time: 781ms\n2 item HASHSET strs time: 1354ms\n\n3 item LIST strs time: 950ms\n3 item HASHSET strs time: 1405ms\n\n4 item LIST strs time: 1126ms\n4 item HASHSET strs time: 1441ms\n\n5 item LIST strs time: 1370ms\n5 item HASHSET strs time: 1452ms\n\n6 item LIST strs time: 1481ms\n6 item HASHSET strs time: 1418ms\n\n7 item LIST strs time: 1581ms\n7 item HASHSET strs time: 1464ms\n\n8 item LIST strs time: 1726ms\n8 item HASHSET strs time: 1398ms\n\n9 item LIST strs time: 1901ms\n9 item HASHSET strs time: 1433ms\n\n1 item LIST objs time: 614ms\n1 item HASHSET objs time: 1993ms\n\n4 item LIST objs time: 837ms\n4 item HASHSET objs time: 1914ms\n\n7 item LIST objs time: 1070ms\n7 item HASHSET objs time: 1900ms\n\n10 item LIST objs time: 1267ms\n10 item HASHSET objs time: 1904ms\n\n13 item LIST objs time: 1494ms\n13 item HASHSET objs time: 1893ms\n\n16 item LIST objs time: 1695ms\n16 item HASHSET objs time: 1879ms\n\n19 item LIST objs time: 1902ms\n19 item HASHSET objs time: 1950ms\n\n22 item LIST objs time: 2136ms\n22 item HASHSET objs time: 1893ms\n\n25 item LIST objs time: 2357ms\n25 item HASHSET objs time: 1826ms\n\n28 item LIST objs time: 2555ms\n28 item HASHSET objs time: 1865ms\n\n31 item LIST objs time: 2755ms\n31 item HASHSET objs time: 1963ms\n\n34 item LIST objs time: 3025ms\n34 item HASHSET objs time: 1874ms\n\n37 item LIST objs time: 3195ms\n37 item HASHSET objs time: 1958ms\n\n40 item LIST objs time: 3401ms\n40 item HASHSET objs time: 1855ms\n\n43 item LIST objs time: 3618ms\n43 item HASHSET objs time: 1869ms\n\n46 item LIST objs time: 3883ms\n46 item HASHSET objs time: 2046ms\n\n49 item LIST objs time: 4218ms\n49 item HASHSET objs time: 1873ms\n static void Main(string[] args)\n{\n int times = 10000000;\n\n for (int listSize = 1; listSize < 10; listSize++)\n {\n List<string> list = new List<string>();\n HashSet<string> hashset = new HashSet<string>();\n\n for (int i = 0; i < listSize; i++)\n {\n list.Add(\"string\" + i.ToString());\n hashset.Add(\"string\" + i.ToString());\n }\n\n Stopwatch timer = new Stopwatch();\n timer.Start();\n for (int i = 0; i < times; i++)\n {\n list.Remove(\"string0\");\n list.Add(\"string0\");\n }\n timer.Stop();\n Console.WriteLine(listSize.ToString() + \" item LIST strs time: \" + timer.ElapsedMilliseconds.ToString() + \"ms\");\n\n timer = new Stopwatch();\n timer.Start();\n for (int i = 0; i < times; i++)\n {\n hashset.Remove(\"string0\");\n hashset.Add(\"string0\");\n }\n timer.Stop();\n Console.WriteLine(listSize.ToString() + \" item HASHSET strs time: \" + timer.ElapsedMilliseconds.ToString() + \"ms\");\n Console.WriteLine();\n }\n\n for (int listSize = 1; listSize < 50; listSize+=3)\n {\n List<object> list = new List<object>();\n HashSet<object> hashset = new HashSet<object>();\n\n for (int i = 0; i < listSize; i++)\n {\n list.Add(new object());\n hashset.Add(new object());\n }\n\n object objToAddRem = list[0];\n \n Stopwatch timer = new Stopwatch();\n timer.Start();\n for (int i = 0; i < times; i++)\n {\n list.Remove(objToAddRem);\n list.Add(objToAddRem);\n }\n timer.Stop();\n Console.WriteLine(listSize.ToString() + \" item LIST objs time: \" + timer.ElapsedMilliseconds.ToString() + \"ms\");\n\n timer = new Stopwatch();\n timer.Start();\n for (int i = 0; i < times; i++)\n {\n hashset.Remove(objToAddRem);\n hashset.Add(objToAddRem);\n }\n timer.Stop();\n Console.WriteLine(listSize.ToString() + \" item HASHSET objs time: \" + timer.ElapsedMilliseconds.ToString() + \"ms\");\n Console.WriteLine();\n }\n\n Console.ReadLine();\n}\n" }, { "answer_id": 13089134, "author": "drzaus", "author_id": 1037948, "author_profile": "https://Stackoverflow.com/users/1037948", "pm_score": 5, "selected": false, "text": "stopwatch.start\nfor X times\n exists = list.Contains(lookup);\nstopwatch.stop\n\nstopwatch.start\nfor X times\n exists = hashset.Contains(lookup);\nstopwatch.stop\n ---------- Testing few small strings ------------\nSample items: (16 total)\nvgnwaloqf diwfpxbv tdcdc grfch icsjwk\n...\n\nBenchmarks:\n1: hashset: late -- 100.00 % -- [Elapsed: 0.0018398 sec]\n2: hashset: middle -- 104.19 % -- [Elapsed: 0.0019169 sec]\n3: hashset: end -- 108.21 % -- [Elapsed: 0.0019908 sec]\n4: list: early -- 144.62 % -- [Elapsed: 0.0026607 sec]\n5: hashset: start -- 174.32 % -- [Elapsed: 0.0032071 sec]\n6: list: middle -- 187.72 % -- [Elapsed: 0.0034536 sec]\n7: list: late -- 192.66 % -- [Elapsed: 0.0035446 sec]\n8: list: end -- 215.42 % -- [Elapsed: 0.0039633 sec]\n9: hashset: early -- 217.95 % -- [Elapsed: 0.0040098 sec]\n10: list: start -- 576.55 % -- [Elapsed: 0.0106073 sec]\n\n\n---------- Testing many small strings ------------\nSample items: (10346 total)\ndmnowa yshtrxorj vthjk okrxegip vwpoltck\n...\n\nBenchmarks:\n1: hashset: end -- 100.00 % -- [Elapsed: 0.0017443 sec]\n2: hashset: late -- 102.91 % -- [Elapsed: 0.0017951 sec]\n3: hashset: middle -- 106.23 % -- [Elapsed: 0.0018529 sec]\n4: list: early -- 107.49 % -- [Elapsed: 0.0018749 sec]\n5: list: start -- 126.23 % -- [Elapsed: 0.0022018 sec]\n6: hashset: early -- 134.11 % -- [Elapsed: 0.0023393 sec]\n7: hashset: start -- 372.09 % -- [Elapsed: 0.0064903 sec]\n8: list: middle -- 48,593.79 % -- [Elapsed: 0.8476214 sec]\n9: list: end -- 99,020.73 % -- [Elapsed: 1.7272186 sec]\n10: list: late -- 99,089.36 % -- [Elapsed: 1.7284155 sec]\n\n\n---------- Testing few long strings ------------\nSample items: (19 total)\nhidfymjyjtffcjmlcaoivbylakmqgoiowbgxpyhnrreodxyleehkhsofjqenyrrtlphbcnvdrbqdvji...\n...\n\nBenchmarks:\n1: list: early -- 100.00 % -- [Elapsed: 0.0018266 sec]\n2: list: start -- 115.76 % -- [Elapsed: 0.0021144 sec]\n3: list: middle -- 143.44 % -- [Elapsed: 0.0026201 sec]\n4: list: late -- 190.05 % -- [Elapsed: 0.0034715 sec]\n5: list: end -- 193.78 % -- [Elapsed: 0.0035395 sec]\n6: hashset: early -- 215.00 % -- [Elapsed: 0.0039271 sec]\n7: hashset: end -- 248.47 % -- [Elapsed: 0.0045386 sec]\n8: hashset: start -- 298.04 % -- [Elapsed: 0.005444 sec]\n9: hashset: middle -- 325.63 % -- [Elapsed: 0.005948 sec]\n10: hashset: late -- 431.62 % -- [Elapsed: 0.0078839 sec]\n\n\n---------- Testing many long strings ------------\nSample items: (5000 total)\nyrpjccgxjbketcpmnvyqvghhlnjblhgimybdygumtijtrwaromwrajlsjhxoselbucqualmhbmwnvnpnm\n...\n\nBenchmarks:\n1: list: early -- 100.00 % -- [Elapsed: 0.0016211 sec]\n2: list: start -- 132.73 % -- [Elapsed: 0.0021517 sec]\n3: hashset: start -- 231.26 % -- [Elapsed: 0.003749 sec]\n4: hashset: end -- 368.74 % -- [Elapsed: 0.0059776 sec]\n5: hashset: middle -- 385.50 % -- [Elapsed: 0.0062493 sec]\n6: hashset: late -- 406.23 % -- [Elapsed: 0.0065854 sec]\n7: hashset: early -- 421.34 % -- [Elapsed: 0.0068304 sec]\n8: list: middle -- 18,619.12 % -- [Elapsed: 0.3018345 sec]\n9: list: end -- 40,942.82 % -- [Elapsed: 0.663724 sec]\n10: list: late -- 41,188.19 % -- [Elapsed: 0.6677017 sec]\n\n\n---------- Testing few ints ------------\nSample items: (16 total)\n7266092 60668895 159021363 216428460 28007724\n...\n\nBenchmarks:\n1: hashset: early -- 100.00 % -- [Elapsed: 0.0016211 sec]\n2: hashset: end -- 100.45 % -- [Elapsed: 0.0016284 sec]\n3: list: early -- 101.83 % -- [Elapsed: 0.0016507 sec]\n4: hashset: late -- 108.95 % -- [Elapsed: 0.0017662 sec]\n5: hashset: middle -- 112.29 % -- [Elapsed: 0.0018204 sec]\n6: hashset: start -- 120.33 % -- [Elapsed: 0.0019506 sec]\n7: list: late -- 134.45 % -- [Elapsed: 0.0021795 sec]\n8: list: start -- 136.43 % -- [Elapsed: 0.0022117 sec]\n9: list: end -- 169.77 % -- [Elapsed: 0.0027522 sec]\n10: list: middle -- 237.94 % -- [Elapsed: 0.0038573 sec]\n\n\n---------- Testing many ints ------------\nSample items: (10357 total)\n370826556 569127161 101235820 792075135 270823009\n...\n\nBenchmarks:\n1: list: early -- 100.00 % -- [Elapsed: 0.0015132 sec]\n2: hashset: end -- 101.79 % -- [Elapsed: 0.0015403 sec]\n3: hashset: early -- 102.08 % -- [Elapsed: 0.0015446 sec]\n4: hashset: middle -- 103.21 % -- [Elapsed: 0.0015618 sec]\n5: hashset: late -- 104.26 % -- [Elapsed: 0.0015776 sec]\n6: list: start -- 126.78 % -- [Elapsed: 0.0019184 sec]\n7: hashset: start -- 130.91 % -- [Elapsed: 0.0019809 sec]\n8: list: middle -- 16,497.89 % -- [Elapsed: 0.2496461 sec]\n9: list: end -- 32,715.52 % -- [Elapsed: 0.4950512 sec]\n10: list: late -- 33,698.87 % -- [Elapsed: 0.5099313 sec]\n" }, { "answer_id": 23949528, "author": "nawfal", "author_id": 661933, "author_profile": "https://Stackoverflow.com/users/661933", "pm_score": 7, "selected": false, "text": "List<T> HashSet<T> List<T> +------------+--------+-------------+-----------+----------+----------+-----------+\n| Collection | Random | Containment | Insertion | Addition | Removal | Memory |\n| | access | | | | | |\n+------------+--------+-------------+-----------+----------+----------+-----------+\n| List<T> | O(1) | O(n) | O(n) | O(1)* | O(n) | Lesser |\n| HashSet<T> | O(n) | O(1) | n/a | O(1) | O(1) | Greater** |\n+------------+--------+-------------+-----------+----------+----------+-----------+\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23372/" ]
150,753
<p>I'm currently working on a project for medical image processing, that needs a huge amount of memory. Is there anything I can do to avoid heap fragmentation and to speed up access of image data that has already been loaded into memory?</p> <p>The application has been written in C++ and runs on Windows XP.</p> <p><strong>EDIT:</strong> The application does some preprocessing with the image data, like reformatting, calculating look-up-tables, extracting sub images of interest ... The application needs about 2 GB RAM during processing, of which about 1,5 GB may be used for the image data.</p>
[ { "answer_id": 264620, "author": "Suma", "author_id": 16673, "author_profile": "https://Stackoverflow.com/users/16673", "pm_score": 2, "selected": false, "text": "LARGE_ADDRESS_AWARE" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150753", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2012356/" ]
150,760
<p>Let me first say that being able to take 17 million records from a flat file, pushing to a DB on a remote box and having it take 7 minutes is amazing. SSIS truly is fantastic. But now that I have that data up there, how do I remove duplicates?</p> <p>Better yet, I want to take the flat file, remove the duplicates from the flat file and put them back into another flat file.</p> <p>I am thinking about a:</p> <p><strong><code>Data Flow Task</code></strong></p> <ul> <li>File source (with an associated file connection)</li> <li>A for loop container</li> <li>A script container that contains some logic to tell if another row exists</li> </ul> <p>Thak you, and everyone on this site is incredibly knowledgeable.</p> <p><strong><code>Update:</code></strong> <a href="http://rafael-salas.blogspot.com/2007/04/remove-duplicates-using-t-sql-rank.html" rel="noreferrer">I have found this link, might help in answering this question</a></p>
[ { "answer_id": 150951, "author": "Hector Sosa Jr", "author_id": 12829, "author_profile": "https://Stackoverflow.com/users/12829", "pm_score": 2, "selected": false, "text": "SET NOCOUNT ON\n\nDECLARE @email varchar(100)\n\nSET @email = ''\n\nSET @emailid = (SELECT min(email) from StagingTable WITH (NOLOCK) WHERE email > @email)\n\nWHILE @emailid IS NOT NULL\nBEGIN\n\n -- Do INSERT statement based on the email\n INSERT StagingTable2 (Email)\n FROM StagingTable WITH (NOLOCK) \n WHERE email = @email\n\n SET @emailid = (SELECT min(email) from StagingTable WITH (NOLOCK) WHERE email > @email)\n\nEND\n" }, { "answer_id": 152833, "author": "AJ.", "author_id": 7211, "author_profile": "https://Stackoverflow.com/users/7211", "pm_score": 2, "selected": false, "text": "sort -u inputfile > outputfile\n CREATE UNIQUE INDEX idx1 ON TABLE (col1, col2, ...) WITH IGNORE_DUP_KEY\n" }, { "answer_id": 618952, "author": "Craig Warren", "author_id": 74706, "author_profile": "https://Stackoverflow.com/users/74706", "pm_score": 5, "selected": false, "text": "1 | sample A |\n1 | sample B |\n" }, { "answer_id": 1539283, "author": "Registered User", "author_id": 38332, "author_profile": "https://Stackoverflow.com/users/38332", "pm_score": 1, "selected": false, "text": "WITH \n sample_records \n ( email_address\n , entry_date\n , row_identifier\n )\n AS\n (\n SELECT 'tester@test.com'\n , '2009-10-08 10:00:00'\n , 1\n UNION ALL\n\n SELECT 'tester@test.com'\n , '2009-10-08 10:00:01'\n , 2\n\n UNION ALL\n\n SELECT 'tester@test.com'\n , '2009-10-08 10:00:02'\n , 3\n\n UNION ALL\n\n SELECT 'the_other_test@test.com'\n , '2009-10-08 10:00:00'\n , 4\n\n UNION ALL\n\n SELECT 'the_other_test@test.com'\n , '2009-10-08 10:00:00'\n , 5\n )\n, filter_records \n ( email_address\n , entry_date\n , row_identifier\n , sequential_order\n , reverse_order\n )\n AS\n (\n SELECT email_address\n , entry_date\n , row_identifier\n , 'sequential_order' = ROW_NUMBER() OVER (\n PARTITION BY email_address \n ORDER BY row_identifier ASC)\n , 'reverse_order' = ROW_NUMBER() OVER (\n PARTITION BY email_address\n ORDER BY row_identifier DESC)\n FROM sample_records\n )\n SELECT email_address\n , entry_date\n , row_identifier\n FROM filter_records\n WHERE reverse_order = 1\n ORDER BY email_address;\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7952/" ]
150,762
<p>I have a file that lists filenames, each on it's own line, and I want to test if each exists in a particular directory. For example, some sample lines of the file might be</p> <pre><code>mshta.dll foobar.dll somethingelse.dll </code></pre> <p>The directory I'm interested in is <code>X:\Windows\System32\</code>, so I want to see if the following files exist:</p> <pre><code>X:\Windows\System32\mshta.dll X:\Windows\System32\foobar.dll X:\Windows\System32\somethingelse.dll </code></pre> <p>How can I do this using the Windows command prompt? Also (out of curiosity) how would I do this using bash or another Unix shell?</p>
[ { "answer_id": 150807, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 1, "selected": false, "text": "\ntype file.txt >NUL 2>NUL\nif ERRORLEVEL 1 then echo \"file doesn't exist\"\n \nif ( test -e file.txt ); then echo \"file exists\"; fi\n" }, { "answer_id": 150829, "author": "JesperE", "author_id": 13051, "author_profile": "https://Stackoverflow.com/users/13051", "pm_score": 3, "selected": false, "text": "while read f; do \n [ -f \"$f\" ] && echo \"$f\" exists\ndone < file.txt\n" }, { "answer_id": 150836, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 4, "selected": true, "text": "@echo off\nrem first arg is the file containing filenames\nrem second arg is the target directory\n\nFOR /F %%f IN (%1) DO IF EXIST %2\\%%f ECHO %%f exists in %2\n filename=\"${1:-please specify filename containing filenames}\"\ndirectory=\"${2:-please specify directory to check}\nfor fn in `cat \"$filename\"`\ndo\n [ -f \"$directory\"/\"$fn\" ] && echo \"$fn\" exists in \"$directory\"\ndone\n" }, { "answer_id": 154093, "author": "Zorantula", "author_id": 18108, "author_profile": "https://Stackoverflow.com/users/18108", "pm_score": 2, "selected": false, "text": "for /f %i in (files.txt) do @if exist \"%i\" (@echo Present: %i) else (@echo Missing: %i)\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5616/" ]
150,764
<p>Any code I've seen that uses Regexes tends to use them as a black box:</p> <ol> <li>Put in string</li> <li>Magic Regex</li> <li>Get out string</li> </ol> <p>This doesn't seem a particularly good idea to use in production code, as even a small change can often result in a completely different regex.</p> <p>Apart from cases where the standard is permanent and unchanging, are regexes the way to do things, or is it better to try different methods?</p>
[ { "answer_id": 150812, "author": "jkramer", "author_id": 12523, "author_profile": "https://Stackoverflow.com/users/12523", "pm_score": 3, "selected": false, "text": "x $foo =~ m{\n (some-thing) # matches something\n \\s* # matches any amount of spaces\n (match another thing) # matches something else\n}x;\n" }, { "answer_id": 207446, "author": "Brad Gilbert", "author_id": 1337, "author_profile": "https://Stackoverflow.com/users/1337", "pm_score": 2, "selected": false, "text": "Perl 5.10 Perl 6 (?(DEFINE)(?<name>pattern)...) (?&name) DEFINE /^\n (?&osg)\\ * ( (?&int)(?&dec)? | (?&dec) )\n (?: [eE](?&osg)(?&int) )?\n $\n (?(DEFINE)\n (?<osg>[-+]?) # optional sign\n (?<int>\\d++) # integer\n (?<dec>\\.(?&int)) # decimal fraction\n )\n/x\n" }, { "answer_id": 282021, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "1)\n $dktpat = '/^[^a-z0-9]*'. // skip any initial non-digits\n '([a-z0-9]:)?'. // division within the district\n '(\\d+)'. // year\n '((-)|-?([a-z][a-z])-?)'. // type of court if any - cv, bk, etc.\n '(\\d+)'. // docket sequence number\n '[^0-9]*$/i'; // ignore anything after the sequence number\n if (preg_match($dktpat,$DocketID,$m)) {\n\n2)\n $pat= array (\n 'Row' => '\\s*(\\d*)',\n 'Parties' => '(.*)',\n 'CourtID' => '<a[^>]*>([a-z]*)</a>',\n 'CaseNo' => '<a[^>]*>([a-z0-9:\\-]*)</a>',\n 'FirstFiled' => '([0-9\\/]*)',\n 'NOS' => '(\\d*)',\n 'CaseClosed' => '([0-9\\/]*)',\n 'CaseTitle' => '(.*)',\n );\n // wrap terms in table syntax\n $pat = '#<tr>(<td[^>]*>'.\n implode('</td>)(</tr><tr>)?(<td[^>]*>',$pat).\n '</td>)</tr>#iUx';\n if (preg_match_all ($pat,$this->DocketText,$matches, PREG_PATTERN_ORDER))\n" }, { "answer_id": 2666774, "author": "Timwi", "author_id": 33225, "author_profile": "https://Stackoverflow.com/users/33225", "pm_score": 1, "selected": false, "text": "foreach (var match in Regex.Matches(input, @\"-?(?<number>\\d+)\"))\n{\n Console.WriteLine(match.Groups[\"number\"].Value);\n}\n int number = 0;\nRegex r = Regex.Char('-').Optional().Then(\n Regex.Digit().OneOrMore().Capture(c => number = int.Parse(c))\n);\nforeach (var match in r.Matches(input))\n{\n Console.WriteLine(number);\n}\n instead of: -?(?<number>\\d+)\ncould have: (\"-\" or \"\") + (number = digit * [1..])\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16511/" ]
150,803
<p>I'm working on a little test application at the minute and I have multiple window objects floating around and they each call RegisterWindowEx with the same WNDCLASSEX structure (mainly because they are all an instance of the same class).</p> <p>The first one registers ok, then multiple ones fail, saying class already registered - as expected.</p> <p>My question is - is this bad? I was thinking of using a hash table to store the ATOM results in, to look up before calling RegisterWindow, but it seems Windows does this already? </p>
[ { "answer_id": 150880, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 3, "selected": false, "text": "RegisterClass() UnregisterClass() RegisterClass() UnregisterClass() GetClassInfo()" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/986/" ]
150,814
<p>This is somewhat of a follow-up to an answer <a href="https://stackoverflow.com/questions/26536/active-x-control-javascript">here</a>.</p> <p>I have a custom ActiveX control that is raising an event ("ReceiveMessage" with a "msg" parameter) that needs to be handled by Javascript in the web browser. Historically we've been able to use the following IE-only syntax to accomplish this on different projects:</p> <pre><code>function MyControl::ReceiveMessage(msg) { alert(msg); } </code></pre> <p>However, when inside a layout in which the control is buried, the Javascript cannot find the control. Specifically, if we put this into a plain HTML page it works fine, but if we put it into an ASPX page wrapped by the <code>&lt;Form&gt;</code> tag, we get a "MyControl is undefined" error. We've tried variations on the following:</p> <pre><code>var GetControl = document.getElementById("MyControl"); function GetControl::ReceiveMessage(msg) { alert(msg); } </code></pre> <p>... but it results in the Javascript error "GetControl is undefined."</p> <p>What is the proper way to handle an event being sent from an ActiveX control? Right now we're only interested in getting this working in IE. This has to be a custom ActiveX control for what we're doing.</p> <p>Thanks.</p>
[ { "answer_id": 152724, "author": "Raelshark", "author_id": 19678, "author_profile": "https://Stackoverflow.com/users/19678", "pm_score": 5, "selected": true, "text": "<script for=\"MyControl\" event=\"ReceiveMessage(msg)\">\n alert(msg);\n</script>\n" }, { "answer_id": 283053, "author": "Adam", "author_id": 1341, "author_profile": "https://Stackoverflow.com/users/1341", "pm_score": 1, "selected": false, "text": "function MyControl::ReceiveMessage(msg)\n{\n alert(msg);\n}\n" }, { "answer_id": 379872, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": " var clock = new ActiveXObject(\"Clocks.clock\");\n var extendedClockEvents = clock.ExtendedClockEvents();\n // Here you assign (subscribe to) your callback method!\n extendedClockEvents.ScriptCallbackObject = clock_Callback; \n ...\n function clock_Callback(time)\n {\n document.getElementById(\"text_tag\").innerHTML = time;\n }\n" }, { "answer_id": 427024, "author": "Frank Schwieterman", "author_id": 32203, "author_profile": "https://Stackoverflow.com/users/32203", "pm_score": 1, "selected": false, "text": "<object id=\"ActivexObject\" name=\"ActivexObject\" classid=\"clsid:15C5A3F3-F8F7-4d5e-B87E-5084CC98A25A\"></object> <script> function document.ActivexObject::OnCallback(callback, callbackparam){ callback(callbackparam); } </script>" }, { "answer_id": 3203444, "author": "Zuhaib", "author_id": 25138, "author_profile": "https://Stackoverflow.com/users/25138", "pm_score": 3, "selected": false, "text": "function onEventHandler(arg1, arg2){\n // do something\n}\n\nwindow.onload = function(){\n var yourActiveXObject = document.getElementById('YourObjectTagID');\n if(typeof(yourActiveXObject) === 'undefined' || yourActiveXObject === null){\n alert('Unable to load ActiveX');\n return;\n }\n\n // attach events\n var status = yourActiveXObject.attachEvent('EventName', onEventHandler);\n}\n" }, { "answer_id": 10557222, "author": "Taudris", "author_id": 108064, "author_profile": "https://Stackoverflow.com/users/108064", "pm_score": 1, "selected": false, "text": "//create the ActiveX\nvar ax = $(\"<object></object>\", {\n classid: \"clsid:\" + clsid,\n codebase: install ? cabfile : undefined,\n width: 0,\n height: 0,\n id: '__ax_'+idIncrement++\n})\n.appendTo('#someHost');\n //this function registers an event listener for an ActiveX object (obviously for IE only)\n//the this argument for the handler is the ActiveX object.\nfunction registerAXEvent(control, name, handler) {\n control = jQuery(control);\n\n //can't use closures through the string due to the parameter renaming done by the JavaScript compressor\n //can't use jQuery.data() on ActiveX objects because it uses expando properties\n\n var id = control[0].id;\n\n var axe = registerAXEvent.axevents = registerAXEvent.axevents || {};\n axe[id] = axe[id] || {};\n axe[id][name] = handler;\n\n var script =\n \"(function(){\"+\n \"var f=registerAXEvent.axevents['\" + id + \"']['\" + name + \"'],e=jQuery('#\" + id + \"');\"+\n \"function document.\" + id + \"::\" + name + \"(){\"+\n \"f.apply(e,arguments);\"+\n \"}\"+\n \"})();\";\n eval(script);\n}\n <object>" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19678/" ]
150,845
<p>I'm having issues creating an ActionLink using Preview 5. All the docs I can find describe the older generic version.</p> <p>I'm constructing links on a list of jobs on the page /jobs. Each job has a guid, and I'd like to construct a link to /jobs/details/{guid} so I can show details about the job. My jobs controller has an Index controller and a Details controller. The Details controller takes a guid. I've tried this</p> <pre><code>&lt;%= Html.ActionLink(job.Name, "Details", job.JobId); %&gt; </code></pre> <p>However, that gives me the url "/jobs/details". What am I missing here?</p> <hr> <p>Solved, with your help.</p> <p>Route (added before the catch-all route):</p> <pre><code>routes.Add(new Route("Jobs/Details/{id}", new MvcRouteHandler()) { Defaults = new RouteValueDictionary(new { controller = "Jobs", action = "Details", id = new Guid() } }); </code></pre> <p>Action link:</p> <pre><code>&lt;%= Html.ActionLink(job.Name, "Details", new { id = job.JobId }) %&gt; </code></pre> <p>Results in the html anchor:</p> <blockquote> <p><a href="http://localhost:3570/WebsiteAdministration/Details?id=2db8cee5-3c56-4861-aae9-a34546ee2113" rel="nofollow noreferrer">http://localhost:3570/WebsiteAdministration/Details?id=2db8cee5-3c56-4861-aae9-a34546ee2113</a></p> </blockquote> <p>So, its confusing routes. I moved my jobs route definition before the website admin and it works now. Obviously, my route definitions SUCK. I need to read more examples.</p> <p>A side note, my links weren't showing, and quickwatches weren't working (can't quickwatch an expression with an anonymous type), which made it much harder to figure out what was going on here. It turned out the action links weren't showing because of a very minor typo:</p> <pre><code>&lt;% Html.ActionLink(job.Name, "Details", new { id = job.JobId })%&gt; </code></pre> <p>That's gonna get me again.</p>
[ { "answer_id": 150875, "author": "Jonathan Carter", "author_id": 6412, "author_profile": "https://Stackoverflow.com/users/6412", "pm_score": 3, "selected": true, "text": "<%= Html.ActionLink(job.Name, \"Details\", new { guid = job.JobId}); %>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
150,891
<p>I have a table with rowID, longitude, latitude, businessName, url, caption. This might look like:</p> <pre><code>rowID | long | lat | businessName | url | caption 1 20 -20 Pizza Hut yum.com null </code></pre> <p>How do I delete all of the duplicates, but only keep the one that has a URL (first priority), or keep the one that has a caption if the other doesn't have a URL (second priority) and delete the rest?</p>
[ { "answer_id": 150967, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 3, "selected": true, "text": "DECLARE @LoopVar int\n\nDECLARE\n @long int,\n @lat int,\n @businessname varchar(30),\n @winner int\n\nSET @LoopVar = (SELECT MIN(rowID) FROM Locations)\n\nWHILE @LoopVar is not null\nBEGIN\n --initialize the variables.\n SELECT \n @long = null,\n @lat = null,\n @businessname = null,\n @winner = null\n\n -- load data from the known good row. \n SELECT\n @long = long,\n @lat = lat,\n @businessname = businessname\n FROM Locations\n WHERE rowID = @LoopVar\n\n --find the winning row with that data\n SELECT top 1 @Winner = rowID\n FROM Locations\n WHERE @long = long\n AND @lat = lat\n AND @businessname = businessname\n ORDER BY\n CASE WHEN URL is not null THEN 1 ELSE 2 END,\n CASE WHEN Caption is not null THEN 1 ELSE 2 END,\n RowId\n\n --delete any losers.\n DELETE FROM Locations\n WHERE @long = long\n AND @lat = lat\n AND @businessname = businessname\n AND @winner != rowID\n\n -- prep the next loop value.\n SET @LoopVar = (SELECT MIN(rowID) FROM Locations WHERE @LoopVar < rowID)\nEND\n" }, { "answer_id": 150991, "author": "Forgotten Semicolon", "author_id": 1960, "author_profile": "https://Stackoverflow.com/users/1960", "pm_score": 0, "selected": false, "text": "UPDATE BusinessLocations\nSET BusinessLocations.url = LocationsWithUrl.url\nFROM BusinessLocations\nINNER JOIN (\n SELECT long, lat, businessName, url, caption\n FROM BusinessLocations \n WHERE url IS NOT NULL) LocationsWithUrl \n ON BusinessLocations.long = LocationsWithUrl.long\n AND BusinessLocations.lat = LocationsWithUrl.lat\n AND BusinessLocations.businessName = LocationsWithUrl.businessName\n\nUPDATE BusinessLocations\nSET BusinessLocations.caption = LocationsWithCaption.caption\nFROM BusinessLocations\nINNER JOIN (\n SELECT long, lat, businessName, url, caption\n FROM BusinessLocations \n WHERE caption IS NOT NULL) LocationsWithCaption \n ON BusinessLocations.long = LocationsWithCaption.long\n AND BusinessLocations.lat = LocationsWithCaption.lat\n AND BusinessLocations.businessName = LocationsWithCaption.businessName\n" }, { "answer_id": 151015, "author": "Constantin", "author_id": 20310, "author_profile": "https://Stackoverflow.com/users/20310", "pm_score": 1, "selected": false, "text": "delete from T as t1\nwhere /* delete if there is a \"better\" row\n with same long, lat and businessName */\n exists(\n select * from T as t2 where\n t1.rowID <> t2.rowID\n and t1.long = t2.long\n and t1.lat = t2.lat\n and t1.businessName = t2.businessName \n and\n case when t1.url is null then 0 else 4 end\n /* 4 points for non-null url */\n + case when t1.businessName is null then 0 else 2 end\n /* 2 points for non-null businessName */\n + case when t1.rowID > t2.rowId then 0 else 1 end\n /* 1 point for having smaller rowId */\n <\n case when t2.url is null then 0 else 4 end\n + case when t2.businessName is null then 0 else 2 end\n )\n" }, { "answer_id": 151057, "author": "Todd Waldorf", "author_id": 17894, "author_profile": "https://Stackoverflow.com/users/17894", "pm_score": 1, "selected": false, "text": "delete MyTable\nfrom MyTable\nleft outer join (\n select min(rowID) as rowID, long, lat, businessName\n from MyTable\n where url is not null\n group by long, lat, businessName\n ) as HasUrl\n on MyTable.long = HasUrl.long\n and MyTable.lat = HasUrl.lat\n and MyTable.businessName = HasUrl.businessName\nleft outer join (\n select min(rowID) as rowID, long, lat, businessName\n from MyTable\n where caption is not null\n group by long, lat, businessName\n ) HasCaption\n on MyTable.long = HasCaption.long\n and MyTable.lat = HasCaption.lat\n and MyTable.businessName = HasCaption.businessName\nleft outer join (\n select min(rowID) as rowID, long, lat, businessName\n from MyTable\n where url is null\n and caption is null\n group by long, lat, businessName\n ) HasNone \n on MyTable.long = HasNone.long\n and MyTable.lat = HasNone.lat\n and MyTable.businessName = HasNone.businessName\nwhere MyTable.rowID <> \n coalesce(HasUrl.rowID, HasCaption.rowID, HasNone.rowID)\n" }, { "answer_id": 151410, "author": "Darrel Miller", "author_id": 6819, "author_profile": "https://Stackoverflow.com/users/6819", "pm_score": 2, "selected": false, "text": "DELETE restaurant\nWHERE rowID in \n(SELECT rowID\n FROM restaurant\n EXCEPT\n SELECT rowID \n FROM (\n SELECT rowID, Rank() over (Partition BY BusinessName, lat, long ORDER BY url DESC, caption DESC ) AS Rank\n FROM restaurant\n ) rs WHERE Rank = 1)\n" }, { "answer_id": 152388, "author": "mancaus", "author_id": 13797, "author_profile": "https://Stackoverflow.com/users/13797", "pm_score": 1, "selected": false, "text": "\n;WITH GroupedRows AS\n( SELECT rowID, Row_Number() OVER (Partition BY BusinessName, lat, long ORDER BY url DESC, caption DESC) rowNum \n FROM restaurant\n)\nDELETE r\nFROM restaurant r\nJOIN GroupedRows gr ON r.rowID = gr.rowID\nWHERE gr.rowNum > 1\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7952/" ]
150,900
<p>I am creating a Windows Forms control derived from UserControl to be embedded in a WPF app. I have generally followed the procedures given in <a href="http://www.codeproject.com/KB/WPF/WPFOpenGL.aspx?display=Print" rel="nofollow noreferrer">this link</a>.</p> <pre><code>public ref class CTiledImgViewControl : public UserControl { ... virtual void OnPaint( PaintEventArgs^ e ) override; ... }; </code></pre> <p>And in my CPP file:</p> <pre><code>void CTiledImgViewControl::OnPaint( PaintEventArgs^ e ) { UserControl::OnPaint(e); // do something interesting... } </code></pre> <p>Everything compiles and runs, however the OnPaint method is never getting called.</p> <p>Any ideas of things to look for? I've done a lot with C++, but am pretty new to WinForms and WPF, so it could well be something obvious...</p>
[ { "answer_id": 151143, "author": "Jeff Yates", "author_id": 23234, "author_profile": "https://Stackoverflow.com/users/23234", "pm_score": 3, "selected": true, "text": "OnPaint UserControl SetStyle UserPaint OnPaint SetStyle(ControlStyles::UserPaint, true);\n OnPaint OnPaint WM_PAINT UserControl OnPaint WndProc WM_PAINT" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150900", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3114/" ]
150,901
<p>Anyone know a good Regex expression to drop in the ValidationExpression to be sure that my users are only entering ASCII characters? </p> <pre><code>&lt;asp:RegularExpressionValidator id="myRegex" runat="server" ControlToValidate="txtName" ValidationExpression="???" ErrorMessage="Non-ASCII Characters" Display="Dynamic" /&gt; </code></pre>
[ { "answer_id": 150925, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 0, "selected": false, "text": "^([\\x00-\\xff]*)$\n" }, { "answer_id": 153549, "author": "Jon Biddle", "author_id": 22895, "author_profile": "https://Stackoverflow.com/users/22895", "pm_score": 3, "selected": true, "text": "^([^\\x0d\\x0a\\x20-\\x7e\\t]*)$\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150901", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13954/" ]
150,902
<p>How can an object be loaded via Hibernate based on a field value of a member object? For example, suppose the following classes existed, with a one-to-one relationship between bar and foo:</p> <pre><code>Foo { Long id; } Bar { Long id; Foo aMember; } </code></pre> <p>How could one use Hibernate Criteria to load Bar if you only had the id of Foo?</p> <p>The first thing that leapt into my head was to load the Foo object and set that as a Criterion to load the Bar object, but that seems wasteful. Is there an effective way to do this with Criteria, or is HQL the way this should be handled?</p>
[ { "answer_id": 150973, "author": "laz", "author_id": 8753, "author_profile": "https://Stackoverflow.com/users/8753", "pm_score": 3, "selected": true, "text": "session.createCriteria(Bar.class).\n createAlias(\"aMember\", \"a\").\n add(Restrictions.eq(\"a.id\", fooId));\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
150,953
<p>I get the following error when attempting to install <a href="http://docs.rubygems.org/" rel="nofollow noreferrer">RubyGems</a>. I've tried Googling but have had no luck there. Has anybody encountered and resolved this issue before?</p> <pre><code> C:\rubygems-1.3.0> ruby setup.rb . . install -c -m 0644 rubygems/validator.rb C:/Ruby/lib/ruby/site_ruby/1.8/rubygems/validator.rb install -c -m 0644 rubygems/version.rb C:/Ruby/lib/ruby/site_ruby/1.8/rubygems/version.rb install -c -m 0644 rubygems/version_option.rb C:/Ruby/lib/ruby/site_ruby/1.8/rubygems/version_option.rb install -c -m 0644 rubygems.rb C:/Ruby/lib/ruby/site_ruby/1.8/rubygems.rb install -c -m 0644 ubygems.rb C:/Ruby/lib/ruby/site_ruby/1.8/ubygems.rb cp gem C:/Users/brian/AppData/Local/Temp/gem install -c -m 0755 C:/Users/brian/AppData/Local/Temp/gem C:/Ruby/bin/gem rm C:/Users/brian/AppData/Local/Temp/gem install -c -m 0755 C:/Users/brian/AppData/Local/Temp/gem.bat C:/Ruby/bin/gem.bat rm C:/Users/brian/AppData/Local/Temp/gem.bat Removing old RubyGems RDoc and ri Installing rubygems-1.3.0 ri into C:/Ruby/lib/ruby/gems/1.8/doc/rubygems-1.3.0/ri ./lib/rubygems.rb:713:in `set_paths': undefined method `uid' for nil:NilClass (NoMethodError) from ./lib/rubygems.rb:711:in `each' from ./lib/rubygems.rb:711:in `set_paths' from ./lib/rubygems.rb:518:in `path' from ./lib/rubygems/source_index.rb:66:in `installed_spec_directories' from ./lib/rubygems/source_index.rb:56:in `from_installed_gems' from ./lib/rubygems.rb:726:in `source_index' from ./lib/rubygems.rb:138:in `activate' from ./lib/rubygems.rb:49:in `gem' from setup.rb:279:in `run_rdoc' from setup.rb:296 C:\rubygems-1.3.0></code></pre> <p>I have Ruby 1.8.6 installed on my laptop running Windows Vista.</p>
[ { "answer_id": 150976, "author": "JasonTrue", "author_id": 13433, "author_profile": "https://Stackoverflow.com/users/13433", "pm_score": 3, "selected": true, "text": "require \"rubygems\" ruby -rubygems myscript.rb" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150953", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1969/" ]
150,977
<p>What is the best way to replace all '&amp;lt' with <code>&amp;lt;</code> in a given database column? Basically perform <code>s/&amp;lt[^;]/&amp;lt;/gi</code></p> <p>Notes:</p> <ul> <li>must work in <a href="http://en.wikipedia.org/wiki/Microsoft_SQL_Server#SQL_Server_2005" rel="noreferrer">MS SQL Server</a> 2000</li> <li>Must be repeatable (and not end up with <code>&amp;lt;;;;;;;;;;</code>)</li> </ul>
[ { "answer_id": 151072, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 5, "selected": true, "text": "create table test\n(\n id int identity(1, 1) not null,\n val varchar(25) not null\n)\n\ninsert into test values ('&lt; <- ok, &lt <- nok')\n\nwhile 1 = 1\nbegin\n update test\n set val = left(val, patindex('%&lt[^;]%', val) - 1) +\n '&lt;' +\n right(val, len(val) - patindex('%&lt[^;]%', val) - 2)\n from test\n where val like '%&lt[^;]%'\n\n IF @@ROWCOUNT = 0 BREAK\nend\n\nselect * from test\n" }, { "answer_id": 153669, "author": "leoinfo", "author_id": 6948, "author_profile": "https://Stackoverflow.com/users/6948", "pm_score": 4, "selected": false, "text": "create table test\n(\n id int identity(1, 1) not null,\n val varchar(25) not null\n)\n\ninsert into test values ('&lt; <- ok, &lt <- nok')\n\nWHILE 1 = 1\nBEGIN\n UPDATE test SET\n val = STUFF( val , PATINDEX('%&lt[^;]%', val) + 3 , 0 , ';' )\n FROM test\n WHERE val LIKE '%&lt[^;]%'\n\n IF @@ROWCOUNT = 0 BREAK\nEND\n\nselect * from test\n" }, { "answer_id": 153746, "author": "ilitirit", "author_id": 9825, "author_profile": "https://Stackoverflow.com/users/9825", "pm_score": 3, "selected": false, "text": " UPDATE tableName\n SET columName = REPLACE(columName , '&lt', '&lt;')\n WHERE columnName LIKE '%lt%'\n AND columnName NOT LIKE '%lt;%'\n &lt; UPDATE tableName\n SET columName = REPLACE(columName , '&lt;;', '&lt;')\n" }, { "answer_id": 153845, "author": "Dave Sherohman", "author_id": 18914, "author_profile": "https://Stackoverflow.com/users/18914", "pm_score": 1, "selected": false, "text": "s/&lt(?!;)/&lt;/gi\n" }, { "answer_id": 48076851, "author": "Kristen", "author_id": 65703, "author_profile": "https://Stackoverflow.com/users/65703", "pm_score": 1, "selected": false, "text": "REPLACE(REPLACE(columName, '&lt;', '&lt'), '&lt', '&lt;') REPLACE(REPLACE(REPLACE(REPLACE(\nREPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(\n columName\n -- Remove existing encoding:\n , '&amp;', '&')\n , '&#34;', '\"')\n , '&#39;', '''')\n -- Reinstate/Encode:\n , '&', '&amp;')\n -- Encode:\n , '\"', '&#34;')\n , '''', '&#39;')\n , ' ', '%20')\n , '<', '%3C')\n , '>', '%3E')\n , '/', '%2F')\n , '\\', '%5C')\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150977", "https://Stackoverflow.com", "https://Stackoverflow.com/users/80/" ]
150,994
<p>For technical reasons, I can't use ClickOnce to auto-update my .NET application and its assemblies. What is the best way to handle auto-updating in .NET?</p>
[ { "answer_id": 151325, "author": "Timothy Carter", "author_id": 4660, "author_profile": "https://Stackoverflow.com/users/4660", "pm_score": 1, "selected": false, "text": " static void Main()\n {\n Application.EnableVisualStyles();\n Application.SetCompatibleTextRenderingDefault(false);\n Update();\n Application.Run(new Form1());\n }\n\n private static void Update()\n {\n string mainFolder;\n string updateFolder;\n string backupFolder;\n\n foreach (string file in\n System.IO.Directory.GetFiles(updateFolder))\n {\n string newFile = file.Replace(\n updateFolder, mainFolder);\n\n if (System.IO.File.Exists(newFile))\n {\n System.IO.File.Replace(file, newFile, backupFolder);\n }\n else\n {\n System.IO.File.Move(file, newFile);\n }\n }\n }\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150994", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14606/" ]
150,998
<p>In my ActionScript3 class, can I have a property with a getter and setter?</p>
[ { "answer_id": 151108, "author": "Max Stewart", "author_id": 18338, "author_profile": "https://Stackoverflow.com/users/18338", "pm_score": 5, "selected": true, "text": "package {\n\n public class PropEG {\n\n private var _prop:String;\n\n public function get prop():String {\n return _prop;\n }\n\n public function set prop(value:String):void {\n _prop = value;\n }\n }\n}\n" }, { "answer_id": 151115, "author": "JustLogic", "author_id": 21664, "author_profile": "https://Stackoverflow.com/users/21664", "pm_score": 2, "selected": false, "text": "\nprivate var _foo:String = \"\";\n\npublic function get foo():String{\n return _foo;\n}\n\npublic function set foo(value:String):void {\n _foo= value;\n}\n" }, { "answer_id": 6558835, "author": "Swati Singh", "author_id": 822792, "author_profile": "https://Stackoverflow.com/users/822792", "pm_score": 0, "selected": false, "text": "import flash.display.Sprite;\nimport flash.text.TextField;\n\npublic class App extends Sprite \n{\n private var tsecField:TextField;\n private var tField:TextField;\n\n public function App() \n {\n myTest();\n }\n\n private function myTest():void \n {\n var a:Testvar = new Testvar();\n\n tField = new TextField();\n tField.autoSize = \"left\";\n tField.background = true;\n tField.border = true;\n a.mynewVar = \"This is the new var.\";\n tField.text = \"Test is: \"+a.myVar;\n addChild(tField);\n }\n}\n public function Testvar() \n{\n}\npublic function set mynewVar(newTest:String):void \n{\n test = newTest;\n}\npublic function get myVar():String \n{\n return test;\n}\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/150998", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14131/" ]
151,000
<p>I've got a class named <code>BackgroundWorker</code> that has a thread constantly running. To turn this thread off, an instance variable named <code>stop</code> to needs to be <code>true</code>. </p> <p>To make sure the thread is freed when the class is done being used, I've added <code>IDisposable</code> and a finalizer that invokes <code>Dispose()</code>. Assuming that <code>stop = true</code> does indeed cause this thread to exit, is this sippet correct? It's fine to invoke <code>Dispose</code> from a finalizer, right?</p> <p>Finalizers should always call <code>Dispose</code> if the <code>object</code> inherits <code>IDisposable</code>, right?</p> <pre><code>/// &lt;summary&gt; /// Force the background thread to exit. /// &lt;/summary&gt; public void Dispose() { lock (this.locker) { this.stop = true; } } ~BackgroundWorker() { this.Dispose(); } </code></pre>
[ { "answer_id": 151207, "author": "nedruod", "author_id": 5504, "author_profile": "https://Stackoverflow.com/users/5504", "pm_score": 4, "selected": false, "text": "public void Dispose()\n{\n Dispose(true);\n GC.SuppressFinalize(this);\n}\n\n/// <summary>\n/// Force the background thread to exit.\n/// </summary>\nprotected virtual void Dispose(bool disposing)\n{\n if (disposing)\n {\n lock (this.locker)\n {\n this.stop = true;\n }\n }\n}\n\n~BackgroundWorker()\n{\n Dispose(false);\n}\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/151000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11574/" ]
151,005
<p>How can I create an Excel spreadsheet with C# without requiring Excel to be installed on the machine that's running the code?</p>
[ { "answer_id": 151014, "author": "GEOCHET", "author_id": 5640, "author_profile": "https://Stackoverflow.com/users/5640", "pm_score": 6, "selected": false, "text": "Microsoft.Office.Interop.Excel" }, { "answer_id": 151048, "author": "Panos", "author_id": 8049, "author_profile": "https://Stackoverflow.com/users/8049", "pm_score": 7, "selected": false, "text": "using (OleDbConnection conn = new OleDbConnection(\"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\\\temp\\\\test.xls;Extended Properties='Excel 8.0;HDR=Yes'\"))\n{\n conn.Open();\n OleDbCommand cmd = new OleDbCommand(\"CREATE TABLE [Sheet1] ([Column1] string, [Column2] string)\", conn);\n cmd.ExecuteNonQuery();\n}\n" }, { "answer_id": 2603625, "author": "Mike Webb", "author_id": 273723, "author_profile": "https://Stackoverflow.com/users/273723", "pm_score": 11, "selected": true, "text": "//Create the data set and table\nDataSet ds = new DataSet(\"New_DataSet\");\nDataTable dt = new DataTable(\"New_DataTable\");\n\n//Set the locale for each\nds.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;\ndt.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;\n\n//Open a DB connection (in this example with OleDB)\nOleDbConnection con = new OleDbConnection(dbConnectionString);\ncon.Open();\n\n//Create a query and fill the data table with the data from the DB\nstring sql = \"SELECT Whatever FROM MyDBTable;\";\nOleDbCommand cmd = new OleDbCommand(sql, con);\nOleDbDataAdapter adptr = new OleDbDataAdapter();\n\nadptr.SelectCommand = cmd;\nadptr.Fill(dt);\ncon.Close();\n\n//Add the table to the data set\nds.Tables.Add(dt);\n\n//Here's the easy part. Create the Excel worksheet from the data set\nExcelLibrary.DataSetHelper.CreateWorkbook(\"MyExcelFile.xls\", ds);\n" }, { "answer_id": 4258376, "author": "Manuel", "author_id": 335911, "author_profile": "https://Stackoverflow.com/users/335911", "pm_score": 6, "selected": false, "text": "var workbook = new XLWorkbook();\nvar worksheet = workbook.Worksheets.Add(\"Sample Sheet\");\nworksheet.Cell(\"A1\").Value = \"Hello World!\";\nworkbook.SaveAs(\"HelloWorld.xlsx\");\n" }, { "answer_id": 4349343, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "using (ExcelHelper helper = new ExcelHelper(TEMPLATE_FILE_NAME, GENERATED_FILE_NAME))\n{\n helper.Direction = ExcelHelper.DirectionType.TOP_TO_DOWN;\n helper.CurrentSheetName = \"Sheet1\";\n helper.CurrentPosition = new CellRef(\"C3\");\n\n //the template xlsx should contains the named range \"header\"; use the command \"insert\"/\"name\".\n helper.InsertRange(\"header\");\n\n //the template xlsx should contains the named range \"sample1\";\n //inside this range you should have cells with these values:\n //<name> , <value> and <comment>, which will be replaced by the values from the getSample()\n CellRangeTemplate sample1 = helper.CreateCellRangeTemplate(\"sample1\", new List<string> {\"name\", \"value\", \"comment\"}); \n helper.InsertRange(sample1, getSample());\n\n //you could use here other named ranges to insert new cells and call InsertRange as many times you want, \n //it will be copied one after another;\n //even you can change direction or the current cell/sheet before you insert\n\n //typically you put all your \"template ranges\" (the names) on the same sheet and then you just delete it\n helper.DeleteSheet(\"Sheet3\");\n} \n private IEnumerable<List<object>> getSample()\n{\n var random = new Random();\n\n for (int loop = 0; loop < 3000; loop++)\n {\n yield return new List<object> {\"test\", DateTime.Now.AddDays(random.NextDouble()*100 - 50), loop};\n }\n}\n" }, { "answer_id": 5817310, "author": "Gaurav", "author_id": 729122, "author_profile": "https://Stackoverflow.com/users/729122", "pm_score": 4, "selected": false, "text": "public class GridViewExportUtil\n{\n public static void Export(string fileName, GridView gv)\n {\n HttpContext.Current.Response.Clear();\n HttpContext.Current.Response.AddHeader(\n \"content-disposition\", string.Format(\"attachment; filename={0}\", fileName));\n HttpContext.Current.Response.ContentType = \"application/ms-excel\";\n\n using (StringWriter sw = new StringWriter())\n {\n using (HtmlTextWriter htw = new HtmlTextWriter(sw))\n {\n // Create a form to contain the grid\n Table table = new Table();\n\n // add the header row to the table\n if (gv.HeaderRow != null)\n {\n GridViewExportUtil.PrepareControlForExport(gv.HeaderRow);\n table.Rows.Add(gv.HeaderRow);\n }\n\n // add each of the data rows to the table\n foreach (GridViewRow row in gv.Rows)\n {\n GridViewExportUtil.PrepareControlForExport(row);\n table.Rows.Add(row);\n }\n\n // add the footer row to the table\n if (gv.FooterRow != null)\n {\n GridViewExportUtil.PrepareControlForExport(gv.FooterRow);\n table.Rows.Add(gv.FooterRow);\n }\n\n // render the table into the htmlwriter\n table.RenderControl(htw);\n\n // render the htmlwriter into the response\n HttpContext.Current.Response.Write(sw.ToString());\n HttpContext.Current.Response.End();\n }\n }\n }\n\n /// <summary>\n /// Replace any of the contained controls with literals\n /// </summary>\n /// <param name=\"control\"></param>\n private static void PrepareControlForExport(Control control)\n {\n for (int i = 0; i < control.Controls.Count; i++)\n {\n Control current = control.Controls[i];\n if (current is LinkButton)\n {\n control.Controls.Remove(current);\n control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));\n }\n else if (current is ImageButton)\n {\n control.Controls.Remove(current);\n control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));\n }\n else if (current is HyperLink)\n {\n control.Controls.Remove(current);\n control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));\n }\n else if (current is DropDownList)\n {\n control.Controls.Remove(current);\n control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));\n }\n else if (current is CheckBox)\n {\n control.Controls.Remove(current);\n control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? \"True\" : \"False\"));\n }\n\n if (current.HasControls())\n {\n GridViewExportUtil.PrepareControlForExport(current);\n }\n }\n }\n}\n" }, { "answer_id": 8385077, "author": "Mike Gledhill", "author_id": 391605, "author_profile": "https://Stackoverflow.com/users/391605", "pm_score": 5, "selected": false, "text": "DataSet DataTable List<> CreateExcelFile.CreateExcelDocument(myDataSet, \"C:\\\\Sample.xlsx\");\n" }, { "answer_id": 27577733, "author": "saurabh27", "author_id": 3847777, "author_profile": "https://Stackoverflow.com/users/3847777", "pm_score": -1, "selected": false, "text": "for (int i = 0; i < TotalFile; i++)\n{\n Contact.Clear();\n if (innerloop == SplitSize)\n {\n for (int j = 0; j < SplitSize; j++)\n {\n string strContact = DSt.Tables[0].Rows[i * SplitSize + j][0].ToString();\n Contact.Add(strContact);\n }\n string strExcel = strFileName + \"_\" + i.ToString() + \".xlsx\";\n File.WriteAllLines(strExcel, Contact.ToArray());\n }\n}\n" }, { "answer_id": 31581330, "author": "Vihana Kewalramani", "author_id": 2082715, "author_profile": "https://Stackoverflow.com/users/2082715", "pm_score": 4, "selected": false, "text": "public static void exportToExcel(DataSet source, string fileName)\n{\n const string endExcelXML = \"</Workbook>\";\n const string startExcelXML = \"<xml version>\\r\\n<Workbook \" +\n \"xmlns=\\\"urn:schemas-microsoft-com:office:spreadsheet\\\"\\r\\n\" +\n \" xmlns:o=\\\"urn:schemas-microsoft-com:office:office\\\"\\r\\n \" +\n \"xmlns:x=\\\"urn:schemas- microsoft-com:office:\" +\n \"excel\\\"\\r\\n xmlns:ss=\\\"urn:schemas-microsoft-com:\" +\n \"office:spreadsheet\\\">\\r\\n <Styles>\\r\\n \" +\n \"<Style ss:ID=\\\"Default\\\" ss:Name=\\\"Normal\\\">\\r\\n \" +\n \"<Alignment ss:Vertical=\\\"Bottom\\\"/>\\r\\n <Borders/>\" +\n \"\\r\\n <Font/>\\r\\n <Interior/>\\r\\n <NumberFormat/>\" +\n \"\\r\\n <Protection/>\\r\\n </Style>\\r\\n \" +\n \"<Style ss:ID=\\\"BoldColumn\\\">\\r\\n <Font \" +\n \"x:Family=\\\"Swiss\\\" ss:Bold=\\\"1\\\"/>\\r\\n </Style>\\r\\n \" +\n \"<Style ss:ID=\\\"StringLiteral\\\">\\r\\n <NumberFormat\" +\n \" ss:Format=\\\"@\\\"/>\\r\\n </Style>\\r\\n <Style \" +\n \"ss:ID=\\\"Decimal\\\">\\r\\n <NumberFormat \" +\n \"ss:Format=\\\"0.0000\\\"/>\\r\\n </Style>\\r\\n \" +\n \"<Style ss:ID=\\\"Integer\\\">\\r\\n <NumberFormat \" +\n \"ss:Format=\\\"0\\\"/>\\r\\n </Style>\\r\\n <Style \" +\n \"ss:ID=\\\"DateLiteral\\\">\\r\\n <NumberFormat \" +\n \"ss:Format=\\\"mm/dd/yyyy;@\\\"/>\\r\\n </Style>\\r\\n \" +\n \"</Styles>\\r\\n \";\n System.IO.StreamWriter excelDoc = null;\n excelDoc = new System.IO.StreamWriter(fileName);\n\n int sheetCount = 1;\n excelDoc.Write(startExcelXML);\n foreach (DataTable table in source.Tables)\n {\n int rowCount = 0;\n excelDoc.Write(\"<Worksheet ss:Name=\\\"\" + table.TableName + \"\\\">\");\n excelDoc.Write(\"<Table>\");\n excelDoc.Write(\"<Row>\");\n for (int x = 0; x < table.Columns.Count; x++)\n {\n excelDoc.Write(\"<Cell ss:StyleID=\\\"BoldColumn\\\"><Data ss:Type=\\\"String\\\">\");\n excelDoc.Write(table.Columns[x].ColumnName);\n excelDoc.Write(\"</Data></Cell>\");\n }\n excelDoc.Write(\"</Row>\");\n foreach (DataRow x in table.Rows)\n {\n rowCount++;\n //if the number of rows is > 64000 create a new page to continue output\n if (rowCount == 64000)\n {\n rowCount = 0;\n sheetCount++;\n excelDoc.Write(\"</Table>\");\n excelDoc.Write(\" </Worksheet>\");\n excelDoc.Write(\"<Worksheet ss:Name=\\\"\" + table.TableName + \"\\\">\");\n excelDoc.Write(\"<Table>\");\n }\n excelDoc.Write(\"<Row>\"); //ID=\" + rowCount + \"\n for (int y = 0; y < table.Columns.Count; y++)\n {\n System.Type rowType;\n rowType = x[y].GetType();\n switch (rowType.ToString())\n {\n case \"System.String\":\n string XMLstring = x[y].ToString();\n XMLstring = XMLstring.Trim();\n XMLstring = XMLstring.Replace(\"&\", \"&\");\n XMLstring = XMLstring.Replace(\">\", \">\");\n XMLstring = XMLstring.Replace(\"<\", \"<\");\n excelDoc.Write(\"<Cell ss:StyleID=\\\"StringLiteral\\\">\" +\n \"<Data ss:Type=\\\"String\\\">\");\n excelDoc.Write(XMLstring);\n excelDoc.Write(\"</Data></Cell>\");\n break;\n case \"System.DateTime\":\n //Excel has a specific Date Format of YYYY-MM-DD followed by \n //the letter 'T' then hh:mm:sss.lll Example 2005-01-31T24:01:21.000\n //The Following Code puts the date stored in XMLDate \n //to the format above\n DateTime XMLDate = (DateTime)x[y];\n string XMLDatetoString = \"\"; //Excel Converted Date\n XMLDatetoString = XMLDate.Year.ToString() +\n \"-\" +\n (XMLDate.Month < 10 ? \"0\" +\n XMLDate.Month.ToString() : XMLDate.Month.ToString()) +\n \"-\" +\n (XMLDate.Day < 10 ? \"0\" +\n XMLDate.Day.ToString() : XMLDate.Day.ToString()) +\n \"T\" +\n (XMLDate.Hour < 10 ? \"0\" +\n XMLDate.Hour.ToString() : XMLDate.Hour.ToString()) +\n \":\" +\n (XMLDate.Minute < 10 ? \"0\" +\n XMLDate.Minute.ToString() : XMLDate.Minute.ToString()) +\n \":\" +\n (XMLDate.Second < 10 ? \"0\" +\n XMLDate.Second.ToString() : XMLDate.Second.ToString()) +\n \".000\";\n excelDoc.Write(\"<Cell ss:StyleID=\\\"DateLiteral\\\">\" +\n \"<Data ss:Type=\\\"DateTime\\\">\");\n excelDoc.Write(XMLDatetoString);\n excelDoc.Write(\"</Data></Cell>\");\n break;\n case \"System.Boolean\":\n excelDoc.Write(\"<Cell ss:StyleID=\\\"StringLiteral\\\">\" +\n \"<Data ss:Type=\\\"String\\\">\");\n excelDoc.Write(x[y].ToString());\n excelDoc.Write(\"</Data></Cell>\");\n break;\n case \"System.Int16\":\n case \"System.Int32\":\n case \"System.Int64\":\n case \"System.Byte\":\n excelDoc.Write(\"<Cell ss:StyleID=\\\"Integer\\\">\" +\n \"<Data ss:Type=\\\"Number\\\">\");\n excelDoc.Write(x[y].ToString());\n excelDoc.Write(\"</Data></Cell>\");\n break;\n case \"System.Decimal\":\n case \"System.Double\":\n excelDoc.Write(\"<Cell ss:StyleID=\\\"Decimal\\\">\" +\n \"<Data ss:Type=\\\"Number\\\">\");\n excelDoc.Write(x[y].ToString());\n excelDoc.Write(\"</Data></Cell>\");\n break;\n case \"System.DBNull\":\n excelDoc.Write(\"<Cell ss:StyleID=\\\"StringLiteral\\\">\" +\n \"<Data ss:Type=\\\"String\\\">\");\n excelDoc.Write(\"\");\n excelDoc.Write(\"</Data></Cell>\");\n break;\n default:\n throw (new Exception(rowType.ToString() + \" not handled.\"));\n }\n }\n excelDoc.Write(\"</Row>\");\n }\n excelDoc.Write(\"</Table>\");\n excelDoc.Write(\" </Worksheet>\");\n sheetCount++;\n }\n\n\n excelDoc.Write(endExcelXML);\n excelDoc.Close();\n }\n" }, { "answer_id": 39923371, "author": "Davis Jebaraj", "author_id": 1628533, "author_profile": "https://Stackoverflow.com/users/1628533", "pm_score": 5, "selected": false, "text": "//Creates a new instance for ExcelEngine.\nExcelEngine excelEngine = new ExcelEngine();\n//Loads or open an existing workbook through Open method of IWorkbooks\nIWorkbook workbook = excelEngine.Excel.Workbooks.Open(fileName);\n//To-Do some manipulation|\n//To-Do some manipulation\n//Set the version of the workbook.\nworkbook.Version = ExcelVersion.Excel2013;\n//Save the workbook in file system as xlsx format\nworkbook.SaveAs(outputFileName);\n" }, { "answer_id": 42497697, "author": "Taterhead", "author_id": 819019, "author_profile": "https://Stackoverflow.com/users/819019", "pm_score": 4, "selected": false, "text": "DesiredLook.xlsx DesiredLook.xlsx GeneratedClass" }, { "answer_id": 43226517, "author": "Gayan Chinthaka Dharmarathna", "author_id": 6863414, "author_profile": "https://Stackoverflow.com/users/6863414", "pm_score": 1, "selected": false, "text": "try\n {\n SaveFileDialog saveFileDialog1 = new SaveFileDialog();\n saveFileDialog1.Filter = \"Excel Documents (*.xls)|*.xls\";\n saveFileDialog1.FileName = \"Employee Details.xls\";\n if (saveFileDialog1.ShowDialog() == DialogResult.OK)\n {\n string fname = saveFileDialog1.FileName;\n StreamWriter wr = new StreamWriter(fname);\n for (int i = 0; i <DataTable.Columns.Count; i++)\n {\n wr.Write(DataTable.Columns[i].ToString().ToUpper() + \"\\t\");\n }\n wr.WriteLine();\n\n //write rows to excel file\n for (int i = 0; i < (DataTable.Rows.Count); i++)\n {\n for (int j = 0; j < DataTable.Columns.Count; j++)\n {\n if (DataTable.Rows[i][j] != null)\n {\n wr.Write(Convert.ToString(getallData.Rows[i][j]) + \"\\t\");\n }\n else\n {\n wr.Write(\"\\t\");\n }\n }\n //go to next line\n wr.WriteLine();\n }\n //close file\n wr.Close();\n }\n }\n catch (Exception)\n {\n MessageBox.Show(\"Error Create Excel Sheet!\");\n }\n" }, { "answer_id": 46451589, "author": "Vladimir Venegas", "author_id": 4216714, "author_profile": "https://Stackoverflow.com/users/4216714", "pm_score": 1, "selected": false, "text": "IList<DummyPerson> dummyPeople = new List<DummyPerson>();\n//Add data to dummyPeople...\nIExportEngine engine = new ExcelExportEngine();\nengine.AddData(dummyPeople); \nMemoryStream memory = engine.Export();\n" }, { "answer_id": 47703396, "author": "AlexDev", "author_id": 733760, "author_profile": "https://Stackoverflow.com/users/733760", "pm_score": 3, "selected": false, "text": "localReport.Render(\"EXCELOPENXML\", null, ((name, ext, encoding, mimeType, willSeek) => stream = new FileStream(name, FileMode.CreateNew)), out warnings);\n \"WORDOPENXML\" \"PDF\"" }, { "answer_id": 53150223, "author": "Vijay Dodamani", "author_id": 3433702, "author_profile": "https://Stackoverflow.com/users/3433702", "pm_score": 1, "selected": false, "text": "SaveAs Microsoft.Office.Interop.Excel wb.SaveAs(filename, 51, System.Reflection.Missing.Value,\nSystem.Reflection.Missing.Value, false, false, 1,1, true, \nSystem.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value)\n" }, { "answer_id": 54033422, "author": "Shubham", "author_id": 8743724, "author_profile": "https://Stackoverflow.com/users/8743724", "pm_score": -1, "selected": false, "text": "var dt = \"your code for getting data into datatable\";\n Response.ClearContent();\n Response.AddHeader(\"content-disposition\", string.Format(\"attachment;filename={0}.xls\", DateTime.Now.ToString(\"yyyy-MM-dd\")));\n Response.ContentType = \"application/vnd.ms-excel\";\n string tab = \"\";\n foreach (DataColumn dataColumn in dt.Columns)\n {\n Response.Write(tab + dataColumn.ColumnName);\n tab = \"\\t\";\n }\n Response.Write(\"\\n\");\n int i;\n foreach (DataRow dataRow in dt.Rows)\n {\n tab = \"\";\n for (i = 0; i < dt.Columns.Count; i++)\n {\n Response.Write(tab + dataRow[i].ToString());\n tab = \"\\t\";\n }\n Response.Write(\"\\n\");\n }\n Response.End();\n" }, { "answer_id": 59203370, "author": "Michael Mainer", "author_id": 2917277, "author_profile": "https://Stackoverflow.com/users/2917277", "pm_score": 2, "selected": false, "text": "{\n Name = \"myExcelFile.xslx\",\n File = new Microsoft.Graph.File()\n};\n\n// Create an empty file in the user's OneDrive.\nvar excelWorkbookDriveItem = await graphClient.Me.Drive.Root.Children.Request().AddAsync(excelWorkbook);\n\n// Add the contents of a template Excel file.\nDriveItem excelDriveItem;\nusing (Stream ms = ResourceHelper.GetResourceAsStream(ResourceHelper.ExcelTestResource))\n{\n //Upload content to the file. ExcelTestResource is an empty template Excel file.\n //https://graph.microsoft.io/en-us/docs/api-reference/v1.0/api/item_uploadcontent\n excelDriveItem = await graphClient.Me.Drive.Items[excelWorkbookDriveItem.Id].Content.Request().PutAsync<DriveItem>(ms);\n}\n\n" }, { "answer_id": 59430197, "author": "Roman.Pavelko", "author_id": 1847554, "author_profile": "https://Stackoverflow.com/users/1847554", "pm_score": 3, "selected": false, "text": "using (var ew = new ExcelWriter(\"C:\\\\temp\\\\test.xlsx\"))\n{\n for (var row = 1; row <= 10; row++)\n {\n for (var col = 1; col <= 5; col++)\n {\n ew.Write($\"row:{row}-col:{col}\", col, row);\n }\n }\n}\n" }, { "answer_id": 62656775, "author": "Miguel Tomás", "author_id": 13794189, "author_profile": "https://Stackoverflow.com/users/13794189", "pm_score": 2, "selected": false, "text": "Imports DocumentFormat.OpenXml\nImports DocumentFormat.OpenXml.Packaging\nImports DocumentFormat.OpenXml.Spreadsheet\n\nPublic Class ExportExcelClass\n Public Sub New()\n\n End Sub\n\n Public Sub ExportDataTable(ByVal table As DataTable, ByVal exportFile As String)\n ' Create a spreadsheet document by supplying the filepath.\n ' By default, AutoSave = true, Editable = true, and Type = xlsx.\n Dim spreadsheetDocument As SpreadsheetDocument = spreadsheetDocument.Create(exportFile, SpreadsheetDocumentType.Workbook)\n\n ' Add a WorkbookPart to the document.\n Dim workbook As WorkbookPart = spreadsheetDocument.AddWorkbookPart\n workbook.Workbook = New Workbook\n\n ' Add a WorksheetPart to the WorkbookPart.\n Dim Worksheet As WorksheetPart = workbook.AddNewPart(Of WorksheetPart)()\n Worksheet.Worksheet = New Worksheet(New SheetData())\n\n ' Add Sheets to the Workbook.\n Dim sheets As Sheets = spreadsheetDocument.WorkbookPart.Workbook.AppendChild(Of Sheets)(New Sheets())\n\n Dim data As SheetData = Worksheet.Worksheet.GetFirstChild(Of SheetData)()\n Dim Header As Row = New Row()\n Header.RowIndex = CType(1, UInt32)\n\n For Each column As DataColumn In table.Columns\n Dim headerCell As Cell = createTextCell(table.Columns.IndexOf(column) + 1, 1, column.ColumnName)\n Header.AppendChild(headerCell)\n Next\n\n data.AppendChild(Header)\n\n Dim contentRow As DataRow\n For i As Integer = 0 To table.Rows.Count - 1\n contentRow = table.Rows(i)\n data.AppendChild(createContentRow(contentRow, i + 2))\n Next\n\n End Sub\n\n Private Function createTextCell(ByVal columnIndex As Integer, ByVal rowIndex As Integer, ByVal cellValue As Object) As Cell\n Dim cell As Cell = New Cell()\n cell.DataType = CellValues.InlineString\n\n cell.CellReference = getColumnName(columnIndex) + rowIndex.ToString\n\n Dim inlineString As InlineString = New InlineString()\n Dim t As Text = New Text()\n t.Text = cellValue.ToString()\n inlineString.AppendChild(t)\n cell.AppendChild(inlineString)\n Return cell\n End Function\n\n Private Function createContentRow(ByVal dataRow As DataRow, ByVal rowIndex As Integer) As Row\n Dim row As Row = New Row With {\n .rowIndex = CType(rowIndex, UInt32)\n }\n\n For i As Integer = 0 To dataRow.Table.Columns.Count - 1\n Dim dataCell As Cell = createTextCell(i + 1, rowIndex, dataRow(i))\n row.AppendChild(dataCell)\n Next\n\n Return row\n End Function\n\n Private Function getColumnName(ByVal columnIndex As Integer) As String\n Dim dividend As Integer = columnIndex\n Dim columnName As String = String.Empty\n Dim modifier As Integer\n\n While dividend > 0\n modifier = (dividend - 1) Mod 26\n columnName = Convert.ToChar(65 + modifier).ToString() & columnName\n dividend = CInt(((dividend - modifier) / 26))\n End While\n\n Return columnName\n End Function\nEnd Class\n" }, { "answer_id": 65206374, "author": "Mauricio Kenny", "author_id": 6227493, "author_profile": "https://Stackoverflow.com/users/6227493", "pm_score": 2, "selected": false, "text": "private static void exportToExcel(DataSet source, string fileName)\n {\n // Documentacion en:\n // https://en.wikipedia.org/wiki/Microsoft_Office_XML_formats\n // https://answers.microsoft.com/en-us/msoffice/forum/all/how-to-save-office-ms-xml-as-xlsx-file/4a77dae5-6855-457d-8359-e7b537beb1db\n // https://riptutorial.com/es/openxml\n\n const string startExcelXML = \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\r\\n\"+\n \"<?mso-application progid=\\\"Excel.Sheet\\\"?>\\r\\n\" +\n \"<Workbook xmlns=\\\"urn:schemas-microsoft-com:office:spreadsheet\\\"\\r\\n\" +\n \"xmlns:o=\\\"urn:schemas-microsoft-com:office:office\\\"\\r\\n \" +\n \"xmlns:x=\\\"urn:schemas-microsoft-com:office:excel\\\"\\r\\n \" +\n \"xmlns:ss=\\\"urn:schemas-microsoft-com:office:spreadsheet\\\"\\r\\n \" +\n \"xmlns:html=\\\"http://www.w3.org/TR/REC-html40\\\">\\r\\n \" +\n \"xmlns:html=\\\"https://www.w3.org/TR/html401/\\\">\\r\\n \" +\n\n \"<DocumentProperties xmlns=\\\"urn:schemas-microsoft-com:office:office\\\">\\r\\n \" +\n \" <Version>16.00</Version>\\r\\n \" +\n \"</DocumentProperties>\\r\\n \" +\n \" <OfficeDocumentSettings xmlns=\\\"urn:schemas-microsoft-com:office:office\\\">\\r\\n \" +\n \" <AllowPNG/>\\r\\n \" +\n \" </OfficeDocumentSettings>\\r\\n \" +\n\n \" <ExcelWorkbook xmlns=\\\"urn:schemas-microsoft-com:office:excel\\\">\\r\\n \" +\n \" <WindowHeight>9750</WindowHeight>\\r\\n \" +\n \" <WindowWidth>24000</WindowWidth>\\r\\n \" +\n \" <WindowTopX>0</WindowTopX>\\r\\n \" +\n \" <WindowTopY>0</WindowTopY>\\r\\n \" +\n \" <RefModeR1C1/>\\r\\n \" +\n \" <ProtectStructure>False</ProtectStructure>\\r\\n \" +\n \" <ProtectWindows>False</ProtectWindows>\\r\\n \" +\n \" </ExcelWorkbook>\\r\\n \" +\n\n \"<Styles>\\r\\n \" +\n \"<Style ss:ID=\\\"Default\\\" ss:Name=\\\"Normal\\\">\\r\\n \" +\n \"<Alignment ss:Vertical=\\\"Bottom\\\"/>\\r\\n <Borders/>\" +\n \"\\r\\n <Font/>\\r\\n <Interior/>\\r\\n <NumberFormat/>\" +\n \"\\r\\n <Protection/>\\r\\n </Style>\\r\\n \" +\n \"<Style ss:ID=\\\"BoldColumn\\\">\\r\\n <Font \" +\n \"x:Family=\\\"Swiss\\\" ss:Bold=\\\"1\\\"/>\\r\\n </Style>\\r\\n \" +\n \"<Style ss:ID=\\\"StringLiteral\\\">\\r\\n <NumberFormat\" +\n \" ss:Format=\\\"@\\\"/>\\r\\n </Style>\\r\\n <Style \" +\n \"ss:ID=\\\"Decimal\\\">\\r\\n <NumberFormat \" +\n \"ss:Format=\\\"0.0000\\\"/>\\r\\n </Style>\\r\\n \" +\n \"<Style ss:ID=\\\"Integer\\\">\\r\\n <NumberFormat/>\" +\n \"ss:Format=\\\"0\\\"/>\\r\\n </Style>\\r\\n <Style \" +\n \"ss:ID=\\\"DateLiteral\\\">\\r\\n <NumberFormat \" +\n \"ss:Format=\\\"dd/mm/yyyy;@\\\"/>\\r\\n </Style>\\r\\n \" +\n \"</Styles>\\r\\n \";\n System.IO.StreamWriter excelDoc = null;\n excelDoc = new System.IO.StreamWriter(fileName,false);\n\n int sheetCount = 1;\n excelDoc.Write(startExcelXML);\n foreach (DataTable table in source.Tables)\n {\n int rowCount = 0;\n excelDoc.Write(\"<Worksheet ss:Name=\\\"\" + table.TableName + \"\\\">\");\n excelDoc.Write(\"<Table>\");\n excelDoc.Write(\"<Row>\");\n for (int x = 0; x < table.Columns.Count; x++)\n {\n excelDoc.Write(\"<Cell ss:StyleID=\\\"BoldColumn\\\"><Data ss:Type=\\\"String\\\">\");\n excelDoc.Write(table.Columns[x].ColumnName);\n excelDoc.Write(\"</Data></Cell>\");\n }\n excelDoc.Write(\"</Row>\");\n foreach (DataRow x in table.Rows)\n {\n rowCount++;\n //if the number of rows is > 64000 create a new page to continue output\n if (rowCount == 1048576)\n {\n rowCount = 0;\n sheetCount++;\n excelDoc.Write(\"</Table>\");\n excelDoc.Write(\" </Worksheet>\");\n excelDoc.Write(\"<Worksheet ss:Name=\\\"\" + table.TableName + \"\\\">\");\n excelDoc.Write(\"<Table>\");\n }\n excelDoc.Write(\"<Row>\"); //ID=\" + rowCount + \"\n for (int y = 0; y < table.Columns.Count; y++)\n {\n System.Type rowType;\n rowType = x[y].GetType();\n switch (rowType.ToString())\n {\n case \"System.String\":\n string XMLstring = x[y].ToString();\n XMLstring = XMLstring.Trim();\n XMLstring = XMLstring.Replace(\"&\", \"&\");\n XMLstring = XMLstring.Replace(\">\", \">\");\n XMLstring = XMLstring.Replace(\"<\", \"<\");\n excelDoc.Write(\"<Cell ss:StyleID=\\\"StringLiteral\\\">\" +\n \"<Data ss:Type=\\\"String\\\">\");\n excelDoc.Write(XMLstring);\n excelDoc.Write(\"</Data></Cell>\");\n break;\n case \"System.DateTime\":\n //Excel has a specific Date Format of YYYY-MM-DD followed by \n //the letter 'T' then hh:mm:sss.lll Example 2005-01-31T24:01:21.000\n //The Following Code puts the date stored in XMLDate \n //to the format above\n DateTime XMLDate = (DateTime)x[y];\n string XMLDatetoString = \"\"; //Excel Converted Date\n XMLDatetoString = XMLDate.Year.ToString() +\n \"-\" +\n (XMLDate.Month < 10 ? \"0\" +\n XMLDate.Month.ToString() : XMLDate.Month.ToString()) +\n \"-\" +\n (XMLDate.Day < 10 ? \"0\" +\n XMLDate.Day.ToString() : XMLDate.Day.ToString()) +\n \"T\" +\n (XMLDate.Hour < 10 ? \"0\" +\n XMLDate.Hour.ToString() : XMLDate.Hour.ToString()) +\n \":\" +\n (XMLDate.Minute < 10 ? \"0\" +\n XMLDate.Minute.ToString() : XMLDate.Minute.ToString()) +\n \":\" +\n (XMLDate.Second < 10 ? \"0\" +\n XMLDate.Second.ToString() : XMLDate.Second.ToString()) +\n \".000\";\n excelDoc.Write(\"<Cell ss:StyleID=\\\"DateLiteral\\\">\" +\n \"<Data ss:Type=\\\"DateTime\\\">\");\n excelDoc.Write(XMLDatetoString);\n excelDoc.Write(\"</Data></Cell>\");\n break;\n case \"System.Boolean\":\n excelDoc.Write(\"<Cell ss:StyleID=\\\"StringLiteral\\\">\" +\n \"<Data ss:Type=\\\"String\\\">\");\n excelDoc.Write(x[y].ToString());\n excelDoc.Write(\"</Data></Cell>\");\n break;\n case \"System.Int16\":\n case \"System.Int32\":\n case \"System.Int64\":\n case \"System.Byte\":\n excelDoc.Write(\"<Cell ss:StyleID=\\\"Integer\\\">\" +\n \"<Data ss:Type=\\\"Number\\\">\");\n excelDoc.Write(x[y].ToString());\n excelDoc.Write(\"</Data></Cell>\");\n break;\n case \"System.Decimal\":\n case \"System.Double\":\n excelDoc.Write(\"<Cell ss:StyleID=\\\"Decimal\\\">\" +\n \"<Data ss:Type=\\\"Number\\\">\");\n excelDoc.Write(x[y].ToString());\n excelDoc.Write(\"</Data></Cell>\");\n break;\n case \"System.DBNull\":\n excelDoc.Write(\"<Cell ss:StyleID=\\\"StringLiteral\\\">\" +\n \"<Data ss:Type=\\\"String\\\">\");\n excelDoc.Write(\"\");\n excelDoc.Write(\"</Data></Cell>\");\n break;\n default:\n throw (new Exception(rowType.ToString() + \" not handled.\"));\n }\n }\n excelDoc.Write(\"</Row>\");\n }\n excelDoc.Write(\"</Table>\");\n excelDoc.Write(\"</Worksheet>\"); \n sheetCount++;\n }\n\n const string endExcelOptions1 = \"\\r\\n<WorksheetOptions xmlns=\\\"urn:schemas-microsoft-com:office:excel\\\">\\r\\n\" +\n \"<Selected/>\\r\\n\" +\n \"<ProtectObjects>False</ProtectObjects>\\r\\n\" +\n \"<ProtectScenarios>False</ProtectScenarios>\\r\\n\" +\n \"</WorksheetOptions>\\r\\n\";\n\n excelDoc.Write(endExcelOptions1);\n excelDoc.Write(\"</Workbook>\");\n excelDoc.Close();\n }\n" }, { "answer_id": 69366171, "author": "toha", "author_id": 1084742, "author_profile": "https://Stackoverflow.com/users/1084742", "pm_score": 0, "selected": false, "text": " //Closed XML\n var workbook = new XLWorkbook(sUrlFile); // load the existing excel file\n var worksheet = workbook.Worksheets.Worksheet(1);\n worksheet.Cell(\"A15\").SetValue(\"\");\n workbook.Save();\n string sUrlFile = \"G:\\\\ReportAmortizedDetail.xls\";\n WorkBook workbook = WorkBook.Load(sUrlFile);\n WorkSheet sheet = workbook.WorkSheets.First();\n //Select cells easily in Excel notation and return the calculated value\n sheet[\"A15\"].First().Value = \"\";\n sheet[\"A15\"].First().FormatString = \"\";\n\n workbook.Save();\n workbook.Close();\n workbook = null;\n string sUrlFile = \"G:\\\\ReportAmortizedDetail.xls\";\n Workbook workbook = new Workbook();\n workbook.LoadFromFile(sUrlFile);\n //Get the 1st sheet\n Worksheet sheet = workbook.Worksheets[0];\n //Specify the cell range\n CellRange range = sheet.Range[\"A15\"];\n //Find all matched text in the range\n CellRange[] cells = range.FindAllString(\"hi\", false, false);\n //Replace text\n foreach (CellRange cell in range)\n {\n cell.Text = \"\";\n }\n //Save\n workbook.Save();\n //ExcelTool Class\n public static int ExcelUpdateSheets(string path, string sWorksheetName, string sCellLocation, string sValue)\n {\n int iResult = -99;\n String sConnectionString = @\"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\" + path + \";Extended Properties='Excel 8.0;HDR=NO'\";\n OleDbConnection objConn = new OleDbConnection(sConnectionString);\n objConn.Open();\n OleDbCommand objCmdSelect = new OleDbCommand(\"UPDATE [\" + sWorksheetName + \"$\" + sCellLocation + \"] SET F1=\" + UtilityClass.ValueSQL(sValue), objConn);\n objCmdSelect.ExecuteNonQuery();\n objConn.Close();\n\n return iResult;\n }\n ExcelTool.ExcelUpdateSheets(sUrlFile, \"ReportAmortizedDetail\", \"A15:A15\", \"\");\n var workbook = new Aspose.Cells.Workbook(sUrlFile);\n // access first (default) worksheet\n var sheet = workbook.Worksheets[0];\n // access CellsCollection of first worksheet\n var cells = sheet.Cells;\n // write HelloWorld to cells A1\n cells[\"A15\"].Value = \"\";\n // save spreadsheet to disc\n workbook.Save(sUrlFile);\n workbook.Dispose();\n workbook = null;\n" }, { "answer_id": 69945347, "author": "user10186832", "author_id": 10186832, "author_profile": "https://Stackoverflow.com/users/10186832", "pm_score": 1, "selected": false, "text": "public class CreateFileOrFolder\n{\n static void Main()\n {\n //\n // https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/file-system/how-to-create-a-file-or-folder\n //\n // https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/file-system/how-to-write-to-a-text-file\n //\n // .NET Framework 4.7.2\n //\n // Specify a name for your top-level folder.\n string folderName = @\"C:\\Users\\david\\Desktop\\Book3\";\n\n // To create a string that specifies the path to a subfolder under your\n // top-level folder, add a name for the subfolder to folderName.\n\n string pathString = System.IO.Path.Combine(folderName, \"_rels\");\n System.IO.Directory.CreateDirectory(pathString);\n pathString = System.IO.Path.Combine(folderName, \"docProps\");\n System.IO.Directory.CreateDirectory(pathString);\n pathString = System.IO.Path.Combine(folderName, \"xl\");\n System.IO.Directory.CreateDirectory(pathString);\n\n string subPathString = System.IO.Path.Combine(pathString, \"_rels\");\n System.IO.Directory.CreateDirectory(subPathString);\n subPathString = System.IO.Path.Combine(pathString, \"theme\");\n System.IO.Directory.CreateDirectory(subPathString);\n subPathString = System.IO.Path.Combine(pathString, \"worksheets\");\n System.IO.Directory.CreateDirectory(subPathString);\n // Keep the console window open in debug mode.\n System.Console.WriteLine(\"Press any key to exit.\");\n System.Console.ReadKey();\n }\n}\n namespace MakeFiles3\n{\n class Program\n {\n static void Main(string[] args)\n {\n //\n // https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/file-system/how-to-write-to-a-text-file\n //\n // .NET Framework 4.7.2\n //\n string fileName = @\"C:\\Users\\david\\Desktop\\Book3\\_rels\\.rels\";\n fnWriteFile(fileName);\n fileName = @\"C:\\Users\\david\\Desktop\\Book3\\docProps\\app.xml\";\n fnWriteFile(fileName);\n fileName = @\"C:\\Users\\david\\Desktop\\Book3\\docProps\\core.xml\";\n fnWriteFile(fileName);\n fileName = @\"C:\\Users\\david\\Desktop\\Book3\\xl\\_rels\\workbook.xml.rels\";\n fnWriteFile(fileName);\n fileName = @\"C:\\Users\\david\\Desktop\\Book3\\xl\\theme\\theme1.xml\";\n fnWriteFile(fileName);\n fileName = @\"C:\\Users\\david\\Desktop\\Book3\\xl\\worksheets\\sheet1.xml\";\n fnWriteFile(fileName);\n fileName = @\"C:\\Users\\david\\Desktop\\Book3\\xl\\styles.xml\";\n fnWriteFile(fileName);\n fileName = @\"C:\\Users\\david\\Desktop\\Book3\\xl\\workbook.xml\";\n fnWriteFile(fileName);\n fileName = @\"C:\\Users\\david\\Desktop\\Book3\\[Content_Types].xml\";\n fnWriteFile(fileName);\n // Keep the console window open in debug mode.\n System.Console.WriteLine(\"Press any key to exit.\");\n System.Console.ReadKey();\n\n bool fnWriteFile(string strFilePath)\n {\n if (!System.IO.File.Exists(strFilePath))\n {\n using (System.IO.FileStream fs = System.IO.File.Create(strFilePath))\n {\n return true;\n }\n }\n else\n {\n System.Console.WriteLine(\"File \\\"{0}\\\" already exists.\", strFilePath);\n return false;\n }\n }\n }\n }\n}\n //\n// https://learn.microsoft.com/en-us/dotnet/standard/io/how-to-write-text-to-a-file\n// .NET Framework 4.7.2\n//\nusing System.IO;\n\nnamespace MakeFiles4\n{\n class Program\n {\n static void Main(string[] args)\n {\n string xContents = @\"a\";\n string xFilename = @\"a\";\n xFilename = @\"C:\\Users\\david\\Desktop\\Book3\\[Content_Types].xml\";\n xContents = @\"<?xml version=\"\"1.0\"\" encoding=\"\"UTF-8\"\" standalone=\"\"yes\"\"?><Types xmlns=\"\"http://schemas.openxmlformats.org/package/2006/content-types\"\"><Default Extension=\"\"rels\"\" ContentType=\"\"application/vnd.openxmlformats-package.relationships+xml\"\"/><Default Extension=\"\"xml\"\" ContentType=\"\"application/xml\"\"/><Override PartName=\"\"/xl/workbook.xml\"\" ContentType=\"\"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml\"\"/><Override PartName=\"\"/xl/worksheets/sheet1.xml\"\" ContentType=\"\"application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml\"\"/><Override PartName=\"\"/xl/theme/theme1.xml\"\" ContentType=\"\"application/vnd.openxmlformats-officedocument.theme+xml\"\"/><Override PartName=\"\"/xl/styles.xml\"\" ContentType=\"\"application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml\"\"/><Override PartName=\"\"/docProps/core.xml\"\" ContentType=\"\"application/vnd.openxmlformats-package.core-properties+xml\"\"/><Override PartName=\"\"/docProps/app.xml\"\" ContentType=\"\"application/vnd.openxmlformats-officedocument.extended-properties+xml\"\"/></Types>\";\n StartExstream(xContents, xFilename);\n\n xFilename = @\"C:\\Users\\david\\Desktop\\Book3\\_rels\\.rels\";\n xContents = @\"<?xml version=\"\"1.0\"\" encoding=\"\"UTF-8\"\" standalone=\"\"yes\"\"?><Relationships xmlns=\"\"http://schemas.openxmlformats.org/package/2006/relationships\"\"><Relationship Id=\"\"rId3\"\" Type=\"\"http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties\"\" Target=\"\"docProps/app.xml\"\"/><Relationship Id=\"\"rId2\"\" Type=\"\"http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties\"\" Target=\"\"docProps/core.xml\"\"/><Relationship Id=\"\"rId1\"\" Type=\"\"http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument\"\" Target=\"\"xl/workbook.xml\"\"/></Relationships>\";\n StartExstream(xContents, xFilename);\n\n xFilename = @\"C:\\Users\\david\\Desktop\\Book3\\docProps\\app.xml\";\n xContents = @\"<?xml version=\"\"1.0\"\" encoding=\"\"UTF-8\"\" standalone=\"\"yes\"\"?><Properties xmlns=\"\"http://schemas.openxmlformats.org/officeDocument/2006/extended-properties\"\" xmlns:vt=\"\"http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes\"\"><Application>Microsoft Excel</Application><DocSecurity>0</DocSecurity><ScaleCrop>false</ScaleCrop><HeadingPairs><vt:vector size=\"\"2\"\" baseType=\"\"variant\"\"><vt:variant><vt:lpstr>Worksheets</vt:lpstr></vt:variant><vt:variant><vt:i4>1</vt:i4></vt:variant></vt:vector></HeadingPairs><TitlesOfParts><vt:vector size=\"\"1\"\" baseType=\"\"lpstr\"\"><vt:lpstr>Sheet1</vt:lpstr></vt:vector></TitlesOfParts><Company></Company><LinksUpToDate>false</LinksUpToDate><SharedDoc>false</SharedDoc><HyperlinksChanged>false</HyperlinksChanged><AppVersion>16.0300</AppVersion></Properties>\";\n StartExstream(xContents, xFilename);\n\n xFilename = @\"C:\\Users\\david\\Desktop\\Book3\\docProps\\core.xml\";\n xContents = @\"<?xml version=\"\"1.0\"\" encoding=\"\"UTF-8\"\" standalone=\"\"yes\"\"?><cp:coreProperties xmlns:cp=\"\"http://schemas.openxmlformats.org/package/2006/metadata/core-properties\"\" xmlns:dc=\"\"http://purl.org/dc/elements/1.1/\"\" xmlns:dcterms=\"\"http://purl.org/dc/terms/\"\" xmlns:dcmitype=\"\"http://purl.org/dc/dcmitype/\"\" xmlns:xsi=\"\"http://www.w3.org/2001/XMLSchema-instance\"\"><dc:creator>David Tallett</dc:creator><cp:lastModifiedBy>David Tallett</cp:lastModifiedBy><dcterms:created xsi:type=\"\"dcterms:W3CDTF\"\">2021-10-26T15:47:15Z</dcterms:created><dcterms:modified xsi:type=\"\"dcterms:W3CDTF\"\">2021-10-26T15:47:35Z</dcterms:modified></cp:coreProperties>\";\n StartExstream(xContents, xFilename);\n\n xFilename = @\"C:\\Users\\david\\Desktop\\Book3\\xl\\styles.xml\";\n xContents = @\"<?xml version=\"\"1.0\"\" encoding=\"\"UTF-8\"\" standalone=\"\"yes\"\"?><styleSheet xmlns=\"\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\"\" xmlns:mc=\"\"http://schemas.openxmlformats.org/markup-compatibility/2006\"\" mc:Ignorable=\"\"x14ac x16r2 xr\"\" xmlns:x14ac=\"\"http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac\"\" xmlns:x16r2=\"\"http://schemas.microsoft.com/office/spreadsheetml/2015/02/main\"\" xmlns:xr=\"\"http://schemas.microsoft.com/office/spreadsheetml/2014/revision\"\"><fonts count=\"\"1\"\" x14ac:knownFonts=\"\"1\"\"><font><sz val=\"\"11\"\"/><color theme=\"\"1\"\"/><name val=\"\"Calibri\"\"/><family val=\"\"2\"\"/><scheme val=\"\"minor\"\"/></font></fonts><fills count=\"\"2\"\"><fill><patternFill patternType=\"\"none\"\"/></fill><fill><patternFill patternType=\"\"gray125\"\"/></fill></fills><borders count=\"\"1\"\"><border><left/><right/><top/><bottom/><diagonal/></border></borders><cellStyleXfs count=\"\"1\"\"><xf numFmtId=\"\"0\"\" fontId=\"\"0\"\" fillId=\"\"0\"\" borderId=\"\"0\"\"/></cellStyleXfs><cellXfs count=\"\"1\"\"><xf numFmtId=\"\"0\"\" fontId=\"\"0\"\" fillId=\"\"0\"\" borderId=\"\"0\"\" xfId=\"\"0\"\"/></cellXfs><cellStyles count=\"\"1\"\"><cellStyle name=\"\"Normal\"\" xfId=\"\"0\"\" builtinId=\"\"0\"\"/></cellStyles><dxfs count=\"\"0\"\"/><tableStyles count=\"\"0\"\" defaultTableStyle=\"\"TableStyleMedium2\"\" defaultPivotStyle=\"\"PivotStyleLight16\"\"/><extLst><ext uri=\"\"{EB79DEF2-80B8-43e5-95BD-54CBDDF9020C}\"\" xmlns:x14=\"\"http://schemas.microsoft.com/office/spreadsheetml/2009/9/main\"\"><x14:slicerStyles defaultSlicerStyle=\"\"SlicerStyleLight1\"\"/></ext><ext uri=\"\"{9260A510-F301-46a8-8635-F512D64BE5F5}\"\" xmlns:x15=\"\"http://schemas.microsoft.com/office/spreadsheetml/2010/11/main\"\"><x15:timelineStyles defaultTimelineStyle=\"\"TimeSlicerStyleLight1\"\"/></ext></extLst></styleSheet>\";\n StartExstream(xContents, xFilename);\n\n xFilename = @\"C:\\Users\\david\\Desktop\\Book3\\xl\\workbook.xml\";\n xContents = @\"<?xml version=\"\"1.0\"\" encoding=\"\"UTF-8\"\" standalone=\"\"yes\"\"?><workbook xmlns=\"\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\"\" xmlns:r=\"\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"\" xmlns:mc=\"\"http://schemas.openxmlformats.org/markup-compatibility/2006\"\" mc:Ignorable=\"\"x15 xr xr6 xr10 xr2\"\" xmlns:x15=\"\"http://schemas.microsoft.com/office/spreadsheetml/2010/11/main\"\" xmlns:xr=\"\"http://schemas.microsoft.com/office/spreadsheetml/2014/revision\"\" xmlns:xr6=\"\"http://schemas.microsoft.com/office/spreadsheetml/2016/revision6\"\" xmlns:xr10=\"\"http://schemas.microsoft.com/office/spreadsheetml/2016/revision10\"\" xmlns:xr2=\"\"http://schemas.microsoft.com/office/spreadsheetml/2015/revision2\"\"><fileVersion appName=\"\"xl\"\" lastEdited=\"\"7\"\" lowestEdited=\"\"7\"\" rupBuild=\"\"24430\"\"/><workbookPr defaultThemeVersion=\"\"166925\"\"/><mc:AlternateContent xmlns:mc=\"\"http://schemas.openxmlformats.org/markup-compatibility/2006\"\"><mc:Choice Requires=\"\"x15\"\"><x15ac:absPath url=\"\"C:\\Users\\david\\Desktop\\\"\" xmlns:x15ac=\"\"http://schemas.microsoft.com/office/spreadsheetml/2010/11/ac\"\"/></mc:Choice></mc:AlternateContent><xr:revisionPtr revIDLastSave=\"\"0\"\" documentId=\"\"8_{C633700D-2D40-49EE-8C5E-2561E28A6758}\"\" xr6:coauthVersionLast=\"\"47\"\" xr6:coauthVersionMax=\"\"47\"\" xr10:uidLastSave=\"\"{00000000-0000-0000-0000-000000000000}\"\"/><bookViews><workbookView xWindow=\"\"-120\"\" yWindow=\"\"-120\"\" windowWidth=\"\"29040\"\" windowHeight=\"\"15840\"\" xr2:uid=\"\"{934C5B62-1DC1-4322-BAE8-00D615BD2FB3}\"\"/></bookViews><sheets><sheet name=\"\"Sheet1\"\" sheetId=\"\"1\"\" r:id=\"\"rId1\"\"/></sheets><calcPr calcId=\"\"191029\"\"/><extLst><ext uri=\"\"{140A7094-0E35-4892-8432-C4D2E57EDEB5}\"\" xmlns:x15=\"\"http://schemas.microsoft.com/office/spreadsheetml/2010/11/main\"\"><x15:workbookPr chartTrackingRefBase=\"\"1\"\"/></ext><ext uri=\"\"{B58B0392-4F1F-4190-BB64-5DF3571DCE5F}\"\" xmlns:xcalcf=\"\"http://schemas.microsoft.com/office/spreadsheetml/2018/calcfeatures\"\"><xcalcf:calcFeatures><xcalcf:feature name=\"\"microsoft.com:RD\"\"/><xcalcf:feature name=\"\"microsoft.com:Single\"\"/><xcalcf:feature name=\"\"microsoft.com:FV\"\"/><xcalcf:feature name=\"\"microsoft.com:CNMTM\"\"/><xcalcf:feature name=\"\"microsoft.com:LET_WF\"\"/></xcalcf:calcFeatures></ext></extLst></workbook>\";\n StartExstream(xContents, xFilename);\n\n xFilename = @\"C:\\Users\\david\\Desktop\\Book3\\xl\\_rels\\workbook.xml.rels\";\n xContents = @\"<?xml version=\"\"1.0\"\" encoding=\"\"UTF-8\"\" standalone=\"\"yes\"\"?><Relationships xmlns=\"\"http://schemas.openxmlformats.org/package/2006/relationships\"\"><Relationship Id=\"\"rId3\"\" Type=\"\"http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles\"\" Target=\"\"styles.xml\"\"/><Relationship Id=\"\"rId2\"\" Type=\"\"http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme\"\" Target=\"\"theme/theme1.xml\"\"/><Relationship Id=\"\"rId1\"\" Type=\"\"http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet\"\" Target=\"\"worksheets/sheet1.xml\"\"/></Relationships>\";\n StartExstream(xContents, xFilename);\n\n xFilename = @\"C:\\Users\\david\\Desktop\\Book3\\xl\\theme\\theme1.xml\";\n xContents = @\"<?xml version=\"\"1.0\"\" encoding=\"\"UTF-8\"\" standalone=\"\"yes\"\"?><a:theme xmlns:a=\"\"http://schemas.openxmlformats.org/drawingml/2006/main\"\" name=\"\"Office Theme\"\"><a:themeElements><a:clrScheme name=\"\"Office\"\"><a:dk1><a:sysClr val=\"\"windowText\"\" lastClr=\"\"000000\"\"/></a:dk1><a:lt1><a:sysClr val=\"\"window\"\" lastClr=\"\"FFFFFF\"\"/></a:lt1><a:dk2><a:srgbClr val=\"\"44546A\"\"/></a:dk2><a:lt2><a:srgbClr val=\"\"E7E6E6\"\"/></a:lt2><a:accent1><a:srgbClr val=\"\"4472C4\"\"/></a:accent1><a:accent2><a:srgbClr val=\"\"ED7D31\"\"/></a:accent2><a:accent3><a:srgbClr val=\"\"A5A5A5\"\"/></a:accent3><a:accent4><a:srgbClr val=\"\"FFC000\"\"/></a:accent4><a:accent5><a:srgbClr val=\"\"5B9BD5\"\"/></a:accent5><a:accent6><a:srgbClr val=\"\"70AD47\"\"/></a:accent6><a:hlink><a:srgbClr val=\"\"0563C1\"\"/></a:hlink><a:folHlink><a:srgbClr val=\"\"954F72\"\"/></a:folHlink></a:clrScheme><a:fontScheme name=\"\"Office\"\"><a:majorFont><a:latin typeface=\"\"Calibri Light\"\" panose=\"\"020F0302020204030204\"\"/><a:ea typeface=\"\"\"\"/><a:cs typeface=\"\"\"\"/><a:font script=\"\"Jpan\"\" typeface=\"\"游ゴシック Light\"\"/><a:font script=\"\"Hang\"\" typeface=\"\"맑은 고딕\"\"/><a:font script=\"\"Hans\"\" typeface=\"\"等线 Light\"\"/><a:font script=\"\"Hant\"\" typeface=\"\"新細明體\"\"/><a:font script=\"\"Arab\"\" typeface=\"\"Times New Roman\"\"/><a:font script=\"\"Hebr\"\" typeface=\"\"Times New Roman\"\"/><a:font script=\"\"Thai\"\" typeface=\"\"Tahoma\"\"/><a:font script=\"\"Ethi\"\" typeface=\"\"Nyala\"\"/><a:font script=\"\"Beng\"\" typeface=\"\"Vrinda\"\"/><a:font script=\"\"Gujr\"\" typeface=\"\"Shruti\"\"/><a:font script=\"\"Khmr\"\" typeface=\"\"MoolBoran\"\"/><a:font script=\"\"Knda\"\" typeface=\"\"Tunga\"\"/><a:font script=\"\"Guru\"\" typeface=\"\"Raavi\"\"/><a:font script=\"\"Cans\"\" typeface=\"\"Euphemia\"\"/><a:font script=\"\"Cher\"\" typeface=\"\"Plantagenet Cherokee\"\"/><a:font script=\"\"Yiii\"\" typeface=\"\"Microsoft Yi Baiti\"\"/><a:font script=\"\"Tibt\"\" typeface=\"\"Microsoft Himalaya\"\"/><a:font script=\"\"Thaa\"\" typeface=\"\"MV Boli\"\"/><a:font script=\"\"Deva\"\" typeface=\"\"Mangal\"\"/><a:font script=\"\"Telu\"\" typeface=\"\"Gautami\"\"/><a:font script=\"\"Taml\"\" typeface=\"\"Latha\"\"/><a:font script=\"\"Syrc\"\" typeface=\"\"Estrangelo Edessa\"\"/><a:font script=\"\"Orya\"\" typeface=\"\"Kalinga\"\"/><a:font script=\"\"Mlym\"\" typeface=\"\"Kartika\"\"/><a:font script=\"\"Laoo\"\" typeface=\"\"DokChampa\"\"/><a:font script=\"\"Sinh\"\" typeface=\"\"Iskoola Pota\"\"/><a:font script=\"\"Mong\"\" typeface=\"\"Mongolian Baiti\"\"/><a:font script=\"\"Viet\"\" typeface=\"\"Times New Roman\"\"/><a:font script=\"\"Uigh\"\" typeface=\"\"Microsoft Uighur\"\"/><a:font script=\"\"Geor\"\" typeface=\"\"Sylfaen\"\"/><a:font script=\"\"Armn\"\" typeface=\"\"Arial\"\"/><a:font script=\"\"Bugi\"\" typeface=\"\"Leelawadee UI\"\"/><a:font script=\"\"Bopo\"\" typeface=\"\"Microsoft JhengHei\"\"/><a:font script=\"\"Java\"\" typeface=\"\"Javanese Text\"\"/><a:font script=\"\"Lisu\"\" typeface=\"\"Segoe UI\"\"/><a:font script=\"\"Mymr\"\" typeface=\"\"Myanmar Text\"\"/><a:font script=\"\"Nkoo\"\" typeface=\"\"Ebrima\"\"/><a:font script=\"\"Olck\"\" typeface=\"\"Nirmala UI\"\"/><a:font script=\"\"Osma\"\" typeface=\"\"Ebrima\"\"/><a:font script=\"\"Phag\"\" typeface=\"\"Phagspa\"\"/><a:font script=\"\"Syrn\"\" typeface=\"\"Estrangelo Edessa\"\"/><a:font script=\"\"Syrj\"\" typeface=\"\"Estrangelo Edessa\"\"/><a:font script=\"\"Syre\"\" typeface=\"\"Estrangelo Edessa\"\"/><a:font script=\"\"Sora\"\" typeface=\"\"Nirmala UI\"\"/><a:font script=\"\"Tale\"\" typeface=\"\"Microsoft Tai Le\"\"/><a:font script=\"\"Talu\"\" typeface=\"\"Microsoft New Tai Lue\"\"/><a:font script=\"\"Tfng\"\" typeface=\"\"Ebrima\"\"/></a:majorFont><a:minorFont><a:latin typeface=\"\"Calibri\"\" panose=\"\"020F0502020204030204\"\"/><a:ea typeface=\"\"\"\"/><a:cs typeface=\"\"\"\"/><a:font script=\"\"Jpan\"\" typeface=\"\"游ゴシック\"\"/><a:font script=\"\"Hang\"\" typeface=\"\"맑은 고딕\"\"/><a:font script=\"\"Hans\"\" typeface=\"\"等线\"\"/><a:font script=\"\"Hant\"\" typeface=\"\"新細明體\"\"/><a:font script=\"\"Arab\"\" typeface=\"\"Arial\"\"/><a:font script=\"\"Hebr\"\" typeface=\"\"Arial\"\"/><a:font script=\"\"Thai\"\" typeface=\"\"Tahoma\"\"/><a:font script=\"\"Ethi\"\" typeface=\"\"Nyala\"\"/><a:font script=\"\"Beng\"\" typeface=\"\"Vrinda\"\"/><a:font script=\"\"Gujr\"\" typeface=\"\"Shruti\"\"/><a:font script=\"\"Khmr\"\" typeface=\"\"DaunPenh\"\"/><a:font script=\"\"Knda\"\" typeface=\"\"Tunga\"\"/><a:font script=\"\"Guru\"\" typeface=\"\"Raavi\"\"/><a:font script=\"\"Cans\"\" typeface=\"\"Euphemia\"\"/><a:font script=\"\"Cher\"\" typeface=\"\"Plantagenet Cherokee\"\"/><a:font script=\"\"Yiii\"\" typeface=\"\"Microsoft Yi Baiti\"\"/><a:font script=\"\"Tibt\"\" typeface=\"\"Microsoft Himalaya\"\"/><a:font script=\"\"Thaa\"\" typeface=\"\"MV Boli\"\"/><a:font script=\"\"Deva\"\" typeface=\"\"Mangal\"\"/><a:font script=\"\"Telu\"\" typeface=\"\"Gautami\"\"/><a:font script=\"\"Taml\"\" typeface=\"\"Latha\"\"/><a:font script=\"\"Syrc\"\" typeface=\"\"Estrangelo Edessa\"\"/><a:font script=\"\"Orya\"\" typeface=\"\"Kalinga\"\"/><a:font script=\"\"Mlym\"\" typeface=\"\"Kartika\"\"/><a:font script=\"\"Laoo\"\" typeface=\"\"DokChampa\"\"/><a:font script=\"\"Sinh\"\" typeface=\"\"Iskoola Pota\"\"/><a:font script=\"\"Mong\"\" typeface=\"\"Mongolian Baiti\"\"/><a:font script=\"\"Viet\"\" typeface=\"\"Arial\"\"/><a:font script=\"\"Uigh\"\" typeface=\"\"Microsoft Uighur\"\"/><a:font script=\"\"Geor\"\" typeface=\"\"Sylfaen\"\"/><a:font script=\"\"Armn\"\" typeface=\"\"Arial\"\"/><a:font script=\"\"Bugi\"\" typeface=\"\"Leelawadee UI\"\"/><a:font script=\"\"Bopo\"\" typeface=\"\"Microsoft JhengHei\"\"/><a:font script=\"\"Java\"\" typeface=\"\"Javanese Text\"\"/><a:font script=\"\"Lisu\"\" typeface=\"\"Segoe UI\"\"/><a:font script=\"\"Mymr\"\" typeface=\"\"Myanmar Text\"\"/><a:font script=\"\"Nkoo\"\" typeface=\"\"Ebrima\"\"/><a:font script=\"\"Olck\"\" typeface=\"\"Nirmala UI\"\"/><a:font script=\"\"Osma\"\" typeface=\"\"Ebrima\"\"/><a:font script=\"\"Phag\"\" typeface=\"\"Phagspa\"\"/><a:font script=\"\"Syrn\"\" typeface=\"\"Estrangelo Edessa\"\"/><a:font script=\"\"Syrj\"\" typeface=\"\"Estrangelo Edessa\"\"/><a:font script=\"\"Syre\"\" typeface=\"\"Estrangelo Edessa\"\"/><a:font script=\"\"Sora\"\" typeface=\"\"Nirmala UI\"\"/><a:font script=\"\"Tale\"\" typeface=\"\"Microsoft Tai Le\"\"/><a:font script=\"\"Talu\"\" typeface=\"\"Microsoft New Tai Lue\"\"/><a:font script=\"\"Tfng\"\" typeface=\"\"Ebrima\"\"/></a:minorFont></a:fontScheme><a:fmtScheme name=\"\"Office\"\"><a:fillStyleLst><a:solidFill><a:schemeClr val=\"\"phClr\"\"/></a:solidFill><a:gradFill rotWithShape=\"\"1\"\"><a:gsLst><a:gs pos=\"\"0\"\"><a:schemeClr val=\"\"phClr\"\"><a:lumMod val=\"\"110000\"\"/><a:satMod val=\"\"105000\"\"/><a:tint val=\"\"67000\"\"/></a:schemeClr></a:gs><a:gs pos=\"\"50000\"\"><a:schemeClr val=\"\"phClr\"\"><a:lumMod val=\"\"105000\"\"/><a:satMod val=\"\"103000\"\"/><a:tint val=\"\"73000\"\"/></a:schemeClr></a:gs><a:gs pos=\"\"100000\"\"><a:schemeClr val=\"\"phClr\"\"><a:lumMod val=\"\"105000\"\"/><a:satMod val=\"\"109000\"\"/><a:tint val=\"\"81000\"\"/></a:schemeClr></a:gs></a:gsLst><a:lin ang=\"\"5400000\"\" scaled=\"\"0\"\"/></a:gradFill><a:gradFill rotWithShape=\"\"1\"\"><a:gsLst><a:gs pos=\"\"0\"\"><a:schemeClr val=\"\"phClr\"\"><a:satMod val=\"\"103000\"\"/><a:lumMod val=\"\"102000\"\"/><a:tint val=\"\"94000\"\"/></a:schemeClr></a:gs><a:gs pos=\"\"50000\"\"><a:schemeClr val=\"\"phClr\"\"><a:satMod val=\"\"110000\"\"/><a:lumMod val=\"\"100000\"\"/><a:shade val=\"\"100000\"\"/></a:schemeClr></a:gs><a:gs pos=\"\"100000\"\"><a:schemeClr val=\"\"phClr\"\"><a:lumMod val=\"\"99000\"\"/><a:satMod val=\"\"120000\"\"/><a:shade val=\"\"78000\"\"/></a:schemeClr></a:gs></a:gsLst><a:lin ang=\"\"5400000\"\" scaled=\"\"0\"\"/></a:gradFill></a:fillStyleLst><a:lnStyleLst><a:ln w=\"\"6350\"\" cap=\"\"flat\"\" cmpd=\"\"sng\"\" algn=\"\"ctr\"\"><a:solidFill><a:schemeClr val=\"\"phClr\"\"/></a:solidFill><a:prstDash val=\"\"solid\"\"/><a:miter lim=\"\"800000\"\"/></a:ln><a:ln w=\"\"12700\"\" cap=\"\"flat\"\" cmpd=\"\"sng\"\" algn=\"\"ctr\"\"><a:solidFill><a:schemeClr val=\"\"phClr\"\"/></a:solidFill><a:prstDash val=\"\"solid\"\"/><a:miter lim=\"\"800000\"\"/></a:ln><a:ln w=\"\"19050\"\" cap=\"\"flat\"\" cmpd=\"\"sng\"\" algn=\"\"ctr\"\"><a:solidFill><a:schemeClr val=\"\"phClr\"\"/></a:solidFill><a:prstDash val=\"\"solid\"\"/><a:miter lim=\"\"800000\"\"/></a:ln></a:lnStyleLst><a:effectStyleLst><a:effectStyle><a:effectLst/></a:effectStyle><a:effectStyle><a:effectLst/></a:effectStyle><a:effectStyle><a:effectLst><a:outerShdw blurRad=\"\"57150\"\" dist=\"\"19050\"\" dir=\"\"5400000\"\" algn=\"\"ctr\"\" rotWithShape=\"\"0\"\"><a:srgbClr val=\"\"000000\"\"><a:alpha val=\"\"63000\"\"/></a:srgbClr></a:outerShdw></a:effectLst></a:effectStyle></a:effectStyleLst><a:bgFillStyleLst><a:solidFill><a:schemeClr val=\"\"phClr\"\"/></a:solidFill><a:solidFill><a:schemeClr val=\"\"phClr\"\"><a:tint val=\"\"95000\"\"/><a:satMod val=\"\"170000\"\"/></a:schemeClr></a:solidFill><a:gradFill rotWithShape=\"\"1\"\"><a:gsLst><a:gs pos=\"\"0\"\"><a:schemeClr val=\"\"phClr\"\"><a:tint val=\"\"93000\"\"/><a:satMod val=\"\"150000\"\"/><a:shade val=\"\"98000\"\"/><a:lumMod val=\"\"102000\"\"/></a:schemeClr></a:gs><a:gs pos=\"\"50000\"\"><a:schemeClr val=\"\"phClr\"\"><a:tint val=\"\"98000\"\"/><a:satMod val=\"\"130000\"\"/><a:shade val=\"\"90000\"\"/><a:lumMod val=\"\"103000\"\"/></a:schemeClr></a:gs><a:gs pos=\"\"100000\"\"><a:schemeClr val=\"\"phClr\"\"><a:shade val=\"\"63000\"\"/><a:satMod val=\"\"120000\"\"/></a:schemeClr></a:gs></a:gsLst><a:lin ang=\"\"5400000\"\" scaled=\"\"0\"\"/></a:gradFill></a:bgFillStyleLst></a:fmtScheme></a:themeElements><a:objectDefaults/><a:extraClrSchemeLst/><a:extLst><a:ext uri=\"\"{05A4C25C-085E-4340-85A3-A5531E510DB2}\"\"><thm15:themeFamily xmlns:thm15=\"\"http://schemas.microsoft.com/office/thememl/2012/main\"\" name=\"\"Office Theme\"\" id=\"\"{62F939B6-93AF-4DB8-9C6B-D6C7DFDC589F}\"\" vid=\"\"{4A3C46E8-61CC-4603-A589-7422A47A8E4A}\"\"/></a:ext></a:extLst></a:theme>\";\n StartExstream(xContents, xFilename);\n\n xFilename = @\"C:\\Users\\david\\Desktop\\Book3\\xl\\worksheets\\sheet1.xml\";\n xContents = @\"<?xml version=\"\"1.0\"\" encoding=\"\"UTF-8\"\" standalone=\"\"yes\"\"?><worksheet xmlns=\"\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\"\" xmlns:r=\"\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"\" xmlns:mc=\"\"http://schemas.openxmlformats.org/markup-compatibility/2006\"\" mc:Ignorable=\"\"x14ac xr xr2 xr3\"\" xmlns:x14ac=\"\"http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac\"\" xmlns:xr=\"\"http://schemas.microsoft.com/office/spreadsheetml/2014/revision\"\" xmlns:xr2=\"\"http://schemas.microsoft.com/office/spreadsheetml/2015/revision2\"\" xmlns:xr3=\"\"http://schemas.microsoft.com/office/spreadsheetml/2016/revision3\"\" xr:uid=\"\"{54E3D330-4E78-4755-89E0-1AADACAC4953}\"\"><dimension ref=\"\"A1:A3\"\"/><sheetViews><sheetView tabSelected=\"\"1\"\" workbookViewId=\"\"0\"\"><selection activeCell=\"\"A4\"\" sqref=\"\"A4\"\"/></sheetView></sheetViews><sheetFormatPr defaultRowHeight=\"\"15\"\" x14ac:dyDescent=\"\"0.25\"\"/><sheetData><row r=\"\"1\"\" spans=\"\"1:1\"\" x14ac:dyDescent=\"\"0.25\"\"><c r=\"\"A1\"\"><v>1</v></c></row><row r=\"\"2\"\" spans=\"\"1:1\"\" x14ac:dyDescent=\"\"0.25\"\"><c r=\"\"A2\"\"><v>2</v></c></row><row r=\"\"3\"\" spans=\"\"1:1\"\" x14ac:dyDescent=\"\"0.25\"\"><c r=\"\"A3\"\"><v>3</v></c></row></sheetData><pageMargins left=\"\"0.7\"\" right=\"\"0.7\"\" top=\"\"0.75\"\" bottom=\"\"0.75\"\" header=\"\"0.3\"\" footer=\"\"0.3\"\"/></worksheet>\";\n StartExstream(xContents, xFilename);\n\n // Keep the console window open in debug mode.\n System.Console.WriteLine(\"Press any key to exit.\");\n System.Console.ReadKey();\n\n bool StartExstream(string strLine, string strFileName)\n {\n // Write the string to a file.\n using (StreamWriter outputFile = new StreamWriter(strFileName))\n {\n outputFile.WriteLine(strLine);\n return true;\n }\n }\n }\n }\n}\n namespace ZipFolder\n// .NET Framework 4.7.2\n// https://stackoverflow.com/questions/15241889/i-didnt-find-zipfile-class-in-the-system-io-compression-namespace?answertab=votes#tab-top\n{\n class Program\n {\n static void Main(string[] args)\n {\n string xlPath = @\"C:\\Users\\david\\Desktop\\Book3.xlsx\";\n string folderPath = @\"C:\\Users\\david\\Desktop\\Book3\";\n\n System.IO.Compression.ZipFile.CreateFromDirectory(folderPath, xlPath);\n\n // Keep the console window open in debug mode.\n System.Console.WriteLine(\"Press any key to exit.\");\n System.Console.ReadKey();\n }\n }\n}\n namespace UnZipXL\n// .NET Framework 4.7.2\n// https://stackoverflow.com/questions/15241889/i-didnt-find-zipfile-class-in-the-system-io-compression-namespace?answertab=votes#tab-top\n{\n class Program\n {\n static void Main(string[] args)\n {\n string XLPath = @\"C:\\Users\\david\\Desktop\\Book2.xlsx\";\n string extractPath = @\"C:\\Users\\david\\Desktop\\extract\";\n\n System.IO.Compression.ZipFile.ExtractToDirectory(XLPath, extractPath);\n\n // Keep the console window open in debug mode.\n System.Console.WriteLine(\"Press any key to exit.\");\n System.Console.ReadKey();\n }\n }\n}\n //\n// https://learn.microsoft.com/en-us/dotnet/standard/io/how-to-write-text-to-a-file\n// .NET Framework 4.7.2\n//\nusing System.IO;\n\nnamespace UpdateWorksheet5\n{\n class Program\n {\n static void Main(string[] args)\n {\n string xContents = @\"a\";\n string xFilename = @\"a\";\n\n xFilename = @\"C:\\Users\\david\\Desktop\\Book3\\xl\\worksheets\\sheet1.xml\";\n xContents = @\"<?xml version=\"\"1.0\"\" encoding=\"\"UTF-8\"\" standalone=\"\"yes\"\"?><worksheet xmlns=\"\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\"\" xmlns:r=\"\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"\" xmlns:mc=\"\"http://schemas.openxmlformats.org/markup-compatibility/2006\"\" mc:Ignorable=\"\"x14ac xr xr2 xr3\"\" xmlns:x14ac=\"\"http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac\"\" xmlns:xr=\"\"http://schemas.microsoft.com/office/spreadsheetml/2014/revision\"\" xmlns:xr2=\"\"http://schemas.microsoft.com/office/spreadsheetml/2015/revision2\"\" xmlns:xr3=\"\"http://schemas.microsoft.com/office/spreadsheetml/2016/revision3\"\" xr:uid=\"\"{54E3D330-4E78-4755-89E0-1AADACAC4953}\"\"><dimension ref=\"\"A1:A3\"\"/><sheetViews><sheetView tabSelected=\"\"1\"\" workbookViewId=\"\"0\"\"><selection activeCell=\"\"A4\"\" sqref=\"\"A4\"\"/></sheetView></sheetViews><sheetFormatPr defaultRowHeight=\"\"15\"\" x14ac:dyDescent=\"\"0.25\"\"/><sheetData><row r=\"\"1\"\" spans=\"\"1:1\"\" x14ac:dyDescent=\"\"0.25\"\"><c r=\"\"A1\"\"><v>1</v></c></row><row r=\"\"2\"\" spans=\"\"1:1\"\" x14ac:dyDescent=\"\"0.25\"\"><c r=\"\"A2\"\"><v>2</v></c></row><row r=\"\"3\"\" spans=\"\"1:1\"\" x14ac:dyDescent=\"\"0.25\"\"><c r=\"\"A3\"\"><v>3</v></c></row></sheetData><pageMargins left=\"\"0.7\"\" right=\"\"0.7\"\" top=\"\"0.75\"\" bottom=\"\"0.75\"\" header=\"\"0.3\"\" footer=\"\"0.3\"\"/></worksheet>\";\n xContents = xContents.Remove(941, 1).Insert(941, \"0\"); // character to replace is at 942 => index 941\n StartExstream(xContents, xFilename);\n\n // Keep the console window open in debug mode.\n System.Console.WriteLine(\"Press any key to exit.\");\n System.Console.ReadKey();\n\n bool StartExstream(string strLine, string strFileName)\n {\n // Write the string to a file.\n using (StreamWriter outputFile = new StreamWriter(strFileName))\n {\n outputFile.WriteLine(strLine);\n return true;\n }\n }\n }\n }\n}\n" }, { "answer_id": 73911370, "author": "Fabian", "author_id": 4226080, "author_profile": "https://Stackoverflow.com/users/4226080", "pm_score": 1, "selected": false, "text": "DataSet DataTable .xlsx using var stream = File.Create(filePath);\nstream.SaveAs(dataSet);\n MiniExcel.SaveAs(filePath, dataSet);\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/151005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19242/" ]
151,024
<p>I'm sure this is a newbie question, but every time I've compiled/dl'ed a new version of vim for os x, running vim on the command-line opens up the gvim app. I just want to upgrade the console version (so I can, for example, have python compiled in to use omnicomplete).</p>
[ { "answer_id": 151169, "author": "Dana the Sane", "author_id": 2567, "author_profile": "https://Stackoverflow.com/users/2567", "pm_score": 4, "selected": true, "text": "/opt/local/bin/vim PATH" }, { "answer_id": 14867094, "author": "David West", "author_id": 1222355, "author_profile": "https://Stackoverflow.com/users/1222355", "pm_score": 2, "selected": false, "text": "brew install macvim\nln -s /usr/local/bin/mvim /usr/local/bin/vim\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/151024", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1367022/" ]
151,026
<pre><code>sqlite&gt; DELETE FROM mails WHERE (`id` = 71); SQL error: database is locked </code></pre> <p>How do I unlock the database so this will work?</p>
[ { "answer_id": 1226850, "author": "Ben L", "author_id": 22185, "author_profile": "https://Stackoverflow.com/users/22185", "pm_score": 4, "selected": false, "text": "mv mydata.db temp.db\ncp temp.db mydata.db\n" }, { "answer_id": 3083942, "author": "Philip Clarke", "author_id": 265155, "author_profile": "https://Stackoverflow.com/users/265155", "pm_score": 1, "selected": false, "text": "fuser $ fuser database.db\n\n$ fuser database.db-journal\n philip 3556 4700 0 10:24 pts/3 00:00:01 /usr/bin/python manage.py shell\n" }, { "answer_id": 3127201, "author": "Dzung Nguyen", "author_id": 195727, "author_profile": "https://Stackoverflow.com/users/195727", "pm_score": 0, "selected": false, "text": ".timeout 100 \"UPDATE table-name SET column-name = value;\" \"UPDATE table-name SET column-name = value\"" }, { "answer_id": 5529397, "author": "Davide Ganz", "author_id": 689765, "author_profile": "https://Stackoverflow.com/users/689765", "pm_score": 2, "selected": false, "text": "rake db:migrate" }, { "answer_id": 7740613, "author": "robert", "author_id": 255345, "author_profile": "https://Stackoverflow.com/users/255345", "pm_score": 7, "selected": false, "text": "echo \".dump\" | sqlite old.db | sqlite new.db\n" }, { "answer_id": 9327800, "author": "Jay", "author_id": 779135, "author_profile": "https://Stackoverflow.com/users/779135", "pm_score": 1, "selected": false, "text": "##############\n#### Defs ####\n##############\ndef conn_exec( connection , cursor , cmd_str ):\n done = False\n try_count = 0.0\n while not done:\n try:\n cursor.execute( cmd_str )\n done = True\n except sqlite.IntegrityError:\n # Ignore this error because it means the item already exists in the database\n done = True\n except Exception, error:\n if try_count%60.0 == 0.0: # print error every minute\n print \"\\t\" , \"Error executing command\" , cmd_str\n print \"Message:\" , error\n\n if try_count%120.0 == 0.0: # if waited for 2 miutes, roll back\n print \"Forcing Unlock\"\n connection.rollback()\n\n time.sleep(0.05) \n try_count += 0.05\n\n\ndef conn_comit( connection ):\n done = False\n try_count = 0.0\n while not done:\n try:\n connection.commit()\n done = True\n except sqlite.IntegrityError:\n # Ignore this error because it means the item already exists in the database\n done = True\n except Exception, error:\n if try_count%60.0 == 0.0: # print error every minute\n print \"\\t\" , \"Error executing command\" , cmd_str\n print \"Message:\" , error\n\n if try_count%120.0 == 0.0: # if waited for 2 miutes, roll back\n print \"Forcing Unlock\"\n connection.rollback()\n\n time.sleep(0.05) \n try_count += 0.05 \n\n\n\n\n##################\n#### Run Code ####\n##################\nconnection = sqlite.connect( db_path )\ncursor = connection.cursor()\n# Create tables if database does not exist\nconn_exec( connection , cursor , '''CREATE TABLE IF NOT EXISTS fix (path TEXT PRIMARY KEY);''')\nconn_exec( connection , cursor , '''CREATE TABLE IF NOT EXISTS tx (path TEXT PRIMARY KEY);''')\nconn_exec( connection , cursor , '''CREATE TABLE IF NOT EXISTS completed (fix DATE, tx DATE);''')\nconn_comit( connection )\n" }, { "answer_id": 9333604, "author": "Mike Keskinov", "author_id": 817767, "author_profile": "https://Stackoverflow.com/users/817767", "pm_score": 2, "selected": false, "text": "sqlite_reset(xxx);\n sqlite_finalize(xxx);\n" }, { "answer_id": 28611052, "author": "J.J", "author_id": 3329564, "author_profile": "https://Stackoverflow.com/users/3329564", "pm_score": 3, "selected": false, "text": "BEGIN EXCLUSIVE END BEGIN EXCLUSIVE BEGIN EXCLUSIVE" }, { "answer_id": 35864013, "author": "user1900210", "author_id": 1900210, "author_profile": "https://Stackoverflow.com/users/1900210", "pm_score": 3, "selected": false, "text": "Pooling=true" }, { "answer_id": 36741074, "author": "kothvandir", "author_id": 1297972, "author_profile": "https://Stackoverflow.com/users/1297972", "pm_score": 1, "selected": false, "text": "final SQLiteConfig config = new SQLiteConfig();\n\nconfig.setReadOnly(false);\n\nconfig.setLockingMode(LockingMode.NORMAL);\n\nconnection = DriverManager.getConnection(url, config.toProperties());\n //myserver /mymount cifs username=*****,password=*****,iocharset=utf8,sec=ntlm,file,nolock,file_mode=0700,dir_mode=0700,uid=0500,gid=0500 0 0\n" }, { "answer_id": 38841507, "author": "ederribeiro", "author_id": 576854, "author_profile": "https://Stackoverflow.com/users/576854", "pm_score": 1, "selected": false, "text": "/var" }, { "answer_id": 48978331, "author": "Bob Stein", "author_id": 673991, "author_profile": "https://Stackoverflow.com/users/673991", "pm_score": 1, "selected": false, "text": "%userprofile%\\Local Settings\\Application Data\\Google\\Chrome\\User Data\\Default\\Web Data\n\nor\n\n%userprofile%\\Local Settings\\Application Data\\Google\\Chrome\\User Data\\Default\\Chrome Web Data\n ~/Library/Application Support/Google/Chrome/Default/Web Data\n" }, { "answer_id": 69419768, "author": "Ярослав Рахматуллин", "author_id": 657703, "author_profile": "https://Stackoverflow.com/users/657703", "pm_score": 0, "selected": false, "text": "# ~/.config/google-chrome/Default\n$ sqlite3 Login\\ Data\nSQLite version 3.35.5 2021-04-19 18:32:05\nsqlite> .tables\nError: database is locked\n $ cp Login\\ Data ~/tmp/ld.sql\n$ sqlite3 ~/tmp/ld.sql .tables\nfield_info meta sync_model_metadata \ninsecure_credentials stats \nlogins sync_entities_metadata\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/151026", "https://Stackoverflow.com", "https://Stackoverflow.com/users/823/" ]
151,030
<p>When I load <code>script/console</code>, sometimes I want to play with the output of a controller or a view helper method.</p> <p>Are there ways to:</p> <ul> <li>simulate a request?</li> <li>call methods from a controller instance on said request?</li> <li>test helper methods, either via said controller instance or another way?</li> </ul>
[ { "answer_id": 151285, "author": "Gordon Wilson", "author_id": 23071, "author_profile": "https://Stackoverflow.com/users/23071", "pm_score": 6, "selected": false, "text": ">> foo = ActionView::Base.new\n=> #<ActionView::Base:0x2aaab0ac2af8 @assigns_added=nil, @assigns={}, @helpers=#<ActionView::Base::ProxyModule:0x2aaab0ac2a58>, @controller=nil, @view_paths=[]>\n\n>> foo.extend YourHelperModule\n=> #<ActionView::Base:0x2aaab0ac2af8 @assigns_added=nil, @assigns={}, @helpers=#<ActionView::Base::ProxyModule:0x2aaab0ac2a58>, @controller=nil, @view_paths=[]>\n\n>> foo.your_helper_method(args)\n=> \"<html>created by your helper</html>\"\n ActionView::Base YourHelperModule" }, { "answer_id": 498899, "author": "Dan McNevin", "author_id": 50924, "author_profile": "https://Stackoverflow.com/users/50924", "pm_score": 4, "selected": false, "text": "./script/server -u\n class EventsController < ApplicationController\n def index\n debugger\n end\nend\n" }, { "answer_id": 1161163, "author": "kch", "author_id": 13989, "author_profile": "https://Stackoverflow.com/users/13989", "pm_score": 10, "selected": true, "text": "helper $ ./script/console\n>> helper.number_to_currency('123.45')\n=> \"R$ 123,45\"\n helper :all ApplicationController >> include BogusHelper\n>> helper.bogus\n=> \"bogus output\"\n > app.get '/posts/1'\n> response = app.response\n# you now have a rails response object much like the integration tests\n\n> response.body # get you the HTML\n> response.cookies # hash of the cookies\n\n# etc, etc\n" }, { "answer_id": 1183393, "author": "David Knight", "author_id": 145136, "author_profile": "https://Stackoverflow.com/users/145136", "pm_score": 3, "selected": false, "text": "class Object\n def request(options = {})\n url=app.url_for(options)\n app.get(url)\n puts app.html_document.root.to_s\n end\nend\n request(:controller => :show, :action => :show_frontpage)\n" }, { "answer_id": 1436342, "author": "Nick B", "author_id": 37460, "author_profile": "https://Stackoverflow.com/users/37460", "pm_score": 7, "selected": false, "text": "> app.get '/posts/1'\n> response = app.response\n# You now have a Ruby on Rails response object much like the integration tests\n\n> response.body # Get you the HTML\n> response.cookies # Hash of the cookies\n\n# etc., etc.\n" }, { "answer_id": 6436124, "author": "Swapnil Chincholkar", "author_id": 617631, "author_profile": "https://Stackoverflow.com/users/617631", "pm_score": 4, "selected": false, "text": "POST app.post 'controller/action?parameter1=value1&parameter2=value2'\n GET app.get 'controller/action'\n" }, { "answer_id": 9159853, "author": "Fernando Fabreti", "author_id": 873650, "author_profile": "https://Stackoverflow.com/users/873650", "pm_score": 7, "selected": false, "text": "app.get '/'\n app.response\n app.response.headers # => { \"Content-Type\"=>\"text/html\", ... }\n app.response.body # => \"<!DOCTYPE html>\\n<html>\\n\\n<head>\\n...\"\n foo = ActionController::Base::ApplicationController.new\nfoo.public_methods(true||false).sort\nfoo.some_method\n app.myresource_path # => \"/myresource\"\napp.myresource_url # => \"http://www.example.com/myresource\"\n foo = ActionView::Base.new\n\nfoo.javascript_include_tag 'myscript' #=> \"<script src=\\\"/javascripts/myscript.js\\\"></script>\"\n\nhelper.link_to \"foo\", \"bar\" #=> \"<a href=\\\"bar\\\">foo</a>\"\n\nActionController::Base.helpers.image_tag('logo.png') #=> \"<img alt=\\\"Logo\\\" src=\\\"/images/logo.png\\\" />\"\n views = Rails::Application::Configuration.new(Rails.root).paths[\"app/views\"]\nviews_helper = ActionView::Base.new views\nviews_helper.render 'myview/mytemplate'\nviews_helper.render file: 'myview/_mypartial', locals: {my_var: \"display:block;\"}\nviews_helper.assets_prefix #=> '/assets'\n require 'active_support/all'\n1.week.ago\n=> 2013-08-31 10:07:26 -0300\na = {'a'=>123}\na.symbolize_keys\n=> {:a=>123}\n > require 'my_utils'\n => true\n> include MyUtils\n => Object\n> MyUtils.say \"hi\"\nevaluate: hi\n => true\n" }, { "answer_id": 15709071, "author": "Tbabs", "author_id": 665215, "author_profile": "https://Stackoverflow.com/users/665215", "pm_score": 3, "selected": false, "text": "session = ActionDispatch::Integration::Session.new(Rails.application)\nsession.get(url)\nbody = session.response.body\n" }, { "answer_id": 19680853, "author": "Jyothu", "author_id": 1852370, "author_profile": "https://Stackoverflow.com/users/1852370", "pm_score": 4, "selected": false, "text": "controller.method_name\nhelper.method_name\n" }, { "answer_id": 23899701, "author": "Chloe", "author_id": 148844, "author_profile": "https://Stackoverflow.com/users/148844", "pm_score": 4, "selected": false, "text": "# Start Rails console\nrails console\n# Get the login form\napp.get '/community_members/sign_in'\n# View the session\napp.session.to_hash\n# Copy the CSRF token \"_csrf_token\" and place it in the login request.\n# Log in from the console to create a session\napp.post '/community_members/login', {\"authenticity_token\"=>\"gT7G17RNFaWUDLC6PJGapwHk/OEyYfI1V8yrlg0lHpM=\", \"refinery_user[login]\"=>'chloe', 'refinery_user[password]'=>'test'}\n# View the session to verify CSRF token is the same\napp.session.to_hash\n# Copy the CSRF token \"_csrf_token\" and place it in the request. It's best to edit this in Notepad++\napp.post '/refinery/blog/posts', {\"authenticity_token\"=>\"gT7G17RNFaWUDLC6PJGapwHk/OEyYfI1V8yrlg0lHpM=\", \"switch_locale\"=>\"en\", \"post\"=>{\"title\"=>\"Test\", \"homepage\"=>\"0\", \"featured\"=>\"0\", \"magazine\"=>\"0\", \"refinery_category_ids\"=>[\"1282\"], \"body\"=>\"Tests do a body good.\", \"custom_teaser\"=>\"\", \"draft\"=>\"0\", \"tag_list\"=>\"\", \"published_at(1i)\"=>\"2014\", \"published_at(2i)\"=>\"5\", \"published_at(3i)\"=>\"27\", \"published_at(4i)\"=>\"21\", \"published_at(5i)\"=>\"20\", \"custom_url\"=>\"\", \"source_url_title\"=>\"\", \"source_url\"=>\"\", \"user_id\"=>\"56\", \"browser_title\"=>\"\", \"meta_description\"=>\"\"}, \"continue_editing\"=>\"false\", \"locale\"=>:en}\n app.cookies.to_hash\napp.flash.to_hash\napp.response # long, raw, HTML\n" }, { "answer_id": 37830674, "author": "Dino Reic", "author_id": 254915, "author_profile": "https://Stackoverflow.com/users/254915", "pm_score": 2, "selected": false, "text": "Struct.new(:t).extend(YourHelper).your_method(*arg)\n reload!; Struct.new(:t).extend(YourHelper).your_method(*arg)\n" }, { "answer_id": 47958804, "author": "Gayan", "author_id": 3647002, "author_profile": "https://Stackoverflow.com/users/3647002", "pm_score": 2, "selected": false, "text": "class PostsController < ApplicationController\n def new\n console\n @post = Post.new\n end\nend\n <% console %>\n\n<h2>New Post</h2>\n" }, { "answer_id": 48145780, "author": "Developer Marius Žilėnas", "author_id": 1737819, "author_profile": "https://Stackoverflow.com/users/1737819", "pm_score": 2, "selected": false, "text": "include YourHelperName method_name(args) my_method include MyHelper my_helper.my_method" }, { "answer_id": 54476954, "author": "Dyaniyal Wilson", "author_id": 8728218, "author_profile": "https://Stackoverflow.com/users/8728218", "pm_score": 3, "selected": false, "text": "class CustomPagesController < ApplicationController\n\n def index\n @customs = CustomPage.all\n end\n\n def get_number\n puts \"Got the Number\"\n end\n\n protected\n\n def get_private_number\n puts 'Got private Number'\n end\n\nend\n\ncustom = CustomPagesController.new\n2.1.5 :011 > custom = CustomPagesController.new\n => #<CustomPagesController:0xb594f77c @_action_has_layout=true, @_routes=nil, @_headers={\"Content-Type\"=>\"text/html\"}, @_status=200, @_request=nil, @_response=nil>\n2.1.5 :014 > custom.get_number\nGot the Number\n => nil\n\n# For calling private or protected methods,\n2.1.5 :048 > custom.send(:get_private_number)\nGot private Number\n => nil\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/151030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13989/" ]
151,046
<p>I'm trying to figure out the best way to determine whether I'm in the last iteration of a loop over a map in order to do something like the following:</p> <pre><code>for (iter = someMap.begin(); iter != someMap.end(); ++iter) { bool last_iteration; // do something for all iterations if (!last_iteration) { // do something for all but the last iteration } } </code></pre> <p>There seem to be several ways of doing this: random access iterators, the <code>distance</code> function, etc. What's the canonical method?</p> <p>Edit: no random access iterators for maps!</p>
[ { "answer_id": 151073, "author": "Torlack", "author_id": 5243, "author_profile": "https://Stackoverflow.com/users/5243", "pm_score": 4, "selected": false, "text": "bool last_iteration = iter == (--someMap.end());\n" }, { "answer_id": 151078, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 6, "selected": true, "text": "final_iter = someMap.end();\n--final_iter;\nif (iter != final_iter) ...\n" }, { "answer_id": 151104, "author": "KTC", "author_id": 12868, "author_profile": "https://Stackoverflow.com/users/12868", "pm_score": 3, "selected": false, "text": "finalIter = someMap.end();\n--finalIter;\nif (iter != final_iter)\n" }, { "answer_id": 151112, "author": "Jason Etheridge", "author_id": 2193, "author_profile": "https://Stackoverflow.com/users/2193", "pm_score": 0, "selected": false, "text": " size_t items_remaining = someMap.size();\n\n for (iter = someMap.begin(); iter != someMap.end(); iter++) {\n bool last_iteration = items_remaining-- == 1;\n }\n" }, { "answer_id": 151165, "author": "florin", "author_id": 18308, "author_profile": "https://Stackoverflow.com/users/18308", "pm_score": -1, "selected": false, "text": "#include <iostream>\n#include <list>\n\nvoid process(int ii)\n{\n std::cout << \" \" << ii;\n}\n\nint main(void)\n{\n std::list<int> ll;\n\n ll.push_back(1);\n ll.push_back(2);\n ll.push_back(3);\n ll.push_back(4);\n ll.push_back(5);\n ll.push_back(6);\n\n std::list<int>::iterator iter = ll.begin();\n if (iter != ll.end())\n {\n std::list<int>::iterator lastIter = iter;\n ++ iter;\n while (iter != ll.end())\n {\n process(*lastIter);\n lastIter = iter;\n ++ iter;\n }\n // todo: think if you need to process *lastIter\n std::cout << \" | last:\";\n process(*lastIter);\n }\n\n std::cout << std::endl;\n\n return 0;\n}\n 1 2 3 4 5 | last: 6\n" }, { "answer_id": 151497, "author": "oz10", "author_id": 14069, "author_profile": "https://Stackoverflow.com/users/14069", "pm_score": 1, "selected": false, "text": "#include <boost/lambda/lambda.hpp>\n#include <boost/lambda/bind.hpp>\n#include <algorithm>\n\nusing namespace boost::lambda;\n\n// call the function foo on each element but the last...\nif( !someMap.empty() )\n{\n std::for_each( someMap.begin(), --someMap.end(), bind( &Foo, _1 ) );\n}\n" }, { "answer_id": 152707, "author": "camh", "author_id": 23744, "author_profile": "https://Stackoverflow.com/users/23744", "pm_score": 3, "selected": false, "text": "for ( i = c.begin(); i != c.end(); ) {\n iterator cur = i++;\n // do something, using cur\n if ( i != c.end() ) {\n // do something using cur for all but the last iteration\n }\n}\n" }, { "answer_id": 156310, "author": "Ates Goral", "author_id": 23501, "author_profile": "https://Stackoverflow.com/users/23501", "pm_score": -1, "selected": false, "text": "iter = someMap.begin();\n\ndo {\n // Note that curr = iter++ may involve up to three copy operations\n curr = iter;\n\n // Do stuff with curr\n\n if (++iter == someMap.end()) {\n // Oh, this was the last iteration\n break;\n }\n\n // Do more stuff with curr\n\n} while (true);\n" }, { "answer_id": 495065, "author": "Pieter", "author_id": 5822, "author_profile": "https://Stackoverflow.com/users/5822", "pm_score": 3, "selected": false, "text": "for (iter = someMap.begin(); iter != someMap.end(); ++iter) {\n // do something for all iterations\n if (boost::next(iter) != someMap.end()) {\n // do something for all but the last iteration\n }\n}\n" }, { "answer_id": 8431209, "author": "mpoleg", "author_id": 1087757, "author_profile": "https://Stackoverflow.com/users/1087757", "pm_score": 2, "selected": false, "text": "if (&*it == &*someMap.rbegin()) {\n //the last iteration\n}\n final_iter = someMap.end();\n--final_iter;\n" }, { "answer_id": 15847509, "author": "Angelin Nadar", "author_id": 412591, "author_profile": "https://Stackoverflow.com/users/412591", "pm_score": 2, "selected": false, "text": "for (iter = someMap.begin(); someMap.end() - 1; ++iter) {\n //apply to all from begin to second last element\n}\n" }, { "answer_id": 33475580, "author": "Todoroki", "author_id": 4145123, "author_profile": "https://Stackoverflow.com/users/4145123", "pm_score": 1, "selected": false, "text": "for (iter = someMap.begin(); iter != someMap.end(); ++iter) {\n // do something for all iterations\n if (iter != --someMap.end()) {\n // do something for all but the last iteration\n }\n}\n" }, { "answer_id": 34222218, "author": "dutchdukes", "author_id": 2392704, "author_profile": "https://Stackoverflow.com/users/2392704", "pm_score": 5, "selected": false, "text": " for (auto iter = someMap.begin(); iter != someMap.end(); ++iter) { \n // do something for all iterations\n if (std::next(iter) != someMap.end()) {\n // do something for all but the last iteration\n }\n }\n" }, { "answer_id": 59188201, "author": "alfred", "author_id": 12483466, "author_profile": "https://Stackoverflow.com/users/12483466", "pm_score": 1, "selected": false, "text": " for (const auto& pair : someMap) {\n if (&pair != &*someMap.rbegin()) ...\n }\n auto pair" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/151046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3594/" ]
151,051
<p>In .NET, under which circumstances should I use <code>GC.SuppressFinalize()</code>?</p> <p>What advantage(s) does using this method give me?</p>
[ { "answer_id": 151058, "author": "albertein", "author_id": 23020, "author_profile": "https://Stackoverflow.com/users/23020", "pm_score": -1, "selected": false, "text": "Dispose IDisposable Dispose" }, { "answer_id": 151059, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 6, "selected": false, "text": "SupressFinalize Dispose() GC.SupressFinalize() SupressFinalize Dispose() GC.SupressFinalize()" }, { "answer_id": 151244, "author": "Robert Paulson", "author_id": 14033, "author_profile": "https://Stackoverflow.com/users/14033", "pm_score": 10, "selected": true, "text": "SuppressFinalize this IDisposable public class MyClass : IDisposable\n{\n private bool disposed = false;\n\n protected virtual void Dispose(bool disposing)\n {\n if (!disposed)\n {\n if (disposing)\n {\n // called via myClass.Dispose(). \n // OK to use any private object references\n }\n // Release unmanaged resources.\n // Set large fields to null. \n disposed = true;\n }\n }\n\n public void Dispose() // Implement IDisposable\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n ~MyClass() // the finalizer\n {\n Dispose(false);\n }\n}\n SuppressFinalize SuppressFinalize SuppressFinalize IDisposable IDisposable IDisposable IDisposable IDisposable public void Dispose() // Implement IDisposable\n{\n Dispose(true);\n#if DEBUG\n GC.SuppressFinalize(this);\n#endif\n}\n\n#if DEBUG\n~MyClass() // the finalizer\n{\n Dispose(false);\n}\n#endif\n" }, { "answer_id": 49848638, "author": "Max CHien", "author_id": 3350329, "author_profile": "https://Stackoverflow.com/users/3350329", "pm_score": 2, "selected": false, "text": "Dispose(true);\nGC.SuppressFinalize(this);\n Dispose(true) GC.SuppressFinalize(this)" }, { "answer_id": 50053055, "author": "supercat", "author_id": 363751, "author_profile": "https://Stackoverflow.com/users/363751", "pm_score": 1, "selected": false, "text": "GC.SuppressFinalize(this) GC.KeepAlive(this) GC.KeepAlive() GC.SuppressFinalize(this) GC.SuppressFinalize(this) Dispose()" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/151051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17174/" ]
151,066
<p>I have a Ruby/Rails app that has two or three main "sections". When a user visits that section, I wish to display some sub-navigation. All three sections use the same layout, so I can't "hard code" the navigation into the layout.</p> <p>I can think of a few different methods to do this. I guess in order to help people vote I'll put them as answers.</p> <p>Any other ideas? Or what do you vote for?</p>
[ { "answer_id": 151289, "author": "webmat", "author_id": 6349, "author_profile": "https://Stackoverflow.com/users/6349", "pm_score": 1, "selected": false, "text": "module RenderHelper\n #options: a nested array of menu names and their corresponding url\n def render_submenu(menu_items=[[]])\n render :partial => 'shared/submenu', :locals => {:menu_items => menu_items}\n end\nend\n" }, { "answer_id": 151311, "author": "webmat", "author_id": 6349, "author_profile": "https://Stackoverflow.com/users/6349", "pm_score": 3, "selected": false, "text": "class PostsController < ApplicationController\n#...\nprotected\n helper_method :menu_items\n def menu_items\n [\n ['Submenu 1', url_for(me)],\n ['Submenu 2', url_for(you)]\n ]\n end\nend\n" }, { "answer_id": 157410, "author": "Jason Miesionczek", "author_id": 18811, "author_profile": "https://Stackoverflow.com/users/18811", "pm_score": 1, "selected": false, "text": "module NestedLayouts\n def render(options = nil, &block)\n if options\n if options[:layout].is_a?(Array)\n layouts = options.delete(:layout)\n options[:layout] = layouts.pop\n inner_layout = layouts.shift\n options[:text] = layouts.inject(render_to_string(options.merge({:layout=>inner_layout}))) do |output,layout|\n render_to_string(options.merge({:text => output, :layout => layout}))\n end\n end\n end\n super\n end\nend\n include NestedLayouts\n def show\n ...\n render :layout => ['admin','application']\nend\n" }, { "answer_id": 157469, "author": "Olly", "author_id": 1174, "author_profile": "https://Stackoverflow.com/users/1174", "pm_score": 4, "selected": true, "text": "PostsController UsersController AdminController views _subnav.html.erb /users/_subnav.html.erb <ul id=\"subnav\">\n <li><%= link_to 'All Users', users_path %></li>\n <li><%= link_to 'New User', new_user_path %></li>\n</ul>\n /posts/_subnav.html.erb <ul id=\"subnav\">\n <li><%= link_to 'All Posts', posts_path %></li>\n <li><%= link_to 'New Post', new_post_path %></li>\n</ul>\n <div id=\"header\">...</div> \n<%= render :partial => \"subnav\" %>\n<div id=\"content\"><%= yield %></div>\n<div id=\"footer\">...</div>\n" }, { "answer_id": 394212, "author": "maurycy", "author_id": 48541, "author_profile": "https://Stackoverflow.com/users/48541", "pm_score": 0, "selected": false, "text": "content_for" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/151066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2590/" ]
151,079
<p>My app generates PDFs for user consumption. The "Content-Disposition" http header is set as mentioned <a href="https://stackoverflow.com/questions/74019/specifying-filename-for-dynamic-pdf-in-aspnet">here</a>. This is set to "inline; filename=foo.pdf", which should be enough for Acrobat to give "foo.pdf" as the filename when saving the pdf.</p> <p>However, upon clicking the "Save" button in the browser-embedded Acrobat, the default name to save is not that filename but instead the URL with slashes changed to underscores. Huge and ugly. Is there a way to affect this default filename in Adobe?</p> <p>There IS a query string in the URLs, and this is non-negotiable. This may be significant, but adding a "&amp;foo=/title.pdf" to the end of the URL doesn't affect the default filename.</p> <p>Update 2: I've tried both</p> <pre><code>content-disposition inline; filename=foo.pdf Content-Type application/pdf; filename=foo.pdf </code></pre> <p>and</p> <pre><code>content-disposition inline; filename=foo.pdf Content-Type application/pdf; name=foo.pdf </code></pre> <p>(as verified through Firebug) Sadly, neither worked.</p> <p>A sample url is</p> <pre>/bar/sessions/958d8a22-0/views/1493881172/export?format=application/pdf&no-attachment=true</pre> <p>which translates to a default Acrobat save as filename of</p> <pre>http___localhost_bar_sessions_958d8a22-0_views_1493881172_export_format=application_pdf&no-attachment=true.pdf</pre> <p>Update 3: Julian Reschke brings actual insight and rigor to this case. Please upvote his answer. This seems to be broken in FF (<a href="https://bugzilla.mozilla.org/show_bug.cgi?id=433613" rel="nofollow noreferrer">https://bugzilla.mozilla.org/show_bug.cgi?id=433613</a>) and IE but work in Opera, Safari, and Chrome. <a href="http://greenbytes.de/tech/tc2231/#inlwithasciifilenamepdf" rel="nofollow noreferrer">http://greenbytes.de/tech/tc2231/#inlwithasciifilenamepdf</a></p>
[ { "answer_id": 151302, "author": "Vivek", "author_id": 7418, "author_profile": "https://Stackoverflow.com/users/7418", "pm_score": 4, "selected": false, "text": "context.Response.ContentType = \"application/pdf; name=\" + fileName;\n// the usual stuff\ncontext.Response.AddHeader(\"content-disposition\", \"inline; filename=\" + fileName);\n context.Response.AddHeader(\"Content-Length\", fileBytes.Length.ToString());\ncontext.Response.BinaryWrite(fileBytes);\n" }, { "answer_id": 151458, "author": "ManiacZX", "author_id": 18148, "author_profile": "https://Stackoverflow.com/users/18148", "pm_score": 1, "selected": false, "text": "Response.AddHeader(\"content-disposition\", \"inline;filename=MyFile.pdf\");\n" }, { "answer_id": 864492, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "/bar/sessions/958d8a22-0/views/1493881172/export?format=application/pdf&no-attachment=true\n /bar/sessions/958d8a22-0/views/1493881172/NameThatIWantPDFToBe.pdf?GeneratePDF=1\n /bar/sessions/958d8a22-0/views/1493881172/NameThatIWantPDFToBe.pdf" }, { "answer_id": 898179, "author": "Fabrizio Accatino", "author_id": 21145, "author_profile": "https://Stackoverflow.com/users/21145", "pm_score": 2, "selected": false, "text": "<httpHandlers> \n<add verb=\"*\" path=\"MyDocument_*.ashx\" type=\"ITextMiscWeb.MyDocumentHandler\"/>\n <add verb=\"*\" path=\"/CustomName/*.ashx\" type=\"ITextMiscWeb.MyDocumentHandler\"/>\n" }, { "answer_id": 1805495, "author": "Rick Cooper", "author_id": 219673, "author_profile": "https://Stackoverflow.com/users/219673", "pm_score": 0, "selected": false, "text": "SomeScript.php?id=ID&data=DATA TEST.pdf SomeScript.php/id/ID/data/DATA/EXT/TEST.pdf SomeScript.php $_REQUEST = MakeFriendlyURI( $_SERVER['PHP\\_SELF'], $_SERVER['SCRIPT_FILENAME']);\n SomeScript.php function MakeFriendlyURI($URI, $ScriptName) {\n\n/* Need to remove everything up to the script name */\n$MyName = '/^.*'.preg_quote(basename($ScriptName).\"/\", '/').'/';\n$Str = preg_replace($MyName,'',$URI);\n$RequestArray = array();\n\n/* Breaks down like this\n 0 1 2 3 4 5\n PARAM1/VAL1/PARAM2/VAL2/PARAM3/VAL3\n*/\n\n$tmp = explode('/',$Str); \n/* Ok so build an associative array with Key->value\n This way it can be returned back to $_REQUEST or $_GET\n */\nfor ($i=0;$i < count($tmp); $i = $i+2){\n $RequestArray[$tmp[$i]] = $tmp[$i+1];\n}\nreturn $RequestArray; \n}//EO MakeFriendlyURI\n $_REQUEST $_GET $_REQUEST['id'] $_REQUEST['data']" }, { "answer_id": 4477176, "author": "Sunder Chhokar", "author_id": 546858, "author_profile": "https://Stackoverflow.com/users/546858", "pm_score": 1, "selected": false, "text": "private void DownloadSharePointDocument()\n{\n Uri uriAddress = new Uri(\"http://hyddlf5187:900/SharePointDownloadService/FulfillmentDownload.svc/GetDocumentByID/1/drmfree/\");\n HttpWebRequest req = WebRequest.Create(uriAddress) as HttpWebRequest;\n // Get response \n using (HttpWebResponse httpWebResponse = req.GetResponse() as HttpWebResponse)\n {\n Stream stream = httpWebResponse.GetResponseStream();\n int byteCount = Convert.ToInt32(httpWebResponse.ContentLength);\n byte[] Buffer1 = new byte[byteCount];\n using (BinaryReader reader = new BinaryReader(stream))\n {\n Buffer1 = reader.ReadBytes(byteCount);\n }\n Response.Clear();\n Response.ClearHeaders();\n // set the content type to PDF \n Response.ContentType = \"application/pdf\";\n Response.AddHeader(\"Content-Disposition\", \"attachment;filename=Filename.pdf\");\n Response.Buffer = true;\n Response.BinaryWrite(Buffer1);\n Response.Flush();\n // Response.End();\n }\n}\n" }, { "answer_id": 4534492, "author": "Karsten", "author_id": 554378, "author_profile": "https://Stackoverflow.com/users/554378", "pm_score": 2, "selected": false, "text": "http://www. server.com/DocServe.aspx?DocId=XXXXXXX\n http://www. server.com/DocServe.aspx/MySaveAsFileName?DocId=XXXXXXX\n MySaveAsFileName.pdf MySaveAsFileName" }, { "answer_id": 6852514, "author": "Mark Nettle", "author_id": 866460, "author_profile": "https://Stackoverflow.com/users/866460", "pm_score": 2, "selected": false, "text": "mod_rewrite /foo/getDoc.service getDoc.pdf apache.conf LoadModule RewriteModule modules/mod_rewrite.so\nRewriteEngine on\nRewriteRule ^/foo/getDoc/(.*)$ /foo/getDoc.service [P,NE]\n /foo/getDoc/filename.pdf?bar&qux /foo/getDoc.service?bar&qux filename.pdf" }, { "answer_id": 51303129, "author": "qräbnö", "author_id": 1707015, "author_profile": "https://Stackoverflow.com/users/1707015", "pm_score": 0, "selected": false, "text": "location /file.pdf\n{\n # more_set_headers \"Content-Type: application/pdf; name=save_as_file.pdf\";\n add_header Content-Disposition \"inline; filename=save_as_file.pdf\";\n alias /var/www/file.pdf;\n}\n curl -I https://example.com/file.pdf\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/151079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9365/" ]
151,083
<p>Having this route:</p> <pre><code>map.foo 'foo/*path', :controller =&gt; 'foo', :action =&gt; 'index' </code></pre> <p>I have the following results for the <code>link_to</code> call</p> <pre><code>link_to "Foo", :controller =&gt; 'foo', :path =&gt; 'bar/baz' # &lt;a href="/foo/bar%2Fbaz"&gt;Foo&lt;/a&gt; </code></pre> <p>Calling <code>url_for</code> or <code>foo_url</code> directly, even with <code>:escape =&gt; false</code>, give me the same url:</p> <pre><code>foo_url(:path =&gt; 'bar/baz', :escape =&gt; false, :only_path =&gt; true) # /foo/bar%2Fbaz </code></pre> <p>I want the resulting url to be: <code>/foo/bar/baz</code></p> <p>Is there a way around this without patching rails?</p>
[ { "answer_id": 151239, "author": "Gordon Wilson", "author_id": 23071, "author_profile": "https://Stackoverflow.com/users/23071", "pm_score": 3, "selected": true, "text": "link_to \"Foo\", :controller => 'foo', :path => %w(bar baz)\n# <a href=\"/foo/bar/baz\">Foo</a>\n # <a href=\"/foo?path[]=bar&path[]=baz\">Foo</a>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/151083", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13989/" ]
151,099
<p>I have two tables that are joined together. </p> <p>A has many B</p> <p>Normally you would do: </p> <pre><code>select * from a,b where b.a_id = a.id </code></pre> <p>To get all of the records from a that has a record in b. </p> <p>How do I get just the records in a that does not have anything in b?</p>
[ { "answer_id": 151102, "author": "albertein", "author_id": 23020, "author_profile": "https://Stackoverflow.com/users/23020", "pm_score": 8, "selected": true, "text": "select * from a where id not in (select a_id from b)\n select a.* from a\nleft outer join b on a.id = b.a_id\nwhere b.a_id is null\n" }, { "answer_id": 151103, "author": "BlackWasp", "author_id": 21862, "author_profile": "https://Stackoverflow.com/users/21862", "pm_score": 1, "selected": false, "text": "SELECT <columnns>\nFROM a WHERE id NOT IN (SELECT a_id FROM b)\n" }, { "answer_id": 151110, "author": "Joseph Anderson", "author_id": 18102, "author_profile": "https://Stackoverflow.com/users/18102", "pm_score": 5, "selected": false, "text": "select * from a\nleft outer join b on a.id = b.a_id\nwhere b.a_id is null\n" }, { "answer_id": 151113, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 3, "selected": false, "text": "select * from a where not exists (select * from b where b.a_id = a.id)\n" }, { "answer_id": 151119, "author": "nathan", "author_id": 16430, "author_profile": "https://Stackoverflow.com/users/16430", "pm_score": 2, "selected": false, "text": "select * from a left outer join b on a.id = b.a_id where b.a_id is null;\n" }, { "answer_id": 151120, "author": "shahkalpesh", "author_id": 23574, "author_profile": "https://Stackoverflow.com/users/23574", "pm_score": 1, "selected": false, "text": "select a.*\nfrom a \nleft outer join b\non a.id = b.id\nwhere b.id is null\n" }, { "answer_id": 9682494, "author": "onedaywhen", "author_id": 15354, "author_profile": "https://Stackoverflow.com/users/15354", "pm_score": 3, "selected": false, "text": "SELECT id FROM a\nEXCEPT\nSELECT a_id FROM b;\n" }, { "answer_id": 48116779, "author": "Petr Štipek", "author_id": 8517134, "author_profile": "https://Stackoverflow.com/users/8517134", "pm_score": 1, "selected": false, "text": "select a.* from a\nwhere a.id NOT IN(SELECT DISTINCT a_id FROM b where a_id IS NOT NULL)\n//And for more joins\nAND a.id NOT IN(SELECT DISTINCT a_id FROM c where a_id IS NOT NULL)\n" }, { "answer_id": 48278755, "author": "Daniele Licitra", "author_id": 5580181, "author_profile": "https://Stackoverflow.com/users/5580181", "pm_score": 0, "selected": false, "text": "select a.* from a where a.id not in (select b.ida from b)\n select a.*\n from a left outer join b on a.id = b.ida\n where b.ida is null\n select count(*) from product a left outer join compatible c on a.id=c.idprod where c.idprod is null\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/151099", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1681/" ]
151,100
<p>I am developing a web application using Struts 2.1.2 and Hibernate 3.2.6.GA. I have an entity, <code>User</code>, which I have mapped to a table <code>USERS</code> in the DB using Hibernate. I want to have an image associated with this entity, which I plan to store as a <code>BLOB</code> in the DB. I also want to display the image on a webpage along with other attributes of the <code>User</code>.</p> <p>The solution I could think of was to have a table <code>IMAGES(ID, IMAGE)</code> where <code>IMAGE</code> is a <code>BLOB</code> column. <code>USERS</code> will have an <code>FK</code> column called <code>IMAGEID</code>, which points to the <code>IMAGES</code> table. I will then map a property on <code>User</code> entity, called <code>imageId</code> mapped to this <code>IMAGEID</code> as a Long. When rendering the page with a JSP, I would add images as <code>&lt;img src="images.action?id=1"/&gt;</code> etc, and have an Action which reads the image and streams the content to the browser, with the headers set to cache the image for a long time.</p> <p>Will this work? Is there a better approach for rendering images stored in a DB? Is storing such images in the DB the right approach in the first place?</p>
[ { "answer_id": 151136, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 0, "selected": false, "text": "data:<mimetype>;base64,<data>\n <img src=\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEYAAAAmCAYAAAB52u3eAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsSAAALEgHS3X78AAAAB3RJTUUH1AkICzQgAc6C2QAACrxJREFUeNrtmnl0VdUVxn/3vnnIPBKmJECYkoAEERArgxGqCDIUkKVoqRZKUVREnC1SXXWJlKo4VrEi4EAUEARUtM5oVcAwZhZIyEySlzfe4fSPlzwSEzGUuLpa2Gu9te49Z99zzvvu3vt8e58rCSEAUBWNoyV1wZtzVHokR0pGkwEASQhB2bF6sX/vCZxhFjzuwDkJSlWFm4LDVYyf1I9ho3pKRiWg8f23ZfTPTCQ+0XkuGwzPr/qCZ1Z8zsDBXTCWFNYKq81EVIwNm910TgNzwbBufPlxCR9uzxMyQEO9j/MSlLpaLwDyeSjal3MOmBunb/gvABNQoepku12qqrVpUxTtjKdQVY1mivFTY7Wn09x/rKSuQ/MYOwsTUViKOn0RxifvRYqLAuDw/goeuO1dIiJtVJa7+PWUAcy//WJUVWPhdTl43AFqqz0sXT4utDOOndCHS/r/jb88fRUjLk1mRvbLbNw1FyEEdy14h9Kj9TS6/MyZfyEDMhP50+LtGI0GMrOSWLJsbBudSTPSmTfzDVRVJyrG1uGX0SnAiGPlKBfPhIp6pAG9Wrw5nfJSF6/tvB6AsYNWM/OGC/j0g0Ji4uw8u2EGleUuZmS/zCNPTmT7pkN07R5Ot56RfLSzAGe4hR4pQZB3bjmMxWrk1W3XoSgaEy58llVrplBZ3sgHexYgyzI7Nh9qo2M0yvRIieLBFRMoKaxl6ugXfxlgPn6vgEaXnyunDQy1abPvRVQUIPfMgghHK/0BgxKR5aDH9ktP4GjxSQrzasjM6gpAfGIYHneArBHdWb50J8m9orlx0QjWrP6K6Bgbo8amhqxv3zel3HJ9DkIIEpPC8HlVBrYYvz2d/XvLSb+gCwDJvaIJj7R2PjB+v8q82a+zbMUVoTZ966fon+1CIgoMMhgMrZ4pyqtudZ3ULYJuPSM5cqAyuD2e9GKxGLFYjERG2di6cT/rts8h59V9bM05yMubZof+VGZWV5avOjX3/r0nkGUpdN+ezptr94bWUHHChauD1OSMgHl4yXvU1LhbWYu+ZjMgBeO4xwdeP9gsp6xJE9w8ZyMN9X4uvbw3cQlOrvrNQN5ev49b575FcX4Ndz+SDcCosal8sO0IdruZkaNTOLD3BPGJYQBMnD6Q9945wtyp64mJc+DzKsy7/eJW62tP57HnJ3PdxFdZMm8zXo9CWETHLIa8g5Vi8+u5or7OK04ne746JszcJn7V/4lTjQFFBLqNF376Cz8Zwm+4QOiFx0PduXvKxC3XbxQeT0DUVLvbjFlZ7hJeb0CcidSd9IiqCtcZ6ei6LsrLGoSmaad97uP3C8T4oc+ILW/kig5ZjM+rMP/aN9EReNwBVFXHaJQRpZWI8uomwzOAVof4OhcpNRg/TGYD0bEObDYTNlvbdCMu4cxzs4hI2xnrSJJEQpewM5qnQ8DcOW8L3+QfJRYHxcdqKThcRb/0BHC5QQ00uRKAhL5+J/KsCQD0HRDPgyuC17ouePetgxQX1+JtCODxBBCAxWIgLSOecdlpRMXaQ3OWHq1n08bvkZGwWc1cM3cIFquRb3cf47PPi7DJrYEWgCo0ps0cRGLXcHLW7aO8ogGT1Drm+XWVPr3imHB1/7MDZlvOQZ5b+wWxOJGABuFh82u59PtzAiTFg8MJblcTV3Sgb9+FOFKC1De51TiapnPLDTkUu6uxYMKPH9AAMyYMJMVE8OTT07hqRnqzi7Nw8euAgXicTJ6ZjsVqZMemQ9z3aA5mnE2AnCJyCl769I4jsWs4j96/i38VF2HG8iMdH9lDMn4WmNMyX0XRePiu9zBjCNmEAwuvvfQdXo+CFBOBPDwD8DT1GkB1oT3wTLvjRUbZiMSBAzNTRw9h0Q3ZpMd1wYmFkzUefjdrAyUFtUE3NBkIw0E0dqIi7UhScAU2uwlTU3skNpxYQj+wUF/na3InK2E4iMFORAs9Ezb8PvXsXCnvQBWHCspxYA61WTGSd6KK3Z+WMGZ8H+SbpqHv2tniqXD0NzYhbr4GadTgdsd1E+Dmu37F6PG9OV5Sx5ispzhZ66FGePhwRx5zFw7/2YV7CHDRkJ489txkmtm/puskp0a30qvHx9LFlzF5VgZCCHQhsNtMZx9jNFrnHBLgR6XgUFUQmKljkVLSEcWFgLXJCHXUBY9g2vNakNv8SCQkGl1+ALolR9KvTwL//CofCfC4lY7lTGhERdsZNLTr6dM3NNIHd2HQ0KTOC7590+MZc3Eftnz+PTE4kZHwoiAh0T8zMahkMiIvmIG25IEmYACciNzd6C9tRr5pStsUAoHDGbTC/XtO8P2BUkwYUNAYfknPDma/Mu7GAOVlLhDBKCJJEvGJzlakz46JbW8foK7Oi6bp+ITCyOEpZA3v/p8DYzTKrNk0m6W3OPloZz5+j0pKagyLbrs0RNUB5EmXot0ZCUJvEbasaE9tQL7xapCkVuM6sbBi2UesWf0Vn35YhMvjJ4DG0lsvY+jIHh0CxomFPV8fZ3ivlUELEjp2q5kv8xcRE+dspffGW3v4x1tfIwEqHpbdMeXsgAGIjrXzwvpZNPh0PPUeEtvjHj4/COVHw9kQ+/MRxWUhXtMsFozs2H0QkIjGhkDw1FPTuOGPF3XY1CUk/LpKua8hSAfQsfstaFpr19cR2DFjx4xAUAtYOyPGhEJqVTnh3dv3U23VOsAHhLeORroXyirhR8D4UZkyZhBF+dUUHa/BgMQLT+9m0swMoltwmdPmbSik9IhhyZxxoaBqMhlwhlnaBN/77x7PtGsHAQJNEx0q+ncYGPXxdYj9uRiX34E0dACYjIii4+grX0Ffsx5oj1kawNGWqTbiZ8mysST3jubCtMfxNip8ebCYh+7YwaqXp3ZoPT4UeqXFsnT5uNPqKWik9okhbUDcL1PalC/KQN+1DWXkNSi9rkJJm4zS92q01X8HHC3Y76n9QIpLaEP0mt2gsryRhC5hLL5rDHV4icXBhrXf8UNRbYdd6XRFJ10PupQJmd2fleD1KPh9Kj6vis+nInTRScBkD0dypAX3lGM/IPLzmtKBiHZAkYB65N9PA3v72WxzPL7+D8PoER6FjqBGd7Nx7b5OqSiaTAY0dCKw8epL3zAs5XEuSl3J0NQVjOj9V8qO13dSzTc2EsOdvwXqAHPT1mz4CeVqpCGXYLjvxlatrnof9Xjx4Q297choG5df0Zca6tDQWP/itwgBQghceKnHS0O9L1TD9ftUFLy48eJu/OlT04nTB+LBSx1eGvFzqLKC3BMnOFBeRnFpNRarsfPqMYYHbkLk/YC+7pUmYGwtsBWAH2hEGp2NaeMqsJ4KhLIkMWlmBhXVjShCpXvPqFDfnPnDqPG6sUtmZCQ87gBJ3SO4ZvJQjJJMuMOK2RJc6sDBXZg+aRhGSWZw+k+Tu4VLL8HuMPHJJ4VIASlkoQo6MZF2nGHWzqnHtBRt7VYRGDFb+K1Zwk9f4SdN+MkUgfRJQn1infhflTOux7Txv2uvRL72SkRZJZSUgaJC13ik3j34f5GzOiWQkuKDpYfzJ5Hnj2jPAwNQUdZwHolmolHZGAwTAb/KPTdvFWHhVkaNTTmnQVkybwtVFY0cqrlHMprMBq6elcnKhz7i689+CJUGzzWpq/VQW+1h5YtTcDjNwW/wABpdft7feuSc/jgxe2JfqTk7/zeNpiqnFESz8wAAAABJRU5ErkJggg==\">\n" }, { "answer_id": 151194, "author": "Craig Wohlfeil", "author_id": 22767, "author_profile": "https://Stackoverflow.com/users/22767", "pm_score": 3, "selected": true, "text": "<a href=\"foo.jsp\"><img src=\"imageservlet/123456789.png\"></a>\n <servlet>\n <servlet-name>ImageServlet</servlet-name>\n <servlet-class>com.example.ImageServlet</servlet-class>\n</servlet>\n<servlet-mapping>\n <servlet-name>ImageServlet</servlet-name>\n <url-pattern>/imageservlet/*</url-pattern>\n</servlet-mapping>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/151100", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3973/" ]
151,124
<p>Which one should I use?</p> <pre><code>catch (_com_error e) </code></pre> <p>or </p> <pre><code>catch (_com_error&amp; e) </code></pre>
[ { "answer_id": 151126, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 6, "selected": true, "text": "catch const throw; throw e; try { throw MyException (\"error\") } \ncatch (Exception e) {\n /* Implies: Exception e (MyException (\"error\")) */\n /* e is an instance of Exception, but not MyException */\n}\n try { throw MyException (\"error\") } \ncatch (Exception& e) {\n /* Implies: Exception &e = MyException (\"error\"); */\n /* e is an instance of MyException */\n}\n" }, { "answer_id": 151141, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 2, "selected": false, "text": "class my_exception : public exception\n{\n int my_exception_data;\n};\n\nvoid foo()\n{\n throw my_exception;\n}\n\nvoid bar()\n{\n try\n {\n foo();\n }\n catch (exception e)\n {\n // e is \"sliced off\" - you lose the \"my_exception-ness\" of the exception object\n }\n}\n" }, { "answer_id": 151451, "author": "jonner", "author_id": 78437, "author_profile": "https://Stackoverflow.com/users/78437", "pm_score": 4, "selected": false, "text": "catch (const _com_error& e)\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/151124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9328/" ]
151,152
<p>I'm using spring 2.5, and am using annotations to configure my controllers. My controller works fine if I do not implement any additional interfaces, but the spring container doesn't recognize the controller/request mapping when I add interface implementations.</p> <p>I can't figure out why adding an interface implementation messes up the configuration of the controller and the request mappings. Any ideas?</p> <p>So, this works:</p> <pre><code>package com.shaneleopard.web.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.providers.encoding.Md5PasswordEncoder; import org.springframework.stereotype.Controller; import org.springframework.validation.Errors; import org.springframework.validation.Validator; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.shaneleopard.model.User; import com.shaneleopard.service.UserService; import com.shaneleopard.validator.RegistrationValidator; import com.shaneleopard.web.command.RegisterCommand; @Controller public class RegistrationController { @Autowired private UserService userService; @Autowired private Md5PasswordEncoder passwordEncoder; @Autowired private RegistrationValidator registrationValidator; @RequestMapping( method = RequestMethod.GET, value = "/register.html" ) public void registerForm(@ModelAttribute RegisterCommand registerCommand) { // no op } @RequestMapping( method = RequestMethod.POST, value = "/register.html" ) public String registerNewUser( @ModelAttribute RegisterCommand command, Errors errors ) { String returnView = "redirect:index.html"; if ( errors.hasErrors() ) { returnView = "register"; } else { User newUser = new User(); newUser.setUsername( command.getUsername() ); newUser.setPassword( passwordEncoder.encodePassword( command .getPassword(), null ) ); newUser.setEmailAddress( command.getEmailAddress() ); newUser.setFirstName( command.getFirstName() ); newUser.setLastName( command.getLastName() ); userService.registerNewUser( newUser ); } return returnView; } public Validator getValidator() { return registrationValidator; } } </code></pre> <p>but this doesn't:</p> <pre><code>package com.shaneleopard.web.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.providers.encoding.Md5PasswordEncoder; import org.springframework.stereotype.Controller; import org.springframework.validation.Errors; import org.springframework.validation.Validator; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.shaneleopard.model.User; import com.shaneleopard.service.UserService; import com.shaneleopard.validator.RegistrationValidator; import com.shaneleopard.web.command.RegisterCommand; @Controller public class RegistrationController extends ValidatingController { @Autowired private UserService userService; @Autowired private Md5PasswordEncoder passwordEncoder; @Autowired private RegistrationValidator registrationValidator; @RequestMapping( method = RequestMethod.GET, value = "/register.html" ) public void registerForm(@ModelAttribute RegisterCommand registerCommand) { // no op } @RequestMapping( method = RequestMethod.POST, value = "/register.html" ) public String registerNewUser( @ModelAttribute RegisterCommand command, Errors errors ) { String returnView = "redirect:index.html"; if ( errors.hasErrors() ) { returnView = "register"; } else { User newUser = new User(); newUser.setUsername( command.getUsername() ); newUser.setPassword( passwordEncoder.encodePassword( command .getPassword(), null ) ); newUser.setEmailAddress( command.getEmailAddress() ); newUser.setFirstName( command.getFirstName() ); newUser.setLastName( command.getLastName() ); userService.registerNewUser( newUser ); } return returnView; } public Validator getValidator() { return registrationValidator; } } </code></pre>
[ { "answer_id": 196647, "author": "Dov Wasserman", "author_id": 26010, "author_profile": "https://Stackoverflow.com/users/26010", "pm_score": 2, "selected": false, "text": "ValidatingController @Controller" }, { "answer_id": 16970812, "author": "user979051", "author_id": 979051, "author_profile": "https://Stackoverflow.com/users/979051", "pm_score": 1, "selected": false, "text": "<aop:aspectj-autoproxy proxy-target-class=\"true\"/>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/151152", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9955/" ]
151,190
<p>I encountered the following ddl in a pl/sql script this morning:</p> <p>create index genuser.idx$$_0bdd0011 ...</p> <p>My initial thought was that the index name was generated by a tool...but I'm also not a pl/sql superstar so I could very well be incorrect. Does the double dollar sign have any special significance in this statement? </p>
[ { "answer_id": 151222, "author": "Eddie Awad", "author_id": 17273, "author_profile": "https://Stackoverflow.com/users/17273", "pm_score": 2, "selected": false, "text": "SQL> create table t (col number)\n 2 /\n\nTable created.\n\nSQL> create index idx$$_0bdd0011 on t(col)\n 2 /\n\nIndex created.\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/151190", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2376109/" ]
151,195
<p>I have a bunch of tasks in a MySQL database, and one of the fields is "deadline date". Not every task has to have to a deadline date.</p> <p>I'd like to use SQL to sort the tasks by deadline date, but put the ones without a deadline date in the back of the result set. As it is now, the null dates show up first, then the rest are sorted by deadline date earliest to latest.</p> <p>Any ideas on how to do this with SQL alone? (I can do it with PHP if needed, but an SQL-only solution would be great.)</p> <p>Thanks!</p>
[ { "answer_id": 151202, "author": "Danimal", "author_id": 2757, "author_profile": "https://Stackoverflow.com/users/2757", "pm_score": 2, "selected": false, "text": "SELECT foo, bar, due_date FROM tablename\nORDER BY CASE ISNULL(due_date, 0)\nWHEN 0 THEN 1 ELSE 0 END, due_date\n" }, { "answer_id": 151203, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 5, "selected": false, "text": "SELECT * FROM myTable\nWHERE ...\nORDER BY ISNULL(myDate), myDate\n" }, { "answer_id": 151343, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 7, "selected": true, "text": "SELECT * FROM myTable\nWHERE ...\nORDER BY CASE WHEN myDate IS NULL THEN 1 ELSE 0 END, myDate;\n" }, { "answer_id": 57891284, "author": "luke", "author_id": 11204120, "author_profile": "https://Stackoverflow.com/users/11204120", "pm_score": 2, "selected": false, "text": "SELECT * FROM request ORDER BY -date DESC" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/151195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
151,199
<p>If I have two dates (ex. <code>'8/18/2008'</code> and <code>'9/26/2008'</code>), what is the best way to get the number of days between these two dates?</p>
[ { "answer_id": 151211, "author": "Dana", "author_id": 7856, "author_profile": "https://Stackoverflow.com/users/7856", "pm_score": 11, "selected": true, "text": "timedelta from datetime import date\n\nd0 = date(2008, 8, 18)\nd1 = date(2008, 9, 26)\ndelta = d1 - d0\nprint(delta.days)\n" }, { "answer_id": 151212, "author": "dguaraglia", "author_id": 2384, "author_profile": "https://Stackoverflow.com/users/2384", "pm_score": 8, "selected": false, "text": "from datetime import datetime\ndate_format = \"%m/%d/%Y\"\na = datetime.strptime('8/18/2008', date_format)\nb = datetime.strptime('9/26/2008', date_format)\ndelta = b - a\nprint delta.days # that's it\n" }, { "answer_id": 151214, "author": "Harley Holcombe", "author_id": 1057, "author_profile": "https://Stackoverflow.com/users/1057", "pm_score": 6, "selected": false, "text": ">>> import datetime\n>>> today = datetime.date.today()\n>>> someday = datetime.date(2008, 12, 25)\n>>> diff = someday - today\n>>> diff.days\n86\n" }, { "answer_id": 151215, "author": "kolrie", "author_id": 14540, "author_profile": "https://Stackoverflow.com/users/14540", "pm_score": 4, "selected": false, "text": ">>> from datetime import datetime, timedelta \n>>> datetime(2008,08,18) - datetime(2008,09,26) \ndatetime.timedelta(4) \n >>> import datetime \n>>> today = datetime.date.today() \n>>> print(today)\n2008-09-01 \n>>> last_year = datetime.date(2007, 9, 1) \n>>> print(today - last_year)\n366 days, 0:00:00 \n" }, { "answer_id": 10332036, "author": "Prasanna Ranganathan", "author_id": 1358487, "author_profile": "https://Stackoverflow.com/users/1358487", "pm_score": 4, "selected": false, "text": "from datetime import datetime\nstart_date = datetime.strptime('8/18/2008', \"%m/%d/%Y\")\nend_date = datetime.strptime('9/26/2008', \"%m/%d/%Y\")\nprint abs((end_date-start_date).days)\n" }, { "answer_id": 36650398, "author": "Parthian Shot", "author_id": 3680301, "author_profile": "https://Stackoverflow.com/users/3680301", "pm_score": 3, "selected": false, "text": "from datetime import date\ndef d(s):\n [month, day, year] = map(int, s.split('/'))\n return date(year, month, day)\ndef days(start, end):\n return (d(end) - d(start)).days\nprint days('8/18/2008', '9/26/2008')\n r'\\d+/\\d+/\\d+'" }, { "answer_id": 43923193, "author": "cimarie", "author_id": 6492656, "author_profile": "https://Stackoverflow.com/users/6492656", "pm_score": 4, "selected": false, "text": "arrow import arrow\n\na = arrow.get('2017-05-09')\nb = arrow.get('2017-05-11')\n\ndelta = (b-a)\nprint delta.days\n" }, { "answer_id": 48540389, "author": "Gavriel Cohen", "author_id": 5770004, "author_profile": "https://Stackoverflow.com/users/5770004", "pm_score": 3, "selected": false, "text": "from datetime import timedelta, datetime, date\nimport dateutil.relativedelta\n\n# current time\ndate_and_time = datetime.now()\ndate_only = date.today()\ntime_only = datetime.now().time()\n\n# calculate date and time\nresult = date_and_time - timedelta(hours=26, minutes=25, seconds=10)\n\n# calculate dates: years (-/+)\nresult = date_only - dateutil.relativedelta.relativedelta(years=10)\n\n# months\nresult = date_only - dateutil.relativedelta.relativedelta(months=10)\n\n# days\nresult = date_only - dateutil.relativedelta.relativedelta(days=10)\n\n# calculate time \nresult = date_and_time - timedelta(hours=26, minutes=25, seconds=10)\nresult.time()\n" }, { "answer_id": 48632627, "author": "Muhammad Elsayeh", "author_id": 9312964, "author_profile": "https://Stackoverflow.com/users/9312964", "pm_score": 3, "selected": false, "text": "#Calculate the Days between Two Date\n\ndaysOfMonths = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\n\ndef isLeapYear(year):\n\n # Pseudo code for this algorithm is found at\n # http://en.wikipedia.org/wiki/Leap_year#Algorithm\n ## if (year is not divisible by 4) then (it is a common Year)\n #else if (year is not divisable by 100) then (ut us a leap year)\n #else if (year is not disible by 400) then (it is a common year)\n #else(it is aleap year)\n return (year % 4 == 0 and year % 100 != 0) or year % 400 == 0\n\ndef Count_Days(year1, month1, day1):\n if month1 ==2:\n if isLeapYear(year1):\n if day1 < daysOfMonths[month1-1]+1:\n return year1, month1, day1+1\n else:\n if month1 ==12:\n return year1+1,1,1\n else:\n return year1, month1 +1 , 1\n else: \n if day1 < daysOfMonths[month1-1]:\n return year1, month1, day1+1\n else:\n if month1 ==12:\n return year1+1,1,1\n else:\n return year1, month1 +1 , 1\n else:\n if day1 < daysOfMonths[month1-1]:\n return year1, month1, day1+1\n else:\n if month1 ==12:\n return year1+1,1,1\n else:\n return year1, month1 +1 , 1\n\n\ndef daysBetweenDates(y1, m1, d1, y2, m2, d2,end_day):\n\n if y1 > y2:\n m1,m2 = m2,m1\n y1,y2 = y2,y1\n d1,d2 = d2,d1\n days=0\n while(not(m1==m2 and y1==y2 and d1==d2)):\n y1,m1,d1 = Count_Days(y1,m1,d1)\n days+=1\n if end_day:\n days+=1\n return days\n\n\n# Test Case\n\ndef test():\n test_cases = [((2012,1,1,2012,2,28,False), 58), \n ((2012,1,1,2012,3,1,False), 60),\n ((2011,6,30,2012,6,30,False), 366),\n ((2011,1,1,2012,8,8,False), 585 ),\n ((1994,5,15,2019,8,31,False), 9239),\n ((1999,3,24,2018,2,4,False), 6892),\n ((1999,6,24,2018,8,4,False),6981),\n ((1995,5,24,2018,12,15,False),8606),\n ((1994,8,24,2019,12,15,True),9245),\n ((2019,12,15,1994,8,24,True),9245),\n ((2019,5,15,1994,10,24,True),8970),\n ((1994,11,24,2019,8,15,True),9031)]\n\n for (args, answer) in test_cases:\n result = daysBetweenDates(*args)\n if result != answer:\n print \"Test with data:\", args, \"failed\"\n else:\n print \"Test case passed!\"\n\ntest()\n" }, { "answer_id": 49385575, "author": "Antoine Thiry", "author_id": 6020412, "author_profile": "https://Stackoverflow.com/users/6020412", "pm_score": 2, "selected": false, "text": "from datetime import datetime\n\nNow = datetime.now()\nStartDate = datetime.strptime(str(Now.year) +'-01-01', '%Y-%m-%d')\nNumberOfDays = (Now - StartDate)\n\nprint(NumberOfDays.days) # Starts at 0\nprint(datetime.now().timetuple().tm_yday) # Starts at 1\nprint(Now.strftime('%j')) # Starts at 1\n" }, { "answer_id": 56515237, "author": "Dmitriy Work", "author_id": 7204581, "author_profile": "https://Stackoverflow.com/users/7204581", "pm_score": 3, "selected": false, "text": "datetime.toordinal() import datetime\nprint(datetime.date(2008,9,26).toordinal() - datetime.date(2008,8,18).toordinal()) # 39\n date. date date.fromordinal(d.toordinal()) == d timedelta.days" }, { "answer_id": 58831380, "author": "Amit Gupta", "author_id": 8884381, "author_profile": "https://Stackoverflow.com/users/8884381", "pm_score": 5, "selected": false, "text": "dt = pd.to_datetime('2008/08/18', format='%Y/%m/%d')\ndt1 = pd.to_datetime('2008/09/26', format='%Y/%m/%d')\n\n(dt1-dt).days\n (dt1-dt).dt.days\n" }, { "answer_id": 63095653, "author": "Abhishek Kulkarni", "author_id": 1532338, "author_profile": "https://Stackoverflow.com/users/1532338", "pm_score": 0, "selected": false, "text": "# A date has day 'd', month 'm' and year 'y' \nclass Date:\n def __init__(self, d, m, y):\n self.d = d\n self.m = m\n self.y = y\n\n# To store number of days in all months from \n# January to Dec. \nmonthDays = [31, 28, 31, 30, 31, 30,\n 31, 31, 30, 31, 30, 31 ]\n\n# This function counts number of leap years \n# before the given date \ndef countLeapYears(d):\n\n years = d.y\n\n # Check if the current year needs to be considered \n # for the count of leap years or not \n if (d.m <= 2) :\n years-= 1\n\n # An year is a leap year if it is a multiple of 4, \n # multiple of 400 and not a multiple of 100. \n return int(years / 4 - years / 100 + years / 400 )\n\n\n# This function returns number of days between two \n# given dates \ndef getDifference(dt1, dt2) :\n\n # COUNT TOTAL NUMBER OF DAYS BEFORE FIRST DATE 'dt1' \n\n # initialize count using years and day \n n1 = dt1.y * 365 + dt1.d\n\n # Add days for months in given date \n for i in range(0, dt1.m - 1) :\n n1 += monthDays[i]\n\n # Since every leap year is of 366 days, \n # Add a day for every leap year \n n1 += countLeapYears(dt1)\n\n # SIMILARLY, COUNT TOTAL NUMBER OF DAYS BEFORE 'dt2' \n\n n2 = dt2.y * 365 + dt2.d\n for i in range(0, dt2.m - 1) :\n n2 += monthDays[i]\n n2 += countLeapYears(dt2)\n\n # return difference between two counts \n return (n2 - n1)\n\n\n# Driver program \ndt1 = Date(31, 12, 2018 )\ndt2 = Date(1, 1, 2019 )\n\nprint(getDifference(dt1, dt2), \"days\")\n" }, { "answer_id": 67474227, "author": "trincot", "author_id": 5459839, "author_profile": "https://Stackoverflow.com/users/5459839", "pm_score": 1, "selected": false, "text": "def ordinal(year, month, day):\n return ((year-1)*365 + (year-1)//4 - (year-1)//100 + (year-1)//400\n + [ 0,31,59,90,120,151,181,212,243,273,304,334][month - 1]\n + day\n + int(((year%4==0 and year%100!=0) or year%400==0) and month > 2))\n date.toordinal print(ordinal(2021, 5, 10) - ordinal(2001, 9, 11))\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/151199", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4872/" ]
151,204
<p>I have a folder, '/var/unity/conf' with some properties files in it, and I'd like the Caucho's Resin JVM to have that directory on the classpath.</p> <p>What is the best way to modifiy resin.conf so that Resin knows to add this directory to the classpath?</p>
[ { "answer_id": 1176542, "author": "Mike", "author_id": 54376, "author_profile": "https://Stackoverflow.com/users/54376", "pm_score": 2, "selected": false, "text": "<server-default>\n ...\n <jvm-classpath>/var/unity/conf/...</jvm-classpath>\n ...\n</server-default>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/151204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18320/" ]
151,210
<p>So I just interviewed two people today, and gave them "tests" to see what their skills were like. Both are entry level applicants, one of which is actually still in college. Neither applicant saw anything wrong with the following code.</p> <p>I do, obviously or I wouldn't have picked those examples. <strong>Do you think these questions are too harsh for newbie programmers?</strong></p> <p>I guess I should also note neither of them had much experience with C#... but I don't think the issues with these are language dependent. </p> <pre><code>//For the following functions, evaluate the code for quality and discuss. E.g. //E.g. could it be done more efficiently? could it cause bugs? public void Question1() { int active = 0; CheckBox chkactive = (CheckBox)item.FindControl("chkactive"); if (chkactive.Checked == true) { active = 1; } dmxdevice.Active = Convert.ToBoolean(active); } public void Question2(bool IsPostBack) { if (!IsPostBack) { BindlistviewNotification(); } if (lsvnotificationList.Items.Count == 0) { BindlistviewNotification(); } } //Question 3 protected void lsvnotificationList_ItemUpdating(object sender, ListViewUpdateEventArgs e) { ListViewDataItem item = lsvnotificationList.Items[e.ItemIndex]; string Email = ((TextBox)item.FindControl("txtEmailAddress")).Text; int id = Convert.ToInt32(((HiddenField)item.FindControl("hfID")).Value); ESLinq.ESLinqDataContext db = new ESLinq.ESLinqDataContext(); var compare = from N in db.NotificationLists where N.ID == id select N; if (compare.Count() &gt; 0) { lblmessage.Text = "Record Already Exists"; } else { ESLinq.NotificationList Notice = db.NotificationLists.Where(N =&gt; N.ID == id).Single(); Notice.EmailAddress = Email; db.SubmitChanges(); } lsvnotificationList.EditIndex = -1; BindlistviewNotification(); } </code></pre>
[ { "answer_id": 151221, "author": "jussij", "author_id": 14738, "author_profile": "https://Stackoverflow.com/users/14738", "pm_score": 0, "selected": false, "text": " boolean active = true;\n if ((!IsPostBack) || (lsvnotificationList.Items.Count == 0)) \n" }, { "answer_id": 151232, "author": "Ed S.", "author_id": 1053, "author_profile": "https://Stackoverflow.com/users/1053", "pm_score": 4, "selected": false, "text": "CheckBox chkactive = (CheckBox)item.FindControl(\"chkactive\");\ndmxdevice.Active = chkactive.Checked\n CheckBox chkactive = item.FindControl(\"chkactive\") as CheckBox;\n public void Question2(bool IsPostBack)\n{\n if (!IsPostBack || lsvnotificationList.Items.Count == 0)\n {\n BindlistviewNotification();\n }\n}\n" }, { "answer_id": 151247, "author": "Matthew Scharley", "author_id": 15537, "author_profile": "https://Stackoverflow.com/users/15537", "pm_score": -1, "selected": false, "text": "item.FindControl()" }, { "answer_id": 151278, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 3, "selected": false, "text": "public void Question1()\n{ \n CheckBox chkactive = item.FindControl(\"chkactive\") as CheckBox;\n if (chkActive != null) \n dmxdevice.Active = chkActive.Checked;\n else\n dmxdevice.Active = false;\n}\n public void Question2(bool IsPostBack)\n{\n if (!IsPostBack || lsnotificationList.Items.Count == 0)\n {\n BindlistviewNotification();\n }\n}\n" }, { "answer_id": 151340, "author": "Kyle Cronin", "author_id": 658, "author_profile": "https://Stackoverflow.com/users/658", "pm_score": 3, "selected": false, "text": "public void Question2(bool IsPostBack)\n{\n if (!IsPostBack)\n {\n foo();\n }\n\n if (lsvnotificationList.Items.Count == 0)\n {\n foo();\n }\n}\n public void Question2(bool IsPostBack)\n{\n if (!IsPostBack || lsvnotificationList.Items.Count == 0)\n {\n foo();\n }\n}\n" }, { "answer_id": 151401, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 3, "selected": false, "text": "ESLinqDataContext" }, { "answer_id": 151450, "author": "Marcel", "author_id": 131, "author_profile": "https://Stackoverflow.com/users/131", "pm_score": -1, "selected": false, "text": "public void Question2(bool IsPostBack, int listItemsCount)\n{\n if (!IsPostBack || listItemsCount == 0)\n BindlistviewNotification();\n}\n" }, { "answer_id": 151499, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 0, "selected": false, "text": "protected void lsvnotificationList_ItemUpdating(object sender, ListViewUpdateEventArgs e)\n{\n string Email = e.NewValues[\"EmailAddress\"].ToString();\n int id = Convert.ToInt32(e.NewValues[\"ID\"]);\n\n using (ESLinq.ESLinqDataContext db = new ESLinq.ESLinqDataContext(connectionString))\n {\n List<NotificationList> compare = db.NotificationLists.Where(n => n.ID = id).ToList();\n\n if (!compare.Any())\n {\n lblmessage.Text = \"Record Does Not Exist\";\n }\n else\n {\n NotificationList Notice = compare.First();\n Notice.EmailAddress = Email;\n db.SubmitChanges();\n }\n }\n lsvnotificationList.EditIndex = -1;\n BindlistviewNotification();\n\n}\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/151210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17145/" ]
151,231
<p>I need to get the actual local network IP address of the computer (e.g. 192.168.0.220) from my program using C# and .NET 3.5. I can't just use 127.0.0.1 in this case.</p> <p>How can I accomplish this?</p>
[ { "answer_id": 151237, "author": "PostMan", "author_id": 18405, "author_profile": "https://Stackoverflow.com/users/18405", "pm_score": 6, "selected": true, "text": "System.Net //To get the local IP address \nstring sHostName = Dns.GetHostName (); \nIPHostEntry ipE = Dns.GetHostByName (sHostName); \nIPAddress [] IpA = ipE.AddressList; \nfor (int i = 0; i < IpA.Length; i++) \n{ \n Console.WriteLine (\"IP Address {0}: {1} \", i, IpA[i].ToString ()); \n}\n" }, { "answer_id": 151313, "author": "GBegen", "author_id": 10223, "author_profile": "https://Stackoverflow.com/users/10223", "pm_score": 5, "selected": false, "text": "using System;\nusing System.Net;\nusing System.Net.NetworkInformation;\n\nclass Program\n{\n static void Main(string[] args)\n {\n foreach ( NetworkInterface netif in NetworkInterface.GetAllNetworkInterfaces() )\n {\n Console.WriteLine(\"Network Interface: {0}\", netif.Name);\n IPInterfaceProperties properties = netif.GetIPProperties();\n foreach ( IPAddress dns in properties.DnsAddresses )\n Console.WriteLine(\"\\tDNS: {0}\", dns);\n foreach ( IPAddressInformation anycast in properties.AnycastAddresses )\n Console.WriteLine(\"\\tAnyCast: {0}\", anycast.Address);\n foreach ( IPAddressInformation multicast in properties.MulticastAddresses )\n Console.WriteLine(\"\\tMultiCast: {0}\", multicast.Address);\n foreach ( IPAddressInformation unicast in properties.UnicastAddresses )\n Console.WriteLine(\"\\tUniCast: {0}\", unicast.Address);\n }\n }\n}\n" }, { "answer_id": 151349, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 5, "selected": false, "text": "NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();\nforeach(NetworkInterface adapter in nics)\n{\n foreach(var x in adapter.GetIPProperties().UnicastAddresses)\n {\n if (x.Address.AddressFamily == AddressFamily.InterNetwork && x.IsDnsEligible)\n {\n Console.WriteLine(\" IPAddress ........ : {0:x}\", x.Address.ToString());\n }\n }\n}\n NetworkInterface.GetAllNetworkInterfaces()\n .SelectMany(adapter=> adapter.GetIPProperties().UnicastAddresses)\n .Where(adr=>adr.Address.AddressFamily == AddressFamily.InterNetwork && adr.IsDnsEligible)\n .Select (adr => adr.Address.ToString());\n" }, { "answer_id": 19432629, "author": "Edward Brey", "author_id": 145173, "author_profile": "https://Stackoverflow.com/users/145173", "pm_score": 1, "selected": false, "text": "Dns.GetHostAddresses(Dns.GetHostName())\n .First(a => a.AddressFamily == AddressFamily.InterNetwork).ToString()\n GetHostAddresses SocketException" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/151231", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1512/" ]
151,238
<p>It seems that I've never got this to work in the past. Currently, I KNOW it doesn't work.</p> <p>But we start up our Java process:</p> <pre><code>-Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=6002 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false </code></pre> <p>I can telnet to the port, and "something is there" (that is, if I don't start the process, nothing answers, but if I do, it does), but I can not get JConsole to work filling in the IP and port.</p> <p>Seems like it should be so simple, but no errors, no noise, no nothing. Just doesn't work.</p> <p>Anyone know the hot tip for this?</p>
[ { "answer_id": 900006, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "-Djava.rmi.server.hostname='<host ip>'" }, { "answer_id": 3256207, "author": "kishore", "author_id": 392775, "author_profile": "https://Stackoverflow.com/users/392775", "pm_score": 1, "selected": false, "text": "/usr/sbin/iptables -I INPUT -s jconsole-host -p tcp --destination-port jmxremote-port -j ACCEPT\n" }, { "answer_id": 17457394, "author": "sushicutta", "author_id": 1531271, "author_profile": "https://Stackoverflow.com/users/1531271", "pm_score": 7, "selected": false, "text": "<jmx-remote-port>\n jmx-remote-port = 15666 \n -Djava.rmi.server.hostname=localhost -Dcom.sun.management.jmxremote\n-Dcom.sun.management.jmxremote.port=<jmx-remote-port>\n-Dcom.sun.management.jmxremote.ssl=false\n-Dcom.sun.management.jmxremote.authenticate=false\n-Dcom.sun.management.jmxremote.local.only=false\n-Djava.rmi.server.hostname=localhost\n java -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=15666 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.local.only=false -Djava.rmi.server.hostname=localhost ch.sushicutta.jmxremote.Main\n ps -ef | grep <java-processname>\n\nresult ---> <process-id>\n ps -ef | grep ch.sushicutta.jmxremote.Main\n\nresult ---> 24321\n netstat -lp lsof -i netstat -lp | grep <process-id>\n\ntcp 0 0 *:<jmx-remote-port> *:* LISTEN 24321/java\ntcp 0 0 *:<rmi-server-port> *:* LISTEN 24321/java\n\n\nresult ---> <rmi-server-port>\n netstat -lp | grep 24321\n\ntcp 0 0 *:15666 *:* LISTEN 24321/java\ntcp 0 0 *:37123 *:* LISTEN 24321/java\n\n\nresult ---> 37123\n Source port: <jmx-remote-port>\nDestination: localhost:<jmx-remote-port>\n[x] Local \n[x] Auto \n\nSource port: <rmi-server-port>\nDestination: localhost:<rmi-server-port>\n[x] Local \n[x] Auto\n Source port: 15666\nDestination: localhost:15666\n[x] Local \n[x] Auto \n\nSource port: 37123\nDestination: localhost:37123\n[x] Local \n[x] Auto\n Windows machine: localhost:15666 >>> SSH >>> linux machine: localhost:15666\n Windows Machine: localhost:37123 >>> SSH >>> linux machine: localhost:37123\n [x] Remote Process:\nservice:jmx:rmi:///jndi/rmi://localhost:<jndi-remote-port>/jmxrmi\n [x] Remote Process:\nservice:jmx:rmi:///jndi/rmi://localhost:15666/jmxrmi\n" }, { "answer_id": 19315119, "author": "supdog", "author_id": 2870472, "author_profile": "https://Stackoverflow.com/users/2870472", "pm_score": 3, "selected": false, "text": "<Listener className=\"org.apache.catalina.mbeans.JmxRemoteLifecycleListener\"\n rmiRegistryPortPlatform=\"10001\" rmiServerPortPlatform=\"10002\" />\n -Dcom.sun.management.jmxremote \\\n -Dcom.sun.management.jmxremote.ssl=false \\\n -Dcom.sun.management.jmxremote.authenticate=false \\\n -Djava.rmi.server.hostname=<HOSTNAME> \\\n service:jmx:rmi://<hostname>:10002/jndi/rmi://<hostname>:10001/jmxrmi\n" }, { "answer_id": 27512104, "author": "Sergio", "author_id": 1750869, "author_profile": "https://Stackoverflow.com/users/1750869", "pm_score": 4, "selected": false, "text": "To Enable Remote JMX on an Atom\n\nIf you want to monitor the status of an Atom, you need to turn on Remote JMX (Java Management Extensions) for the Atom.\n\nUse a text editor to open the <atom_installation_directory>\\bin\\atom.vmoptions file.\n\nAdd the following lines to the file:\n\n-Dcom.sun.management.jmxremote.port=5002\n-Dcom.sun.management.jmxremote.rmi.port=5002\n-Dcom.sun.management.jmxremote.authenticate=false\n-Dcom.sun.management.jmxremote.ssl=false\n -Dcom.sun.management.jmxremote.rmi.port=5002\n -Dcom.sun.management.jmxremote.port -Dcom.sun.management.jmxremote\n-Dcom.sun.management.jmxremote.authenticate=false\n-Dcom.sun.management.jmxremote.ssl=false\n-Dcom.sun.management.jmxremote.port=(jmx remote port)\n\n-Dcom.sun.management.jmxremote.local.only=false\n-Dcom.sun.management.jmxremote.rmi.port=(jmx remote port)\n-Djava.rmi.server.hostname=(CNAME|IP Address)\n" }, { "answer_id": 28167086, "author": "RichS", "author_id": 6247, "author_profile": "https://Stackoverflow.com/users/6247", "pm_score": 2, "selected": false, "text": "-Dcom.sun.management.jmxremote=true\n-Dcom.sun.management.jmxremote.port=8090\n-Dcom.sun.management.jmxremote.ssl=false\n-Dcom.sun.management.jmxremote.authenticate=false\n ssh -D 9696 user@remotemachine.com\n jconsole -J-DsocksProxyHost=localhost -J-DsocksProxyPort=9696\n" }, { "answer_id": 28441044, "author": "Mariusz", "author_id": 1291727, "author_profile": "https://Stackoverflow.com/users/1291727", "pm_score": 0, "selected": false, "text": "hostname -i\n -Dcom.sun.management.jmxremote\n-Dcom.sun.management.jmxremote.port=[jmx port]\n-Dcom.sun.management.jmxremote.local.only=false\n-Dcom.sun.management.jmxremote.authenticate=false\n-Dcom.sun.management.jmxremote.ssl=false\n-Djava.rmi.server.hostname=[server ip from step 1]\n netstat -lp | grep [pid from step 4]\n" }, { "answer_id": 30524467, "author": "smallo", "author_id": 3006519, "author_profile": "https://Stackoverflow.com/users/3006519", "pm_score": 1, "selected": false, "text": "-Djava.rmi.server.hostname=192.168.59.103 docker run ... -p 9999:9999 ..." }, { "answer_id": 30636640, "author": "arganzheng", "author_id": 2423557, "author_profile": "https://Stackoverflow.com/users/2423557", "pm_score": 3, "selected": false, "text": "com.sun.management.jmxremote.port com.sun.management.jmxremote.rmi.port export CATALINA_OPTS=\"-Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=8991 -Dcom.sun.management.jmxremote.rmi.port=8991 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false\"\n" }, { "answer_id": 32748795, "author": "Andrés S.", "author_id": 3469015, "author_profile": "https://Stackoverflow.com/users/3469015", "pm_score": 0, "selected": false, "text": "service iptables stop\n CATALINA_OPTS=\"${CATALINA_OPTS} -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=8085 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false -Djava.rmi.server.hostname=[host_ip]\"\n" }, { "answer_id": 33892861, "author": "freedev", "author_id": 336827, "author_profile": "https://Stackoverflow.com/users/336827", "pm_score": 6, "selected": false, "text": "-Dcom.sun.management.jmxremote.port=1616\n-Dcom.sun.management.jmxremote.rmi.port=1616\n-Dcom.sun.management.jmxremote.ssl=false\n-Dcom.sun.management.jmxremote.authenticate=false\n-Dcom.sun.management.jmxremote.local.only=false\n-Djava.rmi.server.hostname=localhost\n putty.exe -ssh user@remote-host -L 1616:remote-host:1616 ssh user@remote-host -L 1616:remote-host:1616 jconsole jconsole localhost:1616\n ssh -L" }, { "answer_id": 36499387, "author": "user2412906", "author_id": 2412906, "author_profile": "https://Stackoverflow.com/users/2412906", "pm_score": 3, "selected": false, "text": "-Dcom.sun.management.jmxremote.rmi.port=<same port as jmx-remote-port>\n -Dcom.sun.management.jmxremote\n-Dcom.sun.management.jmxremote.port=12345\n-Dcom.sun.management.jmxremote.rmi.port=12345\n-Dcom.sun.management.jmxremote.ssl=false\n-Dcom.sun.management.jmxremote.authenticate=false\n-Dcom.sun.management.jmxremote.local.only=false\n-Djava.rmi.server.hostname=localhost\n ssh -L 12345:localhost:12345 <username>@<host>\n ssh -L 12345:localhost:12345 <username>@<host2>\n" }, { "answer_id": 41274022, "author": "Russ Bateman", "author_id": 339736, "author_profile": "https://Stackoverflow.com/users/339736", "pm_score": 0, "selected": false, "text": "java.arg.90=-Dcom.sun.management.jmxremote=true\njava.arg.91=-Dcom.sun.management.jmxremote.port=9098\njava.arg.92=-Dcom.sun.management.jmxremote.rmi.port=9098\njava.arg.93=-Dcom.sun.management.jmxremote.authenticate=false\njava.arg.94=-Dcom.sun.management.jmxremote.ssl=false\njava.arg.95=-Dcom.sun.management.jmxremote.local.only=false\njava.arg.96=-Djava.rmi.server.hostname=10.10.10.92 (the IP address of my server running NiFi)\n 10.10.10.92 localhost\n Host: 10.10.10.92\nPort: 9098\nUser: (nothing)\nPassword: (ibid)\n service:jmx:rmi:///jndi/rmi://10.10.10.92:9098/jmxrmi\n" }, { "answer_id": 52735308, "author": "Andi M.", "author_id": 6919547, "author_profile": "https://Stackoverflow.com/users/6919547", "pm_score": 2, "selected": false, "text": "-Dcom.sun.management.jmxremote.port=2100\n-Dcom.sun.management.jmxremote.authenticate=false\n-Dcom.sun.management.jmxremote.ssl=false\n-Dcom.sun.management.jmxremote.local.only=false\n-Dcom.sun.management.jmxremote.rmi.port=2101\n-Djava.rmi.server.hostname=<IP_ADDRESS>OR<HOSTNAME>\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/151238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13663/" ]
151,250
<p>I have a setup project for my C# program, and this setup project has a Version in its properties. I'd like for the MSI file that is generated to have this Version embedded in it, so I can mouse over it in explorer and see what version the file is.</p> <p>I'm using VS2008. How can I do this?</p>
[ { "answer_id": 6750147, "author": "Clay Didier", "author_id": 852371, "author_profile": "https://Stackoverflow.com/users/852371", "pm_score": 1, "selected": false, "text": " \"Product\"\n {\n \"Name\" = \"8:Microsoft Visual Studio\"\n \"ProductName\" = \"8:tidAxCleanupScript\"\n \"ProductCode\" = \"8:{0949AAAD-2C29-415E-851C-825C74C9CA81}\"\n \"PackageCode\" = \"8:{8F012EF1-D5D0-43DC-BBFD-761A639DDB07}\"\n \"UpgradeCode\" = \"8:{38DE1949-0782-4EF3-BDC2-080EB5B73EF8}\"\n \"RestartWWWService\" = \"11:FALSE\"\n \"RemovePreviousVersions\" = \"11:TRUE\"\n \"DetectNewerInstalledVersion\" = \"11:TRUE\"\n \"InstallAllUsers\" = \"11:FALSE\"\n \"ProductVersion\" = \"8:**1.5.0**\"\n \"Manufacturer\" = \"8:**Default Company Name**\"\n \"ARPHELPTELEPHONE\" = \"8:\"\n" } ]
2008/09/29
[ "https://Stackoverflow.com/questions/151250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/369/" ]
151,268
<p>In Linux environment, when getting "glibc detected *** free(): invalid pointer" errors, how do I identify which line of code is causing it?</p> <p>Is there a way to force an abort? I recall there being an ENV var to control this?</p> <p>How to set a breakpoint in gdb for the glibc error?</p>
[ { "answer_id": 151286, "author": "Adrian", "author_id": 23624, "author_profile": "https://Stackoverflow.com/users/23624", "pm_score": 2, "selected": false, "text": "MallocErrorAbort If set, causes abort(3) to be called if an\n error was encountered in malloc(3) or\n free(3) , such as a calling free(3) on a\n pointer previously freed.\n" }, { "answer_id": 151308, "author": "mat_geek", "author_id": 11032, "author_profile": "https://Stackoverflow.com/users/11032", "pm_score": 2, "selected": false, "text": "malloc', calloc', -L/usr/lib/debug/lib -ldmallocth\n void *array[512 / sizeof(void *)]; // 100 is just an arbitrary number of backtraces, increase if you want.\nsize_t size;\n\nsize = backtrace (array, 512 / sizeof(void *));\nbacktrace_symbols_fd (array, size, fileno(mp_logfile));\n" }, { "answer_id": 151568, "author": "DGentry", "author_id": 4761, "author_profile": "https://Stackoverflow.com/users/4761", "pm_score": 4, "selected": false, "text": "MALLOC_CHECK_ abort() MALLOC_CHECK_ MALLOC_CHECK_ MALLOC_CHECK_ abort() mallopt(M_CHECK_ACTION, arg) MALLOC_CHECK_ MALLOC_CHECK_ mallopt() SIGABRT" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23630/" ]
151,272
<p>movie id tt0438097 can be found at <a href="http://www.imdb.com/title/tt0438097/" rel="noreferrer">http://www.imdb.com/title/tt0438097/</a></p> <p>What's the url for its poster image?</p>
[ { "answer_id": 151281, "author": "Vincent McNabb", "author_id": 16299, "author_profile": "https://Stackoverflow.com/users/16299", "pm_score": 3, "selected": false, "text": "img poster <a name=\"poster\" src=\"" }, { "answer_id": 5630721, "author": "Kamyar", "author_id": 337294, "author_profile": "https://Stackoverflow.com/users/337294", "pm_score": 4, "selected": false, "text": "Poster\":\"http://ia.media-imdb.com/images/M/MV5BMjAxMzY3NjcxNF5BMl5BanBnXkFtZTcwNTI5OTM0Mw@@._V1._SX320.jpg\"" }, { "answer_id": 27206829, "author": "Brad Soto", "author_id": 1009307, "author_profile": "https://Stackoverflow.com/users/1009307", "pm_score": 1, "selected": false, "text": "var system = require('system');\n\nif (system.args.length === 1) {\n console.log('Usage: moviePoster.js <movie name>');\n phantom.exit();\n}\n\nvar formattedTitle = encodeURIComponent(system.args[1]).replace(/%20/g, \"+\");\nvar page = require('webpage').create();\npage.open('http://m.imdb.com/find?q=' + formattedTitle, function() {\n var url = page.evaluate(function() {\n return 'http://www.imdb.com' + $(\".title\").first().find('a').attr('href');\n });\n page.close();\n page = require('webpage').create();\n page.open(url, function() {\n var url = page.evaluate(function() {\n return 'http://www.imdb.com' + $(\"#img_primary\").find('a').attr('href');\n });\n page.close();\n page = require('webpage').create();\n page.open(url, function() {\n var url = page.evaluate(function() {\n return $(\".photo\").first().find('img').attr('src');\n });\n console.log(url);\n page.close();\n phantom.exit();\n });\n });\n});\n for file in *.mp4; do\n title=\"${file%.mp4}\"\n if [ ! -f \"${title}.jpg\" ] \n then\n wget `phantomjs moviePoster.js \"$title\"` -O \"${title}.jpg\"\n fi\ndone\n" }, { "answer_id": 28677948, "author": "stallingOne", "author_id": 3164679, "author_profile": "https://Stackoverflow.com/users/3164679", "pm_score": 3, "selected": false, "text": "find/ https://api.themoviedb.org/3/find/tt0111161?api_key=__YOURAPIKEY__&external_source=imdb_id poster_path \"poster_path\":\"/9O7gLzmreU0nGkIB6K3BsJbzvNv.jpg\" \"http://image.tmdb.org/t/p/w150\"" }, { "answer_id": 36803347, "author": "Paul Havens", "author_id": 4387130, "author_profile": "https://Stackoverflow.com/users/4387130", "pm_score": 1, "selected": false, "text": "$Movies = Get-ChildItem -path \"Z:\\MOVIES\\COMEDY\" | Where-Object {$_.Extension -eq \".avi\" -or $_.Extension -eq \".mp4\" -or $_.Extension -eq \".mkv\" -or $_.Extension -eq<br> <br>\".flv\" -or $_.Extension -eq \".xvid\" -or $_.Extension -eq \".divx\"} | Select-Object Name, FullName | Sort Name <br>\n#Grab all the extension types and filter the ones I ONLY want <br>\n<br>\n$COMEDY = ForEach($Movie in $Movies) <br>\n{<br>\n $Title = $($Movie.Name)<br>\n #Remove the file extension<br>\n $Title = $Title.split('.')[0] <br> \n<br>\n #Changing the case to all lower <br> \n $Title = $Title.ToLower()<br>\n<br>\n #Replace a space w/ %20 for the search structure<br>\n $searchTitle = $Title.Replace(' ','%20') <br>\n<br>\n #Fetching search results<br>\n $moviesearch = Invoke-WebRequest \"http://www.imdb.com/search/title?title=$searchTitle&title_type=feature\"<br>\n <br>\n #Moving html elements into variable<br>\n $titleclassarray = $moviesearch.AllElements | where Class -eq 'title' | select -First 1<br>\n<br>\n #Checking if result contains movies<br>\n try<br><br>\n {\n $titleclass = $titleclassarray[0]<br>\n }<br>\n catch<br>\n {<br>\n Write-Warning \"No movie found matching that title http://www.imdb.com/search/title?title=$searchTitle&title_type=feature\"<br>\n } <br>\n <br>\n #Parcing HTML for movie link<br>\n $regex = \"<\\s*a\\s*[^>]*?href\\s*=\\s*[`\"']*([^`\"'>]+)[^>]*?>\"<br>\n $linksFound = [Regex]::Matches($titleclass.innerHTML, $regex, \"IgnoreCase\")<br>\n <br><br>\n\n #Fetching the first result from <br>\n $titlelink = New-Object System.Collections.ArrayList<br>\n foreach($link in $linksFound)<br>\n {<br>\n $trimmedlink = $link.Groups[1].Value.Trim()<br>\n if ($trimmedlink.Contains('/title/'))<br>\n {<br>\n [void] $titlelink.Add($trimmedlink)<br>\n }<br>\n }<br>\n #Fetching movie page<br>\n $movieURL = \"http://www.imdb.com$($titlelink[0])\"<br>\n <br>\n #Grabbing the URL for the Movie Poster<br>\n $MoviePoster = ((Invoke-WebRequest –Uri $movieURL).Images | Where-Object {$_.title -like \"$Title Poster\"} | Where src -like \"http:*\").src <br> \n<br>\n $MyVariable = \"<a href=\" + '\"' + $($Movie.FullName) + '\"' + \" \" + \"title='$Title'\" + \">\"<br>\n $ImgLocation = \"<img src=\" + '\"' + \"$MoviePoster\" + '\"' + \"width=\" + '\"' + \"225\" + '\"' + \"height=\" + '\"' + \"275\" + '\"' + \"border=\" + '\"' + \"0\" + '\"' + \"alt=\" +<br> '\"' + $Title + '\"' + \"></a>\" + \"&nbsp;\" + \"&nbsp;\" + \"&nbsp;\"+ \"&nbsp;\" + \"&nbsp;\" + \"&nbsp;\"+ \"&nbsp;\" + \"&nbsp;\" + \"&nbsp;\"<br>\n <br>\n Write-Output $MyVariable, $ImgLocation<br>\n <br>\n }$COMEDY | Out-File z:\\db\\COMEDY.htm <br>\n<br>\n $after = Get-Content z:\\db\\COMEDY.htm <br>\n<br>\n #adding a back button to the Index <br>\n $before = Get-Content z:\\db\\before.txt<br>\n<br>\n #adding the back button prior to the poster images content<br>\n Set-Content z:\\db\\COMEDY.htm –value $before, $after<br>\n" }, { "answer_id": 43197318, "author": "Ako", "author_id": 770081, "author_profile": "https://Stackoverflow.com/users/770081", "pm_score": 0, "selected": false, "text": "npm install -g phantomjs\n var system = require('system');\n\nvar page = require('webpage').create();\npage.open('http://www.imdb.com/company/co0026841/?ref_=fn_al_co_1', function() {\n console.log('Fetching movies list');\n var movies = page.evaluate(function() {\n var list = $('ol li');\n var json = []\n $.each(list, function(index, listItem) {\n var link = $(listItem).find('a');\n json.push({link: 'http://www.imdb.com' + link.attr('href')});\n });\n return json;\n });\n page.close();\n\n console.log('Found ' + movies.length + ' movies');\n\n fetchMovies(movies, 0);\n});\n\nfunction fetchMovies(movies, index) {\n if (index == movies.length) {\n console.log('Done');\n\n console.log('Generating HTML');\n genHtml(movies);\n\n phantom.exit();\n return;\n }\n var movie = movies[index];\n\n console.log('Requesting data for '+ movie.link);\n\n var page = require('webpage').create();\n page.open(movie.link, function() {\n console.log('Fetching data');\n var data = page.evaluate(function() {\n var title = $('.title_wrapper h1').text().trim();\n var summary = $('.summary_text').text().trim();\n var rating = $('.ratingValue strong').attr('title');\n var thumb = $('.poster img').attr('src');\n\n if (title == undefined || thumb == undefined) {\n return null;\n }\n return { title: title, summary: summary, rating: rating, thumb: thumb };\n });\n\n if (data != null) {\n movie.title = data.title;\n movie.summary = data.summary;\n movie.rating = data.rating;\n movie.thumb = data.thumb;\n console.log(movie.title)\n console.log('Request complete');\n } else {\n movies.slice(index, 1);\n index -= 1;\n console.log('No data found');\n }\n page.close();\n fetchMovies(movies, index + 1);\n });\n}\n\nfunction genHtml(movies) {\n var fs = require('fs');\n\n var path = 'movies.html';\n var content = Array();\n\n movies.forEach(function(movie) {\n var section = '';\n\n section += '<div>';\n section += '<h3>'+movie.title+'</h3>';\n section += '<p>'+movie.summary+'</p>';\n section += '<p>'+movie.rating+'</p>';\n section += '<img src=\"'+movie.thumb+'\">';\n section += '</div>';\n\n content.push(section);\n });\n\n var html = '<html>'+content.join('\\n')+'</html>';\n\n fs.write(path, html, 'w');\n}\n phantomjs imdb.js\n" }, { "answer_id": 44876436, "author": "Paul Havens", "author_id": 4387130, "author_profile": "https://Stackoverflow.com/users/4387130", "pm_score": 0, "selected": false, "text": "$Title = $($Movie.Name)\n\n$searchTitle = $Title.Replace(' ','%20') \n\n$moviesearch = Invoke-WebRequest \"http://www.imdb.com/search/title?title=$searchTitle&title_type=feature\"\n\n$titleclassarray = $moviesearch.AllElements | where Class -eq 'loadlate' | select -First 1\n\n$MoviePoster = $titleclassarray.loadlate\n" }, { "answer_id": 46830676, "author": "kenorb", "author_id": 55075, "author_profile": "https://Stackoverflow.com/users/55075", "pm_score": 2, "selected": false, "text": "imdb-cli omdbtool -t \"Ice Age: The Meltdown\" | wget `sed -n '/^poster/{n;p;}'`\n" }, { "answer_id": 54836944, "author": "Bissquitt", "author_id": 11104157, "author_profile": "https://Stackoverflow.com/users/11104157", "pm_score": 1, "selected": false, "text": "@ .jpg https://m.media-amazon.com/images/M/MV5BMjAwODg3OTAxMl5BMl5BanBnXkFtZTcwMjg2NjYyMw@@._V1_UX182_CR0,0,182,268_AL_.jpg\n https://m.media-amazon.com/images/M/MV5BMjAwODg3OTAxMl5BMl5BanBnXkFtZTcwMjg2NjYyMw@@.jpg\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151272", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2033811/" ]
151,291
<p>Is it possible to use system.currency. It says system.currency is inaccessible due to its protection level. what is the alternative of currency.</p>
[ { "answer_id": 151314, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 2, "selected": false, "text": "FromOACurrency() ToOACurrency() System.Decimal Currency" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14752/" ]
151,299
<p>I'd like my .exe to have access to a resource string with my svn version. I can type this in by hand, but I'd prefer an automated way to embed this at compile time. Is there any such capability in Visual Studio 2008?</p>
[ { "answer_id": 151445, "author": "antik", "author_id": 1625, "author_profile": "https://Stackoverflow.com/users/1625", "pm_score": 5, "selected": true, "text": "svnversion -n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/151299", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23071/" ]