qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
319,262
<p>Let's say I have two existing tables, "dogs" and "cats":</p> <pre><code> dog_name | owner ---------+------ Sparky | Bob Rover | Bob Snoopy | Chuck Odie | Jon cat_name | owner ---------+------ Garfield | Jon Muffy | Sam Stupid | Bob </code></pre> <p>How do I write a query with this output?</p> <pre><code> owner | num_dogs | num_cats ------+----------+--------- Bob | 2 | 1 Chuck | 1 | 0 Sam | 0 | 1 Jon | 1 | 1 </code></pre>
[ { "answer_id": 319268, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 5, "selected": true, "text": "select owner, sum(num_dogs), sum(num_cats) from\n (select owner, 1 as num_dogs, 0 as num_cats from dogs\n union\n select owner, 0 as num_dogs, 1 as num_cats from cats)\ngroup by owner\n" }, { "answer_id": 319284, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 2, "selected": false, "text": "WITH ownership AS (\n SELECT owner, COUNT(dog_name) AS num_dogs, 0 AS num_cats -- counts all non-NULL dog_name\n FROM dogs\n GROUP BY owner\n\n UNION\n\n SELECT owner, 0 AS num_dogs, COUNT(cat_name) as num_cats -- counts all non-NULL cat_name\n FROM cats\n GROUP BY owner\n)\nSELECT ownership.owner\n ,SUM(ownership.num_dogs) AS num_dogs\n ,SUM(ownership.num_cats) as num_cats\nFROM ownership\nGROUP BY ownership.owner\n" }, { "answer_id": 319355, "author": "FerranB", "author_id": 40441, "author_profile": "https://Stackoverflow.com/users/40441", "pm_score": 3, "selected": false, "text": "select owner\n , count(dog_name) dogs\n , count(cat_name) cats\n from cats FULL OUTER JOIN dogs ON (cats.owner = dogs.owner)\n" }, { "answer_id": 3886798, "author": "Mark A", "author_id": 369601, "author_profile": "https://Stackoverflow.com/users/369601", "pm_score": 1, "selected": false, "text": "-- Table variable declaration\nDECLARE @RainingCatsDogs TABLE\n(\n Owner nvarchar(255),\n num_cats int,\n num_dogs int\n)\n\n-- Populate the table variable with data from the union of the two SELECT statements\nINSERT INTO @RainingCatsDogs\n\n-- Get the count of doggies\nSELECT \n owner, COUNT(dog_name) AS num_dogs, 0 AS num_cats\nFROM \n dogs\nGROUP BY \n owner\n\n-- join the results from the two SELECT statements\nUNION\n\n-- Get the count of kittehs\nSELECT \n owner, 0 AS num_dogs, COUNT(cat_name) as num_cats\nFROM \n cats\nGROUP BY \n owner\n\n-- From the table variable, you can calculate the summed results\nSELECT\n owner,\n SUM(num_dogs),\n SUM(num_cats)\nFROM \n @RainingCatsDogs\n" }, { "answer_id": 61665689, "author": "Lukas Eder", "author_id": 521799, "author_profile": "https://Stackoverflow.com/users/521799", "pm_score": 1, "selected": false, "text": "NATURAL FULL JOIN SELECT owner, COUNT(dog_name), COUNT(cat_name)\nFROM cats \nNATURAL FULL JOIN dogs\nGROUP BY owner\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/319262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91385/" ]
319,267
<p>I can not figure out what all the parameters to the arc() function are (by experimentation) and I have not found any tutorial that seems to explain them. Where would a good explanation of the arc() function be?</p>
[ { "answer_id": 319286, "author": "strager", "author_id": 39992, "author_profile": "https://Stackoverflow.com/users/39992", "pm_score": 2, "selected": false, "text": "arc(x, y, radius, startAngle, endAngle, anticlockwise)\n" }, { "answer_id": 319432, "author": "Sparr", "author_id": 13675, "author_profile": "https://Stackoverflow.com/users/13675", "pm_score": 6, "selected": true, "text": "arc(x, y, radius, startAngle, endAngle, anticlockwise)\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/319267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10608/" ]
319,279
<p>What's the best way to validate that an IP entered by the user is valid? It comes in as a string.</p>
[ { "answer_id": 319291, "author": "chills42", "author_id": 23855, "author_profile": "https://Stackoverflow.com/users/23855", "pm_score": 3, "selected": false, "text": "def validIP(address):\n parts = address.split(\".\")\n if len(parts) != 4:\n return False\n for item in parts:\n if not 0 <= int(item) <= 255:\n return False\n return True\n" }, { "answer_id": 319293, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 6, "selected": false, "text": "def is_valid_ip(ip):\n \"\"\"Validates IP addresses.\n \"\"\"\n return is_valid_ipv4(ip) or is_valid_ipv6(ip)\n def is_valid_ipv4(ip):\n \"\"\"Validates IPv4 addresses.\n \"\"\"\n pattern = re.compile(r\"\"\"\n ^\n (?:\n # Dotted variants:\n (?:\n # Decimal 1-255 (no leading 0's)\n [3-9]\\d?|2(?:5[0-5]|[0-4]?\\d)?|1\\d{0,2}\n |\n 0x0*[0-9a-f]{1,2} # Hexadecimal 0x0 - 0xFF (possible leading 0's)\n |\n 0+[1-3]?[0-7]{0,2} # Octal 0 - 0377 (possible leading 0's)\n )\n (?: # Repeat 0-3 times, separated by a dot\n \\.\n (?:\n [3-9]\\d?|2(?:5[0-5]|[0-4]?\\d)?|1\\d{0,2}\n |\n 0x0*[0-9a-f]{1,2}\n |\n 0+[1-3]?[0-7]{0,2}\n )\n ){0,3}\n |\n 0x0*[0-9a-f]{1,8} # Hexadecimal notation, 0x0 - 0xffffffff\n |\n 0+[0-3]?[0-7]{0,10} # Octal notation, 0 - 037777777777\n |\n # Decimal notation, 1-4294967295:\n 429496729[0-5]|42949672[0-8]\\d|4294967[01]\\d\\d|429496[0-6]\\d{3}|\n 42949[0-5]\\d{4}|4294[0-8]\\d{5}|429[0-3]\\d{6}|42[0-8]\\d{7}|\n 4[01]\\d{8}|[1-3]\\d{0,9}|[4-9]\\d{0,8}\n )\n $\n \"\"\", re.VERBOSE | re.IGNORECASE)\n return pattern.match(ip) is not None\n def is_valid_ipv6(ip):\n \"\"\"Validates IPv6 addresses.\n \"\"\"\n pattern = re.compile(r\"\"\"\n ^\n \\s* # Leading whitespace\n (?!.*::.*::) # Only a single whildcard allowed\n (?:(?!:)|:(?=:)) # Colon iff it would be part of a wildcard\n (?: # Repeat 6 times:\n [0-9a-f]{0,4} # A group of at most four hexadecimal digits\n (?:(?<=::)|(?<!::):) # Colon unless preceeded by wildcard\n ){6} #\n (?: # Either\n [0-9a-f]{0,4} # Another group\n (?:(?<=::)|(?<!::):) # Colon unless preceeded by wildcard\n [0-9a-f]{0,4} # Last group\n (?: (?<=::) # Colon iff preceeded by exacly one colon\n | (?<!:) #\n | (?<=:) (?<!::) : #\n ) # OR\n | # A v4 address with NO leading zeros \n (?:25[0-4]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)\n (?: \\.\n (?:25[0-4]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)\n ){3}\n )\n \\s* # Trailing whitespace\n $\n \"\"\", re.VERBOSE | re.IGNORECASE | re.DOTALL)\n return pattern.match(ip) is not None\n (?:(?<=::)|(?<!::):) (?(?<!::):)" }, { "answer_id": 319298, "author": "Dustin", "author_id": 39975, "author_profile": "https://Stackoverflow.com/users/39975", "pm_score": 8, "selected": false, "text": "import socket\n\ntry:\n socket.inet_aton(addr)\n # legal\nexcept socket.error:\n # Not legal\n" }, { "answer_id": 330107, "author": "Samat Jain", "author_id": 14878, "author_profile": "https://Stackoverflow.com/users/14878", "pm_score": 6, "selected": false, "text": ">>> from IPy import IP\n>>> IP('127.0.0.1')\nIP('127.0.0.1')\n>>> IP('277.0.0.1')\nTraceback (most recent call last):\n ...\nValueError: '277.0.0.1': single byte must be 0 <= byte < 256\n>>> IP('foobar')\nTraceback (most recent call last):\n ...\nValueError: invalid literal for long() with base 10: 'foobar'\n >>> import ipaddress\n>>> ipaddress.ip_address('127.0.0.1')\nIPv4Address('127.0.0.1')\n>>> ipaddress.ip_address('277.0.0.1')\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"/usr/lib/python3.3/ipaddress.py\", line 54, in ip_address\n address)\nValueError: '277.0.0.1' does not appear to be an IPv4 or IPv6 address\n>>> ipaddress.ip_address('foobar')\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"/usr/lib/python3.3/ipaddress.py\", line 54, in ip_address\n address)\nValueError: 'foobar' does not appear to be an IPv4 or IPv6 address\n pip install ipaddress\n ipaddress.ip_address(u'127.0.0.1')" }, { "answer_id": 4017219, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 6, "selected": false, "text": "import socket\n\ndef is_valid_ipv4_address(address):\n try:\n socket.inet_pton(socket.AF_INET, address)\n except AttributeError: # no inet_pton here, sorry\n try:\n socket.inet_aton(address)\n except socket.error:\n return False\n return address.count('.') == 3\n except socket.error: # not a valid address\n return False\n\n return True\n\ndef is_valid_ipv6_address(address):\n try:\n socket.inet_pton(socket.AF_INET6, address)\n except socket.error: # not a valid address\n return False\n return True\n" }, { "answer_id": 10782565, "author": "Yohann", "author_id": 1158367, "author_profile": "https://Stackoverflow.com/users/1158367", "pm_score": 7, "selected": false, "text": "ipaddress #!/usr/bin/env python\n\nimport ipaddress\nimport sys\n\ntry:\n ip = ipaddress.ip_address(sys.argv[1])\n print('%s is a correct IP%s address.' % (ip, ip.version))\nexcept ValueError:\n print('address/netmask is invalid: %s' % sys.argv[1])\nexcept:\n print('Usage : %s ip' % sys.argv[0])\n pip install ipaddress\n" }, { "answer_id": 14452783, "author": "blag", "author_id": 1999151, "author_profile": "https://Stackoverflow.com/users/1999151", "pm_score": 3, "selected": false, "text": "r\"\"\"^\n \\s* # Leading whitespace\n # Zero-width lookaheads to reject too many quartets\n (?:\n # 6 quartets, ending IPv4 address; no wildcards\n (?:[0-9a-f]{1,4}(?::(?!:))){6}\n (?:25[0-4]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)\n (?:\\.(?:25[0-4]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}\n |\n # 0-5 quartets, wildcard, ending IPv4 address\n (?:(?:[0-9a-f]{1,4}(?::(?!:))){0,4}[0-9a-f]{1,4})?\n (?:::(?!:))\n (?:25[0-4]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)\n (?:\\.(?:25[0-4]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}\n |\n # 0-4 quartets, wildcard, 0-1 quartets, ending IPv4 address\n (?:(?:[0-9a-f]{1,4}(?::(?!:))){0,3}[0-9a-f]{1,4})?\n (?:::(?!:))\n (?:[0-9a-f]{1,4}(?::(?!:)))?\n (?:25[0-4]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)\n (?:\\.(?:25[0-4]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}\n |\n # 0-3 quartets, wildcard, 0-2 quartets, ending IPv4 address\n (?:(?:[0-9a-f]{1,4}(?::(?!:))){0,2}[0-9a-f]{1,4})?\n (?:::(?!:))\n (?:[0-9a-f]{1,4}(?::(?!:))){0,2}\n (?:25[0-4]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)\n (?:\\.(?:25[0-4]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}\n |\n # 0-2 quartets, wildcard, 0-3 quartets, ending IPv4 address\n (?:(?:[0-9a-f]{1,4}(?::(?!:))){0,1}[0-9a-f]{1,4})?\n (?:::(?!:))\n (?:[0-9a-f]{1,4}(?::(?!:))){0,3}\n (?:25[0-4]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)\n (?:\\.(?:25[0-4]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}\n |\n # 0-1 quartets, wildcard, 0-4 quartets, ending IPv4 address\n (?:[0-9a-f]{1,4}){0,1}\n (?:::(?!:))\n (?:[0-9a-f]{1,4}(?::(?!:))){0,4}\n (?:25[0-4]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)\n (?:\\.(?:25[0-4]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}\n |\n # wildcard, 0-5 quartets, ending IPv4 address\n (?:::(?!:))\n (?:[0-9a-f]{1,4}(?::(?!:))){0,5}\n (?:25[0-4]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)\n (?:\\.(?:25[0-4]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}\n |\n # 8 quartets; no wildcards\n (?:[0-9a-f]{1,4}(?::(?!:))){7}[0-9a-f]{1,4}\n |\n # 0-7 quartets, wildcard\n (?:(?:[0-9a-f]{1,4}(?::(?!:))){0,6}[0-9a-f]{1,4})?\n (?:::(?!:))\n |\n # 0-6 quartets, wildcard, 0-1 quartets\n (?:(?:[0-9a-f]{1,4}(?::(?!:))){0,5}[0-9a-f]{1,4})?\n (?:::(?!:))\n (?:[0-9a-f]{1,4})?\n |\n # 0-5 quartets, wildcard, 0-2 quartets\n (?:(?:[0-9a-f]{1,4}(?::(?!:))){0,4}[0-9a-f]{1,4})?\n (?:::(?!:))\n (?:(?:[0-9a-f]{1,4}(?::(?!:))){0,1}[0-9a-f]{1,4})?\n |\n # 0-4 quartets, wildcard, 0-3 quartets\n (?:(?:[0-9a-f]{1,4}(?::(?!:))){0,3}[0-9a-f]{1,4})?\n (?:::(?!:))\n (?:(?:[0-9a-f]{1,4}(?::(?!:))){0,2}[0-9a-f]{1,4})?\n |\n # 0-3 quartets, wildcard, 0-4 quartets\n (?:(?:[0-9a-f]{1,4}(?::(?!:))){0,2}[0-9a-f]{1,4})?\n (?:::(?!:))\n (?:(?:[0-9a-f]{1,4}(?::(?!:))){0,3}[0-9a-f]{1,4})?\n |\n # 0-2 quartets, wildcard, 0-5 quartets\n (?:(?:[0-9a-f]{1,4}(?::(?!:))){0,1}[0-9a-f]{1,4})?\n (?:::(?!:))\n (?:(?:[0-9a-f]{1,4}(?::(?!:))){0,4}[0-9a-f]{1,4})?\n |\n # 0-1 quartets, wildcard, 0-6 quartets\n (?:[0-9a-f]{1,4})?\n (?:::(?!:))\n (?:(?:[0-9a-f]{1,4}(?::(?!:))){0,5}[0-9a-f]{1,4})?\n |\n # wildcard, 0-7 quartets\n (?:::(?!:))\n (?:(?:[0-9a-f]{1,4}(?::(?!:))){0,6}[0-9a-f]{1,4})?\n )\n (?:/(?:1(?:2[0-7]|[01]\\d)|\\d\\d?))? # With an optional CIDR routing prefix (0-128)\n \\s* # Trailing whitespace\n $\"\"\"\n python script.py Fail=::1.2.3.4: pass=::127.0.0.1 false=::: True=::1\n python script.py\n" }, { "answer_id": 25918107, "author": "Grzegorz Luczywo", "author_id": 2184341, "author_profile": "https://Stackoverflow.com/users/2184341", "pm_score": 4, "selected": false, "text": "def is_valid_ip(ip):\n m = re.match(r\"^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$\", ip)\n return bool(m) and all(map(lambda n: 0 <= int(n) <= 255, m.groups()))\n" }, { "answer_id": 29179710, "author": "def_0101", "author_id": 4623860, "author_profile": "https://Stackoverflow.com/users/4623860", "pm_score": 2, "selected": false, "text": "def ip_checkv4(ip):\n parts=ip.split(\".\")\n if len(parts)<4 or len(parts)>4:\n return \"invalid IP length should be 4 not greater or less than 4\"\n else:\n while len(parts)== 4:\n a=int(parts[0])\n b=int(parts[1])\n c=int(parts[2])\n d=int(parts[3])\n if a<= 0 or a == 127 :\n return \"invalid IP address\"\n elif d == 0:\n return \"host id should not be 0 or less than zero \" \n elif a>=255:\n return \"should not be 255 or greater than 255 or less than 0 A\"\n elif b>=255 or b<0: \n return \"should not be 255 or greater than 255 or less than 0 B\"\n elif c>=255 or c<0:\n return \"should not be 255 or greater than 255 or less than 0 C\"\n elif d>=255 or c<0:\n return \"should not be 255 or greater than 255 or less than 0 D\"\n else:\n return \"Valid IP address \", ip\n \n p=raw_input(\"Enter IP address\")\n print ip_checkv4(p)\n" }, { "answer_id": 29748526, "author": "Rajesh", "author_id": 4432589, "author_profile": "https://Stackoverflow.com/users/4432589", "pm_score": 3, "selected": false, "text": "if re.match(r'^((\\d{1,2}|1\\d{2}|2[0-4]\\d|25[0-5])\\.){3}(\\d{1,2}|1\\d{2}|2[0-4]\\d|25[0-5])$', ip): \n print \"Valid IP\" \nelse:\n print \"Invalid IP\"\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/319279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27729/" ]
319,292
<p>I have a vector with 1000 "nodes"</p> <pre><code> if(count + 1 &gt; m_listItems.capacity()) m_listItems.reserve(count + 100); </code></pre> <p>The problem is I also clear it out when I'm about to refill it. </p> <pre><code>m_listItems.clear(); </code></pre> <p>The capacity doesn't change. I've used the resize(1); but that doesn't seem to alter the capacity. So how does one change the reserve?</p>
[ { "answer_id": 319301, "author": "Tim Stewart", "author_id": 26002, "author_profile": "https://Stackoverflow.com/users/26002", "pm_score": 1, "selected": false, "text": "std::vector< int > v;\n// ... fill v with stuff...\nstd::vector< int >().swap( v );\n" }, { "answer_id": 319302, "author": "Kasprzol", "author_id": 5957, "author_profile": "https://Stackoverflow.com/users/5957", "pm_score": 1, "selected": false, "text": "swap vector< int > tmp;\nold.swap( tmp );\n" }, { "answer_id": 319306, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 5, "selected": true, "text": "vector<Item>(m_listItems).swap(m_listItems);\n m_listItems vector<Item>().swap(m_listItems);\n" }, { "answer_id": 319341, "author": "jalf", "author_id": 33213, "author_profile": "https://Stackoverflow.com/users/33213", "pm_score": 2, "selected": false, "text": "std::vector<foo> v(1000); // Create a vector with capacity for 1000 elements\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/319292", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31325/" ]
319,294
<p>when releasing an instance that could exist or not, I usually write this:</p> <p>if (object != nil) [object release];</p> <p>but since sending a message to nil is not a problem, is that conditional necessary?</p> <p>I suppose the question comes down to this: which uses more overhead, comparing an object to nil, or sending nil a message?</p>
[ { "answer_id": 322582, "author": "Matt Gallagher", "author_id": 36103, "author_profile": "https://Stackoverflow.com/users/36103", "pm_score": 3, "selected": false, "text": "nil nil objc_msgSend nil nil release dealloc nil" }, { "answer_id": 322596, "author": "Kornel", "author_id": 27009, "author_profile": "https://Stackoverflow.com/users/27009", "pm_score": 2, "selected": false, "text": "nil [object release]; object = nil;\n nil" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/319294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36182/" ]
319,304
<p>So I added an EXE to my project's solution. The EXE does some stuff and outputs data via stdout. I want to capture the output, but more importantly how do I execute that EXE within my program?</p>
[ { "answer_id": 319311, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "Process.Start ProcessStartInfo" }, { "answer_id": 319312, "author": "Alan", "author_id": 37843, "author_profile": "https://Stackoverflow.com/users/37843", "pm_score": 4, "selected": true, "text": "Process p = new Process();\np.StartInfo.UseShellExecute = false;\np.StartInfo.RedirectStandardOutput = true;\np.StartInfo.FileName = \"myExec.exe\";\np.Start();\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/319304", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40856/" ]
319,305
<p>I love stretching my terminal on unix. What is the history or reason behind windows lame command line?</p>
[ { "answer_id": 375505, "author": "jmucchiello", "author_id": 44065, "author_profile": "https://Stackoverflow.com/users/44065", "pm_score": 7, "selected": false, "text": "mode <cols>,<lines>\nmode 80,25\nmode 120,50\netc.\n" }, { "answer_id": 1065833, "author": "Sasha Chedygov", "author_id": 104184, "author_profile": "https://Stackoverflow.com/users/104184", "pm_score": 2, "selected": false, "text": "cmd.exe" }, { "answer_id": 35302566, "author": "Mijacr", "author_id": 5874943, "author_profile": "https://Stackoverflow.com/users/5874943", "pm_score": 4, "selected": false, "text": "wmic\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/319305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4491/" ]
319,320
<p>I'm a little lost (still working with Ron Jeffries's book). Here's a simple class:</p> <pre><code>public class Model{ private String[] lines; public void myMethod(){ String[] newLines = new String[lines.length + 2]; for (i = 0, i &lt;= lines.length, i++) { newLines[i] = lines[i]; } } } </code></pre> <p>I have another class that initializes <code>Model</code>, and an empty array, by setting <code>myModel = new String[0]</code>. When I invoke <code>myModel.myMethod()</code>, I get a subscript out of range error. Looking at the debugger, what I see is that <code>myModel.lines</code> has zero dimensions and zero length. Shouldn't it have a dimension and length of 1? Granted the value of <code>lines[0]</code> is <code>null</code>, but the array itself shouldn't be, should it? </p> <p>Any thoughts truly appreciated. </p> <p>Randy</p>
[ { "answer_id": 319327, "author": "FerranB", "author_id": 40441, "author_profile": "https://Stackoverflow.com/users/40441", "pm_score": 1, "selected": false, "text": "null private String[] lines = new String[0];\n" }, { "answer_id": 319345, "author": "Paul Sonier", "author_id": 28053, "author_profile": "https://Stackoverflow.com/users/28053", "pm_score": 1, "selected": false, "text": "public class Model {\n private String []lines;\n\n public Model(String [] inLines)\n {\n lines = inLines;\n }\n}\n myStringArray = new String[0];\nmyModel = new Model(myStringArray);\n" }, { "answer_id": 319358, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 2, "selected": true, "text": "public class Model{\n private String[] lines = new string[0];\n\n public Model( string[] lines ) {\n this.lines = lines;\n }\n\n public void myMethod(){\n int len = 2;\n if (lines != null) {\n len = len + lines.length;\n }\n String[] newLines = new String[len];\n for (i = 0, i < lines.length, i++) {\n newLines[i] = lines[i];\n }\n }\n}\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319320", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16851/" ]
319,328
<p>I am asking this question from an educational/hacking point of view, (I wouldn't really want to code like this).</p> <p>Is it possible to implement a while loop only using <strong>C</strong> preprocessor directives. I understand that macros cannot be expanded recursively, so how would this be accomplished?</p>
[ { "answer_id": 8665535, "author": "Vlad", "author_id": 1120747, "author_profile": "https://Stackoverflow.com/users/1120747", "pm_score": 3, "selected": false, "text": "#ifdef pad_always\n\n#define pad(p,f) p##0\n\n#else\n\n#define pad0(p,not_used) p\n#define pad1(p,not_used) p##0\n\n#define pad(p,f) pad##f(p,)\n\n#endif\n\n// f - padding flag\n// p - prefix so far\n// a,b,c - digits\n// x - action to invoke\n\n#define n0(p,x)\n#define n1(p,x) x(p##1)\n#define n2(p,x) n1(p,x) x(p##2)\n#define n3(p,x) n2(p,x) x(p##3)\n#define n4(p,x) n3(p,x) x(p##4)\n#define n5(p,x) n4(p,x) x(p##5)\n#define n6(p,x) n5(p,x) x(p##6)\n#define n7(p,x) n6(p,x) x(p##7)\n#define n8(p,x) n7(p,x) x(p##8)\n#define n9(p,x) n8(p,x) x(p##9)\n\n#define n00(f,p,a,x) n##a(pad(p,f),x)\n#define n10(f,p,a,x) n00(f,p,9,x) x(p##10) n##a(p##1,x)\n#define n20(f,p,a,x) n10(f,p,9,x) x(p##20) n##a(p##2,x)\n#define n30(f,p,a,x) n20(f,p,9,x) x(p##30) n##a(p##3,x)\n#define n40(f,p,a,x) n30(f,p,9,x) x(p##40) n##a(p##4,x)\n#define n50(f,p,a,x) n40(f,p,9,x) x(p##50) n##a(p##5,x)\n#define n60(f,p,a,x) n50(f,p,9,x) x(p##60) n##a(p##6,x)\n#define n70(f,p,a,x) n60(f,p,9,x) x(p##70) n##a(p##7,x)\n#define n80(f,p,a,x) n70(f,p,9,x) x(p##80) n##a(p##8,x)\n#define n90(f,p,a,x) n80(f,p,9,x) x(p##90) n##a(p##9,x)\n\n#define n000(f,p,a,b,x) n##a##0(f,pad(p,f),b,x)\n#define n100(f,p,a,b,x) n000(f,p,9,9,x) x(p##100) n##a##0(1,p##1,b,x)\n#define n200(f,p,a,b,x) n100(f,p,9,9,x) x(p##200) n##a##0(1,p##2,b,x)\n#define n300(f,p,a,b,x) n200(f,p,9,9,x) x(p##300) n##a##0(1,p##3,b,x)\n#define n400(f,p,a,b,x) n300(f,p,9,9,x) x(p##400) n##a##0(1,p##4,b,x)\n#define n500(f,p,a,b,x) n400(f,p,9,9,x) x(p##500) n##a##0(1,p##5,b,x)\n#define n600(f,p,a,b,x) n500(f,p,9,9,x) x(p##600) n##a##0(1,p##6,b,x)\n#define n700(f,p,a,b,x) n600(f,p,9,9,x) x(p##700) n##a##0(1,p##7,b,x)\n#define n800(f,p,a,b,x) n700(f,p,9,9,x) x(p##800) n##a##0(1,p##8,b,x)\n#define n900(f,p,a,b,x) n800(f,p,9,9,x) x(p##900) n##a##0(1,p##9,b,x)\n\n#define n0000(f,p,a,b,c,x) n##a##00(f,pad(p,f),b,c,x)\n#define n1000(f,p,a,b,c,x) n0000(f,p,9,9,9,x) x(p##1000) n##a##00(1,p##1,b,c,x)\n#define n2000(f,p,a,b,c,x) n1000(f,p,9,9,9,x) x(p##2000) n##a##00(1,p##2,b,c,x)\n#define n3000(f,p,a,b,c,x) n2000(f,p,9,9,9,x) x(p##3000) n##a##00(1,p##3,b,c,x)\n#define n4000(f,p,a,b,c,x) n3000(f,p,9,9,9,x) x(p##4000) n##a##00(1,p##4,b,c,x)\n#define n5000(f,p,a,b,c,x) n4000(f,p,9,9,9,x) x(p##5000) n##a##00(1,p##5,b,c,x)\n#define n6000(f,p,a,b,c,x) n5000(f,p,9,9,9,x) x(p##6000) n##a##00(1,p##6,b,c,x)\n#define n7000(f,p,a,b,c,x) n6000(f,p,9,9,9,x) x(p##7000) n##a##00(1,p##7,b,c,x)\n#define n8000(f,p,a,b,c,x) n7000(f,p,9,9,9,x) x(p##8000) n##a##00(1,p##8,b,c,x)\n#define n9000(f,p,a,b,c,x) n8000(f,p,9,9,9,x) x(p##9000) n##a##00(1,p##9,b,c,x)\n\n#define n00000(f,p,a,b,c,d,x) n##a##000(f,pad(p,f),b,c,d,x)\n#define n10000(f,p,a,b,c,d,x) n00000(f,p,9,9,9,9,x) x(p##10000) n##a##000(1,p##1,b,c,d,x)\n#define n20000(f,p,a,b,c,d,x) n10000(f,p,9,9,9,9,x) x(p##20000) n##a##000(1,p##2,b,c,d,x)\n#define n30000(f,p,a,b,c,d,x) n20000(f,p,9,9,9,9,x) x(p##30000) n##a##000(1,p##3,b,c,d,x)\n#define n40000(f,p,a,b,c,d,x) n30000(f,p,9,9,9,9,x) x(p##40000) n##a##000(1,p##4,b,c,d,x)\n#define n50000(f,p,a,b,c,d,x) n40000(f,p,9,9,9,9,x) x(p##50000) n##a##000(1,p##5,b,c,d,x)\n#define n60000(f,p,a,b,c,d,x) n50000(f,p,9,9,9,9,x) x(p##60000) n##a##000(1,p##6,b,c,d,x)\n#define n70000(f,p,a,b,c,d,x) n60000(f,p,9,9,9,9,x) x(p##70000) n##a##000(1,p##7,b,c,d,x)\n#define n80000(f,p,a,b,c,d,x) n70000(f,p,9,9,9,9,x) x(p##80000) n##a##000(1,p##8,b,c,d,x)\n#define n90000(f,p,a,b,c,d,x) n80000(f,p,9,9,9,9,x) x(p##90000) n##a##000(1,p##9,b,c,d,x)\n\n#define cycle5(c1,c2,c3,c4,c5,x) n##c1##0000(0,,c2,c3,c4,c5,x)\n#define cycle4(c1,c2,c3,c4,x) n##c1##000(0,,c2,c3,c4,x)\n#define cycle3(c1,c2,c3,x) n##c1##00(0,,c2,c3,x)\n#define cycle2(c1,c2,x) n##c1##0(0,,c2,x)\n#define cycle1(c1,x) n##c1(,x)\n\n#define concat(a,b,c) a##b##c\n\n#define ck(arg) a[concat(,arg,-1)]++;\n#define SIZEOF(x) (sizeof(x) / sizeof((x)[0]))\n\nvoid check5(void)\n{\n int i, a[32769];\n\n for (i = 0; i < SIZEOF(a); i++) a[i]=0;\n\n cycle5(3,2,7,6,9,ck);\n\n for (i = 0; i < SIZEOF(a); i++) if (a[i] != 1) printf(\"5: [%d] = %d\\n\", i+1, a[i]);\n}\n" }, { "answer_id": 10542793, "author": "Paul Fultz II", "author_id": 375343, "author_profile": "https://Stackoverflow.com/users/375343", "pm_score": 7, "selected": false, "text": "#define EMPTY()\n#define DEFER(id) id EMPTY()\n#define OBSTRUCT(id) id DEFER(EMPTY)()\n#define EXPAND(...) __VA_ARGS__\n\n#define A() 123\nA() // Expands to 123\nDEFER(A)() // Expands to A () because it requires one more scan to fully expand\nEXPAND(DEFER(A)()) // Expands to 123, because the EXPAND macro forces another scan\n EVAL #define EVAL(...) EVAL1(EVAL1(EVAL1(__VA_ARGS__)))\n#define EVAL1(...) EVAL2(EVAL2(EVAL2(__VA_ARGS__)))\n#define EVAL2(...) EVAL3(EVAL3(EVAL3(__VA_ARGS__)))\n#define EVAL3(...) EVAL4(EVAL4(EVAL4(__VA_ARGS__)))\n#define EVAL4(...) EVAL5(EVAL5(EVAL5(__VA_ARGS__)))\n#define EVAL5(...) __VA_ARGS__\n #define CAT(a, ...) PRIMITIVE_CAT(a, __VA_ARGS__)\n#define PRIMITIVE_CAT(a, ...) a ## __VA_ARGS__\n\n#define CHECK_N(x, n, ...) n\n#define CHECK(...) CHECK_N(__VA_ARGS__, 0,)\n\n#define NOT(x) CHECK(PRIMITIVE_CAT(NOT_, x))\n#define NOT_0 ~, 1,\n\n#define COMPL(b) PRIMITIVE_CAT(COMPL_, b)\n#define COMPL_0 1\n#define COMPL_1 0\n\n#define BOOL(x) COMPL(NOT(x))\n\n#define IIF(c) PRIMITIVE_CAT(IIF_, c)\n#define IIF_0(t, ...) __VA_ARGS__\n#define IIF_1(t, ...) t\n\n#define IF(c) IIF(BOOL(c))\n WHILE WHILE_INDIRECT WHILE #define WHILE(pred, op, ...) \\\n IF(pred(__VA_ARGS__)) \\\n ( \\\n OBSTRUCT(WHILE_INDIRECT) () \\\n ( \\\n pred, op, op(__VA_ARGS__) \\\n ), \\\n __VA_ARGS__ \\\n )\n#define WHILE_INDIRECT() WHILE\n #define NARGS_SEQ(_1,_2,_3,_4,_5,_6,_7,_8,N,...) N\n#define NARGS(...) NARGS_SEQ(__VA_ARGS__, 8, 7, 6, 5, 4, 3, 2, 1)\n\n#define IS_1(x) CHECK(PRIMITIVE_CAT(IS_1_, x))\n#define IS_1_1 ~, 1,\n\n#define PRED(x, ...) COMPL(IS_1(NARGS(__VA_ARGS__)))\n M #define OP(x, y, ...) CAT(x, y), __VA_ARGS__ \n#define M(...) CAT(__VA_ARGS__)\n WHILE M(EVAL(WHILE(PRED, OP, x, y, z))) //Expands to xyz\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319328", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27653/" ]
319,334
<p>On Windows XP when a process crashes, we get a dialog box with a link:</p> <p>"To view technical information about the error report, click here."</p> <p>The "click here" link brings up a whole lot of information in a window, but no obvious way to save it to a file. Is there a way? It would be very nice to be able to send that data to several different external vendors we're working with.</p> <p>The only other option I see in the dialog box is to send it to Microsoft, but this crash is likely not Microsoft's fault and there is no reason to send it to them.</p>
[ { "answer_id": 8665535, "author": "Vlad", "author_id": 1120747, "author_profile": "https://Stackoverflow.com/users/1120747", "pm_score": 3, "selected": false, "text": "#ifdef pad_always\n\n#define pad(p,f) p##0\n\n#else\n\n#define pad0(p,not_used) p\n#define pad1(p,not_used) p##0\n\n#define pad(p,f) pad##f(p,)\n\n#endif\n\n// f - padding flag\n// p - prefix so far\n// a,b,c - digits\n// x - action to invoke\n\n#define n0(p,x)\n#define n1(p,x) x(p##1)\n#define n2(p,x) n1(p,x) x(p##2)\n#define n3(p,x) n2(p,x) x(p##3)\n#define n4(p,x) n3(p,x) x(p##4)\n#define n5(p,x) n4(p,x) x(p##5)\n#define n6(p,x) n5(p,x) x(p##6)\n#define n7(p,x) n6(p,x) x(p##7)\n#define n8(p,x) n7(p,x) x(p##8)\n#define n9(p,x) n8(p,x) x(p##9)\n\n#define n00(f,p,a,x) n##a(pad(p,f),x)\n#define n10(f,p,a,x) n00(f,p,9,x) x(p##10) n##a(p##1,x)\n#define n20(f,p,a,x) n10(f,p,9,x) x(p##20) n##a(p##2,x)\n#define n30(f,p,a,x) n20(f,p,9,x) x(p##30) n##a(p##3,x)\n#define n40(f,p,a,x) n30(f,p,9,x) x(p##40) n##a(p##4,x)\n#define n50(f,p,a,x) n40(f,p,9,x) x(p##50) n##a(p##5,x)\n#define n60(f,p,a,x) n50(f,p,9,x) x(p##60) n##a(p##6,x)\n#define n70(f,p,a,x) n60(f,p,9,x) x(p##70) n##a(p##7,x)\n#define n80(f,p,a,x) n70(f,p,9,x) x(p##80) n##a(p##8,x)\n#define n90(f,p,a,x) n80(f,p,9,x) x(p##90) n##a(p##9,x)\n\n#define n000(f,p,a,b,x) n##a##0(f,pad(p,f),b,x)\n#define n100(f,p,a,b,x) n000(f,p,9,9,x) x(p##100) n##a##0(1,p##1,b,x)\n#define n200(f,p,a,b,x) n100(f,p,9,9,x) x(p##200) n##a##0(1,p##2,b,x)\n#define n300(f,p,a,b,x) n200(f,p,9,9,x) x(p##300) n##a##0(1,p##3,b,x)\n#define n400(f,p,a,b,x) n300(f,p,9,9,x) x(p##400) n##a##0(1,p##4,b,x)\n#define n500(f,p,a,b,x) n400(f,p,9,9,x) x(p##500) n##a##0(1,p##5,b,x)\n#define n600(f,p,a,b,x) n500(f,p,9,9,x) x(p##600) n##a##0(1,p##6,b,x)\n#define n700(f,p,a,b,x) n600(f,p,9,9,x) x(p##700) n##a##0(1,p##7,b,x)\n#define n800(f,p,a,b,x) n700(f,p,9,9,x) x(p##800) n##a##0(1,p##8,b,x)\n#define n900(f,p,a,b,x) n800(f,p,9,9,x) x(p##900) n##a##0(1,p##9,b,x)\n\n#define n0000(f,p,a,b,c,x) n##a##00(f,pad(p,f),b,c,x)\n#define n1000(f,p,a,b,c,x) n0000(f,p,9,9,9,x) x(p##1000) n##a##00(1,p##1,b,c,x)\n#define n2000(f,p,a,b,c,x) n1000(f,p,9,9,9,x) x(p##2000) n##a##00(1,p##2,b,c,x)\n#define n3000(f,p,a,b,c,x) n2000(f,p,9,9,9,x) x(p##3000) n##a##00(1,p##3,b,c,x)\n#define n4000(f,p,a,b,c,x) n3000(f,p,9,9,9,x) x(p##4000) n##a##00(1,p##4,b,c,x)\n#define n5000(f,p,a,b,c,x) n4000(f,p,9,9,9,x) x(p##5000) n##a##00(1,p##5,b,c,x)\n#define n6000(f,p,a,b,c,x) n5000(f,p,9,9,9,x) x(p##6000) n##a##00(1,p##6,b,c,x)\n#define n7000(f,p,a,b,c,x) n6000(f,p,9,9,9,x) x(p##7000) n##a##00(1,p##7,b,c,x)\n#define n8000(f,p,a,b,c,x) n7000(f,p,9,9,9,x) x(p##8000) n##a##00(1,p##8,b,c,x)\n#define n9000(f,p,a,b,c,x) n8000(f,p,9,9,9,x) x(p##9000) n##a##00(1,p##9,b,c,x)\n\n#define n00000(f,p,a,b,c,d,x) n##a##000(f,pad(p,f),b,c,d,x)\n#define n10000(f,p,a,b,c,d,x) n00000(f,p,9,9,9,9,x) x(p##10000) n##a##000(1,p##1,b,c,d,x)\n#define n20000(f,p,a,b,c,d,x) n10000(f,p,9,9,9,9,x) x(p##20000) n##a##000(1,p##2,b,c,d,x)\n#define n30000(f,p,a,b,c,d,x) n20000(f,p,9,9,9,9,x) x(p##30000) n##a##000(1,p##3,b,c,d,x)\n#define n40000(f,p,a,b,c,d,x) n30000(f,p,9,9,9,9,x) x(p##40000) n##a##000(1,p##4,b,c,d,x)\n#define n50000(f,p,a,b,c,d,x) n40000(f,p,9,9,9,9,x) x(p##50000) n##a##000(1,p##5,b,c,d,x)\n#define n60000(f,p,a,b,c,d,x) n50000(f,p,9,9,9,9,x) x(p##60000) n##a##000(1,p##6,b,c,d,x)\n#define n70000(f,p,a,b,c,d,x) n60000(f,p,9,9,9,9,x) x(p##70000) n##a##000(1,p##7,b,c,d,x)\n#define n80000(f,p,a,b,c,d,x) n70000(f,p,9,9,9,9,x) x(p##80000) n##a##000(1,p##8,b,c,d,x)\n#define n90000(f,p,a,b,c,d,x) n80000(f,p,9,9,9,9,x) x(p##90000) n##a##000(1,p##9,b,c,d,x)\n\n#define cycle5(c1,c2,c3,c4,c5,x) n##c1##0000(0,,c2,c3,c4,c5,x)\n#define cycle4(c1,c2,c3,c4,x) n##c1##000(0,,c2,c3,c4,x)\n#define cycle3(c1,c2,c3,x) n##c1##00(0,,c2,c3,x)\n#define cycle2(c1,c2,x) n##c1##0(0,,c2,x)\n#define cycle1(c1,x) n##c1(,x)\n\n#define concat(a,b,c) a##b##c\n\n#define ck(arg) a[concat(,arg,-1)]++;\n#define SIZEOF(x) (sizeof(x) / sizeof((x)[0]))\n\nvoid check5(void)\n{\n int i, a[32769];\n\n for (i = 0; i < SIZEOF(a); i++) a[i]=0;\n\n cycle5(3,2,7,6,9,ck);\n\n for (i = 0; i < SIZEOF(a); i++) if (a[i] != 1) printf(\"5: [%d] = %d\\n\", i+1, a[i]);\n}\n" }, { "answer_id": 10542793, "author": "Paul Fultz II", "author_id": 375343, "author_profile": "https://Stackoverflow.com/users/375343", "pm_score": 7, "selected": false, "text": "#define EMPTY()\n#define DEFER(id) id EMPTY()\n#define OBSTRUCT(id) id DEFER(EMPTY)()\n#define EXPAND(...) __VA_ARGS__\n\n#define A() 123\nA() // Expands to 123\nDEFER(A)() // Expands to A () because it requires one more scan to fully expand\nEXPAND(DEFER(A)()) // Expands to 123, because the EXPAND macro forces another scan\n EVAL #define EVAL(...) EVAL1(EVAL1(EVAL1(__VA_ARGS__)))\n#define EVAL1(...) EVAL2(EVAL2(EVAL2(__VA_ARGS__)))\n#define EVAL2(...) EVAL3(EVAL3(EVAL3(__VA_ARGS__)))\n#define EVAL3(...) EVAL4(EVAL4(EVAL4(__VA_ARGS__)))\n#define EVAL4(...) EVAL5(EVAL5(EVAL5(__VA_ARGS__)))\n#define EVAL5(...) __VA_ARGS__\n #define CAT(a, ...) PRIMITIVE_CAT(a, __VA_ARGS__)\n#define PRIMITIVE_CAT(a, ...) a ## __VA_ARGS__\n\n#define CHECK_N(x, n, ...) n\n#define CHECK(...) CHECK_N(__VA_ARGS__, 0,)\n\n#define NOT(x) CHECK(PRIMITIVE_CAT(NOT_, x))\n#define NOT_0 ~, 1,\n\n#define COMPL(b) PRIMITIVE_CAT(COMPL_, b)\n#define COMPL_0 1\n#define COMPL_1 0\n\n#define BOOL(x) COMPL(NOT(x))\n\n#define IIF(c) PRIMITIVE_CAT(IIF_, c)\n#define IIF_0(t, ...) __VA_ARGS__\n#define IIF_1(t, ...) t\n\n#define IF(c) IIF(BOOL(c))\n WHILE WHILE_INDIRECT WHILE #define WHILE(pred, op, ...) \\\n IF(pred(__VA_ARGS__)) \\\n ( \\\n OBSTRUCT(WHILE_INDIRECT) () \\\n ( \\\n pred, op, op(__VA_ARGS__) \\\n ), \\\n __VA_ARGS__ \\\n )\n#define WHILE_INDIRECT() WHILE\n #define NARGS_SEQ(_1,_2,_3,_4,_5,_6,_7,_8,N,...) N\n#define NARGS(...) NARGS_SEQ(__VA_ARGS__, 8, 7, 6, 5, 4, 3, 2, 1)\n\n#define IS_1(x) CHECK(PRIMITIVE_CAT(IS_1_, x))\n#define IS_1_1 ~, 1,\n\n#define PRED(x, ...) COMPL(IS_1(NARGS(__VA_ARGS__)))\n M #define OP(x, y, ...) CAT(x, y), __VA_ARGS__ \n#define M(...) CAT(__VA_ARGS__)\n WHILE M(EVAL(WHILE(PRED, OP, x, y, z))) //Expands to xyz\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319334", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4761/" ]
319,339
<p>I can start with my own .NET dll. I have a dll I use in all my web projects (around 10) and I have util classes for FTP, zip, imageresizing, extensionmethods and a generic singleton class.</p> <p>I think it is a common practice and I just thought it would be interesting to hear what people put in their 'Utils' dlls</p> <p>EDIT: What small code gems do you have that have made you much more productive with lesser code?</p> <p>These extension methods are pretty useful for me when parsing nullable form input before putting into the database</p> <pre><code> public static int? ToInt(this string input) { int val; if (int.TryParse(input, out val)) return val; return null; } public static DateTime? ToDate(this string input) { DateTime val; if (DateTime.TryParse(input, out val)) return val; return null; } public static decimal? ToDecimal(this string input) { decimal val; if (decimal.TryParse(input, out val)) return val; return null; } </code></pre>
[ { "answer_id": 319360, "author": "bugmagnet", "author_id": 426, "author_profile": "https://Stackoverflow.com/users/426", "pm_score": 1, "selected": false, "text": "(Autogenerated by TLViewer, © Mark Pryor 2000-2003) \n\nLibrary: Std\n P:\\other\\StdLib\\StdLib.dll \n Description: Std \n\ncoclass Drives\n\nFunction DriveType(ByVal sDrv As String) As String\n\n\ncoclass Arrays\n\nFunction AAdd(aToThis ,ByVal xAddThis ) As Integer\n\nFunction AAdd_PostIncrement(a , ByVal X ) As Variant\n\nFunction AAdd_PreIncrement(a , ByVal X ) As Variant\n\nFunction AMax(aVec ) As Variant\n\nFunction AMin(aVec ) As Variant\n\nSub DeleteFirst(anArray )\n\nSub DeleteLast(anArray )\n\nSub DeleteNth(anArray , ByVal nElement As Long)\n\nFunction GenerateRange(nBot As Double, nTop As Double, [nStep As Double = 1]) As Variant\n\nFunction GenerateRangeFromString(sRange ) As Variant\n\nFunction InArray(sItem , aList ) As Boolean\n\nFunction Reverse1DArray(aInput ) As Variant\n\nFunction ShowStructure(vToShow ) As String\n\nFunction StrInArray(sItem , aList , [bCaseInsens As Boolean = True]) As String\n\n\ncoclass CmdLine\n\nProperty AppExeName([BaseOnly As Boolean = False]) As String [Get/o]\n\nProperty AppPath As String [Get/o]\n\nProperty Argument(ByVal Which As Long) As String [Get/o]\n\nProperty Arguments As Long [Get/o]\n\nProperty CaseSensitive As Boolean [Get/Let]\n\nFunction FlaggedArg(ByVal Flag As String) As String\n\nFunction FlagPresent(ByVal Flag As String) As Long\n\nFunction FlagPresentFromList(Flags () As Variant) As Boolean\n\nSub Refresh()\n\nFunction ToString() As String\n\n\ncoclass BigString\n\nSub ClearStr()\n\nFunction GetStr([ByVal vJoiner = ]) As String\n\nFunction GetStrArray() As Variant\n\nSub PutStr(ByVal vString )\n\n\ncoclass Config\n\nSub Define(sKey , sValue )\n\nProperty gsFilename As String [Get/Let]\n\nFunction List(sFilter ) As String\n\nFunction Load(sFile ) As Boolean\n\nFunction LoadW(sFile ) As Boolean\n\nFunction Recall(sKey ) As Variant\n\nFunction RecallElse(sKey , sDefault ) As Variant\n\nSub Save([sFile = ], [bAsAnsi = False])\n\nSub SaveW([sFile = ], [bAsAnsi = False])\n\n\ncoclass Collections\n\nFunction Add(vData , [sKey ]) As _Variable \n\nProperty AddOnly As Boolean [Get/Let]\n\nFunction Count() As Long\n\nFunction Exists(vntIndexKey ) As Boolean\n\nProperty Item(vntIndexKey ) As _Variable [Get/o]\n\nFunction Items() As Variant\n\nFunction Keys() As Variant\n\nSub Modify(sValue , sKey )\n\nProperty NewEnum As stdole.IUnknown [Get/o]\n\nSub Remove(vntIndexKey )\n\n\ncoclass Computers\n\nFunction ComputerName() As String\n\nFunction ExistsFolder(sComputer As String, sDir As String) As Boolean\n\nFunction GetComputers(sDomain As String)() As Variant\n\nFunction GetDomainComputers(ByVal strDomain As String)() As Variant\n\nFunction GetNBT(sComputer As String) As String\n\nFunction GetNBTA(sIPAddr As String) As String\n\nFunction GetNetView(sDomain As String) As String\n\nFunction GetOnlineComputers(sDomain As String)() As Variant\n\nFunction GetRemoteEnvironment(sComputer )() As Variant\n\nFunction GetSpecs(sComputer As String) As String\n\nFunction GetTheComputerName() As String\n\nFunction ResolveIP(sName As String) As String\n\n\ncoclass Logic\n\nFunction IIF(bCondition As Boolean, vTrue , vFalse ) As Variant\n\n\ncoclass Decimals\n\nProperty Dec As Variant [Get/Let]\n\n\ncoclass Domains\n\nFunction GetAvailableNTDomains()() As Variant\n\n\ncoclass Database\n\nSub CreateDatabase(sFile As String)\n\nSub CreateIndex(ByVal oDb As ADODB.Connection, sSpec As String)\n\nSub CreateStructure(ByVal oDb As ADODB.Connection, sSpec As String)\n\nFunction OpenDatabase(theFile As String) As ADODB._Connection \n\nFunction OpenRecordSet(ByVal oDb As ADODB.Connection, sQuery As String) As ADODB._Recordset \n\n\ncoclass DateTime\n\nFunction dbDate(vDate ) As String\n\nFunction GetGmtTime([StartingDate ]) As Date\n\nFunction GetTimeDifference() As Long\n\nFunction GetTimeHere(gmtTime As Date) As Date\n\nFunction InternetTimeToVbLocalTime(ByVal DateString As String) As Date\n\n\ncoclass Wallpaper\n\nFunction ActiveDesktopSetWallpaper(ByVal strFile As String) As Boolean\n\nSub At(ByVal nX As Integer, ByVal nY As Integer)\n\nSub AtSay(ByVal nX As Integer, ByVal nY As Integer, ByVal sText As String)\n\nSub Attributes(ByVal sAttribList As String)\n\nSub Colour(ByVal iFGColour As Long, ByVal iBGColour As Long)\n\nSub Dimensions(ByVal nHeight As Integer, ByVal nWidth As Integer)\n\nSub Font(ByVal sName As String, ByVal iSize As Integer)\n\nFunction LoadPic(sFilename As String, [nDestX As Integer = ], [nDestY As Integer = ]) As Variant\n\nProperty Picture As Object [Get/Set]\n\nSub SavePic(sFilename As String, [iType As Integer = 1])\n\nSub Say(ByVal sText As String)\n\nSub ScaleMode(ByVal iMode As Integer)\n\nFunction TextHeight(ByVal sText As String) As Integer\n\nFunction TextWidth(ByVal sText As String) As Integer\n\n\ncoclass Excel\n\nSub ExcelColumnNames(aHeadings () As Variant, [bBold As Boolean = True])\n\nSub ExcelNewSheet()\n\nSub ExcelStart([bHidden As Boolean = False])\n\n\ncoclass StopWatch\n\nSub Finish()\n\nFunction FinishTime() As Date\n\nFunction LapTime() As String\n\nFunction Seconds() As Integer\n\nSub Start()\n\nFunction StartTime() As Date\n\n\ncoclass Environments\n\nFunction GetProcessEnv(strEnvVar As String) As String\n\nFunction GetSystemEnv(strEnvVar As String) As String\n\nFunction GetUserEnv(strEnvVar As String) As String\n\nFunction GetVolatileEnv(strEnvVar As String) As String\n\n\ncoclass Schedule\n\nFunction AddTask(strTime , strCommand , [enDaysInWeek As ENUM_WEEKDAYS = ], [strDaysInMonth = ], [RunInteractive As Boolean = True], [ReOccuring As Boolean = True]) As Long\n\nFunction DeleteTask(lngID As Long) As Boolean\n\nFunction GetNameOfComputer() As String\n\n\ncoclass SymbolTable\n\nFunction Append(sName , sValue ) As String\n\nSub Clear()\n\nFunction Increment(sName ) As Integer\n\nFunction IsSym(sName ) As Boolean\n\nFunction Keys()() As Variant\n\nSub Parse(sData , sSep )\n\nFunction Recall(sName ) As Variant\n\nSub Remove(sData )\n\nSub Store(sName , vValue )\n\nSub StoreDup(sName , xValue )\n\nSub StoreDup2(sName , xValue )\n\nFunction SymList() As Variant\n\nFunction SymListText() As String\n\n\ncoclass Files\n\nFunction CollectFiles(sDirectory , sFileType ) As Variant\n\nSub DeleteFile(ByVal cFilename )\n\nFunction Exists(sFile ) As Boolean\n\nFunction FileHasBeenModified(sFile As String, dThen As Date) As Boolean\n\nFunction FileModificationDate(sFile As String) As Date\n\nFunction IsUTF16LE(sFile As String) As Boolean\n\nFunction RandomInputFile(sExt As String) As String\n\nFunction RandomOutputFile(sRandomInputFile As String, sExt As String) As String\n\nFunction ReadFileA(FileName ) As String\n\nFunction ReadFileE(FileName ) As String\n\nFunction ReadFileU(FileName ) As String\n\nFunction ReadFirstLineA(FileName ) As Variant\n\nFunction ReadFirstLineE(FileName ) As String\n\nFunction ReadFirstLineU(FileName ) As String\n\nSub WriteFileA(sFilename , sContents , nMode As Long)\n\nSub WriteFileB(sFilename , nOffset As Long, vData )\n\nSub WriteFileU(sFilename , sContents , nMode As Long)\n\n\ncoclass System\n\nFunction AvailableDesktopDimensions() As Variant\n\nFunction CaptureDOS(sCommand , [bSynch As Boolean = True]) As Variant\n\nFunction ConsoleWrite(sText As String) As Long\n\nFunction ConsoleWriteLine(sText As String) As Long\n\nFunction CreateGUID() As String\n\nFunction DesktopDimensions() As Variant\n\nFunction DoEventsSeconds(nSeconds As Integer) As Integer\n\nSub DoEventsSeconds2(iSeconds As Integer)\n\nFunction GetTheWindowsDirectory() As String\n\nFunction GetUUID(sUuid As String) As Boolean\n\nFunction KillProcess(ProcessName As String) As Boolean\n\nSub Navigate(ByVal NavTo As String)\n\nFunction SetProcessPriority(sProcess As String, nPriority As EPROCESS_PRIORITY ) As Boolean\n\nFunction ShellEx(ByVal sFile As String, [eShowCmd As EShellShowConstants = essSW_SHOWDEFAULT], [ByVal sParameters As String = ], [ByVal sDefaultDir As String = ], [sOperation As String = \"open\"], [Owner As Long = ]) As Boolean\n\nSub Sleep(nMilli As Integer)\n\nFunction SystemDefaultUILanguage() As Long\n\nFunction ThreadLocale() As Long\n\n\ncoclass Groups\n\nFunction GetComputerGroups(ByVal strComputerName As String)() As Variant\n\nFunction GetDefaultNamingContext() As String\n\nFunction GetGroups()() As Variant\n\n\ncoclass Help\n\nFunction HHDisplayHeadTopic(ByVal lHwnd As Long) As Long\n\nFunction HHDisplaySearch(ByVal lHwnd As Long, [toSearch As String = ]) As Long\n\nFunction HHHelpContents(ByVal lHwnd As Long) As Long\n\nFunction HHHelpIndex(ByVal lHwnd As Long, [toSearch As String = ]) As Long\n\nSub HHInitialize()\n\nFunction HHKeywordLookup(ByVal lHwnd As Long, [sKeyword As String = ]) As Long\n\nSub HHUninitialize()\n\nProperty sHelpFile As String [Get/Let]\n\n\ncoclass Number\n\nFunction IntegerToUnsigned(Value As Integer) As Long\n\nFunction LongToUnsigned(Value As Long) As Double\n\nFunction UnsignedToInteger(Value As Long) As Integer\n\nFunction UnsignedToLong(Value As Double) As Long\n\n\ncoclass IEDisplay\n\nSub Display(sMsg As String, nMillisec As Integer)\n\nSub Init(sPosition )\n\nProperty sName As String [Get/Let]\n\n\ncoclass Temp\n\nFunction GetTempFileName([sSeed As String = ]) As String\n\nFunction LocGetFilePath(ByVal iCFName As String) As String\n\nFunction TempDir() As String\n\nFunction TempDirWide() As String\n\nFunction TempFile(Create As Boolean, [lpPrefixString ], [lpszPath ]) As String\n\nFunction UnicodeTempFile(ByVal iFileName As String) As String\n\n\ncoclass INI\n\nSub Clear()\n\nFunction GetValue(sSection As String, sKey As String, strDefault As String) As String\n\nFunction HasSection(sSection As String) As Boolean\n\nFunction Load(sIniName As String) As Boolean\n\nFunction ReadINIA(sSection , sKeyName , sINIFileName ) As String\n\nFunction ReadINIU(sSection As String, sKeyName As String, sINIFileName As String) As String\n\nFunction WriteINIA(sSection , sKeyName , sNewString , sINIFileName ) As Boolean\n\nFunction WriteINIU(sSection As String, sKeyName As String, sNewString As String, sINIFileName As String) As Boolean\n\n\ncoclass Variable\n\nProperty Name As Variant [Get/Let/Set]\n\nProperty Value As Variant [Get/Let/Set]\n\n\ncoclass Mouse\n\nFunction Between(ByVal nNumber As Integer, ByVal nLowerBound As Integer, ByVal nUpperBound As Integer) As Boolean\n\nFunction MouseX([ByVal hWnd As Long = ]) As Long\n\nFunction MouseY([ByVal hWnd As Long = ]) As Long\n\n\ncoclass Traces\n\nSub ClearTrace()\n\nSub Trace([ByVal sTag = \"!@#$%^&*()_\"])\n\nProperty TraceFile As String [Get/Let]\n\nProperty Tracing As Boolean [Get/Let]\n\n\ncoclass Registry\n\nProperty ClassKey As ERegistryClassConstants [Get/Let]\n\nSub CreateAdditionalEXEAssociations(ByVal sClassName As String, vItems () As Variant)\n\nSub CreateEXEAssociation(ByVal sExePath As String, ByVal sClassName As String, ByVal sClassDescription As String, ByVal sAssociation As String, [ByVal sOpenMenuText As String = \"&Open\"], [ByVal bSupportPrint As Boolean = False], [ByVal sPrintMenuText As String = \"&Print\"], [ByVal bSupportNew As Boolean = False], [ByVal sNewMenuText As String = \"&New\"], [ByVal bSupportInstall As Boolean = False], [ByVal sInstallMenuText As String = ], [ByVal lDefaultIconIndex As Long = -1])\n\nFunction CreateKey() As Boolean\n\nProperty Default As Variant [Get/Let]\n\nFunction DeleteKey() As Boolean\n\nFunction DeleteValue() As Boolean\n\nFunction EnumerateSections(sSect () As String, iSectCount As Long) As Boolean\n\nFunction EnumerateValues(sKeyNames () As String, iKeyCount As Long) As Boolean\n\nProperty KeyExists As Boolean [Get/o]\n\nProperty Machine As String [Get/Let]\n\nProperty SectionKey As String [Get/Let]\n\nProperty Value As Variant [Get/Let]\n\nProperty ValueEx(ClassKey As ERegistryClassConstants , SectionKey As String, ValueKey As String, ValueType As ERegistryValueTypes , Default ) As Variant [Get/Let]\n\nProperty ValueKey As String [Get/Let]\n\nProperty ValueType As ERegistryValueTypes [Get/Let]\n\n\ncoclass Users\n\nFunction GetComputerUsers(ByVal strComputerName As String)() As Variant\n\nFunction GetComputerUsers2(ByVal strComputerName )() As Variant\n\nFunction GetDomainUser(sComputer As String) As String\n\nFunction GetLoginProfiles(sComputer )() As Variant\n\nFunction GetMac(sDevice ) As String\n\nFunction GetNameAndDescription(spDomain As String, sUsername As String) As String\n\nFunction GetOUofUser(sDomain As String, sUsername As String) As String\n\n\ncoclass Sort\n\nSub heapsort(aVec )\n\nSub quicksort(aVec )\n\nSub shellsort(a0 , [bAscending As Boolean = True])\n\nSub shellSortOnField(aVec , ByVal nField As Integer, ByVal sFieldSep , [nComparisonType As SSOF_COMPARISON = SSOF_NUMERICAL])\n\nFunction sorted()() As Variant\n\n\ncoclass Strings\n\nFunction AnyOf(sText , nOperator As AO_COMPARATORS , sChar ) As Boolean\n\nFunction AnyOfList(sText , nOperator As AO_COMPARATORS , aChar ) As Boolean\n\nFunction AsString(X ) As String\n\nFunction BeginsWith(sText , sBeginning , [bCaseInsensitive As Boolean = True]) As Boolean\n\nFunction Between(sText , sBegin , sEnd ) As String\n\nFunction ByteArrayToString(aBytes () As Byte) As String\n\nFunction ComprehendCSV(sText ) As Variant\n\nFunction Contains(sText , sChunk , [bCaseInsensitive As Boolean = True]) As Boolean\n\nFunction CountFields(strText , strDelim ) As Integer\n\nFunction DQ(s ) As String\n\nFunction EndsWith(sText , sEnding , [bCaseInsensitive As Boolean = True]) As Boolean\n\nFunction EndsWithSet(sText , vEnding , [bCaseInsensitive As Boolean = True]) As Boolean\n\nFunction FirstLineOf(sData ) As String\n\nFunction FirstWord(sText ) As String\n\nFunction ForceExtension(sFilename , sExtension ) As String\n\nFunction HexDump(sData ) As String\n\nFunction HTMLWrap(sTag , sContent ) As String\n\nFunction LastLineOf(sData ) As String\n\nFunction LeftFill(sText , nLen , sFill ) As String\n\nFunction LeftOf(sText , sItem ) As String\n\nFunction LeftOfLast(sText , sItem ) As String\n\nFunction NthField(sText , sDelimiter , nReqdField ) As String\n\nFunction NthLineOf(n As Integer, sData ) As String\n\nFunction RemoveSpaces(sText ) As String\n\nFunction Reverse(sText ) As String\n\nFunction RightFill(sText , nLen , sFill ) As String\n\nFunction RightOf(sText , sItem ) As String\n\nFunction RightOfLast(sText , sItem ) As String\n\nFunction SplitSet(ByVal sString , ByVal sSet ) As Variant\n\nFunction StringConversion(s , n As Integer) As String\n\nFunction StringMap(sText , aFrom , vTo ) As String\n\nFunction StringToByteArray(ByVal sString )() As Byte\n\nFunction Subst(sText , paArgList () As Variant) As String\n\nFunction Subst2(sText , paArgList () As Variant) As String\n\nFunction ZeroFill(nNum , nWidth ) As String\n\nFunction Zerofill2(nNum ) As String\n" }, { "answer_id": 320040, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 0, "selected": false, "text": "namespace madrat.Common {\n public interface ICopyable<T> {\n T Copy();\n }\n}\n System.ICloneable" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29519/" ]
319,343
<p>Here's a question for those of you with experience in larger projects and API/framework design.</p> <p>I am working on a framework that will be used by many other projects in the future, so I want to make it nice and extensible, but at the same time it needs to be simple and easy to understand.</p> <p>I know that a lot of people complain that the .NET framework contains too many sealed classes and private members. Should I avoid this criticism and open up all my classes with plenty of protected virtual members?</p> <p>Is it a good idea to make as many of my methods and properties <strong>protected virtual</strong> as possible? Under what situations would you avoid <strong>protected virtual</strong> and make members private.</p>
[ { "answer_id": 319361, "author": "FerranB", "author_id": 40441, "author_profile": "https://Stackoverflow.com/users/40441", "pm_score": 2, "selected": false, "text": "events protected protected" }, { "answer_id": 320181, "author": "Brian Rasmussen", "author_id": 38206, "author_profile": "https://Stackoverflow.com/users/38206", "pm_score": 3, "selected": false, "text": "sealed sealed" }, { "answer_id": 320239, "author": "Zooba", "author_id": 891, "author_profile": "https://Stackoverflow.com/users/891", "pm_score": 1, "selected": false, "text": "protected private protected virtual virtual" }, { "answer_id": 31907748, "author": "Lightman", "author_id": 2444725, "author_profile": "https://Stackoverflow.com/users/2444725", "pm_score": 0, "selected": false, "text": "protected virtual" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319343", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21966/" ]
319,354
<p>I have a SQL Server database and I want to know what columns and types it has. I'd prefer to do this through a query rather than using a GUI like Enterprise Manager. Is there a way to do this?</p>
[ { "answer_id": 319366, "author": "Brannon", "author_id": 5745, "author_profile": "https://Stackoverflow.com/users/5745", "pm_score": 7, "selected": false, "text": "EXEC sp_help tablename\n INFORMATION_SCHEMA" }, { "answer_id": 319368, "author": "Vincent Ramdhanie", "author_id": 27439, "author_profile": "https://Stackoverflow.com/users/27439", "pm_score": 9, "selected": false, "text": "exec sp_columns MyTable\n" }, { "answer_id": 319424, "author": "Salamander2007", "author_id": 10629, "author_profile": "https://Stackoverflow.com/users/10629", "pm_score": 6, "selected": false, "text": "select * \n from information_schema.columns \n where table_name = 'aspnet_Membership'\n order by ordinal_position\n" }, { "answer_id": 14505337, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "Select SC.name AS 'Field', ISC.DATA_TYPE AS 'Type', ISC.CHARACTER_MAXIMUM_LENGTH AS 'Length', SC.IS_NULLABLE AS 'Null', I.is_primary_key AS 'Key', SC.is_identity AS 'Identity'\nFrom sys.columns AS SC \nLEFT JOIN sys.index_columns AS IC\nON IC.object_id = OBJECT_ID('dbo.Expenses') AND \nIC.column_id = SC.column_id\nLEFT JOIN sys.indexes AS I \nON I.object_id = OBJECT_ID('dbo.Expenses') AND \nIC.index_id = I.index_id\nLEFT JOIN information_schema.columns ISC\nON ISC.TABLE_NAME = 'Expenses'\nAND ISC.COLUMN_NAME = SC.name\nWHERE SC.object_id = OBJECT_ID('dbo.Expenses')\n" }, { "answer_id": 14565143, "author": "Zsolt Hidasi", "author_id": 1128025, "author_profile": "https://Stackoverflow.com/users/1128025", "pm_score": 3, "selected": false, "text": "USE YourDB\nGO\n\nDECLARE @objectName NVARCHAR(128) = 'YourTable';\n\nSELECT\n a.[NAME]\n ,a.[TYPE]\n ,a.[CHARSET]\n ,a.[COLLATION]\n ,a.[NULLABLE]\n ,a.[DEFAULT]\n ,b.[COMMENTS]\n-- ,a.[ORDINAL_POSITION]\nFROM\n (\n SELECT\n COLUMN_NAME AS [NAME]\n ,CASE DATA_TYPE\n WHEN 'char' THEN DATA_TYPE + '(' + CAST(CHARACTER_MAXIMUM_LENGTH AS VARCHAR) + ')'\n WHEN 'numeric' THEN DATA_TYPE + '(' + CAST(NUMERIC_PRECISION AS VARCHAR) + ', ' + CAST(NUMERIC_SCALE AS VARCHAR) + ')'\n WHEN 'nvarchar' THEN DATA_TYPE + '(' + CAST(CHARACTER_MAXIMUM_LENGTH AS VARCHAR) + ')'\n WHEN 'varbinary' THEN DATA_TYPE + '(' + CAST(CHARACTER_MAXIMUM_LENGTH AS VARCHAR) + ')'\n WHEN 'varchar' THEN DATA_TYPE + '(' + CAST(CHARACTER_MAXIMUM_LENGTH AS VARCHAR) + ')'\n ELSE DATA_TYPE\n END AS [TYPE]\n ,CHARACTER_SET_NAME AS [CHARSET]\n ,COLLATION_NAME AS [COLLATION]\n ,IS_NULLABLE AS [NULLABLE]\n ,COLUMN_DEFAULT AS [DEFAULT]\n ,ORDINAL_POSITION\n FROM \n INFORMATION_SCHEMA.COLUMNS\n WHERE\n TABLE_NAME = @objectName\n ) a\n FULL JOIN\n (\n SELECT\n CAST(value AS NVARCHAR) AS [COMMENTS]\n ,CAST(objname AS NVARCHAR) AS [NAME]\n FROM\n ::fn_listextendedproperty ('MS_Description', 'user', 'dbo', 'table', @objectName, 'column', default)\n ) b\n ON a.NAME COLLATE YourCollation = b.NAME COLLATE YourCollation\nORDER BY\n a.[ORDINAL_POSITION];\n USE master;\nGO\n\nIF OBJECT_ID('sp_desc', 'P') IS NOT NULL\n DROP PROCEDURE sp_desc\nGO\n\nCREATE PROCEDURE sp_desc (\n @tableName nvarchar(128)\n) AS\nBEGIN\n DECLARE @dbName sysname;\n DECLARE @schemaName sysname;\n DECLARE @objectName sysname;\n DECLARE @objectID int;\n DECLARE @tmpTableName varchar(100);\n DECLARE @sqlCmd nvarchar(4000);\n\n SELECT @dbName = PARSENAME(@tableName, 3);\n IF @dbName IS NULL SELECT @dbName = DB_NAME();\n\n SELECT @schemaName = PARSENAME(@tableName, 2);\n IF @schemaName IS NULL SELECT @schemaName = SCHEMA_NAME();\n\n SELECT @objectName = PARSENAME(@tableName, 1);\n IF @objectName IS NULL\n BEGIN\n PRINT 'Object is missing from your function call!';\n RETURN;\n END;\n\n SELECT @objectID = OBJECT_ID(@dbName + '.' + @schemaName + '.' + @objectName);\n IF @objectID IS NULL\n BEGIN\n PRINT 'Object [' + @dbName + '].[' + @schemaName + '].[' + @objectName + '] does not exist!';\n RETURN;\n END;\n\n SELECT @tmpTableName = '#tmp_DESC_' + CAST(@@SPID AS VARCHAR) + REPLACE(REPLACE(REPLACE(REPLACE(CAST(CONVERT(CHAR, GETDATE(), 121) AS VARCHAR), '-', ''), ' ', ''), ':', ''), '.', '');\n --PRINT @tmpTableName;\n SET @sqlCmd = '\n USE ' + @dbName + '\n CREATE TABLE ' + @tmpTableName + ' (\n [NAME] nvarchar(128) NOT NULL\n ,[TYPE] varchar(50)\n ,[CHARSET] varchar(50)\n ,[COLLATION] varchar(50)\n ,[NULLABLE] varchar(3)\n ,[DEFAULT] nvarchar(4000)\n ,[COMMENTS] nvarchar(3750));\n\n INSERT INTO ' + @tmpTableName + '\n SELECT\n a.[NAME]\n ,a.[TYPE]\n ,a.[CHARSET]\n ,a.[COLLATION]\n ,a.[NULLABLE]\n ,a.[DEFAULT]\n ,b.[COMMENTS]\n FROM\n (\n SELECT\n COLUMN_NAME AS [NAME]\n ,CASE DATA_TYPE\n WHEN ''char'' THEN DATA_TYPE + ''('' + CAST(CHARACTER_MAXIMUM_LENGTH AS VARCHAR) + '')''\n WHEN ''numeric'' THEN DATA_TYPE + ''('' + CAST(NUMERIC_PRECISION AS VARCHAR) + '', '' + CAST(NUMERIC_SCALE AS VARCHAR) + '')''\n WHEN ''nvarchar'' THEN DATA_TYPE + ''('' + CAST(CHARACTER_MAXIMUM_LENGTH AS VARCHAR) + '')''\n WHEN ''varbinary'' THEN DATA_TYPE + ''('' + CAST(CHARACTER_MAXIMUM_LENGTH AS VARCHAR) + '')''\n WHEN ''varchar'' THEN DATA_TYPE + ''('' + CAST(CHARACTER_MAXIMUM_LENGTH AS VARCHAR) + '')''\n ELSE DATA_TYPE\n END AS [TYPE]\n ,CHARACTER_SET_NAME AS [CHARSET]\n ,COLLATION_NAME AS [COLLATION]\n ,IS_NULLABLE AS [NULLABLE]\n ,COLUMN_DEFAULT AS [DEFAULT]\n ,ORDINAL_POSITION\n FROM \n INFORMATION_SCHEMA.COLUMNS\n WHERE \n TABLE_NAME = ''' + @objectName + '''\n ) a\n FULL JOIN\n (\n SELECT\n CAST(value AS NVARCHAR) AS [COMMENTS]\n ,CAST(objname AS NVARCHAR) AS [NAME]\n FROM\n ::fn_listextendedproperty (''MS_Description'', ''user'', ''' + @schemaName + ''', ''table'', ''' + @objectName + ''', ''column'', default)\n ) b\n ON a.NAME COLLATE Hungarian_CI_AS = b.NAME COLLATE Hungarian_CI_AS\n ORDER BY\n a.[ORDINAL_POSITION];\n\n SELECT * FROM ' + @tmpTableName + ';'\n\n --PRINT @sqlCmd;\n\n EXEC sp_executesql @sqlCmd;\n RETURN;\nEND;\nGO\n\nEXEC sys.sp_MS_marksystemobject sp_desc\nGO\n EXEC sp_desc 'YourDB.YourSchema.YourTable';\n EXEC sp_desc 'YourTable';\n sp_desc 'YourTable';\n" }, { "answer_id": 21045353, "author": "sukhi", "author_id": 3181932, "author_profile": "https://Stackoverflow.com/users/3181932", "pm_score": 5, "selected": false, "text": "Select * From INFORMATION_SCHEMA.COLUMNS Where TABLE_NAME = 'TABLENAME'\n" }, { "answer_id": 25681551, "author": "Viranja kaushalya", "author_id": 3686796, "author_profile": "https://Stackoverflow.com/users/3686796", "pm_score": 6, "selected": false, "text": "sp_help tablename sp_help Customer Select" }, { "answer_id": 32839841, "author": "Simon Hughes", "author_id": 5884, "author_profile": "https://Stackoverflow.com/users/5884", "pm_score": 2, "selected": false, "text": "EntityFramework Reverse POCO Generator SELECT c.TABLE_SCHEMA AS SchemaName,\n c.TABLE_NAME AS TableName,\n t.TABLE_TYPE AS TableType,\n c.ORDINAL_POSITION AS Ordinal,\n c.COLUMN_NAME AS ColumnName,\n CAST(CASE WHEN IS_NULLABLE = 'YES' THEN 1\n ELSE 0\n END AS BIT) AS IsNullable,\n DATA_TYPE AS TypeName,\n ISNULL(CHARACTER_MAXIMUM_LENGTH, 0) AS [MaxLength],\n CAST(ISNULL(NUMERIC_PRECISION, 0) AS INT) AS [Precision],\n ISNULL(COLUMN_DEFAULT, '') AS [Default],\n CAST(ISNULL(DATETIME_PRECISION, 0) AS INT) AS DateTimePrecision,\n ISNULL(NUMERIC_SCALE, 0) AS Scale,\n CAST(COLUMNPROPERTY(OBJECT_ID(QUOTENAME(c.TABLE_SCHEMA) + '.' + QUOTENAME(c.TABLE_NAME)), c.COLUMN_NAME, 'IsIdentity') AS BIT) AS IsIdentity,\n CAST(CASE WHEN COLUMNPROPERTY(OBJECT_ID(QUOTENAME(c.TABLE_SCHEMA) + '.' + QUOTENAME(c.TABLE_NAME)), c.COLUMN_NAME, 'IsIdentity') = 1 THEN 1\n WHEN COLUMNPROPERTY(OBJECT_ID(QUOTENAME(c.TABLE_SCHEMA) + '.' + QUOTENAME(c.TABLE_NAME)), c.COLUMN_NAME, 'IsComputed') = 1 THEN 1\n WHEN DATA_TYPE = 'TIMESTAMP' THEN 1\n ELSE 0\n END AS BIT) AS IsStoreGenerated,\n CAST(CASE WHEN pk.ORDINAL_POSITION IS NULL THEN 0\n ELSE 1\n END AS BIT) AS PrimaryKey,\n ISNULL(pk.ORDINAL_POSITION, 0) PrimaryKeyOrdinal,\n CAST(CASE WHEN fk.COLUMN_NAME IS NULL THEN 0\n ELSE 1\n END AS BIT) AS IsForeignKey\nFROM INFORMATION_SCHEMA.COLUMNS c\n LEFT OUTER JOIN (SELECT u.TABLE_SCHEMA,\n u.TABLE_NAME,\n u.COLUMN_NAME,\n u.ORDINAL_POSITION\n FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE u\n INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc\n ON u.TABLE_SCHEMA = tc.CONSTRAINT_SCHEMA\n AND u.TABLE_NAME = tc.TABLE_NAME\n AND u.CONSTRAINT_NAME = tc.CONSTRAINT_NAME\n WHERE CONSTRAINT_TYPE = 'PRIMARY KEY') pk\n ON c.TABLE_SCHEMA = pk.TABLE_SCHEMA\n AND c.TABLE_NAME = pk.TABLE_NAME\n AND c.COLUMN_NAME = pk.COLUMN_NAME\n LEFT OUTER JOIN (SELECT DISTINCT\n u.TABLE_SCHEMA,\n u.TABLE_NAME,\n u.COLUMN_NAME\n FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE u\n INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc\n ON u.TABLE_SCHEMA = tc.CONSTRAINT_SCHEMA\n AND u.TABLE_NAME = tc.TABLE_NAME\n AND u.CONSTRAINT_NAME = tc.CONSTRAINT_NAME\n WHERE CONSTRAINT_TYPE = 'FOREIGN KEY') fk\n ON c.TABLE_SCHEMA = fk.TABLE_SCHEMA\n AND c.TABLE_NAME = fk.TABLE_NAME\n AND c.COLUMN_NAME = fk.COLUMN_NAME\n INNER JOIN INFORMATION_SCHEMA.TABLES t\n ON c.TABLE_SCHEMA = t.TABLE_SCHEMA\n AND c.TABLE_NAME = t.TABLE_NAME\nWHERE c.TABLE_NAME NOT IN ('EdmMetadata', '__MigrationHistory')\n SELECT FK.name AS FK_Table,\n FkCol.name AS FK_Column,\n PK.name AS PK_Table,\n PkCol.name AS PK_Column,\n OBJECT_NAME(f.object_id) AS Constraint_Name,\n SCHEMA_NAME(FK.schema_id) AS fkSchema,\n SCHEMA_NAME(PK.schema_id) AS pkSchema,\n PkCol.name AS primarykey,\n k.constraint_column_id AS ORDINAL_POSITION\nFROM sys.objects AS PK\n INNER JOIN sys.foreign_keys AS f\n INNER JOIN sys.foreign_key_columns AS k\n ON k.constraint_object_id = f.object_id\n INNER JOIN sys.indexes AS i\n ON f.referenced_object_id = i.object_id\n AND f.key_index_id = i.index_id\n ON PK.object_id = f.referenced_object_id\n INNER JOIN sys.objects AS FK\n ON f.parent_object_id = FK.object_id\n INNER JOIN sys.columns AS PkCol\n ON f.referenced_object_id = PkCol.object_id\n AND k.referenced_column_id = PkCol.column_id\n INNER JOIN sys.columns AS FkCol\n ON f.parent_object_id = FkCol.object_id\n AND k.parent_column_id = FkCol.column_id\nORDER BY FK_Table, FK_Column\n SELECT s.name AS [schema],\n t.name AS [table],\n c.name AS [column],\n value AS [property]\nFROM sys.extended_properties AS ep\n INNER JOIN sys.tables AS t\n ON ep.major_id = t.object_id\n INNER JOIN sys.schemas AS s\n ON s.schema_id = t.schema_id\n INNER JOIN sys.columns AS c\n ON ep.major_id = c.object_id\n AND ep.minor_id = c.column_id\nWHERE class = 1\nORDER BY t.name\n" }, { "answer_id": 34043991, "author": "Brian Somerfield", "author_id": 5630510, "author_profile": "https://Stackoverflow.com/users/5630510", "pm_score": 0, "selected": false, "text": "CREATE PROCEDURE [dbo].[describe] \n( \n@SearchStr nvarchar(max) \n) \nAS \nBEGIN \nSELECT \n CONCAT([COLUMN_NAME],' ',[DATA_TYPE],' ',[CHARACTER_MAXIMUM_LENGTH],' ', \n (SELECT CASE [IS_NULLABLE] WHEN 'NO' THEN 'NOT NULL' ELSE 'NULL' END),\n (SELECT CASE WHEN [COLUMN_DEFAULT] IS NULL THEN '' ELSE CONCAT(' DEFAULT ',[COLUMN_DEFAULT]) END)\n ) AS DESCRIPTION\n FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME LIKE @SearchStr\nEND \n" }, { "answer_id": 37665640, "author": "Abhijeet", "author_id": 2012163, "author_profile": "https://Stackoverflow.com/users/2012163", "pm_score": 4, "selected": false, "text": "select * FROM INFORMATION_SCHEMA.Columns where table_name = 'tablename';\n" }, { "answer_id": 40535762, "author": "kingfrito_5005", "author_id": 3373283, "author_profile": "https://Stackoverflow.com/users/3373283", "pm_score": 4, "selected": false, "text": "SELECT TOP 0 * FROM table_name\n" }, { "answer_id": 52123273, "author": "Pravin Bansal", "author_id": 6095444, "author_profile": "https://Stackoverflow.com/users/6095444", "pm_score": 1, "selected": false, "text": "SELECT COL_LENGTH('tablename', 'colname')\n" }, { "answer_id": 55107206, "author": "VHS", "author_id": 5749570, "author_profile": "https://Stackoverflow.com/users/5749570", "pm_score": 3, "selected": false, "text": "describe sp_help describe USE mydb;\nexec sp_help 'myschema.mytable';\n" }, { "answer_id": 57593334, "author": "Graham", "author_id": 1180438, "author_profile": "https://Stackoverflow.com/users/1180438", "pm_score": 2, "selected": false, "text": "name DataType Collation Constraints PK FK Comment\n\nid int NOT NULL IDENTITY PK Order Line Id\npid int NOT NULL tbl_orders Order Id\nitemCode varchar(10) Latin1_General_CI_AS NOT NULL Product Code\n DECLARE @tname varchar(100) = 'yourTableName';\n\nSELECT col.name,\n\n CASE typ.name\n WHEN 'nvarchar' THEN 'nvarchar('+CAST((col.max_length / 2) as varchar)+')'\n WHEN 'varchar' THEN 'varchar('+CAST(col.max_length as varchar)+')'\n WHEN 'char' THEN 'char('+CAST(col.max_length as varchar)+')'\n WHEN 'nchar' THEN 'nchar('+CAST((col.max_length / 2) as varchar)+')'\n WHEN 'binary' THEN 'binary('+CAST(col.max_length as varchar)+')'\n WHEN 'varbinary' THEN 'varbinary('+CAST(col.max_length as varchar)+')'\n WHEN 'numeric' THEN 'numeric('+CAST(col.precision as varchar)+(CASE WHEN col.scale = 0 THEN '' ELSE ','+CAST(col.scale as varchar) END) +')'\n WHEN 'decimal' THEN 'decimal('+CAST(col.precision as varchar)+(CASE WHEN col.scale = 0 THEN '' ELSE ','+CAST(col.scale as varchar) END) +')'\n ELSE typ.name\n END DataType,\n\n ISNULL(col.collation_name,'') Collation,\n\n CASE WHEN col.is_nullable = 0 THEN 'NOT NULL ' ELSE '' END + CASE WHEN col.is_identity = 1 THEN 'IDENTITY' ELSE '' END Constraints,\n\n ISNULL((SELECT 'PK'\n FROM sys.key_constraints kc INNER JOIN\n sys.tables tb ON tb.object_id = kc.parent_object_id INNER JOIN\n sys.indexes si ON si.name = kc.name INNER JOIN\n sys.index_columns sic ON sic.index_id = si.index_id AND sic.object_id = si.object_id\n WHERE kc.type = 'PK'\n AND tb.name = @tname\n AND sic.column_id = col.column_id),'') PK,\n\n ISNULL((SELECT (SELECT name FROM sys.tables st WHERE st.object_id = fkc.referenced_object_id)\n FROM sys.foreign_key_columns fkc INNER JOIN\n sys.columns c ON c.column_id = fkc.parent_column_id AND fkc.parent_object_id = c.object_id INNER JOIN\n sys.tables t ON t.object_id = c.object_id\n WHERE t.name = tab.name\n AND c.name = col.name),'') FK,\n\n ISNULL((SELECT value\n FROM sys.extended_properties\n WHERE major_id = tab.object_id\n AND minor_id = col.column_id),'') Comment\n\nFROM sys.columns col INNER JOIN\n sys.tables tab ON tab.object_id = col.object_id INNER JOIN\n sys.types typ ON typ.system_type_id = col.system_type_id\nWHERE tab.name = @tname\n AND typ.name != 'sysname'\nORDER BY col.column_id;\n" }, { "answer_id": 58568148, "author": "abhishek khanna", "author_id": 9837900, "author_profile": "https://Stackoverflow.com/users/9837900", "pm_score": 1, "selected": false, "text": "SELECT C.COLUMN_NAME, C.IS_NULLABLE, C.DATA_TYPE, TC.CONSTRAINT_TYPE, C.COLUMN_DEFAULT\n FROM INFORMATION_SCHEMA.COLUMNS AS C\n FULL JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE AS CC ON C.COLUMN_NAME = CC.COLUMN_NAME \n FULL JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS TC ON CC.CONSTRAINT_NAME = TC.CONSTRAINT_NAME\nWHERE C.TABLE_NAME = '<Table Name>';\n" }, { "answer_id": 58967900, "author": "Dmitriy Grishin - dogrishin", "author_id": 3773486, "author_profile": "https://Stackoverflow.com/users/3773486", "pm_score": 1, "selected": false, "text": "exec sp_blitzindex @tablename='MyTable'\n" }, { "answer_id": 62957601, "author": "Hari_pb", "author_id": 5661594, "author_profile": "https://Stackoverflow.com/users/5661594", "pm_score": 3, "selected": false, "text": "db_name.dbo.table_name USE db_name; EXEC sp_help 'dbo.tablename' dbo exec sp_help 'dbo.table_name'" }, { "answer_id": 63483993, "author": "Abd Abughazaleh", "author_id": 8370334, "author_profile": "https://Stackoverflow.com/users/8370334", "pm_score": 2, "selected": false, "text": "exec sp_help TABLE_NAME\n" }, { "answer_id": 63895241, "author": "teresaruan-alt", "author_id": 14278872, "author_profile": "https://Stackoverflow.com/users/14278872", "pm_score": 0, "selected": false, "text": "info() USE [Database_Name]\n\nIF OBJECT_ID('tempdo.dob.#primary_key', 'U') IS NOT NULL DROP TABLE #primary_key\n\nSELECT \nCONS_T.TABLE_CATALOG,\nCONS_T.TABLE_SCHEMA,\nCONS_T.TABLE_NAME,\nCONS_C.COLUMN_NAME,\nCONS_T.CONSTRAINT_TYPE,\nCONS_T.CONSTRAINT_NAME\nINTO #primary_key\nFROM\nINFORMATION_SCHEMA.TABLE_CONSTRAINTS AS CONS_T \nJOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE AS CONS_C ON CONS_C.CONSTRAINT_NAME= CONS_T.CONSTRAINT_NAME\n\n\nSELECT\nSMA.name AS [Schema Name],\nST.name AS [Table Name],\nSC.column_id AS [Column Order],\nSC.name AS [Column Name],\nPKT.CONSTRAINT_TYPE, \nPKT.CONSTRAINT_NAME, \nSC.system_type_id,\nSTP.name AS [Data Type],\nSC.max_length,\nSC.precision, \nSC.scale, \nSC.is_nullable, \nSC.is_masked\nFROM sys.tables AS ST\nJOIN sys.schemas AS SMA ON SMA.schema_id = ST.schema_id\nJOIN sys.columns AS SC ON SC.object_id = ST.object_id \nJOIN sys.types AS STP ON STP.system_type_id = SC.system_type_id\nLEFT JOIN #primary_key AS PKT ON PKT.TABLE_SCHEMA = SMA.name\n AND PKT.TABLE_NAME = ST.name\n AND PKT.COLUMN_NAME = SC.name\nORDER BY ST.name ASC, SMA.name ASC\n" }, { "answer_id": 65607606, "author": "jiujiu", "author_id": 7083759, "author_profile": "https://Stackoverflow.com/users/7083759", "pm_score": 3, "selected": false, "text": "EXEC [ServerName].[DatabaseName].dbo.sp_columns 'TableName'\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
319,367
<p>I have a problem with time<br> My server is in the USA and I'm in Denmark (Europa) and I would like to have my site show the time in my local time. How can I do that?</p> <p>I try this </p> <pre><code>Datetime localtime = DateTimeOffset.Now.ToOffset(new TimeSpan(1,0,0)).DateTime; </code></pre> <p>and it works, but it will only work when I'm in GMT+1 / UTC+1 and not when I'm in GMT+2 / UTC+2. Is there another way of doing this - a simpler way of doing it?</p>
[ { "answer_id": 319380, "author": "HitLikeAHammer", "author_id": 35165, "author_profile": "https://Stackoverflow.com/users/35165", "pm_score": 0, "selected": false, "text": "DateTime myTimeGMT = ServerTime.ToUniversalTime();\n DateTime myTimeLocal = myTimeGMT.ToLocalTime();\n" }, { "answer_id": 319398, "author": "Robert Paulson", "author_id": 14033, "author_profile": "https://Stackoverflow.com/users/14033", "pm_score": 5, "selected": true, "text": "string zoneId = \"Central European Standard Time\";\nTimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById(zoneId);\nDateTime result = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow,tzi);\nConsole.WriteLine(\"Time is \" + result + \" in Denmark\");\n TimeZoneInfo.ConvertTimeToUtc(dtLocal,tzi) foreach( var tz in TimeZoneInfo.GetSystemTimeZones() )\n{\n Console.WriteLine(tz.DisplayName + \" is Id=','\" + tz.Id + \"'\");\n}\n" }, { "answer_id": 16221354, "author": "cal5barton", "author_id": 2225114, "author_profile": "https://Stackoverflow.com/users/2225114", "pm_score": 0, "selected": false, "text": "<asp:TemplateField HeaderText=\"Last Activity\">\n <ItemTemplate>\n <asp:Label ID=\"LastActivityLBL\" runat=\"server\" Text='<%# Convert.ToDateTime(Eval(\"LastActivityDate\")).ToLocalTime() %>'></asp:Label>\n </ItemTemplate>\n </asp:TemplateField>\n <asp:TemplateField HeaderText=\"Last Login\">\n <ItemTemplate>\n <asp:Label ID=\"LastLoginLBL\" runat=\"server\" Text='<%# Convert.ToDateTime(Eval(\"LastLoginDate\")).ToLocalTime() %>'></asp:Label>\n </ItemTemplate>\n </asp:TemplateField>\n" }, { "answer_id": 35620017, "author": "Shivam Singh Rajawat", "author_id": 5978656, "author_profile": "https://Stackoverflow.com/users/5978656", "pm_score": 0, "selected": false, "text": "Datetime localtime = DateTimeOffset.Now.ToOffset(new TimeSpan(1,0,0)).DateTime;\n Datetime localtime = DateTimeOffset.Now.ToOffset(new TimeSpan(3,0,0)).DateTime;\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319367", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31296/" ]
319,384
<p>I have a column in my database (a flag) with type varchar(1) that is populated either Y or NULL (this is how it is, not in my control).</p> <p>In SQL Server, doing an ascending order by query, NULL is ordered at the top. Should this behaviour be consistent for Oracle and DB2? </p> <p>If, instead I have a COALESCE on the column to ensure it is not null in the query, am I likely to hit any performance issues (due to table scans and the like)?</p> <p><strong>EDIT</strong></p> <p>The query needs to be consistent over all 3 databases, otherwise I will have to handle it in code, hence my thinking of using the COALESCE function</p> <p><strong>EDIT</strong></p> <p>I chose Pax as the answer, as it dealt with both parts of the question and gave a helpful workaround, however, thanks to me.yahoo.com/a/P4tXrx for the link to <a href="http://en.wikipedia.org/wiki/Order_by_(SQL)" rel="nofollow noreferrer">here</a></p>
[ { "answer_id": 319390, "author": "FerranB", "author_id": 40441, "author_profile": "https://Stackoverflow.com/users/40441", "pm_score": 0, "selected": false, "text": "ORDER BY value NULLS FIRST \n ORDER BY value NULLS LAST\n" }, { "answer_id": 319418, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 3, "selected": true, "text": "NULLS FIRST select * from tbl where fld is null\n union all select * from tbl where fld is not null\n UNION ALL" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319384", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5302/" ]
319,393
<p>I am trying to create a control that implements the per-pixel alpha blend while painting a 32-bit bitmap.</p> <p>I extended a CWnd and use static control in the resource editor. I managed to paint the alpha channel correctly but still the static control keep painting the gray background.</p> <p>I overwrote the OnEraseBkgnd to prevent the control from painting the background but it didn't worked. I finally managed to do it by using WS_EX_TRANSPARENT.</p> <p>My problem now is that my control is placed over other control. The first time the dialog is painted all works fine...but if I click over the "parent" control (ie the one beneath my control) my control doesn't received the WM_PAINT message. So it is not painted anymore.</p> <p>If I minimize the aplication and maximized it again the controls are painted again.</p> <p>Please, can anybody give a hint? I am getting crazy with this control!!!</p> <p>Thanks. </p>
[ { "answer_id": 4454240, "author": "Alexander Stoyan", "author_id": 543837, "author_profile": "https://Stackoverflow.com/users/543837", "pm_score": 2, "selected": false, "text": "BEGIN_MESSAGE_MAP(CTransparentStatic, CStatic)\n ON_WM_ERASEBKGND()\n ON_WM_CTLCOLOR_REFLECT()\nEND_MESSAGE_MAP()\n\nBOOL CTransparentStatic::OnEraseBkgnd(CDC* /*pDC*/)\n{\n // Prevent from default background erasing.\n return FALSE;\n}\n\nBOOL CTransparentStatic::PreCreateWindow(CREATESTRUCT& cs)\n{\n cs.dwExStyle |= WS_EX_TRANSPARENT;\n return CStatic::PreCreateWindow(cs);\n}\n\nHBRUSH CTransparentStatic::CtlColor(CDC* pDC, UINT /*nCtlColor*/)\n{\n pDC->SetBkMode(TRANSPARENT);\n return reinterpret_cast<HBRUSH>(GetStockObject(NULL_BRUSH));\n}\n\nvoid CTransparentStatic::PreSubclassWindow()\n{\n CStatic::PreSubclassWindow();\n\n const LONG_PTR exStyle = GetWindowLongPtr(m_hWnd, GWL_EXSTYLE);\n SetWindowLongPtr(m_hWnd, GWL_EXSTYLE, exStyle | WS_EX_TRANSPARENT);\n}\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14053/" ]
319,395
<p>I have two questions:</p> <p>1) How can I make an array which points to objects of integers?</p> <pre><code>int* myName[5]; // is this correct? </code></pre> <p>2) If I want to return a pointer to an array, which points to objects (like (1)) how can I do this in a method? ie) I want to impliment the method:</p> <pre><code>int **getStuff() { // what goes here? return *(myName); // im pretty sure this is not correct } </code></pre> <p>Thanks for the help!</p>
[ { "answer_id": 319404, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 4, "selected": true, "text": "int * myName[5]; /* correct */\n int * (* getStuff() )[5] {\n return &myName;\n}\n int ** getStuff() {\n return myName; /* or return &myName[0]; */\n}\n getStuff()[0] = &someInteger;" }, { "answer_id": 319405, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 1, "selected": false, "text": "int int int **getStuff() {\n return myName; // 1\n return &myName[0]; // 2\n}\n" }, { "answer_id": 319409, "author": "Aistina", "author_id": 37472, "author_profile": "https://Stackoverflow.com/users/37472", "pm_score": 1, "selected": false, "text": "int **myName;\n\nint **getStuff() {\n int **array = new int*[5];\n\n for (int i = 0; i < 5; i++)\n {\n int key = i;\n array[i] = &key;\n }\n\n return array;\n}\n" }, { "answer_id": 319608, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 2, "selected": false, "text": "int* myName[5];\n int **myFunction() {\n int *myArray[5];\n return myArray;\n} // <-- end of scope, and return takes us out of it\n int **myFunction() {\n int **myArray = new int[5];\n return myArray;\n}\n delete[] myArray;\n int **myFunction() {\n static int *myArray[5];\n return myArray;\n}\n int myArray[5] = { 1, 2, 3, 4, 5};\n" }, { "answer_id": 320967, "author": "Imran.Fanaswala", "author_id": 2117360, "author_profile": "https://Stackoverflow.com/users/2117360", "pm_score": 0, "selected": false, "text": "int **myFunction() {\n int **myArray = new int*[5];\n return myArray;\n}\n" }, { "answer_id": 11835448, "author": "stentor", "author_id": 573350, "author_profile": "https://Stackoverflow.com/users/573350", "pm_score": 0, "selected": false, "text": "template <class T>\nT* newarray(int len)\n {\n T *a;\n try\n {\n a = new T[len];\n memset(a,0,len*sizeof(T));\n return a;\n }\n catch (...) \n {return 0;}\n } \n void foo()\n {\n float *f=0;\n f=newarray<float>(1000000);\n if(!f) return;\n //use f\n delete [] f;\n }\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
319,401
<p>It would be really handy to be able to somehow say that certain properties in the generated entity classes should, for example, be decorated by (say) validation attributes (as well as Linq To SQL column attributes).</p> <p>Is it a T4 template someplace? Or are there other ways to skin the cat?</p>
[ { "answer_id": 319772, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 0, "selected": false, "text": "Foo Foo .cs" }, { "answer_id": 368255, "author": "Erwin", "author_id": 7236, "author_profile": "https://Stackoverflow.com/users/7236", "pm_score": 0, "selected": false, "text": "[MetadataType(typeof(Product_Meta))]\n public partial class Product\n { \n public partial class Product_Meta \n {\n [Range(5, 50, ErrorMessage = \"The product's reorder level must be greater than 5 and less than 50\")]\n public object ReorderLevel { get; set; } \n } \n }\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20971/" ]
319,413
<p>I have a search form in an app I'm currently developing, and I would like for it to be the equivalent of <code>method="GET"</code>.</p> <p>Thus, when clicking the search button, the user goes to <code>search.aspx?q=the+query+he+entered</code></p> <p>The reason I want this is simply bookmarkable URLs, plus it feels cleaner to do it this way.</p> <p>I also don't want the viewstate hidden field value appended to the URL either.</p> <p>The best I could come up with for this is: </p> <ol> <li>Capture the server-side click event of the button and <code>Response.Redirect</code>.</li> <li>Attach a Javascript <code>onclick</code> handler to the button that fires a <code>window.location.replace</code>.</li> </ol> <p>Both feel quirky and sub-optimal... Can you think of a better approach?</p>
[ { "answer_id": 319645, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 0, "selected": false, "text": " $(document).ready( function() {\n $('input[type=hidden]').remove();\n $('form').attr('method','get');\n });\n" }, { "answer_id": 2624176, "author": "Solburn", "author_id": 75755, "author_profile": "https://Stackoverflow.com/users/75755", "pm_score": 3, "selected": false, "text": "protected void Button1_Click(object sender, EventArgs e)\n{\n string SearchQueryStringParameters = @\"?SearchParameters=\";\n string SearchURL = \"Search.aspx\" + SearchQueryStringParameters;\n\n Response.Redirect(SearchURL);\n}\n protected void Page_Load(object sender, EventArgs e)\n{\n if (!string.IsNullOrEmpty(Request.QueryString[\"SearchParameters\"]))\n {\n // prefill your search textbox\n this.txtSearch.Text = Request.QueryString[\"SearchParameters\"];\n\n // run your code that does a search and fill your repeater/datagrid/whatever here\n }\n else\n {\n // do nothing but show the search page\n }\n}\n" }, { "answer_id": 4093296, "author": "Valerio Gentile", "author_id": 496676, "author_profile": "https://Stackoverflow.com/users/496676", "pm_score": 2, "selected": false, "text": "$(document).ready(function(){ enableSubmitFormByGet(); });\n\nfunction enableSubmitFormByGet(){\n if($(\"form\").attr(\"method\") == \"get\"){\n $(\"form\").submit(function() {\n $(\"[name^=\" + \"ctl00\" + \"]\").each(function(i){\n var myName = $(this).attr(\"name\");\n var newName = \"p\" + (i-1);\n $(this).attr(\"name\", newName);\n });\n var qs =$(this).find(\"input[rel!='do-not-submit'],textarea[rel!='do-not-submit'],select[rel!='do-not-submit'],hidden[rel!='do-not-submit']\").not(\"#__VIEWSTATE,#__EVENTVALIDATION,#__EVENTTARGET,#__EVENTARGUMENT\").serialize();\n window.document.location.href = \"?\" + qs;\n return false;\n});\n" }, { "answer_id": 34908660, "author": "DBithead", "author_id": 5817785, "author_profile": "https://Stackoverflow.com/users/5817785", "pm_score": 0, "selected": false, "text": " $(\"#__VIEWSTATE\").remove();\n $(\"#__EVENTVALIDATION\").remove();\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3314/" ]
319,422
<p>i'm generating controls dynamically on my asp.net page by xslt transformation from an xml file. i will need to reference these controls from code behind later. i would like to add these references to the list/hashtable/whatever during creation (in xslt file i suppose) so that i could reach them later and i have no idea how to do this. i will be absolutely grateful for any suggestions, agnieszka</p>
[ { "answer_id": 320164, "author": "Generic Error", "author_id": 40944, "author_profile": "https://Stackoverflow.com/users/40944", "pm_score": 3, "selected": true, "text": "protected void Page_Load(object sender, EventArgs e)\n{\n // Fetch your XML here and transform it. This string represents\n // the transformed output\n string content = @\"\n <asp:Button runat=\"\"server\"\" Text=\"\"Hello\"\" />\n <asp:Button runat=\"\"server\"\" Text=\"\"World\"\" />\";\n\n var controls = ParseControl(content);\n\n foreach (var control in controls)\n {\n // Wire up events, change settings etc here\n }\n\n // placeHolder is simply an ASP.Net PlaceHolder control on the page\n // where I would like the controls to end up\n placeHolder.Controls.Add(controls);\n}\n" }, { "answer_id": 320490, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "// Load the xslt to do the transformations\nXslTransform transform = new XslTransform();\ntransform.Load(Server.MapPath(\"MakeControls.xslt\"));\n\n// Get the transformed result\nStringWriter sw = new StringWriter();\ntransform.Transform(surveyDoc, null, sw);\nstring result = sw.ToString();\n\n// parse the control(s) and add it to the page\nControl ctrl = Page.ParseControl(result);\nform1.Controls.Add(ctrl);\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319422", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40872/" ]
319,423
<p>I am new to mysqli, and trying to confirm that if I so something like the below, the errno will be set to the last error, if any, and not the error of the last query. </p> <p>Is this a decent practice or should I be checking for the error in between every query?</p> <p>Thanks! </p> <pre><code>$mysqli-&gt;autocommit(FALSE); $mysqli-&gt;query("INSERT INTO ....."); $mysqli-&gt;query("INSERT INTO ....."); $mysqli-&gt;query("INSERT INTO ....."); $mysqli-&gt;query("INSERT INTO ....."); $mysqli-&gt;query("INSERT INTO ....."); if ( 0==$mysqli-&gt;errno ) { $mysqli-&gt;commit(); } else { $mysqli-&gt;rollback(); // Handle error } </code></pre>
[ { "answer_id": 319436, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 2, "selected": false, "text": "$mysqli->query() if (!$mysqli->query(\"INSERT ...\")) {\n printf(\"Errorcode: %d\\n\", $mysqli->errno);\n}\n" }, { "answer_id": 15491620, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "class DBException extends Exception {\n}\nclass DBConnectException extends DBException {\n}\nclass DBQueryException extends DBException {\n}\n\nclass DB extends MySQLi {\n private static $instance = null;\n\n private function __construct() {\n parent::__construct('host',\n 'username',\n 'passwd',\n 'dbname');\n\n if ($this->connect_errno) {\n throw new DBConnectException($this->connect_error, $this->connect_errno);\n }\n }\n\n private function __destructor() {\n parent::close();\n }\n\n private function __clone() {\n }\n\n public static function getInstance() {\n if (self::$instance == null) {\n self::$instance = new self();\n }\n return self::$instance;\n }\n\n public function query($query, $resultmode = MYSQLI_STORE_RESULT) {\n $result = parent::query($query, $resultmode);\n if (!$result) {\n // or do whatever you wanna do when an error occurs\n throw new DBQueryException($this->error, $this->errno);\n }\n return $result;\n }\n}\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319423", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27580/" ]
319,426
<p>How can I compare strings in a case insensitive way in Python?</p> <p>I would like to encapsulate comparison of a regular strings to a repository string, using simple and Pythonic code. I also would like to have ability to look up values in a dict hashed by strings using regular python strings.</p>
[ { "answer_id": 319435, "author": "Harley Holcombe", "author_id": 1057, "author_profile": "https://Stackoverflow.com/users/1057", "pm_score": 11, "selected": true, "text": "string1 = 'Hello'\nstring2 = 'hello'\n\nif string1.lower() == string2.lower():\n print(\"The strings are the same (case insensitive)\")\nelse:\n print(\"The strings are NOT the same (case insensitive)\")\n string1 = 'Hello'\nstring2 = 'hello'\n\nif string1.casefold() == string2.casefold():\n print(\"The strings are the same (case insensitive)\")\nelse:\n print(\"The strings are NOT the same (case insensitive)\")\n" }, { "answer_id": 319437, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 2, "selected": false, "text": ">>> \"hello\".upper() == \"HELLO\".upper()\nTrue\n>>> \n" }, { "answer_id": 319439, "author": "Camilo Díaz Repka", "author_id": 861, "author_profile": "https://Stackoverflow.com/users/861", "pm_score": 2, "selected": false, "text": "string.lower()" }, { "answer_id": 322359, "author": "Patrick Harrington", "author_id": 41165, "author_profile": "https://Stackoverflow.com/users/41165", "pm_score": -1, "selected": false, "text": "def insenStringCompare(s1, s2):\n \"\"\" Method that takes two strings and returns True or False, based\n on if they are equal, regardless of case.\"\"\"\n try:\n return s1.lower() == s2.lower()\n except AttributeError:\n print \"Please only pass strings into this method.\"\n print \"You passed a %s and %s\" % (s1.__class__, s2.__class__)\n" }, { "answer_id": 11573384, "author": "Nathan Craike", "author_id": 387306, "author_profile": "https://Stackoverflow.com/users/387306", "pm_score": 6, "selected": false, "text": ".lower() string1.lower() == string2.lower()\n unicode.txt Σίσυφος ΣΊΣΥΦΟΣ >>> utf8_bytes = open(\"unicode.txt\", 'r').read()\n>>> print repr(utf8_bytes)\n'\\xce\\xa3\\xce\\xaf\\xcf\\x83\\xcf\\x85\\xcf\\x86\\xce\\xbf\\xcf\\x82\\n\\xce\\xa3\\xce\\x8a\\xce\\xa3\\xce\\xa5\\xce\\xa6\\xce\\x9f\\xce\\xa3\\n'\n>>> u = utf8_bytes.decode('utf8')\n>>> print u\nΣίσυφος\nΣΊΣΥΦΟΣ\n\n>>> first, second = u.splitlines()\n>>> print first.lower()\nσίσυφος\n>>> print second.lower()\nσίσυφοσ\n>>> first.lower() == second.lower()\nFalse\n>>> first.upper() == second.upper()\nTrue\n .lower() >>> s = open('unicode.txt', encoding='utf8').read()\n>>> print(s)\nΣίσυφος\nΣΊΣΥΦΟΣ\n\n>>> first, second = s.splitlines()\n>>> print(first.lower())\nσίσυφος\n>>> print(second.lower())\nσίσυφος\n>>> first.lower() == second.lower()\nTrue\n>>> first.upper() == second.upper()\nTrue\n" }, { "answer_id": 29247821, "author": "Veedrac", "author_id": 1763356, "author_profile": "https://Stackoverflow.com/users/1763356", "pm_score": 9, "selected": false, "text": "text.lower() != text.upper().lower() \"ß\" >>> \"ß\".lower()\n'ß'\n>>> \"ß\".upper().lower()\n'ss'\n \"BUSSE\" \"Buße\" \"BUSSE\" \"BUẞE\" casefold lower casefold .upper().lower() \"ê\" == \"ê\" >>> \"ê\" == \"ê\"\nFalse\n >>> import unicodedata\n>>> [unicodedata.name(char) for char in \"ê\"]\n['LATIN SMALL LETTER E WITH CIRCUMFLEX']\n>>> [unicodedata.name(char) for char in \"ê\"]\n['LATIN SMALL LETTER E', 'COMBINING CIRCUMFLEX ACCENT']\n unicodedata.normalize >>> unicodedata.normalize(\"NFKD\", \"ê\") == unicodedata.normalize(\"NFKD\", \"ê\")\nTrue\n import unicodedata\n\ndef normalize_caseless(text):\n return unicodedata.normalize(\"NFKD\", text.casefold())\n\ndef caseless_equal(left, right):\n return normalize_caseless(left) == normalize_caseless(right)\n" }, { "answer_id": 38627691, "author": "Shiwangi", "author_id": 2811399, "author_profile": "https://Stackoverflow.com/users/2811399", "pm_score": 3, "selected": false, "text": "import re\nif re.search('mandy', 'Mandy Pande', re.IGNORECASE):\n# is True\n In [42]: if re.search(\"ê\",\"ê\", re.IGNORECASE):\n....: print(1)\n....:\n1\n In [36]: \"ß\".lower()\nOut[36]: 'ß'\nIn [37]: \"ß\".upper()\nOut[37]: 'SS'\nIn [38]: \"ß\".upper().lower()\nOut[38]: 'ss'\nIn [39]: if re.search(\"ß\",\"ßß\", re.IGNORECASE):\n....: print(1)\n....:\n1\nIn [40]: if re.search(\"SS\",\"ßß\", re.IGNORECASE):\n....: print(1)\n....:\nIn [41]: if re.search(\"ß\",\"SS\", re.IGNORECASE):\n....: print(1)\n....:\n" }, { "answer_id": 40551443, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 6, "selected": false, "text": "X.casefold() == Y.casefold() 'å' 'å' import unicodedata\n\ndef NFD(text):\n return unicodedata.normalize('NFD', text)\n\ndef canonical_caseless(text):\n return NFD(NFD(text).casefold())\n NFD() >>> 'å'.casefold() == 'å'.casefold()\nFalse\n>>> canonical_caseless('å') == canonical_caseless('å')\nTrue\n '㎒'" }, { "answer_id": 52136637, "author": "Ali Paul", "author_id": 10306352, "author_profile": "https://Stackoverflow.com/users/10306352", "pm_score": -1, "selected": false, "text": " import re as yes\n\n def bar_or_spam():\n\n message = raw_input(\"\\nEnter FoO for BaR or SpaM for EgGs (NCS): \") \n\n message_in_coconut = yes.compile(r'foo*|spam*', yes.I)\n\n lost_n_found = message_in_coconut.search(message).group()\n\n if lost_n_found != None:\n return lost_n_found.lower()\n else:\n print (\"Make tea not love\")\n return\n\n whatz_for_breakfast = bar_or_spam()\n\n if whatz_for_breakfast == foo:\n print (\"BaR\")\n\n elif whatz_for_breakfast == spam:\n print (\"EgGs\")\n" }, { "answer_id": 66834952, "author": "mpriya", "author_id": 14545111, "author_profile": "https://Stackoverflow.com/users/14545111", "pm_score": 0, "selected": false, "text": "data['Column_name'].str.contains('abcd', case=False)\n" }, { "answer_id": 66835004, "author": "mpriya", "author_id": 14545111, "author_profile": "https://Stackoverflow.com/users/14545111", "pm_score": 3, "selected": false, "text": "firstString = \"Hi EVERYONE\"\nsecondString = \"Hi everyone\"\n\nif firstString.casefold() == secondString.casefold():\n print('The strings are equal.')\nelse:\n print('The strings are not equal.')\n The strings are equal.\n" }, { "answer_id": 71606766, "author": "zackakshay", "author_id": 16951469, "author_profile": "https://Stackoverflow.com/users/16951469", "pm_score": 0, "selected": false, "text": "def search_specificword(key, stng):\n key = key.lower()\n stng = stng.lower()\n flag_present = False\n if stng.startswith(key+\" \"):\n flag_present = True\n symb = [',','.']\n for i in symb:\n if stng.find(\" \"+key+i) != -1:\n flag_present = True\n if key == stng:\n flag_present = True\n if stng.endswith(\" \"+key):\n flag_present = True\n if stng.find(\" \"+key+\" \") != -1:\n flag_present = True\n print(flag_present)\n return flag_present\n" }, { "answer_id": 73428864, "author": "Jason Leaver", "author_id": 6334082, "author_profile": "https://Stackoverflow.com/users/6334082", "pm_score": 2, "selected": false, "text": "from pathlib import Path\n\n\nclass CaseInsitiveString(str):\n def __eq__(self, __o: str) -> bool:\n return self.casefold() == __o.casefold()\n\nGZ = CaseInsitiveString(\".gz\")\nZIP = CaseInsitiveString(\".zip\")\nTAR = CaseInsitiveString(\".tar\")\n\npath = Path(\"/tmp/ALL_CAPS.TAR.GZ\")\n\nGZ in path.suffixes, ZIP in path.suffixes, TAR in path.suffixes, TAR == \".tAr\"\n\n# (True, False, True, True)\n" }, { "answer_id": 73806474, "author": "Luciano Narimatsu de Faria", "author_id": 19244118, "author_profile": "https://Stackoverflow.com/users/19244118", "pm_score": 0, "selected": false, "text": "from re import search, IGNORECASE\n\ndef is_string_match(word1, word2):\n # Case insensitively function that checks if two words are the same\n # word1: string\n # word2: string | list\n\n # if the word1 is in a list of words\n if isinstance(word2, list):\n for word in word2:\n if search(rf'\\b{word1}\\b', word, IGNORECASE):\n return True\n return False\n\n # if the word1 is same as word2\n if search(rf'\\b{word1}\\b', word2, IGNORECASE):\n return True\n return False\n is_match_word = is_string_match(\"Hello\", \"hELLO\") \nTrue\n is_match_word = is_string_match(\"Hello\", [\"Bye\", \"hELLO\", \"@vagavela\"])\nTrue\n is_match_word = is_string_match(\"Hello\", \"Bye\")\nFalse\n" }, { "answer_id": 74144463, "author": "Jason R. Coombs", "author_id": 70170, "author_profile": "https://Stackoverflow.com/users/70170", "pm_score": 0, "selected": false, "text": ">>> from jaraco.text import FoldedCase\n>>> FoldedCase('Hello World') in ['hello world']\nTrue\n >>> from jaraco.collections import FoldedCaseKeyedDict\n>>> d = FoldedCaseKeyedDict()\n>>> d['heLlo'] = 'world'\n>>> list(d.keys()) == ['heLlo']\nTrue\n>>> d['hello'] == 'world'\nTrue\n>>> 'hello' in d\nTrue\n>>> 'HELLO' in d\nTrue\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319426", "https://Stackoverflow.com", "https://Stackoverflow.com/users/52490/" ]
319,429
<p>I have a C# .NET application with which I've created a custom image display control. Each image display represents its own display context and draws the image using glDrawPixels (Yes I know it would be better to use textures, I plan to in the futures but this app is already too far along and my time is limited).</p> <p>I am now trying to have both images pan simultaneously. That is, when one image is moved down ten pixels, the second image moves down ten pixels. Like so:</p> <pre><code>imageOne.YPan -= 10; imageTwo.YPan -= 10; imageOne.Invalidate(); //This forces a redraw. imageTwo.Invalidate(); //This forces a redraw. </code></pre> <p>Alright so here is the problem I am having. Only one of the images displays is redrawing. If I place a pause in between the two Invalidate calls and make the pause duration at least 110 milliseconds both will redraw, but not simultaneously. So it looks as if the second image is always trying to catch up to the first. Plus, a 110 millisecond pause slows down the motion too much. </p> <p>I have tried placing the updating and invalidating of each image in its own thread but this did not help.</p> <p>At the beginning of drawing I make the appropriate context is current, and at the end I am calling swapbuffers(). I tried adding a glFinish to the end of the draw function, but there was no change. </p> <p>Could it be that its the graphics card that is the problem? I am stuck using an integrated gpu that only has openGL 1.4. </p> <p>Hopefully, I have provided enough detail that the answer to my problem can be found. </p>
[ { "answer_id": 319561, "author": "shoosh", "author_id": 9611, "author_profile": "https://Stackoverflow.com/users/9611", "pm_score": 1, "selected": false, "text": "glFinish() glError() swapBuffers()" }, { "answer_id": 5628707, "author": "Ben Voigt", "author_id": 103167, "author_profile": "https://Stackoverflow.com/users/103167", "pm_score": 0, "selected": false, "text": "Invalidate Control.OnPaint Control.Paint" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/55638/" ]
319,438
<p>I'm able to get cells to format as Dates, but I've been unable to get cells to format as currency... Anyone have an example of how to create a style to get this to work? My code below show the styles I'm creating... the styleDateFormat works like a champ while styleCurrencyFormat has no affect on the cell.</p> <pre><code>private HSSFWorkbook wb; private HSSFCellStyle styleDateFormat = null; private HSSFCellStyle styleCurrencyFormat = null; </code></pre> <p>......</p> <pre><code>public CouponicsReportBean(){ wb = new HSSFWorkbook(); InitializeFonts(); } public void InitializeFonts() { styleDateFormat = wb.createCellStyle(); styleDateFormat.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy")); styleCurrencyFormat = wb.createCellStyle(); styleCurrencyFormat.setDataFormat(HSSFDataFormat.getBuiltinFormat("$#,##0.00")); } </code></pre>
[ { "answer_id": 319917, "author": "Dave K", "author_id": 19864, "author_profile": "https://Stackoverflow.com/users/19864", "pm_score": 7, "selected": true, "text": " styleCurrencyFormat.setDataFormat((short)8); //8 = \"($#,##0.00_);[Red]($#,##0.00)\"\n" }, { "answer_id": 9907568, "author": "user1073214", "author_id": 1073214, "author_profile": "https://Stackoverflow.com/users/1073214", "pm_score": 3, "selected": false, "text": "cell.setCellValue(416.17); \ncellStyle.setDataFormat((short)7);\ncell.setCellStyle(cellStyle);\n" }, { "answer_id": 27277918, "author": "Andrew", "author_id": 1721406, "author_profile": "https://Stackoverflow.com/users/1721406", "pm_score": 5, "selected": false, "text": "createHelper.createDataFormat().getFormat(\"<here>\");\n createHelper.createDataFormat().getFormat(\"_($* #,##0.00_);_($* (#,##0.00);_($* \\\"-\\\"??_);_(@_)\"); //is the \"Accounting\" format.\n" }, { "answer_id": 28414666, "author": "deldev", "author_id": 1767021, "author_profile": "https://Stackoverflow.com/users/1767021", "pm_score": 2, "selected": false, "text": "HSSFCellStyle cell = yourWorkBook.createCellStyle();\nCreationHelper ch = yourWorkBook.getCreationHelper();\ncell.setDataFormat(ch.createDataFormat().getFormat(\"#,##0.00;\\\\-#,##0.00\"));\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319438", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19864/" ]
319,443
<p>I'm not at all familiar with VB.NET or ASP. I need to create a simple page which makes a call to a remote web service. I used the wsdl utility which comes with the DotNet SDK to generate a service proxy and write it to a VB file. Unfortunately I have no idea how to reference this code in either my ASPX file or the code behind VB file so I can create an instance of the proxy.</p> <p>Edit: I should have qualified this by noting that I'm not using visual studio. I just coded up a .aspx with a .vb behind it and dropped it into an IIS location. Is there a way to do what you're suggesting outside of VS?</p>
[ { "answer_id": 319469, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "dim x as new xyz\nvar = x.methodname()\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319443", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14128/" ]
319,463
<p>Is there a way using the iPhone SDK to get the same results as an HTTP POST or GET methods? </p>
[ { "answer_id": 322573, "author": "Matt Gallagher", "author_id": 36103, "author_profile": "https://Stackoverflow.com/users/36103", "pm_score": 5, "selected": false, "text": "responseData responseData = [[NSMutableData data] retain];\n\nNSURLRequest *request =\n [NSURLRequest requestWithURL:[NSURL URLWithString:@\"http://www.domain.com/path\"]];\n[[NSURLConnection alloc] initWithRequest:request delegate:self];\n - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response\n{\n [responseData setLength:0];\n}\n\n- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data\n{\n [responseData appendData:data];\n}\n\n- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error\n{\n // Show error\n}\n\n- (void)connectionDidFinishLoading:(NSURLConnection *)connection\n{\n // Once this method is invoked, \"responseData\" contains the complete result\n}\n responseData NSMutableURLRequest *request =\n [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@\"http://www.domain.com/path\"]];\n[request setHTTPMethod:@\"POST\"];\n\nNSString *postString = @\"Some post string\";\n[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319463", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
319,479
<p>Are there any libraries out there for Java that will accept two strings, and return a string with formatted output as per the *nix diff command?</p> <p>e.g. feed in </p> <pre><code>test 1,2,3,4 test 5,6,7,8 test 9,10,11,12 test 13,14,15,16 </code></pre> <p>and </p> <pre><code>test 1,2,3,4 test 5,6,7,8 test 9,10,11,12,13 test 13,14,15,16 </code></pre> <p>as input, and it would give you </p> <pre><code>test 1,2,3,4 test 1,2,3,4 test 5,6,7,8 test 5,6,7,8 test 9,10,11,12 | test 9,10,11,12,13 test 13,14,15,16 test 13,14,15,16 </code></pre> <p>Exactly the same as if I had passed the files to <code>diff -y expected actual</code></p> <p>I found <a href="https://stackoverflow.com/questions/132478/how-to-perform-string-diffs-in-java">this question</a>, and it gives some good advice on general libraries for giving you programmatic output, but I'm wanting the straight string results.</p> <p>I could call <code>diff</code> directly as a system call, but this particular app will be running on unix and windows and I can't be sure that the environment will actually have <code>diff</code> available.</p>
[ { "answer_id": 319857, "author": "madlep", "author_id": 14160, "author_profile": "https://Stackoverflow.com/users/14160", "pm_score": 4, "selected": true, "text": "public static String diffSideBySide(String fromStr, String toStr){\n // this is equivalent of running unix diff -y command\n // not pretty, but it works. Feel free to refactor against unit test.\n String[] fromLines = fromStr.split(\"\\n\");\n String[] toLines = toStr.split(\"\\n\");\n List<Difference> diffs = (new Diff(fromLines, toLines)).diff();\n\n int padding = 3;\n int maxStrWidth = Math.max(maxLength(fromLines), maxLength(toLines)) + padding;\n\n StrBuilder diffOut = new StrBuilder();\n diffOut.setNewLineText(\"\\n\");\n int fromLineNum = 0;\n int toLineNum = 0;\n for(Difference diff : diffs) {\n int delStart = diff.getDeletedStart();\n int delEnd = diff.getDeletedEnd();\n int addStart = diff.getAddedStart();\n int addEnd = diff.getAddedEnd();\n\n boolean isAdd = (delEnd == Difference.NONE && addEnd != Difference.NONE);\n boolean isDel = (addEnd == Difference.NONE && delEnd != Difference.NONE);\n boolean isMod = (delEnd != Difference.NONE && addEnd != Difference.NONE);\n\n //write out unchanged lines between diffs\n while(true) {\n String left = \"\";\n String right = \"\";\n if (fromLineNum < (delStart)){\n left = fromLines[fromLineNum];\n fromLineNum++;\n }\n if (toLineNum < (addStart)) {\n right = toLines[toLineNum];\n toLineNum++;\n }\n diffOut.append(StringUtils.rightPad(left, maxStrWidth));\n diffOut.append(\" \"); // no operator to display\n diffOut.appendln(right);\n\n if( (fromLineNum == (delStart)) && (toLineNum == (addStart))) {\n break;\n }\n }\n\n if (isDel) {\n //write out a deletion\n for(int i=delStart; i <= delEnd; i++) {\n diffOut.append(StringUtils.rightPad(fromLines[i], maxStrWidth));\n diffOut.appendln(\"<\");\n }\n fromLineNum = delEnd + 1;\n } else if (isAdd) {\n //write out an addition\n for(int i=addStart; i <= addEnd; i++) {\n diffOut.append(StringUtils.rightPad(\"\", maxStrWidth));\n diffOut.append(\"> \");\n diffOut.appendln(toLines[i]);\n }\n toLineNum = addEnd + 1; \n } else if (isMod) {\n // write out a modification\n while(true){\n String left = \"\";\n String right = \"\";\n if (fromLineNum <= (delEnd)){\n left = fromLines[fromLineNum];\n fromLineNum++;\n }\n if (toLineNum <= (addEnd)) {\n right = toLines[toLineNum];\n toLineNum++;\n }\n diffOut.append(StringUtils.rightPad(left, maxStrWidth));\n diffOut.append(\"| \");\n diffOut.appendln(right);\n\n if( (fromLineNum > (delEnd)) && (toLineNum > (addEnd))) {\n break;\n }\n }\n }\n\n }\n\n //we've finished displaying the diffs, now we just need to run out all the remaining unchanged lines\n while(true) {\n String left = \"\";\n String right = \"\";\n if (fromLineNum < (fromLines.length)){\n left = fromLines[fromLineNum];\n fromLineNum++;\n }\n if (toLineNum < (toLines.length)) {\n right = toLines[toLineNum];\n toLineNum++;\n }\n diffOut.append(StringUtils.rightPad(left, maxStrWidth));\n diffOut.append(\" \"); // no operator to display\n diffOut.appendln(right);\n\n if( (fromLineNum == (fromLines.length)) && (toLineNum == (toLines.length))) {\n break;\n }\n }\n\n return diffOut.toString();\n}\n\nprivate static int maxLength(String[] fromLines) {\n int maxLength = 0;\n\n for (int i = 0; i < fromLines.length; i++) {\n if (fromLines[i].length() > maxLength) {\n maxLength = fromLines[i].length();\n }\n }\n return maxLength;\n}\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319479", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14160/" ]
319,482
<p>I have a simple app that uses an SQL Express 2005 database. When the user closes the app, I want to give the option to back up the database by making a copy in another directory. However, when I try to do it, I get "The process cannot access the file '...\Pricing.MDF' because it is being used by another process." I closed the connection, disposed the connection, set it to nothing, and GC.Collect(), but it makes no difference. My connection string is "Data Source=.\SQLEXPRESS2005;AttachDbFilename=|DataDirectory|\Pricing.mdf;Integrated Security=True; User Instance=True" and I just keep using the same connection throughout. I didn't see where I could detach the database to counter the attach in the connection string.</p> <p>1 - How do I RELEASE the thing? 2 - Is there a better way than just copying the database? The app is for my husband only, so I will be able to handle it if he actually does need to restore from backup.</p> <p>Thanks!</p>
[ { "answer_id": 319686, "author": "Adam", "author_id": 13320, "author_profile": "https://Stackoverflow.com/users/13320", "pm_score": 3, "selected": true, "text": "BACKUP DATABASE [mydatabasename]\nTO DISK = N'C:\\Program Files\\Microsoft SQL Server\\MSSQL.1\\MSSQL\\Backup\\Scheduled Task Backups\\mydatabasename-backup' WITH NOFORMAT, NOINIT, NAME = N'mydatabasename-Full Data\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12897/" ]
319,506
<p>I've be working with a Java application run through the command-line. It deals with XML files, specially the dblp.xml database which has more than 400MB. </p> <p>I was using JVM 5 and my app needed sort of 600-700MB of memory to processe the dblp.xml. After updating to JVM 6, it starting needing more than 1gb of memory (something I don't have), although it runs a bit faster.</p> <p>I'm pretty sure of the memory consumption difference, because I've already tested both again and again in this same computer. Resulting in the same difference of memory consumption.</p> <p>I didn't set any special parameters, just -Xmx800M or -Xmx1000M. Running with Ubuntu Hardy Heron on a dual core 1.7ghz, with 1,5gb of memory Using only the top/ps commands to measure</p> <p>Any one have an idea why this occurs? I really wanted to use JVM 6, because in my production server it is the JVM in use, and I'm not quite able to change easily.</p> <p>Thanks</p>
[ { "answer_id": 320217, "author": "the.duckman", "author_id": 21368, "author_profile": "https://Stackoverflow.com/users/21368", "pm_score": 2, "selected": false, "text": "java -version\n" }, { "answer_id": 321957, "author": "the.duckman", "author_id": 21368, "author_profile": "https://Stackoverflow.com/users/21368", "pm_score": 1, "selected": false, "text": "top ps top ps System.gc();\nRuntime runtime = Runtime.getRuntime();\nlong memUsedInBytes = runtime.totalMemory() - runtime.freeMemory();\n System.gc()" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40876/" ]
319,508
<p>I want to get the VB.NET or VB code to access the hard disk serial no when starting the program. It's to help me to protect my own software from people who try to pirate copies. </p>
[ { "answer_id": 319655, "author": "Jon B", "author_id": 27414, "author_profile": "https://Stackoverflow.com/users/27414", "pm_score": 3, "selected": false, "text": "string driveLetter = Environment.SystemDirectory.Substring(0, 2);\nstring sn = new System.Management.ManagementObject(\"Win32_LogicalDisk.DeviceID=\\\"\" + driveLetter + \"\\\"\").GetPropertyValue(\"VolumeSerialNumber\").ToString();\n" }, { "answer_id": 5285651, "author": "masood raji", "author_id": 656986, "author_profile": "https://Stackoverflow.com/users/656986", "pm_score": 1, "selected": false, "text": "Project--> References --> Microsoft Scripting Runtime\n Sub ShowDriveInfo(path)\n Dim fso, drv, bytesPerGB, freeGB, totalGB, s\n\n s = \"\"\n bytesPerGB = 1024 * 1024 * 1024\n\n Set fso = CreateObject(\"Scripting.FileSystemObject\")\n Set drv = fso.GetDrive(fso.GetDriveName(path))\n\n s = s & drv.Path & \" - \"\n\n if drv.IsReady Then\n freeGB = drv.FreeSpace / bytesPerGB\n totalGB = drv.TotalSize / bytesPerGB\n\n s = s & FormatNumber(freeGB, 3) + \" GB free of \"\n s = s & FormatNumber(totalGB, 3) + \" GB\"\n Else\n s = s & \"Not Ready\"\n End If\n s = s & \"<br />\"\n\n document.write (s)\nEnd Sub\n" }, { "answer_id": 5285663, "author": "masood raji", "author_id": 656986, "author_profile": "https://Stackoverflow.com/users/656986", "pm_score": 0, "selected": false, "text": "Function ShowDriveInfo(drvpath)\n Dim fso, d, s, t\n Set fso = CreateObject(\"Scripting.FileSystemObject\")\n Set d = fso.GetDrive(fso.GetDriveName(fso.GetAbsolutePathName(drvpath)))\n Select Case d.DriveType\n Case 0: t = \"Unknown\"\n Case 1: t = \"Removable\"\n Case 2: t = \"Fixed\"\n Case 3: t = \"Network\"\n Case 4: t = \"CD-ROM\"\n Case 5: t = \"RAM Disk\"\n End Select\n s = \"Drive \" & d.DriveLetter & \": - \" & t\n s = s & \"<BR>\" & \"SN: \" & d.SerialNumber\n ShowDriveInfo = s\nEnd Function\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319508", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40875/" ]
319,516
<p>I'm developing an FTP-like program to download a large number of small files onto an Xbox 360 devkit (which uses Winsock), and porting it to Playstation3 (also a devkit, and uses linux AFAIK). The program uses BSD-style sockets (TCP). Both of the programs communicate with the same server, downloading the same data. The program iterates through all the files in a loop like this:</p> <pre>for each file send(retrieve command) send(filename) receive(response) test response receive(size) receive(data) </pre> <p>On the Xbox 360 implementation, the whole download takes 1:27, and the time between the last send and first receive takes about 14 seconds. This seems quite reasonable to me.</p> <p>The Playstation3 implementation takes 4:01 for the same data. The bottleneck seems to be between the last send and first receive, which takes up 3:43 of that time. The network and disk times are both significantly less than the Xbox 360.</p> <p>Both these devkits are on the same switch as my PC, which does the file serving, and there is no other traffic on said switch.</p> <p>I've tried setting the <code>TCP_NODELAY</code> flag, which didn't change things significantly. I've also tried setting the <code>SO_SNDBUF</code>/<code>SO_RCVBUF</code> to 625KB, which also didn't significantly affect the time.</p> <p>I'm assuming that the difference lies between the TCP/IP stack implementations between Winsock and linux; is there some socket option that I could set to make the linux implementation behave more like Winsock? Is there something else I'm not accounting for?</p> <p>The only solution looks to be to rewrite it so that it sends all the file requests together, then receives them all.</p> <p>Unfortunately, Sony's implementation does not have the TCP_CORK option, so I cannot say if that is the difference.</p>
[ { "answer_id": 319550, "author": "geocar", "author_id": 37507, "author_profile": "https://Stackoverflow.com/users/37507", "pm_score": 2, "selected": false, "text": "TCP_CORK int v,vlen;\nv=1; vlen=sizeof(v);\nsetsockopt(fd, IPPROTO_TCP, TCP_CORK, &v, &vlen);\n v=0 int v,vlen;\nv=0; vlen=sizeof(v);\nsetsockopt(fd, IPPROTO_TCP, TCP_CORK, &v, &vlen);\n writev() sendfile()" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319516", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40877/" ]
319,518
<p>I've got the a SQL Server stored procedure with the following T-SQL code contained within:</p> <pre><code>insert into #results ([ID], [Action], [Success], [StartTime], [EndTime], [Process]) select 'ID' = aa.[ActionID], 'Action' = cast(aa.[Action] as int), 'Success' = aa.[Success], 'StartTime' = aa.[StartTime], 'EndTime' = aa.[EndTime], 'Process' = cast(aa.[Process] as int) from [ApplicationActions] aa with(nolock) where 0 = case when (@loggingLevel = 0) then 0 when (@loggingLevel = 1 and aa.[LoggingLevel] = 1) then 0 end and 1 = case when (@applicationID is null) then 1 when (@applicationID is not null and aa.[ApplicationID] = @applicationID) then 1 end and 2 = case when (@startDate is null) then 2 when (@startDate is not null and aa.[StartTime] &gt;= @startDate) then 2 end and 3 = case when (@endDate is null) then 3 when (@endDate is not null and aa.[StartTime] &lt;= @endDate) then 3 end and 4 = case when (@success is null) then 4 when (@success is not null and aa.[Success] = @success) then 4 end and 5 = case when (@process is null) then 5 when (@process is not null and aa.[Process] = @process) then 5 end </code></pre> <p>It's that "dynamic" WHERE clause that is bothering me. The user doesn't have to pass in every parameter to this stored procedure. Just the ones that they are interested in using as a filter for the output.</p> <p>How would I go about using SQL Server Studio or Profiler to test whether or not this store procedure is recompiling every time?</p>
[ { "answer_id": 319558, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 2, "selected": false, "text": " 2 = case\n when (@startDate is null) then 2\n when (@startDate is not null and aa.[StartTime] >= @startDate) then 2\n end\n (@startDate is null OR aa.[StartTime] >= @startDate)\n WITH RECOMPILE" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319518", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2049/" ]
319,524
<p>I'm looking to generate a random number and issue it to a table in a database for a particular user_id. The catch is, the same number can't be used twice. There's a million ways to do this, but I'm hoping someone very keen on algorithms has a clever way of solving the problem in an elegant solution in that the following criteria is met:</p> <p>1) The least amount of queries to the database are made. 2) The least amount of crawling through a data structure in memory is made.</p> <p>Essentially the idea is to do the following</p> <p>1) Create a random number from 0 to 9999999<br> 2) Check the database to see if the number exists<br> OR<br> 2) Query the database for all numbers<br> 3) See if the returned result matches whatever came from the db<br> 4) If it matches, repeat step 1, if not, problem is solved. </p> <p>Thanks.</p>
[ { "answer_id": 319547, "author": "UnkwnTech", "author_id": 115, "author_profile": "https://Stackoverflow.com/users/115", "pm_score": 1, "selected": false, "text": "<?php\n//Lets assume we already have a connection to the db\n$sql = \"SELECT randField FROM tableName\";\n$result = mysql_query($sql);\n$array = array();\nwhile($row = mysql_fetch_assoc($result))\n {\n $array[] = $row['randField'];\n }\nwhile(True)\n {\n $rand = rand(0, 999999);\n if(!in_array($rand))\n {\n //This number is not in the db so use it!\n break;\n }\n }\n?>\n" }, { "answer_id": 324764, "author": "qualbeen", "author_id": 36975, "author_profile": "https://Stackoverflow.com/users/36975", "pm_score": 1, "selected": false, "text": "$array = range(0, 9999999);\n$numbers = shuffle($array);\n" }, { "answer_id": 324777, "author": "ConcernedOfTunbridgeWells", "author_id": 15401, "author_profile": "https://Stackoverflow.com/users/15401", "pm_score": 1, "selected": false, "text": "X(i) = AX(i-1)|M\n 742,938,285 \n950,706,376 \n1,226,874,159 \n62,089,911 \n1,343,714,438 \n" }, { "answer_id": 9033661, "author": "John Einem", "author_id": 1172905, "author_profile": "https://Stackoverflow.com/users/1172905", "pm_score": 1, "selected": false, "text": "dim array(0 to 9999999) as integer\nfor x% = 1 to 9999999\narray(x%)=x%\nnext x%\nmaxPlus = 10000000\nmax =9999999\npickedrandom =int(Rndfunc*maxPlus) picks a random indext of the array based on \n how many numbers are left\nmaxplus = maxplus-1\nswap array(pickedrandom) , array(max) swap this array value to the current end of the\n array \nmax = max -1 decrement the pointer of the max array value so it \n points to the next lowest place..\n" }, { "answer_id": 32939180, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "seed * seed & p x such that 2x < p p - x * x % p p = 3 mod 4 9999999" }, { "answer_id": 69857587, "author": "Muhammad Ali", "author_id": 10589426, "author_profile": "https://Stackoverflow.com/users/10589426", "pm_score": 0, "selected": false, "text": "<?PHP\n /*set the bigger range if there is huge demand*/\n$n=range(111111,999999);\n\nshuffle($n); //shuffle those\n\nfor ($x=0; $x< 1; $x++) //selects unique random number.\n{\necho $n[$x].' ';\n}\necho \"\\n\"\n\n?>" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40882/" ]
319,527
<p>I have config.time_zone in environment.rb set to "UTC", and my mySQL server returns the current time in my local time zone when I issue "select now();" and in utc when I ask for "select utc_timestamp;"</p> <p>I'm running rails 2.1.2, the mysql gem 2.7.3, activerecord gem 2.1.2, and mysql --version returns "Ver 14.12 Distrib 5.0.27 for Win32 (ia32)". </p> <p>EDIT: My environment.rb is set to UTC and had been since I started the project. A server restart would have picked up no changes.</p> <pre><code>record = Record.find(:first) puts Time.now # Tue Nov 25 17:40:48 -0800 2008 record.time_column = Time.now record.save mysql&gt; select * from records; --------------------- 2008-11-26 01:40:48 #note that this is the same time, in UTC. record = Record.find(:first) puts record.time_column Wed Nov 26 01:40:48 -0800 2008 #NOTE that this is eight hours in advance! #All I've done is store a date in the database and retrieve it again! </code></pre> <p>Any ideas what causes this?</p>
[ { "answer_id": 320263, "author": "Laurent Farcy", "author_id": 40666, "author_profile": "https://Stackoverflow.com/users/40666", "pm_score": 4, "selected": true, "text": "(\"time = %t\", Tue Nov 25 17:40:48 -0800 2008) => \"time = '2008-11-26 01:40:48'\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319527", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30997/" ]
319,530
<p>What does RESTful Authentication mean and how does it work? I can't find a good overview on Google. My only understanding is that you pass the session key (remeberal) in the URL, but this could be horribly wrong.</p>
[ { "answer_id": 7158864, "author": "Arnaud Bouchez", "author_id": 458259, "author_profile": "https://Stackoverflow.com/users/458259", "pm_score": 10, "selected": true, "text": "GET /spec.html HTTP/1.1\nHost: www.example.org\nAuthorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==\n GET /spec.html HTTP/1.1\nHost: www.example.org\nCookie: theme=light; sessionToken=abc123\n GET /resource/1 HTTP/1.1\n Host: example.com\n Authorization: Bearer mF_9.B5f-4.1JqM\n GET /object?apiKey=Qwerty2010\n GET /object?timestamp=1261496500&apiKey=Qwerty2010&signature=abcdef0123456789\n /object?apikey=Qwerty2010&timestamp=1261496500" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319530", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35338/" ]
319,531
<p>For example, I hate typing things like:</p> <pre><code>$x = mysql_escape_string(stripslashes($_GET['x'])); </code></pre> <p>Is there a way to alias those two functions in init.php or something without writing a separate function that takes one argument and returns that argument with those functions applied to it?</p> <p>My C/C++ is not very good, but I think this is sort of like #typedef but for functions?</p>
[ { "answer_id": 319536, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 2, "selected": false, "text": "function myget($string)\n{\n return mysql_real_escape_string(stripslashes($_GET[$string]));\n}\n" }, { "answer_id": 319548, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 0, "selected": false, "text": "class DB\n{ \n public static function escape()\n { \n $args = func_get_args(); \n return call_user_func_array('mysql_real_escape_string', $args ); \n }\n}\n\nDB::escape( $foo ); \n class DB\n{ \n public static function escape($string)\n { \n return mysql_real_escape_string( $string ); \n }\n}\n class DB\n{ \n public static function un_gpc($string)\n {\n if( get_magic_quotes_gpc() === 1 )\n {\n return stripslashes( $string ); \n }\n return $string;\n }\n public static function escape($string, $quote=false)\n {\n if( !$quote )\n { \n return mysql_real_escape_string( $string ); \n }\n return '\"' . self::escape( $string ) . '\"'; \n }\n public static function escape_gpc( $string , $quote = false )\n {\n return self::escape( self::un_gpc( $string ), $quote); \n }\n public static function get( $string , $quote = true )\n { \n return self::escape_gpc( $_GET[$string] , $quote ); \n }\n\n}\n\n# Handy Dandy.\n$q = 'SELECT * FROM FOO WHERE BAR = ' . DB::get( 'bar' ) ; \n" }, { "answer_id": 319555, "author": "Franck", "author_id": 38072, "author_profile": "https://Stackoverflow.com/users/38072", "pm_score": 3, "selected": true, "text": "// Macros\n$mes = \"mysql_escape_string\";\n$ss = \"stripslashes\";\n\n// Using your macros\n$x = $mes($ss($_GET['x']));\n" }, { "answer_id": 319557, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 1, "selected": false, "text": "$newFunc = create_function('', 'return mysql_escape_string(stripslashes($_GET[\\'x\\']));');\n$newFunc();\n" }, { "answer_id": 319570, "author": "staticsan", "author_id": 28832, "author_profile": "https://Stackoverflow.com/users/28832", "pm_score": 3, "selected": false, "text": "stripslashes() magic_quotes_gpc mysql_real_escape_string() prepare execute mysql_escape_string() $x = $_GET['x'];\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319531", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29595/" ]
319,552
<p>I am working on setting up a Drupal based website and wanted to replace the site title in the header with an image file. I came across this article: <a href="http://www.mezzoblue.com/tests/revised-image-replacement/" rel="nofollow noreferrer">"Revised Image Replacement"</a> summarizing several techniques for doing just that.</p> <p>I was wondering what the current best practice is, in terms of SEO and browser compatibility?</p>
[ { "answer_id": 319536, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 2, "selected": false, "text": "function myget($string)\n{\n return mysql_real_escape_string(stripslashes($_GET[$string]));\n}\n" }, { "answer_id": 319548, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 0, "selected": false, "text": "class DB\n{ \n public static function escape()\n { \n $args = func_get_args(); \n return call_user_func_array('mysql_real_escape_string', $args ); \n }\n}\n\nDB::escape( $foo ); \n class DB\n{ \n public static function escape($string)\n { \n return mysql_real_escape_string( $string ); \n }\n}\n class DB\n{ \n public static function un_gpc($string)\n {\n if( get_magic_quotes_gpc() === 1 )\n {\n return stripslashes( $string ); \n }\n return $string;\n }\n public static function escape($string, $quote=false)\n {\n if( !$quote )\n { \n return mysql_real_escape_string( $string ); \n }\n return '\"' . self::escape( $string ) . '\"'; \n }\n public static function escape_gpc( $string , $quote = false )\n {\n return self::escape( self::un_gpc( $string ), $quote); \n }\n public static function get( $string , $quote = true )\n { \n return self::escape_gpc( $_GET[$string] , $quote ); \n }\n\n}\n\n# Handy Dandy.\n$q = 'SELECT * FROM FOO WHERE BAR = ' . DB::get( 'bar' ) ; \n" }, { "answer_id": 319555, "author": "Franck", "author_id": 38072, "author_profile": "https://Stackoverflow.com/users/38072", "pm_score": 3, "selected": true, "text": "// Macros\n$mes = \"mysql_escape_string\";\n$ss = \"stripslashes\";\n\n// Using your macros\n$x = $mes($ss($_GET['x']));\n" }, { "answer_id": 319557, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 1, "selected": false, "text": "$newFunc = create_function('', 'return mysql_escape_string(stripslashes($_GET[\\'x\\']));');\n$newFunc();\n" }, { "answer_id": 319570, "author": "staticsan", "author_id": 28832, "author_profile": "https://Stackoverflow.com/users/28832", "pm_score": 3, "selected": false, "text": "stripslashes() magic_quotes_gpc mysql_real_escape_string() prepare execute mysql_escape_string() $x = $_GET['x'];\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40332/" ]
319,576
<p>I'm trying to make a TCP Client program in C where the client will start up, connect to a server. Then it will send a little information and then just listen to what it receives and react accordingly.</p> <p>The part that I'm having trouble with is the continuous listening. Here is what I have</p> <pre><code>... while (1) { numbytes = recv(sockfd, buf, MAXDATASIZE-1, 0); buf[numbytes] = '\0'; printf("Received: %s\n", buf); // more code to react goes here } ... </code></pre> <p>Upon connecting to the server, after sending two lines of data, the server should receive a good bit of information, but when I run this, it prints:</p> <blockquote> <p>Received:</p> </blockquote> <p>And then continues to just sit there until i force it to close.</p> <p>** EDIT ** when i do what Jonathan told me to do, I get the following:</p> <blockquote> <p>Count: -1, Error: 111, Received:</p> </blockquote> <p>So that means its erroring, but what do i do about it?</p>
[ { "answer_id": 319584, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 3, "selected": true, "text": "while (1) {\n numbytes = recv(sockfd, buf, MAXDATASIZE-1, 0);\n buf[numbytes] = '\\0';\n printf(\"Count: %d, Error: %d, Received: %s\\n\", numbytes, errno, buf);\n // more code to react goes here\n}\n telnet www.microsoft.com 80 hello ENTER HTTP/1.1 400 Bad Request\nContent-Type: text/html; charset=us-ascii\nServer: Microsoft-HTTPAPI/2.0\nDate: Thu, 27 Nov 2008 01:45:09 GMT\nConnection: close\nContent-Length: 326\n\n<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\"\"http://www.w3.org/TR/html4/strict.dtd\">\n<HTML><HEAD><TITLE>Bad Request</TITLE>\n<META HTTP-EQUIV=\"Content-Type\" Content=\"text/html; charset=us-ascii\"></HEAD>\n<BODY><h2>Bad Request - Invalid Verb</h2>\n<hr><p>HTTP Error 400. The request verb is invalid.</p>\n</BODY></HTML>\n" }, { "answer_id": 320865, "author": "Alnitak", "author_id": 6782, "author_profile": "https://Stackoverflow.com/users/6782", "pm_score": 0, "selected": false, "text": "listen()ing accept()ed recv() read() strerror() s = socket();\nerr = listen(s, n); // n = backlog number\nwhile (1) {\n int fd = accept(s, &addr, sizeof(addr));\n while (1) {\n int numrecv = read(fd, ...);\n // break if eof\n }\n close(fd);\n}\nclose(s);\n" }, { "answer_id": 323017, "author": "Nathan Strong", "author_id": 9780, "author_profile": "https://Stackoverflow.com/users/9780", "pm_score": 0, "selected": false, "text": "#define MAX_CONNECTIONS 256\nint main(int argc, char *argv[])\n{\n int i = 0;\n int running = 1;\n int connections[MAX_CONNECTIONS];\n while( running )\n {\n fd_set in_fd, out_fd, exc_fd;\n FD_ZERO(in_fd);\n FD_ZERO(out_fd);\n FD_ZERO(exc_fd);\n for( i = 0; i < MAX_CONNECTIONS; i++ )\n {\n if( connections[i] > 0 )\n {\n FD_SET(&in_fd, connections[i]);\n FD_SET(&out_fd, connections[i]);\n FD_SET(&exc_fd, connections[i]);\n }\n }\n select(&in_fd, &out_fd, &exc_fd, NULL); // this will block until there's an I/O to handle.\n for( i = 0; i < MAX_CONNECTIONS; i++ )\n {\n if( FD_ISSET(&exc_fd, connections[i]) )\n { /* error occurred on this connection; clean up and set connection[i] to 0 */ }\n else\n {\n if( FD_ISSET(&in_fd, connections[i]) )\n { /* handle input */ }\n if( FD_ISSET(&out_fd, connections[i]) )\n { /* handle output */ }\n }\n }\n }\n}\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2128/" ]
319,578
<p>I have an app that I'm writing a little wizard for. It automated a small part of the app by moving the mouse to appropriate buttons, menus and clicking them so the user can watch.</p> <p>So far it moves the mouse to a tree item and sends a right-click. That pops up a menu via TrackPopupMenu. Next I move the mouse to the appropriate item on the popup menu. What I can't figure out is how to select the menu item.</p> <p>I've tried sending left-clicks to the menu's owner window, tried sending WM_COMMAND to the menu's owner, etc. Nothing works.</p> <p>I suppose the menu is a window in and of itself, but I don't know how to get the HWND for it from the HMENU that I have.</p> <p>Any thoughts on how to PostMessage a click to the popup menu?</p> <p>PS I'm using a separate thread to drive the mouse and post messages, so no problems with TrackPopupMenu being synchronous.</p>
[ { "answer_id": 319640, "author": "Rob Kennedy", "author_id": 33732, "author_profile": "https://Stackoverflow.com/users/33732", "pm_score": 1, "selected": false, "text": "SendInput" }, { "answer_id": 326608, "author": "DougN", "author_id": 7442, "author_profile": "https://Stackoverflow.com/users/7442", "pm_score": 3, "selected": true, "text": "//in my case, the menu is a popup from a tree control created with:\nCMenu menu;\nmenu.CreatePopupMenu();\n//add stuff to the menu...\npTreeCtrl->SetMenu(&menu);\nm_hMenu = menu.GetSafeHmenu();\nCPoint pt;\nGetCursorPos(&pt);\nmenu.TrackPopupMenu(TPM_LEFTALIGN | TPM_LEFTBUTTON, pt.x, pt.y, _pTreeCtrl);\nmenu.Detach();\nm_hMenu = NULL;\n CRect rc;\nGetMenuItemRect(pTreeCtrl->GetSafeHwnd(), m_hMenu, targetMenuItemIndex, &rc);\nif(FALSE == rc.IsRectEmpty())\n{\n CPoint target = rc.CenterPoint();\n //this closes the menu\n ::PostMessage(pTreeCtrl->GetSafeHwnd(), WM_CANCELMODE, 0, 0);\n DestroyMenu(m_hMenu);\n m_hMenu = NULL;\n //now simulate the menu click\n ::PostMessage(pTreeCtrl->GetSafeHwnd(), WM_COMMAND, targetMenuItemID, 0);\n}\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7442/" ]
319,587
<p>When using Html.ActionLink passing a string containing the # char renders it like it is but if you UrlEncode it renders as %2523.</p> <p>I believe it's a bug. MVC Beta Release.</p> <p>Is it really a bug?</p> <p><a href="http://example.com/test#" rel="nofollow noreferrer">http://example.com/test#</a> is rendered as </p> <p><a href="http://example.com/test%2523" rel="nofollow noreferrer">http://example.com/test%2523</a> instead of </p> <p><a href="http://example.com/test%2523" rel="nofollow noreferrer">http://example.com/test%2523</a></p>
[ { "answer_id": 319614, "author": "Turnkey", "author_id": 13144, "author_profile": "https://Stackoverflow.com/users/13144", "pm_score": 1, "selected": false, "text": "using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.Web;\n\nnamespace ConsoleApplication1\n{\n class Program\n {\n static void Main(string[] args)\n {\n string hash = \"#\";\n Console.WriteLine(HttpUtility.UrlEncode(hash));\n }\n }\n}\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
319,591
<p>With .net 3.5, there is a SyndicationFeed that will load in a RSS feed and allow you to run LINQ on it. </p> <p>Here is an example of the RSS that I am loading:</p> <pre><code>&lt;rss version="2.0" xmlns:media="http://search.yahoo.com/mrss/"&gt; &lt;channel&gt; &lt;title&gt;Title of RSS feed&lt;/title&gt; &lt;link&gt;http://www.google.com&lt;/link&gt; &lt;description&gt;Details about the feed&lt;/description&gt; &lt;pubDate&gt;Mon, 24 Nov 08 21:44:21 -0500&lt;/pubDate&gt; &lt;language&gt;en&lt;/language&gt; &lt;item&gt; &lt;title&gt;Article 1&lt;/title&gt; &lt;description&gt;&lt;![CDATA[How to use StackOverflow.com]]&gt;&lt;/description&gt; &lt;link&gt;http://youtube.com/?v=y6_-cLWwEU0&lt;/link&gt; &lt;media:player url="http://youtube.com/?v=y6_-cLWwEU0" /&gt; &lt;media:thumbnail url="http://img.youtube.com/vi/y6_-cLWwEU0/default.jpg" width="120" height="90" /&gt; &lt;media:title&gt;Jared on StackOverflow&lt;/media:title&gt; &lt;media:category label="Tags"&gt;tag1, tag2&lt;/media:category&gt; &lt;media:credit&gt;Jared&lt;/media:credit&gt; &lt;enclosure url="http://youtube.com/v/y6_-cLWwEU0.swf" length="233" type="application/x-shockwave-flash"/&gt; &lt;/item&gt; &lt;/channel&gt; </code></pre> <p>When I loop through the items, I can get back the title and the link through the public properties of SyndicationItem.</p> <p>I can't seem to figure out how to get the attributes of the enclosure tag, or the values of the media tags. I tried using </p> <pre><code>SyndicationItem.ElementExtensions.ReadElementExtensions&lt;string&gt;("player", "http://search.yahoo.com/mrss/") </code></pre> <p>Any help with either of these?</p>
[ { "answer_id": 321548, "author": "jr.", "author_id": 2415, "author_profile": "https://Stackoverflow.com/users/2415", "pm_score": 4, "selected": true, "text": "string xml = @\"\n <rss version='2.0' xmlns:media='http://search.yahoo.com/mrss/'> \n <channel> \n <title>Title of RSS feed</title> \n <link>http://www.google.com</link> \n <description>Details about the feed</description> \n <pubDate>Mon, 24 Nov 08 21:44:21 -0500</pubDate> \n <language>en</language> \n <item> \n <title>Article 1</title> \n <description><![CDATA[How to use StackOverflow.com]]></description> \n <link>http://youtube.com/?v=y6_-cLWwEU0</link> \n <media:player url='http://youtube.com/?v=y6_-cLWwEU0' /> \n <media:thumbnail url='http://img.youtube.com/vi/y6_-cLWwEU0/default.jpg' width='120' height='90' /> \n <media:title>Jared on StackOverflow</media:title> \n <media:category label='Tags'>tag1, tag2</media:category> \n <media:credit>Jared</media:credit> \n <enclosure url='http://youtube.com/v/y6_-cLWwEU0.swf' length='233' type='application/x-shockwave-flash'/> \n </item> \n </channel>\n </rss>\n \";\n\n\n\nXElement rss = XElement.Parse( xml );\nXNamespace media = \"http://search.yahoo.com/mrss/\";\n\nvar player = rss.Element( \"channel\" ).Element( \"item\" ).Element(media + \"player\").Attribute( \"url\" );\nplayer.Dump();\n" }, { "answer_id": 321595, "author": "Oppositional", "author_id": 2029, "author_profile": "https://Stackoverflow.com/users/2029", "pm_score": 4, "selected": false, "text": "HttpWebRequest webRequest = WebRequest.Create(\"http://www.pwop.com/feed.aspx?show=dotnetrocks&filetype=master\") as HttpWebRequest;\n\nusing (Stream stream = webRequest.GetResponse().GetResponseStream())\n{\n XmlReaderSettings settings = new XmlReaderSettings();\n settings.IgnoreComments = true;\n settings.IgnoreWhitespace = true;\n\n using(XmlReader reader = XmlReader.Create(stream, settings))\n {\n SyndicationFeed feed = SyndicationFeed.Load(reader);\n\n foreach(SyndicationItem item in feed.Items)\n {\n // Get values of syndication extension elements for a given namespace\n string extensionNamespaceUri = \"http://www.itunes.com/dtds/podcast-1.0.dtd\";\n SyndicationElementExtension extension = item.ElementExtensions.Where<SyndicationElementExtension>(x => x.OuterNamespace == extensionNamespaceUri).FirstOrDefault();\n XPathNavigator dataNavigator = new XPathDocument(extension.GetReader()).CreateNavigator();\n\n XmlNamespaceManager resolver = new XmlNamespaceManager(dataNavigator.NameTable);\n resolver.AddNamespace(\"itunes\", extensionNamespaceUri);\n\n XPathNavigator authorNavigator = dataNavigator.SelectSingleNode(\"itunes:author\", resolver);\n XPathNavigator subtitleNavigator = dataNavigator.SelectSingleNode(\"itunes:subtitle\", resolver);\n XPathNavigator summaryNavigator = dataNavigator.SelectSingleNode(\"itunes:summary\", resolver);\n XPathNavigator durationNavigator = dataNavigator.SelectSingleNode(\"itunes:duration\", resolver);\n\n string author = authorNavigator != null ? authorNavigator.Value : String.Empty;\n string subtitle = subtitleNavigator != null ? subtitleNavigator.Value : String.Empty;\n string summary = summaryNavigator != null ? summaryNavigator.Value : String.Empty;\n string duration = durationNavigator != null ? durationNavigator.Value : String.Empty;\n\n // Get attributes of <enclosure> element\n foreach (SyndicationLink enclosure in item.Links.Where<SyndicationLink>(x => x.RelationshipType == \"enclosure\"))\n {\n Uri url = enclosure.Uri;\n long length = enclosure.Length;\n string mediaType = enclosure.MediaType;\n }\n }\n }\n}\n" }, { "answer_id": 790808, "author": "hitec", "author_id": 120, "author_profile": "https://Stackoverflow.com/users/120", "pm_score": 4, "selected": false, "text": "static void Main(string[] args)\n{\n var feedUrl = \"https://blog.stackoverflow.com/index.php?feed=podcast\";\n\n using (var feedReader = XmlReader.Create(feedUrl))\n {\n var feedContent = SyndicationFeed.Load(feedReader);\n\n if (null == feedContent) return;\n\n foreach (var item in feedContent.Items)\n {\n Debug.WriteLine(\"Item Title: \" + item.Title.Text);\n\n Debug.WriteLine(\"Item Links\");\n foreach (var link in item.Links)\n {\n Debug.WriteLine(\"Link Title: \" + link.Title);\n Debug.WriteLine(\"URI: \" + link.Uri);\n Debug.WriteLine(\"RelationshipType: \" + link.RelationshipType);\n Debug.WriteLine(\"MediaType: \" + link.MediaType);\n Debug.WriteLine(\"Length: \" + link.Length);\n }\n }\n }\n}\n \n" }, { "answer_id": 1768359, "author": "Ron", "author_id": 2293628, "author_profile": "https://Stackoverflow.com/users/2293628", "pm_score": 5, "selected": false, "text": "using System.Linq;\nusing System.ServiceModel.Syndication;\nusing System.Xml;\nusing System.Xml.Linq;\n SyndicationFeed feed = reader.Read();\n\nforeach (var item in feed.Items)\n{\n foreach (SyndicationElementExtension extension in item.ElementExtensions)\n {\n XElement ele = extension.GetObject<XElement>();\n Console.WriteLine(ele.Value);\n }\n}\n" }, { "answer_id": 2960954, "author": "jkade", "author_id": 299443, "author_profile": "https://Stackoverflow.com/users/299443", "pm_score": 4, "selected": false, "text": "private static T GetExtensionElementValue<T>(SyndicationItem item, string extensionElementName)\n{\n return item.ElementExtensions.First(ee => ee.OuterName == extensionElementName).GetObject<T>();\n}\n" }, { "answer_id": 74210819, "author": "PJJ", "author_id": 10270820, "author_profile": "https://Stackoverflow.com/users/10270820", "pm_score": 0, "selected": false, "text": "foreach(var item in feed.Items)\n{\n List<string> urlList = new List<string>();\n foreach(SyndicationElementExtension extension in item.ElementExtensions)\n {\n XElement ele = extension.GetObject<XElement>();\n if( ele.HasAttributes && ele.GetAttribute(\"url\")!=null)\n {\n urlList.Add(ele.GetAttribute(\"url\"));\n }\n }\n //.... store/use item's urlList\n}\n string thumnailUrl = null;\nforeach (SyndicationElementExtension ext in item.ElementExtensions)\n{\n XmlElement ele = ext.GetObject<XmlElement>();\n if (ele.Name == \"media:thumbnail\" && ele.HasAttributes)\n {\n thumnailUrl = ele.GetAttribute(\"url\");\n }\n}\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319591", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24841/" ]
319,594
<p>Given two colors and <em>n</em> steps, how can one calculate n colors including the two given colors that create a fade effect? </p> <p>If possible pseudo-code is preferred but this will probably be implemented in Java.</p> <p>Thanks!</p>
[ { "answer_id": 319604, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 5, "selected": true, "text": "oldRed = 120;\nnewRed = 200;\nsteps = 10;\nredStepAmount = (newRed - oldRed) / steps;\n\ncurrentRed = oldRed;\nfor (i = 0; i < steps; i++) {\n currentRed += redStepAmount;\n}\n" }, { "answer_id": 22796560, "author": "Chris Dolphin", "author_id": 2687479, "author_profile": "https://Stackoverflow.com/users/2687479", "pm_score": 2, "selected": false, "text": "ratio rgbColor2 function fadeToColor(rgbColor1, rgbColor2, ratio) {\n var color1 = rgbColor1.substring(4, rgbColor1.length - 1).split(','),\n color2 = rgbColor2.substring(4, rgbColor2.length - 1).split(','),\n difference,\n newColor = [];\n\n for (var i = 0; i < color1.length; i++) {\n difference = color2[i] - color1[i];\n newColor.push(Math.floor(parseInt(color1[i], 10) + difference * ratio));\n }\n\n return 'rgb(' + newColor + ')';\n}\n" }, { "answer_id": 31376038, "author": "hbk", "author_id": 2012219, "author_profile": "https://Stackoverflow.com/users/2012219", "pm_score": 0, "selected": false, "text": "- (UIColor *)colorFromColor:(UIColor *)fromColor toColor:(UIColor *)toColor percent:(float)percent\n{\n float dec = percent / 100.f;\n CGFloat fRed, fBlue, fGreen, fAlpha;\n CGFloat tRed, tBlue, tGreen, tAlpha;\n CGFloat red, green, blue, alpha;\n\n if(CGColorGetNumberOfComponents(fromColor.CGColor) == 2) {\n [fromColor getWhite:&fRed alpha:&fAlpha];\n fGreen = fRed;\n fBlue = fRed;\n }\n else {\n [fromColor getRed:&fRed green:&fGreen blue:&fBlue alpha:&fAlpha];\n }\n if(CGColorGetNumberOfComponents(toColor.CGColor) == 2) {\n [toColor getWhite:&tRed alpha:&tAlpha];\n tGreen = tRed;\n tBlue = tRed;\n }\n else {\n [toColor getRed:&tRed green:&tGreen blue:&tBlue alpha:&tAlpha];\n }\n\n red = (dec * (tRed - fRed)) + fRed;\n green = (dec * (tGreen - fGreen)) + fGreen;\n blue = (dec * (tBlue - fBlue)) + fBlue;\n alpha = (dec * (tAlpha - fAlpha)) + fAlpha;\n\n return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];\n}\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/868/" ]
319,595
<p>Hi if I am creating something on the stack using new I declare it like:</p> <pre><code>object *myObject = new object(contr, params); </code></pre> <p>Is there a way to declare this such as:</p> <pre><code>object *myObject; myObject = new object(constr, params); </code></pre> <p>Is this correct?</p>
[ { "answer_id": 319602, "author": "SoapBox", "author_id": 36384, "author_profile": "https://Stackoverflow.com/users/36384", "pm_score": 3, "selected": false, "text": "object myObject(constr, params);\n" }, { "answer_id": 319603, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 2, "selected": false, "text": "object myObject(contr,params);\n" }, { "answer_id": 319606, "author": "Mr Fooz", "author_id": 25050, "author_profile": "https://Stackoverflow.com/users/25050", "pm_score": 1, "selected": false, "text": "object myObject(contr, params);\n" }, { "answer_id": 319793, "author": "John Dibling", "author_id": 241536, "author_profile": "https://Stackoverflow.com/users/241536", "pm_score": 0, "selected": false, "text": "object *myObject;\nmyObject = new object(constr, params);\n object *myObject;\n object *myObject = 0;\nmyObject = new object(constr, params);\n delete myObject;\nmyObject = 0;\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319595", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
319,623
<p>void (int a[]) { a[5] = 3; // this is wrong? }</p> <p>Can I do this so that the array that is passed in is modified?</p> <p>Sorry for deleting, a bit new here...</p> <p>I have another question which might answer my question:</p> <p>If I have</p> <pre><code>void Test(int a) { } void Best(int &amp;a) { } </code></pre> <p>are these two statements equivalent?</p> <pre><code>Test(a); Best(&amp;a); </code></pre>
[ { "answer_id": 319663, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 5, "selected": true, "text": "void Test(int a[]) \n{\n a[5] = 3;\n}\n void Test(int* a) \n{\n *(a+5) = 3;\n}\n void Test(int a) \n{\n}\n\nvoid Best(int &a) \n{\n}\n Test(aa); // Passes aa by value. Changes to a in Test() do not effect aa\nBest(aa); // Passes aa by reference; Changes to a DO effect aa\nBest(&aa); // Is a syntax error: Passing a pointer instead of an int.\n" }, { "answer_id": 319723, "author": "Jason Baker", "author_id": 2147, "author_profile": "https://Stackoverflow.com/users/2147", "pm_score": -1, "selected": false, "text": "void foo(int x[500000000000]);\n void foo(SomeClass x);\n void foo(SomeClass &x);\n" }, { "answer_id": 320062, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 0, "selected": false, "text": "int[] int* char* char[] Test Best" }, { "answer_id": 321705, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 0, "selected": false, "text": "#include <iostream>\n\n// Arrays always de-generate to pointers.\nvoid plop(int a[]) // Make sure this function has a name.\n{\n a[5] = 3;\n}\n\nint main()\n{\n int test[] = { 1,1,1,1,1,1,1,1};\n\n plop(test);\n\n std::cout << test[5] << std::endl;\n}\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319623", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
319,626
<p>I have a DataTable that queries out something like below</p> <pre><code>usergroupid...userid......username 1.............1...........John 1.............2...........Lisa 2.............3...........Nathan 3.............4...........Tim </code></pre> <p>What I'm trying to do is write a LINQ statement that will return an array of UserGroup instances. The UserGroup class has properties of UserGroupId and Users. Users is an array of User instances. The User class then has properties of UserId and UserName.</p> <p>Can filling such a hierarchy be done with a single LINQ statement and what would it look like?</p> <p>Thanks a million</p>
[ { "answer_id": 319691, "author": "Rohan West", "author_id": 38686, "author_profile": "https://Stackoverflow.com/users/38686", "pm_score": 4, "selected": true, "text": "var users = new[] \n{\n new {UserGroupId = 1, UserId = 1, UserName = \"John\"},\n new {UserGroupId = 1, UserId = 2, UserName = \"Lisa\"},\n new {UserGroupId = 2, UserId = 3, UserName = \"Nathan\"},\n new {UserGroupId = 3, UserId = 4, UserName = \"Tim\"}\n};\n\nvar userGroups = from user in users \n group user by user.UserGroupId into userGroup \n select new {\n UserGroupId = userGroup.Key, \n Users = userGroup.ToList()\n };\n\nforeach (var group in userGroups)\n{\n Console.WriteLine(\"{0} - {1}\",group.UserGroupId, group.Users.Count);\n}\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8280/" ]
319,634
<p>all files in ~/Cipher/nsdl/crypto can be found <a href="http://nsdeleon.wikispaces.com/file/detail/crypto.zip" rel="nofollow noreferrer">here</a> java files compiled with gcj, see compile.sh</p> <pre><code>nmint@nqmk-mint ~/Cipher/nsdl/crypto $ echo test | ./cryptTest encrypt deadbeefdeadbeefdeadbeefdeadbeef deadbeef Blowfish CBC &gt; test null Exception in thread "main" java.lang.IllegalStateException: cipher is not for encrypting or decrypting at javax.crypto.Cipher.update(libgcj.so.81) at javax.crypto.CipherOutputStream.write(libgcj.so.81) at nsdl.crypto.BlockCrypt.encrypt(cryptTest) at nsdl.crypto.cryptTest.main(cryptTest) </code></pre> <p>BlockCrypt.java: </p> <pre><code>package nsdl.crypto; import java.io.*; import java.security.spec.*; import javax.crypto.*; import javax.crypto.spec.*; public class BlockCrypt { Cipher ecipher; Cipher dcipher; byte[] keyBytes; byte[] ivBytes; SecretKey key; AlgorithmParameterSpec iv; byte[] buf = new byte[1024]; BlockCrypt(String keyStr, String ivStr, String algorithm, String mode) { try { ecipher = Cipher.getInstance(algorithm + "/" + mode + "/PKCS5Padding"); dcipher = Cipher.getInstance(algorithm + "/" + mode + "/PKCS5Padding"); keyBytes = hexStringToByteArray(keyStr); ivBytes = hexStringToByteArray(ivStr); key = new SecretKeySpec(keyBytes, algorithm); iv = new IvParameterSpec(ivBytes); ecipher.init(Cipher.ENCRYPT_MODE, key, iv); dcipher.init(Cipher.DECRYPT_MODE, key, iv); } catch (Exception e) { System.err.println(e.getMessage()); } } public void encrypt(InputStream in, OutputStream out) { try { // out: where the plaintext goes to become encrypted out = new CipherOutputStream(out, ecipher); // in: where the plaintext comes from int numRead = 0; while ((numRead = in.read(buf)) &gt;= 0) { out.write(buf, 0, numRead); } out.close(); } catch (IOException e) { System.err.println(e.getMessage()); } } public void decrypt(InputStream in, OutputStream out) { try { // in: where the plaintext come from, decrypted on-the-fly in = new CipherInputStream(in, dcipher); // out: where the plaintext goes int numRead = 0; while ((numRead = in.read(buf)) &gt;= 0) { out.write(buf, 0, numRead); } out.flush(); out.close(); } catch (IOException e) { System.err.println(e.getMessage()); } } public static byte[] hexStringToByteArray(String s) { int len = s.length(); byte[] data = new byte[len / 2]; for (int i = 0; i &lt; len; i += 2) { data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) &lt;&lt; 4) + Character.digit(s.charAt(i+1), 16)); } return data; } } </code></pre> <p>cryptTest.java: </p> <pre><code>package nsdl.crypto; import nsdl.crypto.BlockCrypt; public class cryptTest { public static void main (String args[]) { if (args.length != 5) { System.err.println("Usage: cryptTest (encrypt|decrypt) key iv algorithm mode"); System.err.println("Takes input from STDIN. Output goes to STDOUT."); } else { String operation = args[0]; String key = args[1]; String iv = args[2]; String algorithm = args[3]; String mode = args[4]; BlockCrypt blockCrypt = new BlockCrypt(key, iv, algorithm, mode); if (operation.equalsIgnoreCase("encrypt")) { blockCrypt.encrypt(System.in, System.out); } else if (operation.equalsIgnoreCase("decrypt")) { blockCrypt.decrypt(System.in, System.out); } else { System.err.println("Invalid operation. Use (encrypt|decrypt)."); } } } } </code></pre>
[ { "answer_id": 320032, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 3, "selected": true, "text": "ecipher IllegalStateException ENCRYPT_MODE catch BlockCrypt System.err System.err.println(e.getMessage()) e.printStackTrace() System.err.println(e) ecipher.init()" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40807/" ]
319,649
<p>I have a database with one table, like so:</p> <pre><code>UserID (int), MovieID (int), Rating (real) </code></pre> <p>The userIDs and movieIDs are large numbers, but my database only has a sample of the many possible values (4000 unique users, and 3000 unique movies)</p> <p>I am going to do a matrix SVD (singular value decomposition) on it, so I want to return this database as an ordered array. Basically, I want to return each user in order, and for each user, return each movie in order, and then return the rating for that user, movie pair, or null if that user did not rate that particular movie. example:</p> <pre><code>USERID | MOVIEID | RATING ------------------------- 99835 8847874 4 99835 8994385 3 99835 9001934 null 99835 3235524 2 . . . 109834 8847874 null 109834 8994385 1 109834 9001934 null etc </code></pre> <p>This way, I can simply read these results into a two dimensional array, suitable for my SVD algorithm. (Any other suggestions for getting a database of info into a simple two dimensional array of floats would be appreciated)</p> <p>It is important that this be returned in order so that when I get my two dimensional array back, I will be able to re-map the values to the respective users and movies to do my analysis.</p>
[ { "answer_id": 319669, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 4, "selected": true, "text": "SELECT m.UserID, m.MovieID, r.Rating\n FROM (SELECT a.userid, b.movieid\n FROM (SELECT DISTINCT UserID FROM Ratings) AS a,\n (SELECT DISTINCT MovieID FROM Ratings) AS b\n ) AS m LEFT OUTER JOIN Ratings AS r\n ON (m.MovieID = r.MovieID AND m.UserID = r.UserID)\n ORDER BY m.UserID, m.MovieID;\n SELECT UserID, MovieID, Rating\n FROM Ratings\n ORDER BY UserID, MovieID;\n" }, { "answer_id": 319717, "author": "John Fouhy", "author_id": 15154, "author_profile": "https://Stackoverflow.com/users/15154", "pm_score": 0, "selected": false, "text": "select userid, movieid, rating\nfrom ratings\norder by userid, movieid\n" }, { "answer_id": 319771, "author": "Amir", "author_id": 40914, "author_profile": "https://Stackoverflow.com/users/40914", "pm_score": 1, "selected": false, "text": "\nselect UserId, FirstName, LastName, MoveId, Name, cast(null as int) as Rating\ninto #FinalResults\nfrom Users\ncross join Movies\n \nupdate #FinalResults\nset Rating = UMR.Rating\nfrom #FinalResults FR\ninner join UserMovieRatings UMR\non FR.UserId = UMR.UserId and FR.MovieId = UMR.MovieId\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319649", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2504/" ]
319,651
<p>I used standard exception handling methods in C++. Which is try{} and catch{} block. In my code, func1() would throw an exception, And func2 is like this:</p> <pre><code>bool func2() { try{ func1(); } catch(myException&amp; e) { cerr &lt;&lt; "error!" &lt;&lt; endl; return false; } return true; } </code></pre> <p>But when I run my code, a strange thing happens. I never reached the code of throwing the exception, but I always reached the line of return false in catch block (but the line of <code>cerr &lt;&lt;</code> is never reached either). Then the function continue to return true. I don't know what the reason is. Can anyone help me to figure the problem out? Thank you very much!</p>
[ { "answer_id": 320279, "author": "CesarB", "author_id": 28258, "author_profile": "https://Stackoverflow.com/users/28258", "pm_score": 2, "selected": false, "text": "bool func2()\n{\n bool ret;\n\n try{\n func1();\n ret = true;\n }\n\n catch(myException& e)\n {\n cerr << \"error!\" << endl;\n ret = false;\n }\n\n return ret;\n}\n return ret; return false; return true; %eax %eax" }, { "answer_id": 321676, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 0, "selected": false, "text": "bool func2()\n{\n try\n {\n func1();\n }\n catch(MyException const& e)\n {\n std::cerr << \"Error!: Cought My Exception\\n\";\n return false;\n }\n catch(...) // Catch any other exceptions\n {\n std::cerr << \"Error!: Unknown Exception detected\\n\";\n /*\n * To keep the same functionality of your original code\n * Rethrow the unknown exception.\n */\n throw;\n }\n return true;\n}\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26404/" ]
319,672
<p>I was using GetWindowLong like this:</p> <pre><code>[DllImport("user32.dll")] private static extern IntPtr GetWindowLong(IntPtr hWnd, int nIndex); </code></pre> <p>But according to the MSDN docs I am supposed to be using GetWindowLongPtr to be 64bit compatible. <a href="http://msdn.microsoft.com/en-us/library/ms633584(VS.85).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms633584(VS.85).aspx</a></p> <p>The MSDN docs for GetWindowLongPtr say that I should define it like this (in C++):</p> <pre><code>LONG_PTR GetWindowLongPtr(HWND hWnd, int nIndex); </code></pre> <p>I used to be using IntPtr as the return type, but what the heck would I use for an equivalent for LONG_PTR? I have also seen GetWindowLong defined as this in C#:</p> <pre><code>[DllImport("user32.dll")] private static extern long GetWindowLong(IntPtr hWnd, int nIndex); </code></pre> <p>What is right, and how can I ensure proper 64bit compatibility?</p>
[ { "answer_id": 319693, "author": "SoapBox", "author_id": 36384, "author_profile": "https://Stackoverflow.com/users/36384", "pm_score": 3, "selected": false, "text": "[DllImport(\"user32.dll\")]\nprivate static extern IntPtr GetWindowLongPtr(IntPtr hWnd, int nIndex);\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319672", "https://Stackoverflow.com", "https://Stackoverflow.com/users/343/" ]
319,696
<p>This is probably pretty basic... but I don't seem to get it:</p> <p>How does </p> <pre><code>(2 &amp; 1) = 0 (3 &amp; 1) = 1 (4 &amp; 1) = 0 </code></pre> <p>etc..</p> <p>This pattern above seems to help find even numbers</p> <p>or </p> <pre><code>(0 | 1) = 1 (1 | 1) = 1 (2 | 1) = 3 (3 | 1) = 4 (4 | 1) = 5 (5 | 1) = 5 </code></pre> <p>I know how boolean algebra works between bits. But I don't understand how Boolean algebra works with integers (in C# at the least).</p> <p>thanks in advance.</p>
[ { "answer_id": 319698, "author": "SoapBox", "author_id": 36384, "author_profile": "https://Stackoverflow.com/users/36384", "pm_score": 3, "selected": false, "text": "2 | 1 = 3 4 | 1 = 5 010 | 001 = 011 100 | 001 = 101 010 & 001 = 000 011 & 001 = 001" }, { "answer_id": 319708, "author": "chromakode", "author_id": 40508, "author_profile": "https://Stackoverflow.com/users/40508", "pm_score": 2, "selected": false, "text": "and 2 & 1 => 010 & 001 = 000 = 0\n3 & 1 => 011 & 001 = 001 = 1\n4 & 1 => 100 & 001 = 000 = 0\n5 & 1 => 101 & 001 = 001 = 1\n or 0 | 1 => 000 | 001 = 001 = 1\n1 | 1 => 001 | 001 = 001 = 1\n2 | 1 => 010 | 001 = 011 = 3\n3 | 1 => 011 | 001 = 011 = 3\n4 | 1 => 100 | 001 = 101 = 5\n5 | 1 => 101 | 001 = 101 = 5\n or 1" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319696", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
319,702
<pre><code>public enum myEnum { VAL1(10), VAL2(20), VAL3("hai") { public Object getValue() { return this.strVal; } public String showMsg() { return "This is your msg!"; } }; String strVal; Integer intVal; public Object getValue() { return this.intVal; } private myEnum(int i) { this.intVal = new Integer(i); } private myEnum(String str) { this.strVal = str; } } </code></pre> <p>In the above enum what exactly happens when I add a constant specific class body for VAL3?<br><br> The type of VAL3 is definetly a subtype of myEnum as it has overloaded and additional methods. (the class type comes as 'myEnum$1' ) <br><br> But how can the compiler creates a subtype enum extending myEnum as all the enums are already extending java.lang.enum ? <br></p>
[ { "answer_id": 320152, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "\npackage com.sun.tools.xjc.outline;\n\n\npublic final class Aspect extends Enum\n{\n public static final Aspect EXPOSED;\n public static final Aspect IMPLEMENTATION;\n private static final Aspect $VALUES[];\n\n static \n {\n EXPOSED = new Aspect(\"EXPOSED\", 0);\n IMPLEMENTATION = new Aspect(\"IMPLEMENTATION\", 1);\n $VALUES = (new Aspect[] {\n EXPOSED, IMPLEMENTATION\n });\n }\n\n public static final Aspect[] values()\n {\n return (Aspect[])$VALUES.clone();\n }\n\n public static Aspect valueOf(String name)\n {\n Aspect arr$[] = $VALUES;\n int len$ = arr$.length;\n for(int i$ = 0; i$ < len$; i$++)\n {\n Aspect aspect = arr$[i$];\n if(aspect.name().equals(name))\n return aspect;\n }\n\n throw new IllegalArgumentException(name);\n }\n\n private Aspect(String s, int i)\n {\n super(s, i);\n }\n\n\n}\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319702", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27784/" ]
319,711
<p>I posted a question earlier today when I'd not zeroed in quite so far on the problem. I'll be able to be more concise here.</p> <p>I'm running RoR 2.1.2, on Windows, with MySQL. The SQL server's native time zone is UTC. My local timezone is Pacific (-0800)</p> <p>I have a model with a :timestamp type column which I can do things like this with:</p> <pre><code>record = Record.find(:first) record.the_time = Time.now() </code></pre> <p>When I do a "select * from records" in the database, the time shown is eight hours in advance of my local time, which is correct, given that the DB is on UTC. (I have verified that it is 'thinking in utc' with a simple 'select now()' and 'select utc_timestamp()')</p> <p>This is where the trouble begins. If I display the time in a view:</p> <pre><code>&lt;%= h record.the_time %&gt; </code></pre> <p>...then I get back the correct time, displayed in UTC format. If I wrote to the database at 16:40:00 local time, the database showed 00:40:00.</p> <p>HOWEVER, if I am running a standalone script:</p> <pre><code>record = Record.find(:first) puts record.the_time </code></pre> <p>...then I get back the UTC time that I stored in the database (00:40:00,) but with the local timezone:</p> <pre><code>Wed Nov 26 00:40:00 (-0800) 2008 </code></pre> <p>...an eight-hour time warp. Why is it that storing the time translates it correctly, but retrieving it does not? If I compare a stored time from the recent past in the DB and compare it to the current time, the current time is less - telling me this isn't just a string conversion issue. </p> <p>Any ideas?</p>
[ { "answer_id": 328157, "author": "mrflip", "author_id": 41857, "author_profile": "https://Stackoverflow.com/users/41857", "pm_score": 1, "selected": false, "text": "# Make Time.zone default to the specified zone, and make Active Record store time values\n# in the database in UTC, and return them converted to the specified local zone.\n# Run \"rake -D time\" for a list of tasks for finding time zone names. Uncomment to use default local time.\nconfig.time_zone = 'UTC'\n require 'active_support/core_ext/date/conversions'\nrecord.the_time.utc.to_s(:db) \n" }, { "answer_id": 333295, "author": "Daniel Lucraft", "author_id": 11951, "author_profile": "https://Stackoverflow.com/users/11951", "pm_score": 1, "selected": false, "text": "active_support" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30997/" ]
319,716
<p>I'm working on a .Net application which uses Asp.net 3.5 and Lucene.Net I am showing search results given by Lucene.Net in an asp.net datagrid. I need to implement Paging (10 records on each page) for this aspx page.</p> <p>How do I get this done using Lucene.Net?</p>
[ { "answer_id": 319770, "author": "David Thibault", "author_id": 5903, "author_profile": "https://Stackoverflow.com/users/5903", "pm_score": 6, "selected": true, "text": "int first = 0, last = 9; // TODO: Set first and last to correct values according to page number and size\nSearcher searcher = new IndexSearcher(YourIndexFolder);\nQuery query = BuildQuery(); // TODO: Implement BuildQuery\nHits hits = searcher.Search(query);\nList<Document> results = new List<Document>();\nfor (int i = first; i <= last && i < hits.Length(); i++)\n results.Add(hits.Doc(i));\n\n// results now contains a page of documents matching the query\n" }, { "answer_id": 320773, "author": "Corey Trager", "author_id": 9328, "author_profile": "https://Stackoverflow.com/users/9328", "pm_score": -1, "selected": false, "text": "void Page_Load(Object sender, EventArgs e)\n{\n\n dbutil = new DbUtil();\n security = new Security();\n security.check_security(dbutil, HttpContext.Current, Security.ANY_USER_OK);\n\n Lucene.Net.Search.Query query = null;\n\n try\n {\n if (string.IsNullOrEmpty(Request[\"query\"]))\n {\n throw new Exception(\"You forgot to enter something to search for...\");\n }\n\n query = MyLucene.parser.Parse(Request[\"query\"]);\n\n }\n catch (Exception e3)\n {\n display_exception(e3);\n }\n\n\n Lucene.Net.Highlight.QueryScorer scorer = new Lucene.Net.Highlight.QueryScorer(query);\n Lucene.Net.Highlight.Highlighter highlighter = new Lucene.Net.Highlight.Highlighter(MyLucene.formatter, scorer);\n highlighter.SetTextFragmenter(MyLucene.fragmenter); // new Lucene.Net.Highlight.SimpleFragmenter(400));\n\n StringBuilder sb = new StringBuilder();\n string guid = Guid.NewGuid().ToString().Replace(\"-\", \"\");\n Dictionary<string, int> dict_already_seen_ids = new Dictionary<string, int>();\n\n sb.Append(@\"\ncreate table #$GUID\n(\ntemp_bg_id int,\ntemp_bp_id int,\ntemp_score float,\ntemp_text nvarchar(3000)\n)\n \");\n\n lock (MyLucene.my_lock)\n {\n\n Lucene.Net.Search.Hits hits = null;\n try\n {\n hits = MyLucene.search(query);\n }\n catch (Exception e2)\n {\n display_exception(e2);\n }\n\n // insert the search results into a temp table which we will join with what's in the database\n for (int i = 0; i < hits.Length(); i++)\n {\n if (dict_already_seen_ids.Count < 100)\n {\n Lucene.Net.Documents.Document doc = hits.Doc(i);\n string bg_id = doc.Get(\"bg_id\");\n if (!dict_already_seen_ids.ContainsKey(bg_id))\n {\n dict_already_seen_ids[bg_id] = 1;\n sb.Append(\"insert into #\");\n sb.Append(guid);\n sb.Append(\" values(\");\n sb.Append(bg_id);\n sb.Append(\",\");\n sb.Append(doc.Get(\"bp_id\"));\n sb.Append(\",\");\n //sb.Append(Convert.ToString((hits.Score(i))));\n sb.Append(Convert.ToString((hits.Score(i))).Replace(\",\", \".\")); // Somebody said this fixes a bug. Localization issue?\n sb.Append(\",N'\");\n\n string raw_text = Server.HtmlEncode(doc.Get(\"raw_text\"));\n Lucene.Net.Analysis.TokenStream stream = MyLucene.anal.TokenStream(\"\", new System.IO.StringReader(raw_text));\n string highlighted_text = highlighter.GetBestFragments(stream, raw_text, 1, \"...\").Replace(\"'\", \"''\");\n if (highlighted_text == \"\") // someties the highlighter fails to emit text...\n {\n highlighted_text = raw_text.Replace(\"'\",\"''\");\n }\n if (highlighted_text.Length > 3000)\n {\n highlighted_text = highlighted_text.Substring(0,3000);\n }\n sb.Append(highlighted_text);\n sb.Append(\"'\");\n sb.Append(\")\\n\");\n }\n }\n else\n {\n break;\n }\n }\n //searcher.Close();\n }\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40907/" ]
319,728
<p>Has anyone ever used the <a href="https://www.dofactory.com/net/bridge-design-pattern" rel="nofollow noreferrer">Bridge pattern</a> in a real world application? If so, how did you use it? Is it me, or is it just the <a href="https://www.dofactory.com/net/adapter-design-pattern" rel="nofollow noreferrer">Adapter pattern</a> with a little dependency injection thrown into the mix? Does it really deserve its own pattern?</p>
[ { "answer_id": 319792, "author": "Dima", "author_id": 13313, "author_profile": "https://Stackoverflow.com/users/13313", "pm_score": 3, "selected": false, "text": "class A\n{\npublic: \n void foo()\n {\n pImpl->foo();\n }\nprivate:\n Aimpl *pImpl;\n};\n\nclass Aimpl\n{\npublic:\n void foo();\n void bar();\n}; \n class A class Aimpl Aimpl::foo() A Aimpl::bar() Aimpl A Aimpl A pImpl Aimpl" }, { "answer_id": 9406293, "author": "John Sonmez", "author_id": 45365, "author_profile": "https://Stackoverflow.com/users/45365", "pm_score": 8, "selected": false, "text": " A\n / \\\n Aa Ab\n / \\ / \\\n Aa1 Aa2 Ab1 Ab2\n A N\n / \\ / \\\nAa(N) Ab(N) 1 2\n" }, { "answer_id": 10689017, "author": "Anton Shchastnyi", "author_id": 593415, "author_profile": "https://Stackoverflow.com/users/593415", "pm_score": 8, "selected": false, "text": " ----Shape---\n / \\\n Rectangle Circle\n / \\ / \\\nBlueRectangle RedRectangle BlueCircle RedCircle\n ----Shape--- Color\n / \\ / \\\nRectangle(Color) Circle(Color) Blue Red\n" }, { "answer_id": 18807213, "author": "NotAgain says Reinstate Monica", "author_id": 1754255, "author_profile": "https://Stackoverflow.com/users/1754255", "pm_score": 3, "selected": false, "text": "#include<iostream>\n#include<string>\n#include<cstdlib>\n\nusing namespace std;\n\nclass IColor\n{\npublic:\n virtual string Color() = 0;\n};\n\nclass RedColor: public IColor\n{\npublic:\n string Color()\n {\n return \"of Red Color\";\n }\n};\n\nclass BlueColor: public IColor\n{\npublic:\n string Color()\n {\n return \"of Blue Color\";\n }\n};\n\n\nclass IShape\n{\npublic:\nvirtual string Draw() = 0;\n};\n\nclass Circle: public IShape\n{\n IColor* impl;\n public:\n Circle(IColor *obj):impl(obj){}\n string Draw()\n {\n return \"Drawn a Circle \"+ impl->Color();\n }\n};\n\nclass Square: public IShape\n{\n IColor* impl;\n public:\n Square(IColor *obj):impl(obj){}\n string Draw()\n {\n return \"Drawn a Square \"+ impl->Color();;\n }\n};\n\nint main()\n{\nIColor* red = new RedColor();\nIColor* blue = new BlueColor();\n\nIShape* sq = new Square(red);\nIShape* cr = new Circle(blue);\n\ncout<<\"\\n\"<<sq->Draw();\ncout<<\"\\n\"<<cr->Draw();\n\ndelete red;\ndelete blue;\nreturn 1;\n}\n Drawn a Square of Red Color\nDrawn a Circle of Blue Color\n" }, { "answer_id": 37514779, "author": "Ravindra babu", "author_id": 4999394, "author_profile": "https://Stackoverflow.com/users/4999394", "pm_score": 5, "selected": false, "text": "Abstraction RefinedAbstraction Implementor ConcreteImplementor The crux of Bridge pattern : /* Implementor interface*/\ninterface Gear{\n void handleGear();\n}\n\n/* Concrete Implementor - 1 */\nclass ManualGear implements Gear{\n public void handleGear(){\n System.out.println(\"Manual gear\");\n }\n}\n/* Concrete Implementor - 2 */\nclass AutoGear implements Gear{\n public void handleGear(){\n System.out.println(\"Auto gear\");\n }\n}\n/* Abstraction (abstract class) */\nabstract class Vehicle {\n Gear gear;\n public Vehicle(Gear gear){\n this.gear = gear;\n }\n abstract void addGear();\n}\n/* RefinedAbstraction - 1*/\nclass Car extends Vehicle{\n public Car(Gear gear){\n super(gear);\n // initialize various other Car components to make the car\n }\n public void addGear(){\n System.out.print(\"Car handles \");\n gear.handleGear();\n }\n}\n/* RefinedAbstraction - 2 */\nclass Truck extends Vehicle{\n public Truck(Gear gear){\n super(gear);\n // initialize various other Truck components to make the car\n }\n public void addGear(){\n System.out.print(\"Truck handles \" );\n gear.handleGear();\n }\n}\n/* Client program */\npublic class BridgeDemo { \n public static void main(String args[]){\n Gear gear = new ManualGear();\n Vehicle vehicle = new Car(gear);\n vehicle.addGear();\n\n gear = new AutoGear();\n vehicle = new Car(gear);\n vehicle.addGear();\n\n gear = new ManualGear();\n vehicle = new Truck(gear);\n vehicle.addGear();\n\n gear = new AutoGear();\n vehicle = new Truck(gear);\n vehicle.addGear();\n }\n}\n Car handles Manual gear\nCar handles Auto gear\nTruck handles Manual gear\nTruck handles Auto gear\n Vehicle Car Truck Vehicle Vehicle addGear() Gear ManualGear AutoGear Gear Vehicle implementor Compositon Car Truck addGear() Gear Manual Auto" }, { "answer_id": 47966065, "author": "sohan kumawat", "author_id": 3829160, "author_profile": "https://Stackoverflow.com/users/3829160", "pm_score": -1, "selected": false, "text": "Bridge design pattern we can easily understand helping of service and dao layer.\n\nDao layer -> create common interface for dao layer ->\npublic interface Dao<T>{\nvoid save(T t);\n}\npublic class AccountDao<Account> implement Dao<Account>{\npublic void save(Account){\n}\n}\npublic LoginDao<Login> implement Dao<Login>{\npublic void save(Login){\n}\n}\nService Layer ->\n1) interface\npublic interface BasicService<T>{\n void save(T t);\n}\nconcrete implementation of service -\nAccount service -\npublic class AccountService<Account> implement BasicService<Account>{\n private Dao<Account> accountDao;\n public AccountService(AccountDao dao){\n this.accountDao=dao;\n }\npublic void save(Account){\n accountDao.save(Account);\n }\n}\nlogin service- \npublic class LoginService<Login> implement BasicService<Login>{\n private Dao<Login> loginDao;\n public AccountService(LoginDao dao){\n this.loginDao=dao;\n }\npublic void save(Login){\n loginDao.save(login);\n }\n}\n\npublic class BridgePattenDemo{\npublic static void main(String[] str){\nBasicService<Account> aService=new AccountService(new AccountDao<Account>());\nAccount ac=new Account();\naService.save(ac);\n}\n}\n}\n" }, { "answer_id": 62143764, "author": "Sylvain Rodrigue", "author_id": 54783, "author_profile": "https://Stackoverflow.com/users/54783", "pm_score": 3, "selected": false, "text": "public class Task {...}\npublic class AccountingTask : Task {...}\npublic class ContractTask : Task {...}\npublic class ClaimTask : Task {...}\n public class EmailAccountingTask : AccountingTask {...}\npublic class FaxAccountingTask : AccountingTask {...}\npublic class EmessagingAccountingTask : AccountingTask {...}\n\npublic class EmailContractTask : ContractTask {...}\npublic class FaxContractTask : ContractTask {...}\npublic class EmessagingContractTask : ContractTask {...}\n\npublic class EmailClaimTask : ClaimTask {...}\npublic class FaxClaimTask : ClaimTask {...}\npublic class EmessagingClaimTask : ClaimTask {...}\n // Source\npublic class Source {\n public string GetSender();\n public string GetMessage();\n public string GetContractReference();\n (...)\n}\n\npublic class EmailSource : Source {...}\npublic class FaxSource : Source {...}\npublic class EmessagingSource : Source {...}\n\n// Task\npublic class Task {\n public Task(Source source);\n (...)\n}\npublic class AccountingTask : Task {...}\npublic class ContractTask : Task {...}\npublic class ClaimTask : Task {...}\n" }, { "answer_id": 72064279, "author": "Maggyero", "author_id": 2326961, "author_profile": "https://Stackoverflow.com/users/2326961", "pm_score": 1, "selected": false, "text": " ------Shape----- Shape Colour\n / \\ Bridge / \\ / \\\n Circle Square -----> Circle Square Red Blue\n / \\ / \\\nRedCircle BlueCircle RedSquare BlueSquare\n ------Shape-----\n / \\\n Circle Square\n / \\ / \\\nRedCircle BlueCircle RedSquare GreenSquare\n Shape\n |\nCircle\n |\nRedCircle\n | Shape | Colour | | Shape | | Colour |\n| ------ | ------ | | ------ | | ------ |\n| circle | red | Bridge | circle | | red |\n| circle | blue | -----> | square | | blue |\n| square | red |\n| square | blue |\n | Shape | Colour |\n| ------ | ------ |\n| circle | red |\n| circle | blue |\n| square | red |\n| square | green |\n | Shape | Colour |\n| ------ | ------ |\n| circle | red |\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7705/" ]
319,730
<p>How can I escape a bracket in a full-text SQL Server <code>contains()</code> query? I've tried all the following, <em>none</em> of which work:</p> <pre><code>CONTAINS(crev.RawText, 'arg[0]') CONTAINS(crev.RawText, 'arg[[0]]') CONTAINS(crev.RawText, 'arg\[0\]') </code></pre> <p>Using double quotes does work, but it <strong>forces the entire search to be a phrase</strong>, which is a showstopper for multiple word queries. </p> <pre><code>CONTAINS(crev.RawText, '"arg[0]"') </code></pre> <p>All I really want to do is escape the bracket, but I can't seem to do that..</p>
[ { "answer_id": 319737, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 2, "selected": false, "text": "LIKE SELECT *\nFROM dbo.stackoverflow_319730\nWHERE txtcol LIKE 'arg[ [ ]0]'\n SELECT *\nFROM dbo.stackoverflow_319730\nWHERE CONTAINS(txtcol, '\"arg[0]\"')\n 'arg[1]' CREATE TABLE [dbo].[stackoverflow_319730](\n [id] [int] IDENTITY(1,1) NOT NULL,\n [txtcol] [text] NOT NULL,\n CONSTRAINT [PK_stackoverflow_319730] PRIMARY KEY CLUSTERED \n(\n [id] ASC\n)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]\n) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]\n\nINSERT INTO [dbo].[stackoverflow_319730] (txtcol) VALUES ('arg[0]')\nINSERT INTO [dbo].[stackoverflow_319730] (txtcol) VALUES ('arg[1]')\nINSERT INTO [dbo].[stackoverflow_319730] (txtcol) VALUES ('some other text')\nINSERT INTO [dbo].[stackoverflow_319730] (txtcol) VALUES ('arg[0], arg[1]')\n\nEXEC sp_fulltext_catalog 'FTCatalog','create'\nEXEC sp_fulltext_table 'stackoverflow_319730', 'create', 'FTCatalog', 'pk_stackoverflow_319730' \nEXEC sp_fulltext_column 'stackoverflow_319730', 'txtcol', 'add' \nEXEC sp_fulltext_table 'stackoverflow_319730','activate' \nEXEC sp_fulltext_catalog 'FTCatalog', 'start_full' \n\nSELECT *\nFROM dbo.stackoverflow_319730\nWHERE txtcol LIKE 'arg[ [ ]0]'\n\nSELECT *\nFROM dbo.stackoverflow_319730\nWHERE CONTAINS(txtcol, '\"arg[0]\"')\n id txtcol\n----------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n1 arg[0]\n\n(1 row(s) affected)\n\nid txtcol\n----------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n1 arg[0]\n2 arg[1]\n4 arg[0], arg[1]\nInformational: The full-text search condition contained noise word(s).\n" }, { "answer_id": 319795, "author": "arcanecode", "author_id": 40912, "author_profile": "https://Stackoverflow.com/users/40912", "pm_score": 4, "selected": true, "text": "CONTAINS('\"word1\" or \"word2\" or \"word3\"')\n CONTAINS('\"word1\" and \"word2\" and \"word3\"')\n CONTAINS('shifting and \"on or off-road\"') \n CONTAINS('shifting ~ smooth')\n CONTAINS('shifting NEAR smooth')\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1/" ]
319,732
<p>I have a .NET 2.0 server that seems to be running into scaling problems, probably due to poor design of the socket-handling code, and I am looking for guidance on how I might redesign it to improve performance.</p> <p><strong>Usage scenario:</strong> 50 - 150 clients, high rate (up to 100s / second) of small messages (10s of bytes each) to / from each client. Client connections are long-lived - typically hours. (The server is part of a trading system. The client messages are aggregated into groups to send to an exchange over a smaller number of 'outbound' socket connections, and acknowledgment messages are sent back to the clients as each group is processed by the exchange.) OS is Windows Server 2003, hardware is 2 x 4-core X5355. </p> <p><strong>Current client socket design:</strong> A <code>TcpListener</code> spawns a thread to read each client socket as clients connect. The threads block on <code>Socket.Receive</code>, parsing incoming messages and inserting them into a set of queues for processing by the core server logic. Acknowledgment messages are sent back out over the client sockets using async <code>Socket.BeginSend</code> calls from the threads that talk to the exchange side.</p> <p><strong>Observed problems:</strong> As the client count has grown (now 60-70), we have started to see intermittent delays of up to 100s of milliseconds while sending and receiving data to/from the clients. (We log timestamps for each acknowledgment message, and we can see occasional long gaps in the timestamp sequence for bunches of acks from the same group that normally go out in a few ms total.) </p> <p>Overall system CPU usage is low (&lt; 10%), there is plenty of free RAM, and the core logic and the outbound (exchange-facing) side are performing fine, so the problem seems to be isolated to the client-facing socket code. There is ample network bandwidth between the server and clients (gigabit LAN), and we have ruled out network or hardware-layer problems.</p> <p>Any suggestions or pointers to useful resources would be greatly appreciated. If anyone has any diagnostic or debugging tips for figuring out exactly what is going wrong, those would be great as well.</p> <p><em>Note: I have the MSDN Magazine article <a href="http://msdn2.microsoft.com/en-us/magazine/cc300760.aspx" rel="noreferrer">Winsock: Get Closer to the Wire with High-Performance Sockets in .NET</a>, and I have glanced at the Kodart "XF.Server" component - it looks sketchy at best.</em></p>
[ { "answer_id": 319806, "author": "Luke Quinane", "author_id": 18437, "author_profile": "https://Stackoverflow.com/users/18437", "pm_score": 2, "selected": false, "text": "Socket.BeginConnect Socket.BeginAccept ConnectEx AcceptEx BeginConnect" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3776/" ]
319,736
<p>I using GWT and have created a login form. I've tried all sorts of ways to get IE7 to prompt to remember the login info but with no success. I thought that maybe this would have worked (but it didn't):</p> <pre><code> TextBox submit = new TextBox(); submit.getElement().setAttribute("type", "submit"); </code></pre> <p>Any ideas?</p>
[ { "answer_id": 325772, "author": "Drejc", "author_id": 6482, "author_profile": "https://Stackoverflow.com/users/6482", "pm_score": 2, "selected": false, "text": "private TextBox mName = new TextBox();\nprivate PasswordTextBox mPassword = new PasswordTextBox();\n\nmName.setText(\"username\");\nmPassword.setText(\"password\");\n public static String getLastLoginName()\n{ \n return Cookies.getCookie(LAST_LOGIN_COOKIE);\n}\n\npublic static void setLastLoginName(String userName)\n{\n Cookies.setCookie(LAST_LOGIN_COOKIE, userName);\n}\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319736", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
319,741
<p>Here is pseudo-code of how I setup an array representing the MandelBrot set, yet it becomes horribly stretched when leaving an aspect ratio of 1:1.</p> <pre><code>xStep = (maxX - minX) / width; yStep = (maxY - minY) / height; for(i = 0; i &lt; width; i++) for(j = 0; j &lt; height; j++) { constantReal = minReal + xStep * i; constantImag = minImag + yStep * j; image[i][j] = inSet(constantReal, constantImag); } </code></pre> <p>Thanks!</p>
[ { "answer_id": 319750, "author": "Ned Batchelder", "author_id": 14343, "author_profile": "https://Stackoverflow.com/users/14343", "pm_score": 0, "selected": false, "text": "image image[j][i] =" }, { "answer_id": 319818, "author": "Federico A. Ramponi", "author_id": 18770, "author_profile": "https://Stackoverflow.com/users/18770", "pm_score": 4, "selected": true, "text": "xStep = (maxX - minX) / width;\nyStep = (maxY - minY) / height;\n width maxX - minX\n---------- = ---------------------\n height maxY - minY\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319741", "https://Stackoverflow.com", "https://Stackoverflow.com/users/868/" ]
319,748
<p>I have tried to use ASP.NET MVC for a while, then I face a problem that I don't want to include all of my js and css in master page. But how can I register it in head of master page from my specific view?</p>
[ { "answer_id": 322517, "author": "sliderhouserules", "author_id": 31385, "author_profile": "https://Stackoverflow.com/users/31385", "pm_score": 4, "selected": true, "text": "<head runat=\"server\">\n <title></title>\n <asp:ContentPlaceHolder ID=\"head\" runat=\"server\" />\n</head>\n <asp:Content ID=\"Content1\" ContentPlaceHolderID=\"head\" runat=\"server\">\n <script src=\"Scripts/myScripts.js\" type=\"text/javascript\"></script>\n <link href=\"Styles/myStyles.css\" rel=\"stylesheet\" type=\"text/css\" />\n</asp:Content>\n" }, { "answer_id": 734820, "author": "Jason", "author_id": 7391, "author_profile": "https://Stackoverflow.com/users/7391", "pm_score": 3, "selected": false, "text": "private static SortedList<int, string> GetRegisteredScriptIncludes()\n{\n var registeredScriptIncludes = System.Web.HttpContext.Current.Items[\"RegisteredScriptIncludes\"] as SortedList<int, string>;\n\n if (registeredScriptIncludes == null)\n {\n registeredScriptIncludes = new SortedList<int, string>();\n System.Web.HttpContext.Current.Items[\"RegisteredScriptIncludes\"] = registeredScriptIncludes;\n }\n\n return registeredScriptIncludes;\n}\n\npublic static void RegisterScriptInclude(this HtmlHelper htmlhelper, string script)\n{\n var registeredScriptIncludes = GetRegisteredScriptIncludes();\n if (!registeredScriptIncludes.ContainsValue(script))\n {\n registeredScriptIncludes.Add(registeredScriptIncludes.Count, script);\n }\n}\n\npublic static string RenderScripts(this HtmlHelper htmlhelper)\n{\n var registeredScriptIncludes = GetRegisteredScriptIncludes();\n var scripts = new StringBuilder();\n foreach (string script in registeredScriptIncludes.Values)\n {\n scripts.AppendLine(\"<script src='\" + script + \"' type='text/javascript'></script>\");\n }\n return scripts.ToString();\n}\n <%\n Html.RegisterScriptInclude(Url.Content(\"~/Scripts/MapLayers/MapLayer.js\"));\n Html.RegisterScriptInclude(Url.Content(\"~/Scripts/MapLayers/Vehicles.js\"));\n%>\n <%=Html.RenderScripts() %>\n" }, { "answer_id": 1767298, "author": "Matthew M. Osborn", "author_id": 5235, "author_profile": "https://Stackoverflow.com/users/5235", "pm_score": 0, "selected": false, "text": "1.<head>\n2. <title><asp:ContentPlaceHolder ID=\"TitleContent\" runat=\"server\" /></title>\n3. <%= Html.Css(\"BlueTheme/site.css\") %>\n4. <%= Html.Script(\"jquery-1.3.2.js\") %>\n5.</head>\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35700/" ]
319,752
<p>We have a C# windows application that needs to be able to connect to a server on a network, download and save a file to a specified location. We can not use a web service as we can not assume that our clients will have IIS on their server. </p> <p>The way that I am considering doing it is to FTP onto the server and download the file. I can write the code to connect to the server and located the file but I have 2 questions. </p> <ol> <li><p>Is there a way of using the windows credentials to FTP on to the remote server? (I understand that I cannot directly get the user's password).</p></li> <li><p>Is there a better way of getting the file from a server other than ftp-ing on to it?</p></li> </ol> <p>Thanks for the advice. </p>
[ { "answer_id": 322517, "author": "sliderhouserules", "author_id": 31385, "author_profile": "https://Stackoverflow.com/users/31385", "pm_score": 4, "selected": true, "text": "<head runat=\"server\">\n <title></title>\n <asp:ContentPlaceHolder ID=\"head\" runat=\"server\" />\n</head>\n <asp:Content ID=\"Content1\" ContentPlaceHolderID=\"head\" runat=\"server\">\n <script src=\"Scripts/myScripts.js\" type=\"text/javascript\"></script>\n <link href=\"Styles/myStyles.css\" rel=\"stylesheet\" type=\"text/css\" />\n</asp:Content>\n" }, { "answer_id": 734820, "author": "Jason", "author_id": 7391, "author_profile": "https://Stackoverflow.com/users/7391", "pm_score": 3, "selected": false, "text": "private static SortedList<int, string> GetRegisteredScriptIncludes()\n{\n var registeredScriptIncludes = System.Web.HttpContext.Current.Items[\"RegisteredScriptIncludes\"] as SortedList<int, string>;\n\n if (registeredScriptIncludes == null)\n {\n registeredScriptIncludes = new SortedList<int, string>();\n System.Web.HttpContext.Current.Items[\"RegisteredScriptIncludes\"] = registeredScriptIncludes;\n }\n\n return registeredScriptIncludes;\n}\n\npublic static void RegisterScriptInclude(this HtmlHelper htmlhelper, string script)\n{\n var registeredScriptIncludes = GetRegisteredScriptIncludes();\n if (!registeredScriptIncludes.ContainsValue(script))\n {\n registeredScriptIncludes.Add(registeredScriptIncludes.Count, script);\n }\n}\n\npublic static string RenderScripts(this HtmlHelper htmlhelper)\n{\n var registeredScriptIncludes = GetRegisteredScriptIncludes();\n var scripts = new StringBuilder();\n foreach (string script in registeredScriptIncludes.Values)\n {\n scripts.AppendLine(\"<script src='\" + script + \"' type='text/javascript'></script>\");\n }\n return scripts.ToString();\n}\n <%\n Html.RegisterScriptInclude(Url.Content(\"~/Scripts/MapLayers/MapLayer.js\"));\n Html.RegisterScriptInclude(Url.Content(\"~/Scripts/MapLayers/Vehicles.js\"));\n%>\n <%=Html.RenderScripts() %>\n" }, { "answer_id": 1767298, "author": "Matthew M. Osborn", "author_id": 5235, "author_profile": "https://Stackoverflow.com/users/5235", "pm_score": 0, "selected": false, "text": "1.<head>\n2. <title><asp:ContentPlaceHolder ID=\"TitleContent\" runat=\"server\" /></title>\n3. <%= Html.Css(\"BlueTheme/site.css\") %>\n4. <%= Html.Script(\"jquery-1.3.2.js\") %>\n5.</head>\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26300/" ]
319,762
<p>I am trying to use this in my page class. I only just started using objects in PHP so I'm still a little clueless (but learning as much as I can). This is in my <code>page()</code> function (so called when there is a new instance of page)</p> <pre><code>set_error_handler('$this-&gt;appendError'); </code></pre> <p>This is causing an error</p> <blockquote> <p>Warning: set_error_handler() expects the argument (appendError) to be a valid callback</p> </blockquote> <p>Now how do I set a class internal function whilst passing the function as a string. Is this not possible? Should I use a normal function which then calls the class function and sends through all arguments? This sounds a little cumbersome to me.</p> <p>Or have I missed the problem? I've tried making my appendError return a string, and echo.. but it still isn't playing nice.</p> <p>Any help would be greatly appreciated.</p> <p>Thank you!!</p>
[ { "answer_id": 319786, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 1, "selected": false, "text": "// Type 3: Object method call\n$obj = new MyClass();\ncall_user_func(array($obj, 'myCallbackMethod'));\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31671/" ]
319,764
<p>I'm using (GNU) Make in my project. I'm currently putting one makefile per directory and specify the subdirectories using SUBDIRS. It's been suggested to me that this is not the ideal way of using make, that using a one toplevel make file (or several, split up using include). I've tried migrating/using this layout in the past, but it appears to me that it's unnecessary complicated.</p> <p>Which are the benefits/drawbacks of using recursive makefiles?</p>
[ { "answer_id": 320527, "author": "JesperE", "author_id": 13051, "author_profile": "https://Stackoverflow.com/users/13051", "pm_score": 6, "selected": true, "text": " main: CFLAGS=-O2\n lib: CFLAGS=-O2 -g\n" }, { "answer_id": 5893381, "author": "Kramer", "author_id": 125368, "author_profile": "https://Stackoverflow.com/users/125368", "pm_score": 3, "selected": false, "text": "$LIBS = libfoo libbar\n$(LIBS):\n cd $@ && $(MAKE)\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14337/" ]
319,765
<p>Is there any way other than using reflection to access the members of a anonymous inner class?</p>
[ { "answer_id": 319953, "author": "Ivan Dubrov", "author_id": 31118, "author_profile": "https://Stackoverflow.com/users/31118", "pm_score": 3, "selected": false, "text": "public class Test {\n public static void main(String... args) {\n class MyInner {\n private int value = 10;\n }\n\n MyInner inner = new MyInner();\n System.out.println(inner.value);\n }\n}\n MyInner java.lang.Object" }, { "answer_id": 320106, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "\npublic class AccessAnonymous {\n private Runnable runnable; // to have instance of the class\n\n public static void main(String[] args) throws Exception {\n AccessAnonymous a = new AccessAnonymous();\n a.a(); // init field\n\n Class clazz = a.runnable.getClass();\n Field field = clazz.getDeclaredField(\"i\");\n field.setAccessible(true);\n\n int int1 = field.getInt(a.runnable);\n System.out.println(\"int1=\" + int1);\n }\n\n public void a() {\n runnable = new Runnable() {\n private int i = 1;\n\n public void run() {\n i = 90;\n }\n\n };\n runnable.run();// change value\n }\n}\n" }, { "answer_id": 320426, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 4, "selected": true, "text": "final AtomicInteger y = new AtomicInteger();\nnew Runnable() {\n int x;\n {\n x = 5;\n doRun(this);\n y.set(x);\n }\n public void run() {\n ... blah ...\n }\n};\n final int y = new Runnable() {\n int x;\n {\n x = 5;\n doRun(this);\n }\n public void run() {\n ... blah ...\n }\n}.x;\n <T extends Runnable> T doRun(T runnable);\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27784/" ]
319,788
<p>I am using Zend_Db to insert some data inside a transaction. My function starts a transaction and then calls another method that also attempts to start a transaction and of course fails(I am using MySQL5). So, the question is - how do I detect that transaction has already been started? Here is a sample bit of code:</p> <pre><code> try { Zend_Registry::get('database')-&gt;beginTransaction(); $totals = self::calculateTotals($Cart); $PaymentInstrument = new PaymentInstrument; $PaymentInstrument-&gt;create(); $PaymentInstrument-&gt;validate(); $PaymentInstrument-&gt;save(); Zend_Registry::get('database')-&gt;commit(); return true; } catch(Zend_Exception $e) { Bootstrap::$Log-&gt;err($e-&gt;getMessage()); Zend_Registry::get('database')-&gt;rollBack(); return false; } </code></pre> <p>Inside PaymentInstrument::create there is another beginTransaction statement that produces the exception that says that transaction has already been started. </p>
[ { "answer_id": 319844, "author": "Sean McSomething", "author_id": 39413, "author_profile": "https://Stackoverflow.com/users/39413", "pm_score": 2, "selected": false, "text": "SELECT @@autocommit" }, { "answer_id": 319939, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 5, "selected": false, "text": "$db->query('START TRANSACTION') commit() commit() $transDepth commit() rollback() $transDepth beginTransaction() commit() beginTransaction()" }, { "answer_id": 17645646, "author": "Gregory Magarshak", "author_id": 467460, "author_profile": "https://Stackoverflow.com/users/467460", "pm_score": 0, "selected": false, "text": "wrapper.php:\n\ntry {\n // start transaction\n include(\"your_script.php\");\n // commit transaction\n} catch (RollbackException $e) {\n // roll back transaction\n}\n" }, { "answer_id": 29049300, "author": "Dens", "author_id": 3375045, "author_profile": "https://Stackoverflow.com/users/3375045", "pm_score": 1, "selected": false, "text": "try {\n Zend_Registry::get('database')->beginTransaction();\n} \ncatch (Exception $e) { }\n\ntry {\n $totals = self::calculateTotals($Cart);\n\n $PaymentInstrument = new PaymentInstrument;\n $PaymentInstrument->create();\n $PaymentInstrument->validate();\n $PaymentInstrument->save();\n\n Zend_Registry::get('database')->commit();\n return true;\n} \ncatch (Zend_Exception $e) {\n Bootstrap::$Log->err($e->getMessage());\n Zend_Registry::get('database')->rollBack();\n return false;\n}\n" }, { "answer_id": 31231025, "author": "curlyhairedgenius", "author_id": 1154453, "author_profile": "https://Stackoverflow.com/users/1154453", "pm_score": 1, "selected": false, "text": "SELECT * FROM INFORMATION_SCHEMA.INNODB_TRX WHERE TRX_MYSQL_THREAD_ID = CONNECTION_ID();\n" }, { "answer_id": 43152871, "author": "Zac Imboden", "author_id": 398517, "author_profile": "https://Stackoverflow.com/users/398517", "pm_score": 0, "selected": false, "text": "function transBegin(){\n //increment our number of levels\n $this->_transBegin += 1;\n //if we are only one level deep, we can create transaction\n if($this->_transBegin ==1) {\n $this->db->trans_begin();\n }\n}\n\nfunction transCommit(){\n if($this->_transBegin == 1) {\n //if we are only one level deep, we can commit transaction\n $this->db->trans_commit();\n }\n //decrement our number of levels\n $this->_transBegin -= 1;\n\n}\n\nfunction transRollback(){\n if($this->_transBegin == 1) {\n //if we are only one level deep, we can roll back transaction\n $this->db->trans_rollback();\n }\n //decrement our number of levels\n $this->_transBegin -= 1;\n}\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319788", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35520/" ]
319,789
<p>Sorry if this is basic but I was trying to pick up on .Net 3.5.</p> <p>Question: Is there anything great about Func&lt;> and it's 5 overloads? From the looks of it, I can still create a similar delgate on my own say, MyFunc&lt;> with the exact 5 overloads and even more.</p> <p>eg: <code>public delegate TResult MyFunc&lt;TResult&gt;()</code> and a combo of various overloads...</p> <p>The thought came up as I was trying to understand Func&lt;> delegates and hit upon the following scenario:</p> <pre><code>Func&lt;int,int&gt; myDelegate = (y) =&gt; IsComposite(10); </code></pre> <p>This implies a delegate with one parameter of type int and a return type of type int. There are five variations (if you look at the overloads through intellisense). So I am guessing that we can have a delegate with no return type?</p> <p>So am I justified in saying that Func&lt;> is nothing great and just an example in the .Net framework that we can use and if needed, create custom "func&lt;>" delegates to suit our own needs?</p> <p>Thanks,</p>
[ { "answer_id": 319803, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 4, "selected": false, "text": "Func Action Func delegate Foo Foo(Foo f)" }, { "answer_id": 319920, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": false, "text": "Action System" }, { "answer_id": 319929, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 6, "selected": false, "text": "System.Threading.ThreadStart System.Action" }, { "answer_id": 3114687, "author": "ZXX", "author_id": 374835, "author_profile": "https://Stackoverflow.com/users/374835", "pm_score": 3, "selected": false, "text": "class Session ( \n public delegate string CleanBody(); // tying you up and you don't see it :-)\n public static void Execute(string name, string q, CleanBody body) ... \n public static void Execute(string name, string q, Func<string> body)\n Type type = Type.GetType(\"Bla.Session, FooSessionDll\", true); \nMethodInfo methodInfo = type.GetMethod(\"Execute\"); \n\nFunc<string> d = delegate() { .....} // see Ma - no tie-ups :-)\nObject [] params = { \"foo\", \"bar\", d};\nmethodInfo.Invoke(\"Trial Execution :-)\", params);\n" }, { "answer_id": 8696658, "author": "Luis Perez", "author_id": 984780, "author_profile": "https://Stackoverflow.com/users/984780", "pm_score": 1, "selected": false, "text": "string FormatName(string pFirstName, string pLastName) {\n Func<string, string> MakeFirstUpper = (pText) => {\n return pText.Substring(0,1).ToUpper() + pText.Substring(1);\n };\n\n return MakeFirstUpper(pFirstName) + \" \" + MakeFirstUpper(pLastName);\n}\n Func<T, TReturn> Lambda<T, TReturn>(Func<T, TReturn> pFunc) {\n return pFunc;\n}\n string FormatName(string pFirstName, string pLastName) {\n var MakeFirstUpper = Lambda((string pText) => {\n return pText.Substring(0,1).ToUpper() + pText.Substring(1);\n });\n\n return MakeFirstUpper(pFirstName) + \" \" + MakeFirstUpper(pLastName);\n}\n Console.WriteLine(FormatName(\"luis\", \"perez\"));\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319789", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
319,809
<p>escaping html is fine - it will remove <code>&lt;</code>'s and <code>&gt;</code>'s etc. </p> <p>ive run into a problem where i am outputting a filename inside a comment tag eg. <code>&lt;!-- ${filename} --&gt;</code></p> <p>of course things can be bad if you dont escape, so it becomes: <code>&lt;!-- &lt;c:out value="${filename}"/&gt; --&gt;</code></p> <p>the problem is that if the file has "--" in the name, all the html gets screwed, since youre not allowed to have <code>&lt;!-- -- --&gt;</code>. </p> <p>the standard html escape doesnt escape these dashes, and i was wondering if anyone is familiar with a simple / standard way to escape them. </p>
[ { "answer_id": 319830, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 0, "selected": false, "text": "[HYPHEN]" }, { "answer_id": 320753, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 0, "selected": false, "text": "<!-- 'my-string' -->\n <!-- 'Bob\\x27s\\x2D\\x2Dstring' -->\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319809", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18582/" ]
319,811
<p>Does anyone have an example AUTORUN.INF which can launch an MSI installer automatically when the user inserts the CD.</p> <p>I'm sure this can be done but I've been Googling around for ages and have not found any working solution.</p> <p><strong>UPDATE:</strong> I have an AUTORUN.INF similar to this but it won't launch the installer:</p> <pre><code>[autorun] open=MyInstaller-1.0.0.msi label=My CD Label icon=MyIcon.ico </code></pre>
[ { "answer_id": 319837, "author": "Adam Pierce", "author_id": 5324, "author_profile": "https://Stackoverflow.com/users/5324", "pm_score": 1, "selected": false, "text": "[autorun]\nshellexecute=MyInstaller-1.0.0.msi\nlabel=My CD Label\nicon=MyIcon.ico\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5324/" ]
319,814
<p>Could someone please point me toward a cleaner method to generate a random enum member. This works but seems ugly.</p> <p>Thanks!</p> <pre><code>public T RandomEnum&lt;T&gt;() { string[] items = Enum.GetNames(typeof( T )); Random r = new Random(); string e = items[r.Next(0, items.Length - 1)]; return (T)Enum.Parse(typeof (T), e, true); } </code></pre>
[ { "answer_id": 319826, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 6, "selected": true, "text": "public T RandomEnum<T>()\n{ \n T[] values = (T[]) Enum.GetValues(typeof(T));\n return values[new Random().Next(0,values.Length)];\n}\n" }, { "answer_id": 319842, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 4, "selected": false, "text": "Next(0,values.Length) private Random rand = new Random();\npublic T RandomEnum<T>()\n{ \n T[] values = (T[]) Enum.GetValues(typeof(T));\n return values[rand.Next(0,values.Length)];\n}\n" }, { "answer_id": 319875, "author": "BCS", "author_id": 1343, "author_profile": "https://Stackoverflow.com/users/1343", "pm_score": 0, "selected": false, "text": "enum A {b=0,c=2,d=3,e=42};\n\nswitch(rand.Next(0,4))\n{\n case 0: return A.b;\n case 1: return A.c;\n case 2: return A.d;\n case 3: return A.e;\n}\n" }, { "answer_id": 1910455, "author": "pixie", "author_id": 232454, "author_profile": "https://Stackoverflow.com/users/232454", "pm_score": 2, "selected": false, "text": "private Random rnd = new Random();\n\npublic T RndEnum<T>()\n{\n FieldInfo[] fields = typeof(T).GetFields(BindingFlags.Static | BindingFlags.Public);\n\n int index = rnd.Next(fields.Length);\n\n return (T) Enum.Parse(typeof(T), fields[index].Name, false);\n}\n" }, { "answer_id": 8737103, "author": "Alex", "author_id": 1131272, "author_profile": "https://Stackoverflow.com/users/1131272", "pm_score": 0, "selected": false, "text": "Enum.Parse(typeof(SomeEnum), mRandom.Next(min, max).ToString()).ToString()\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10178/" ]
319,835
<p>Scott Gu just posted about a new set of charting controls being distributed by the .NET team. They look incredible: <a href="http://weblogs.asp.net/scottgu/archive/2008/11/24/new-asp-net-charting-control-lt-asp-chart-runat-quot-server-quot-gt.aspx" rel="noreferrer">http://weblogs.asp.net/scottgu/archive/2008/11/24/new-asp-net-charting-control-lt-asp-chart-runat-quot-server-quot-gt.aspx</a></p> <p>The million dollar question is ... will they work with MVC, and if so, when?</p>
[ { "answer_id": 320891, "author": "Simon Steele", "author_id": 4591, "author_profile": "https://Stackoverflow.com/users/4591", "pm_score": 8, "selected": true, "text": "Chart chart = new Chart();\nchart.BackColor = Color.Transparent;\nchart.Width = Unit.Pixel(250);\nchart.Height = Unit.Pixel(100);\n\nSeries series1 = new Series(\"Series1\");\nseries1.ChartArea = \"ca1\";\nseries1.ChartType = SeriesChartType.Pie;\nseries1.Font = new Font(\"Verdana\", 8.25f, FontStyle.Regular);\nseries1.Points.Add(new DataPoint { \n AxisLabel = \"Value1\", YValues = new double[] { value1 } });\nseries1.Points.Add(new DataPoint {\n AxisLabel = \"Value2\", YValues = new double[] { value2 } });\nchart.Series.Add(series1);\n\nChartArea ca1 = new ChartArea(\"ca1\");\nca1.BackColor = Color.Transparent;\nchart.ChartAreas.Add(ca1);\n\nusing (var ms = new MemoryStream())\n{\n chart.SaveImage(ms, ChartImageFormat.Png);\n ms.Seek(0, SeekOrigin.Begin);\n\n return File(ms.ToArray(), \"image/png\", \"mychart.png\");\n}\n <controls>\n ...\n <add tagPrefix=\"asp\"\n namespace=\"System.Web.UI.DataVisualization.Charting\"\n assembly=\"System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"/>\n</controls>\n\n<httpHandlers>\n ...\n <add path=\"ChartImg.axd\"\n verb=\"GET,HEAD\"\n validate=\"false\"\n type=\"System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\" />\n</httpHandlers>\n\n<handlers>\n ...\n <add name=\"ChartImageHandler\"\n preCondition=\"integratedMode\" \n verb=\"GET,HEAD\"\n path=\"ChartImg.axd\"\n type=\"System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"/>\n</handlers>\n /{Controller}/ChartImg.axd public static void RegisterRoutes(RouteCollection routes)\n{\n routes.IgnoreRoute(\"ChartImg.axd/{*pathInfo}\");\n routes.IgnoreRoute(\"{controller}/ChartImg.axd/{*pathInfo}\");\n routes.IgnoreRoute(\"{controller}/{action}/ChartImg.axd/{*pathInfo}\");\n...\n" }, { "answer_id": 2708061, "author": "Carl Hörberg", "author_id": 80589, "author_profile": "https://Stackoverflow.com/users/80589", "pm_score": 1, "selected": false, "text": "<%@ Control Language=\"C#\" Inherits=\"System.Web.Mvc.ViewUserControl<System.Web.UI.DataVisualization.Charting.Chart>\" %>\n<%\n Model.Page = this.Page;\n var writer = new HtmlTextWriter(Page.Response.Output);\n Model.RenderControl(writer);\n%>\n public ActionResult Chart(){\n var c = new Chart();\n //...\n return View(c);\n}\n <% Html.RenderPartial(\"Chart\", Model); %>\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319835", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34133/" ]
319,847
<p>In a program to find whether the given number is an <a href="http://en.wikipedia.org/wiki/Narcissistic_number" rel="nofollow noreferrer">Armstrong</a> number, I stored the input no (3 digit) as string as follows.</p> <pre><code>char input[10]; scanf("%s",&amp;input); </code></pre> <p>Now I have to calculate cube of each digit by using pow method of math.h as follows.</p> <pre><code>int a; a = pow(input[0],3); </code></pre> <p>By coding like this, I could not get correct result. If I print the value of "a", it shows some irrelevant answer. My doubt is, how to convert from string value to integer value? </p>
[ { "answer_id": 319854, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 1, "selected": false, "text": "input &input input scanf(\"%s\", input);\n scanf(\"%s\", &input[0]);\n" }, { "answer_id": 319856, "author": "Adam Pierce", "author_id": 5324, "author_profile": "https://Stackoverflow.com/users/5324", "pm_score": 3, "selected": false, "text": "int digit = input[0] - '0';\n\nint a; a = pow(digit, 3);\n" }, { "answer_id": 319883, "author": "Stefan Mai", "author_id": 13257, "author_profile": "https://Stackoverflow.com/users/13257", "pm_score": 2, "selected": false, "text": "scanf(\"%s\", input);\n a = pow(input[0]-'0',3);\n" }, { "answer_id": 319889, "author": "Ömer", "author_id": 40929, "author_profile": "https://Stackoverflow.com/users/40929", "pm_score": 0, "selected": false, "text": "char input[10];\nint power, sum = 0;\n\nscanf(\"%s\", input);\npower = strlen(input);\nsum += pow(input[0] - '0', power);\n\n/* you need to compare in here */\n" }, { "answer_id": 319949, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 0, "selected": false, "text": "int inputNumber;\nscanf(\"%d\", &inputNumber);\n int a = pow(input[0], 3);\n input[0] - '0'" }, { "answer_id": 320019, "author": "unwind", "author_id": 28169, "author_profile": "https://Stackoverflow.com/users/28169", "pm_score": 0, "selected": false, "text": "#include <stdio.h>\n#include <stdlib.h>\n\nint main(void)\n{\n int a, sum, i;\n\n printf(\"Enter an Armstrong number, an integer in the range 100..999:\\n\");\n if(scanf(\"%d\", &a) != 1)\n return EXIT_FAILURE;\n if(a < 100 || a > 999)\n return EXIT_FAILURE;\n\n /* Now extract digits, and compute sum of cubes. */\n for(sum = i = 0; i < 3; i++)\n {\n sum += pow(a % 10, 3);\n a /= 10;\n }\n printf(\"sum is: %d\\n\", sum);\n return EXIT_SUCCESS;\n}\n" }, { "answer_id": 320849, "author": "luke", "author_id": 25920, "author_profile": "https://Stackoverflow.com/users/25920", "pm_score": 1, "selected": false, "text": "int isArmstrong(int n, int b)\n{\n int sum = 0;\n int n2 = n;\n int nDigits = 0;\n while(n2 != 0)\n {\n nDigits++;\n n2 /= b;\n }\n n2 = n;\n for(int i = 0; i < nDigits; i+++)\n {\n sum += pow(n2 % b, nDigits);\n n2 /= b;\n }\n\n return sum == n;\n}\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
319,873
<p>I have a table with some duplicate rows. I want to modify only the duplicate rows as follows.</p> <p>Before:</p> <pre><code>id col1 ------------ 1 vvvv 2 vvvv 3 vvvv </code></pre> <p>After:</p> <pre><code>id col1 ------------ 1 vvvv 2 vvvv-2 3 vvvv-3 </code></pre> <p>Col1 is appended with a hyphen and the value of <code>id</code> column.</p>
[ { "answer_id": 319928, "author": "Dheer", "author_id": 17266, "author_profile": "https://Stackoverflow.com/users/17266", "pm_score": 2, "selected": false, "text": "IN update table1 set\ncol1 = col1 || id\nwhere\nid not in (\nselect min(id) from table1\ngroupby col1\n)\n" }, { "answer_id": 320275, "author": "Berzerk", "author_id": 37599, "author_profile": "https://Stackoverflow.com/users/37599", "pm_score": 3, "selected": false, "text": "update tbl\n set col1 = col1 + '-' + convert(varchar, id)\n where exists(select * from tbl t where t.col1 = tbl.col1 and t.id < tbl.id)\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319873", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
319,879
<p>I have two strings</p> <pre><code>&lt;EM&gt;is &lt;i&gt;love&lt;/i&gt;&lt;/EM&gt;,&lt;PARTITION /&gt; </code></pre> <p>and</p> <pre><code>&lt;EM&gt;is &lt;i&gt;love&lt;/i&gt;,&lt;PARTITION /&gt; </code></pre> <p>I want a regex to match the second string completely but should not match the first one. Please help.</p> <p>Note: Everything can change except the EM and PARTITION tags.</p>
[ { "answer_id": 319978, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 0, "selected": false, "text": "^<EM>(?:(?<!</EM>).)*<PARTITION />$\n ^<EM>.*<PARTITION />$ </EM>" }, { "answer_id": 320235, "author": "Jan Goyvaerts", "author_id": 33358, "author_profile": "https://Stackoverflow.com/users/33358", "pm_score": 1, "selected": false, "text": "if (Regex.IsMatch(subjectString, \"</EM>\")) {\n return null;\n} else {\n return subjectString;\n} \n if (subjectString.Contains(\"</EM>\")) {\n return null;\n} else {\n return subjectString;\n} \n \\A((?!</EM>).)*\\Z\n" }, { "answer_id": 325220, "author": "shabby", "author_id": 40570, "author_profile": "https://Stackoverflow.com/users/40570", "pm_score": 1, "selected": true, "text": "<EM>\\w*\\s*\\W*\\S*[^\\(</EM>)]<PARTITION[ ]/>\n </EM>" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40570/" ]
319,880
<p>Suppose <code>a</code> and <code>b</code> are both of type <code>int</code>, and <code>b</code> is nonzero. Consider the result of performing <code>a/b</code> in the following cases:</p> <ol> <li><code>a</code> and <code>b</code> are both nonnegative.</li> <li><code>a</code> and <code>b</code> are both negative.</li> <li>Exactly one of them is negative.</li> </ol> <p>In Case 1 the result is rounded down to the nearest integer. But what does the standard say about Cases 2 and 3? An old draft I found floating on the Internet indicates that it is implementation dependent (yes, even case 2) but the committee is leaning toward making it always 'round toward zero.' Does anyone know what the (latest) standard says? Please answer only based on the standard, not what makes sense, or what particular compilers do.</p>
[ { "answer_id": 8137586, "author": "Sjoerd", "author_id": 396551, "author_profile": "https://Stackoverflow.com/users/396551", "pm_score": 5, "selected": false, "text": "a%b a" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
319,893
<p>I am using gravatar to load avatars for each user that posts a story on a page. I also am using jquery to round the corners of some span elements on the page. Unfortunately, it looks like grabbing the avatars from gravatar occurs before the jquery effects are applied (Without the gravatar code the elements are immediately rounded) so the elements change in appearance an instant after being visible on the site. Is there any way to work around this? (I am using asp.net mvc)</p>
[ { "answer_id": 15237259, "author": "Maksym Kozlenko", "author_id": 171847, "author_profile": "https://Stackoverflow.com/users/171847", "pm_score": 0, "selected": false, "text": " $(\"form\").on(\"submit\", function(e) {\n e.preventDefault();\n\n $.ajax(\"http://en.gravatar.com/\" + md5($(\"#email\").val()) + \".json\", { dataType: \"jsonp\" })\n .done(function(result) { \n for(var idx in result.entry)\n {\n var profile = result.entry[idx];\n console.log(profile);\n $(\"#displayName\").text(profile.displayName);\n $(\"#avatar\").attr(\"src\", profile.thumbnailUrl);\n }\n }).fail(function(result) { console.log(\"fail\", arguments); });\n\n\n });\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319893", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15059/" ]
319,894
<p>Many of our customers have access to InstallShield, WISE or AdminStudio. These aren't a problem. I'm hoping there is some way I can provide our smaller customers <strong>without access to commercial repackaging tools</strong> a freely available set of tools and steps to do the file replacement themselves.</p> <p>Only need to replace a single configuration file inside a compressed MSI, the target user can be assumed to already have Orca installed, know how to use this to customize the Property table (to embed license details for GPO deployment) and have generated an MST file.</p> <p><br><br> <strong>Disclaimer</strong>: <em>this is very similar to <a href="https://stackoverflow.com/questions/126562/how-to-replace-a-file-in-a-msi-installer">another question</a> but both questions and answers in that thread are not clear.</em></p>
[ { "answer_id": 519092, "author": "saschabeaumont", "author_id": 592, "author_profile": "https://Stackoverflow.com/users/592", "pm_score": 4, "selected": true, "text": "Option Explicit\n\nConst MY_CONFIG = \"MyConfigApp.xml\"\nConst CAB_FILE = \"config.cab\"\nConst MSI = \"MyApp.msi\"\n\nDim filesys : Set filesys=CreateObject(\"Scripting.FileSystemObject\")\n\nIf filesys.FileExists(\"temp.tmp\") Then filesys.DeleteFile(\"temp.tmp\")\nfilesys.CopyFile MSI, \"temp.tmp\"\n\nDim installer, database, database2, view\nSet installer = CreateObject(\"WindowsInstaller.Installer\")\nSet database = installer.OpenDatabase (\"temp.tmp\", 1)\nSet database2 = installer.OpenDatabase (MSI, 1)\n\nIf Not filesys.FileExists(MY_CONFIG) Then WScript.Quit 2 ' No config file, abort!\n\nDim objFile, size, result, seq, objCab\n\n' MakeCab object has been depreciated so we fallback to makecab.exe for with Windows 7\nOn Error Resume Next ' Disable error handling, for a moment\nSet objCab = CreateObject(\"MakeCab.MakeCab.1\") \nOn Error Goto 0 ' Turn error handling back on\n\nIf IsObject(objCab) Then ' Object creation successful - use XP method \n objCab.CreateCab CAB_FILE, False, False, False\n objCab.AddFile MY_CONFIG, filesys.GetFileName(MY_CONFIG)\n objCab.CloseCab\n Set objCab = Nothing\nElse ' object creation failed - try Windows 7 method\n Dim WshShell, oExec\n Set WshShell = CreateObject(\"WScript.Shell\")\n Set oExec = WshShell.Exec(\"makecab \" & filesys.GetFileName(MY_CONFIG) & \" \" & CAB_FILE)\nEnd If\n\nSet objFile = filesys.GetFile(MY_CONFIG)\nsize = objFile.Size\n\nSet view = database.OpenView (\"SELECT LastSequence FROM Media WHERE DiskId = 1\")\nview.Execute\nSet result = view.Fetch\nseq = result.StringData(1) + 1 ' Sequence for new configuration file\n\nSet view = database.OpenView (\"INSERT INTO Media (DiskId, LastSequence, Cabinet) VALUES ('2', '\" & seq & \"', '\" & CAB_FILE & \"')\")\nview.Execute\n\nSet view = database.OpenView (\"UPDATE File SET FileSize = \" & size & \", Sequence = \" & seq & \", FileName = 'MYC~2.CNF|MyConfigApp.xml' WHERE File = '\" & MY_CONFIG & \"'\")\nview.Execute\n\ndatabase.GenerateTransform database2, \"CustomConfig.mst\"\ndatabase.CreateTransformSummaryInfo database2, \"CustomConfig.mst\", 0, 0\nfilesys.DeleteFile(\"temp.tmp\")\n\nSet view = nothing\nSet installer = nothing\nSet database = nothing\nSet database2 = nothing\nSet filesys = Nothing\nWScript.Quit 0\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319894", "https://Stackoverflow.com", "https://Stackoverflow.com/users/592/" ]
319,896
<p>using jython</p> <p>I have a situation where emails come in with different attachments. Certain file types I process others I ignore and dont write to file. I am caught in a rather nasty situation, because sometimes people send an email as an attachment, and that attached email has legal attachments. </p> <p>What I want to do is skip that attached email and all its attachments.</p> <p>using python/jythons std email lib how can i do this?</p> <hr> <p>to make it clearer</p> <p>I need to parse an email (named ROOT email), I want to get the attachments from this email using jython. Next certain attachments are supported ie .pdf .doc etc now it just so happens that, the clients send an email (ROOT email) with another email message (CHILD email) as an attachment, and in CHILD email it has .pdf attachments and such like.</p> <p>What I need is: to get rid of any CHILD emails attached to the ROOT email AND the CHILD emails attachments. What happens is I walk over the whole email and it just parses every attachment, BOTH ROOT attachments and CHILD attachments as if they were ROOT attachments.</p> <p>I cannot have this. I am only interested in ROOT attachements that are legal ie .pdf .doc. xls .rtf .tif .tiff</p> <p>That should do for now, I have to run to catch a bus! thanks!</p>
[ { "answer_id": 320093, "author": "bortzmeyer", "author_id": 15625, "author_profile": "https://Stackoverflow.com/users/15625", "pm_score": 0, "selected": false, "text": "import email\n...\nmsg = email.message_from_file(fp)\n...\nfor part in msg.walk():\n # multipart/* are just containers\n if part.get_content_maintype() == 'multipart':\n continue\n # Applications should really sanitize the given filename so that an\n # email message can't be used to overwrite important files\n filename = part.get_filename()\n if not filename:\n ext = mimetypes.guess_extension(part.get_content_type())\n ...\n" }, { "answer_id": 320301, "author": "Harley Holcombe", "author_id": 1057, "author_profile": "https://Stackoverflow.com/users/1057", "pm_score": 0, "selected": false, "text": "mimetypes.guess_type() def check(self, msg):\n import mimetypes\n\n for part in msg.walk():\n if part.get_filename() is not None:\n filenames = [n for n in part.getaltnames() if n]\n for filename in filenames:\n type, enc = mimetypes.guess_type(filename)\n if type.startswith('message'):\n print \"This is an email and I want to ignore it.\"\n else:\n print \"I want to keep looking at this file.\"\n def check(self, msg):\n import mimetypes\n\n for part in msg.walk():\n filename = part.get_filename()\n if filename is not None:\n type, enc = mimetypes.guess_type(filename)\n if type.startswith('message'):\n print \"This is an email and I want to ignore it.\"\n else:\n part_filenames = [n for n in part.getaltnames() if n]\n for part_filename in part_filenames:\n print \"I want to keep looking at this file.\"\n" }, { "answer_id": 321134, "author": "jmanning2k", "author_id": 1480, "author_profile": "https://Stackoverflow.com/users/1480", "pm_score": 3, "selected": true, "text": "if msg.is_multipart():\n for part in msg.get_payload():\n \"\"\" Process message, but do not recurse \"\"\"\n filename = part.get_filename()\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319896", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21537/" ]
319,899
<p>Suppose I have a text file with data separated by whitespace into columns. I want to write a shell script which takes as input a filename and a number N and prints out only that column. With awk I can do the following:</p> <pre><code>awk &lt; /tmp/in '{print $2}' &gt; /tmp/out </code></pre> <p>This code prints out the second column. </p> <p>But how would one wrap that in a shell script so that a arbitrary column could be passed in argv?</p>
[ { "answer_id": 319914, "author": "strager", "author_id": 39992, "author_profile": "https://Stackoverflow.com/users/39992", "pm_score": 3, "selected": false, "text": "awk '{print $'$myvar'}' < /tmp/in > /tmp/out\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39584/" ]
319,900
<p>I am going to spend 30 minutes teaching Perl to an experienced programmer. The best way to learn Perl is by writing code. In addition to CPAN, what would you show a programmer so they would understand the expressiveness of Perl, the amount of functionality provided by CPAN, while keeping everything clean and tidy so they walk away comfortable with the language? I'll save the tricky stuff for another day. </p> <pre> use warnings; use strict; # use A_CPAN_LIB; sub example_func1 { # use the CPAN lib or demonstrate some basic feature of Perl } example_func1(); # ... __END__ </pre> <p><hr> Here's what I came up with...<br></p> <h2>Where to Start</h2> <p>Believe it or not, the man pages. Ok, we'll just use perldoc instead to be Windows friendly.</p> <p>The perldoc pages (or man pages on Unix/Mac) are excellent for Perl. You can type man perl or perldoc perl</p> <p><strong>perldoc perl</strong>; # Show an overview and dozens of tutorials; man perl is the same.<br></p> <p><strong>perldoc perlintro</strong>; # A Perl intro for beginners; man perlintro<br> <strong>perldoc perlrequick</strong>; # An example Perl regex tutoral<br></p> <p><strong>perldoc perlfunc</strong>; # Shows builtin Perl functions<br> <strong>perldoc perlre</strong>; # More Perl regex.<br></p> <h2>CPAN</h2> <p>There are thousands of libraries on the Perl library site CPAN.<br> <strong>perl -MCPAN -e 'install DateTime'</strong><br></p> <p>perldoc works for installed modules too: perldoc module<br></p> <p><strong>perldoc DateTime</strong><br> <strong>perldoc DBI</strong>; # Database API. If this doesn't work then install it:<br> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<strong>perl -MCPAN -e 'install DBI'</strong></p> <h2>Recommended Modules</h2> <p><strong>perl -MCPAN -e 'install Moose'</strong>; # Perl does OOP<br> <strong>perldoc Moose</strong>; # Tell me more about the Moose<br> <strong>perl -MCPAN -e 'install CGI'</strong>; # Quick and dirty web pages<br> <strong>perl -MCPAN -e 'install Catalyst'</strong>; # Big web framework. Sometimes have problems installing. Google is your friend<br> <strong>perl -MCPAN -e 'install CGI::Application'</strong>; # Another web framework<br> <strong>perldoc CGI::Application</strong>; # Take a quick look at the docs<br> <br> A little Q&amp;A.<br> <br> Q: Why should I use Perl instead Ruby or Python?<br> A: More people use Perl. There are more libraries for Perl(way more). Perl is a really great GTD language.<br> <br> Q: Why do people hate Perl?<br> A: You can do some ugly stuff with it. Remember use warnings; use strict; in all of your code. You can check your code before running it. <strong>perl -c</strong> hello.pl<br></p> <p><br></p> <h2>Perl Topics</h2> <h3>Using Perl with Databases</h3> <p><a href="http://www.perl.com/pub/a/1999/10/DBI.html" rel="nofollow noreferrer"><a href="http://www.perl.com/pub/a/1999/10/DBI.html" rel="nofollow noreferrer">http://www.perl.com/pub/a/1999/10/DBI.html</a></a> <br></p> <h3>Using Perl for Web Development</h3> <p><a href="http://www.catalystframework.org" rel="nofollow noreferrer"><a href="http://www.catalystframework.org" rel="nofollow noreferrer">http://www.catalystframework.org</a></a> <br></p> <h3>OO Perl</h3> <p><a href="http://www.iinteractive.com/moose" rel="nofollow noreferrer"><a href="http://www.iinteractive.com/moose" rel="nofollow noreferrer">http://www.iinteractive.com/moose</a></a> <br></p> <h3>Perl 1-Liners</h3> <p><a href="http://www.perlmonks.org/?node_id=470397" rel="nofollow noreferrer"><a href="http://www.perlmonks.org/?node_id=470397" rel="nofollow noreferrer">http://www.perlmonks.org/?node_id=470397</a></a><br> <a href="http://sial.org/howto/perl/one-liner" rel="nofollow noreferrer"><a href="http://sial.org/howto/perl/one-liner" rel="nofollow noreferrer">http://sial.org/howto/perl/one-liner</a></a> <br></p> <h3>Other Tutorials</h3> <p><a href="http://perlmonks.org/index.pl?node=Tutorials" rel="nofollow noreferrer"><a href="http://perlmonks.org/index.pl?node=Tutorials" rel="nofollow noreferrer">http://perlmonks.org/index.pl?node=Tutorials</a></a></p> <h2>Books</h2> <p>There are dozens.<br> <a href="http://www.amazon.com/s/ref=nb_ss_gw?url=search-alias%3Dstripbooks&amp;field-keywords=perl&amp;x=0&amp;y=0" rel="nofollow noreferrer">http://www.amazon.com/s/ref=nb_ss_gw?url=search-alias%3Dstripbooks&amp;field-keywords=perl&amp;x=0&amp;y=0</a><br> <br></p> <h2>Websites</h2> <p><a href="http://perlmonks.com" rel="nofollow noreferrer">Perlmonks</a><br> <a href="http://www.perl.org" rel="nofollow noreferrer">Perl.org</a><br> <a href="http://pleac.sourceforge.net" rel="nofollow noreferrer">Pleac</a><br> <a href="https://stackoverflow.com/questions/161872/hidden-features-of-perl">StackOverFlow's Hidden Features of Perl</a><br> <a href="http://www.cpan.org/misc/cpan-faq.html" rel="nofollow noreferrer">CPAN FAQ</a><br> <a href="http://www.stonehenge.com/merlyn/LinuxMag" rel="nofollow noreferrer">Randall Schwartz's articles</a><br> <br> <br></p> <h2>Getting Help</h2> <p><a href="http://www.nabble.com/Perl-f13578.html" rel="nofollow noreferrer">Perl Nabble Forum</a><br> IRC Channels: freenode, irc.perl.org. There are several:<br> <br> irc://irc.perl.org/perl<br> irc://irc.perl.org/catalyst<br> irc://irc.freenode.net/modperl<br> irc://irc.perl.org/perl6<br></p>
[ { "answer_id": 319956, "author": "zoul", "author_id": 17279, "author_profile": "https://Stackoverflow.com/users/17279", "pm_score": 2, "selected": false, "text": "-d:DProf dprofpp __DATA__" }, { "answer_id": 321642, "author": "Brad Gilbert", "author_id": 1337, "author_profile": "https://Stackoverflow.com/users/1337", "pm_score": 2, "selected": false, "text": "xml JSON use strict;\nuse warnings;\n\nuse JSON;\nuse XML::Simple;\n\nmy $data;\n{\n open( my $file, '<', 'filename.xml' ) or die;\n $data = XMLin($file);\n close $file;\n}\n{\n open( my $file, '>', 'filename.json' ) or die;\n print $file to_json( $data );\n close $file;\n}\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319900", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
319,923
<p>I'm looking for a way to upload a file to s3. I am using django. I am currently using amazon's python library for uploading along with the following code: </p> <p>View:</p> <pre><code>def submitpicture(request): fuser = request.session["login"] copied_data = request.POST.copy() copied_data.update(request.FILES) content_type = copied_data['file'].get('content-type') ffile = copied_data['file']['content'] key = '%s-%s' % (fuser, ''.join(copied_data['file']['filename'].split(' '))) site_s3.save_s3_data(key, ffile, content_type) </code></pre> <p>Template:</p> <pre><code>&lt;form action="/submitpicture/" method="POST"&gt; &lt;input type="file" id="file" name="file" /&gt; &lt;input type="submit" value="submit" /&gt; &lt;/form&gt; </code></pre> <p>However, when I actually try to run it i get the following error:</p> <pre><code>"Key 'file' not found in &lt;QueryDict: {}&gt;" #MultiValueDictKeyError </code></pre> <p>I really don't see what I'm doing wrong. Can someone point me in the right direction?</p> <p>Edit: Just in case someone wonders, I am planning on adding some validation after I get the actual upload working. </p>
[ { "answer_id": 319943, "author": "ayaz", "author_id": 23191, "author_profile": "https://Stackoverflow.com/users/23191", "pm_score": 5, "selected": true, "text": "<form action=\"/submitpicture/\" method=\"POST\" enctype=\"multipart/form-data\" >\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23695/" ]
319,925
<p>I am in the process of writing a text editor. After looking at other text editors I have noticed that a number of them refer to a "soft" versus "hard" wrap. What is the difference? I can't seem to find the answer by searching.</p>
[ { "answer_id": 319996, "author": "Will Robertson", "author_id": 4161, "author_profile": "https://Stackoverflow.com/users/4161", "pm_score": 4, "selected": false, "text": "diff" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319925", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18091/" ]
319,936
<p>How do I connect to the database(MYSQL) in connection bean using JSF to retrieve its contents. Also please let me know how do I configure the web.xml file?</p>
[ { "answer_id": 355514, "author": "Warrior", "author_id": 40933, "author_profile": "https://Stackoverflow.com/users/40933", "pm_score": 3, "selected": true, "text": "public void open() {\n try {\n String databaseName = \"custom\";\n String userName = \"root\";\n String password = \"welcome\";\n\n // \n String url = \"jdbc:mysql://localhost/\" + databaseName;\n\n Class.forName(\"com.mysql.jdbc.Driver\").newInstance();\n connection = DriverManager.getConnection(url, userName, password);\n } catch (Exception e) {\n System.out.println(\"Not able to connect\");\n }\n }\n <dependency>\n <groupId>groupId = mysql</groupId>\n\n <artifactId>mysql-connector-java</artifactId>\n <version>5.1.6</version>\n</dependency> \n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40933/" ]
319,950
<p>i want to create a number of databases in ms-access using a code or any option of ms-access, but i want delete databases also. Please help me</p>
[ { "answer_id": 320351, "author": "Berzerk", "author_id": 37599, "author_profile": "https://Stackoverflow.com/users/37599", "pm_score": 2, "selected": false, "text": " Set fso = CreateObject(\"scripting.filesystemobject\")\n fso.CopyFile \"c:\\db.mdb\", \"c:\\db_copy1.mdb\", True\n fso.CopyFile \"c:\\db.mdb\", \"c:\\db_copy2.mdb\", True\n fso.CopyFile \"c:\\db.mdb\", \"c:\\db_copy3.mdb\", True\n fso.DeleteFile \"c:\\db.mdb\"\n" }, { "answer_id": 321972, "author": "Philippe Grondier", "author_id": 11436, "author_profile": "https://Stackoverflow.com/users/11436", "pm_score": 1, "selected": false, "text": "createDatabase \"myNewMDB.mdb\", dbLangGeneral\n kill \"myNewMDB.mdb\"\n public Function createDeleteDatabase(howManyDatabases as integer) as boolean\n\n''output is by default False\ncreateDeleteDatabase = False\n\non error goto createDeleteDatabase_Error\n\nDim i as integer\nFor i = 1 to howManyDatabases\n createDatabase \"myMDBNumber_\" & str(i,0) & \".mdb\", dbLangGeneral\nNext i\nFor i = 1 to howManyDatabases\n kill \"myMDBNumber_\" & str(i,0) & \".mdb\"\nNext i\n\n''if no errors in the fonction, set the output to True\ncreateDeleteDatabase = True\n\nExit function\ncreateDeleteDatabase_Error:\n'' your error treatment\nEnd function\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
319,973
<p>I would like to use Linq to query a bus schedule in my project, so that at any time I can get the next 5 bus arrival times. How can I limit my query to the first 5 results?</p> <p>More generally, how can I take a slice of a list in C#? (In Python I would use <code>mylist[:5]</code> to get the first 5 elements.)</p>
[ { "answer_id": 319976, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 11, "selected": true, "text": "var firstFiveItems = myList.Take(5);\n var secondFiveItems = myList.Skip(5).Take(5);\n var firstFiveArrivals = myList.OrderBy(i => i.ArrivalTime).Take(5);\n" }, { "answer_id": 320055, "author": "netadictos", "author_id": 31791, "author_profile": "https://Stackoverflow.com/users/31791", "pm_score": 6, "selected": false, "text": "myList.Sort(CLASS_FOR_COMPARER);\nList<string> fiveElements = myList.GetRange(0, 5);\n" }, { "answer_id": 320074, "author": "Valera Kolupaev", "author_id": 29300, "author_profile": "https://Stackoverflow.com/users/29300", "pm_score": 2, "selected": false, "text": "var firstFiveArrivals = myList.Where([EXPRESSION]).Take(5); var firstFiveArrivals = myList.Where([EXPRESSION]).Take(5).OrderBy([ORDER EXPR]); class MyList : IEnumerable<int>\n{\n\n int maxCount = 0;\n\n public int RequestCount\n {\n get;\n private set;\n }\n public MyList(int maxCount)\n {\n this.maxCount = maxCount;\n }\n public void Reset()\n {\n RequestCount = 0;\n }\n #region IEnumerable<int> Members\n\n public IEnumerator<int> GetEnumerator()\n {\n int i = 0;\n while (i < maxCount)\n {\n RequestCount++;\n yield return i++;\n }\n }\n\n #endregion\n\n #region IEnumerable Members\n\n System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()\n {\n throw new NotImplementedException();\n }\n\n #endregion\n}\nclass Program\n{\n static void Main(string[] args)\n {\n var list = new MyList(15);\n list.Take(5).ToArray();\n Console.WriteLine(list.RequestCount); // 5;\n\n list.Reset();\n list.OrderBy(q => q).Take(5).ToArray();\n Console.WriteLine(list.RequestCount); // 15;\n\n list.Reset();\n list.Where(q => (q & 1) == 0).Take(5).ToArray();\n Console.WriteLine(list.RequestCount); // 9; (first 5 odd)\n\n list.Reset();\n list.Where(q => (q & 1) == 0).Take(5).OrderBy(q => q).ToArray();\n Console.WriteLine(list.RequestCount); // 9; (first 5 odd)\n }\n}\n" }, { "answer_id": 50910524, "author": "Sina Lotfi", "author_id": 9044084, "author_profile": "https://Stackoverflow.com/users/9044084", "pm_score": 3, "selected": false, "text": "pagination slice of list or elements var slice = myList.Skip((pageNumber - 1) * pageSize)\n .Take(pageSize);\n var pageNumber = 1;\nvar pageSize = 5;\n var pageNumber = 2;\nvar pageSize = 5;\n var pageNumber = 3;\nvar pageSize = 5;\n pageSize = 5 pageNumber pageSize" }, { "answer_id": 66286358, "author": "Mouad Amzil", "author_id": 14073205, "author_profile": "https://Stackoverflow.com/users/14073205", "pm_score": 2, "selected": false, "text": " dataGridView1.DataSource = (from S in EE.Stagaire\n join F in EE.Filiere on\n S.IdFiliere equals F.IdFiliere\n where S.Nom.StartsWith(\"A\")\n select new\n {\n ID=S.Id,\n Name = S.Nom,\n Prénon= S.Prenon,\n Email=S.Email,\n MoteDePass=S.MoteDePass,\n Filiere = F.Filiere1\n }).Take(1).ToList();\n" }, { "answer_id": 71954055, "author": "Heinzlmaen", "author_id": 2767662, "author_profile": "https://Stackoverflow.com/users/2767662", "pm_score": 3, "selected": false, "text": " [Test]\n public void TestListLinqTake()\n {\n List<string> elements = new List<string>() { \"storm\", \"earth\", \"fire\"};\n List<string> noErrorThrown = elements.Take(5).ToList();\n List<string> someElements = elements.Take(2).ToList();\n\n Assert.True(\n someElements.First().Equals(\"storm\") &&\n someElements.Count == 2 &&\n noErrorThrown.Count == 3);\n }\n using System.Linq;\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319973", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38146/" ]
319,993
<p>This is a <a href="https://stackoverflow.com/questions/319199/why-is-java-able-to-store-0xff000000-as-an-int">follow up question</a>. So, Java store's integers in <a href="http://en.wikipedia.org/wiki/Two%27s_complement" rel="nofollow noreferrer">two's-complements</a> and you can do the following:</p> <pre><code>int ALPHA_MASK = 0xff000000; </code></pre> <p>In C# this requires the use of an unsigned integer, <code>uint</code>, because it interprets this to be <code>4278190080</code> instead of <code>-16777216</code>.</p> <p>My question, how do declare negative values in hexadecimal notation in c#, and how exactly are integers represented internally? What are the differences to Java here?</p>
[ { "answer_id": 320000, "author": "Martin v. Löwis", "author_id": 33006, "author_profile": "https://Stackoverflow.com/users/33006", "pm_score": 6, "selected": true, "text": "int ALPHA_MASK = unchecked((int)0xFF000000);\n int ALPHA_MASK = -0x1000000; // == -16777216\n" }, { "answer_id": 320006, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 3, "selected": false, "text": "unchecked\n{\n int ALPHA_MASK = (int)0xff000000;\n}\n int ALPHA_MASK = unchecked((int)0xff000000);\n" }, { "answer_id": 2480573, "author": "Quadko", "author_id": 297717, "author_profile": "https://Stackoverflow.com/users/297717", "pm_score": 0, "selected": false, "text": "-0x7F000000\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/319993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13466/" ]
320,001
<p>So I wrote buggy code that occasionally crash ... and creates a stackdump file.</p> <p>Using <a href="https://man7.org/linux/man-pages/man1/addr2line.1.html" rel="nofollow noreferrer">addr2line</a> I can figure out how the program got to the crash point by decoding the addresses from the stackdump one by one. Is there an alternative tool that can ease the debug using stack dumps? Is there a way to to load this information in Insight/Gdb?</p>
[ { "answer_id": 320029, "author": "BenB", "author_id": 11703, "author_profile": "https://Stackoverflow.com/users/11703", "pm_score": 0, "selected": false, "text": "gcc -g -o myfile myfile.c\n gdb myfile core\n" }, { "answer_id": 415923, "author": "Gerhard", "author_id": 34989, "author_profile": "https://Stackoverflow.com/users/34989", "pm_score": 7, "selected": true, "text": "error_start=action export CYGWIN=\"$CYGWIN error_start=gdb -nw %1 %2\" export CYGWIN=\"$CYGWIN error_start=dumper -d %1 %2\"" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/320001", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34989/" ]
320,004
<p>Given a couple of simple tables like so:</p> <pre><code>create table R(foo text); create table S(bar text); </code></pre> <p>If I were to union them together in a query, what do I call the column?</p> <pre><code>select T.???? from ( select foo from R union select bar from S) as T; </code></pre> <p>Now, in mysql, I can apparently refer to the column of T as 'foo' -- the name of the matching column for the first relation in the union. In sqlite3, however, that doesn't seem to work. Is there a way to do it that's standard across all SQL implementations?</p> <p>If not, how about just for sqlite3?</p> <p>Correction: sqlite3 does allow you to refer to T's column as 'foo' after all! Oops!</p>
[ { "answer_id": 320018, "author": "Ali Ersöz", "author_id": 4215, "author_profile": "https://Stackoverflow.com/users/4215", "pm_score": 4, "selected": false, "text": "select T.Col1\nfrom (\n select foo as Col1\n from R\n union\n select bar as Col1\n from S) as T;\n" }, { "answer_id": 12213781, "author": "Iman", "author_id": 184572, "author_profile": "https://Stackoverflow.com/users/184572", "pm_score": 3, "selected": false, "text": "select T.Col1\nfrom (\n select 'val1' as Col1\n union\n select 'val2'\n union\n select 'val3' \n) as T;\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/320004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22897/" ]
320,009
<p>In C++, I code this way:</p> <pre><code>//foo.h class cBar { void foobar(); } </code></pre> <hr> <pre><code>//foo.cpp void cBar::foobar() { //Code } </code></pre> <p>I tried to do this on PHP but the parser would complain. PHP's documentation also doesn't help. Can this be done in PHP?</p>
[ { "answer_id": 320024, "author": "Aron Rotteveel", "author_id": 11568, "author_profile": "https://Stackoverflow.com/users/11568", "pm_score": 1, "selected": false, "text": "abstract class cBar\n{\n // MUST be extended\n abstract protected function foobar();\n\n // MAY be extended\n protected function someMethod()\n {\n // do stuff\n }\n}\n\nclass cBarExtender extends cBar\n{\n protected function foobar()\n {\n // do stuff\n }\n\n}\n interface cBar \n{\n // MUST be implemented\n protected function foobar();\n}\n\nclass cBarImplementation implements cBar\n{\n protected function foobar()\n {\n // do stuff\n }\n}\n" }, { "answer_id": 320026, "author": "Josh", "author_id": 10902, "author_profile": "https://Stackoverflow.com/users/10902", "pm_score": 3, "selected": true, "text": "interface iBar\n{\n function foobar();\n}\n\n\nclass cBar implements iBar\n{\n function foobar()\n {\n //Code\n }\n}\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/320009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1599/" ]
320,028
<p>I cannot get a two-way bind in WPF to work. </p> <p>I have a string property in my app's main window that is bound to a TextBox (I set the mode to "TwoWay"). </p> <p>The only time that the value of the TextBox will update is when the window initializes. </p> <p>When I type into the TextBox, the underlying string properties value does not change. </p> <p>When the string property's value is changed by an external source (an event on Click, for example, that just resets the TextBox's value), the change doesn't propagate up to the TextBox.</p> <p>What are the steps that I must implement to get two-way binding to work properly in even this almost trivial example?</p>
[ { "answer_id": 320035, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 7, "selected": true, "text": "<Window x:Class=\"DataBinding.MyWindow\" ...\n Title=\"MyWindow\" Height=\"300\" Width=\"300\">\n <StackPanel x:Name=\"TopLevelContainer\">\n <TextBox x:Name=\"txtValue\" Background=\"AliceBlue\" Text=\"{Binding Path=MyDotNetProperty}\" />\n <TextBlock TextWrapping=\"Wrap\">We're twin blue boxes bound to the same property.</TextBlock>\n <TextBox x:Name=\"txtValue2\" Background=\"AliceBlue\" Text=\"{Binding Path=MyDotNetProperty}\" />\n </StackPanel>\n</Window>\n public partial class MyWindow : Window, INotifyPropertyChanged\n{\n public MyWindow()\n {\n InitializeComponent();\n this.MyDotNetProperty = \"Go ahead. Change my value.\";\n TopLevelContainer.DataContext = this;\n }\n\n private string m_sValue;\n public string MyDotNetProperty\n {\n get { return m_sValue; }\n set\n {\n m_sValue = value;\n if (null != this.PropertyChanged)\n {\n PropertyChanged(this, new PropertyChangedEventArgs(\"MyDotNetProperty\"));\n }\n }\n }\n\n #region INotifyPropertyChanged Members\n public event PropertyChangedEventHandler PropertyChanged;\n #endregion\n}\n" }, { "answer_id": 71372190, "author": "ΩmegaMan", "author_id": 285795, "author_profile": "https://Stackoverflow.com/users/285795", "pm_score": 1, "selected": false, "text": " <TextBox Text=\"{Binding TextBuffer, \n UpdateSourceTrigger=PropertyChanged, \n Mode=TwoWay}\"/>\n TextBox Text TextBuffer PropertyChanged TwoWay" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/320028", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29119/" ]
320,045
<p>When programming a large transaction (lots of inserts, deletes, updates) and thereby violating a constraint in Informix (v10, but should apply to other versions too) I get a not very helpful message saying, for example, I violated constraint r190_710. How can I find out which table(s) and key(s) are covered by a certain constraint I know only the name of?</p>
[ { "answer_id": 337605, "author": "user39039", "author_id": 39039, "author_profile": "https://Stackoverflow.com/users/39039", "pm_score": 0, "selected": false, "text": "SELECT si.part1, si.part2, si.part3, si.part4, si.part5, \n si.part6, si.part7, si.part8, si.part9, si.part10, \n si.part11, si.part12, si.part13, si.part14, si.part15, si.part16, \n st.tabname, rt.tabname as reftable, sr.primary as primconstr, \n sr.delrule, sc.constrid, sc.constrname, sc.constrtype, \n si.idxname, si.tabid as tabid, rc.tabid as rtabid \nFROM 'informix'.systables st, 'informix'.sysconstraints sc, \n 'informix'.sysindexes si, 'informix'.sysreferences sr, \n 'informix'.systables rt, 'informix'.sysconstraints rc \nWHERE st.tabid = sc.tabid \n AND st.tabtype != 'Q' \n AND st.tabname NOT MATCHES 'cdr_deltab_[0-9][0-9][0-9][0-9][0-9][0-9]*' \n AND rt.tabid = sr.ptabid \n AND rc.tabid = sr.ptabid\n AND sc.constrid = sr.constrid \n AND sc.tabid = si.tabid \n AND sc.idxname = si.idxname \n AND sc.constrtype = 'R' \n AND sc.constrname = ?\n AND sr.primary = rc.constrid \nORDER BY si.tabid, sc.constrname\n SELECT part1, part2, part3, part4, part5, part6, part7, part8, \n part9, part10, part11, part12, part13, part14, part15, part16 \nFROM 'informix'.sysindexes si, 'informix'.sysconstraints sc \nWHERE si.tabid = sc.tabid \nAND si.idxname = sc.idxname \nAND sc.constrid = ? -- primconstr from (1)\n SELECT colno, colname \nFROM 'informix'.syscolumns \nWHERE tabid = ? -- tabid(for referenced) or rtabid(for referencing) from (1)\n AND colno = ? -- via parts from (1) and (2)\nORDER BY colno\n SELECT type, seqno, checktext\nFROM 'informix'.syschecks\nWHERE constrid = ? -- constrid from (1)\n" }, { "answer_id": 10948547, "author": "cab", "author_id": 1444471, "author_profile": "https://Stackoverflow.com/users/1444471", "pm_score": 3, "selected": false, "text": "SELECT\n a.tabname, b.constrname, d.colname\nFROM\n systables a, sysconstraints b, sysindexes c, syscolumns d\nWHERE\n a.tabname = 'your_table_name_here'\nAND\n b.tabid = a.tabid\nAND\n c.idxname = b.idxname\nAND\n d.tabid = a.tabid\nAND\n(\n d.colno = c.part1 or \n d.colno = c.part2 or \n d.colno = c.part3 or \n d.colno = c.part4 or \n d.colno = c.part5 or \n d.colno = c.part6 or \n d.colno = c.part7 or \n d.colno = c.part8 or \n d.colno = c.part9 or \n d.colno = c.part10 or \n d.colno = c.part11 or \n d.colno = c.part12 or\n d.colno = c.part13 or \n d.colno = c.part14 or \n d.colno = c.part15 or \n d.colno = c.part16\n)\nORDER BY\n a.tabname, \n b.constrname,\n d.colname\n" }, { "answer_id": 32891474, "author": "Santiago Taba", "author_id": 5212480, "author_profile": "https://Stackoverflow.com/users/5212480", "pm_score": 1, "selected": false, "text": "select TABNAME from SYSTABLES where TABID IN\n(select TABID from sysconstraints where CONSTRID IN\n(select CONSTRID from sysreferences where PTABID IN \n(select TABID from sysconstraints where CONSTRNAME= \"r190_710\" )\n)\n);\n" }, { "answer_id": 34178841, "author": "ekarak", "author_id": 1032608, "author_profile": "https://Stackoverflow.com/users/1032608", "pm_score": 0, "selected": false, "text": "constraint_c6 OUTPUT TO '/tmp/constraint_c6.sql' WITHOUT HEADINGS\nSELECT ch.checktext\nFROM syschecks ch, sysconstraints co\nWHERE ch.constrid = co.constrid\n AND ch.type = 'T' -- text lines only\n AND co.constrname = 'constraint_c6' \nORDER BY ch.seqno;\n" }, { "answer_id": 40282869, "author": "Otherside", "author_id": 18697, "author_profile": "https://Stackoverflow.com/users/18697", "pm_score": 2, "selected": false, "text": "select\n tab.tabname,\n constr.*, \n chk.*,\n c1.colname col1,\n c2.colname col2,\n c3.colname col3,\n c4.colname col4,\n c5.colname col5\nfrom sysconstraints constr\n join systables tab on tab.tabid = constr.tabid\n left outer join syschecks chk on chk.constrid = constr.constrid and chk.type = 'T'\n left outer join sysindexes i on i.idxname = constr.idxname\n left outer join syscolumns c1 on c1.tabid = tab.tabid and c1.colno = abs(i.part1)\n left outer join syscolumns c2 on c2.tabid = tab.tabid and c2.colno = abs(i.part2)\n left outer join syscolumns c3 on c3.tabid = tab.tabid and c3.colno = abs(i.part3)\n left outer join syscolumns c4 on c4.tabid = tab.tabid and c4.colno = abs(i.part4)\n left outer join syscolumns c5 on c5.tabid = tab.tabid and c5.colno = abs(i.part5)\nwhere constr.constrname = 'your constraint name'\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/320045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39039/" ]
320,046
<p>This is intended to be a more concrete, easily expressable form of my earlier question.</p> <p>Take a list of words from a dictionary with common letter length.<br> How to reorder this list tto keep as many letters as possible common between adjacent words? </p> <p>Example 1:</p> <pre><code>AGNI, CIVA, DEVA, DEWA, KAMA, RAMA, SIVA, VAYU reorders to: AGNI, CIVA, SIVA, DEVA, DEWA, KAMA, RAMA, VAYU </code></pre> <p>Example 2:</p> <pre><code>DEVI, KALI, SHRI, VACH reorders to: DEVI, SHRI, KALI, VACH </code></pre> <p>The simplest algorithm seems to be: Pick anything, then search for the shortest distance?<br> However, DEVI->KALI (1 common) is equivalent to DEVI->SHRI (1 common)<br> Choosing the first match would result in fewer common pairs in the entire list (4 versus 5). </p> <p>This seems that it should be simpler than full TSP? </p>
[ { "answer_id": 320063, "author": "schnaader", "author_id": 34065, "author_profile": "https://Stackoverflow.com/users/34065", "pm_score": 0, "selected": false, "text": "Start with one of the words, call it w\nFindNext(w, l) // l = list of words without w\n Get a list l of the words near to w\n If only one word in list\n Return that word\n Else\n For every word w' in l do FindNext(w', l') //l' = l without w'\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/320046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
320,052
<p>What is your preferred method of traversing a tree data structure, since recursive method calls can be pretty inefficient in some circumstances. I am simply using a generator like the one above. Do you have any hints to make it faster?</p> <pre><code>def children(self): stack = [self.entities] while stack: for e in stack.pop(): yield e if e.entities: stack.append(e.entities) </code></pre> <p>Here is some test data. The first one is recursive, the second uses the generator:</p> <pre><code>s = time.time() for i in range(100000): e.inc_counter() print time.time() - s s = time.time() for i in range(100000): for e in e.children(): e.inc_counter_s() print time.time() - s </code></pre> <p>Results:</p> <pre><code>0.416000127792 0.298999786377 </code></pre> <p>Test code:</p> <pre><code>import random class Entity(): def __init__(self, name): self.entities = [] self.name = name self.counter = 1 self.depth = 0 def add_entity(self, e): e.depth = self.depth + 1 self.entities.append(e) def inc_counter_r(self): for e in self.entities: e.counter += 1 e.inc_counter_r() def children(self): stack = [self.entities] while stack: for e in stack.pop(): yield e if e.entities: stack.append(e.entities) root = Entity("main") def fill_node(root, max_depth): if root.depth &lt;= max_depth: for i in range(random.randint(10, 15)): e = Entity("node_%s_%s" % (root.depth, i)) root.add_entity(e) fill_node(e, max_depth) fill_node(root, 3) import time s = time.time() for i in range(100): root.inc_counter_r() print "recursive:", time.time() - s s = time.time() for i in range(100): for e in root.children(): e.counter += 1 print "generator:", time.time() - s </code></pre>
[ { "answer_id": 320061, "author": "Aaron Digulla", "author_id": 34088, "author_profile": "https://Stackoverflow.com/users/34088", "pm_score": 2, "selected": false, "text": "def children(self):\n if self._children_cache is not None:\n return self._children_cache\n # Put your code into collectChildren()\n self._children_cache = self.collectChildren()\n return self._children_cache\n" }, { "answer_id": 320252, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 4, "selected": true, "text": "def children(self):\n stack = [self.entities]\n push = stack.append\n pop = stack.pop\n while stack: \n for e in pop():\n yield e\n if e.entities:\n push(e.entities)\n children : 5.53942348004\nchildren_bind: 4.77636131253\n" }, { "answer_id": 320329, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 0, "selected": false, "text": "def children(self):\n stack = [self.entities]\n for e in stack:\n yield e\n if e.entities:\n stack.extend(e.entities)\n extend append for while for" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/320052", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40948/" ]
320,058
<p>Greetings,</p> <p>I've got a bat script which copies certain information from a computer onto a USB hard drive using Robocopy. The hard drive is FAT formatted and therefore doesn't support directories with extended attributes, leading me to robocopy error 282 <a href="http://forums.hexus.net/thecus-care-hexus/121981-n5200pro-error-mounted-file-system-does-not-support-extended-attributes.html" rel="nofollow noreferrer">as described here</a>.</p> <p>How do I tell robocopy to copy all the attribute information EXCEPT for the extendable attributes?</p> <p><strong>I still need help, but, some helpful info from the googling ive done thus far</strong></p> <ul> <li>Robocopy Command-Line Options: <a href="http://www.ss64.com/nt/robocopy.html" rel="nofollow noreferrer">http://www.ss64.com/nt/robocopy.html</a></li> <li>What is an Extended File Attribute: <a href="http://en.wikipedia.org/wiki/Extended_file_attributes" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Extended_file_attributes</a></li> <li>Windows Hotfix (which would be great if I wasn't copying to a USB hard drive): <a href="http://support.microsoft.com/kb/329145/en-us" rel="nofollow noreferrer">http://support.microsoft.com/kb/329145/en-us</a></li> </ul> <p><strong>EDIT:</strong> <em>Wow, the file system isn't FAT, I was wrong. Its RAW.</em></p>
[ { "answer_id": 6185871, "author": "jack", "author_id": 181699, "author_profile": "https://Stackoverflow.com/users/181699", "pm_score": 0, "selected": false, "text": "convert e: /fs:ntfs \n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/320058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5021/" ]
320,078
<p>How do you add that little "X" button on the right side of a UITextField that clears the text? I can't find an attribute for adding this sub-control in Interface Builder in the iPhone OS 2.2 SDK.</p> <p><strong>Note:</strong> In Xcode 4.x and later (iPhone 3.0 SDK and later), you can do this in Interface Builder.</p>
[ { "answer_id": 320079, "author": "Kristopher Johnson", "author_id": 1175, "author_profile": "https://Stackoverflow.com/users/1175", "pm_score": 10, "selected": true, "text": "UITextField viewDidLoad myUITextField.clearButtonMode = UITextFieldViewModeWhileEditing;\n myUITextField.clearButtonMode = .whileEditing\n" }, { "answer_id": 18078048, "author": "Hossam Ghareeb", "author_id": 1752899, "author_profile": "https://Stackoverflow.com/users/1752899", "pm_score": 5, "selected": false, "text": "UIButton *clearButton = [UIButton buttonWithType:UIButtonTypeCustom];\n[clearButton setImage:img forState:UIControlStateNormal];\n[clearButton setFrame:frame];\n[clearButton addTarget:self action:@selector(clearTextField:) forControlEvents:UIControlEventTouchUpInside];\n\ntextField.rightViewMode = UITextFieldViewModeAlways; //can be changed to UITextFieldViewModeNever, UITextFieldViewModeWhileEditing, UITextFieldViewModeUnlessEditing\n[textField setRightView:clearButton];\n" }, { "answer_id": 32979308, "author": "Esqarrouth", "author_id": 2589276, "author_profile": "https://Stackoverflow.com/users/2589276", "pm_score": 6, "selected": false, "text": "textField.clearButtonMode = UITextField.ViewMode.whileEditing\n textField.clearButtonMode = .whileEditing\n" }, { "answer_id": 35174866, "author": "PT Vyas", "author_id": 5593725, "author_profile": "https://Stackoverflow.com/users/5593725", "pm_score": 3, "selected": false, "text": "self.txtUserNameTextfield.myUITextField.clearButtonMode = UITextFieldViewModeWhileEditing;\n txtUserNameTextfield.clearButtonMode = UITextField.ViewMode.WhileEditing;\n" }, { "answer_id": 37981534, "author": "Tritmm", "author_id": 3550584, "author_profile": "https://Stackoverflow.com/users/3550584", "pm_score": 3, "selected": false, "text": "customTextField.clearButtonMode = UITextField.ViewMode.Always\n\ncustomTextField.clearsOnBeginEditing = true;\n\nfunc textFieldShouldClear(textField: UITextField) -> Bool {\n return true\n}\n" }, { "answer_id": 39611518, "author": "Aidan.C", "author_id": 6857362, "author_profile": "https://Stackoverflow.com/users/6857362", "pm_score": 3, "selected": false, "text": "textField.clearButtonMode = UITextField.ViewMode.whileEditing;\n" }, { "answer_id": 50559038, "author": "Pardeep Kumar", "author_id": 5461402, "author_profile": "https://Stackoverflow.com/users/5461402", "pm_score": 1, "selected": false, "text": " func clear_btn(box_is : UITextField){\n box_is.clearButtonMode = .always\n if let clearButton = box_is.value(forKey: \"_clearButton\") as? UIButton {\n let templateImage = clearButton.imageView?.image?.withRenderingMode(.alwaysTemplate)\n\n clearButton.setImage(templateImage, for: .normal)\n clearButton.setImage(templateImage, for: .highlighted)\n\n clearButton.tintColor = .white\n\n }\n}\n" }, { "answer_id": 52928150, "author": "Edouard Barbier", "author_id": 4062268, "author_profile": "https://Stackoverflow.com/users/4062268", "pm_score": 3, "selected": false, "text": "textfield.clearButtonMode = .always\n\ntextfield.clearButtonMode = .whileEditing\n\ntextfield.clearButtonMode = .unlessEditing\n\ntextfield.clearButtonMode = .never\n" }, { "answer_id": 70902487, "author": "Payal Maniyar", "author_id": 1850983, "author_profile": "https://Stackoverflow.com/users/1850983", "pm_score": 0, "selected": false, "text": "self.txtField.rightView = nil\nself.txtField.rightViewMode = .never\nself.txtField.clearButtonMode = UITextField.ViewMode.always\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/320078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1175/" ]
320,089
<p>My WPF application generates sets of data which may have a different number of columns each time. Included in the output is a description of each column that will be used to apply formatting. A simplified version of the output might be something like:</p> <pre><code>class Data { IList&lt;ColumnDescription&gt; ColumnDescriptions { get; set; } string[][] Rows { get; set; } } </code></pre> <p>This class is set as the DataContext on a WPF DataGrid but I actually create the columns programmatically:</p> <pre><code>for (int i = 0; i &lt; data.ColumnDescriptions.Count; i++) { dataGrid.Columns.Add(new DataGridTextColumn { Header = data.ColumnDescriptions[i].Name, Binding = new Binding(string.Format("[{0}]", i)) }); } </code></pre> <p>Is there any way to replace this code with data bindings in the XAML file instead?</p>
[ { "answer_id": 343447, "author": "Generic Error", "author_id": 40944, "author_profile": "https://Stackoverflow.com/users/40944", "pm_score": 4, "selected": false, "text": "public static void GenerateColumns(this DataGrid dataGrid, IEnumerable<ColumnSchema> columns)\n{\n dataGrid.Columns.Clear();\n\n int index = 0;\n foreach (var column in columns)\n {\n dataGrid.Columns.Add(new DataGridTextColumn\n {\n Header = column.Name,\n Binding = new Binding(string.Format(\"[{0}]\", index++))\n });\n }\n}\n\n// E.g. myGrid.GenerateColumns(schema);\n" }, { "answer_id": 1411326, "author": "Andy", "author_id": 172115, "author_profile": "https://Stackoverflow.com/users/172115", "pm_score": 2, "selected": false, "text": "public ObservableCollection<DataGridColumn> gridColumns\n{\n get\n {\n return (ObservableCollection<DataGridColumn>)GetValue(ColumnsProperty);\n }\n set\n {\n SetValue(ColumnsProperty, value);\n }\n}\npublic static readonly DependencyProperty ColumnsProperty =\n DependencyProperty.Register(\"gridColumns\",\n typeof(ObservableCollection<DataGridColumn>),\n typeof(parentControl),\n new PropertyMetadata(new ObservableCollection<DataGridColumn>()));\n\npublic void LoadGrid()\n{\n if (gridColumns.Count > 0)\n myGrid.Columns.Clear();\n\n foreach (DataGridColumn c in gridColumns)\n {\n myGrid.Columns.Add(c);\n }\n}\n <local:parentControl x:Name=\"deGrid\"> \n <local:parentControl.gridColumns>\n <toolkit:DataGridTextColumn Width=\"Auto\" Header=\"1\" Binding=\"{Binding Path=.}\" />\n <toolkit:DataGridTextColumn Width=\"Auto\" Header=\"2\" Binding=\"{Binding Path=.}\" />\n </local:parentControl.gridColumns> \n</local:parentControl>\n InitalizeComponent childGrid.deGrid.LoadGrid();\n" }, { "answer_id": 4379965, "author": "Fredrik Hedblad", "author_id": 318425, "author_profile": "https://Stackoverflow.com/users/318425", "pm_score": 8, "selected": true, "text": "public ObservableCollection<DataGridColumn> ColumnCollection\n{\n get;\n private set;\n}\n <DataGrid Name=\"dataGrid\"\n local:DataGridColumnsBehavior.BindableColumns=\"{Binding ColumnCollection}\"\n AutoGenerateColumns=\"False\"\n ...>\n public class DataGridColumnsBehavior\n{\n public static readonly DependencyProperty BindableColumnsProperty =\n DependencyProperty.RegisterAttached(\"BindableColumns\",\n typeof(ObservableCollection<DataGridColumn>),\n typeof(DataGridColumnsBehavior),\n new UIPropertyMetadata(null, BindableColumnsPropertyChanged));\n private static void BindableColumnsPropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs e)\n {\n DataGrid dataGrid = source as DataGrid;\n ObservableCollection<DataGridColumn> columns = e.NewValue as ObservableCollection<DataGridColumn>;\n dataGrid.Columns.Clear();\n if (columns == null)\n {\n return;\n }\n foreach (DataGridColumn column in columns)\n {\n dataGrid.Columns.Add(column);\n }\n columns.CollectionChanged += (sender, e2) =>\n {\n NotifyCollectionChangedEventArgs ne = e2 as NotifyCollectionChangedEventArgs;\n if (ne.Action == NotifyCollectionChangedAction.Reset)\n {\n dataGrid.Columns.Clear();\n foreach (DataGridColumn column in ne.NewItems)\n {\n dataGrid.Columns.Add(column);\n }\n }\n else if (ne.Action == NotifyCollectionChangedAction.Add)\n {\n foreach (DataGridColumn column in ne.NewItems)\n {\n dataGrid.Columns.Add(column);\n }\n }\n else if (ne.Action == NotifyCollectionChangedAction.Move)\n {\n dataGrid.Columns.Move(ne.OldStartingIndex, ne.NewStartingIndex);\n }\n else if (ne.Action == NotifyCollectionChangedAction.Remove)\n {\n foreach (DataGridColumn column in ne.OldItems)\n {\n dataGrid.Columns.Remove(column);\n }\n }\n else if (ne.Action == NotifyCollectionChangedAction.Replace)\n {\n dataGrid.Columns[ne.NewStartingIndex] = ne.NewItems[0] as DataGridColumn;\n }\n };\n }\n public static void SetBindableColumns(DependencyObject element, ObservableCollection<DataGridColumn> value)\n {\n element.SetValue(BindableColumnsProperty, value);\n }\n public static ObservableCollection<DataGridColumn> GetBindableColumns(DependencyObject element)\n {\n return (ObservableCollection<DataGridColumn>)element.GetValue(BindableColumnsProperty);\n }\n}\n" }, { "answer_id": 4836583, "author": "Lukas Cenovsky", "author_id": 138803, "author_profile": "https://Stackoverflow.com/users/138803", "pm_score": 3, "selected": false, "text": "DataGridTemplateColumn ItemsControl" }, { "answer_id": 8890435, "author": "doblak", "author_id": 127027, "author_profile": "https://Stackoverflow.com/users/127027", "pm_score": 3, "selected": false, "text": "MyItemsCollection.AddPropertyDescriptor(\n new DynamicPropertyDescriptor<User, int>(\"Age\", x => x.Age));\n IList<string> ColumnNames { get; set; }\n//dict.key is column name, dict.value is value\nDictionary<string, string> Rows { get; set; }\n var descriptors= new List<PropertyDescriptor>();\n//retrieve column name from preprepared list or retrieve from one of the items in dictionary\nforeach(var columnName in ColumnNames)\n descriptors.Add(new DynamicPropertyDescriptor<Dictionary, string>(ColumnName, x => x[columnName]))\nMyItemsCollection = new DynamicDataGridSource(Rows, descriptors) \n" }, { "answer_id": 35893291, "author": "Mikhail Orlov", "author_id": 1271135, "author_profile": "https://Stackoverflow.com/users/1271135", "pm_score": 2, "selected": false, "text": "public class DataGridColumnsBehavior\n{\n public static readonly DependencyProperty BindableColumnsProperty =\n DependencyProperty.RegisterAttached(\"BindableColumns\",\n typeof(ObservableCollection<DataGridColumn>),\n typeof(DataGridColumnsBehavior),\n new UIPropertyMetadata(null, BindableColumnsPropertyChanged));\n\n /// <summary>Collection to store collection change handlers - to be able to unsubscribe later.</summary>\n private static readonly Dictionary<DataGrid, NotifyCollectionChangedEventHandler> _handlers;\n\n static DataGridColumnsBehavior()\n {\n _handlers = new Dictionary<DataGrid, NotifyCollectionChangedEventHandler>();\n }\n\n private static void BindableColumnsPropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs e)\n {\n DataGrid dataGrid = source as DataGrid;\n\n ObservableCollection<DataGridColumn> oldColumns = e.OldValue as ObservableCollection<DataGridColumn>;\n if (oldColumns != null)\n {\n // Remove all columns.\n dataGrid.Columns.Clear();\n\n // Unsubscribe from old collection.\n NotifyCollectionChangedEventHandler h;\n if (_handlers.TryGetValue(dataGrid, out h))\n {\n oldColumns.CollectionChanged -= h;\n _handlers.Remove(dataGrid);\n }\n }\n\n ObservableCollection<DataGridColumn> newColumns = e.NewValue as ObservableCollection<DataGridColumn>;\n dataGrid.Columns.Clear();\n if (newColumns != null)\n {\n // Add columns from this source.\n foreach (DataGridColumn column in newColumns)\n dataGrid.Columns.Add(column);\n\n // Subscribe to future changes.\n NotifyCollectionChangedEventHandler h = (_, ne) => OnCollectionChanged(ne, dataGrid);\n _handlers[dataGrid] = h;\n newColumns.CollectionChanged += h;\n }\n }\n\n static void OnCollectionChanged(NotifyCollectionChangedEventArgs ne, DataGrid dataGrid)\n {\n switch (ne.Action)\n {\n case NotifyCollectionChangedAction.Reset:\n dataGrid.Columns.Clear();\n foreach (DataGridColumn column in ne.NewItems)\n dataGrid.Columns.Add(column);\n break;\n case NotifyCollectionChangedAction.Add:\n foreach (DataGridColumn column in ne.NewItems)\n dataGrid.Columns.Add(column);\n break;\n case NotifyCollectionChangedAction.Move:\n dataGrid.Columns.Move(ne.OldStartingIndex, ne.NewStartingIndex);\n break;\n case NotifyCollectionChangedAction.Remove:\n foreach (DataGridColumn column in ne.OldItems)\n dataGrid.Columns.Remove(column);\n break;\n case NotifyCollectionChangedAction.Replace:\n dataGrid.Columns[ne.NewStartingIndex] = ne.NewItems[0] as DataGridColumn;\n break;\n }\n }\n\n public static void SetBindableColumns(DependencyObject element, ObservableCollection<DataGridColumn> value)\n {\n element.SetValue(BindableColumnsProperty, value);\n }\n\n public static ObservableCollection<DataGridColumn> GetBindableColumns(DependencyObject element)\n {\n return (ObservableCollection<DataGridColumn>)element.GetValue(BindableColumnsProperty);\n }\n}\n" }, { "answer_id": 40174153, "author": "David Soler", "author_id": 5324242, "author_profile": "https://Stackoverflow.com/users/5324242", "pm_score": 0, "selected": false, "text": "public partial class UserControlWithComboBoxColumnDataGrid : UserControl\n{\n private Dictionary<int, string> _Dictionary;\n private ObservableCollection<MyItem> _MyItems;\n public UserControlWithComboBoxColumnDataGrid() {\n _Dictionary = new Dictionary<int, string>();\n _Dictionary.Add(1,\"A\");\n _Dictionary.Add(2,\"B\");\n _MyItems = new ObservableCollection<MyItem>();\n dataGridMyItems.AutoGeneratingColumn += DataGridMyItems_AutoGeneratingColumn;\n dataGridMyItems.ItemsSource = _MyItems;\n\n }\nprivate void DataGridMyItems_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)\n {\n var desc = e.PropertyDescriptor as PropertyDescriptor;\n var att = desc.Attributes[typeof(ColumnNameAttribute)] as ColumnNameAttribute;\n if (att != null)\n {\n if (att.Name == \"My Combobox Item\") {\n var comboBoxColumn = new DataGridComboBoxColumn {\n DisplayMemberPath = \"Value\",\n SelectedValuePath = \"Key\",\n ItemsSource = _ApprovalTypes,\n SelectedValueBinding = new Binding( \"Bazinga\"), \n };\n e.Column = comboBoxColumn;\n }\n\n }\n }\n\n}\npublic class MyItem {\n public string Name{get;set;}\n [ColumnName(\"My Combobox Item\")]\n public int Bazinga {get;set;}\n}\n\n public class ColumnNameAttribute : Attribute\n {\n public string Name { get; set; }\n public ColumnNameAttribute(string name) { Name = name; }\n}\n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/320089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40944/" ]
320,096
<p>If there a way to protect against concurrent modifications of the same data base entry by two or more users?</p> <p>It would be acceptable to show an error message to the user performing the second commit/save operation, but data should not be silently overwritten.</p> <p>I think locking the entry is not an option, as a user might use the "Back" button or simply close his browser, leaving the lock for ever.</p>
[ { "answer_id": 320221, "author": "Guillaume", "author_id": 23704, "author_profile": "https://Stackoverflow.com/users/23704", "pm_score": 5, "selected": false, "text": "UPDATE ... WHERE version = 'version_from_user';\n" }, { "answer_id": 1874807, "author": "seanyboy", "author_id": 1726, "author_profile": "https://Stackoverflow.com/users/1726", "pm_score": -1, "selected": false, "text": "def save(self):\n if(self.id):\n foo = Foo.objects.get(pk=self.id)\n if(foo.timestamp > self.timestamp):\n raise Exception, \"trying to save outdated Foo\" \n super(Foo, self).save()\n" }, { "answer_id": 2166298, "author": "Andrei Savu", "author_id": 3885, "author_profile": "https://Stackoverflow.com/users/3885", "pm_score": 6, "selected": false, "text": "updated = Entry.objects.filter(Q(id=e.id) && Q(version=e.version))\\\n .update(updated_field=new_value, version=e.version+1)\nif not updated:\n raise ConcurrentModificationException()\n" }, { "answer_id": 6892809, "author": "Kiril", "author_id": 836016, "author_profile": "https://Stackoverflow.com/users/836016", "pm_score": 0, "selected": false, "text": "updated = Entry.objects.filter(Q(id=e.id) && Q(version=e.version))\\\n .update(updated_field=new_value, version=e.version+1)\nif not updated:\n raise ConcurrentModificationException()\n def _update(self, values, **kwargs):\n return self.get_query_set()._update(values, **kwargs)\n def _update(self, values, **kwargs):\n #TODO Get version field value\n v = self.get_version_field_value(values[0])\n return self.get_query_set().filter(Q(version=v))._update(values, **kwargs)\n" }, { "answer_id": 11133520, "author": "giZm0", "author_id": 481406, "author_profile": "https://Stackoverflow.com/users/481406", "pm_score": 5, "selected": false, "text": "select_for_update(nowait=True)\n nowait=True nowait=False" }, { "answer_id": 44045082, "author": "kravietz", "author_id": 1274149, "author_profile": "https://Stackoverflow.com/users/1274149", "pm_score": 4, "selected": false, "text": "Something.objects.select_for_update() Something.objects.select_for_update(nowait=True) DatabaseError Something.objects.select_for_update(skip_locked=True) select_for_update nowait skip_locked skip_locked" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/320096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11527/" ]
320,103
<p>Using the Facebook API, is there a way of getting a friend's phone/cell number? I'm sure I saw an app a while ago that could sync Facebook with your Mac Address Book, but I haven't found anything in the API documentation that allows you to get a friend's number. Is this possible?</p> <p>Thanks in advance.</p>
[ { "answer_id": 320221, "author": "Guillaume", "author_id": 23704, "author_profile": "https://Stackoverflow.com/users/23704", "pm_score": 5, "selected": false, "text": "UPDATE ... WHERE version = 'version_from_user';\n" }, { "answer_id": 1874807, "author": "seanyboy", "author_id": 1726, "author_profile": "https://Stackoverflow.com/users/1726", "pm_score": -1, "selected": false, "text": "def save(self):\n if(self.id):\n foo = Foo.objects.get(pk=self.id)\n if(foo.timestamp > self.timestamp):\n raise Exception, \"trying to save outdated Foo\" \n super(Foo, self).save()\n" }, { "answer_id": 2166298, "author": "Andrei Savu", "author_id": 3885, "author_profile": "https://Stackoverflow.com/users/3885", "pm_score": 6, "selected": false, "text": "updated = Entry.objects.filter(Q(id=e.id) && Q(version=e.version))\\\n .update(updated_field=new_value, version=e.version+1)\nif not updated:\n raise ConcurrentModificationException()\n" }, { "answer_id": 6892809, "author": "Kiril", "author_id": 836016, "author_profile": "https://Stackoverflow.com/users/836016", "pm_score": 0, "selected": false, "text": "updated = Entry.objects.filter(Q(id=e.id) && Q(version=e.version))\\\n .update(updated_field=new_value, version=e.version+1)\nif not updated:\n raise ConcurrentModificationException()\n def _update(self, values, **kwargs):\n return self.get_query_set()._update(values, **kwargs)\n def _update(self, values, **kwargs):\n #TODO Get version field value\n v = self.get_version_field_value(values[0])\n return self.get_query_set().filter(Q(version=v))._update(values, **kwargs)\n" }, { "answer_id": 11133520, "author": "giZm0", "author_id": 481406, "author_profile": "https://Stackoverflow.com/users/481406", "pm_score": 5, "selected": false, "text": "select_for_update(nowait=True)\n nowait=True nowait=False" }, { "answer_id": 44045082, "author": "kravietz", "author_id": 1274149, "author_profile": "https://Stackoverflow.com/users/1274149", "pm_score": 4, "selected": false, "text": "Something.objects.select_for_update() Something.objects.select_for_update(nowait=True) DatabaseError Something.objects.select_for_update(skip_locked=True) select_for_update nowait skip_locked skip_locked" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/320103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21709/" ]
320,119
<p>I use the <kbd>Shift</kbd> + <kbd>F7</kbd> often to switch between source and design view.</p> <p>Does anyone know of a hotkey to switch between the <strong>source file</strong> and its <strong>code behind file</strong>, e.g. between (Default.aspx and Default.aspx.cs)?</p>
[ { "answer_id": 19097004, "author": "Eduardo Cuomo", "author_id": 717267, "author_profile": "https://Stackoverflow.com/users/717267", "pm_score": 7, "selected": false, "text": "> >" }, { "answer_id": 20342984, "author": "James G", "author_id": 1196415, "author_profile": "https://Stackoverflow.com/users/1196415", "pm_score": 5, "selected": false, "text": "Tools > Options > Keyboard" }, { "answer_id": 26490854, "author": "Dan", "author_id": 1394392, "author_profile": "https://Stackoverflow.com/users/1394392", "pm_score": 3, "selected": false, "text": "Show Commands Containing: Use new shortcut in: Global Press shortcut keys: Assign" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/320119", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4639/" ]
320,124
<p>I want to debug an application in Linux. The application is created in C++. The GUI is created using QT. The GUI is linked with a static library that can be treated as the back end of the application.</p> <p>I want to debug the static library but am not sure how to do that.</p> <p>I tried using gdb</p> <pre><code>gdb GUI </code></pre> <p>But how can I attach the library?</p> <p>Has anyone had experience in debugging libraries in linux?</p>
[ { "answer_id": 320136, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 4, "selected": true, "text": "gdb ./foo\nrun\n -g3 -O1" }, { "answer_id": 320257, "author": "Sam Stokes", "author_id": 20131, "author_profile": "https://Stackoverflow.com/users/20131", "pm_score": 3, "selected": false, "text": "-g -g" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/320124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33411/" ]
320,128
<p>This problem crops up every now and then at work. Our build machine can have it's files accessed via a normal windows file share. If someone browses a folder remotely on the machine, and leaves the window open overnight, then the build fails (as it has done now). The explorer window left opened points at one of the sub folders in the source tree. The build deletes the source, and does a clean checkout before building. The delete is failing.</p> <p>Right now, I'd like to get the build to work. I'm logged in from home, and I'd rather not reboot the build machine. I'm unable to get hold of the person whose machine is looking and the files, and I can't remotely reboot their machine.</p> <p>When a windows share has a lock, the locking process is System, so I don't think I can kill it, as with normal locks.</p> <p>Does anyone know a way to release the lock on a shared folder without having to reboot the machine?</p>
[ { "answer_id": 34425394, "author": "Charles Burns", "author_id": 161816, "author_profile": "https://Stackoverflow.com/users/161816", "pm_score": 3, "selected": false, "text": "Miscellaneous Terminator" }, { "answer_id": 44355260, "author": "Panuels", "author_id": 8110637, "author_profile": "https://Stackoverflow.com/users/8110637", "pm_score": 0, "selected": false, "text": "perfmon.exe /res" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/320128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28840/" ]
320,135
<p>I need to ensure that an application I am developing is accessable and also works with JavaScript turned off. I just need a pointer to assist with the following.</p> <p>I had 3 'chained' select boxes and I wanted JavaScript enabled clients to have a nice Ajax experience. I can easily write the required functionality to populate the chained boxes on the change event of the preceeding select using jQuery and JSON with a WCF service. However what about the non JavaScript client?</p> <p>Would I wrap a submit next to the select and place these inside their own form to post back with a certain action or different querstring parameter? Can the same controller give me a partial JSON response as well as feeding the full HTML response. Can anyone point me to a good demo that utilises both JSON and normal HTTP posts to produce the same result in ASP.NET MVC. All ASP.NET MVC demo/examples I see forget about the non JavaScript enabled client.</p> <p><strong>Update</strong></p> <p>But isn't that true for Ajax calls using the Microsoft Ajax client library if I read it corectly - which I am wanting to avoid and use only jQuery - apologies should have mentioned that.</p> <p>Also I would prefer not to put that noise everywhere in the controllers (reminds me of ispostback from webforms...shudder).</p> <p>It's a shame there is no attribute that I can use on a controller like with [AcceptVerbs(HttpVerbs.Post)] but for content types e.g [AcceptType(httpTypes.Json)].</p> <p>There must be a better way than using that if statement everywhere.....</p>
[ { "answer_id": 321473, "author": "rodbv", "author_id": 79101, "author_profile": "https://Stackoverflow.com/users/79101", "pm_score": 2, "selected": false, "text": "public ActionResult List()\n{\n if (!Request.IsMvcAjaxRequest())\n {\n // Non AJAX requests see the entire ViewPage.\n return View();\n }\n else\n {\n // AJAX requests just get a trimmed down UserControl.\n return Json(...);\n }\n } \n" } ]
2008/11/26
[ "https://Stackoverflow.com/questions/320135", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6440/" ]