qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
27,405
<p>On an 8-bit micro controller I would like to do the following:</p> <pre><code>16bit_integer = another_16bit_integer * 0.997;</code></pre> <p>with the least possible number of instructions.</p>
[ { "answer_id": 27415, "author": "T Percival", "author_id": 954, "author_profile": "https://Stackoverflow.com/users/954", "pm_score": 2, "selected": false, "text": "16bit_integer = (int16_t) (another_16bit_integer * (int32_t) 997 / 1000);\n" }, { "answer_id": 27418, "author": "Justin Tanner", "author_id": 609, "author_profile": "https://Stackoverflow.com/users/609", "pm_score": 1, "selected": false, "text": "16bit_integer = another_16bit_integer * 0.997; 16bit_integer = (int16_t) (another_16bit_integer * (int32_t) 997 / 1000);" }, { "answer_id": 27451, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "16bit_integer = products[another_16bit_integer];\n" }, { "answer_id": 27479, "author": "Josh", "author_id": 257, "author_profile": "https://Stackoverflow.com/users/257", "pm_score": 0, "selected": false, "text": "16bit_integer = products[another_16bit_integer];\n" }, { "answer_id": 27481, "author": "Mike Thompson", "author_id": 2754, "author_profile": "https://Stackoverflow.com/users/2754", "pm_score": 0, "selected": false, "text": "result16 = operand16 - (operand16 * 3)/1000\n" }, { "answer_id": 27483, "author": "Josh", "author_id": 257, "author_profile": "https://Stackoverflow.com/users/257", "pm_score": 0, "selected": false, "text": "16bit_integer = another_16bit_integer * 0.997;\n 16bit_integer = (int16_t) (another_16bit_integer * (int32_t) 997 / 1000);\n" }, { "answer_id": 28013, "author": "Mike Haboustak", "author_id": 2146, "author_profile": "https://Stackoverflow.com/users/2146", "pm_score": 2, "selected": false, "text": "16bit_integer = another_16bit_integer - 1 - (another_16bit_integer/334);\n" }, { "answer_id": 41497, "author": "smh", "author_id": 1077, "author_profile": "https://Stackoverflow.com/users/1077", "pm_score": 2, "selected": false, "text": "y = 0xFF3B * (int32_t) x >> 16;\n y = (0.997 * 0x10000) * (int32_t)x >> 16;\n" }, { "answer_id": 4758603, "author": "Rocketmagnet", "author_id": 55934, "author_profile": "https://Stackoverflow.com/users/55934", "pm_score": 1, "selected": false, "text": "a = b * 0.99609375;\n a = b;\na -= b>>8;\n a = b;\na -= *((int8*)((&b)+1));\n ; a = b\nMOVFF 0xc4, 0xc2\nNOP\nMOVFF 0xc5, 0xc3\nNOP\n\n; a -= *((int8*)((&b)+1));\nMOVF 0xc5, w\nSUBWF 0xc2, f\nBTFSC STATUS, C\nDECF 0xc\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/27405", "https://Stackoverflow.com", "https://Stackoverflow.com/users/609/" ]
27,407
<p>Virtual memory from a computer size perspective is </p> <blockquote> <p>[a way to make the program] think it has a large range of contiguous addresses; but in reality the parts it is currently using are scattered around RAM, and the inactive parts are saved in a disk file. (<a href="http://en.wikipedia.org/wiki/Virtual_memory" rel="noreferrer">Wikipedia</a>)</p> </blockquote> <p>I would interpret VM Size in the Windows Task manager as either the total addressable virtual memory space or the amount of memory the process is currently using in the virtual memory space. </p> <p>But in the Task Manager the WM Size is in many cases less than Mem Usage, which should be amount of RAM the process is using. Therefor I guess that WM Size means something else?</p>
[ { "answer_id": 27426, "author": "T Percival", "author_id": 954, "author_profile": "https://Stackoverflow.com/users/954", "pm_score": 1, "selected": false, "text": "cat cat /proc/self/maps 00400000-00408000 r-xp /bin/cat\n00607000-00608000 rw-p /bin/cat\n008ac000-008cd000 rw-p [heap]\n7fbd54175000-7fbd543cf000 r--p /usr/lib/locale/locale-archive\n7fbd543cf000-7fbd54519000 r-xp /lib/libc-2.7.so\n7fbd54519000-7fbd54718000 ---p /lib/libc-2.7.so\n7fbd54718000-7fbd5471b000 r--p /lib/libc-2.7.so\n7fbd5471b000-7fbd5471d000 rw-p /lib/libc-2.7.so\n7fbd5471d000-7fbd54722000 rw-p\n7fbd54722000-7fbd5473e000 r-xp /lib/ld-2.7.so\n7fbd5491d000-7fbd5491f000 rw-p \n7fbd5493a000-7fbd5493d000 rw-p\n7fbd5493d000-7fbd5493f000 rw-p /lib/ld-2.7.so\n7fff5c929000-7fff5c93e000 rw-p [stack]\n7fff5c9fe000-7fff5c9ff000 r-xp [vdso]\nffffffffff600000-ffffffffff601000 r-xp [vsyscall]\n [stack] 0x7fff5c9ff000 - 0x7fff5c9fe000 = 0x1000 /lib/libc-2.7.so" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/27407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1918/" ]
27,435
<p>I am working on a web application using Python (Django) and would like to know whether MySQL or PostgreSQL would be more suitable when deploying for production.</p> <p>In one <a href="https://blog.stackoverflow.com/2008/06/podcast-8/">podcast</a> Joel said that he had some problems with MySQL and the data wasn't consistent.</p> <p>I would like to know whether someone had any such problems. Also when it comes to performance which can be easily tweaked?</p>
[ { "answer_id": 27440, "author": "Josh", "author_id": 257, "author_profile": "https://Stackoverflow.com/users/257", "pm_score": 8, "selected": true, "text": "count" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/27435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1448/" ]
27,442
<p>Is there a rake task for backing up the data in your database? </p> <p>I already have my schema backed up, but I want to make a backup of the data. It's a small MySQL database. </p>
[ { "answer_id": 27448, "author": "thelsdj", "author_id": 163, "author_profile": "https://Stackoverflow.com/users/163", "pm_score": 4, "selected": true, "text": "set :dbuser \"user\"\nset :dbhost \"host\"\nset :database \"db\"\n\nnamespace :db do\n desc \"Get the database password from user\"\n task :get_password do\n set(:dbpass) do\n Capistrano::CLI.ui.ask \"Enter mysql password: \"\n end\n end\n\n task :backup_name, :only => { :primary => true } do\n now = Time.now\n run \"mkdir -p #{shared_path}/db_backups\"\n backup_time = [now.year,now.month,now.day,now.hour,now.min,now.sec].join('-')\n set :backup_file, \"#{shared_path}/db_backups/#{database}-snapshot-#{backup_time}.sql\"\n end\n\n desc \"Dump database to backup file\"\n task :dump, :roles => :db, :only => {:primary => true} do\n backup_name\n run \"mysqldump --add-drop-table -u #{dbuser} -h #{dbhost} -p#{dbpass} #{database} | bzip2 -c > #{backup_file}.bz2\"\n end\nend\n" }, { "answer_id": 27503, "author": "Chris Bunch", "author_id": 422, "author_profile": "https://Stackoverflow.com/users/422", "pm_score": 1, "selected": false, "text": "filename = 'wp-config.php'\ndef get_db_info(file)\n username = nil\n password = nil\n db_name = nil\n\n file.each { |line|\n if line =~ /'DB_(USER|PASSWORD|NAME)', '([[:alnum:]]*)'/\n if $1 == \"USER\"\n username = $2\n elsif $1 == \"PASSWORD\"\n password = $2\n elsif $1 == \"NAME\"\n db_name = $2\n end\n end\n }\n\n if username.nil? || password.nil? || db_name.nil?\n puts \"[backup_db][bad] couldn't get all needed info\"\n exit\n end\n\n return username, password, db_name\nend\n\nbegin\n config_file = open(\"#{filename}\")\nrescue Errno::ENOENT\n puts \"[backup_db][bad] File '#{filename}' didn't exist\"\n exit\nelse\n puts \"[backup_db][good] File '#{filename}' existed\"\nend\n\nusername, password, db_name = get_db_info(config_file)\nsql_dump_info = `mysqldump --user=#{username} --password=#{password} #{dbname}`\nputs sql_dump_info\n" }, { "answer_id": 1131737, "author": "Darren Bishop", "author_id": 133330, "author_profile": "https://Stackoverflow.com/users/133330", "pm_score": 2, "selected": false, "text": "db:fixtures:dump db:fixtures:load" }, { "answer_id": 19730313, "author": "mikowiec", "author_id": 2945404, "author_profile": "https://Stackoverflow.com/users/2945404", "pm_score": 0, "selected": false, "text": "#encoding: utf-8\n#require 'fileutils'\n\nnamespace :mls do\n desc 'Create of realty_dev database backup'\n\n task :backup => :environment do\n backup_max_records = 4\n datestamp = Time.now.strftime(\"%Y-%m-%d_%H-%M\")\n backup_dir = File.join(Rails.root, ENV['DIR'] || 'backups', 'db')\n backup_file_name = \"#{datestamp}_#{Rails.env}_dump.sql\"\n backup_file_path = File.join(backup_dir, \"#{backup_file_name}\")\n FileUtils.mkdir_p(backup_dir)\n\n #database processing\n db_config = ActiveRecord::Base.configurations[Rails.env]\n system \"mysqldump -u#{db_config['username']} -p#{db_config['password']} -i -c -q #{db_config['database']} > #{backup_file_path}\"\n raise 'Unable to make DB backup!' if ($?.to_i > 0)\n\n # sql dump file compression\n system \"gzip -9 #{backup_file_path}\"\n\n # backup rotation\n dir = Dir.new(backup_dir)\n backup_all_records = dir.entries.sort[2..-1].reverse\n puts \"Created backup: #{backup_file_name}.gz\"\n #redundant records\n backup_del_records = backup_all_records[backup_max_records..-1] || []\n\n # backup deleting too old records\n for backup_del_record in backup_del_records\n FileUtils.rm_rf(File.join(backup_dir, backup_del_record))\n end\n\n puts \"Deleted #{backup_del_records.length} old backups, #{backup_all_records.length - backup_del_records.length} backups available\"\n puts \"Backup passed\"\n end\nend\n\n=begin\n run by this command: \" rake db:backup RAILS_ENV=\"development\" \"\n=end\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/27442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1632/" ]
27,472
<p>I have a long running SQL statement that I want to run, and no matter what I put in the "timeout=" clause of my connection string, it always seems to end after 30 seconds. </p> <p>I'm just using <code>SqlHelper.ExecuteNonQuery()</code> to execute it, and letting it take care of opening connections, etc.</p> <p>Is there something else that could be overriding my timeout, or causing sql server to ignore it? I have run profiler over the query, and the trace doesn't look any different when I run it in management studio, versus in my code.</p> <p>Management studio completes the query in roughly a minute, but even with a timeout set to 300, or 30000, my code still times out after 30 seconds.</p>
[ { "answer_id": 27477, "author": "Ishmaeel", "author_id": 227, "author_profile": "https://Stackoverflow.com/users/227", "pm_score": 4, "selected": false, "text": "SqlCommand command = new SqlCommand(sqlQuery, _Database.Connection);\ncommand.CommandTimeout = 0;\nint rows = command.ExecuteNonQuery();\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/27472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/489/" ]
27,474
<p>I need to send hundreds of newsletters, but would like to check first if email exists on server. It's called <a href="http://en.wikipedia.org/wiki/Simple_Mail_Transfer_Protocol" rel="noreferrer">SMTP</a> validation, at least I think so, based on my research on Internet. </p> <p>There's several libraries that can do that, and also a page with open-source code in <a href="http://en.wikipedia.org/wiki/Active_Server_Pages" rel="noreferrer">ASP Classic</a> (<a href="http://www.coveryourasp.com/ValidateEmail.asp#Result3" rel="noreferrer">http://www.coveryourasp.com/ValidateEmail.asp#Result3</a>), but I have hard time reading ASP Classic, and it seems that it uses some third-party library... </p> <p>Is there some code for SMTP validation in C#, and/or general explanation of how it works?</p>
[ { "answer_id": 2795865, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "\n // Create a new instance of the EmailValidator class.\n EmailValidator em = new EmailValidator();\n em.MessageLogging += em_MessageLogging;\n em.EmailValidated += em_EmailValidationCompleted;\n try\n {\n string[] list = new string[3] { \"[email protected]\", \"[email protected]\", \"[email protected]\" };\n em.ValidateEmails(list);\n }\n catch (EmailValidatorException exc2)\n {\n Console.WriteLine(\"EmailValidatorException: \" + exc2.Message);\n }\n" }, { "answer_id": 21849102, "author": "Rahul Saraswat", "author_id": 2810254, "author_profile": "https://Stackoverflow.com/users/2810254", "pm_score": 2, "selected": false, "text": "public class EmailTest {\n private static int hear(BufferedReader in) throws IOException {\n String line = null;\n int res = 0;\n\n while ((line = in.readLine()) != null) {\n String pfx = line.substring(0, 3);\n try {\n res = Integer.parseInt(pfx);\n } catch (Exception ex) {\n res = -1;\n }\n if (line.charAt(3) != '-')\n break;\n }\n\n return res;\n }\n\n private static void say(BufferedWriter wr, String text) throws IOException {\n wr.write(text + \"\\r\\n\");\n wr.flush();\n\n return;\n }\n\n @SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n private static ArrayList getMX(String hostName) throws NamingException {\n // Perform a DNS lookup for MX records in the domain\n Hashtable env = new Hashtable();\n env.put(\"java.naming.factory.initial\", \"com.sun.jndi.dns.DnsContextFactory\");\n DirContext ictx = new InitialDirContext(env);\n Attributes attrs = ictx.getAttributes(hostName, new String[] { \"MX\" });\n Attribute attr = attrs.get(\"MX\");\n\n // if we don't have an MX record, try the machine itself\n if ((attr == null) || (attr.size() == 0)) {\n attrs = ictx.getAttributes(hostName, new String[] { \"A\" });\n attr = attrs.get(\"A\");\n if (attr == null)\n throw new NamingException(\"No match for name '\" + hostName + \"'\");\n }\n /*\n Huzzah! we have machines to try. Return them as an array list\n NOTE: We SHOULD take the preference into account to be absolutely\n correct. This is left as an exercise for anyone who cares.\n */\n ArrayList res = new ArrayList();\n NamingEnumeration en = attr.getAll();\n\n while (en.hasMore()) {\n String mailhost;\n String x = (String) en.next();\n String f[] = x.split(\" \");\n // THE fix *************\n if (f.length == 1)\n mailhost = f[0];\n else if (f[1].endsWith(\".\"))\n mailhost = f[1].substring(0, (f[1].length() - 1));\n else\n mailhost = f[1];\n // THE fix *************\n res.add(mailhost);\n }\n return res;\n }\n\n @SuppressWarnings(\"rawtypes\")\n public static boolean isAddressValid(String address) {\n // Find the separator for the domain name\n int pos = address.indexOf('@');\n\n // If the address does not contain an '@', it's not valid\n if (pos == -1)\n return false;\n\n // Isolate the domain/machine name and get a list of mail exchangers\n String domain = address.substring(++pos);\n ArrayList mxList = null;\n try {\n mxList = getMX(domain);\n } catch (NamingException ex) {\n return false;\n }\n\n /*\n Just because we can send mail to the domain, doesn't mean that the\n address is valid, but if we can't, it's a sure sign that it isn't\n */\n if (mxList.size() == 0)\n return false;\n\n /* \n Now, do the SMTP validation, try each mail exchanger until we get\n a positive acceptance. It *MAY* be possible for one MX to allow\n a message [store and forwarder for example] and another [like\n the actual mail server] to reject it. This is why we REALLY ought\n to take the preference into account.\n */\n for (int mx = 0; mx < mxList.size(); mx++) {\n boolean valid = false;\n try {\n int res;\n //\n Socket skt = new Socket((String) mxList.get(mx), 25);\n BufferedReader rdr = new BufferedReader(new InputStreamReader(skt.getInputStream()));\n BufferedWriter wtr = new BufferedWriter(new OutputStreamWriter(skt.getOutputStream()));\n\n res = hear(rdr);\n if (res != 220)\n throw new Exception(\"Invalid header\");\n say(wtr, \"EHLO rgagnon.com\");\n\n res = hear(rdr);\n if (res != 250)\n throw new Exception(\"Not ESMTP\");\n\n // validate the sender address\n say(wtr, \"MAIL FROM: <[email protected]>\");\n res = hear(rdr);\n if (res != 250)\n throw new Exception(\"Sender rejected\");\n\n say(wtr, \"RCPT TO: <\" + address + \">\");\n res = hear(rdr);\n\n // be polite\n say(wtr, \"RSET\");\n hear(rdr);\n say(wtr, \"QUIT\");\n hear(rdr);\n if (res != 250)\n throw new Exception(\"Address is not valid!\");\n\n valid = true;\n rdr.close();\n wtr.close();\n skt.close();\n } catch (Exception ex) {\n // Do nothing but try next host\n ex.printStackTrace();\n } finally {\n if (valid)\n return true;\n }\n }\n return false;\n }\n\n public static void main(String args[]) {\n String testData[] = { \"[email protected]\", \"[email protected]\", \"[email protected]\",\n \"[email protected]\" };\n System.out.println(testData.length);\n for (int ctr = 0; ctr < testData.length; ctr++) {\n System.out.println(testData[ctr] + \" is valid? \" + isAddressValid(testData[ctr]));\n }\n return;\n }\n}\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/27474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1407/" ]
27,482
<p>Im currently writing my bachelor thesis with latex and using TexnicCenter. I want to be able to send my generated pdf file to people and they should be able to write comments. It seems like commenting is not allowed by default, how do I change this?</p> <p>I am using straight to PDF with pdflatex and acrobat reader 9 to read and comment on the files</p>
[ { "answer_id": 27513, "author": "onnodb", "author_id": 1037, "author_profile": "https://Stackoverflow.com/users/1037", "pm_score": 2, "selected": false, "text": "pdflatex pdflatex" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/27482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2450/" ]
27,499
<p>Recently Jeff has <a href="http://blog.codinghorror.com/deadlocked/" rel="noreferrer">posted</a> regarding his trouble with database deadlocks related to reading. <a href="https://en.m.wikipedia.org/wiki/Multiversion_concurrency_control" rel="noreferrer">Multiversion Concurrency Control (MVCC)</a> claims to solve this problem. What is it, and what databases support it?</p> <p>updated: these support it (which others?)</p> <ul> <li>oracle</li> <li>postgresql </li> </ul>
[ { "answer_id": 952122, "author": "John Greeley", "author_id": 62209, "author_profile": "https://Stackoverflow.com/users/62209", "pm_score": 3, "selected": false, "text": "SET READ_COMMITTED_SNAPSHOT ON" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/27499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/116/" ]
27,509
<p>How do I check if an object property in JavaScript is undefined?</p>
[ { "answer_id": 27510, "author": "tslocum", "author_id": 1662, "author_profile": "https://Stackoverflow.com/users/1662", "pm_score": -1, "selected": false, "text": "if (somevariable == undefined) {\n alert('the variable is not defined!');\n}\n function isset(varname){\n return(typeof(window[varname]) != 'undefined');\n}\n" }, { "answer_id": 27517, "author": "Pandincus", "author_id": 2273, "author_profile": "https://Stackoverflow.com/users/2273", "pm_score": 7, "selected": false, "text": "if (something == undefined)\n var person = {\n name: \"John\",\n age: 28,\n sex: \"male\"\n};\n\nalert(person.name); // \"John\"\nalert(person.fakeVariable); // undefined\n" }, { "answer_id": 27911, "author": "Ricky", "author_id": 653, "author_profile": "https://Stackoverflow.com/users/653", "pm_score": 4, "selected": false, "text": "null == undefined\n if (something === undefined)\n" }, { "answer_id": 416327, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 13, "selected": true, "text": "undefined if(o.myProperty === undefined) {\n alert(\"myProperty value is the special value `undefined`\");\n}\n undefined if(!o.hasOwnProperty('myProperty')) {\n alert(\"myProperty does not exist\");\n}\n undefined if(typeof myVariable === 'undefined') {\n alert('myVariable is either the special value `undefined`, or it has not been declared');\n}\n undefined foo === undefined undefined if(myVariable === void 0) {\n alert(\"myVariable is the special value `undefined`\");\n}\n" }, { "answer_id": 3232194, "author": "Rixius", "author_id": 212307, "author_profile": "https://Stackoverflow.com/users/212307", "pm_score": 2, "selected": false, "text": "function isUnset(inp) {\n return (typeof inp === 'undefined')\n}\n if (isUnset(var)) {\n // initialize variable here\n}\n" }, { "answer_id": 3345556, "author": "Kevin", "author_id": 403606, "author_profile": "https://Stackoverflow.com/users/403606", "pm_score": 6, "selected": false, "text": "if ( typeof( something ) == \"undefined\") \n" }, { "answer_id": 3550319, "author": "MarkPflug", "author_id": 190371, "author_profile": "https://Stackoverflow.com/users/190371", "pm_score": 10, "selected": false, "text": "if (typeof myVar === \"undefined\")\n myVar var undefined = false; // Shockingly, this is completely legal!\nif (myVar === undefined) {\n alert(\"You have been misled. Run away!\");\n}\n myVar === undefined" }, { "answer_id": 3770178, "author": "Eric", "author_id": 455129, "author_profile": "https://Stackoverflow.com/users/455129", "pm_score": 5, "selected": false, "text": "=== typeof typeof x; // some string literal \"string\", \"object\", \"undefined\"\nif (typeof x === \"string\") { // === is redundant because we already know typeof returns a string literal\nif (typeof x == \"string\") { // sufficient\n" }, { "answer_id": 6274093, "author": "Michael Anderson", "author_id": 221955, "author_profile": "https://Stackoverflow.com/users/221955", "pm_score": 6, "selected": false, "text": "undefined undefined typeof obj.foo \"foo\" in obj | typeof obj.x === 'undefined' | !(\"x\" in obj)\n1. { x:1 } | false | false\n2. { x : (function(){})() } | true | false\n3. {} | true | true\n null | typeof obj.x === 'undefined' | !(\"x\" in obj)\n { x:null } | false | false\n if( typeof blob.x != 'undefined' ) { fn(blob.x); }\n if( \"x\" in blob ) { fn(blob.x); }\n" }, { "answer_id": 7041744, "author": "Codebeat", "author_id": 565244, "author_profile": "https://Stackoverflow.com/users/565244", "pm_score": 4, "selected": false, "text": "if (myvar == undefined )\n{ \n alert('var does not exists or is not initialized');\n}\n myvar var myvar = 'test';\n if(window.myvar == undefined )\n{ \n alert('var does not exists or is not initialized');\n}\n !window.myvar !window.myvar myvar = undefined myvar = false myvar = 0 if( !window.myvar || typeof window.myvar != 'string' )\n{\n alert('var does not exists or is not type of string');\n}\n" }, { "answer_id": 7793028, "author": "Anoop", "author_id": 460942, "author_profile": "https://Stackoverflow.com/users/460942", "pm_score": 3, "selected": false, "text": " function getAllUndefined(object) {\n\n function convertPath(arr, key) {\n var path = \"\";\n for (var i = 1; i < arr.length; i++) {\n\n path += arr[i] + \"->\";\n }\n path += key;\n return path;\n }\n\n\n var stack = [];\n var saveUndefined= [];\n function getUndefiend(obj, key) {\n\n var t = typeof obj;\n switch (t) {\n case \"object\":\n if (t === null) {\n return false;\n }\n break;\n case \"string\":\n case \"number\":\n case \"boolean\":\n case \"null\":\n return false;\n default:\n return true;\n }\n stack.push(key);\n for (k in obj) {\n if (obj.hasOwnProperty(k)) {\n v = getUndefiend(obj[k], k);\n if (v) {\n saveUndefined.push(convertPath(stack, k));\n }\n }\n }\n stack.pop();\n\n }\n\n getUndefiend({\n \"\": object\n }, \"\");\n return saveUndefined;\n }\n" }, { "answer_id": 9342877, "author": "Corey Richardson", "author_id": 1419479, "author_profile": "https://Stackoverflow.com/users/1419479", "pm_score": -1, "selected": false, "text": "Object.hasOwnProperty(o, 'propertyname');" }, { "answer_id": 12589152, "author": "Joe Johnson", "author_id": 836474, "author_profile": "https://Stackoverflow.com/users/836474", "pm_score": 5, "selected": false, "text": "if (obj && obj.prop) {\n // Do something;\n}\n ?." }, { "answer_id": 14306293, "author": "drzaus", "author_id": 1037948, "author_profile": "https://Stackoverflow.com/users/1037948", "pm_score": 5, "selected": false, "text": "someObject.<whatever> var in (function(undefined) {\n var definedButNotInitialized;\n definedAndInitialized = 3;\n someObject = {\n firstProp: \"1\"\n , secondProp: false\n // , undefinedProp not defined\n }\n // var notDefined;\n\n var tests = [\n 'definedButNotInitialized in window',\n 'definedAndInitialized in window',\n 'someObject.firstProp in window',\n 'someObject.secondProp in window',\n 'someObject.undefinedProp in window',\n 'notDefined in window',\n\n '\"definedButNotInitialized\" in window',\n '\"definedAndInitialized\" in window',\n '\"someObject.firstProp\" in window',\n '\"someObject.secondProp\" in window',\n '\"someObject.undefinedProp\" in window',\n '\"notDefined\" in window',\n\n 'typeof definedButNotInitialized == \"undefined\"',\n 'typeof definedButNotInitialized === typeof undefined',\n 'definedButNotInitialized === undefined',\n '! definedButNotInitialized',\n '!! definedButNotInitialized',\n\n 'typeof definedAndInitialized == \"undefined\"',\n 'typeof definedAndInitialized === typeof undefined',\n 'definedAndInitialized === undefined',\n '! definedAndInitialized',\n '!! definedAndInitialized',\n\n 'typeof someObject.firstProp == \"undefined\"',\n 'typeof someObject.firstProp === typeof undefined',\n 'someObject.firstProp === undefined',\n '! someObject.firstProp',\n '!! someObject.firstProp',\n\n 'typeof someObject.secondProp == \"undefined\"',\n 'typeof someObject.secondProp === typeof undefined',\n 'someObject.secondProp === undefined',\n '! someObject.secondProp',\n '!! someObject.secondProp',\n\n 'typeof someObject.undefinedProp == \"undefined\"',\n 'typeof someObject.undefinedProp === typeof undefined',\n 'someObject.undefinedProp === undefined',\n '! someObject.undefinedProp',\n '!! someObject.undefinedProp',\n\n 'typeof notDefined == \"undefined\"',\n 'typeof notDefined === typeof undefined',\n 'notDefined === undefined',\n '! notDefined',\n '!! notDefined'\n ];\n\n var output = document.getElementById('results');\n var result = '';\n for(var t in tests) {\n if( !tests.hasOwnProperty(t) ) continue; // bleh\n\n try {\n result = eval(tests[t]);\n } catch(ex) {\n result = 'Exception--' + ex;\n }\n console.log(tests[t], result);\n output.innerHTML += \"\\n\" + tests[t] + \": \" + result;\n }\n})();\n definedButNotInitialized in window: true\ndefinedAndInitialized in window: false\nsomeObject.firstProp in window: false\nsomeObject.secondProp in window: false\nsomeObject.undefinedProp in window: true\nnotDefined in window: Exception--ReferenceError: notDefined is not defined\n\"definedButNotInitialized\" in window: false\n\"definedAndInitialized\" in window: true\n\"someObject.firstProp\" in window: false\n\"someObject.secondProp\" in window: false\n\"someObject.undefinedProp\" in window: false\n\"notDefined\" in window: false\ntypeof definedButNotInitialized == \"undefined\": true\ntypeof definedButNotInitialized === typeof undefined: true\ndefinedButNotInitialized === undefined: true\n! definedButNotInitialized: true\n!! definedButNotInitialized: false\ntypeof definedAndInitialized == \"undefined\": false\ntypeof definedAndInitialized === typeof undefined: false\ndefinedAndInitialized === undefined: false\n! definedAndInitialized: false\n!! definedAndInitialized: true\ntypeof someObject.firstProp == \"undefined\": false\ntypeof someObject.firstProp === typeof undefined: false\nsomeObject.firstProp === undefined: false\n! someObject.firstProp: false\n!! someObject.firstProp: true\ntypeof someObject.secondProp == \"undefined\": false\ntypeof someObject.secondProp === typeof undefined: false\nsomeObject.secondProp === undefined: false\n! someObject.secondProp: true\n!! someObject.secondProp: false\ntypeof someObject.undefinedProp == \"undefined\": true\ntypeof someObject.undefinedProp === typeof undefined: true\nsomeObject.undefinedProp === undefined: true\n! someObject.undefinedProp: true\n!! someObject.undefinedProp: false\ntypeof notDefined == \"undefined\": true\ntypeof notDefined === typeof undefined: true\nnotDefined === undefined: Exception--ReferenceError: notDefined is not defined\n! notDefined: Exception--ReferenceError: notDefined is not defined\n!! notDefined: Exception--ReferenceError: notDefined is not defined\n" }, { "answer_id": 18135509, "author": "Konstantin Smolyanin", "author_id": 1823469, "author_profile": "https://Stackoverflow.com/users/1823469", "pm_score": 7, "selected": false, "text": "var o = { a: undefined }\n o.a o.b typeof o.a == 'undefined' // true\ntypeof o.b == 'undefined' // true\no.a === undefined // true\no.b === undefined // true\n'a' in o // true\n'b' in o // false\n typeof obj.prop == 'undefined' obj.prop === undefined 'prop' in obj obj.prop === undefined // IMHO, see \"final fight\" below\n 'prop' in obj\n x.a === undefined typeof x.a == 'undefined' ReferenceError: x is not defined undefined window.undefined obj.prop === undefined typeof obj.prop == 'undefined' obj.prop === undefined undefined obj.prop === undefined undefined typeof obj.prop == 'undefined' typeof obj.prop == 'undefined' 'undefned' undefined global.undefined" }, { "answer_id": 18254258, "author": "wayneseymour", "author_id": 352033, "author_profile": "https://Stackoverflow.com/users/352033", "pm_score": 3, "selected": false, "text": "if( typeof restResult.data[0] === \"undefined\" ) { throw \"Some error\"; }\n" }, { "answer_id": 20679527, "author": "Marthijn", "author_id": 788840, "author_profile": "https://Stackoverflow.com/users/788840", "pm_score": 4, "selected": false, "text": "function isUndefined(obj){\n return obj === void 0;\n}\n" }, { "answer_id": 20883574, "author": "bevacqua", "author_id": 389745, "author_profile": "https://Stackoverflow.com/users/389745", "pm_score": 3, "selected": false, "text": "void 0 if (foo !== void 0)\n if (typeof foo !== 'undefined')" }, { "answer_id": 21682564, "author": "DenisS", "author_id": 2088061, "author_profile": "https://Stackoverflow.com/users/2088061", "pm_score": 4, "selected": false, "text": "if (window.x) var x; if (window.history) {\n history.call_some_function();\n}\n window.x" }, { "answer_id": 22053469, "author": "Ry-", "author_id": 707111, "author_profile": "https://Stackoverflow.com/users/707111", "pm_score": 8, "selected": false, "text": "typeof undefined undefined typeof 'undefined' var snapshot = …;\n\nif (typeof snaposhot === 'undefined') {\n // ^\n // misspelled¹ – this will never run, but it won’t throw an error!\n}\n var foo = …;\n\nif (typeof foo === 'undefned') {\n // ^\n // misspelled – this will never run, but it won’t throw an error!\n}\n typeof module !== 'undefined' typeof var foo = …;\n\nif (foo === undefined) {\n ⋮\n}\n var foo function bar(foo) { … } bar() undefined undefined undefined Object Math NaN undefined void 0 typeof typeof if (typeof foo.bar === 'undefined') {\n ⋮\n}\n if (foo.bar === undefined) {\n ⋮\n}\n typeof === === undefined undefined undefined undefined undefined undefined 'key' in obj Object.prototype.hasOwnProperty.call(obj, 'key') undefined undefined" }, { "answer_id": 23463075, "author": "sam", "author_id": 822138, "author_profile": "https://Stackoverflow.com/users/822138", "pm_score": 4, "selected": false, "text": "\"propertyName\" in obj //-> true | false\n" }, { "answer_id": 24243518, "author": "raskalbass", "author_id": 1289868, "author_profile": "https://Stackoverflow.com/users/1289868", "pm_score": 2, "selected": false, "text": "if (!variable){\n // Do it if the variable is undefined\n}\n if (variable){\n // Do it if the variable is defined\n}\n" }, { "answer_id": 24277572, "author": "Juan Garcia", "author_id": 1802325, "author_profile": "https://Stackoverflow.com/users/1802325", "pm_score": 3, "selected": false, "text": "var hasUndefinedProperty = function hasUndefinedProperty(obj, prop){\n return ((prop in obj) && (typeof obj[prop] == 'undefined'));\n};\n var a = { b : 1, e : null };\na.c = a.d;\n\nhasUndefinedProperty(a, 'b'); // false: b is defined as 1\nhasUndefinedProperty(a, 'c'); // true: c is defined as undefined\nhasUndefinedProperty(a, 'd'); // false: d is undefined\nhasUndefinedProperty(a, 'e'); // false: e is defined as null\n\n// And now...\ndelete a.c ;\nhasUndefinedProperty(a, 'c'); // false: c is undefined\n var undefined ; undefined ; // undefined\n({}).a ; // undefined\n[].a ; // undefined\n''.a ; // undefined\n(function(){}()) ; // undefined\nvoid(0) ; // undefined\neval() ; // undefined\n1..a ; // undefined\n/a/.a ; // undefined\n(true).a ; // undefined\n" }, { "answer_id": 24626893, "author": "Angelin Nadar", "author_id": 412591, "author_profile": "https://Stackoverflow.com/users/412591", "pm_score": 3, "selected": false, "text": "//Just in JavaScript\nvar s; // Undefined\nif (typeof s == \"undefined\" || s === null){\n alert('either it is undefined or value is null')\n}\n jQuery.isEmptyObject() var s; // Undefined\njQuery.isEmptyObject(s); // Will return true;\n\ns = null; // Defined as null\njQuery.isEmptyObject(s); // Will return true;\n\n//Usage\nif (jQuery.isEmptyObject(s)) {\n alert('Either variable:s is undefined or its value is null');\n} else {\n alert('variable:s has value ' + s);\n}\n\ns = 'something'; // Defined with some value\njQuery.isEmptyObject(s); // Will return false;\n" }, { "answer_id": 26273383, "author": "Seti", "author_id": 3535045, "author_profile": "https://Stackoverflow.com/users/3535045", "pm_score": 2, "selected": false, "text": "undefined Object.defineProperty(window, 'undefined', {});\n window.undefined \"use strict\"" }, { "answer_id": 27474938, "author": "Vitalii Fedorenko", "author_id": 288671, "author_profile": "https://Stackoverflow.com/users/288671", "pm_score": 3, "selected": false, "text": "angular.isUndefined(obj)\nangular.isUndefined(obj.prop)\n _.isUndefined(obj) \n_.isUndefined(obj.prop) \n" }, { "answer_id": 28522648, "author": "Travis", "author_id": 4303905, "author_profile": "https://Stackoverflow.com/users/4303905", "pm_score": 4, "selected": false, "text": "true null undefined undefined if(obj.prop === void 0) console.log(\"The value has never been defined\");\n true undefined === undefined if(obj.prop === undefined) console.log(\"The value is defined as undefined, or never defined\");\n undefined null if(obj.prop == false || obj.prop === null || obj.prop === undefined) {\n console.log(\"The value is falsy, null, or undefined\");\n}\n" }, { "answer_id": 28902597, "author": "Val", "author_id": 1083704, "author_profile": "https://Stackoverflow.com/users/1083704", "pm_score": 3, "selected": false, "text": "if (this.variable) if (variable) obj.someField this window if (this.abc) \n alert(\"defined\"); \nelse \n alert(\"undefined\");\n\nabc = \"abc\";\nif (this.abc) \n alert(\"defined\"); \nelse \n alert(\"undefined\"); abc" }, { "answer_id": 32009076, "author": "Mike Clark", "author_id": 4261022, "author_profile": "https://Stackoverflow.com/users/4261022", "pm_score": 2, "selected": false, "text": "if (typeof something === \"undefined\") {\n alert(\"undefined\");\n}\n if (typeof something !== \"undefined\") {\n alert(\"not undefined\");\n}\n" }, { "answer_id": 34782448, "author": "lzl124631x", "author_id": 3127828, "author_profile": "https://Stackoverflow.com/users/3127828", "pm_score": 2, "selected": false, "text": "var undefined;\nfunction isUndefined(value) {\n return value === undefined;\n}\n undefined undefined value undefined function isUndefined(value) {\n return value === void 0;\n}\n" }, { "answer_id": 35768990, "author": "Marian Klühspies", "author_id": 2324388, "author_profile": "https://Stackoverflow.com/users/2324388", "pm_score": 3, "selected": false, "text": "var a = obj.prop || defaultValue;\n var yourFunction = function(config){\n\n this.config = config || {};\n this.yourConfigValue = config.yourConfigValue || 1;\n console.log(this.yourConfigValue);\n}\n yourFunction({yourConfigValue:2});\n//=> 2\n\nyourFunction();\n//=> 1\n\nyourFunction({otherProperty:5});\n//=> 1\n" }, { "answer_id": 43058440, "author": "Patrick Roberts", "author_id": 1541563, "author_profile": "https://Stackoverflow.com/users/1541563", "pm_score": 1, "selected": false, "text": "typeof Object.getOwnPropertyDescriptor() undefined // to test someObject.someProperty\nvar descriptor = Object.getOwnPropertyDescriptor(someObject, 'someProperty');\n\nif (typeof descriptor === 'undefined') {\n // was never initialized\n} else if (typeof descriptor.value === 'undefined') {\n if (descriptor.get || descriptor.set) {\n // is an accessor property, defined via getter and setter\n } else {\n // is initialized with `undefined`\n }\n} else {\n // is initialized with some other value\n}\n" }, { "answer_id": 43527813, "author": "Bekim Bacaj", "author_id": 5896426, "author_profile": "https://Stackoverflow.com/users/5896426", "pm_score": 0, "selected": false, "text": "undefined \"propertyName\" in containerObject && \"\"+containerObject[\"propertyName\"] == \"undefined\";\n>> true \\ false\n true undefined undefined == === containerObject = { propertyName: void \"anything\" }\n>> Object { propertyName: undefined }\n\n// Now the testing\n\n\"propertyName\" in containerObject && \"\"+containerObject[\"propertyName\"] == \"undefined\";\n>> true\n\n/* Which makes sure that nonexistent property will not return a false positive\n * unless it is previously defined */\n\n\"foo\" in containerObject && \"\"+containerObject[\"foo\"] == \"undefined\";\n>> false\n" }, { "answer_id": 44161028, "author": "Alireza", "author_id": 5423108, "author_profile": "https://Stackoverflow.com/users/5423108", "pm_score": 4, "selected": false, "text": "typeof typeof whatever === 'undefined' isUndefined() function isUndefined(value) {return typeof value === 'undefined';} \n false true var stackoverflow = {};\nstackoverflow.javascipt = 'javascript';\nvar today;\nvar self = this;\nvar num = 8;\nvar list = [1, 2, 3, 4, 5];\nvar y = null;\n isUndefined(stackoverflow); //false\nisUndefined(stackoverflow.javascipt); //false\nisUndefined(today); //true\nisUndefined(self); //false\nisUndefined(num); //false\nisUndefined(list); //false\nisUndefined(y); //false\nisUndefined(stackoverflow.java); //true\nisUndefined(stackoverflow.php); //true\nisUndefined(stackoverflow && stackoverflow.css); //true\n typeof isUndefined(x.css);\nVM808:2 Uncaught ReferenceError: x is not defined(…)\n if(typeof x !== 'undefined') {\n //do something\n}\n function isDefined(value) {return typeof value !== 'undefined';}\n typeof var x;\nif (x === undefined) {\n // these statements execute\n}\nelse {\n // these statements do not execute\n}\n var x;\nif (typeof x === 'undefined') {\n // these statements execute\n}\n // x has not been declared before\nif (typeof x === 'undefined') { // evaluates to true without errors\n // these statements execute\n}\n\nif (x === undefined) { // throws a ReferenceError\n\n}\n var x;\nif (x === void 0) {\n // these statements execute\n}\n\n// y has not been declared before\nif (y === void 0) {\n // throws a ReferenceError (in contrast to `typeof`)\n}\n" }, { "answer_id": 44556602, "author": "IliasT", "author_id": 3015469, "author_profile": "https://Stackoverflow.com/users/3015469", "pm_score": 2, "selected": false, "text": "undefined null myVar == null true myVar undefined null false 0 false '' NaN isNil" }, { "answer_id": 46988171, "author": "blackmiaool", "author_id": 4831179, "author_profile": "https://Stackoverflow.com/users/4831179", "pm_score": 3, "selected": false, "text": "function isUndefined1(val) {\n try {\n val.a;\n } catch (e) {\n return /undefined/.test(e.message);\n }\n return false;\n}\n\nfunction isUndefined2(val) {\n return !val && val+'' === 'undefined';\n}\n\nfunction isUndefined3(val) {\n const defaultVal = {};\n return ((input = defaultVal) => input === defaultVal)(val);\n}\n\nfunction test(func){\n console.group(`test start :`+func.name);\n console.log(func(undefined));\n console.log(func(null));\n console.log(func(1));\n console.log(func(\"1\"));\n console.log(func(0));\n console.log(func({}));\n console.log(func(function () { }));\n console.groupEnd();\n}\ntest(isUndefined1);\ntest(isUndefined2);\ntest(isUndefined3); \"undefined\" undefined" }, { "answer_id": 49158713, "author": "Aditya Vashishtha", "author_id": 8618959, "author_profile": "https://Stackoverflow.com/users/8618959", "pm_score": 0, "selected": false, "text": "var ojb ={\n age: 12\n}\n\nif(ojb.hasOwnProperty('name')){\n console.log('property exists and is not undefined');\n}\n true" }, { "answer_id": 49412206, "author": "Sarkis Arutiunian", "author_id": 5278472, "author_profile": "https://Stackoverflow.com/users/5278472", "pm_score": 2, "selected": false, "text": "function resolveUnknownProps(obj, resolveKey) {\n const handler = {\n get(target, key) {\n if (\n target[key] !== null &&\n typeof target[key] === 'object'\n ) {\n return resolveUnknownProps(target[key], resolveKey);\n } else if (!target[key]) {\n return resolveUnknownProps({ [resolveKey]: true }, resolveKey);\n }\n\n return target[key];\n },\n };\n\n return new Proxy(obj, handler);\n}\n\nconst user = {}\n\nconsole.log(resolveUnknownProps(user, 'isUndefined').personalInfo.name.something.else); // { isUndefined: true }\n const { isUndefined } = resolveUnknownProps(user, 'isUndefined').personalInfo.name.something.else;\nif (!isUndefined) {\n // Do something\n}\n" }, { "answer_id": 49706807, "author": "Aliaksandr Sushkevich", "author_id": 7600492, "author_profile": "https://Stackoverflow.com/users/7600492", "pm_score": 0, "selected": false, "text": "undefined _.isUndefined(undefined) // => true\n_.isUndefined(null) // => false\n const object = { 'a': { 'b': 2 } }\n\n_.has(object, 'a.b') // => true\n_.has(object, 'a.c') // => false\n" }, { "answer_id": 51478480, "author": "Krishnadas PC", "author_id": 2295484, "author_profile": "https://Stackoverflow.com/users/2295484", "pm_score": 1, "selected": false, "text": "undefined var handler = {\n get: function(target, name) {\n return name in target ? target[name] : 'N/A';\n }\n};\n\nvar p = new Proxy({}, handler);\np.name = 'Kevin';\nconsole.log('Name: ' +p.name, ', Age: '+p.age, ', Gender: '+p.gender)\n Name: Kevin , Age: N/A , Gender: N/A\n" }, { "answer_id": 52275862, "author": "CodeDraken", "author_id": 10326132, "author_profile": "https://Stackoverflow.com/users/10326132", "pm_score": 2, "selected": false, "text": "in if (key in obj) {\n // Do something\n} else {\n // Create key\n}\n\nconst obj = {\n 0: 'abc',\n 1: 'def'\n}\n\nconst hasZero = 0 in obj\n\nconsole.log(hasZero) // true\n" }, { "answer_id": 58129331, "author": "Przemek Struciński", "author_id": 8680601, "author_profile": "https://Stackoverflow.com/users/8680601", "pm_score": 4, "selected": false, "text": "const userPhone = user?.contactDetails?.phone;\n" }, { "answer_id": 59999090, "author": "Ravi Makwana", "author_id": 6631280, "author_profile": "https://Stackoverflow.com/users/6631280", "pm_score": 0, "selected": false, "text": "undefined" }, { "answer_id": 61550879, "author": "Kiran Maniya", "author_id": 8203357, "author_profile": "https://Stackoverflow.com/users/8203357", "pm_score": 0, "selected": false, "text": "if(!ob.someProp){\n console.log('someProp is falsy')\n}\n === undefined if if(ob.someProp === undefined){\n console.log('someProp is undefined')\n}\n typeof typeof if(typeof ob.someProp === 'undefined'){\n console.log('someProp is undefined')\n}\n hasOwnProperty hasOwnProperty if(!ob.hasOwnProperty('someProp')){\n console.log('someProp is undefined')\n}\n undefined if undefined NaN false '' 0 if hasOwnProperty" }, { "answer_id": 61607190, "author": "Sajad Saderi", "author_id": 9845404, "author_profile": "https://Stackoverflow.com/users/9845404", "pm_score": 3, "selected": false, "text": "x = {prop:{name:\"sajad\"}}\n\nconsole.log(x.prop?.name) // Output is: \"sajad\"\nconsole.log(x.prop?.lastName) // Output is: undefined\n if(x.prop?.lastName) // The result of this 'if' statement is false and is not throwing an error\n" }, { "answer_id": 63021093, "author": "Kamil Kiełczewski", "author_id": 860099, "author_profile": "https://Stackoverflow.com/users/860099", "pm_score": 0, "selected": false, "text": "undefined let obj = {\n a: 666,\n u: undefined // The 'u' property has value 'undefined'\n // The 'x' property does not exist\n}\n\nconsole.log('>>> good results:');\nconsole.log('A', \"u\" in obj, \"x\" in obj);\nconsole.log('B', obj.hasOwnProperty(\"u\"), obj.hasOwnProperty(\"x\"));\n\nconsole.log('\\n>>> bad results:');\nconsole.log('C', obj.u === undefined, obj.x === undefined);\nconsole.log('D', obj.u == undefined, obj.x == undefined);\nconsole.log('E', obj[\"u\"] === undefined, obj[\"x\"] === undefined);\nconsole.log('F', obj[\"u\"] == undefined, obj[\"x\"] == undefined);\nconsole.log('G', !obj.u, !obj.x);\nconsole.log('H', typeof obj.u === 'undefined', typeof obj.x === 'undefined');" }, { "answer_id": 64125263, "author": "Hanzla Habib", "author_id": 3946527, "author_profile": "https://Stackoverflow.com/users/3946527", "pm_score": 2, "selected": false, "text": " const adventurer = {\n name: 'Alice',\n cat: {\n name: 'Dinah'\n }\n};\n\nconst dogName = adventurer.dog?.name;\nconsole.log(dogName);\n// expected output: undefined\n\nconsole.log(adventurer.someNonExistentMethod?.());\n// expected output: undefined\n if (response && response.data && response.data.someData && response.data.someData.someMoreData) {}\n if( response?.data?.someData?.someMoreData) {}\n" }, { "answer_id": 65342690, "author": "Adam111p", "author_id": 3058581, "author_profile": "https://Stackoverflow.com/users/3058581", "pm_score": 1, "selected": false, "text": "var boo ='lala';\n\nfunction check(){\n if(this['foo']){\n console.log('foo is here');}\n else{\n console.log('have no foo');\n }\n\n if(this['boo']){\n console.log('boo is here');}\n else{\n console.log('have no boo');\n }\n}\n\ncheck();" }, { "answer_id": 68147770, "author": "Balaji", "author_id": 8389576, "author_profile": "https://Stackoverflow.com/users/8389576", "pm_score": 0, "selected": false, "text": "function isUndefined(variable,defaultvalue=''){\n\n if (variable == undefined ) return defaultvalue;\n \n return variable;\n\n}\n var obj={\nund:undefined,\nnotundefined:'hi i am not undefined'\n}\n\n\nfunction isUndefined(variable,defaultvalue=''){\n\n if (variable == undefined )\n { \n return defaultvalue;\n }\n return variable\n\n}\n\nconsole.log(isUndefined(obj.und,'i am print'))\nconsole.log(isUndefined(obj.notundefined,'i am print'))" }, { "answer_id": 69569312, "author": "Ali Yaghoubi", "author_id": 11662335, "author_profile": "https://Stackoverflow.com/users/11662335", "pm_score": 2, "selected": false, "text": "!! if (!(!!variable)) {\n // Code\n}\n if (!variable) {\n // Code\n}\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/27509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/797/" ]
27,532
<p>Given 2 rgb colors and a rectangular area, I'd like to generate a basic linear gradient between the colors. I've done a quick search and the only thing I've been able to find is <a href="http://jtauber.com/blog/2008/05/18/creating_gradients_programmatically_in_python/" rel="noreferrer">this blog entry</a>, but the example code seems to be missing, or at least it was as of this posting. Anything helps, algorithms, code examples, whatever. This will be written in Java, but the display layer is already taken care of, I just need to figure out how to figure out what to display.</p>
[ { "answer_id": 27536, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 6, "selected": true, "text": "R = firstCol.R * p + secondCol.R * (1 - p)\n GradientPaint" }, { "answer_id": 27553, "author": "David Crow", "author_id": 2783, "author_profile": "https://Stackoverflow.com/users/2783", "pm_score": 3, "selected": false, "text": "import java.awt.Color;\nimport java.awt.Graphics;\nimport java.awt.Graphics2D;\nimport java.awt.geom.Rectangle2D;\nimport javax.swing.JPanel;\n\npublic class LinearGradient extends JPanel {\n\n public void paint(Graphics g) {\n Graphics2D g2 = (Graphics2D) g;\n Color color1 = Color.RED;\n Color color2 = Color.BLUE;\n int steps = 30;\n int rectWidth = 10;\n int rectHeight = 10;\n\n for (int i = 0; i < steps; i++) {\n float ratio = (float) i / (float) steps;\n int red = (int) (color2.getRed() * ratio + color1.getRed() * (1 - ratio));\n int green = (int) (color2.getGreen() * ratio + color1.getGreen() * (1 - ratio));\n int blue = (int) (color2.getBlue() * ratio + color1.getBlue() * (1 - ratio));\n Color stepColor = new Color(red, green, blue);\n Rectangle2D rect2D = new Rectangle2D.Float(rectWidth * i, 0, rectWidth, rectHeight);\n g2.setPaint(stepColor);\n g2.fill(rect2D);\n }\n }\n}\n" }, { "answer_id": 27561, "author": "dbkk", "author_id": 838, "author_profile": "https://Stackoverflow.com/users/838", "pm_score": 4, "selected": false, "text": "void Paint(Graphics2D g, Regtangle r, Color c1, Color c2)\n{\n GradientPaint gp = new GradientPaint(0,0,c1,r.getWidth(),r.getHeight(),c2); \n g.setPaint(gp);\n g.fill(rect);\n}\n" }, { "answer_id": 47324548, "author": "Holger Brandl", "author_id": 590437, "author_profile": "https://Stackoverflow.com/users/590437", "pm_score": 2, "selected": false, "text": "fun gradientColor(x: Double, minX: Double, maxX: Double, \n from: Color = Color.RED, to: Color = Color.GREEN): Color {\n val range = maxX - minX\n val p = (x - minX) / range\n\n return Color(\n from.red * p + to.red * (1 - p),\n from.green * p + to.green * (1 - p),\n from.blue * p + to.blue * (1 - p),\n 1.0\n )\n}\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/27532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/85/" ]
27,559
<p>The ones that stick out and make life usefull.</p>
[ { "answer_id": 27563, "author": "chrissie1", "author_id": 2936, "author_profile": "https://Stackoverflow.com/users/2936", "pm_score": 1, "selected": false, "text": "\n Imports Nunit.FrameWork\n\n Namespace $NAMESPACE$\n ''' \n ''' A TestClass\n ''' \n ''' \n _\n Public Class $CLASSNAME$\n\n#Region \" Setup and TearDown \"\n ''' \n ''' Sets up the Tests\n ''' \n ''' \n _\n Public Sub Setup()\n\n End Sub\n\n ''' \n ''' Tears down the test. Is executed after the Test is Completed\n ''' \n ''' \n _\n Public Sub TearDown()\n\n End Sub \n#End Region \n\n#Region \" Tests \"\n ''' \n ''' A Test\n ''' \n ''' \n _\n Public Sub $Test_Name$()\n\n End Sub\n#End Region\n\n End Class\nEnd Namespace" }, { "answer_id": 9226526, "author": "Boris Callens", "author_id": 11333, "author_profile": "https://Stackoverflow.com/users/11333", "pm_score": 0, "selected": false, "text": "Imports Microsoft.VisualStudio.TestTools.UnitTesting\n\n<TestClass()> _\nPublic Class $ClassName$\n $END$\nEnd Class\n $Classname" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/27559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2936/" ]
27,562
<p>I am running oracle and have a query which pulls some results from the database. I would like to write the results as a text file. How would I go about doing this?</p> <p>My prefered way would be by using UTL_FILE. Would some one have an example of how to do this?</p>
[ { "answer_id": 39409, "author": "Andrew Wood", "author_id": 1095, "author_profile": "https://Stackoverflow.com/users/1095", "pm_score": 2, "selected": false, "text": "\n create directory logfile as 'd:\\logfile'; -- must have priv to do this\n\ndeclare\n vFile utl_file.file_type;\nbegin\n vFile := utl_file.fopen(logfile ,'syslog','w'); -- w is write. This returns file handle\n utl_file.put(vFile,'Start Logfile'); -- note use of file handle vFile\n utl_file.fclose(vFile); -- note use of file handle vFile\nend;\n\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/27562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
27,568
<p>I'd like to learn how to program in Assembler. I've done a bit of assembly before (during my A-Level Computing course) but that was very definitely a simplified 'pseudo-assembler'. I've borrowed my Dad's old Z80 Assembler reference manual, and that seems quite interesting so if possible I'd like to have a go with Z80 assembler.</p> <p>However, I don't have a Z80 processor to hand, and would like to do it on my PC (I have windows or linux so either is good). I've found various assemblers around on the internet, but I'm not particularly interested in assembling down to a hex file, I want to just be able to assemble it to something that some kind of simulator on the PC can run. Preferably this simulator would show me the contents of all the registers, memory locations etc, and let me step through instructions. I've found a few bits of software that suggest they might do this - but they either refuse to compile, or don't seem to work properly. Has anyone got any suggestions? If there are good simulator/IDE things available for another type of assembler then I could try that instead (assuming there is a good online reference manual available).</p>
[ { "answer_id": 27626, "author": "Nic Wise", "author_id": 2947, "author_profile": "https://Stackoverflow.com/users/2947", "pm_score": 2, "selected": false, "text": "<%@ page language=\"Asm80386\" %>\n<%\nStr: DB \"Testing...\", 0\n\n mov eax, -2\n cmp eax, 2\n jle Label1\n xor eax, eax\nLabel1:\n lea esi, Str\n push esi\n call \"Response.Write(string)\"\n pop esi\n%>\n<br>EAX: <%= eax %>\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/27568", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1912/" ]
27,570
<p>Is there a way to find the number of files of a specific type without having to loop through all results inn a Directory.GetFiles() or similar method? I am looking for something like this:</p> <pre><code>int ComponentCount = MagicFindFileCount(@"c:\windows\system32", "*.dll"); </code></pre> <p>I know that I can make a recursive function to call Directory.GetFiles , but it would be much cleaner if I could do this without all the iterating.</p> <p><strong>EDIT:</strong> If it is not possible to do this without recursing and iterating yourself, what would be the best way to do it?</p>
[ { "answer_id": 27584, "author": "Jon Limjap", "author_id": 372, "author_profile": "https://Stackoverflow.com/users/372", "pm_score": 6, "selected": true, "text": "string[] files = directory.GetFiles(@\"c:\\windows\\system32\", \"*.dll\", SearchOption.AllDirectories);\n\nreturn files.Length;\n return Directory.EnumerateFiles(@\"c:\\windows\\system32\", \"*.dll\", SearchOption.AllDirectories).Count();\n" }, { "answer_id": 27592, "author": "Huppie", "author_id": 1830, "author_profile": "https://Stackoverflow.com/users/1830", "pm_score": 1, "selected": false, "text": "private int MagicFindFileCount( string strDirectory, string strFilter ) {\n int nFiles = Directory.GetFiles( strDirectory, strFilter ).Length;\n\n foreach( String dir in Directory.GetDirectories( strDirectory ) ) {\n nFiles += GetNumberOfFiles(dir, strFilter);\n }\n\n return nFiles;\n }\n" }, { "answer_id": 5410210, "author": "Sauleil", "author_id": 331752, "author_profile": "https://Stackoverflow.com/users/331752", "pm_score": 3, "selected": false, "text": " public static int GetFileCount(string path, string searchPattern, SearchOption searchOption)\n {\n var fileCount = 0;\n var fileIter = Directory.EnumerateFiles(path, searchPattern, searchOption);\n foreach (var file in fileIter)\n fileCount++;\n return fileCount;\n }\n" }, { "answer_id": 7430990, "author": "Dean", "author_id": 257810, "author_profile": "https://Stackoverflow.com/users/257810", "pm_score": 3, "selected": false, "text": "var fileCount = (from file in Directory.EnumerateFiles(@\"H:\\iPod_Control\\Music\", \"*.mp3\", SearchOption.AllDirectories)\n select file).Count();\n" }, { "answer_id": 10193988, "author": "DraxReaper", "author_id": 1315396, "author_profile": "https://Stackoverflow.com/users/1315396", "pm_score": 1, "selected": false, "text": "public class DirectoryFileCounter\n{\n int mDirectoriesToRead = 0;\n\n // Pass this method the parent directory path\n public void ADirectoryPathWasSelected(string path)\n {\n // create a task to do this in the background for responsive ui\n // state is the path\n Task.Factory.StartNew((state) =>\n {\n try\n {\n // Get the first layer of sub directories\n this.AddCountFilesAndFolders(state.ToString())\n\n\n }\n catch // Add Handlers for exceptions\n {}\n }, path));\n }\n\n // This method is called recursively\n private void AddCountFilesAndFolders(string path)\n {\n try\n {\n // Only doing the top directory to prevent an exception from stopping the entire recursion\n var directories = Directory.EnumerateDirectories(path, \"*.*\", SearchOption.TopDirectoryOnly);\n\n // calling class is tracking the count of directories\n this.mDirectoriesToRead += directories.Count();\n\n // get the child directories\n // this uses an extension method to the IEnumerable<V> interface,\n // which will run a function on an object. In this case 'd' is the \n // collection of directories\n directories.ActionOnEnumerable(d => AddCountFilesAndFolders(d));\n }\n catch // Add Handlers for exceptions\n {\n }\n try\n {\n // count the files in the directory\n this.mFilesToRead += Directory.EnumerateFiles(path).Count();\n }\n catch// Add Handlers for exceptions\n { }\n }\n}\n// Extension class\npublic static class Extensions\n{ \n // this runs the supplied method on each object in the supplied enumerable\n public static void ActionOnEnumerable<V>(this IEnumerable<V> nodes,Action<V> doit)\n {\n\n foreach (var node in nodes)\n { \n doit(node);\n }\n }\n}\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/27570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2257/" ]
27,578
<p>In Java (or any other language with checked exceptions), when creating your own exception class, how do you decide whether it should be checked or unchecked?</p> <p>My instinct is to say that a checked exception would be called for in cases where the caller might be able to recover in some productive way, where as an unchecked exception would be more for unrecoverable cases, but I'd be interested in other's thoughts.</p>
[ { "answer_id": 73355, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 5, "selected": false, "text": "/**\n * Build a folder. <br />\n * Folder located under a Parent Folder (either RootFolder or an existing Folder)\n * @param aFolderName name of folder\n * @param aPVob project vob containing folder (MUST NOT BE NULL)\n * @param aParent parent folder containing folder \n * (MUST NOT BE NULL, MUST BE IN THE SAME PVOB than aPvob)\n * @param aComment comment for folder (MUST NOT BE NULL)\n * @return a new folder or an existing one\n * @throws CCException if any problems occurs during folder creation\n * @throws AssertionFailedException if aParent is not in the same PVob\n * @throws NullPointerException if aPVob or aParent or aComment is null\n */\nstatic public Folder makeOrGetFolder(final String aFoldername, final Folder aParent,\n final IPVob aPVob, final Comment aComment) throws CCException {\n Folder aFolderRes = null;\n if (aPVob.equals(aParent.getPVob() == false) { \n // UNCHECKED EXCEPTION because the caller failed to live up\n // to the documented entry criteria for this function\n Assert.isLegal(false, \"parent Folder must be in the same PVob than \" + aPVob); }\n\n final String ctcmd = \"mkfolder \" + aComment.getCommentOption() + \n \" -in \" + getPNameFromRepoObject(aParent) + \" \" + aPVob.getFullName(aFolderName);\n\n final Status st = getCleartool().executeCmd(ctcmd);\n\n if (st.status || StringUtils.strictContains(st.message,\"already exists.\")) {\n aFolderRes = Folder.getFolder(aFolderName, aPVob);\n }\n else {\n // CHECKED EXCEPTION because the callee failed to respect his contract\n throw new CCException.Error(\"Unable to make/get folder '\" + aFolderName + \"'\");\n }\n return aFolderRes;\n}\n" }, { "answer_id": 322889, "author": "OscarRyz", "author_id": 20654, "author_profile": "https://Stackoverflow.com/users/20654", "pm_score": 5, "selected": false, "text": "/**\n * @params operation - The operation to execute.\n * @throws IllegalArgumentException if the operation is \"exit\"\n */\n public final void execute( String operation ) {\n if( \"exit\".equals(operation)){\n throw new IllegalArgumentException(\"I told you not to...\");\n }\n this.operation = operation; \n ..... \n }\n private void secretCode(){\n // we perform the operation.\n // at this point the opreation was validated already.\n // so we don't worry that operation is \"exit\"\n ..... \n }\n IllegalArgumentException: I told you not to use \"exit\" \n at some.package.AClass.execute(Aclass.java:5)\n at otherPackage.Otherlass.delegateTheWork(OtherClass.java:4569)\n ar ......\n public static MyClass createInstane( Object data1, Object data2 /* etc */ ){ \n if( data1 == null ){ throw NullPointerException( \"data1 cannot be null\"); }\n\n }\n\n\n // the rest of the methods don't validate data1 anymore.\n public void method1(){ // don't worry, nothing is null \n ....\n }\n public void method2(){ // don't worry, nothing is null \n ....\n }\n public void method3(){ // don't worry, nothing is null \n ....\n }\n" }, { "answer_id": 19061110, "author": "Gili", "author_id": 14731, "author_profile": "https://Stackoverflow.com/users/14731", "pm_score": 9, "selected": true, "text": "SQLException IOException RepositoryException" }, { "answer_id": 23439719, "author": "user3598189", "author_id": 3598189, "author_profile": "https://Stackoverflow.com/users/3598189", "pm_score": 4, "selected": false, "text": "x.doSomething(); // the code throws a NullPointerException\n if (x==null)\n{\n //do something below to make sure when x.doSomething() is executed, it won’t throw a NullPointerException.\n x = new X();\n}\nx.doSomething();\n Socket s = new Socket(“google.com”, 80);\nInputStream in = s.getInputStream();\nOutputStream out = s.getOutputStream();\n" }, { "answer_id": 33167087, "author": "Jacky", "author_id": 1318528, "author_profile": "https://Stackoverflow.com/users/1318528", "pm_score": 1, "selected": false, "text": "String name = null;\n... // some logics\nSystem.out.print(name.length()); // name is still null here\n String name = ExternalService.getName(); // return null\nSystem.out.print(name.length()); // name is null here\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/27578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/797/" ]
27,581
<p>What issues / pitfalls must be considered when overriding <code>equals</code> and <code>hashCode</code>?</p>
[ { "answer_id": 27609, "author": "Antti Kissaniemi", "author_id": 2948, "author_profile": "https://Stackoverflow.com/users/2948", "pm_score": 12, "selected": true, "text": "equals() o.equals(null) hashCode() equals() a.equals(b) a.hashCode() b.hashCode() equals() hashCode() public class Person {\n private String name;\n private int age;\n // ...\n\n @Override\n public int hashCode() {\n return new HashCodeBuilder(17, 31). // two randomly chosen prime numbers\n // if deriving: appendSuper(super.hashCode()).\n append(name).\n append(age).\n toHashCode();\n }\n\n @Override\n public boolean equals(Object obj) {\n if (!(obj instanceof Person))\n return false;\n if (obj == this)\n return true;\n\n Person rhs = (Person) obj;\n return new EqualsBuilder().\n // if deriving: appendSuper(super.equals(obj)).\n append(name, rhs.name).\n append(age, rhs.age).\n isEquals();\n }\n}\n" }, { "answer_id": 32223, "author": "Ran Biron", "author_id": 931, "author_profile": "https://Stackoverflow.com/users/931", "pm_score": 6, "selected": false, "text": "obj.getClass() != getClass() equals() A.equals(B) == true B.equals(A) true equals() class A {\n int field1;\n\n A(int field1) {\n this.field1 = field1;\n }\n\n public boolean equals(Object other) {\n return (other != null && other instanceof A && ((A) other).field1 == field1);\n }\n }\n\n class B extends A {\n int field2;\n\n B(int field1, int field2) {\n super(field1);\n this.field2 = field2;\n }\n\n public boolean equals(Object other) {\n return (other != null && other instanceof B && ((B)other).field2 == field2 && super.equals(other));\n }\n } \n new A(1).equals(new A(1)) new B(1,1).equals(new B(1,1)) A a = new A(1);\nB b = new B(1,1);\na.equals(b) == true;\nb.equals(a) == false;\n super.equals(other) B A if (other instanceof B )\n return (other != null && ((B)other).field2 == field2 && super.equals(other)); \nif (other instanceof A) return super.equals(other); \n else return false;\n a.equals(b) == true;\nb.equals(a) == true;\n a B A super.equals()" }, { "answer_id": 33010, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 4, "selected": false, "text": "instanceof this.getClass().equals(that.getClass()) final java.util (obj instanceof Set) Comparable equals compareTo Comparable final class MyClass implements Comparable<MyClass>\n{\n\n …\n\n @Override\n public boolean equals(Object obj)\n {\n /* If compareTo and equals aren't final, we should check with getClass instead. */\n if (!(obj instanceof MyClass)) \n return false;\n return compareTo((MyClass) obj) == 0;\n }\n\n}\n" }, { "answer_id": 55736, "author": "Kevin Wong", "author_id": 4792, "author_profile": "https://Stackoverflow.com/users/4792", "pm_score": 6, "selected": false, "text": "class Point {\n private int x;\n private int y;\n protected boolean blindlyEquals(Object o) {\n if (!(o instanceof Point))\n return false;\n Point p = (Point)o;\n return (p.x == this.x && p.y == this.y);\n }\n public boolean equals(Object o) {\n return (this.blindlyEquals(o) && o.blindlyEquals(this));\n }\n}\n\nclass ColorPoint extends Point {\n private Color c;\n protected boolean blindlyEquals(Object o) {\n if (!(o instanceof ColorPoint))\n return false;\n ColorPoint cp = (ColorPoint)o;\n return (super.blindlyEquals(cp) && \n cp.color == this.color);\n }\n}\n" }, { "answer_id": 256447, "author": "Johannes Brodwall", "author_id": 27658, "author_profile": "https://Stackoverflow.com/users/27658", "pm_score": 8, "selected": false, "text": "this.getClass() == o.getClass() false Person saved = new Person(\"John Doe\");\nLong key = dao.save(saved);\ndao.flush();\nPerson retrieved = dao.retrieve(key);\nsaved.getClass().equals(retrieved.getClass()); // Will return false if Person is loaded lazy\n o instanceof Person person.name null person person.getName() hashCode() equals() hashCode() equals() id hashCode() equals() if (this.getId() == null) {\n return this == other;\n}\nelse {\n return this.getId().equals(other.getId());\n}\n getId() hashCode() hashCode HashSet Person getName() hashCode getId() getName() equals() hashCode() equals() hashCode() equals()" }, { "answer_id": 14827378, "author": "Eugene", "author_id": 1059372, "author_profile": "https://Stackoverflow.com/users/1059372", "pm_score": 5, "selected": false, "text": " //Sample taken from a current working project of mine just to illustrate the idea\n\n @Override\n public int hashCode(){\n return Objects.hashCode(this.getDate(), this.datePattern);\n }\n\n @Override\n public boolean equals(Object obj){\n if ( ! obj instanceof DateAndPattern ) {\n return false;\n }\n return Objects.equal(((DateAndPattern)obj).getDate(), this.getDate())\n && Objects.equal(((DateAndPattern)obj).getDate(), this.getDatePattern());\n }\n" }, { "answer_id": 15599729, "author": "Khaled.K", "author_id": 2128327, "author_profile": "https://Stackoverflow.com/users/2128327", "pm_score": 3, "selected": false, "text": "a.getClass().equals(b.getClass()) && a.equals(b) a.hashCode() == b.hashCode()" }, { "answer_id": 19563996, "author": "rohan kamat", "author_id": 2335562, "author_profile": "https://Stackoverflow.com/users/2335562", "pm_score": 4, "selected": false, "text": "public class Tiger {\n private String color;\n private String stripePattern;\n private int height;\n\n @Override\n public boolean equals(Object object) {\n boolean result = false;\n if (object == null || object.getClass() != getClass()) {\n result = false;\n } else {\n Tiger tiger = (Tiger) object;\n if (this.color == tiger.getColor()\n && this.stripePattern == tiger.getStripePattern()) {\n result = true;\n }\n }\n return result;\n }\n\n // just omitted null checks\n @Override\n public int hashCode() {\n int hash = 3;\n hash = 7 * hash + this.color.hashCode();\n hash = 7 * hash + this.stripePattern.hashCode();\n return hash;\n }\n\n public static void main(String args[]) {\n Tiger bengalTiger1 = new Tiger(\"Yellow\", \"Dense\", 3);\n Tiger bengalTiger2 = new Tiger(\"Yellow\", \"Dense\", 2);\n Tiger siberianTiger = new Tiger(\"White\", \"Sparse\", 4);\n System.out.println(\"bengalTiger1 and bengalTiger2: \"\n + bengalTiger1.equals(bengalTiger2));\n System.out.println(\"bengalTiger1 and siberianTiger: \"\n + bengalTiger1.equals(siberianTiger));\n\n System.out.println(\"bengalTiger1 hashCode: \" + bengalTiger1.hashCode());\n System.out.println(\"bengalTiger2 hashCode: \" + bengalTiger2.hashCode());\n System.out.println(\"siberianTiger hashCode: \"\n + siberianTiger.hashCode());\n }\n\n public String getColor() {\n return color;\n }\n\n public String getStripePattern() {\n return stripePattern;\n }\n\n public Tiger(String color, String stripePattern, int height) {\n this.color = color;\n this.stripePattern = stripePattern;\n this.height = height;\n\n }\n}\n bengalTiger1 and bengalTiger2: true \nbengalTiger1 and siberianTiger: false \nbengalTiger1 hashCode: 1398212510 \nbengalTiger2 hashCode: 1398212510 \nsiberianTiger hashCode: –1227465966\n" }, { "answer_id": 20697433, "author": "Luna Kong", "author_id": 2038772, "author_profile": "https://Stackoverflow.com/users/2038772", "pm_score": 5, "selected": false, "text": "public boolean equals(Object obj)\npublic int hashCode()\n public class Test\n{\n private int num;\n private String data;\n public boolean equals(Object obj)\n {\n if(this == obj)\n return true;\n if((obj == null) || (obj.getClass() != this.getClass()))\n return false;\n // object must be Test at this point\n Test test = (Test)obj;\n return num == test.num &&\n (data == test.data || (data != null && data.equals(test.data)));\n }\n\n public int hashCode()\n {\n int hash = 7;\n hash = 31 * hash + num;\n hash = 31 * hash + (null == data ? 0 : data.hashCode());\n return hash;\n }\n\n // other methods\n}\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/27581", "https://Stackoverflow.com", "https://Stackoverflow.com/users/797/" ]
27,598
<p>I've deployed some Managed Beans on WebSphere 6.1 and I've managed to invoke them through a standalone client, but when I try to use the application "jconsole" distributed with the standard JDK can can't make it works.</p> <p>Has anyone achieved to connect the jconsole with WAS 6.1?</p> <p>IBM WebSphere 6.1 it's supossed to support JSR 160 JavaTM Management Extensions (JMX) Remote API. Furthermore, it uses the MX4J implementation (<a href="http://mx4j.sourceforge.net" rel="nofollow noreferrer">http://mx4j.sourceforge.net</a>). But I can't make it works with neither "jconsole" nor "MC4J".</p> <p>I have the Classpath and the JAVA_HOME correctly setted, so the issue it's not there.</p>
[ { "answer_id": 922409, "author": "Flueras Bogdan", "author_id": 83843, "author_profile": "https://Stackoverflow.com/users/83843", "pm_score": 1, "selected": false, "text": " 1) Change the config.xml and start the server. \n 2) start the jconsole with : jconsole -J-Djavax.net.ssl.keyStore=%GERONIMO_HOME%\\var\\security\\keystores\\geronimo-default -J-Djavax.net.ssl.keyStorePassword=secret -J-Djavax.net.ssl.trustStore=%GERONIMO_HOME%\\var\\security\\keystores\\geronimo-default -J-Djavax.net.ssl.trustStorePassword=secret -J-Djava.class.path=%JAVA_HOME%\\lib\\jconsole.jar;%JAVA_HOME%\\lib\\tools.jar;%GERONIMO_HOME%\\repository\\org\\apache\\geronimo\\framework\\geronimo-kernel\\2.1.4\\geronimo-kernel-2.1.4.jar\n 3) in the jconsole interface->advanced, input:\n JMX URL: service:jmx:rmi:///jndi/rmi://localhost:1099/JMXSecureConnector\n user name: system\n password: manager\n\n 4) click the connect button.\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/27598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2937/" ]
27,599
<p>(<strong>Updated a little</strong>)</p> <p>I'm not very experienced with internationalization using PHP, it must be said, and a deal of searching didn't really provide the answers I was looking for.</p> <p>I'm in need of working out a reliable way to convert only 'relevant' text to Unicode to send in an SMS message, using PHP (just temporarily, whilst service is rewritten using C#) - obviously, messages sent at the moment are sent as plain text.</p> <p>I could conceivably convert everything to the Unicode charset (as opposed to using the standard GSM charset), but that would mean that <em>all</em> messages would be limited to 70 characters (instead of 160).</p> <p>So, I guess my real question is: <em>what is the most reliable way to detect the requirement for a message to be Unicode-encoded, so I only have to do it when it's</em> <strong><em>absolutely necessary</em></strong> <em>(e.g. for non-Latin-language characters)?</em></p> <h2>Added Info:</h2> <p>Okay, so I've spent the morning working on this, and I'm still no further on than when I started (certainly due to my complete lack of competency when it comes to charset conversion). So here's the revised scenario:</p> <p>I have text SMS messages coming from an external source, this external source provides the responses to me in plain text + Unicode slash-escaped characters. E.g. the 'displayed' text:</p> <blockquote> <p>Let's test öäü éàè אין תמיכה בעברית</p> </blockquote> <p>Returns:</p> <blockquote> <p>Let's test \u00f6\u00e4\u00fc \u00e9\u00e0\u00e8 \u05d0\u05d9\u05df \u05ea\u05de\u05d9\u05db\u05d4 \u05d1\u05e2\u05d1\u05e8\u05d9\u05ea</p> </blockquote> <p>Now, I can send on to my SMS provider in plaintext, GSM 03.38 or Unicode. Obviously, sending the above as plaintext results in a lot of missing characters (they're replaced by spaces by my provider) - I need to adopt relating to what content there is. What I want to <em>do</em> with this is the following:</p> <ol> <li><p>If all text is within the <a href="http://www.dreamfabric.com/sms/default_alphabet.html" rel="nofollow noreferrer">GSM 03.38 codepage</a>, send it as-is. (All but the Hebrew characters above fit into this category, but need to be converted.)</p></li> <li><p>Otherwise, convert it to Unicode, and send it over multiple messages (as the Unicode limit is 70 chars not 160 for an SMS).</p></li> </ol> <p>As I said above, I'm stumped on doing this in PHP (C# wasn't much of an issue due to some simple conversion functions built-in), but it's quite probable I'm just missing the obvious, here. I couldn't find any pre-made conversion classes for 7-bit encoding in PHP, either - and my attempts to convert the string myself and send it on seemed futile.</p> <p><strong>Any help would be greatly appreciated.</strong></p>
[ { "answer_id": 27603, "author": "Ross", "author_id": 2025, "author_profile": "https://Stackoverflow.com/users/2025", "pm_score": 0, "selected": false, "text": "mb_convert_encoding mb_detect_encoding" }, { "answer_id": 27623, "author": "Magnus Westin", "author_id": 2957, "author_profile": "https://Stackoverflow.com/users/2957", "pm_score": 2, "selected": false, "text": "#define UCS2_TO_GSM_LOOKUP_TABLE_SIZE 0x100\n#define NON_GSM 0x80 \n#define UCS2_GCL_RANGE 24\n#define UCS2_GREEK_CAPITAL_LETTER_ALPHA 0x0391\n#define EXTEND 0x001B\n// note that the ` character is mapped to ' so that all characters that can be typed on\n// a standard north american keyboard can be converted to the GSM default character set\nstatic unsigned char Ucs2ToGsm[UCS2_TO_GSM_LOOKUP_TABLE_SIZE] =\n{ /*+0x0 +0x1 +0x2 +0x3 +0x4 +0x5 +0x6 +0x7*/\n/*0x00*/ NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM,\n/*0x08*/ NON_GSM, NON_GSM, 0x0a, NON_GSM, NON_GSM, 0x0d, NON_GSM, NON_GSM,\n/*0x10*/ NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM,\n/*0x18*/ NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM,\n/*0x20*/ 0x20, 0x21, 0x22, 0x23, 0x02, 0x25, 0x26, 0x27,\n/*0x28*/ 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,\n/*0x30*/ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,\n/*0x38*/ 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,\n/*0x40*/ 0x00, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47,\n/*0x48*/ 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f,\n/*0x50*/ 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57,\n/*0x58*/ 0x58, 0x59, 0x5a, EXTEND, EXTEND, EXTEND, EXTEND, 0x11,\n/*0x60*/ 0x27, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67,\n/*0x68*/ 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f,\n/*0x70*/ 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77,\n/*0x78*/ 0x78, 0x79, 0x7a, EXTEND, EXTEND, EXTEND, EXTEND, NON_GSM,\n/*0x80*/ NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM,\n/*0x88*/ NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM,\n/*0x90*/ NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM,\n/*0x98*/ NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM,\n/*0xa0*/ NON_GSM, 0x40, NON_GSM, 0x01, 0x24, 0x03, NON_GSM, 0x5f,\n/*0xa8*/ NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM,\n/*0xb0*/ NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM,\n/*0xb8*/ NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM, 0x60,\n/*0xc0*/ NON_GSM, NON_GSM, NON_GSM, NON_GSM, 0x5b, 0x0e, 0x1c, 0x09,\n/*0xc8*/ NON_GSM, 0x1f, NON_GSM, NON_GSM, NON_GSM, NON_GSM, NON_GSM, 0x60,\n/*0xd0*/ NON_GSM, 0x5d, NON_GSM, NON_GSM, NON_GSM, NON_GSM, 0x5c, NON_GSM,\n/*0xd8*/ 0x0b, NON_GSM, NON_GSM, NON_GSM, 0x5e, NON_GSM, NON_GSM, 0x1e,\n/*0xe0*/ 0x7f, NON_GSM, NON_GSM, NON_GSM, 0x7b, 0x0f, 0x1d, NON_GSM,\n/*0xe8*/ 0x04, 0x05, NON_GSM, NON_GSM, 0x07, NON_GSM, NON_GSM, NON_GSM,\n/*0xf0*/ NON_GSM, 0x7d, 0x08, NON_GSM, NON_GSM, NON_GSM, 0x7c, NON_GSM,\n/*0xf8*/ 0x0c, 0x06, NON_GSM, NON_GSM, 0x7e, NON_GSM, NON_GSM, NON_GSM\n};\n\nstatic unsigned char Ucs2GclToGsm[UCS2_GCL_RANGE + 1] =\n{\n/*0x0391*/ 0x41, // Alpha A\n/*0x0392*/ 0x42, // Beta B\n/*0x0393*/ 0x13, // Gamma\n/*0x0394*/ 0x10, // Delta\n/*0x0395*/ 0x45, // Epsilon E\n/*0x0396*/ 0x5A, // Zeta Z\n/*0x0397*/ 0x48, // Eta H\n/*0x0398*/ 0x19, // Theta\n/*0x0399*/ 0x49, // Iota I\n/*0x039a*/ 0x4B, // Kappa K\n/*0x039b*/ 0x14, // Lambda\n/*0x039c*/ 0x4D, // Mu M\n/*0x039d*/ 0x4E, // Nu N\n/*0x039e*/ 0x1A, // Xi\n/*0x039f*/ 0x4F, // Omicron O\n/*0x03a0*/ 0X16, // Pi\n/*0x03a1*/ 0x50, // Rho P\n/*0x03a2*/ NON_GSM,\n/*0x03a3*/ 0x18, // Sigma\n/*0x03a4*/ 0x54, // Tau T\n/*0x03a5*/ 0x59, // Upsilon Y\n/*0x03a6*/ 0x12, // Phi \n/*0x03a7*/ 0x58, // Chi X\n/*0x03a8*/ 0x17, // Psi\n/*0x03a9*/ 0x15 // Omega\n};\n\nbool Gsm0338Encoding::IsNotGSM( wchar_t szUnicodeChar )\n{\n bool result = true;\n if( szUnicodeChar < UCS2_TO_GSM_LOOKUP_TABLE_SIZE )\n {\n result = ( Ucs2ToGsm[szUnicodeChar] == NON_GSM );\n }\n else if( (szUnicodeChar >= UCS2_GREEK_CAPITAL_LETTER_ALPHA) &&\n (szUnicodeChar <= (UCS2_GREEK_CAPITAL_LETTER_ALPHA + UCS2_GCL_RANGE)) )\n {\n result = ( Ucs2GclToGsm[szUnicodeChar - UCS2_GREEK_CAPITAL_LETTER_ALPHA] == NON_GSM );\n }\n else if( szUnicodeChar == 0x20AC ) // €\n {\n result = false;\n }\n return result;\n}\n\nbool Gsm0338Encoding::IsGSM( const std::wstring& str )\n{\n bool result = true;\n if( std::find_if( str.begin(), str.end(), IsNotGSM ) != str.end() )\n {\n result = false;\n }\n return result;\n}\n" }, { "answer_id": 68096, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": true, "text": "// second column of http://unicode.org/Public/MAPPINGS/ETSI/GSM0338.TXT\n$gsm338_codepoints = array(0x0040, 0x0000, ..., 0x00fc, 0x00e0)\n$can_use_gsm338 = true;\nforeach(codepoints($mystring) as $codepoint){\n if(!in_array($codepoint, $gsm338_codepoints)){\n $can_use_gsm338 = false;\n break;\n }\n}\n" }, { "answer_id": 1441442, "author": "jW.", "author_id": 8880, "author_profile": "https://Stackoverflow.com/users/8880", "pm_score": 3, "selected": false, "text": " $valid_gsm_keycodes = Array( \n 0x0040, 0x0394, 0x0020, 0x0030, 0x00a1, 0x0050, 0x00bf, 0x0070,\n 0x00a3, 0x005f, 0x0021, 0x0031, 0x0041, 0x0051, 0x0061, 0x0071,\n 0x0024, 0x03a6, 0x0022, 0x0032, 0x0042, 0x0052, 0x0062, 0x0072,\n 0x00a5, 0x0393, 0x0023, 0x0033, 0x0043, 0x0053, 0x0063, 0x0073,\n 0x00e8, 0x039b, 0x00a4, 0x0034, 0x0035, 0x0044, 0x0054, 0x0064, 0x0074,\n 0x00e9, 0x03a9, 0x0025, 0x0045, 0x0045, 0x0055, 0x0065, 0x0075,\n 0x00f9, 0x03a0, 0x0026, 0x0036, 0x0046, 0x0056, 0x0066, 0x0076,\n 0x00ec, 0x03a8, 0x0027, 0x0037, 0x0047, 0x0057, 0x0067, 0x0077, \n 0x00f2, 0x03a3, 0x0028, 0x0038, 0x0048, 0x0058, 0x0068, 0x0078,\n 0x00c7, 0x0398, 0x0029, 0x0039, 0x0049, 0x0059, 0x0069, 0x0079,\n 0x000a, 0x039e, 0x002a, 0x003a, 0x004a, 0x005a, 0x006a, 0x007a,\n 0x00d8, 0x001b, 0x002b, 0x003b, 0x004b, 0x00c4, 0x006b, 0x00e4,\n 0x00f8, 0x00c6, 0x002c, 0x003c, 0x004c, 0x00d6, 0x006c, 0x00f6,\n 0x000d, 0x00e6, 0x002d, 0x003d, 0x004d, 0x00d1, 0x006d, 0x00f1,\n 0x00c5, 0x00df, 0x002e, 0x003e, 0x004e, 0x00dc, 0x006e, 0x00fc,\n 0x00e5, 0x00c9, 0x002f, 0x003f, 0x004f, 0x00a7, 0x006f, 0x00e0 );\n\n\n for($i = 0; $i < strlen($string); $i++) {\n if(!in_array($string[$i], $valid_gsm_keycodes)) return false;\n }\n\n return true;\n" }, { "answer_id": 12196609, "author": "Sergey Shuchkin", "author_id": 594867, "author_profile": "https://Stackoverflow.com/users/594867", "pm_score": 3, "selected": false, "text": "function is_gsm0338( $utf8_string ) {\n $gsm0338 = array(\n '@','Δ',' ','0','¡','P','¿','p',\n '£','_','!','1','A','Q','a','q',\n '$','Φ','\"','2','B','R','b','r',\n '¥','Γ','#','3','C','S','c','s',\n 'è','Λ','¤','4','D','T','d','t',\n 'é','Ω','%','5','E','U','e','u',\n 'ù','Π','&','6','F','V','f','v',\n 'ì','Ψ','\\'','7','G','W','g','w',\n 'ò','Σ','(','8','H','X','h','x',\n 'Ç','Θ',')','9','I','Y','i','y',\n \"\\n\",'Ξ','*',':','J','Z','j','z',\n 'Ø',\"\\x1B\",'+',';','K','Ä','k','ä',\n 'ø','Æ',',','<','L','Ö','l','ö',\n \"\\r\",'æ','-','=','M','Ñ','m','ñ',\n 'Å','ß','.','>','N','Ü','n','ü',\n 'å','É','/','?','O','§','o','à'\n );\n $len = mb_strlen( $utf8_string, 'UTF-8');\n\n for( $i=0; $i < $len; $i++)\n if (!in_array(mb_substr($utf8_string,$i,1,'UTF-8'), $gsm0338))\n return false;\n\n return true;\n}\n" }, { "answer_id": 13469742, "author": "Enyby", "author_id": 1504248, "author_profile": "https://Stackoverflow.com/users/1504248", "pm_score": 0, "selected": false, "text": "preg_match('/^[\\x0A\\x0C\\x0D\\x20-\\x5F\\x61-\\x7E\\xA0\\xA1\\xA3-\\xA5\\xA7'.\n '\\xBF\\xC4-\\xC6\\xC9\\xD1\\xD6\\xD8\\xDC\\xDF\\xE0\\xE4-\\xE9\\xEC\\xF1'.\n '\\xF2\\xF6\\xF8\\xF9\\xFC'.\n json_decode('\"\\u0393\\u0394\\u0398\\u039B\\u039E\\u03A0\\u03A3\\u03A6\\u03A8\\u03A9\\u20AC\"').\n ']*$/u', $text)\n preg_match('/^[\\x0A\\x0C\\x0D\\x20-\\x5F\\x61-\\x7E\\xA0\\xA1\\xA3-\\xA5\\xA7\\xBF\\xC4-\\xC6\\xC9\\xD1\\xD6\\xD8\\xDC\\xDF\\xE0\\xE4-\\xE9\\xEC\\xF1\\xF2\\xF6\\xF8\\xF9\\xFCΓΔΘΛΞΠΣΦΨΩ€]*$/u', $text)\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/27599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2951/" ]
27,607
<p>Let's say I have a list of server names stored in a vector, and I would like to contact them one at a time until one has successfully responded. I was thinking about using STL's find_if algorithm in the following way:</p> <pre><code>find_if(serverNames.begin(), serverNames.end(), ContactServer()); </code></pre> <p>Where ContactServer is a predicate function object.<br> On one hand, there's a problem since the predicate will not always return the same result for the same server name (because of server downtime, network problems, etc...). However, the same result will be returned regardless of which copy of the predicate is used (<em>i.e.</em> the predicate has no real state), so the original problem with state-keeping predicates is not relevant in this case.</p> <p>What do you say?</p>
[ { "answer_id": 27614, "author": "Magnus Hoff", "author_id": 2971, "author_profile": "https://Stackoverflow.com/users/2971", "pm_score": 2, "selected": false, "text": "ContactServer CanContactServer" }, { "answer_id": 27619, "author": "Daren Thomas", "author_id": 2260, "author_profile": "https://Stackoverflow.com/users/2260", "pm_score": 0, "selected": false, "text": "find_if" }, { "answer_id": 27620, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 0, "selected": false, "text": "find_if" }, { "answer_id": 103138, "author": "Timmie Smith", "author_id": 8405, "author_profile": "https://Stackoverflow.com/users/8405", "pm_score": 0, "selected": false, "text": "\nstruct AttemptServerContact {\n bool server_contacted;\n std::string active_server; // name of server contacted\n\n AttemptServerContact() : server_contacted(false) {}\n\n void operator()(Server& s) {\n if (!server_contacted) {\n //attempt to contact s\n //if successful, set server_contacted and active_server\n }\n }\n};\n\nAttemptServerContact func;\nfunc = std::for_each(serverNames.begin(), serverNames.end(), func);\n//func.server_contacted and func.active_server contain server information.\n" }, { "answer_id": 10757848, "author": "Luc Touraille", "author_id": 20984, "author_profile": "https://Stackoverflow.com/users/20984", "pm_score": 2, "selected": false, "text": "std::find_if find_if find_if for (std::string const & name : serverNames)\n{\n if (ContactServer(name)) break;\n}\n apply_until template <typename InputIterator, typename Function>\nvoid apply_until(InputIterator first, InputIterator last, Function f)\n{\n std::find_if(first, last, f);\n // or\n // while (first != last)\n // {\n // if (f(*first)) break;\n //\n // ++first;\n // }\n}\n}\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/27607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2150/" ]
27,610
<p>I want to introduce some tracing to a C# application I am writing. Sadly, I can never really remember how it works and would like a tutorial with reference qualities to check up on every now and then. It should include:</p> <ul> <li>App.config / Web.config stuff to add for registering TraceListeners</li> <li>how to set it up in the calling application</li> </ul> <p>Do you know the über tutorial that we should link to?</p> <hr/> <p>Glenn Slaven pointed me in the right direction. Add this to your App.config/Web.config inside <code>&lt;configuration/&gt;</code>:</p> <pre><code>&lt;system.diagnostics&gt; &lt;trace autoflush=&quot;true&quot;&gt; &lt;listeners&gt; &lt;add type=&quot;System.Diagnostics.TextWriterTraceListener&quot; name=&quot;TextWriter&quot; initializeData=&quot;trace.log&quot; /&gt; &lt;/listeners&gt; &lt;/trace&gt; &lt;/system.diagnostics&gt; </code></pre> <p>This will add a <code>TextWriterTraceListener</code> that will catch everything you send to with <code>Trace.WriteLine</code>, etc.</p> <p>@DanEsparza pointed out that you should use <code>Trace.TraceInformation</code>, <code>Trace.TraceWarning</code> and <code>Trace.TraceError</code> instead of <code>Trace.WriteLine</code>, as they allow you to format messages the same way as <code>string.Format</code>.</p> <p><strong>Tip:</strong> If you don't add any listeners, then you can still see the trace output with the Sysinternals program <a href="https://learn.microsoft.com/en-us/sysinternals/downloads/debugview" rel="nofollow noreferrer">DebugView</a> (<code>Dbgview.exe</code>):</p>
[ { "answer_id": 35034967, "author": "Shaun", "author_id": 276874, "author_profile": "https://Stackoverflow.com/users/276874", "pm_score": 3, "selected": false, "text": "TraceSource.TraceEvent(TraceEventType, Int32, String) TraceSource tracelog.txt TraceSource source = new TraceSource(\"sourceName\");\nsource.TraceEvent(TraceEventType.Verbose, 1, \"Trace message\");\n <system.diagnostics>\n <sources>\n <source name=\"sourceName\" switchName=\"switchName\">\n <listeners>\n <add\n name=\"textWriterTraceListener\"\n type=\"System.Diagnostics.TextWriterTraceListener\"\n initializeData=\"tracelog.txt\" />\n </listeners>\n </source>\n </sources>\n\n <switches>\n <add name=\"switchName\" value=\"Verbose\" />\n </switches>\n</system.diagnostics>\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/27610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2260/" ]
27,621
<p>On the UNIX bash shell (specifically Mac OS X Leopard) what would be the simplest way to copy every file having a specific extension from a folder hierarchy (including subdirectories) to the same destination folder (without subfolders)?</p> <p>Obviously there is the problem of having duplicates in the source hierarchy. I wouldn't mind if they are overwritten.</p> <p>Example: I need to copy every .txt file in the following hierarchy</p> <pre><code>/foo/a.txt /foo/x.jpg /foo/bar/a.txt /foo/bar/c.jpg /foo/bar/b.txt </code></pre> <p>To a folder named 'dest' and get:</p> <pre><code>/dest/a.txt /dest/b.txt </code></pre>
[ { "answer_id": 27625, "author": "Magnus Hoff", "author_id": 2971, "author_profile": "https://Stackoverflow.com/users/2971", "pm_score": 7, "selected": true, "text": "find /foo -iname '*.txt' -exec cp \\{\\} /dest/ \\;\n find /foo *.txt -iname find cp {} /dest/ {}" }, { "answer_id": 27747, "author": "Stephen Darlington", "author_id": 2998, "author_profile": "https://Stackoverflow.com/users/2998", "pm_score": 4, "selected": false, "text": "find . -name \"*.xml\" -print0 | xargs -0 echo cp -t a\n" }, { "answer_id": 58536, "author": "Jon Ericson", "author_id": 1438, "author_profile": "https://Stackoverflow.com/users/1438", "pm_score": 2, "selected": false, "text": "$ find /foo -name '*.txt' | xargs echo | sed -e 's/^/cp /' -e 's|$| /dest|' | bash -sx\n cp: will not overwrite just-created `/dest/tubguide.tex' with `./texmf/tex/plain/tugboat/tubguide.tex'\n $ find /foo -name '*.txt' | xargs -i cp {} /dest\n" }, { "answer_id": 3228414, "author": "Rob Styles", "author_id": 389473, "author_profile": "https://Stackoverflow.com/users/389473", "pm_score": 4, "selected": false, "text": "find ./from -type f | awk '{ str=$0; sub(/\\.\\//, \"\", str); gsub(/\\//, \"-\", str); print \"mv \" $0 \" ./to/\" str }' | bash\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/27621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2954/" ]
27,622
<p>The <strong><a href="http://msdn.microsoft.com/en-us/library/4wyz8787(VS.80).aspx" rel="noreferrer">TRACE macro</a></strong> can be used to output diagnostic messages to the debugger when the code is compiled in <strong>Debug</strong> mode. I need the same messages while in <strong>Release</strong> mode. Is there a way to achieve this?</p> <p>(Please do <strong>not</strong> waste your time discussing why I should not be using TRACE in Release mode :-)</p>
[ { "answer_id": 27628, "author": "Mark Ingram", "author_id": 986, "author_profile": "https://Stackoverflow.com/users/986", "pm_score": 1, "selected": false, "text": "#define ATLTRACE __noop\n void MyTrace(const CString& text)\n{\n ::OutputDebugString(text); // Outputs to console, same as regular TRACE\n // TODO: Do whatever output you need here. Write to event log / write to text file / write to pipe etc.\n}\n" }, { "answer_id": 41046, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 4, "selected": true, "text": "void trace(const char* format, ...)\n{\n char buffer[1000];\n\n va_list argptr;\n va_start(argptr, format);\n wvsprintf(buffer, format, argptr);\n va_end(argptr);\n\n OutputDebugString(buffer);\n}\n" }, { "answer_id": 25657721, "author": "deniro.wang", "author_id": 2261302, "author_profile": "https://Stackoverflow.com/users/2261302", "pm_score": 2, "selected": false, "text": "#undef ATLTRACE\n#undef ATLTRACE2\n\n#define ATLTRACE2 CAtlTrace(__FILE__, __LINE__, __FUNCTION__)\n#define ATLTRACE ATLTRACE2\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/27622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1630/" ]
27,643
<p>On a web page I want to dynamically render very basic flow diagrams, i.e. a few boxes joined by lines. Ideally the user could then click on one of these boxes (<code>DIVs</code>?) and be taken to a different page. Resorting to Flash seems like an overkill. Is anyone aware of any client-side (i.e. <code>server agnostic</code>) Javascript or <code>CSS library/technique</code> that may help achieve this?</p>
[ { "answer_id": 16935309, "author": "bluish", "author_id": 505893, "author_profile": "https://Stackoverflow.com/users/505893", "pm_score": 2, "selected": false, "text": "/**Draw an arrow made of 3 lines. \n * Requires wz_jsGraphics (http://www.walterzorn.de/en/jsgraphics/jsgraphics_e.htm).\n * @canvas a jsGraphics object used as canvas\n * @blockFrom id of the object from which the arrow starts\n * @blockTo id of the object where the arrow ends with a arrowhead \n */\nfunction drawArrow(canvas, blockFrom, blockTo){\n\n //blocks\n var f = $(\"#\" + blockFrom);\n var t = $(\"#\" + blockTo);\n\n //lines positions and measures\n var p1 = { left: f.position().left + f.outerWidth(), top: f.position().top + f.outerHeight()/2 };\n var p4 = { left: t.position().left, top: t.position().top + t.outerHeight()/2 };\n var mediumX = Math.abs(p4.left - p1.left)/2;\n var p2 = { left: p1.left + mediumX, top: p1.top };\n var p3 = { left: p1.left + mediumX, top: p4.top };\n\n //line A\n canvas.drawLine(p1.left, p1.top, p2.left, p2.top);\n //line B\n canvas.drawLine(p2.left, p2.top, p3.left, p3.top);\n //line C\n canvas.drawLine(p3.left, p3.top, p4.left, p4.top);\n //arrowhead\n canvas.drawLine(p4.left - 7, p4.top - 4, p4.left, p4.top);\n canvas.drawLine(p4.left - 7, p4.top + 4, p4.left, p4.top);\n}\n\nvar jg = new jsGraphics('myCanvasDiv');\ndrawArrow(jg, 'myFirstBlock', 'mySecondBlock');\njg.paint(); \n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/27643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2966/" ]
27,674
<p>In our project, <a href="http://sharpwired.sourceforge.net/" rel="nofollow noreferrer">SharpWired</a>, we're trying to create a download component similar to the download windows in Firefox or Safari. That is, one single top down list of downloads which are custom controls containing progress bars, buttons and what not.</p> <p>The requirements are that there should be one single list, with one element on each row. Each element must be a custom control. The whole list should be dynamically re-sizable, so that when you make it longer / shorter the list adds a scroll bar when needed and when you make it thinner / wider the custom controls should resize to the width of the list.</p> <p>We've tried using a <code>FlowLayoutPanel</code> but haven't gotten resizing to work the way we want to. Preferably we should only have to set anchoring of the custom controls to Left &amp; Right. We've also thought about using a <code>TableLayoutPanel</code> but found adding rows dynamically to be a too big overhead so far.</p> <p>This must be quite a common use case, and it seems a bit weird to me that the <code>FlowLayoutPanel</code> has no intuitive way of doing this. <em>Has anyone done something similar or have tips or tricks to get us under way?</em></p> <p>Cheers!<br> /Adam</p>
[ { "answer_id": 619685, "author": "SLaks", "author_id": 34397, "author_profile": "https://Stackoverflow.com/users/34397", "pm_score": 3, "selected": true, "text": "DataRepeater Panel AutoScroll Dock Top" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/27674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2457/" ]
27,695
<p>It happens to me all the time. I accidentally version a file, I do not want to be versioned (i.e. developer/machine specific config-files).</p> <p>If I commit this file, I will mess up the paths on all the other developer machines - they will be unhappy.</p> <p>If I do delete the file from versioning, it will be deleted from the other developers machines - they will be unhappy.</p> <p>If I choose to never commit the file, I always have a "dirty" checkout - I am unhappy.</p> <p>Is a clean way to "unversion" a file from revision-control, that will result in no-one being unhappy?</p> <p>edit: trying to clarify a bit: I have already commited the file to the repository and I want to only remove it from versioning - I specifically do not want it to be physically deleted from everyone doing a checkout. I initially wanted it to be ignored.</p> <p>Answer: If I could accept a second answer, it would be <a href="https://stackoverflow.com/questions/27695/how-to-unversion-a-file-in-either-svn-andor-git#27727">this</a>. It answers my question with respect to git - the accepted answer is about svn.</p>
[ { "answer_id": 27701, "author": "Sergio Acosta", "author_id": 2954, "author_profile": "https://Stackoverflow.com/users/2954", "pm_score": 2, "selected": false, "text": "git rm <filename>\n git commit -m ...\n" }, { "answer_id": 27707, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 2, "selected": false, "text": "config.xml.sample config.xml config.xml" }, { "answer_id": 27727, "author": "Kai", "author_id": 2963, "author_profile": "https://Stackoverflow.com/users/2963", "pm_score": 3, "selected": false, "text": "git rm git rebase --interactive" }, { "answer_id": 27735, "author": "Sir Rippov the Maple", "author_id": 2822, "author_profile": "https://Stackoverflow.com/users/2822", "pm_score": 2, "selected": false, "text": "svnadmin dump svnadmin load" }, { "answer_id": 35913, "author": "dbr", "author_id": 745, "author_profile": "https://Stackoverflow.com/users/745", "pm_score": 2, "selected": false, "text": "git filter-branch --index-filter 'git update-index --remove filename' HEAD\n" }, { "answer_id": 36814, "author": "Damien Diederen", "author_id": 3844, "author_profile": "https://Stackoverflow.com/users/3844", "pm_score": 0, "selected": false, "text": ".gitignore" }, { "answer_id": 2978194, "author": "wxs", "author_id": 12981, "author_profile": "https://Stackoverflow.com/users/12981", "pm_score": 6, "selected": false, "text": "git rm --cached <filename>\n" }, { "answer_id": 9799129, "author": "Manu Manjunath", "author_id": 495598, "author_profile": "https://Stackoverflow.com/users/495598", "pm_score": 1, "selected": false, "text": "svn propedit svn:ignore . \n svn rm mydir\n" }, { "answer_id": 35891315, "author": "PerfectGamesOnline.com", "author_id": 929170, "author_profile": "https://Stackoverflow.com/users/929170", "pm_score": 0, "selected": false, "text": "sed find . | sed '1!G;h;$!d'| awk '{print \"svn rm --keep-local \" $1}'\n svn rm --keep-local yourFileNameXXX\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/27695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1870/" ]
27,711
<p>I'm having a problem obtaining the total row count for items displayed in a Gridview using Paging and with a LinqDataSource as the source of data.</p> <p>I've tried several approaches:</p> <pre><code>protected void GridDataSource_Selected(object sender, LinqDataSourceStatusEventArgs e) { totalLabel.Text = e.TotalRowCount.ToString(); } </code></pre> <p>returns -1 every time.</p> <pre><code>protected void LinqDataSource1_Selected(object sender, LinqDataSourceStatusEventArgs e) { System.Collections.Generic.List&lt;country&gt; lst = e.Result as System.Collections.Generic.List&lt;country&gt;; int count = lst.Count; } </code></pre> <p>only gives me the count for the current page, and not the total.</p> <p>Any other suggestions?</p>
[ { "answer_id": 3347416, "author": "Nick Kahn", "author_id": 275390, "author_profile": "https://Stackoverflow.com/users/275390", "pm_score": 0, "selected": false, "text": " protected void LinqDataSource1_Selecting(object sender, LinqDataSourceStatusEventArgs e)\n {\n System.Collections.Generic.List<country> lst = e.Result as System.Collections.Generic.List<country>;\n\n int count = lst.Count;\n }\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/27711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2841/" ]
27,726
<p>I completely understand the concept of expression trees, but I am having a hard time trying to find situations in which they are useful. Is there a specific instance in which expression trees can be applied? Or is it only useful as a transport mechanism for code? I feel like I am missing something here. Thanks!</p>
[ { "answer_id": 27736, "author": "Fredrik Kalseth", "author_id": 1710, "author_profile": "https://Stackoverflow.com/users/1710", "pm_score": 3, "selected": false, "text": "myMock.Verify(m => m.SomeMethod(someObject)); // tells moq to verify that the method\n // SomeMethod was called with \n // someObject as the argument\n myMock.Verify(\"SomeMethod\", someObject) // we've lost the strong typing\n" }, { "answer_id": 28734, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 2, "selected": false, "text": "//a linq to sql statement\nvar recs (\n from rec in LinqDataContext.Table\n where rec.IntField > 5\n select rec );\n where rec.IntField > 5 --SQL statment executed\nselect *\nfrom [table]\nwhere [table].[IntField] > 5\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/27726", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2993/" ]
27,743
<p>My RubyOnRails app is set up with the usual pack of mongrels behind Apache configuration. We've noticed that our Mongrel web server memory usage can grow quite large on certain operations and we'd really like to be able to dynamically do a graceful restart of selected Mongrel processes at any time.</p> <p>However, for reasons I won't go into here it can sometimes be <em>very</em> important that we don't interrupt a Mongrel while it is servicing a request, so I assume a simple process kill isn't the answer.</p> <p>Ideally, I want to send the Mongrel a signal that says "finish whatever you're doing and then quit before accepting any more connections".</p> <p>Is there a standard technique or best practice for this?</p>
[ { "answer_id": 27787, "author": "John Topley", "author_id": 1450, "author_profile": "https://Stackoverflow.com/users/1450", "pm_score": 0, "selected": false, "text": "mongrel_cluster_ctl stop\n mongrel_cluster_ctl restart\n" }, { "answer_id": 31556, "author": "AndrewR", "author_id": 2994, "author_profile": "https://Stackoverflow.com/users/2994", "pm_score": 5, "selected": true, "text": "** TERM signal received.\nThu Aug 28 00:52:35 +0000 2008: Reaping 2 threads for slow workers because of 'shutdown'\nWaiting for 2 requests to finish, could take 60 seconds.Thu Aug 28 00:52:41 +0000 2008: Reaping 2 threads for slow workers because of 'shutdown'\nWaiting for 2 requests to finish, could take 60 seconds.Thu Aug 28 00:52:43 +0000 2008 (13051) Rendering layoutfalsecontent_typetext/htmlactionindex within layouts/application\n" }, { "answer_id": 33906, "author": "hoyhoy", "author_id": 3499, "author_profile": "https://Stackoverflow.com/users/3499", "pm_score": 3, "selected": false, "text": "check process mongrel-8000 with pidfile /var/www/apps/fooapp/current/tmp/pids/mongrel.8000.pid\n start program = \"/usr/local/bin/mongrel_rails cluster::start --only 8000\"\n stop program = \"/usr/local/bin/mongrel_rails cluster::stop --only 8000\"\n\n if totalmem is greater than 150.0 MB for 5 cycles then restart # eating up memory?\n if cpu is greater than 50% for 8 cycles then alert # send an email to admin\n if cpu is greater than 80% for 5 cycles then restart # hung process?\n if loadavg(5min) greater than 10 for 3 cycles then restart # bad, bad, bad\n if 3 restarts within 5 cycles then timeout # something is wrong, call the sys-admin\n\n if failed host 192.168.106.53 port 8000 protocol http request /monit_stub\n with timeout 10 seconds\n then restart\n group mongrel\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/27743", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2994/" ]
27,745
<p>Given the URL (single line):<br> <a href="http://test.example.com/dir/subdir/file.html" rel="noreferrer">http://test.example.com/dir/subdir/file.html</a></p> <p>How can I extract the following parts using regular expressions:</p> <ol> <li>The Subdomain (test)</li> <li>The Domain (example.com)</li> <li>The path without the file (/dir/subdir/)</li> <li>The file (file.html)</li> <li>The path with the file (/dir/subdir/file.html)</li> <li>The URL without the path (<a href="http://test.example.com" rel="noreferrer">http://test.example.com</a>)</li> <li>(add any other that you think would be useful)</li> </ol> <p>The regex should work correctly even if I enter the following URL: </p> <pre><code>http://example.example.com/example/example/example.html </code></pre>
[ { "answer_id": 27755, "author": "hometoast", "author_id": 2009, "author_profile": "https://Stackoverflow.com/users/2009", "pm_score": 8, "selected": true, "text": "^((http[s]?|ftp):\\/)?\\/?([^:\\/\\s]+)((\\/\\w+)*\\/)([\\w\\-\\.]+[^#?\\s]+)(.*)?(#[\\w\\-]+)?$ /*\n ^(.*:)//([A-Za-z0-9\\-\\.]+)(:[0-9]+)?(.*)$\n*/\nproto $1\nhost $2\nport $3\nthe-rest $4\n" }, { "answer_id": 27759, "author": "Mark Ingram", "author_id": 986, "author_profile": "https://Stackoverflow.com/users/986", "pm_score": 3, "selected": false, "text": "^((ht|f)tp(s?)\\:\\/\\/|~/|/)?([\\w]+:\\w+@)?([a-zA-Z]{1}([\\w\\-]+\\.)+([\\w]{2,5}))(:[\\d]{1,5})?((/?\\w+/)+|/?)(\\w+\\.[\\w]{3,4})?((\\?\\w+=\\w+)?(&\\w+=\\w+)*)?\n" }, { "answer_id": 27768, "author": "tgmdbm", "author_id": 1851, "author_profile": "https://Stackoverflow.com/users/1851", "pm_score": 3, "selected": false, "text": " the path without the file : http://[^/]+/((?:[^/]+/)*(?:[^/]+$)?) \n the file : http://[^/]+/(?:[^/]+/)*((?:[^/.]+\\.)+[^/.]+)$ \n the path with the file : http://[^/]+/(.*) \n the URL without the path : (http://[^/]+/) \n" }, { "answer_id": 27785, "author": "Brian Warshaw", "author_id": 1344, "author_profile": "https://Stackoverflow.com/users/1344", "pm_score": 0, "selected": false, "text": "(?:SOMESTUFF) https?" }, { "answer_id": 309360, "author": "mingfai", "author_id": 39701, "author_profile": "https://Stackoverflow.com/users/39701", "pm_score": 5, "selected": false, "text": "^((http[s]?|ftp):\\/)?\\/?([^:\\/\\s]+)(:([^\\/]*))?((\\/\\w+)*\\/)([\\w\\-\\.]+[^#?\\s]+)(\\?([^#]*))?(#(.*))?$\n int SCHEMA = 2, DOMAIN = 3, PORT = 5, PATH = 6, FILE = 8, QUERYSTRING = 9, HASH = 12\n function getFileName(path) {\n return path.match(/^((http[s]?|ftp):\\/)?\\/?([^:\\/\\s]+)(:([^\\/]*))?((\\/[\\w\\/-]+)*\\/)([\\w\\-\\.]+[^#?\\s]+)(\\?([^#]*))?(#(.*))?$/i)[8];\n}\n" }, { "answer_id": 441881, "author": "strager", "author_id": 39992, "author_profile": "https://Stackoverflow.com/users/39992", "pm_score": 2, "selected": false, "text": "/^((?P<scheme>https?|ftp):\\/)?\\/?((?P<username>.*?)(:(?P<password>.*?)|)@)?(?P<hostname>[^:\\/\\s]+)(?P<port>:([^\\/]*))?(?P<path>(\\/\\w+)*\\/)(?P<filename>[-\\w.]+[^#?\\s]*)?(?P<query>\\?([^#]*))?(?P<fragment>#(.*))?$/\n" }, { "answer_id": 3724500, "author": "Shelby Moore", "author_id": 449214, "author_profile": "https://Stackoverflow.com/users/449214", "pm_score": 3, "selected": false, "text": " // Applies to URI, not just URL or URN:\n // http://en.wikipedia.org/wiki/Uniform_Resource_Identifier#Relationship_to_URL_and_URN\n //\n // http://labs.apache.org/webarch/uri/rfc/rfc3986.html#regexp\n //\n // (?:([^:/?#]+):)?(?://([^/?#]*))?([^?#]*)(?:\\?([^#]*))?(?:#(.*))?\n //\n // http://en.wikipedia.org/wiki/URI_scheme#Generic_syntax\n //\n // $@ matches the entire uri\n // $1 matches scheme (ftp, http, mailto, mshelp, ymsgr, etc)\n // $2 matches authority (host, user:pwd@host, etc)\n // $3 matches path\n // $4 matches query (http GET REST api, etc)\n // $5 matches fragment (html anchor, etc)\n //\n // Match specific schemes, non-optional authority, disallow white-space so can delimit in text, and allow 'www.' w/o scheme\n // Note the schemes must match ^[^\\s|:/?#]+(?:\\|[^\\s|:/?#]+)*$\n //\n // (?:()(www\\.[^\\s/?#]+\\.[^\\s/?#]+)|(schemes)://([^\\s/?#]*))([^\\s?#]*)(?:\\?([^\\s#]*))?(#(\\S*))?\n //\n // Validate the authority with an orthogonal RegExp, so the RegExp above won’t fail to match any valid urls.\n function uriRegExp( flags, schemes/* = null*/, noSubMatches/* = false*/ )\n {\n if( !schemes )\n schemes = '[^\\\\s:\\/?#]+'\n else if( !RegExp( /^[^\\s|:\\/?#]+(?:\\|[^\\s|:\\/?#]+)*$/ ).test( schemes ) )\n throw TypeError( 'expected URI schemes' )\n return noSubMatches ? new RegExp( '(?:www\\\\.[^\\\\s/?#]+\\\\.[^\\\\s/?#]+|' + schemes + '://[^\\\\s/?#]*)[^\\\\s?#]*(?:\\\\?[^\\\\s#]*)?(?:#\\\\S*)?', flags ) :\n new RegExp( '(?:()(www\\\\.[^\\\\s/?#]+\\\\.[^\\\\s/?#]+)|(' + schemes + ')://([^\\\\s/?#]*))([^\\\\s?#]*)(?:\\\\?([^\\\\s#]*))?(?:#(\\\\S*))?', flags )\n }\n\n // http://en.wikipedia.org/wiki/URI_scheme#Official_IANA-registered_schemes\n function uriSchemesRegExp()\n {\n return 'about|callto|ftp|gtalk|http|https|irc|ircs|javascript|mailto|mshelp|sftp|ssh|steam|tel|view-source|ymsgr'\n }\n" }, { "answer_id": 11976301, "author": "baadf00d", "author_id": 1577533, "author_profile": "https://Stackoverflow.com/users/1577533", "pm_score": 4, "selected": false, "text": "/(?:([^\\:]*)\\:\\/\\/)?(?:([^\\:\\@]*)(?:\\:([^\\@]*))?\\@)?(?:([^\\/\\:]*)\\.(?=[^\\.\\/\\:]*\\.[^\\.\\/\\:]*))?([^\\.\\/\\:]*)(?:\\.([^\\/\\.\\:]*))?(?:\\:([0-9]*))?(\\/[^\\?#]*(?=.*?\\/)\\/)?([^\\?#]*)?(?:\\?([^#]*))?(?:#(.*))?/\n ftp://user:[email protected]:8080/dir1/dir2/file.php?param1=value1#hashtag\n [\"ftp\", \"user\", \"pass\", \"www.cs\", \"server\", \"com\", \"8080\", \"/dir1/dir2/\", \"file.php\", \"param1=value1\", \"hashtag\"]\n mailto://[email protected]\n [\"mailto\", \"admin\", undefined, \"www.cs\", \"server\", \"com\", undefined, undefined, undefined, undefined, undefined] \n" }, { "answer_id": 12470263, "author": "Rob", "author_id": 203452, "author_profile": "https://Stackoverflow.com/users/203452", "pm_score": 6, "selected": false, "text": "var a = document.createElement('a');\na.href = 'http://www.example.com:123/foo/bar.html?fox=trot#foo';\n\n['href','protocol','host','hostname','port','pathname','search','hash'].forEach(function(k) {\n console.log(k+':', a[k]);\n});\n\n/*//Output:\nhref: http://www.example.com:123/foo/bar.html?fox=trot#foo\nprotocol: http:\nhost: www.example.com:123\nhostname: www.example.com\nport: 123\npathname: /foo/bar.html\nsearch: ?fox=trot\nhash: #foo\n*/\n" }, { "answer_id": 14057711, "author": "mjs", "author_id": 961018, "author_profile": "https://Stackoverflow.com/users/961018", "pm_score": 2, "selected": false, "text": "function getServerURL(url) {\n var m = url.match(\"(^(?:(?:.*?)?//)?[^/?#;]*)\");\n console.log(m[1]) // Remove this\n return m[1];\n }\n\ngetServerURL(\"http://dev.test.se\")\ngetServerURL(\"http://dev.test.se/\")\ngetServerURL(\"//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js\")\ngetServerURL(\"//\")\ngetServerURL(\"www.dev.test.se/sdas/dsads\")\ngetServerURL(\"www.dev.test.se/\")\ngetServerURL(\"www.dev.test.se?abc=32\")\ngetServerURL(\"www.dev.test.se#abc\")\ngetServerURL(\"//dev.test.se?sads\")\ngetServerURL(\"http://www.dev.test.se#321\")\ngetServerURL(\"http://localhost:8080/sads\")\ngetServerURL(\"https://localhost:8080?sdsa\")\n http://dev.test.se\n\nhttp://dev.test.se\n\n//ajax.googleapis.com\n\n//\n\nwww.dev.test.se\n\nwww.dev.test.se\n\nwww.dev.test.se\n\nwww.dev.test.se\n\n//dev.test.se\n\nhttp://www.dev.test.se\n\nhttp://localhost:8080\n\nhttps://localhost:8080\n" }, { "answer_id": 14385452, "author": "Skone", "author_id": 158039, "author_profile": "https://Stackoverflow.com/users/158039", "pm_score": 2, "selected": false, "text": "/^(?:((?:https?|s?ftp):)\\/\\/)([^:\\/\\s]+)(?::(\\d*))?(?:\\/([^\\s?#]+)?([?][^?#]*)?(#.*)?)?/\n" }, { "answer_id": 17892757, "author": "okigan", "author_id": 142207, "author_profile": "https://Stackoverflow.com/users/142207", "pm_score": 3, "selected": false, "text": "def url_path_to_dict(path):\n pattern = (r'^'\n r'((?P<schema>.+?)://)?'\n r'((?P<user>.+?)(:(?P<password>.*?))?@)?'\n r'(?P<host>.*?)'\n r'(:(?P<port>\\d+?))?'\n r'(?P<path>/.*?)?'\n r'(?P<query>[?].*?)?'\n r'$'\n )\n regex = re.compile(pattern)\n m = regex.match(path)\n d = m.groupdict() if m is not None else None\n\n return d\n\ndef main():\n print url_path_to_dict('http://example.example.com/example/example/example.html')\n {\n'host': 'example.example.com', \n'user': None, \n'path': '/example/example/example.html', \n'query': None, \n'password': None, \n'port': None, \n'schema': 'http'\n}\n" }, { "answer_id": 24527267, "author": "Sam Adams", "author_id": 1584651, "author_profile": "https://Stackoverflow.com/users/1584651", "pm_score": 4, "selected": false, "text": "var url = new URL('http://a:[email protected]:890/path/wah@t/foo.js?foo=bar&bingobang=&[email protected]#foobar/bing/bo@ng?bang');\n {\n \"hash\": \"#foobar/bing/bo@ng?bang\",\n \"search\": \"?foo=bar&bingobang=&[email protected]\",\n \"pathname\": \"/path/wah@t/foo.js\",\n \"port\": \"890\",\n \"hostname\": \"example.com\",\n \"host\": \"example.com:890\",\n \"password\": \"b\",\n \"username\": \"a\",\n \"protocol\": \"http:\",\n \"origin\": \"http://example.com:890\",\n \"href\": \"http://a:[email protected]:890/path/wah@t/foo.js?foo=bar&bingobang=&[email protected]#foobar/bing/bo@ng?bang\"\n}\n ^(?:(?:(([^:\\/#\\?]+:)?(?:(?:\\/\\/)(?:(?:(?:([^:@\\/#\\?]+)(?:\\:([^:@\\/#\\?]*))?)@)?(([^:\\/#\\?\\]\\[]+|\\[[^\\/\\]@#?]+\\])(?:\\:([0-9]+))?))?)?)?((?:\\/?(?:[^\\/\\?#]+\\/+)*)(?:[^\\?#]*)))?(\\?[^#]+)?)(#.*)?\n var keys = [\n \"href\", // http://user:[email protected]:81/directory/file.ext?query=1#anchor\n \"origin\", // http://user:[email protected]:81\n \"protocol\", // http:\n \"username\", // user\n \"password\", // pass\n \"host\", // host.com:81\n \"hostname\", // host.com\n \"port\", // 81\n \"pathname\", // /directory/file.ext\n \"search\", // ?query=1\n \"hash\" // #anchor\n];\n" }, { "answer_id": 26766402, "author": "jds", "author_id": 1830334, "author_profile": "https://Stackoverflow.com/users/1830334", "pm_score": 7, "selected": false, "text": "^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?\n 12 3 4 5 6 7 8 9\n http://www.ics.uci.edu/pub/ietf/uri/#Related $1 = http:\n$2 = http\n$3 = //www.ics.uci.edu\n$4 = www.ics.uci.edu\n$5 = /pub/ietf/uri/\n$6 = <undefined>\n$7 = <undefined>\n$8 = #Related\n$9 = Related\n ^(([^:\\/?#]+):)?(\\/\\/([^\\/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?" }, { "answer_id": 34451670, "author": "ylev", "author_id": 3187132, "author_profile": "https://Stackoverflow.com/users/3187132", "pm_score": -1, "selected": false, "text": "String s = \"https://www.thomas-bayer.com/axis2/services/BLZService?wsdl\";\n\nString regex = \"(^http.?://)(.*?)([/\\\\?]{1,})(.*)\";\n\nSystem.out.println(\"1: \" + s.replaceAll(regex, \"$1\"));\nSystem.out.println(\"2: \" + s.replaceAll(regex, \"$2\"));\nSystem.out.println(\"3: \" + s.replaceAll(regex, \"$3\"));\nSystem.out.println(\"4: \" + s.replaceAll(regex, \"$4\"));\n" }, { "answer_id": 39284990, "author": "Steve K", "author_id": 2020820, "author_profile": "https://Stackoverflow.com/users/2020820", "pm_score": 0, "selected": false, "text": "^(?:(?P<protocol>\\w+(?=:\\/\\/))(?::\\/\\/))?\n(?:(?P<host>(?:(?:&(?:amp|apos|gt|lt|nbsp|quot|bull|hellip|[lr][ds]quo|[mn]dash|permil|\\#[1-9][0-9]{1,3}|[A-Za-z][0-9A-Za-z]+);)|[^\\/?#:]+)(?::(?P<port>[0-9]+))?)\\/)?\n(?:(?P<path>(?:(?:&(?:amp|apos|gt|lt|nbsp|quot|bull|hellip|[lr][ds]quo|[mn]dash|permil|\\#[1-9][0-9]{1,3}|[A-Za-z][0-9A-Za-z]+);)|[^?#])+)\\/)?\n(?P<file>(?:(?:&(?:amp|apos|gt|lt|nbsp|quot|bull|hellip|[lr][ds]quo|[mn]dash|permil|\\#[1-9][0-9]{1,3}|[A-Za-z][0-9A-Za-z]+);)|[^?#])+)\n(?:\\?(?P<querystring>(?:(?:&(?:amp|apos|gt|lt|nbsp|quot|bull|hellip|[lr][ds]quo|[mn]dash|permil|\\#[1-9][0-9]{1,3}|[A-Za-z][0-9A-Za-z]+);)|[^#])+))?\n(?:#(?P<fragment>.*))?$\n ? # $htmlentity = \"&(?:amp|apos|gt|lt|nbsp|quot|bull|hellip|[lr][ds]quo|[mn]dash|permil|\\#[1-9][0-9]{1,3}|[A-Za-z][0-9A-Za-z]+);\"\n ^(?:(?P<protocol>(?:ht|f)tps?|\\w+(?=:\\/\\/))(?::\\/\\/))?\n(?:(?P<host>(?:{{htmlentity}}|[^\\/?#:])+(?::(?P<port>[0-9]+))?)\\/)?\n(?:(?P<path>(?:{{htmlentity}}|[^?#])+)\\/)?\n(?P<file>(?:{{htmlentity}}|[^?#])+)\n(?:\\?(?P<querystring>(?:{{htmlentity}};|[^#])+))?\n(?:#(?P<fragment>.*))?$\n ^(?:(\\w+(?=:\\/\\/))(?::\\/\\/))?(?:((?:(?:&(?:amp|apos|gt|lt|nbsp|quot|bull|hellip|[lr][ds]quo|[mn]dash|permil|\\#[1-9][0-9]{1,3}|[A-Za-z][0-9A-Za-z]+);)|[^\\/?#:]+)(?::([0-9]+))?)\\/)?(?:((?:(?:&(?:amp|apos|gt|lt|nbsp|quot|bull|hellip|[lr][ds]quo|[mn]dash|permil|\\#[1-9][0-9]{1,3}|[A-Za-z][0-9A-Za-z]+);)|[^?#])+)\\/)?((?:(?:&(?:amp|apos|gt|lt|nbsp|quot|bull|hellip|[lr][ds]quo|[mn]dash|permil|\\#[1-9][0-9]{1,3}|[A-Za-z][0-9A-Za-z]+);)|[^?#])+)(?:\\?((?:(?:&(?:amp|apos|gt|lt|nbsp|quot|bull|hellip|[lr][ds]quo|[mn]dash|permil|\\#[1-9][0-9]{1,3}|[A-Za-z][0-9A-Za-z]+);)|[^#])+))?(?:#(.*))?$\n \\1 \\2 \\3 \\4 \\5 \\6 \\7" }, { "answer_id": 40766359, "author": "Gil Zellner", "author_id": 1889311, "author_profile": "https://Stackoverflow.com/users/1889311", "pm_score": 1, "selected": false, "text": "^((?P<protocol>http[s]?|ftp):\\/)?\\/?(?P<host>[^:\\/\\s]+)(?P<path>((\\/\\w+)*\\/)([\\w\\-\\.]+[^#?\\s]+))*(.*)?(#[\\w\\-]+)?$\n" }, { "answer_id": 45708666, "author": "mohan mu", "author_id": 7745445, "author_profile": "https://Stackoverflow.com/users/7745445", "pm_score": 0, "selected": false, "text": "//USING REGEX\n/**\n * Parse URL to get information\n *\n * @param url the URL string to parse\n * @return parsed the URL parsed or null\n */\nvar UrlParser = function (url) {\n \"use strict\";\n\n var regx = /^(((([^:\\/#\\?]+:)?(?:(\\/\\/)((?:(([^:@\\/#\\?]+)(?:\\:([^:@\\/#\\?]+))?)@)?(([^:\\/#\\?\\]\\[]+|\\[[^\\/\\]@#?]+\\])(?:\\:([0-9]+))?))?)?)?((\\/?(?:[^\\/\\?#]+\\/+)*)([^\\?#]*)))?(\\?[^#]+)?)(#.*)?/,\n matches = regx.exec(url),\n parser = null;\n\n if (null !== matches) {\n parser = {\n href : matches[0],\n withoutHash : matches[1],\n url : matches[2],\n origin : matches[3],\n protocol : matches[4],\n protocolseparator : matches[5],\n credhost : matches[6],\n cred : matches[7],\n user : matches[8],\n pass : matches[9],\n host : matches[10],\n hostname : matches[11],\n port : matches[12],\n pathname : matches[13],\n segment1 : matches[14],\n segment2 : matches[15],\n search : matches[16],\n hash : matches[17]\n };\n }\n\n return parser;\n};\n\nvar parsedURL=UrlParser(url);\nconsole.log(parsedURL);\n" }, { "answer_id": 63028949, "author": "Bilal Demir", "author_id": 9082736, "author_profile": "https://Stackoverflow.com/users/9082736", "pm_score": 0, "selected": false, "text": "^((http[s]?|ftp):\\/)?\\/?([^:\\/\\s]+)(:([^\\/]*))?((\\/?(?:[^\\/\\?#]+\\/+)*)([^\\?#]*))(\\?([^#]*))?(#(.*))?$\n https://www.google.com/my/path/sample/asd-dsa/this?key1=value1&key2=value2 Group 1. 0-7 https:/\nGroup 2. 0-5 https\nGroup 3. 8-22 www.google.com\nGroup 6. 22-50 /my/path/sample/asd-dsa/this\nGroup 7. 22-46 /my/path/sample/asd-dsa/\nGroup 8. 46-50 this\nGroup 9. 50-74 ?key1=value1&key2=value2\nGroup 10. 51-74 key1=value1&key2=value2\n" }, { "answer_id": 64468826, "author": "CallMarl", "author_id": 5540407, "author_profile": "https://Stackoverflow.com/users/5540407", "pm_score": 1, "selected": false, "text": "^((http[s]?):\\/\\/)?([a-zA-Z0-9-.]*)?([\\/]?[^?#\\n]*)?([?]?[^?#\\n]*)?([#]?[^?#\\n]*)$ http://\nhttps://\nwww.demo.com\n/slug\n?foo=bar\n#anchor\n\nhttps://demo.com\nhttps://demo.com/\nhttps://demo.com/slug\nhttps://demo.com/slug/foo\nhttps://demo.com/?foo=bar\nhttps://demo.com/?foo=bar#anchor\nhttps://demo.com/?foo=bar&bar=foo#anchor\nhttps://www.greate-demo.com/\n #anchor#\n?toto?\n" }, { "answer_id": 65070175, "author": "Hritik Soni", "author_id": 5113528, "author_profile": "https://Stackoverflow.com/users/5113528", "pm_score": 0, "selected": false, "text": "^((http[s]?|ftp):\\/)?\\/?([^:\\/\\s]+)(:\\d+)?((\\/\\w+)*\\/)([\\w\\-\\.]+[^#?\\s]+)(.*)?(#[\\w\\-]+)?$\n" }, { "answer_id": 67148884, "author": "igorzg", "author_id": 3053382, "author_profile": "https://Stackoverflow.com/users/3053382", "pm_score": 3, "selected": false, "text": "const URI_RE = /^(([^:\\/\\s]+):\\/?\\/?([^\\/\\s@]*@)?([^\\/@:]*)?:?(\\d+)?)?(\\/[^?]*)?(\\?([^#]*))?(#[\\s\\S]*)?$/;\n/**\n* GROUP 1 ([scheme][authority][host][port])\n* GROUP 2 (scheme)\n* GROUP 3 (authority)\n* GROUP 4 (host)\n* GROUP 5 (port)\n* GROUP 6 (path)\n* GROUP 7 (?query)\n* GROUP 8 (query)\n* GROUP 9 (fragment)\n*/\nURI_RE.exec(\"https://john:[email protected]:123/forum/questions/?tag=networking&order=newest#top\");\nURI_RE.exec(\"/forum/questions/?tag=networking&order=newest#top\");\nURI_RE.exec(\"ldap://[2001:db8::7]/c=GB?objectClass?one\");\nURI_RE.exec(\"mailto:[email protected]\");\n" }, { "answer_id": 67796005, "author": "MattWeiler", "author_id": 1827349, "author_profile": "https://Stackoverflow.com/users/1827349", "pm_score": 1, "selected": false, "text": "\"^(?:(http[s]?|ftp):/)?/?\" + // METHOD\n\"([^:^/^?^#\\\\s]+)\" + // HOSTNAME\n\"(?::(\\\\d+))?\" + // PORT\n\"([^?^#.*]+)?\" + // PATH\n\"(\\\\?[^#.]*)?\" + // QUERY\n\"(#[\\\\w\\\\-]+)?$\" // ID\n final Pattern pattern = Pattern.compile(\n \"^(?:(http[s]?|ftp):/)?/?\" + // METHOD\n \"([^:^/^?^#\\\\s]+)\" + // HOSTNAME\n \"(?::(\\\\d+))?\" + // PORT\n \"([^?^#.*]+)?\" + // PATH\n \"(\\\\?[^#.]*)?\" + // QUERY\n \"(#[\\\\w\\\\-]+)?$\" // ID\n);\nfinal Matcher matcher = pattern.matcher(url);\n\nSystem.out.println(\" URL: \" + url);\n\nif (matcher.matches())\n{\n System.out.println(\" Method: \" + matcher.group(1));\n System.out.println(\"Hostname: \" + matcher.group(2));\n System.out.println(\" Port: \" + matcher.group(3));\n System.out.println(\" Path: \" + matcher.group(4));\n System.out.println(\" Query: \" + matcher.group(5));\n System.out.println(\" ID: \" + matcher.group(6));\n \n return matcher.group(2);\n}\n\nSystem.out.println();\nSystem.out.println();\n" }, { "answer_id": 70326445, "author": "Exo Flame", "author_id": 4530300, "author_profile": "https://Stackoverflow.com/users/4530300", "pm_score": 0, "selected": false, "text": "let url = new URL('https://test.example.com/cats?name=foofy')\nurl.protocall; // https:\nurl.hostname; // test.example.com\nurl.pathname; // /cats\nurl.search; // ?name=foofy\n\nlet params = url.searchParams\nlet name = params.get('name');// always string I think so parse accordingly\n\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/27745", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2644/" ]
27,757
<p>I am storing a PNG as an embedded resource in an assembly. From within the same assembly I have some code like this:</p> <pre><code>Bitmap image = new Bitmap(typeof(MyClass), "Resources.file.png"); </code></pre> <p>The file, named "file.png" is stored in the "Resources" folder (within Visual Studio), and is marked as an embedded resource.</p> <p>The code fails with an exception saying: </p> <blockquote> <p>Resource MyNamespace.Resources.file.png cannot be found in class MyNamespace.MyClass</p> </blockquote> <p>I have identical code (in a different assembly, loading a different resource) which works. So I know the technique is sound. My problem is I end up spending a lot of time trying to figure out what the correct path is. If I could simply query (eg. in the debugger) the assembly to find the correct path, that would save me a load of headaches.</p>
[ { "answer_id": 27769, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 4, "selected": false, "text": "ProjectNamespace.Properties.Resources.file\n" }, { "answer_id": 27773, "author": "John", "author_id": 33, "author_profile": "https://Stackoverflow.com/users/33", "pm_score": 9, "selected": true, "text": "System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceNames();\n" }, { "answer_id": 28253, "author": "Dylan", "author_id": 3074, "author_profile": "https://Stackoverflow.com/users/3074", "pm_score": 6, "selected": false, "text": "public class Utility\n{\n /// <summary>\n /// Takes the full name of a resource and loads it in to a stream.\n /// </summary>\n /// <param name=\"resourceName\">Assuming an embedded resource is a file\n /// called info.png and is located in a folder called Resources, it\n /// will be compiled in to the assembly with this fully qualified\n /// name: Full.Assembly.Name.Resources.info.png. That is the string\n /// that you should pass to this method.</param>\n /// <returns></returns>\n public static Stream GetEmbeddedResourceStream(string resourceName)\n {\n return Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName);\n }\n\n /// <summary>\n /// Get the list of all emdedded resources in the assembly.\n /// </summary>\n /// <returns>An array of fully qualified resource names</returns>\n public static string[] GetEmbeddedResourceNames()\n {\n return Assembly.GetExecutingAssembly().GetManifestResourceNames();\n }\n}\n" }, { "answer_id": 22045449, "author": "user3356450", "author_id": 3356450, "author_profile": "https://Stackoverflow.com/users/3356450", "pm_score": 2, "selected": false, "text": "public static Stream GetResourceFileStream(String nameSpace, String filePath)\n{\n String pseduoName = filePath.Replace('\\\\', '.');\n Assembly assembly = Assembly.GetExecutingAssembly();\n return assembly.GetManifestResourceStream(nameSpace + \".\" + pseduoName);\n}\n GetResourceFileStream(\"my.namespace\", \"resources\\\\xml\\\\my.xml\")\n" }, { "answer_id": 27993476, "author": "masterwok", "author_id": 563509, "author_profile": "https://Stackoverflow.com/users/563509", "pm_score": 3, "selected": false, "text": "protected static Stream GetResourceStream(string resourcePath)\n{\n Assembly assembly = Assembly.GetExecutingAssembly();\n List<string> resourceNames = new List<string>(assembly.GetManifestResourceNames());\n\n resourcePath = resourcePath.Replace(@\"/\", \".\");\n resourcePath = resourceNames.FirstOrDefault(r => r.Contains(resourcePath));\n\n if (resourcePath == null)\n throw new FileNotFoundException(\"Resource not found\");\n\n return assembly.GetManifestResourceStream(resourcePath);\n}\n GetResourceStream(@\"DirectoryPathInLibrary/Filename\");\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/27757", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1006/" ]
27,758
<p>OK, I know what you're thinking, &quot;why write a method you do not want people to use?&quot; Right?</p> <p>Well, in short, I have a class that needs to be serialized to XML. In order for the <a href="https://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer%28v=vs.110%29.aspx" rel="noreferrer"><code>XmlSerializer</code></a> to do its magic, the class must have a default, empty constructor:</p> <pre><code>public class MyClass { public MyClass() { // required for xml serialization } } </code></pre> <p>So, I need to have it, but I don't want people to <em>use</em> it, so <strong>is there any attribute that can be use to mark the method as &quot;DO NOT USE&quot;?</strong></p> <p>I was thinking of using the <em>Obsolete</em> attribute (since this can stop the build), but that just seems kinda &quot;wrong&quot;, is there any other way of doing this, or do I need to go ahead and bite the bullet? :)</p> <h2>Update</h2> <p>OK, I have accepted Keith's answer, since I guess in my heart of hearts, I totally agree. This is why I asked the question in the first place, I don't like the notion of having the <em>Obsolete</em> attribute.</p> <h3>However...</h3> <p>There <em>is</em> still a problem, while we are being notified in intellisense, ideally, we would like to break the build, so is there any way to do this? Perhaps create a custom attribute?</p> <p><strong>More focused question has been created <a href="https://stackoverflow.com/questions/28150/create-an-attribute-to-break-the-build">here</a>.</strong></p>
[ { "answer_id": 27763, "author": "hometoast", "author_id": 2009, "author_profile": "https://Stackoverflow.com/users/2009", "pm_score": 2, "selected": false, "text": " /// <summary>\n /// do not use\n /// </summary>\n /// <param name=\"item\">don't pass it anything -- you shouldn't use it.</param>\n /// <returns>nothing - you shouldn't use it</returns>\n public bool Include(T item) { \n ....\n" }, { "answer_id": 27764, "author": "Sir Rippov the Maple", "author_id": 2822, "author_profile": "https://Stackoverflow.com/users/2822", "pm_score": 0, "selected": false, "text": "ObsoleteAttribute" }, { "answer_id": 27765, "author": "Mark Ingram", "author_id": 986, "author_profile": "https://Stackoverflow.com/users/986", "pm_score": 0, "selected": false, "text": "ObsoleteAttribute using System;\n\npublic sealed class App {\n static void Main() { \n // The line below causes the compiler to issue a warning:\n // 'App.SomeDeprecatedMethod()' is obsolete: 'Do not call this method.'\n SomeDeprecatedMethod();\n }\n\n // The method below is marked with the ObsoleteAttribute. \n // Any code that attempts to call this method will get a warning.\n [Obsolete(\"Do not call this method.\")]\n private static void SomeDeprecatedMethod() { }\n}\n" }, { "answer_id": 27766, "author": "chrissie1", "author_id": 2936, "author_profile": "https://Stackoverflow.com/users/2936", "pm_score": 0, "selected": false, "text": "\npublic class MyClass\n{\n [Obsolete(\"reason\", true)]\n public MyClass()\n {\n // required for xml serialization\n }\n}\n" }, { "answer_id": 27767, "author": "Biri", "author_id": 968, "author_profile": "https://Stackoverflow.com/users/968", "pm_score": 0, "selected": false, "text": "ObsoleteAttribute" }, { "answer_id": 27825, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 5, "selected": true, "text": "[Serialisable] XmlSerializer [Obsolete]" }, { "answer_id": 27906, "author": "rjzii", "author_id": 1185, "author_profile": "https://Stackoverflow.com/users/1185", "pm_score": 2, "selected": false, "text": "ObsoleteAttribute" }, { "answer_id": 29068, "author": "ICR", "author_id": 214, "author_profile": "https://Stackoverflow.com/users/214", "pm_score": 5, "selected": false, "text": "[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]\n" }, { "answer_id": 29079, "author": "Sergio Acosta", "author_id": 2954, "author_profile": "https://Stackoverflow.com/users/2954", "pm_score": 2, "selected": false, "text": "Attribute NonCallableAttribute" }, { "answer_id": 29090, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 3, "selected": false, "text": "throw new ISaidDoNotUseException();\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/27758", "https://Stackoverflow.com", "https://Stackoverflow.com/users/832/" ]
27,774
<p>Effectively I want to give numeric scores to alphabetic grades and sum them. In Excel, putting the <code>LOOKUP</code> function into an array formula works:</p> <pre><code>{=SUM(LOOKUP(grades, scoringarray))} </code></pre> <p>With the <code>VLOOKUP</code> function this does not work (only gets the score for the first grade). Google Spreadsheets does not appear to have the <code>LOOKUP</code> function and <code>VLOOKUP</code> fails in the same way using:</p> <pre><code>=SUM(ARRAYFORMULA(VLOOKUP(grades, scoresarray, 2, 0))) </code></pre> <p>or</p> <pre><code>=ARRAYFORMULA(SUM(VLOOKUP(grades, scoresarray, 2, 0))) </code></pre> <p>Is it possible to do this (but I have the syntax wrong)? Can you suggest a method that allows having the calculation in one simple cell like this rather than hiding the lookups somewhere else and summing them afterwards?</p>
[ { "answer_id": 29690, "author": "Sam Brightman", "author_id": 2492, "author_profile": "https://Stackoverflow.com/users/2492", "pm_score": 1, "selected": true, "text": "MATCH INDEX OFFSET INDIRECT CHOOSE CHOOSE CHOOSE =ARRAYFORMULA(SUM(CHOOSE(MATCH(D1:D8,Lookups!$A$1:$A$3,0),\n Lookups!$B$1,Lookups!$B$2,Lookups!$B$3)))\n" }, { "answer_id": 14738977, "author": "HHains", "author_id": 2048572, "author_profile": "https://Stackoverflow.com/users/2048572", "pm_score": 0, "selected": false, "text": "=ARRAYFORMULA(SUM(INDIRECT(ADDRESS(MATCH(), MATCH())))\n" }, { "answer_id": 51566590, "author": "pnuts", "author_id": 1505120, "author_profile": "https://Stackoverflow.com/users/1505120", "pm_score": 1, "selected": false, "text": "grades scoringarray" }, { "answer_id": 55196805, "author": "player0", "author_id": 5632629, "author_profile": "https://Stackoverflow.com/users/5632629", "pm_score": 0, "selected": false, "text": "=SUM(IFERROR(ARRAYFORMULA(VLOOKUP(A2:A, {{\"A\", 6};\n {\"B\", 5};\n {\"C\", 4};\n {\"D\", 3};\n {\"E\", 2};\n {\"F\", 1}}, 2, 0)), ))\n =SUM(IFERROR(ARRAYFORMULA(VLOOKUP(A2:A, E2:F, 2, 0)), ))\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/27774", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2492/" ]
27,818
<p>We've embedded an OSGi runtime (Equinox) into out custom client-server application to facilitate plugin development and so far things are going great. We've been using Eclipse to build plugins due to the built-in manifest editor, dependency management, and export wizard. Using Eclipse to manager builds isn't very conducive to continuous integration via Hudson.</p> <p>We have OSGi bundles which depend on other OSGi bundles. I'd really hate to hardcode build order in a custom ANT build. We've done this is the past and it's pretty horrible. Is there any build tool that can EASILY manage OSGi dependencies, if not automatically resolve them? Are there any DECENT examples of how to this?</p> <p>CLARIFICATION:</p> <p>The generated build scripts are only usable via Eclipse. They require manually running pieces of Eclipse. We've also got some standard targets which the Eclipse build won't have, and I don't want to modify the generated file since I may regenerate (I know I can do includes, but I want to avoid the Eclipse gen file all together)</p> <p>Here is my project layout:</p> <pre><code>/ -PluginA -PluginB -PluginC . . . </code></pre> <p>In using the Eclipse PDE, each plugin has a Manifest, but no build.xml as the PDE does that for me. Hard to automate a gui driven process w/ Hudson. I'd like to setup my own build.xml to build each, BUT there are dependencies and build order issues. These issues are driven by the Manifest files (which describe OSGi imports). For example, PluginC depends on PluginB which depends on PluginA. They must be built in the correct order. I realize that I can manually control the build order, I'm looking for a tool to help automate the build order dependency management.</p>
[ { "answer_id": 5155085, "author": "mike", "author_id": 639398, "author_profile": "https://Stackoverflow.com/users/639398", "pm_score": 0, "selected": false, "text": "select 252 - osgi-archetype\nmvn idea:idea\n <Export-Package>org.foo.myproject.api</Export-Package>\n <Import-Package>org.foo.myproject.api</Import-Package>\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/27818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/287/" ]
27,832
<p>I have a DirectShow graph to render MPEG2/4 movies from a network stream. When I assemble the graph by connecting the pins manually it doesn't render. But when I call Render on the GraphBuilder it renders fine. </p> <p>Obviously there is some setup step that I'm not performing on some filter in the graph that GraphBuilder is performing. </p> <p>Is there any way to see debug output from GraphBuilder when it assembles a graph?</p> <p>Is there a way to dump a working graph to see how it was put together?</p> <p>Any other ideas for unraveling the mystery that lives in the DirectShow box?</p> <p>Thanks! -Z</p>
[ { "answer_id": 27858, "author": "Timbo", "author_id": 1810, "author_profile": "https://Stackoverflow.com/users/1810", "pm_score": 5, "selected": true, "text": "void AddToRot( IUnknown *pUnkGraph, DWORD *pdwRegister ) \n{\n IMoniker* pMoniker;\n IRunningObjectTable* pROT;\n GetRunningObjectTable( 0, &pROT );\n\n WCHAR wsz[256]; \n swprintf_s( wsz, L\"FilterGraph %08p pid %08x\", (DWORD_PTR)pUnkGraph, GetCurrentProcessId() );\n CreateItemMoniker( L\"!\", wsz, &pMoniker );\n\n pROT->Register( 0, pUnkGraph, pMoniker, pdwRegister );\n\n // Clean up any COM stuff here ...\n}\n" }, { "answer_id": 26786068, "author": "Nitay", "author_id": 328059, "author_profile": "https://Stackoverflow.com/users/328059", "pm_score": 1, "selected": false, "text": "void AddToROT( IUnknown *pUnkGraph, DWORD *pdwRegister ) \n{\n IMoniker * pMoniker;\n IRunningObjectTable *pROT;\n WCHAR wsz[128];\n HRESULT hr;\n\n if (FAILED(GetRunningObjectTable(0, &pROT)))\n return;\n\n wsprintfW(wsz, L\"FilterGraph %08x pid %08x\", (DWORD_PTR)pUnkGraph, GetCurrentProcessId());\n\n hr = CreateItemMoniker(L\"!\", wsz, &pMoniker);\n if (SUCCEEDED(hr)) \n {\n hr = pROT->Register(0, pUnkGraph, pMoniker, pdwRegister);\n pMoniker->Release();\n }\n\n pROT->Release();\n}\n void RemoveFromROT(DWORD pdwRegister)\n{\n IRunningObjectTable *pROT;\n\n if (SUCCEEDED(GetRunningObjectTable(0, &pROT))) \n {\n pROT->Revoke(pdwRegister);\n pROT->Release();\n }\n}\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/27832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2587612/" ]
27,835
<p>Recently, I started changing some of our applications to support <code>MS SQL Server</code> as an alternative back end. </p> <p>One of the compatibility issues I ran into is the use of MySQL's CREATE TEMPORARY TABLE to create in-memory tables that hold data for very fast access during a session with no need for permanent storage.</p> <p>What is the equivalent in MS SQL?</p> <p>A requirement is that I need to be able to use the temporary table just like any other, especially <code>JOIN</code> it with the permanent ones.</p>
[ { "answer_id": 27842, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 2, "selected": false, "text": "declare @foo table (\n Id int,\n Name varchar(100)\n);\n select * from @foo f\n join bar b on b.Id = f.Id\n" }, { "answer_id": 27848, "author": "JamesSugrue", "author_id": 1075, "author_profile": "https://Stackoverflow.com/users/1075", "pm_score": 1, "selected": false, "text": "CREATE TABLE #localtemp\n" }, { "answer_id": 27849, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 4, "selected": false, "text": "--visible only to me, in memory (SQL 2000 and above only)\ndeclare @test table (\n Field1 int,\n Field2 nvarchar(50)\n);\n\n--visible only to me, stored in tempDB\ncreate table #test (\n Field1 int,\n Field2 nvarchar(50)\n)\n\n--visible to everyone, stored in tempDB\ncreate table ##test (\n Field1 int,\n Field2 nvarchar(50)\n)\n #table ##table @Table" }, { "answer_id": 27886095, "author": "Joezer", "author_id": 1994420, "author_profile": "https://Stackoverflow.com/users/1994420", "pm_score": 2, "selected": false, "text": "-- create a database with a memory-optimized filegroup and a container.\nCREATE DATABASE imoltp \nGO\n\nALTER DATABASE imoltp ADD FILEGROUP imoltp_mod CONTAINS MEMORY_OPTIMIZED_DATA \nALTER DATABASE imoltp ADD FILE (name='imoltp_mod1', filename='c:\\data\\imoltp_mod1') TO FILEGROUP imoltp_mod \nALTER DATABASE imoltp SET MEMORY_OPTIMIZED_ELEVATE_TO_SNAPSHOT=ON\nGO\n\nUSE imoltp\nGO\n\n\n-- create a durable (data will be persisted) memory-optimized table\n-- two of the columns are indexed\nCREATE TABLE dbo.ShoppingCart ( \n ShoppingCartId INT IDENTITY(1,1) PRIMARY KEY NONCLUSTERED,\n UserId INT NOT NULL INDEX ix_UserId NONCLUSTERED HASH WITH (BUCKET_COUNT=1000000), \n CreatedDate DATETIME2 NOT NULL, \n TotalPrice MONEY\n ) WITH (MEMORY_OPTIMIZED=ON) \nGO\n\n -- create a non-durable table. Data will not be persisted, data loss if the server turns off unexpectedly\nCREATE TABLE dbo.UserSession ( \n SessionId INT IDENTITY(1,1) PRIMARY KEY NONCLUSTERED HASH WITH (BUCKET_COUNT=400000), \n UserId int NOT NULL, \n CreatedDate DATETIME2 NOT NULL,\n ShoppingCartId INT,\n INDEX ix_UserId NONCLUSTERED HASH (UserId) WITH (BUCKET_COUNT=400000) \n ) WITH (MEMORY_OPTIMIZED=ON, DURABILITY=SCHEMA_ONLY) \nGO\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/27835", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2077/" ]
27,846
<p>What is the configuration setting for modifying the default homepage in a Grails application to no longer be appName/index.gsp? Of course you can set that page to be a redirect but there must be a better way.</p>
[ { "answer_id": 17335212, "author": "Rashedul.Rubel", "author_id": 1632305, "author_profile": "https://Stackoverflow.com/users/1632305", "pm_score": 4, "selected": false, "text": "class UrlMappings {\n\n static mappings = {\n\n \"/$controller/$action?/$id?\"{\n constraints {\n // apply constraints here\n }\n }\n\n //\"/\"(view:\"/index\")\n \"/\" ( controller:'Item', action:'index' ) // Here i have changed the desired action to show the desired page while running the application\n \"500\"(view:'/error')\n }\n}\n" }, { "answer_id": 26539671, "author": "Mehul Katpara", "author_id": 4093220, "author_profile": "https://Stackoverflow.com/users/4093220", "pm_score": 0, "selected": false, "text": "// \"/$controller/$action?/$id?(.$format)?\"{\n// constraints {\n// // apply constraints here\n// }\n// }\n" }, { "answer_id": 28975869, "author": "Robert Erlinger", "author_id": 1552745, "author_profile": "https://Stackoverflow.com/users/1552745", "pm_score": 2, "selected": false, "text": "class UrlMappings {\n static mappings = {\n \"/\" (controller:'dashboard', view: 'index', action: 'index')\n \"500\"(view:'/error')\n }\n}\n" }, { "answer_id": 55970990, "author": "John Little", "author_id": 1072187, "author_profile": "https://Stackoverflow.com/users/1072187", "pm_score": 0, "selected": false, "text": "\"/\"(controller:\"dashboard\", view:\"/index\")\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/27846", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3014/" ]
27,850
<p>So far I have encountered adjacency list, nested sets and nested intervals as models for storing tree structures in a database. I know these well enough and have migrated trees from one to another.</p> <p>What are other popular models? What are their characteristics? What are good resources (books, web, etc) on this topic?</p> <p>I'm not only looking for db storage but would like to expand my knowledge on trees in general. For example, I understand that nested sets/intervals are especially favorable for relational database storage and have asked myself, are they actually a <i>bad</i> choice in other contexts?</p>
[ { "answer_id": 27863, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 2, "selected": false, "text": "C:\\\n Temp\n Windows\n System32\n Key Name Parent Path\n1 C: *1*\n2 Temp 1 *1*2*\n3 Windows 1 *1*3*\n4 System32 3 *1*3*4*\n WHERE Path LIKE '*1*2*%'\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/27850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2077/" ]
27,894
<p>In SQL Server 2005, we can create temp tables one of two ways:</p> <pre><code>declare @tmp table (Col1 int, Col2 int); </code></pre> <p>or</p> <pre><code>create table #tmp (Col1 int, Col2 int); </code></pre> <p>What are the differences between these two? I have read conflicting opinions on whether @tmp still uses tempdb, or if everything happens in memory. </p> <p>In which scenarios does one out-perform the other? </p>
[ { "answer_id": 64891, "author": "Rory", "author_id": 8479, "author_profile": "https://Stackoverflow.com/users/8479", "pm_score": 10, "selected": true, "text": "SELECT NOLOCK" }, { "answer_id": 8204184, "author": "Martin Smith", "author_id": 73226, "author_profile": "https://Stackoverflow.com/users/73226", "pm_score": 5, "selected": false, "text": "insert update delete @table_variable #temp sys.syssingleobjrefs #temp nvarchar sqlcmd :setvar tablename \"@T\" \n:setvar tablescript \"DECLARE @T TABLE\"\n\n/*\n --Uncomment this section to test a #temp table\n:setvar tablename \"#T\" \n:setvar tablescript \"CREATE TABLE #T\"\n*/\n\nUSE tempdb \nGO \nCHECKPOINT\n\nDECLARE @LSN NVARCHAR(25)\n\nSELECT @LSN = MAX([Current LSN])\nFROM fn_dblog(null, null) \n\n\nEXEC(N'BEGIN TRAN StartBatch\nSAVE TRAN StartBatch\nCOMMIT\n\n$(tablescript)\n(\n[4CA996AC-C7E1-48B5-B48A-E721E7A435F0] INT PRIMARY KEY DEFAULT 0,\nInRowFiller char(7000) DEFAULT ''A'',\nOffRowFiller varchar(8000) DEFAULT REPLICATE(''B'',8000),\nLOBFiller varchar(max) DEFAULT REPLICATE(cast(''C'' as varchar(max)),10000)\n)\n\n\nBEGIN TRAN InsertFirstRow\nSAVE TRAN InsertFirstRow\nCOMMIT\n\nINSERT INTO $(tablename)\nDEFAULT VALUES\n\nBEGIN TRAN Insert9Rows\nSAVE TRAN Insert9Rows\nCOMMIT\n\n\nINSERT INTO $(tablename) ([4CA996AC-C7E1-48B5-B48A-E721E7A435F0])\nSELECT TOP 9 ROW_NUMBER() OVER (ORDER BY (SELECT 0))\nFROM sys.all_columns\n\nBEGIN TRAN InsertFailure\nSAVE TRAN InsertFailure\nCOMMIT\n\n\n/*Try and Insert 10 rows, the 10th one will cause a constraint violation*/\nBEGIN TRY\nINSERT INTO $(tablename) ([4CA996AC-C7E1-48B5-B48A-E721E7A435F0])\nSELECT TOP (10) (10 + ROW_NUMBER() OVER (ORDER BY (SELECT 0))) % 20\nFROM sys.all_columns\nEND TRY\nBEGIN CATCH\nPRINT ERROR_MESSAGE()\nEND CATCH\n\nBEGIN TRAN Update10Rows\nSAVE TRAN Update10Rows\nCOMMIT\n\nUPDATE $(tablename)\nSET InRowFiller = LOWER(InRowFiller),\n OffRowFiller =LOWER(OffRowFiller),\n LOBFiller =LOWER(LOBFiller)\n\n\nBEGIN TRAN Delete10Rows\nSAVE TRAN Delete10Rows\nCOMMIT\n\nDELETE FROM $(tablename)\nBEGIN TRAN AfterDelete\nSAVE TRAN AfterDelete\nCOMMIT\n\nBEGIN TRAN EndBatch\nSAVE TRAN EndBatch\nCOMMIT')\n\n\nDECLARE @LSN_HEX NVARCHAR(25) = \n CAST(CAST(CONVERT(varbinary,SUBSTRING(@LSN, 1, 8),2) AS INT) AS VARCHAR) + ':' +\n CAST(CAST(CONVERT(varbinary,SUBSTRING(@LSN, 10, 8),2) AS INT) AS VARCHAR) + ':' +\n CAST(CAST(CONVERT(varbinary,SUBSTRING(@LSN, 19, 4),2) AS INT) AS VARCHAR) \n\nSELECT \n [Operation],\n [Context],\n [AllocUnitName],\n [Transaction Name],\n [Description]\nFROM fn_dblog(@LSN_HEX, null) AS D\nWHERE [Current LSN] > @LSN \n\nSELECT CASE\n WHEN GROUPING(Operation) = 1 THEN 'Total'\n ELSE Operation\n END AS Operation,\n Context,\n AllocUnitName,\n COALESCE(SUM([Log Record Length]), 0) AS [Size in Bytes],\n COUNT(*) AS Cnt\nFROM fn_dblog(@LSN_HEX, null) AS D\nWHERE [Current LSN] > @LSN \nGROUP BY GROUPING SETS((Operation, Context, AllocUnitName),())\n +-----------------------+--------------------+---------------------------+---------------+------+---------------+------+------------------+\n| | | | @TV | #TV | |\n+-----------------------+--------------------+---------------------------+---------------+------+---------------+------+------------------+\n| Operation | Context | AllocUnitName | Size in Bytes | Cnt | Size in Bytes | Cnt | Difference Bytes |\n+-----------------------+--------------------+---------------------------+---------------+------+---------------+------+------------------+\n| LOP_ABORT_XACT | LCX_NULL | | 52 | 1 | 52 | 1 | |\n| LOP_BEGIN_XACT | LCX_NULL | | 6056 | 50 | 6056 | 50 | |\n| LOP_COMMIT_XACT | LCX_NULL | | 2548 | 49 | 2548 | 49 | |\n| LOP_COUNT_DELTA | LCX_CLUSTERED | sys.sysallocunits.clust | 624 | 3 | 624 | 3 | |\n| LOP_COUNT_DELTA | LCX_CLUSTERED | sys.sysrowsets.clust | 208 | 1 | 208 | 1 | |\n| LOP_COUNT_DELTA | LCX_CLUSTERED | sys.sysrscols.clst | 832 | 4 | 832 | 4 | |\n| LOP_CREATE_ALLOCCHAIN | LCX_NULL | | 120 | 3 | 120 | 3 | |\n| LOP_DELETE_ROWS | LCX_INDEX_INTERIOR | Unknown Alloc Unit | 720 | 9 | 720 | 9 | |\n| LOP_DELETE_ROWS | LCX_MARK_AS_GHOST | sys.sysallocunits.clust | 444 | 3 | 444 | 3 | |\n| LOP_DELETE_ROWS | LCX_MARK_AS_GHOST | sys.sysallocunits.nc | 276 | 3 | 276 | 3 | |\n| LOP_DELETE_ROWS | LCX_MARK_AS_GHOST | sys.syscolpars.clst | 628 | 4 | 628 | 4 | |\n| LOP_DELETE_ROWS | LCX_MARK_AS_GHOST | sys.syscolpars.nc | 484 | 4 | 484 | 4 | |\n| LOP_DELETE_ROWS | LCX_MARK_AS_GHOST | sys.sysidxstats.clst | 176 | 1 | 176 | 1 | |\n| LOP_DELETE_ROWS | LCX_MARK_AS_GHOST | sys.sysidxstats.nc | 144 | 1 | 144 | 1 | |\n| LOP_DELETE_ROWS | LCX_MARK_AS_GHOST | sys.sysiscols.clst | 100 | 1 | 100 | 1 | |\n| LOP_DELETE_ROWS | LCX_MARK_AS_GHOST | sys.sysiscols.nc1 | 88 | 1 | 88 | 1 | |\n| LOP_DELETE_ROWS | LCX_MARK_AS_GHOST | sys.sysobjvalues.clst | 596 | 5 | 596 | 5 | |\n| LOP_DELETE_ROWS | LCX_MARK_AS_GHOST | sys.sysrowsets.clust | 132 | 1 | 132 | 1 | |\n| LOP_DELETE_ROWS | LCX_MARK_AS_GHOST | sys.sysrscols.clst | 528 | 4 | 528 | 4 | |\n| LOP_DELETE_ROWS | LCX_MARK_AS_GHOST | sys.sysschobjs.clst | 1040 | 6 | 1276 | 6 | 236 |\n| LOP_DELETE_ROWS | LCX_MARK_AS_GHOST | sys.sysschobjs.nc1 | 820 | 6 | 1060 | 6 | 240 |\n| LOP_DELETE_ROWS | LCX_MARK_AS_GHOST | sys.sysschobjs.nc2 | 820 | 6 | 1060 | 6 | 240 |\n| LOP_DELETE_ROWS | LCX_MARK_AS_GHOST | sys.sysschobjs.nc3 | 480 | 6 | 480 | 6 | |\n| LOP_DELETE_ROWS | LCX_MARK_AS_GHOST | sys.syssingleobjrefs.clst | 96 | 1 | | | -96 |\n| LOP_DELETE_ROWS | LCX_MARK_AS_GHOST | sys.syssingleobjrefs.nc1 | 88 | 1 | | | -88 |\n| LOP_DELETE_ROWS | LCX_MARK_AS_GHOST | Unknown Alloc Unit | 72092 | 19 | 72092 | 19 | |\n| LOP_DELETE_ROWS | LCX_TEXT_MIX | Unknown Alloc Unit | 16348 | 37 | 16348 | 37 | |\n| LOP_FORMAT_PAGE | LCX_HEAP | Unknown Alloc Unit | 1596 | 19 | 1596 | 19 | |\n| LOP_FORMAT_PAGE | LCX_IAM | Unknown Alloc Unit | 252 | 3 | 252 | 3 | |\n| LOP_FORMAT_PAGE | LCX_INDEX_INTERIOR | Unknown Alloc Unit | 84 | 1 | 84 | 1 | |\n| LOP_FORMAT_PAGE | LCX_TEXT_MIX | Unknown Alloc Unit | 4788 | 57 | 4788 | 57 | |\n| LOP_HOBT_DDL | LCX_NULL | | 108 | 3 | 108 | 3 | |\n| LOP_HOBT_DELTA | LCX_NULL | | 9600 | 150 | 9600 | 150 | |\n| LOP_INSERT_ROWS | LCX_CLUSTERED | sys.sysallocunits.clust | 456 | 3 | 456 | 3 | |\n| LOP_INSERT_ROWS | LCX_CLUSTERED | sys.syscolpars.clst | 644 | 4 | 644 | 4 | |\n| LOP_INSERT_ROWS | LCX_CLUSTERED | sys.sysidxstats.clst | 180 | 1 | 180 | 1 | |\n| LOP_INSERT_ROWS | LCX_CLUSTERED | sys.sysiscols.clst | 104 | 1 | 104 | 1 | |\n| LOP_INSERT_ROWS | LCX_CLUSTERED | sys.sysobjvalues.clst | 616 | 5 | 616 | 5 | |\n| LOP_INSERT_ROWS | LCX_CLUSTERED | sys.sysrowsets.clust | 136 | 1 | 136 | 1 | |\n| LOP_INSERT_ROWS | LCX_CLUSTERED | sys.sysrscols.clst | 544 | 4 | 544 | 4 | |\n| LOP_INSERT_ROWS | LCX_CLUSTERED | sys.sysschobjs.clst | 1064 | 6 | 1300 | 6 | 236 |\n| LOP_INSERT_ROWS | LCX_CLUSTERED | sys.syssingleobjrefs.clst | 100 | 1 | | | -100 |\n| LOP_INSERT_ROWS | LCX_CLUSTERED | Unknown Alloc Unit | 135888 | 19 | 135888 | 19 | |\n| LOP_INSERT_ROWS | LCX_INDEX_INTERIOR | Unknown Alloc Unit | 1596 | 19 | 1596 | 19 | |\n| LOP_INSERT_ROWS | LCX_INDEX_LEAF | sys.sysallocunits.nc | 288 | 3 | 288 | 3 | |\n| LOP_INSERT_ROWS | LCX_INDEX_LEAF | sys.syscolpars.nc | 500 | 4 | 500 | 4 | |\n| LOP_INSERT_ROWS | LCX_INDEX_LEAF | sys.sysidxstats.nc | 148 | 1 | 148 | 1 | |\n| LOP_INSERT_ROWS | LCX_INDEX_LEAF | sys.sysiscols.nc1 | 92 | 1 | 92 | 1 | |\n| LOP_INSERT_ROWS | LCX_INDEX_LEAF | sys.sysschobjs.nc1 | 844 | 6 | 1084 | 6 | 240 |\n| LOP_INSERT_ROWS | LCX_INDEX_LEAF | sys.sysschobjs.nc2 | 844 | 6 | 1084 | 6 | 240 |\n| LOP_INSERT_ROWS | LCX_INDEX_LEAF | sys.sysschobjs.nc3 | 504 | 6 | 504 | 6 | |\n| LOP_INSERT_ROWS | LCX_INDEX_LEAF | sys.syssingleobjrefs.nc1 | 92 | 1 | | | -92 |\n| LOP_INSERT_ROWS | LCX_TEXT_MIX | Unknown Alloc Unit | 5112 | 71 | 5112 | 71 | |\n| LOP_MARK_SAVEPOINT | LCX_NULL | | 508 | 8 | 508 | 8 | |\n| LOP_MODIFY_COLUMNS | LCX_CLUSTERED | Unknown Alloc Unit | 1560 | 10 | 1560 | 10 | |\n| LOP_MODIFY_HEADER | LCX_HEAP | Unknown Alloc Unit | 3780 | 45 | 3780 | 45 | |\n| LOP_MODIFY_ROW | LCX_CLUSTERED | sys.syscolpars.clst | 384 | 4 | 384 | 4 | |\n| LOP_MODIFY_ROW | LCX_CLUSTERED | sys.sysidxstats.clst | 100 | 1 | 100 | 1 | |\n| LOP_MODIFY_ROW | LCX_CLUSTERED | sys.sysrowsets.clust | 92 | 1 | 92 | 1 | |\n| LOP_MODIFY_ROW | LCX_CLUSTERED | sys.sysschobjs.clst | 1144 | 13 | 1144 | 13 | |\n| LOP_MODIFY_ROW | LCX_IAM | Unknown Alloc Unit | 4224 | 48 | 4224 | 48 | |\n| LOP_MODIFY_ROW | LCX_PFS | Unknown Alloc Unit | 13632 | 169 | 13632 | 169 | |\n| LOP_MODIFY_ROW | LCX_TEXT_MIX | Unknown Alloc Unit | 108640 | 120 | 108640 | 120 | |\n| LOP_ROOT_CHANGE | LCX_CLUSTERED | sys.sysallocunits.clust | 960 | 10 | 960 | 10 | |\n| LOP_SET_BITS | LCX_GAM | Unknown Alloc Unit | 1200 | 20 | 1200 | 20 | |\n| LOP_SET_BITS | LCX_IAM | Unknown Alloc Unit | 1080 | 18 | 1080 | 18 | |\n| LOP_SET_BITS | LCX_SGAM | Unknown Alloc Unit | 120 | 2 | 120 | 2 | |\n| LOP_SHRINK_NOOP | LCX_NULL | | | | 32 | 1 | 32 |\n+-----------------------+--------------------+---------------------------+---------------+------+---------------+------+------------------+\n| Total | | | 410144 | 1095 | 411232 | 1092 | 1088 |\n+-----------------------+--------------------+---------------------------+---------------+------+---------------+------+------------------+\n" }, { "answer_id": 32400833, "author": "Teoman shipahi", "author_id": 929902, "author_profile": "https://Stackoverflow.com/users/929902", "pm_score": 3, "selected": false, "text": "SELECT session_id,\ndatabase_id,\nuser_objects_alloc_page_count\nFROM sys.dm_db_session_space_usage\nWHERE session_id > 50 ;\n CREATE TABLE #TempTable ( ID INT ) ;\nINSERT INTO #TempTable ( ID )\nVALUES ( 1 ) ;\nGO\nSELECT session_id,\ndatabase_id,\nuser_objects_alloc_page_count\nFROM sys.dm_db_session_space_usage\nWHERE session_id > 50 ;\n DECLARE @TempTable TABLE ( ID INT ) ;\nINSERT INTO @TempTable ( ID )\nVALUES ( 1 ) ;\nGO\nSELECT session_id,\ndatabase_id,\nuser_objects_alloc_page_count\nFROM sys.dm_db_session_space_usage\nWHERE session_id > 50 ;\n" }, { "answer_id": 58875211, "author": "Litisqe Kumar", "author_id": 5047627, "author_profile": "https://Stackoverflow.com/users/5047627", "pm_score": 2, "selected": false, "text": "Temporary Tables (##temp/#temp) Table Variables (@table) Table variable (@table) memory Temporary table (##temp/#temp) tempdb database Table variables transactions, logging or locking @table faster then #temp Temporary table Table variables Temporary tables Temporary tables CREATE INDEXes Table variables CREATE INDEX Primary Key or Unique Constraint" }, { "answer_id": 70033739, "author": "satheesh", "author_id": 17242923, "author_profile": "https://Stackoverflow.com/users/17242923", "pm_score": 1, "selected": false, "text": "Select Dept.DeptName, Dept.DeptId, COUNT(*) as TotalEmployees\ninto #TempEmpCount\nfrom Tbl_EmpDetails Emp\njoin Tbl_Dept Dept\non Emp.DeptId = Dept.DeptId\ngroup by DeptName, Dept.DeptId\n Declare @tblEmployeeCount table\n(DeptName nvarchar(20),DeptId int, TotalEmployees int)\nInsert @tblEmployeeCount\nSelect DeptName, Tbl_Dept.DeptId, COUNT(*) as TotalEmployees\nfrom Tbl_EmpDetails\njoin Tbl_Dept\non Tbl_EmpDetails.DeptId = Tbl_Dept.DeptId\ngroup by DeptName, Tbl_Dept.DeptId\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/27894", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1219/" ]
27,899
<p>Is there a way to make S3 default to an index.html page? E.g.: My bucket object listing:</p> <pre><code>/index.html /favicon.ico /images/logo.gif </code></pre> <p>A call to <strong>www.example.com/<em>index.html</em></strong> works great! But if one were to call <strong>www.example.com/</strong> we'd either get a 403 or a REST object listing XML document depending on how bucket-level ACL was configured.</p> <p>So, the question: Is there a way to have index.html functionality with content hosted on S3?</p>
[ { "answer_id": 5040105, "author": "Alex Jasmin", "author_id": 162407, "author_profile": "https://Stackoverflow.com/users/162407", "pm_score": 6, "selected": true, "text": "index.html aws s3 website $MY_BUCKET_NAME --index-document index.html\n" }, { "answer_id": 24377823, "author": "fiatjaf", "author_id": 973380, "author_profile": "https://Stackoverflow.com/users/973380", "pm_score": 6, "selected": false, "text": "<bucket_name>.s3-us-west-2.amazonaws.com <bucket_name>.s3-website-us-west-2.amazonaws.com AccessDenied Properties Static Website Hosting" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/27899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2961/" ]
27,910
<p>The <a href="http://doi.org/" rel="noreferrer">DOI</a> system places basically no useful limitations on what constitutes <a href="http://doi.org/handbook_2000/enumeration.html#2.2" rel="noreferrer">a reasonable identifier</a>. However, being able to pull DOIs out of PDFs, web pages, etc. is quite useful for citation information, etc.</p> <p>Is there a reliable way to identify a DOI in a block of text without assuming the 'doi:' prefix? (any language acceptable, regexes preferred, and avoiding false positives a must)</p>
[ { "answer_id": 29639, "author": "Silas Snider", "author_id": 2933, "author_profile": "https://Stackoverflow.com/users/2933", "pm_score": 1, "selected": false, "text": "/(10\\.\\d+\\/\\d+)/\n http://hdl.handle.net/<doi>\n http://dx.doi.org/<doi>\n" }, { "answer_id": 1876427, "author": "rgcb", "author_id": 8178, "author_profile": "https://Stackoverflow.com/users/8178", "pm_score": 2, "selected": false, "text": "(10.(\\d)+/(\\S)+)\n (10.(\\d)+/([^(\\s\\>\\\"\\<)])+)\n" }, { "answer_id": 10300246, "author": "Alix Axel", "author_id": 89771, "author_profile": "https://Stackoverflow.com/users/89771", "pm_score": 2, "selected": false, "text": "(10[.][0-9]{4,}[^\\s\"/<>]*/[^\\s\"<>]+)\n 10.1007/978-3-642-28108-2_19 10.1007.10/978-3-642-28108-2_19 10.1016/S0735-1097(98)00347-7 10.1579/0044-7447(2006)35\\[89:RDUICP\\]2.0.CO;2 <geo coords=\"10.4515260,51.1656910\"></geo>" }, { "answer_id": 10324802, "author": "Alix Axel", "author_id": 89771, "author_profile": "https://Stackoverflow.com/users/89771", "pm_score": 7, "selected": true, "text": "\\b 10. $pattern = '\\b(10[.]';\n $pattern = '\\b(10[.][0-9]{4,}';\n $pattern = '\\b(10[.][0-9]{4,}(?:[.][0-9]+)*'; 10.1000.123456 10.1000/123456 $pattern = '\\b(10[.][0-9]{4,}(?:[.][0-9]+)*/'; [0-9a-zA-Z] .-()/:- 10.1016.12.31/nature.S0735-1097(98)2000/12/31/34:7-7 \\S [[:graph:]] $pattern = '\\b(10[.][0-9]{4,}(?:[.][0-9]+)*/\\S+'; // or $pattern = '\\b(10[.][0-9]{4,}(?:[.][0-9]+)*/[[:graph:]]+'; [[:graph:]] [[:punct:]] \"'&<> $pattern = '\\b(10[.][0-9]{4,}(?:[.][0-9]+)*/(?:(?![\"&\\'<>])\\S)+'; // or $pattern = '\\b(10[.][0-9]{4,}(?:[.][0-9]+)*/(?:(?![\"&\\'<>])[[:graph:]])+'; & [\"'] [<>] 10.1016.12.31/nature.S0735-1097(98)2000/12/31/34:7-7 $pattern = '\\b(10[.][0-9]{4,}(?:[.][0-9]+)*/(?:(?![\"&\\'<>])\\S)+)\\b'; // or $pattern = '\\b(10[.][0-9]{4,}(?:[.][0-9]+)*/(?:(?![\"&\\'<>])[[:graph:]])+)\\b';" }, { "answer_id": 24246270, "author": "hobwell", "author_id": 1781344, "author_profile": "https://Stackoverflow.com/users/1781344", "pm_score": 2, "selected": false, "text": "\\b10\\.(\\d+\\.*)+[\\/](([^\\s\\.])+\\.*)+\\b" }, { "answer_id": 48524047, "author": "Katrin Leinweber", "author_id": 4341322, "author_profile": "https://Stackoverflow.com/users/4341322", "pm_score": 4, "selected": false, "text": "/^10.\\d{4,9}/[-._;()/:A-Z0-9]+$/i\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/27910", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2963/" ]
27,921
<p>Story: The user uploads an image that will be added to a photo gallery. As part of the upload process, we need to A) store the image on the web server's hard drive and B) store a thumbnail of the image on the web server's hard drive.</p> <p>"Best" here is defined as </p> <ul> <li>Relatively easy to implement, understand, and maintain</li> <li>Results in a thumbnail of reasonable quality</li> </ul> <p>Performance and high-quality thumbnails are secondary.</p>
[ { "answer_id": 27938, "author": "Huppie", "author_id": 1830, "author_profile": "https://Stackoverflow.com/users/1830", "pm_score": 5, "selected": true, "text": "// Example in C#, should be quite alike in ASP.NET\n// Assuming filename as the uploaded file\nusing ( Image bigImage = new Bitmap( filename ) )\n{\n // Algorithm simplified for purpose of example.\n int height = bigImage.Height / 10;\n int width = bigImage.Width / 10;\n\n // Now create a thumbnail\n using ( Image smallImage = image.GetThumbnailImage( width, \n height,\n new Image.GetThumbnailImageAbort(Abort), IntPtr.Zero) )\n {\n smallImage.Save(\"thumbnail.jpg\", ImageFormat.Jpeg);\n }\n}\n" }, { "answer_id": 27939, "author": "chrissie1", "author_id": 2936, "author_profile": "https://Stackoverflow.com/users/2936", "pm_score": 2, "selected": false, "text": "Imports System.Runtime.CompilerServices\n\nNamespace Extensions\n ''' <summary>\n ''' Extensions for the Image class.\n ''' </summary>\n ''' <remarks>Several usefull extensions for the image class.</remarks>\n Public Module ImageExtensions\n\n ''' <summary>\n ''' Extends the image class so that it is easier to get a thumbnail from an image\n ''' </summary>\n ''' <param name=\"Input\">Th image that is inputted, not really a parameter</param>\n ''' <param name=\"MaximumSize\">The maximumsize the thumbnail must be if keepaspectratio is set to true then the highest number of width or height is used and the other is calculated accordingly. </param>\n ''' <param name=\"KeepAspectRatio\">If set false width and height will be the same else the highest number of width or height is used and the other is calculated accordingly.</param>\n ''' <returns>A thumbnail as image.</returns>\n ''' <remarks>\n ''' <example>Can be used as such. \n ''' <code>\n ''' Dim _NewImage as Image \n ''' Dim _Graphics As Graphics\n ''' _Image = New Bitmap(100, 100)\n ''' _Graphics = Graphics.FromImage(_Image)\n ''' _Graphics.FillRectangle(Brushes.Blue, New Rectangle(0, 0, 100, 100))\n ''' _Graphics.DrawLine(Pens.Black, 10, 0, 10, 100)\n ''' Assert.IsNotNull(_Image)\n ''' _NewImage = _Image.ToThumbnail(10)\n ''' </code>\n ''' </example>\n ''' </remarks>\n <Extension()> _\n Public Function ToThumbnail(ByVal Input As Image, ByVal MaximumSize As Integer, Optional ByVal KeepAspectRatio As Boolean = True) As Image\n Dim ReturnImage As Image\n Dim _Callback As Image.GetThumbnailImageAbort = Nothing\n Dim _OriginalHeight As Double\n Dim _OriginalWidth As Double\n Dim _NewHeight As Double\n Dim _NewWidth As Double\n Dim _NormalImage As Image\n Dim _Graphics As Graphics\n\n _NormalImage = New Bitmap(Input.Width, Input.Height)\n _Graphics = Graphics.FromImage(_NormalImage)\n _Graphics.DrawImage(Input, 0, 0, Input.Width, Input.Height)\n _OriginalHeight = _NormalImage.Height\n _OriginalWidth = _NormalImage.Width\n If KeepAspectRatio = True Then\n If _OriginalHeight > _OriginalWidth Then\n If _OriginalHeight > MaximumSize Then\n _NewHeight = MaximumSize\n _NewWidth = _OriginalWidth / _OriginalHeight * MaximumSize\n Else\n _NewHeight = _OriginalHeight\n _NewWidth = _OriginalWidth\n End If\n Else\n If _OriginalWidth > MaximumSize Then\n _NewWidth = MaximumSize\n _NewHeight = _OriginalHeight / _OriginalWidth * MaximumSize\n Else\n _NewHeight = _OriginalHeight\n _NewWidth = _OriginalWidth\n End If\n End If\n Else\n _NewHeight = MaximumSize\n _NewWidth = MaximumSize\n End If\n ReturnImage = _\n _NormalImage.GetThumbnailImage(Convert.ToInt32(_NewWidth), Convert.ToInt32(_NewHeight), _Callback, _\n IntPtr.Zero)\n _NormalImage.Dispose()\n _NormalImage = Nothing\n _Graphics.Dispose()\n _Graphics = Nothing\n _Callback = Nothing\n Return ReturnImage\n End Function\n End Module\nEnd Namespace\n" }, { "answer_id": 27940, "author": "Mark Ingram", "author_id": 986, "author_profile": "https://Stackoverflow.com/users/986", "pm_score": 0, "selected": false, "text": "public bool ThumbnailCallback()\n{\n return false;\n}\n\npublic void Example_GetThumb(PaintEventArgs e)\n{\n Image.GetThumbnailImageAbort myCallback = new Image.GetThumbnailImageAbort(ThumbnailCallback);\n Bitmap myBitmap = new Bitmap(\"Climber.jpg\");\n Image myThumbnail = myBitmap.GetThumbnailImage(40, 40, myCallback, IntPtr.Zero);\n e.Graphics.DrawImage(myThumbnail, 150, 75);\n}\n" }, { "answer_id": 27950, "author": "Sean Chambers", "author_id": 2993, "author_profile": "https://Stackoverflow.com/users/2993", "pm_score": 5, "selected": false, "text": "Image photo; // your uploaded image\n\nBitmap bmp = new Bitmap(resizeToWidth, resizeToHeight);\ngraphic = Graphics.FromImage(bmp);\ngraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;\ngraphic.SmoothingMode = SmoothingMode.HighQuality;\ngraphic.PixelOffsetMode = PixelOffsetMode.HighQuality;\ngraphic.CompositingQuality = CompositingQuality.HighQuality;\ngraphic.DrawImage(photo, 0, 0, resizeToWidth, resizeToHeight);\nimageToSave = bmp;\n" }, { "answer_id": 266640, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "System.Drawing.Imaging.ImageCodecInfo[] info = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders();\nSystem.Drawing.Imaging.EncoderParameters encoderParameters;\nencoderParameters = new System.Drawing.Imaging.EncoderParameters(1);\nencoderParameters.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 90L);\n\nthumb.Save(ms, info[1], encoderParameters);\n" }, { "answer_id": 944282, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "using System.Drawing;\nusing System.Drawing.Drawing2D;\nusing System.IO;\n\npublic static void ResizeImage(string FileNameInput, string FileNameOutput, double ResizeHeight, double ResizeWidth, ImageFormat OutputFormat)\n{\n using (System.Drawing.Image photo = new Bitmap(FileNameInput))\n {\n double aspectRatio = (double)photo.Width / photo.Height;\n double boxRatio = ResizeWidth / ResizeHeight;\n double scaleFactor = 0;\n\n if (photo.Width < ResizeWidth && photo.Height < ResizeHeight)\n {\n // keep the image the same size since it is already smaller than our max width/height\n scaleFactor = 1.0;\n }\n else\n {\n if (boxRatio > aspectRatio)\n scaleFactor = ResizeHeight / photo.Height;\n else\n scaleFactor = ResizeWidth / photo.Width;\n }\n\n int newWidth = (int)(photo.Width * scaleFactor);\n int newHeight = (int)(photo.Height * scaleFactor);\n\n using (Bitmap bmp = new Bitmap(newWidth, newHeight))\n {\n using (Graphics g = Graphics.FromImage(bmp))\n {\n g.InterpolationMode = InterpolationMode.HighQualityBicubic;\n g.SmoothingMode = SmoothingMode.HighQuality;\n g.CompositingQuality = CompositingQuality.HighQuality;\n g.PixelOffsetMode = PixelOffsetMode.HighQuality;\n\n g.DrawImage(photo, 0, 0, newWidth, newHeight);\n\n if (ImageFormat.Png.Equals(OutputFormat))\n {\n bmp.Save(FileNameOutput, OutputFormat);\n }\n else if (ImageFormat.Jpeg.Equals(OutputFormat))\n {\n ImageCodecInfo[] info = ImageCodecInfo.GetImageEncoders();\n EncoderParameters encoderParameters;\n using (encoderParameters = new System.Drawing.Imaging.EncoderParameters(1))\n {\n // use jpeg info[1] and set quality to 90\n encoderParameters.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 90L);\n bmp.Save(FileNameOutput, info[1], encoderParameters);\n }\n }\n }\n }\n }\n}\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/27921", "https://Stackoverflow.com", "https://Stackoverflow.com/users/308/" ]
27,928
<p>How do I calculate the distance between two points specified by latitude and longitude?</p> <p>For clarification, I'd like the distance in kilometers; the points use the WGS84 system and I'd like to understand the relative accuracies of the approaches available.</p>
[ { "answer_id": 27943, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 11, "selected": true, "text": "function getDistanceFromLatLonInKm(lat1,lon1,lat2,lon2) {\n var R = 6371; // Radius of the earth in km\n var dLat = deg2rad(lat2-lat1); // deg2rad below\n var dLon = deg2rad(lon2-lon1); \n var a = \n Math.sin(dLat/2) * Math.sin(dLat/2) +\n Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * \n Math.sin(dLon/2) * Math.sin(dLon/2)\n ; \n var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); \n var d = R * c; // Distance in km\n return d;\n}\n\nfunction deg2rad(deg) {\n return deg * (Math.PI/180)\n}\n" }, { "answer_id": 215849, "author": "jaircazarin-old-account", "author_id": 20915, "author_profile": "https://Stackoverflow.com/users/20915", "pm_score": 6, "selected": false, "text": "static class DistanceAlgorithm\n{\n const double PIx = 3.141592653589793;\n const double RADIUS = 6378.16;\n\n /// <summary>\n /// Convert degrees to Radians\n /// </summary>\n /// <param name=\"x\">Degrees</param>\n /// <returns>The equivalent in radians</returns>\n public static double Radians(double x)\n {\n return x * PIx / 180;\n }\n\n /// <summary>\n /// Calculate the distance between two places.\n /// </summary>\n /// <param name=\"lon1\"></param>\n /// <param name=\"lat1\"></param>\n /// <param name=\"lon2\"></param>\n /// <param name=\"lat2\"></param>\n /// <returns></returns>\n public static double DistanceBetweenPlaces(\n double lon1,\n double lat1,\n double lon2,\n double lat2)\n {\n double dlon = Radians(lon2 - lon1);\n double dlat = Radians(lat2 - lat1);\n\n double a = (Math.Sin(dlat / 2) * Math.Sin(dlat / 2)) + Math.Cos(Radians(lat1)) * Math.Cos(Radians(lat2)) * (Math.Sin(dlon / 2) * Math.Sin(dlon / 2));\n double angle = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));\n return angle * RADIUS;\n }\n\n}\n" }, { "answer_id": 4377364, "author": "Stephen Watson", "author_id": 485514, "author_profile": "https://Stackoverflow.com/users/485514", "pm_score": 5, "selected": false, "text": "const double PIx = 3.141592653589793;\nconst double RADIO = 6371; // Mean radius of Earth in Km\n\ndouble convertToRadians(double val) {\n\n return val * PIx / 180;\n}\n\n-(double)kilometresBetweenPlace1:(CLLocationCoordinate2D) place1 andPlace2:(CLLocationCoordinate2D) place2 {\n\n double dlon = convertToRadians(place2.longitude - place1.longitude);\n double dlat = convertToRadians(place2.latitude - place1.latitude);\n\n double a = ( pow(sin(dlat / 2), 2) + cos(convertToRadians(place1.latitude))) * cos(convertToRadians(place2.latitude)) * pow(sin(dlon / 2), 2);\n double angle = 2 * asin(sqrt(a));\n\n return angle * RADIO;\n}\n -(double)kilometresBetweenPlace1:(CLLocationCoordinate2D) place1 andPlace2:(CLLocationCoordinate2D) place2 {\n\n MKMapPoint start, finish;\n\n\n start = MKMapPointForCoordinate(place1);\n finish = MKMapPointForCoordinate(place2);\n\n return MKMetersBetweenMapPoints(start, finish) / 1000;\n}\n" }, { "answer_id": 9676337, "author": "conualfy", "author_id": 703474, "author_profile": "https://Stackoverflow.com/users/703474", "pm_score": 5, "selected": false, "text": "SELECT denumire, (6371 * acos( cos( radians(45.20327) ) * cos( radians( coord_lat ) ) * cos( radians( 23.7806 ) - radians(coord_long) ) + sin( radians(45.20327) ) * sin( radians(coord_lat) ) )) AS distanta \nFROM obiective \nWHERE coord_lat<>'' \n AND coord_long<>'' \nHAVING distanta<50 \nORDER BY distanta desc\n" }, { "answer_id": 11178145, "author": "tony gil", "author_id": 1166727, "author_profile": "https://Stackoverflow.com/users/1166727", "pm_score": 5, "selected": false, "text": "<?php\nfunction distance($lat1, $lon1, $lat2, $lon2) {\n\n $pi80 = M_PI / 180;\n $lat1 *= $pi80;\n $lon1 *= $pi80;\n $lat2 *= $pi80;\n $lon2 *= $pi80;\n\n $r = 6372.797; // mean radius of Earth in km\n $dlat = $lat2 - $lat1;\n $dlon = $lon2 - $lon1;\n $a = sin($dlat / 2) * sin($dlat / 2) + cos($lat1) * cos($lat2) * sin($dlon / 2) * sin($dlon / 2);\n $c = 2 * atan2(sqrt($a), sqrt(1 - $a));\n $km = $r * $c;\n\n //echo '<br/>'.$km;\n return $km;\n}\n?>\n" }, { "answer_id": 12600225, "author": "whostolebenfrog", "author_id": 599936, "author_profile": "https://Stackoverflow.com/users/599936", "pm_score": 6, "selected": false, "text": "public final static double AVERAGE_RADIUS_OF_EARTH_KM = 6371;\npublic int calculateDistanceInKilometer(double userLat, double userLng,\n double venueLat, double venueLng) {\n\n double latDistance = Math.toRadians(userLat - venueLat);\n double lngDistance = Math.toRadians(userLng - venueLng);\n\n double a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2)\n + Math.cos(Math.toRadians(userLat)) * Math.cos(Math.toRadians(venueLat))\n * Math.sin(lngDistance / 2) * Math.sin(lngDistance / 2);\n\n double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));\n\n return (int) (Math.round(AVERAGE_RADIUS_OF_EARTH_KM * c));\n}\n" }, { "answer_id": 12930877, "author": "bherto39", "author_id": 1531382, "author_profile": "https://Stackoverflow.com/users/1531382", "pm_score": 0, "selected": false, "text": "function getApproximateDistanceUnits(point1, point2) {\n\n var xs = 0;\n var ys = 0;\n\n xs = point2.getX() - point1.getX();\n xs = xs * xs;\n\n ys = point2.getY() - point1.getY();\n ys = ys * ys;\n\n return Math.sqrt(xs + ys);\n}\n function isMapPlacemarkInRadius(point1, point2, radi) {\n if (point1 && point2) {\n return getApproximateDistanceUnits(point1, point2) <= radi;\n } else {\n return 0;\n }\n}\n $$.getPoint = function(lati, longi) {\n var location = {\n x: 0,\n y: 0,\n getX: function() { return location.x; },\n getY: function() { return location.y; }\n };\n location.x = lati;\n location.y = longi;\n\n return location;\n };\n //put it on the map if within the range of a specified radi assuming 100,000,000 units\n var iconpoint = Map.getPoint(pp.latitude, pp.longitude);\n var centerpoint = Map.getPoint(Settings.CenterLatitude, Settings.CenterLongitude);\n\n //approx ~200 units to show only half of the globe from the default center radius\n if (isMapPlacemarkInRadius(centerpoint, iconpoint, 120)) {\n addPlacemark(pp.latitude, pp.longitude, pp.name);\n }\n else {\n otherSidePlacemarks.push({\n latitude: pp.latitude,\n longitude: pp.longitude,\n name: pp.name\n });\n\n }\n" }, { "answer_id": 14329945, "author": "ayalcinkaya", "author_id": 1589731, "author_profile": "https://Stackoverflow.com/users/1589731", "pm_score": 2, "selected": false, "text": " function distance($lat1, $lon1, $lat2, $lon2, $unit) {\n\n $theta = $lon1 - $lon2;\n $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));\n $dist = acos($dist);\n $dist = rad2deg($dist);\n $miles = $dist * 60 * 1.1515;\n $unit = strtoupper($unit);\n\n if ($unit == \"K\") {\n return ($miles * 1.609344);\n } else if ($unit == \"N\") {\n return ($miles * 0.8684);\n } else {\n return $miles;\n }\n }\n" }, { "answer_id": 15759519, "author": "Taiseer Joudeh", "author_id": 3625265, "author_profile": "https://Stackoverflow.com/users/3625265", "pm_score": 2, "selected": false, "text": "Public Enum DistanceType\n Miles\n KiloMeters\nEnd Enum\n\nPublic Structure Position\n Public Latitude As Double\n Public Longitude As Double\nEnd Structure\n\nPublic Class Haversine\n\n Public Function Distance(Pos1 As Position,\n Pos2 As Position,\n DistType As DistanceType) As Double\n\n Dim R As Double = If((DistType = DistanceType.Miles), 3960, 6371)\n\n Dim dLat As Double = Me.toRadian(Pos2.Latitude - Pos1.Latitude)\n\n Dim dLon As Double = Me.toRadian(Pos2.Longitude - Pos1.Longitude)\n\n Dim a As Double = Math.Sin(dLat / 2) * Math.Sin(dLat / 2) + Math.Cos(Me.toRadian(Pos1.Latitude)) * Math.Cos(Me.toRadian(Pos2.Latitude)) * Math.Sin(dLon / 2) * Math.Sin(dLon / 2)\n\n Dim c As Double = 2 * Math.Asin(Math.Min(1, Math.Sqrt(a)))\n\n Dim result As Double = R * c\n\n Return result\n\n End Function\n\n Private Function toRadian(val As Double) As Double\n\n Return (Math.PI / 180) * val\n\n End Function\n\nEnd Class\n" }, { "answer_id": 17078193, "author": "Kache", "author_id": 234593, "author_profile": "https://Stackoverflow.com/users/234593", "pm_score": 2, "selected": false, "text": "include Math\nearth_radius_mi = 3959\nradians = lambda { |deg| deg * PI / 180 }\ncoord_radians = lambda { |c| { :lat => radians[c[:lat]], :lng => radians[c[:lng]] } }\n\n# from/to = { :lat => (latitude_in_degrees), :lng => (longitude_in_degrees) }\ndef haversine_distance(from, to)\n from, to = coord_radians[from], coord_radians[to]\n cosines_product = cos(to[:lat]) * cos(from[:lat]) * cos(from[:lng] - to[:lng])\n sines_product = sin(to[:lat]) * sin(from[:lat])\n return earth_radius_mi * acos(cosines_product + sines_product)\nend\n" }, { "answer_id": 17315408, "author": "Andre Cytryn", "author_id": 1165337, "author_profile": "https://Stackoverflow.com/users/1165337", "pm_score": 3, "selected": false, "text": "CLLocation *location1 = [[CLLocation alloc] initWithLatitude:latitude1 longitude:longitude1];\nCLLocation *location2 = [[CLLocation alloc] initWithLatitude:latitude2 longitude:longitude2];\n[self distanceInMetersFromLocation:location1 toLocation:location2]\n\n- (int)distanceInMetersFromLocation:(CLLocation*)location1 toLocation:(CLLocation*)location2 {\n CLLocationDistance distanceInMeters = [location1 distanceFromLocation:location2];\n return distanceInMeters;\n}\n" }, { "answer_id": 19772119, "author": "Arturo Hernandez", "author_id": 937703, "author_profile": "https://Stackoverflow.com/users/937703", "pm_score": 4, "selected": false, "text": "HalfPi = 1.5707963;\nR = 3956; /* the radius gives you the measurement unit*/\n\na = HalfPi - latoriginrad;\nb = HalfPi - latdestrad;\nu = a * a + b * b;\nv = - 2 * a * b * cos(longdestrad - longoriginrad);\nc = sqrt(abs(u + v));\nreturn R * c;\n" }, { "answer_id": 19852967, "author": "MPaulo", "author_id": 1105558, "author_profile": "https://Stackoverflow.com/users/1105558", "pm_score": 2, "selected": false, "text": "function getDistanceFromLatLonInKm(lat1,lon1,lat2,lon2,units) {\n var R = 6371; // Radius of the earth in km\n var dLat = deg2rad(lat2-lat1); // deg2rad below\n var dLon = deg2rad(lon2-lon1); \n var a = \n Math.sin(dLat/2) * Math.sin(dLat/2) +\n Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * \n Math.sin(dLon/2) * Math.sin(dLon/2)\n ; \n var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); \n var d = R * c; \n var miles = d / 1.609344; \n\nif ( units == 'km' ) { \nreturn d; \n } else {\nreturn miles;\n}}\n" }, { "answer_id": 21623206, "author": "Salvador Dali", "author_id": 1090562, "author_profile": "https://Stackoverflow.com/users/1090562", "pm_score": 9, "selected": false, "text": "function distance(lat1, lon1, lat2, lon2) {\n var p = 0.017453292519943295; // Math.PI / 180\n var c = Math.cos;\n var a = 0.5 - c((lat2 - lat1) * p)/2 + \n c(lat1 * p) * c(lat2 * p) * \n (1 - c((lon2 - lon1) * p))/2;\n\n return 12742 * Math.asin(Math.sqrt(a)); // 2 * R; R = 6371 km\n}\n from math import cos, asin, sqrt, pi\n\ndef distance(lat1, lon1, lat2, lon2):\n p = pi/180\n a = 0.5 - cos((lat2-lat1)*p)/2 + cos(lat1*p) * cos(lat2*p) * (1-cos((lon2-lon1)*p))/2\n return 12742 * asin(sqrt(a)) #2*R*asin...\n" }, { "answer_id": 21739328, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "public static double distanceLatLong2(double lat1, double lng1, double lat2, double lng2) \n{\n double earthRadius = 6371.0d; // KM: use mile here if you want mile result\n\n double dLat = toRadian(lat2 - lat1);\n double dLng = toRadian(lng2 - lng1);\n\n double a = Math.pow(Math.sin(dLat/2), 2) + \n Math.cos(toRadian(lat1)) * Math.cos(toRadian(lat2)) * \n Math.pow(Math.sin(dLng/2), 2);\n\n double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));\n\n return earthRadius * c; // returns result kilometers\n}\n\npublic static double toRadian(double degrees) \n{\n return (degrees * Math.PI) / 180.0d;\n}\n" }, { "answer_id": 23095329, "author": "Jaap", "author_id": 2204410, "author_profile": "https://Stackoverflow.com/users/2204410", "pm_score": 5, "selected": false, "text": "distm geosphere distm(p1, p2, fun = distHaversine)\n p1 = longitude/latitude for point(s)\np2 = longitude/latitude for point(s)\n# type of distance calculation\nfun = distCosine / distHaversine / distVincentySphere / distVincentyEllipsoid \n geosphere distm(p1, p2, fun = distVincentyEllipsoid)\n geosphere R hav.dist <- function(long1, lat1, long2, lat2) {\n R <- 6371\n diff.long <- (long2 - long1)\n diff.lat <- (lat2 - lat1)\n a <- sin(diff.lat/2)^2 + cos(lat1) * cos(lat2) * sin(diff.long/2)^2\n b <- 2 * asin(pmin(1, sqrt(a))) \n d = R * b\n return(d)\n}\n" }, { "answer_id": 23907104, "author": "shanavascet", "author_id": 2286174, "author_profile": "https://Stackoverflow.com/users/2286174", "pm_score": 2, "selected": false, "text": "POINT(LONG,LAT) CREATE FUNCTION `distance`(a POINT, b POINT)\n RETURNS double\n DETERMINISTIC\nBEGIN\n\nRETURN\n\nGLength( LineString(( PointFromWKB(a)), (PointFromWKB(b)))) * 100000; -- To Make the distance in meters\n\nEND;\n" }, { "answer_id": 24058134, "author": "borchvm", "author_id": 3115822, "author_profile": "https://Stackoverflow.com/users/3115822", "pm_score": 0, "selected": false, "text": "//JAVA\n public Double getDistanceBetweenTwoPoints(Double latitude1, Double longitude1, Double latitude2, Double longitude2) {\n final int RADIUS_EARTH = 6371;\n\n double dLat = getRad(latitude2 - latitude1);\n double dLong = getRad(longitude2 - longitude1);\n\n double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(getRad(latitude1)) * Math.cos(getRad(latitude2)) * Math.sin(dLong / 2) * Math.sin(dLong / 2);\n double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));\n return (RADIUS_EARTH * c) * 1000;\n }\n\n private Double getRad(Double x) {\n return x * Math.PI / 180;\n }\n" }, { "answer_id": 24846150, "author": "Steven Christenson", "author_id": 2723552, "author_profile": "https://Stackoverflow.com/users/2723552", "pm_score": 3, "selected": false, "text": "<script src=\"http://maps.google.com/maps/api/js?sensor=false&libraries=geometry\" type=\"text/javascript\"></script> \n\ndistance = google.maps.geometry.spherical.computeDistanceBetween(\n new google.maps.LatLng(fromLat, fromLng), \n new google.maps.LatLng(toLat, toLng));\n" }, { "answer_id": 25266454, "author": "Jorik", "author_id": 1346170, "author_profile": "https://Stackoverflow.com/users/1346170", "pm_score": 0, "selected": false, "text": "var latLng1 = new LatLng(5, 3);\nvar latLng2 = new LatLng(6, 7);\nvar distance = latLng1.distanceTo(latLng2); \n /**\n * latLng point\n * @param {Number} lat\n * @param {Number} lng\n * @returns {LatLng}\n * @constructor\n */\nfunction LatLng(lat,lng) {\n this.lat = parseFloat(lat);\n this.lng = parseFloat(lng);\n\n this.__cache = {};\n}\n\nLatLng.prototype = {\n toString: function() {\n return [this.lat, this.lng].join(\",\");\n },\n\n /**\n * calculate distance in km to another latLng, with caching\n * @param {LatLng} latLng\n * @returns {Number} distance in km\n */\n distanceTo: function(latLng) {\n var cacheKey = latLng.toString();\n if(cacheKey in this.__cache) {\n return this.__cache[cacheKey];\n }\n\n // the fastest way to calculate the distance, according to this jsperf test;\n // http://jsperf.com/haversine-salvador/8\n // http://stackoverflow.com/questions/27928\n var deg2rad = 0.017453292519943295; // === Math.PI / 180\n var lat1 = this.lat * deg2rad;\n var lng1 = this.lng * deg2rad;\n var lat2 = latLng.lat * deg2rad;\n var lng2 = latLng.lng * deg2rad;\n var a = (\n (1 - Math.cos(lat2 - lat1)) +\n (1 - Math.cos(lng2 - lng1)) * Math.cos(lat1) * Math.cos(lat2)\n ) / 2;\n var distance = 12742 * Math.asin(Math.sqrt(a)); // Diameter of the earth in km (2 * 6371)\n\n // cache the distance\n this.__cache[cacheKey] = distance;\n\n return distance;\n }\n};\n" }, { "answer_id": 27218153, "author": "Eric Walsh", "author_id": 2577822, "author_profile": "https://Stackoverflow.com/users/2577822", "pm_score": 1, "selected": false, "text": "function calcDist(lat1, lon1, lat2, lon2)\n lat1= lat1*0.0174532925\n lat2= lat2*0.0174532925\n lon1= lon1*0.0174532925\n lon2= lon2*0.0174532925\n\n dlon = lon2-lon1\n dlat = lat2-lat1\n\n a = math.pow(math.sin(dlat/2),2) + math.cos(lat1) * math.cos(lat2) * math.pow(math.sin(dlon/2),2)\n c = 2 * math.asin(math.sqrt(a))\n dist = 6371 * c -- multiply by 0.621371 to convert to miles\n return dist\nend\n" }, { "answer_id": 29946545, "author": "Raphael C", "author_id": 1872349, "author_profile": "https://Stackoverflow.com/users/1872349", "pm_score": 2, "selected": false, "text": "function getDistanceFromLatLonInKm(position1, position2) {\n \"use strict\";\n var deg2rad = function (deg) { return deg * (Math.PI / 180); },\n R = 6371,\n dLat = deg2rad(position2.lat - position1.lat),\n dLng = deg2rad(position2.lng - position1.lng),\n a = Math.sin(dLat / 2) * Math.sin(dLat / 2)\n + Math.cos(deg2rad(position1.lat))\n * Math.cos(deg2rad(position2.lat))\n * Math.sin(dLng / 2) * Math.sin(dLng / 2),\n c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));\n return R * c;\n}\n\nconsole.log(getDistanceFromLatLonInKm(\n {lat: 48.7931459, lng: 1.9483572},\n {lat: 48.827167, lng: 2.2459745}\n));\n" }, { "answer_id": 31398615, "author": "invoketheshell", "author_id": 4930264, "author_profile": "https://Stackoverflow.com/users/4930264", "pm_score": 3, "selected": false, "text": "pip install haversine from haversine import haversine, Unit\norigin = (39.50, 98.35)\nparis = (48.8567, 2.3508)\nhaversine(origin, paris, unit=Unit.MILES)\n unit=Unit.KILOMETERS" }, { "answer_id": 33090122, "author": "Eduardo Naveda", "author_id": 1472511, "author_profile": "https://Stackoverflow.com/users/1472511", "pm_score": 2, "selected": false, "text": "package com.project529.garage.util;\n\n\n/**\n * Mean radius.\n */\nprivate static double EARTH_RADIUS = 6371;\n\n/**\n * Returns the distance between two sets of latitudes and longitudes in meters.\n * <p/>\n * Based from the following JavaScript SO answer:\n * http://stackoverflow.com/questions/27928/calculate-distance-between-two-latitude-longitude-points-haversine-formula,\n * which is based on https://en.wikipedia.org/wiki/Haversine_formula (error rate: ~0.55%).\n */\npublic double getDistanceBetween(double lat1, double lon1, double lat2, double lon2) {\n double dLat = toRadians(lat2 - lat1);\n double dLon = toRadians(lon2 - lon1);\n\n double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +\n Math.cos(toRadians(lat1)) * Math.cos(toRadians(lat2)) *\n Math.sin(dLon / 2) * Math.sin(dLon / 2);\n double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));\n double d = EARTH_RADIUS * c;\n\n return d;\n}\n\npublic double toRadians(double degrees) {\n return degrees * (Math.PI / 180);\n}\n" }, { "answer_id": 34241873, "author": "Sel", "author_id": 2706338, "author_profile": "https://Stackoverflow.com/users/2706338", "pm_score": 3, "selected": false, "text": "static getDistanceFromLatLonInKm(lat1: number, lon1: number, lat2: number, lon2: number): number {\n var deg2Rad = deg => {\n return deg * Math.PI / 180;\n }\n\n var r = 6371; // Radius of the earth in km\n var dLat = deg2Rad(lat2 - lat1); \n var dLon = deg2Rad(lon2 - lon1);\n var a =\n Math.sin(dLat / 2) * Math.sin(dLat / 2) +\n Math.cos(deg2Rad(lat1)) * Math.cos(deg2Rad(lat2)) *\n Math.sin(dLon / 2) * Math.sin(dLon / 2);\n var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));\n var d = r * c; // Distance in km\n return d;\n}\n" }, { "answer_id": 35309170, "author": "Meymann", "author_id": 361169, "author_profile": "https://Stackoverflow.com/users/361169", "pm_score": 3, "selected": false, "text": "pythagoras = function (lat1, lon1, lat2, lon2) {\n function sqr(x) {return x * x;}\n function cosDeg(x) {return Math.cos(x * Math.PI / 180.0);}\n\n var earthCyclePerimeter = 40000000.0 * cosDeg((lat1 + lat2) / 2.0);\n var dx = (lon1 - lon2) * earthCyclePerimeter / 360.0;\n var dy = 37000000.0 * (lat1 - lat2) / 360.0;\n\n return Math.sqrt(sqr(dx) + sqr(dy));\n};\n" }, { "answer_id": 37870363, "author": "Keerthana Gopalakrishnan", "author_id": 4400634, "author_profile": "https://Stackoverflow.com/users/4400634", "pm_score": 3, "selected": false, "text": "a= 6378.137#equitorial radius in km\nb= 6356.752#polar radius in km\n\ndef Distance(lat1, lons1, lat2, lons2):\n lat1=math.radians(lat1)\n lons1=math.radians(lons1)\n R1=(((((a**2)*math.cos(lat1))**2)+(((b**2)*math.sin(lat1))**2))/((a*math.cos(lat1))**2+(b*math.sin(lat1))**2))**0.5 #radius of earth at lat1\n x1=R1*math.cos(lat1)*math.cos(lons1)\n y1=R1*math.cos(lat1)*math.sin(lons1)\n z1=R1*math.sin(lat1)\n\n lat2=math.radians(lat2)\n lons2=math.radians(lons2)\n R2=(((((a**2)*math.cos(lat2))**2)+(((b**2)*math.sin(lat2))**2))/((a*math.cos(lat2))**2+(b*math.sin(lat2))**2))**0.5 #radius of earth at lat2\n x2=R2*math.cos(lat2)*math.cos(lons2)\n y2=R2*math.cos(lat2)*math.sin(lons2)\n z2=R2*math.sin(lat2)\n \n return ((x1-x2)**2+(y1-y2)**2+(z1-z2)**2)**0.5\n" }, { "answer_id": 41257416, "author": "fla", "author_id": 2598693, "author_profile": "https://Stackoverflow.com/users/2598693", "pm_score": 2, "selected": false, "text": "CREATE OR REPLACE FUNCTION public.geodistance(alat float, alng float, blat \n\nfloat, blng float)\n RETURNS float AS\n$BODY$\nDECLARE\n v_distance float;\nBEGIN\n\n v_distance = asin( sqrt(\n sin(radians(blat-alat)/2)^2 \n + (\n (sin(radians(blng-alng)/2)^2) *\n cos(radians(alat)) *\n cos(radians(blat))\n )\n )\n ) * cast('7926.3352' as float) * cast('1.609344' as float) ;\n\n\n RETURN v_distance;\nEND \n$BODY$\nlanguage plpgsql VOLATILE SECURITY DEFINER;\nalter function geodistance(alat float, alng float, blat float, blng float)\nowner to postgres;\n" }, { "answer_id": 42360739, "author": "Er.Subhendu Kumar Pati", "author_id": 7596912, "author_profile": "https://Stackoverflow.com/users/7596912", "pm_score": 3, "selected": false, "text": "public static function getDistanceOfTwoPoints($source, $dest, $unit='K') {\n $lat1 = $source[0];\n $lon1 = $source[1];\n $lat2 = $dest[0];\n $lon2 = $dest[1];\n\n $theta = $lon1 - $lon2;\n $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));\n $dist = acos($dist);\n $dist = rad2deg($dist);\n $miles = $dist * 60 * 1.1515;\n $unit = strtoupper($unit);\n\n if ($unit == \"K\") {\n return ($miles * 1.609344);\n }\n else if ($unit == \"M\")\n {\n return ($miles * 1.609344 * 1000);\n }\n else if ($unit == \"N\") {\n return ($miles * 0.8684);\n } \n else {\n return $miles;\n }\n }\n" }, { "answer_id": 46771383, "author": "aldrien.h", "author_id": 2534479, "author_profile": "https://Stackoverflow.com/users/2534479", "pm_score": 2, "selected": false, "text": "include Math\n#Note: from/to = [lat, long]\n\ndef get_distance_in_km(from, to)\n radians = lambda { |deg| deg * Math.PI / 180 }\n radius = 6371 # Radius of the earth in kilometer\n dLat = radians[to[0]-from[0]]\n dLon = radians[to[1]-from[1]]\n\n cosines_product = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(radians[from[0]]) * Math.cos(radians[to[1]]) * Math.sin(dLon/2) * Math.sin(dLon/2)\n\n c = 2 * Math.atan2(Math.sqrt(cosines_product), Math.sqrt(1-cosines_product)) \n return radius * c # Distance in kilometer\nend\n" }, { "answer_id": 49916544, "author": "Chong Lip Phang", "author_id": 2435020, "author_profile": "https://Stackoverflow.com/users/2435020", "pm_score": 3, "selected": false, "text": "geoDistance(50,5,58,3)\nHaversine: 899 km\nMaymenn: 833 km\nKeerthana: 897 km\ngoogle.maps.geometry.spherical.computeDistanceBetween(): 900 km\n\ngeoDistance(50,5,-58,-3)\nHaversine: 12030 km\nMaymenn: 11135 km\nKeerthana: 10310 km\ngoogle.maps.geometry.spherical.computeDistanceBetween(): 12044 km\n\ngeoDistance(.05,.005,.058,.003)\nHaversine: 0.9169 km\nMaymenn: 0.851723 km\nKeerthana: 0.917964 km\ngoogle.maps.geometry.spherical.computeDistanceBetween(): 0.917964 km\n\ngeoDistance(.05,80,.058,80.3)\nHaversine: 33.37 km\nMaymenn: 33.34 km\nKeerthana: 33.40767 km\ngoogle.maps.geometry.spherical.computeDistanceBetween(): 33.40770 km\n function geoDistance(lat1, lng1, lat2, lng2){\n const a = 6378.137; // equitorial radius in km\n const b = 6356.752; // polar radius in km\n\n var sq = x => (x*x);\n var sqr = x => Math.sqrt(x);\n var cos = x => Math.cos(x);\n var sin = x => Math.sin(x);\n var radius = lat => sqr((sq(a*a*cos(lat))+sq(b*b*sin(lat)))/(sq(a*cos(lat))+sq(b*sin(lat))));\n\n lat1 = lat1 * Math.PI / 180;\n lng1 = lng1 * Math.PI / 180;\n lat2 = lat2 * Math.PI / 180;\n lng2 = lng2 * Math.PI / 180;\n\n var R1 = radius(lat1);\n var x1 = R1*cos(lat1)*cos(lng1);\n var y1 = R1*cos(lat1)*sin(lng1);\n var z1 = R1*sin(lat1);\n\n var R2 = radius(lat2);\n var x2 = R2*cos(lat2)*cos(lng2);\n var y2 = R2*cos(lat2)*sin(lng2);\n var z2 = R2*sin(lat2);\n\n return sqr(sq(x1-x2)+sq(y1-y2)+sq(z1-z2));\n}\n" }, { "answer_id": 50866722, "author": "Ryan", "author_id": 3355222, "author_profile": "https://Stackoverflow.com/users/3355222", "pm_score": 1, "selected": false, "text": "let radialDistanceHaversine location1 location2 : float = \n let degreeToRadian degrees = degrees * System.Math.PI / 180.0\n let earthRadius = 3959.0\n let deltaLat = location2.Latitude - location1.Latitude |> degreeToRadian\n let deltaLong = location2.Longitude - location1.Longitude |> degreeToRadian\n let a =\n (deltaLat / 2.0 |> sin) ** 2.0\n + (location1.Latitude |> degreeToRadian |> cos)\n * (location2.Latitude |> degreeToRadian |> cos)\n * (deltaLong / 2.0 |> sin) ** 2.0\n atan2 (a |> sqrt) (1.0 - a |> sqrt)\n * 2.0\n * earthRadius\n" }, { "answer_id": 52718561, "author": "Kiran Maniya", "author_id": 8203357, "author_profile": "https://Stackoverflow.com/users/8203357", "pm_score": 3, "selected": false, "text": "SELECT UserId, ( 3959 * acos( cos( radians( your latitude here ) ) * cos( radians(latitude) ) * \ncos( radians(longitude) - radians( your longitude here ) ) + sin( radians( your latitude here ) ) * \nsin( radians(latitude) ) ) ) AS distance FROM user HAVING\ndistance < 5 ORDER BY distance LIMIT 0 , 5;\n" }, { "answer_id": 54448795, "author": "ak-j", "author_id": 5925898, "author_profile": "https://Stackoverflow.com/users/5925898", "pm_score": 2, "selected": false, "text": "double calculateDistance(double latPoint1, double lngPoint1, \n double latPoint2, double lngPoint2) {\n if(latPoint1 == latPoint2 && lngPoint1 == lngPoint2) {\n return 0d;\n }\n\n final double EARTH_RADIUS = 6371.0; //km value;\n\n //converting to radians\n latPoint1 = Math.toRadians(latPoint1);\n lngPoint1 = Math.toRadians(lngPoint1);\n latPoint2 = Math.toRadians(latPoint2);\n lngPoint2 = Math.toRadians(lngPoint2);\n\n double distance = Math.pow(Math.sin((latPoint2 - latPoint1) / 2.0), 2) \n + Math.cos(latPoint1) * Math.cos(latPoint2)\n * Math.pow(Math.sin((lngPoint2 - lngPoint1) / 2.0), 2);\n distance = 2.0 * EARTH_RADIUS * Math.asin(Math.sqrt(distance));\n\n return distance; //km value\n}\n" }, { "answer_id": 55455344, "author": "Ramprasath Selvam", "author_id": 8079610, "author_profile": "https://Stackoverflow.com/users/8079610", "pm_score": 2, "selected": false, "text": "dlon = lon2 - lon1\ndlat = lat2 - lat1\na = (sin(dlat/2))^2 + cos(lat1) * cos(lat2) * (sin(dlon/2))^2\nc = 2 * atan2( sqrt(a), sqrt(1-a) )\ndistance = R * c (where R is the radius of the Earth)\n \nR = 6367 km OR 3956 mi\n lat1, lon1: The Latitude and Longitude of point 1 (in decimal degrees)\n lat2, lon2: The Latitude and Longitude of point 2 (in decimal degrees)\n unit: The unit of measurement in which to calculate the results where:\n 'M' is statute miles (default)\n 'K' is kilometers\n 'N' is nautical miles\n function distance(lat1, lon1, lat2, lon2, unit) {\n try {\n var radlat1 = Math.PI * lat1 / 180\n var radlat2 = Math.PI * lat2 / 180\n var theta = lon1 - lon2\n var radtheta = Math.PI * theta / 180\n var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);\n dist = Math.acos(dist)\n dist = dist * 180 / Math.PI\n dist = dist * 60 * 1.1515\n if (unit == \"K\") {\n dist = dist * 1.609344\n }\n if (unit == \"N\") {\n dist = dist * 0.8684\n }\n return dist\n } catch (err) {\n console.log(err);\n }\n}\n" }, { "answer_id": 59646977, "author": "Oleg Khalidov", "author_id": 2450439, "author_profile": "https://Stackoverflow.com/users/2450439", "pm_score": 1, "selected": false, "text": "import 'dart:math' show cos, sqrt, asin;\n\ndouble calculateDistance(LatLng l1, LatLng l2) {\n const p = 0.017453292519943295;\n final a = 0.5 -\n cos((l2.latitude - l1.latitude) * p) / 2 +\n cos(l1.latitude * p) *\n cos(l2.latitude * p) *\n (1 - cos((l2.longitude - l1.longitude) * p)) /\n 2;\n return 12742 * asin(sqrt(a));\n}\n" }, { "answer_id": 59656546, "author": "Oleg Medvedyev", "author_id": 3044692, "author_profile": "https://Stackoverflow.com/users/3044692", "pm_score": 2, "selected": false, "text": "def haversine(lat1, lon1, lat2, lon2):\n \"\"\"\n Calculate the great circle distance between two points\n on the earth (specified in decimal degrees)\n\n All args must be of equal length.\n Distances are in meters.\n \n Ref:\n https://stackoverflow.com/questions/29545704/fast-haversine-approximation-python-pandas\n https://ipython.readthedocs.io/en/stable/interactive/magics.html\n \"\"\"\n Radius = 6.371e6\n lon1, lat1, lon2, lat2 = map(np.radians, [lon1, lat1, lon2, lat2])\n\n dlon = lon2 - lon1\n dlat = lat2 - lat1\n\n a = np.sin(dlat/2.0)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon/2.0)**2\n\n c = 2 * np.arcsin(np.sqrt(a))\n s12 = Radius * c\n \n # initial azimuth in degrees\n y = np.sin(lon2-lon1) * np.cos(lat2)\n x = np.cos(lat1)*np.sin(lat2) - np.sin(lat1)*np.cos(lat2)*np.cos(dlon)\n azi1 = np.arctan2(y, x)*180./math.pi\n\n return {'s12':s12, 'azi1': azi1}\n np.random.seed(42)\nlats1 = np.random.uniform(-90,90,100000)\nlons1 = np.random.uniform(-180,180,100000)\nlats2 = np.random.uniform(-90,90,100000)\nlons2 = np.random.uniform(-180,180,100000)\nr1 = inverse(lats1, lons1, lats2, lons2)\nr2 = haversine(lats1, lons1, lats2, lons2)\nprint(\"Max absolute error: {:4.2f}m\".format(np.max(r1['s12']-r2['s12'])))\nprint(\"Mean absolute error: {:4.2f}m\".format(np.mean(r1['s12']-r2['s12'])))\nprint(\"Max relative error: {:4.2f}%\".format(np.max((r2['s12']/r1['s12']-1)*100)))\nprint(\"Mean relative error: {:4.2f}%\".format(np.mean((r2['s12']/r1['s12']-1)*100)))\n Max absolute error: 26671.47m\nMean absolute error: -2499.84m\nMax relative error: 0.55%\nMean relative error: -0.02%\n Direct method for 100,000 points\n94.9 ms ± 25 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n9.79 s ± 1.4 s per loop (mean ± std. dev. of 7 runs, 1 loop each)\n\nInverse method for 100,000 points\n1.5 s ± 504 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n24.2 s ± 3.91 s per loop (mean ± std. dev. of 7 runs, 1 loop each)\n" }, { "answer_id": 59682648, "author": "WapShivam", "author_id": 9629819, "author_profile": "https://Stackoverflow.com/users/9629819", "pm_score": 1, "selected": false, "text": "a = sin²(Δφ/2) + cos φ1 ⋅ cos φ2 ⋅ sin²(Δλ/2)\nc = 2 ⋅ atan2( √a, √(1−a) )\nd = R ⋅ c\n New delhi co-ordinates= 28.7041° N, 77.1025° E\nLondon co-ordinates= 51.5074° N, 0.1278° W\n\nvar R = 6371e3; // metres\nvar φ1 = 28.7041.toRadians();\nvar φ2 = 51.5074.toRadians();\nvar Δφ = (51.5074-28.7041).toRadians();\nvar Δλ = (0.1278-77.1025).toRadians();\n\nvar a = Math.sin(Δφ/2) * Math.sin(Δφ/2) +\n Math.cos(φ1) * Math.cos(φ2) *\n Math.sin(Δλ/2) * Math.sin(Δλ/2);\nvar c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));\n\nvar d = R * c; // metres\nd = d/1000; // km\n" }, { "answer_id": 60159168, "author": "Korayem", "author_id": 80434, "author_profile": "https://Stackoverflow.com/users/80434", "pm_score": 2, "selected": false, "text": "=ACOS(COS(RADIANS(90-Lat1))*COS(RADIANS(90-Lat2))+SIN(RADIANS(90-Lat1))*SIN(RADIANS(90-Lat2))*COS(RADIANS(Long1-Long2)))*6371\n" }, { "answer_id": 62139010, "author": "Kristian K", "author_id": 13505403, "author_profile": "https://Stackoverflow.com/users/13505403", "pm_score": 1, "selected": false, "text": "#pip install geopy\nfrom geopy.distance import geodesic\nNY = [40.71278,-74.00594]\nBeijing = [39.90421,116.40739]\nprint(\"WGS84: \",geodesic(NY, Beijing).km) #WGS84 is Standard\nprint(\"Intl24: \",geodesic(NY, Beijing, ellipsoid='Intl 1924').km) #geopy includes different ellipsoids\nprint(\"Custom ellipsoid: \",geodesic(NY, Beijing, ellipsoid=(6377., 6356., 1 / 297.)).km) #custom ellipsoid\n\n#supported ellipsoids:\n#model major (km) minor (km) flattening\n#'WGS-84': (6378.137, 6356.7523142, 1 / 298.257223563)\n#'GRS-80': (6378.137, 6356.7523141, 1 / 298.257222101)\n#'Airy (1830)': (6377.563396, 6356.256909, 1 / 299.3249646)\n#'Intl 1924': (6378.388, 6356.911946, 1 / 297.0)\n#'Clarke (1880)': (6378.249145, 6356.51486955, 1 / 293.465)\n#'GRS-67': (6378.1600, 6356.774719, 1 / 298.25)\n #pip install geovectorslib\nfrom geovectorslib import inverse\nprint(inverse(lats1,lons1,lats2,lons2)['s12'])\n" }, { "answer_id": 64214020, "author": "sourav karwa", "author_id": 5022656, "author_profile": "https://Stackoverflow.com/users/5022656", "pm_score": 2, "selected": false, "text": "custom_hav_dist <- function(lat1, lon1, lat2, lon2) {\nR <- 6371\nRadian_factor <- 0.0174533\nlat_1 <- (90-lat1)*Radian_factor\nlat_2 <- (90-lat2)*Radian_factor\ndiff_long <-(lon1-lon2)*Radian_factor\n\ndistance_in_km <- 6371*acos((cos(lat_1)*cos(lat_2))+ \n (sin(lat_1)*sin(lat_2)*cos(diff_long)))\nrm(lat1, lon1, lat2, lon2)\nreturn(distance_in_km)\n}\n custom_hav_dist(50.31,19.08,54.14,19.39)\n[1] 426.3987\n" }, { "answer_id": 64696900, "author": "Irfan wani", "author_id": 13789135, "author_profile": "https://Stackoverflow.com/users/13789135", "pm_score": 1, "selected": false, "text": "from geopy.distance import geodesic\n\n\norigin = (30.172705, 31.526725) # (latitude, longitude) don't confuse\ndestination = (30.288281, 31.732326)\n\nprint(geodesic(origin, destination).meters) # 23576.805481751613\nprint(geodesic(origin, destination).kilometers) # 23.576805481751613\nprint(geodesic(origin, destination).miles) # 14.64994773134371\n" }, { "answer_id": 65109214, "author": "Renato Probst", "author_id": 1713345, "author_profile": "https://Stackoverflow.com/users/1713345", "pm_score": 2, "selected": false, "text": "getDrivingDistanceBetweenTwoLatLong(origin, destination) {\n\n return new Observable(subscriber => {\n let service = new google.maps.DistanceMatrixService();\n service.getDistanceMatrix(\n {\n origins: [new google.maps.LatLng(origin.lat, origin.long)],\n destinations: [new google.maps.LatLng(destination.lat, destination.long)],\n travelMode: 'DRIVING'\n }, (response, status) => {\n if (status !== google.maps.DistanceMatrixStatus.OK) {\n console.log('Error:', status);\n subscriber.error({error: status, status: status});\n } else {\n console.log(response);\n try {\n let valueInMeters = response.rows[0].elements[0].distance.value;\n let valueInKms = valueInMeters / 1000;\n subscriber.next(valueInKms);\n subscriber.complete();\n }\n catch(error) {\n subscriber.error({error: error, status: status});\n }\n }\n });\n});\n}\n" }, { "answer_id": 66994120, "author": "Anurag", "author_id": 10665583, "author_profile": "https://Stackoverflow.com/users/10665583", "pm_score": 0, "selected": false, "text": "function distance($lat1, $lon1, $lat2, $lon2) { \n $pi80 = M_PI / 180; \n $lat1 *= $pi80; $lon1 *= $pi80; $lat2 *= $pi80; $lon2 *= $pi80; \n $dlat = $lat2 - $lat1; \n $dlon = $lon2 - $lon1; \n $a = sin($dlat / 2) * sin($dlat / 2) + cos($lat1) * cos($lat2) * sin($dlon / 2) * sin($dlon / 2); \n $km = 6372.797 * 2 * atan2(sqrt($a), sqrt(1 - $a)); \n return $km; \n}\n" }, { "answer_id": 67357990, "author": "Aaron Lelevier", "author_id": 1913888, "author_profile": "https://Stackoverflow.com/users/1913888", "pm_score": 1, "selected": false, "text": "lat_lng({Lat1, Lon1}=_Point1, {Lat2, Lon2}=_Point2) ->\n P = math:pi() / 180,\n R = 6371, % Radius of Earth in KM\n A = 0.5 - math:cos((Lat2 - Lat1) * P) / 2 +\n math:cos(Lat1 * P) * math:cos(Lat2 * P) * (1 - math:cos((Lon2 - Lon1) * P))/2,\n R * 2 * math:asin(math:sqrt(A)).\n" }, { "answer_id": 68985288, "author": "Arthur Ronconi", "author_id": 2272598, "author_profile": "https://Stackoverflow.com/users/2272598", "pm_score": 2, "selected": false, "text": "$ npm install geolib\n import { getDistance } from 'geolib'\n\nconst distance = getDistance(\n { latitude: 51.5103, longitude: 7.49347 },\n { latitude: \"51° 31' N\", longitude: \"7° 28' E\" }\n)\n\nconsole.log(distance)\n" }, { "answer_id": 70532052, "author": "Remis Haroon - رامز", "author_id": 1843011, "author_profile": "https://Stackoverflow.com/users/1843011", "pm_score": 0, "selected": false, "text": " def calculateHaversineDistance(lat1: Double, lon1: Double, lat2: Double, lon2: Double): Double = {\n val long2 = lon2 * math.Pi / 180\n val lat2 = lat2 * math.Pi / 180\n val long1 = lon1 * math.Pi / 180\n val lat1 = lat1 * math.Pi / 180\n\n val dlon = long2 - long1\n val dlat = lat2 - lat1\n val a = math.pow(math.sin(dlat / 2), 2) + math.cos(lat1) * math.cos(lat2) * math.pow(math.sin(dlon / 2), 2)\n val c = 2 * math.atan2(Math.sqrt(a), math.sqrt(1 - a))\n val haversineDistance = 3961 * c // 3961 = radius of earth in miles\n haversineDistance\n }\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/27928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1456/" ]
27,952
<p>Basically what I want to do it this: a pdb file contains a location of source files (e.g. <code>C:\dev\proj1\helloworld.cs</code>). Is it possible to modify that pdb file so that it contains a different location (e.g. <code>\more\differenter\location\proj1\helloworld.cs</code>)?</p>
[ { "answer_id": 28174, "author": "Matt Dillard", "author_id": 863, "author_profile": "https://Stackoverflow.com/users/863", "pm_score": 3, "selected": false, "text": "subst subst N: <MyRealPath>\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/27952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2822/" ]
27,983
<p>I have a table of tags and want to get the highest count tags from the list.</p> <p>Sample data looks like this</p> <pre><code>id (1) tag ('night') id (2) tag ('awesome') id (3) tag ('night') </code></pre> <p>using</p> <pre><code>SELECT COUNT(*), `Tag` from `images-tags` GROUP BY `Tag` </code></pre> <p>gets me back the data I'm looking for perfectly. However, I would like to organize it, so that the highest tag counts are first, and limit it to only send me the first 20 or so.</p> <p>I tried this...</p> <pre><code>SELECT COUNT(id), `Tag` from `images-tags` GROUP BY `Tag` ORDER BY COUNT(id) DESC LIMIT 20 </code></pre> <p>and I keep getting an "Invalid use of group function - ErrNr 1111"</p> <p>What am I doing wrong?</p> <p>I'm using MySQL 4.1.25-Debian</p>
[ { "answer_id": 27992, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 6, "selected": false, "text": "SELECT COUNT(id), `Tag` from `images-tags`\nGROUP BY `Tag`\nORDER BY 1 DESC\nLIMIT 20\n" }, { "answer_id": 27994, "author": "jerhinesmith", "author_id": 1108, "author_profile": "https://Stackoverflow.com/users/1108", "pm_score": 4, "selected": false, "text": "order by group by SELECT COUNT(id), `Tag` from `images-tags`\nGROUP BY `Tag`\nORDER BY COUNT(id) DESC\nLIMIT 20\n SELECT COUNT(id), `Tag` from `images-tags`\nGROUP BY `Tag`\nORDER 1 DESC\nLIMIT 20\n" }, { "answer_id": 28686, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": 3, "selected": false, "text": "select 'Tag', counts.cnt\nfrom\n (\n select count(*) as cnt, 'Tag'\n from 'images-tags'\n group by 'tag'\n ) counts\norder by counts.cnt desc\n" }, { "answer_id": 30503, "author": "Scott Noyes", "author_id": 3254, "author_profile": "https://Stackoverflow.com/users/3254", "pm_score": 9, "selected": true, "text": "SELECT COUNT(id) AS theCount, `Tag` from `images-tags`\nGROUP BY `Tag`\nORDER BY theCount DESC\nLIMIT 20\n" }, { "answer_id": 31380216, "author": "Ashutosh Gupta", "author_id": 4527338, "author_profile": "https://Stackoverflow.com/users/4527338", "pm_score": -1, "selected": false, "text": " SELECT data_collector_id , count (data_collector_id ) as frequency \n from rent_flats \n where is_contact_person_landlord = 'True' \n GROUP BY data_collector_id \n ORDER BY count(data_collector_id) DESC\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/27983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1477/" ]
27,998
<p>Most of my C/C++ development involves monolithic module files and absolutely no classes whatsoever, so usually when I need to make a <strong>DLL</strong> with accessible functions I just export them using the standard <code>__declspec(dllexport)</code> directive. Then access them either dynamically via <code>LoadLibrary()</code> or at compile time with a header and lib file. </p> <p>How do you do this when you want to export an entire class (and all it's public methods and properties)?</p> <p>Is it possible to dynamically load that class at runtime and if so, how?</p> <p>How would you do it with a header and lib for compile time linking?</p>
[ { "answer_id": 28018, "author": "crashmstr", "author_id": 1441, "author_profile": "https://Stackoverflow.com/users/1441", "pm_score": 4, "selected": false, "text": "#define ISDLL USEDLL LoadLibrary" }, { "answer_id": 28022, "author": "Graeme Perrow", "author_id": 1821, "author_profile": "https://Stackoverflow.com/users/1821", "pm_score": 4, "selected": false, "text": "#if defined( BUILD_DLL )\n #define IMPORT_EXPORT __declspec(dllexport)\n#else\n #define IMPORT_EXPORT __declspec(dllimport)\n#endif\nclass IMPORT_EXPORT MyClass {\n ...\n};\n" }, { "answer_id": 7452230, "author": "Eli Bendersky", "author_id": 8206, "author_profile": "https://Stackoverflow.com/users/8206", "pm_score": 3, "selected": false, "text": "LoadLibrary" }, { "answer_id": 24384693, "author": "SridharKritha", "author_id": 1308589, "author_profile": "https://Stackoverflow.com/users/1308589", "pm_score": 4, "selected": false, "text": "#ifdef MYDLL_EXPORTS \n#define DLLCALL __declspec(dllexport) /* Should be enabled before compiling \n .dll project for creating .dll*/\n#else\n#define DLLCALL __declspec(dllimport) /* Should be enabled in Application side\n for using already created .dll*/\n#endif\n\n// Interface Class\nclass ImyMath {\npublic:\n virtual ~ImyMath() {;}\n virtual int Add(int a, int b) = 0;\n virtual int Subtract(int a, int b) = 0;\n};\n\n// Concrete Class\nclass MyMath: public ImyMath {\npublic:\n MyMath() {}\n int Add(int a, int b);\n int Subtract(int a, int b);\n int a,b;\n};\n\n// Factory function that will return the new object instance. (Only function\n// should be declared with DLLCALL)\nextern \"C\" /*Important for avoiding Name decoration*/\n{\n DLLCALL ImyMath* _cdecl CreateMathObject();\n};\n\n// Function Pointer Declaration of CreateMathObject() [Entry Point Function]\ntypedef ImyMath* (*CREATE_MATH) ();\n #include \"dllHeader.h\"\n\n// Create Object\nDLLCALL ImyMath* _cdecl CreateMathObject() {\n return new MyMath();\n}\n\nint MyMath::Add(int a, int b) {\n return a+b;\n}\n\nint MyMath::Subtract(int a, int b) {\n return a-b;\n}\n #include <iostream>\n#include <windows.h>\n#include \"dllHeader.h\"\n\nint main()\n{\n HINSTANCE hDLL = LoadLibrary(L\"MyDLL.dll\"); // L\".\\Debug\\MyDLL.dll\"\n\n if (hDLL == NULL) {\n std::cout << \"Failed to load library.\\n\";\n }\n else {\n CREATE_MATH pEntryFunction = (CREATE_MATH)GetProcAddress(hDLL,\"CreateMathObject\");\n ImyMath* pMath = pEntryFunction();\n if (pMath) {\n std::cout << \"10+10=\" << pMath->Add(10, 10) << std::endl;\n std::cout << \"50-10=\" << pMath->Subtract(50, 10) << std::endl;\n }\n FreeLibrary(hDLL);\n }\n std::cin.get();\n return 0;\n}\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/27998", "https://Stackoverflow.com", "https://Stackoverflow.com/users/194/" ]
28,002
<p>I've been writing C and C++ code for almost twenty years, but there's one aspect of these languages that I've never really understood. I've obviously used regular casts i.e.</p> <pre><code>MyClass *m = (MyClass *)ptr; </code></pre> <p>all over the place, but there seem to be two other types of casts, and I don't know the difference. What's the difference between the following lines of code?</p> <pre><code>MyClass *m = (MyClass *)ptr; MyClass *m = static_cast&lt;MyClass *&gt;(ptr); MyClass *m = dynamic_cast&lt;MyClass *&gt;(ptr); </code></pre>
[ { "answer_id": 28020, "author": "Inisheer", "author_id": 2982, "author_profile": "https://Stackoverflow.com/users/2982", "pm_score": 4, "selected": false, "text": "dynamic_cast static_cast" }, { "answer_id": 1255015, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 12, "selected": true, "text": "static_cast static_cast void func(void *data) {\n // Conversion from MyClass* -> void* is implicit\n MyClass *c = static_cast<MyClass*>(data);\n ...\n}\n\nint main() {\n MyClass c;\n start_thread(&func, &c) // func(&c) will be called\n .join();\n}\n MyClass dynamic_cast bad_cast if (JumpStm *j = dynamic_cast<JumpStm*>(&stm)) {\n ...\n} else if (ExprStm *e = dynamic_cast<ExprStm*>(&stm)) {\n ...\n}\n dynamic_cast Base struct Base { };\nstruct Derived : Base { };\nint main() {\n Derived d; Base *b = &d;\n dynamic_cast<Derived*>(b); // Invalid\n}\n static_cast dynamic_cast public dynamic_cast const_cast static_cast reinterpret_cast dynamic_cast static_cast" }, { "answer_id": 9151168, "author": "larsmoa", "author_id": 167251, "author_profile": "https://Stackoverflow.com/users/167251", "pm_score": 4, "selected": false, "text": "dynamic_cast NULL dynamic_cast static_cast" }, { "answer_id": 18414172, "author": "Hossein", "author_id": 2736559, "author_profile": "https://Stackoverflow.com/users/2736559", "pm_score": 8, "selected": false, "text": "char c = 10; // 1 byte\nint *p = (int*)&c; // 4 bytes\n *p = 5; // run-time error: stack corruption\n int *q = static_cast<int*>(&c); // compile-time error\n int *r = reinterpret_cast<int*>(&c); // forced conversion\n MyChild MyBase class MyBase \n{ \n public:\n virtual void test() {}\n};\nclass MyChild : public MyBase {};\n\n\n\nint main()\n{\n MyChild *child = new MyChild();\n MyBase *base = dynamic_cast<MyBase*>(child); // ok\n}\n MyBase MyChild MyBase *base = new MyBase();\nMyChild *child = dynamic_cast<MyChild*>(base);\n\n \nif (child == 0) \nstd::cout << \"Null pointer returned\";\n bad_cast try-catch #include <exception>\n// … \ntry\n{ \n MyChild &child = dynamic_cast<MyChild&>(*base);\n}\ncatch(std::bad_cast &e) \n{ \n std::cout << e.what(); // bad dynamic_cast\n}\n MyBase *base = static_cast<MyBase*>(child); // ok\n MyBase MyBase MyChild // Succeeds for a MyChild object\nMyChild *child = dynamic_cast<MyChild*>(base);\n // Allowed, but invalid\nMyChild *child = static_cast<MyChild*>(base);\n \n// Incomplete MyChild object dereferenced\n(*child);\n const const int myConst = 5;\nint *nonConst = const_cast<int*>(&myConst); // removes const\n const *nonConst = 10; // potential run-time error\n const void print(int *p) \n{\n std::cout << *p;\n}\n const print(&myConst); // error: cannot convert \n // const int* to int*\n \nprint(nonConst); // allowed\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1821/" ]
28,003
<p>I have a large database and would like to select table names that have a certain column name. I have done something like this in MySQL, but can't find any info on SQL Server.</p> <p>I want to do something like:</p> <pre><code>select [table] from [db] where table [has column 'classtypeid'] </code></pre> <p>How can I do something like this?</p>
[ { "answer_id": 28008, "author": "SQLMenace", "author_id": 740, "author_profile": "https://Stackoverflow.com/users/740", "pm_score": 4, "selected": true, "text": "select table_name \nfrom information_schema.columns \nwhere column_name = 'classtypeid'\n" }, { "answer_id": 28012, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 2, "selected": false, "text": "SELECT C.TABLE_NAME\nFROM INFORMATION_SCHEMA.COLUMNS AS C\n INNER JOIN INFORMATION_SCHEMA.TABLES AS T ON C.TABLE_NAME = T.TABLE_NAME\n AND C.TABLE_SCHEMA = T.TABLE_SCHEMA\nWHERE C.COLUMN_NAME = 'classtypeid'\n AND T.TABLE_TYPE = 'BASE TABLE'\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1638/" ]
28,011
<p>Working with dates in ruby and rails on windows, I'm having problems with pre-epoch dates (before 1970) throwing out of range exceptions. I tried using both <a href="http://ruby-doc.org/core-2.2.0/Time.html" rel="nofollow noreferrer"><code>Time</code></a> and <a href="http://ruby-doc.org/stdlib-1.9.3/libdoc/date/rdoc/DateTime.html" rel="nofollow noreferrer"><code>DateTime</code></a> objects, but still have the same problems.</p>
[ { "answer_id": 28148, "author": "Mo.", "author_id": 1870, "author_profile": "https://Stackoverflow.com/users/1870", "pm_score": 2, "selected": true, "text": "Date" }, { "answer_id": 28517, "author": "John Duff", "author_id": 3041, "author_profile": "https://Stackoverflow.com/users/3041", "pm_score": 0, "selected": false, "text": "Date" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28011", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3041/" ]
28,029
<p>How can I have it so Visual Studio doesn't keep re-creating this folder that I never use. It's annoying ot keep looking and unnecessary.</p>
[ { "answer_id": 29442, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": -1, "selected": true, "text": "Tools->Options->Addin/Macro Security\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28029", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2993/" ]
28,051
<p>Suppose you have 2 different ASP.NET applications in IIS. Also, you have some ASCX controls that you want to share across these 2 applications.</p> <p>What's the best way to create a "user control library", so that you can use the same control implementation in the 2 applications, withuot having to duplicate code?</p> <p>Controls have ASCX with HTML + code behind.</p> <hr> <p>Composite controls will be difficult, because we work with designers who use the HTML syntax in the ASCX files to style the controls.</p> <p>Tundey, we use SVN here. Do you have an example on how to implement your suggestion? How can SVN share the ASP.NET controls?</p> <p>Thanks!</p>
[ { "answer_id": 28142, "author": "EndangeredMassa", "author_id": 106, "author_profile": "https://Stackoverflow.com/users/106", "pm_score": 1, "selected": false, "text": "<DefaultProperty(\"Text\"), ToolboxData(\"<{0}:BreadCrumb runat=server />\")> _\nPublic Class BreadCrumb\n WebControl\n\n <Bindable(True)> _\n Property Text() As String\n '...'\n End Property\n\n Protected Overrides Sub RenderContents(output as HtmlTextWriter)\n output.write(Text)\n End Sub\n\n Private Sub Page_Load(...) Handles MyBase.Load\n ' Setup your breadcrumb and store the HTML output '\n ' in the Text property '\n End Sub\nEnd Class\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2868/" ]
28,080
<p>We often hear/read that one should avoid dynamic casting. I was wondering what would be 'good use' examples of it, according to you?</p> <p>Edit:</p> <p>Yes, I'm aware of <a href="https://stackoverflow.com/questions/28002/regular-cast-vs-staticcast-vs-dynamiccast">that other thread</a>: it is indeed when reading one of the first answers there that I asked my question!</p>
[ { "answer_id": 117185, "author": "rlerallut", "author_id": 20055, "author_profile": "https://Stackoverflow.com/users/20055", "pm_score": 1, "selected": false, "text": "template<class T>\nclass MyVector : public ContainerInterface\n...\n // function prototype (public API, in the header file)\nvoid ProcessVector( ContainerInterface& vecIfce );\n\n// function implementation (private, in the .cpp file)\nvoid ProcessVector( ContainerInterface& vecIfce)\n{\n MyVector<int>& vecInt = dynamic_cast<MyVector<int> >(vecIfce); \n // the cast throws bad_cast in case of error but you could use a\n // more complex method to choose which low-level implementation\n // to use, basically rolling by hand your own polymorphism.\n\n // Process a vector of integers\n ...\n}\n" }, { "answer_id": 303260, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "List<myObject> myObjectList = getMyObjects();\n\nList<string> ids = myObjectList.PropertyList(\"id\");\n public static List<string> PropertyList(this object objList, string propName) {\n var genList = (objList.GetType())objList;\n}\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2638/" ]
28,092
<p>I have a ListBox that has a style defined for ListBoxItems. Inside this style, I have some labels and a button. One that button, I want to define a click event that can be handled on my page (or any page that uses that style). How do I create an event handler on my WPF page to handle the event from my ListBoxItems style?</p> <p>Here is my style (affected code only):</p> <pre><code>&lt;Style x:Key="UsersTimeOffList" TargetType="{x:Type ListBoxItem}"&gt; ... &lt;Grid&gt; &lt;Button x:Name="btnRemove" Content="Remove" Margin="0,10,40,0" Click="btnRemove_Click" /&gt; &lt;/Grid&gt; &lt;/Style&gt; </code></pre> <p>Thanks! </p>
[ { "answer_id": 28187, "author": "Jas", "author_id": 777, "author_profile": "https://Stackoverflow.com/users/777", "pm_score": 0, "selected": false, "text": "Public Event btnRemove()\n RaiseEvent btnRemove()\n" }, { "answer_id": 28252, "author": "Arcturus", "author_id": 900, "author_profile": "https://Stackoverflow.com/users/900", "pm_score": 4, "selected": true, "text": " public static readonly RoutedCommand Login = new RoutedCommand();\n <Button Command=\"{x:Static myclass.Login}\" /> \n CommandBindings.Add(new CommandBinding(myclass.Login, ExecuteLogin));\n <UserControl.CommandBindings>\n <CommandBinding Command=\"{x:Static myclass.Login}\" Executed=\"ExecuteLogin\" />\n </UserControl.CommandBindings>\n private void ExecuteLogin(object sender, ExecutedRoutedEventArgs e)\n {\n //Your code goes here... e has your parameter!\n }\n" }, { "answer_id": 190051, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 3, "selected": false, "text": "<ListBox Button.Click=\"removeButtonClick\" ... />\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3047/" ]
28,098
<p>How do I convert the value of a PHP variable to string?</p> <p>I was looking for something better than concatenating with an empty string:</p> <pre><code>$myText = $myVar . ''; </code></pre> <p>Like the <code>ToString()</code> method in Java or .NET.</p>
[ { "answer_id": 28101, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 4, "selected": false, "text": "$myText = \"$myVar\";\n" }, { "answer_id": 28104, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 1, "selected": false, "text": "$in . ''; \n" }, { "answer_id": 28111, "author": "Tom Mayfield", "author_id": 2314, "author_profile": "https://Stackoverflow.com/users/2314", "pm_score": 11, "selected": true, "text": "$myText = (string)$myVar;\n" }, { "answer_id": 28131, "author": "Ross", "author_id": 2025, "author_profile": "https://Stackoverflow.com/users/2025", "pm_score": 8, "selected": false, "text": "$strvar = (string) $var; // Casts to string\necho $var; // Will cast to string implicitly\nvar_dump($var); // Will show the true type of the variable\n __toString class Bottles {\n public function __toString()\n {\n return 'Ninety nine green bottles';\n }\n}\n\n$ex = new Bottles;\nvar_dump($ex, (string) $ex);\n// Returns: instance of Bottles and \"Ninety nine green bottles\"\n $i = 1;\n\n// int 1\nvar_dump((int) $i);\n\n// bool true\nvar_dump((bool) $i);\n\n// string \"1\"\nvar_dump((string) 1);\n" }, { "answer_id": 28152, "author": "Michał Niedźwiedzki", "author_id": 2169, "author_profile": "https://Stackoverflow.com/users/2169", "pm_score": 4, "selected": false, "text": "(string)$var __toString()" }, { "answer_id": 1936122, "author": "opensas", "author_id": 47633, "author_profile": "https://Stackoverflow.com/users/47633", "pm_score": 5, "selected": false, "text": "string strval ( mixed $var )" }, { "answer_id": 1991021, "author": "Joel Larson", "author_id": 242230, "author_profile": "https://Stackoverflow.com/users/242230", "pm_score": 6, "selected": false, "text": "$var = (string)$varname;\n $var = strval($varname);\n $success = settype($varname, 'string');\n// $varname itself becomes a string\n" }, { "answer_id": 3559247, "author": "Cedric", "author_id": 278739, "author_profile": "https://Stackoverflow.com/users/278739", "pm_score": 7, "selected": false, "text": "$myText = print_r($myVar,true);\n $myText = print_r($myVar,true).\"foo bar\";\n $myText array (\n 0 => '11',\n)foo bar\n $myText = var_export($myVar,true);\n" }, { "answer_id": 5219818, "author": "Justin Weeks", "author_id": 598548, "author_profile": "https://Stackoverflow.com/users/598548", "pm_score": 3, "selected": false, "text": "<?php\n$foo = \"5bar\"; // string\n$bar = true; // boolean\n\nsettype($foo, \"integer\"); // $foo is now 5 (integer)\nsettype($bar, \"string\"); // $bar is now \"1\" (string)\n?>\n" }, { "answer_id": 10473070, "author": "Yauhen Yakimovich", "author_id": 544463, "author_profile": "https://Stackoverflow.com/users/544463", "pm_score": 3, "selected": false, "text": "function castToString($instance) \n{ \n if (is_object($instance) && method_exists($instance, '__toString')) {\n return call_user_func_array(array($instance, '__toString'));\n }\n}\n" }, { "answer_id": 15794348, "author": "Archimedes Trajano", "author_id": 242042, "author_profile": "https://Stackoverflow.com/users/242042", "pm_score": 0, "selected": false, "text": "json_encode() error_log(json_encode($args));\n" }, { "answer_id": 20011937, "author": "DarthKotik", "author_id": 2964871, "author_profile": "https://Stackoverflow.com/users/2964871", "pm_score": 2, "selected": false, "text": "$str = \"$foo\";\n" }, { "answer_id": 22016653, "author": "mikikg", "author_id": 783354, "author_profile": "https://Stackoverflow.com/users/783354", "pm_score": 0, "selected": false, "text": "$my_std_obj_result = $SomeResponse->return->data; // Specific to object/implementation\n\n$my_string_result = implode ((array)$my_std_obj_result); // Do conversion\n" }, { "answer_id": 22028490, "author": "Daan", "author_id": 987864, "author_profile": "https://Stackoverflow.com/users/987864", "pm_score": 4, "selected": false, "text": "print_r var_dump <?php\n ob_start();\n var_dump($someVar);\n $result = ob_get_clean();\n?>\n" }, { "answer_id": 23732710, "author": "user1587439", "author_id": 1587439, "author_profile": "https://Stackoverflow.com/users/1587439", "pm_score": 3, "selected": false, "text": "$str $no = 077543\n$str = (string)$no;\n$str = \"$no\";\n$str = print_r($no,true);\n$str = strval($no);\n$str = settype($no, \"integer\");\n" }, { "answer_id": 37725483, "author": "Daniel Adenew", "author_id": 2281472, "author_profile": "https://Stackoverflow.com/users/2281472", "pm_score": 1, "selected": false, "text": "$parent_category_name = \"new clothes & shoes\";\n\n// To make it to string option one\n$parent_category = strval($parent_category_name);\n\n// Or make it a string by concatenating it with 'new clothes & shoes'\n// It is useful for database queries\n$parent_category = \"'\" . strval($parent_category_name) . \"'\";\n" }, { "answer_id": 39259207, "author": "jimp", "author_id": 791265, "author_profile": "https://Stackoverflow.com/users/791265", "pm_score": 3, "selected": false, "text": "__toString __toString md5(spl_object_hash($this))" }, { "answer_id": 53883743, "author": "Xanlantos", "author_id": 4693430, "author_profile": "https://Stackoverflow.com/users/4693430", "pm_score": 3, "selected": false, "text": "// Java\nString myText = (string) myVar;\n\n// PHP\n$myText = (string) $myVar;\n // Java\nclass SomeClass{\n public String toString(){\n return \"some string representation\";\n }\n}\n\n// PHP\nclass SomeClass{\n public function __toString()\n {\n return \"some string representation\";\n }\n}\n // Java\nnew SomeClass().toString(); // \"Some string representation\"\n\n// PHP\nstrval(new SomeClass); // \"Some string representation\"\n $no = 421337 // A number in PHP\n$str = \"$no\"; // In PHP, stuff inside \"\" is calculated and variables are replaced\n$str = print_r($no, true); // Same as String.format();\n$str = settype($no, 'string'); // Sets $no to the String Type\n$str = strval($no); // Get the string value of $no\n$str = $no . ''; // As you said concatenate an empty string works too\n" }, { "answer_id": 64322954, "author": "dılo sürücü", "author_id": 5582655, "author_profile": "https://Stackoverflow.com/users/5582655", "pm_score": 0, "selected": false, "text": "$string=(string)$variable; //force make string \n \nclass Foo\n{\n\n public function __toString()\n {\n return \"foo\";\n }\n\n}\n\necho new Foo(); //foo\n \n$string=''.$intvariable;\n" }, { "answer_id": 72723752, "author": "JSON", "author_id": 1246037, "author_profile": "https://Stackoverflow.com/users/1246037", "pm_score": 0, "selected": false, "text": "$myText = $my_var .''; $myText = (string)$my_var;" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28098", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2680/" ]
28,110
<p>I have a large table with 1 million+ records. Unfortunately, the person who created the table decided to put dates in a <code>varchar(50)</code> field.</p> <p>I need to do a simple date comparison -</p> <pre><code>datediff(dd, convert(datetime, lastUpdate, 100), getDate()) &lt; 31 </code></pre> <p>But it fails on the <code>convert()</code>:</p> <pre><code>Conversion failed when converting datetime from character string. </code></pre> <p>Apparently there is something in that field it doesn't like, and since there are so many records, I can't tell just by looking at it. How can I properly sanitize the entire date field so it does not fail on the <code>convert()</code>? Here is what I have now:</p> <pre><code>select count(*) from MyTable where isdate(lastUpdate) &gt; 0 and datediff(dd, convert(datetime, lastUpdate, 100), getDate()) &lt; 31 </code></pre> <hr> <p><a href="https://stackoverflow.com/questions/28110/ms-sql-datetime-conversion-failure#28209">@SQLMenace</a></p> <p>I'm not concerned about performance in this case. This is going to be a one time query. Changing the table to a datetime field is not an option.</p> <p><a href="https://stackoverflow.com/questions/28110/ms-sql-datetime-conversion-failure#28139">@Jon Limjap</a></p> <p>I've tried adding the third argument, and it makes no difference.</p> <hr> <p><a href="https://stackoverflow.com/questions/28110/ms-sql-datetime-conversion-failure#28209">@SQLMenace</a></p> <blockquote> <p>The problem is most likely how the data is stored, there are only two safe formats; ISO YYYYMMDD; ISO 8601 yyyy-mm-dd Thh:mm:ss:mmm (no spaces)</p> </blockquote> <p>Wouldn't the <code>isdate()</code> check take care of this?</p> <p>I don't have a need for 100% accuracy. I just want to get most of the records that are from the last 30 days.</p> <hr> <p><a href="https://stackoverflow.com/questions/28110/ms-sql-datetime-conversion-failure#28209">@SQLMenace</a></p> <pre><code>select isdate('20080131') -- returns 1 select isdate('01312008') -- returns 0 </code></pre> <hr> <p><a href="https://stackoverflow.com/questions/28110/ms-sql-datetime-conversion-failure#28209">@Brian Schkerke</a></p> <blockquote> <p>Place the CASE and ISDATE inside the CONVERT() function.</p> </blockquote> <p>Thanks! That did it.</p>
[ { "answer_id": 28135, "author": "SQLMenace", "author_id": 740, "author_profile": "https://Stackoverflow.com/users/740", "pm_score": 0, "selected": false, "text": "WHERE datediff(dd, convert(datetime, lastUpdate), getDate()) < 31\n where lastUpdate > getDate() -31\n" }, { "answer_id": 28184, "author": "Skerkles", "author_id": 3067, "author_profile": "https://Stackoverflow.com/users/3067", "pm_score": 4, "selected": true, "text": "CASE ISDATE CONVERT() SELECT COUNT(*) FROM MyTable\nWHERE\n DATEDIFF(dd, CONVERT(DATETIME, CASE IsDate(lastUpdate)\n WHEN 1 THEN lastUpdate\n ELSE '12-30-1899'\n END), GetDate()) < 31\n '12-30-1899'" }, { "answer_id": 28186, "author": "SQLMenace", "author_id": 740, "author_profile": "https://Stackoverflow.com/users/740", "pm_score": 0, "selected": false, "text": "select isdate('20080131')\nselect isdate('01312008')\n" }, { "answer_id": 28206, "author": "SQLMenace", "author_id": 740, "author_profile": "https://Stackoverflow.com/users/740", "pm_score": 2, "selected": false, "text": "select * into BadDates\nfrom Yourtable\nwhere isdate(lastUpdate) = 0\n\nselect * into GoodDates\nfrom Yourtable\nwhere isdate(lastUpdate) = 1\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28110", "https://Stackoverflow.com", "https://Stackoverflow.com/users/357/" ]
28,150
<p>OK, this kind of follows on from <a href="https://stackoverflow.com/questions/27758/notify-developer-of-a-do-not-use-method">my previous question</a>.</p> <p>What I would really like to do is create some sort of attribute which allows me to decorate a method that will <strong>break the build</strong>. Much like the <em>Obsolete("reason", true)</em> attribute, but without falsely identifying obsolete code.</p> <p><strong>To clarify</strong>: I dont want it to break the build on <em>ANY</em> F6 (Build) press, I only want it to break the build if a method decorated with the attribute is called somewhere else in the code. Like I said, <em>similar</em> to obsolete, but not the same.</p> <p>I know I am not alone in this, since <a href="https://stackoverflow.com/questions/27758/notify-developer-of-a-do-not-use-method#27796">other users want to use it for other reasons</a>. I have never created custom attributes before so it is all new to me!</p>
[ { "answer_id": 28191, "author": "Greg Hurlman", "author_id": 35, "author_profile": "https://Stackoverflow.com/users/35", "pm_score": -1, "selected": false, "text": "[MyMadeUpAttributeThatBreaksTheBuildForSure]\npublic class NotDoneYet {}\n" }, { "answer_id": 28242, "author": "Jorge Córdoba", "author_id": 2695, "author_profile": "https://Stackoverflow.com/users/2695", "pm_score": 0, "selected": false, "text": "[Conditional(\"CONDITION\")] \npublic static void MiMethod(int a, string msg)\n" }, { "answer_id": 43746, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 3, "selected": false, "text": "CompilerExecutedAttribute" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/832/" ]
28,160
<p>For whatever reason, our company has a coding guideline that states:</p> <p><code>Each class shall have it's own header and implementation file.</code></p> <p>So if we wrote a class called <code>MyString</code> we would need an associated <strong>MyStringh.h</strong> and <strong>MyString.cxx</strong>.</p> <p>Does anyone else do this? Has anyone seen any compiling performance repercussions as a result? Does 5000 classes in 10000 files compile just as quickly as 5000 classes in 2500 files? If not, is the difference noticeable?</p> <p>[We code C++ and use GCC 3.4.4 as our everyday compiler]</p>
[ { "answer_id": 105329, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 6, "selected": false, "text": "A.def.hpp B.def.hpp A.inl.hpp B.inl.hpp A.hpp B.hpp A.def.hpp B.def.hpp A.inl.hpp B.inl.hpp A.def.hpp B.def.hpp A.hpp B.hpp A.def.hpp A.inl.hpp B.def.hpp B.inl.hpp A.hpp B.hpp" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1881/" ]
28,165
<p>Python has this wonderful way of handling string substitutions using dictionaries:</p> <pre><code>&gt;&gt;&gt; 'The %(site)s site %(adj)s because it %(adj)s' % {'site':'Stackoverflow', 'adj':'rocks'} 'The Stackoverflow site rocks because it rocks' </code></pre> <p>I love this because you can specify a value once in the dictionary and then replace it all over the place in the string.</p> <p>I've tried to achieve something similar in PHP using various string replace functions but everything I've come up with feels awkward.</p> <p>Does anybody have a nice clean way to do this kind of string substitution in PHP?</p> <p><strong><em>Edit</em></strong><br> Here's the code from the sprintf page that I liked best. </p> <pre><code>&lt;?php function sprintf3($str, $vars, $char = '%') { $tmp = array(); foreach($vars as $k =&gt; $v) { $tmp[$char . $k . $char] = $v; } return str_replace(array_keys($tmp), array_values($tmp), $str); } echo sprintf3( 'The %site% site %adj% because it %adj%', array('site'=&gt;'Stackoverflow', 'adj'=&gt;'rocks')); ?&gt; </code></pre>
[ { "answer_id": 28247, "author": "Marius", "author_id": 1585, "author_profile": "https://Stackoverflow.com/users/1585", "pm_score": 4, "selected": true, "text": "function subst($str, $dict){\n return preg_replace(array_map(create_function('$a', 'return \"/%\\\\($a\\\\)s/\";'), array_keys($dict)), array_values($dict), $str);\n }\n echo subst('The %(site)s site %(adj)s because it %(adj)s', array('site'=>'Stackoverflow', 'adj'=>'rocks'));\n" }, { "answer_id": 28349, "author": "Gary Richardson", "author_id": 2506, "author_profile": "https://Stackoverflow.com/users/2506", "pm_score": 2, "selected": false, "text": "function subst($str, $dict)\n{\n foreach ($dict AS $key, $value)\n {\n $str = str_replace($key, $value, $str);\n }\n\n return $str;\n}\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28165", "https://Stackoverflow.com", "https://Stackoverflow.com/users/305/" ]
28,196
<p>This is a very specific question regarding <strong>MySQL</strong> as implemented in <strong>WordPress</strong>.</p> <p>I'm trying to develop a plugin that will show (select) posts that have specific '<strong>tags</strong>' and belong to specific '<strong>categories</strong>' (both multiple)</p> <p>I was told it's impossible because of the way categories and tags are stored:</p> <ol> <li><code>wp_posts</code> contains a list of posts, each post have an &quot;ID&quot;</li> <li><code>wp_terms</code> contains a list of terms (both categories and tags). Each term has a TERM_ID</li> <li><code>wp_term_taxonomy</code> has a list of terms with their TERM_IDs and has a Taxonomy definition for each one of those (either a Category or a Tag)</li> <li><code>wp_term_relationships</code> has associations between terms and posts</li> </ol> <p>How can I join the tables to get all posts with tags &quot;Nuclear&quot; <strong>and</strong> &quot;Deals&quot; that also belong to the category &quot;Category1&quot;?</p>
[ { "answer_id": 28233, "author": "Matt Rogish", "author_id": 2590, "author_profile": "https://Stackoverflow.com/users/2590", "pm_score": 2, "selected": false, "text": "SELECT *\n FROM wp_posts p\n WHERE EXISTS( SELECT *\n FROM wp_term_relationship tr\n WHERE tr.object_id = p.id\n AND EXISTS( SELECT *\n FROM wp_term_taxonomy tt\n WHERE tt.term_taxonomy_id = tr.term_taxonomy_id\n AND tt.taxonomy = 'category'\n AND EXISTS( SELECT *\n FROM wp_terms t\n WHERE t.term_id = tt.term_id\n AND t.name = \"Category1\" \n )\n )\n AND EXISTS( SELECT *\n FROM wp_term_taxonomy tt\n WHERE tt.term_taxonomy_id = tr.term_taxonomy_id\n AND tt.taxonomy = 'post_tag'\n AND EXISTS( SELECT *\n FROM wp_terms t\n WHERE t.term_id = tt.term_id\n AND t.name = \"Nuclear\" \n )\n AND EXISTS( SELECT *\n FROM wp_terms t\n WHERE t.term_id = tt.term_id\n AND t.name = \"Deals\" \n )\n )\n )\n" }, { "answer_id": 28373, "author": "Eric", "author_id": 2610, "author_profile": "https://Stackoverflow.com/users/2610", "pm_score": 2, "selected": false, "text": "select p.*\nfrom wp_posts p, \nwp_terms t, wp_term_taxonomy tt, wp_term_relationship tr\nwp_terms t2, wp_term_taxonomy tt2, wp_term_relationship tr2\n\nwhere p.id = tr.object_id\nand t.term_id = tt.term_id\nand tr.term_taxonomy_id = tt.term_taxonomy_id\n\nand p.id = tr2.object_id\nand t2.term_id = tt2.term_id\nand tr2.term_taxonomy_id = tt2.term_taxonomy_id\n\nand (tt.taxonomy = 'category' and tt.term_id = t.term_id and t.name = 'Category1')\nand (tt2.taxonomy = 'post_tag' and tt2.term_id = t2.term_id and t2.name in ('Nuclear', 'Deals'))\n" }, { "answer_id": 30733, "author": "Eric", "author_id": 2610, "author_profile": "https://Stackoverflow.com/users/2610", "pm_score": 4, "selected": true, "text": "select p.*\nfrom wp_posts p, wp_terms t, wp_term_taxonomy tt, wp_term_relationship tr,\nwp_terms t2, wp_term_taxonomy tt2, wp_term_relationship tr2\nwp_terms t2, wp_term_taxonomy tt2, wp_term_relationship tr2\n\nwhere p.id = tr.object_id and t.term_id = tt.term_id and tr.term_taxonomy_id = tt.term_taxonomy_id\n\nand p.id = tr2.object_id and t2.term_id = tt2.term_id and tr2.term_taxonomy_id = tt2.term_taxonomy_id\n\nand p.id = tr3.object_id and t3.term_id = tt3.term_id and tr3.term_taxonomy_id = tt3.term_taxonomy_id\n\nand (tt.taxonomy = 'category' and tt.term_id = t.term_id and t.name = 'Category1')\nand (tt2.taxonomy = 'post_tag' and tt2.term_id = t2.term_id and t2.name = 'Nuclear')\nand (tt3.taxonomy = 'post_tag' and tt3.term_id = t3.term_id and t3.name = 'Deals')\n" }, { "answer_id": 32017, "author": "yoavf", "author_id": 1011, "author_profile": "https://Stackoverflow.com/users/1011", "pm_score": 0, "selected": false, "text": "wp_terms t2, wp_term_taxonomy tt2, wp_term_relationship \n\ntr2 wp_terms t3, wp_term_taxonomy tt3, wp_term_relationship \n\ntr3" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1011/" ]
28,202
<p>Every time I create a new project I copy the last project's ant file to the new one and make the appropriate changes (trying at the same time to make it more flexible for the next project). But since I didn't really thought about it at the beginning, the file started to look really ugly.</p> <p>Do you have an Ant template that can be easily ported in a new project? Any tips/sites for making one?</p> <p>Thank you.</p>
[ { "answer_id": 28448, "author": "Peter Hilton", "author_id": 2670, "author_profile": "https://Stackoverflow.com/users/2670", "pm_score": 4, "selected": true, "text": "<project name=\"myapp\">\n ...\n <target name=\"jar\">\n ...\n <jar jarfile=\"${ant.project.name}.jar\" ...\n <copy todir=\"${war}/WEB-INF/lib\" flatten=\"true\">\n <fileset dir=\"lib\" includes=\"**/*.jar\">\n</copy>\n <!-- Machine-specific property over-rides -->\n<property file=\"/etc/ant/build.properties\" />\n\n<!-- Project-specific property over-rides -->\n<property file=\"build.properties\" />\n\n<!-- Default property values, used if not specified in properties files -->\n<property name=\"jboss.home\" value=\"/usr/share/jboss\" />\n...\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28202", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2644/" ]
28,212
<p>I'm using two different libraries in my project, and both of them supply a basic rectangle <code>struct</code>. The problem with this is that there seems to be no way to insert a conversion between the types, so I can't call a function in one library with the result from a function in the other. If I was the author of either of these, I could create conversions, from the outside, I can't.</p> <p>library a:</p> <pre><code>typedef struct rectangle { sint16 x; sint16 y; uint16 w; uint16 h; } rectangle; </code></pre> <p>library b:</p> <pre><code>class Rect { int x; int y; int width; int height; /* ... */ }; </code></pre> <p>Now, I can't make a converter <code>class</code>, because C++ will only look for a conversion in one step. This is probably a good thing, because there would be a lot of possibilities involving creating new objects of all kinds of types.</p> <p>I can't make an operator that takes the <code>struct</code> from <code>a</code> and supplies an object of the <code>class</code> from <code>b</code>:</p> <pre>foo.cpp:123 error: ‘operator b::Rect(const rectangle&)’ must be a nonstatic member function</pre> <p>So, is there a sensible way around this?</p> <h2>edit:</h2> <p>I should perhaps also point out that I'd really like some solution that makes working with the result seamless, since I don't expect to be that coder. (Though I agree, old-school, explicit, conversion would have been a good choice. The other branch, <a href="http://en.cppreference.com/w/cpp/language/reinterpret_cast" rel="nofollow noreferrer"><code>reinterpret_cast</code></a> has the same problem..)</p> <h2>edit2:</h2> <p>Actually, none of the suggestions really answer my actual question, <a href="https://stackoverflow.com/users/1968/konrad-rudolph">Konrad Rudolph</a> seems to be correct. C++ actually can't do this. Sucks, but true. (If it makes any difference, I'm going to try subclassing as suggested by <a href="https://stackoverflow.com/users/90/codingthewheel">CodingTheWheel</a>.</p>
[ { "answer_id": 28226, "author": "Stu", "author_id": 414, "author_profile": "https://Stackoverflow.com/users/414", "pm_score": 0, "selected": false, "text": "struct reinterpret_cast" }, { "answer_id": 28232, "author": "mmattax", "author_id": 1638, "author_profile": "https://Stackoverflow.com/users/1638", "pm_score": 0, "selected": false, "text": "\nprivate Rect* convert(const rectangle& src)\n{\n return new Rect(src.x,src.y,src.w,src.h);\n}\nint main()\n{\n rectangle r;\n r.x = 1;\n r.y = 2;\n r.w = 3;\n r.h = 4;\n\n Rect* foo = convert(&r);\n ...\n delete foo;\n\n}\n" }, { "answer_id": 28240, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "RectangleEx class rect Rectangle" }, { "answer_id": 28246, "author": "Kristopher Johnson", "author_id": 1175, "author_profile": "https://Stackoverflow.com/users/1175", "pm_score": 2, "selected": false, "text": "class R\n{\npublic:\n R(const rectangle& r) { ... };\n R(const Rect& r) { ... };\n\n operator rectangle() const { return ...; }\n operator Rect() const { return ...; }\n\nprivate:\n ...\n};\n rectangle R()" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1421/" ]
28,219
<p>Can I get a 'when to use' for these and others? </p> <pre><code>&lt;% %&gt; &lt;%# EVAL() %&gt; </code></pre> <p>Thanks</p>
[ { "answer_id": 28227, "author": "Brian Warshaw", "author_id": 1344, "author_profile": "https://Stackoverflow.com/users/1344", "pm_score": 2, "selected": false, "text": "<%= Class.Method() %>" }, { "answer_id": 28263, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 2, "selected": false, "text": "<%$ Resources:resource, welcome%>\n" }, { "answer_id": 8488412, "author": "sevenkul", "author_id": 931378, "author_profile": "https://Stackoverflow.com/users/931378", "pm_score": 1, "selected": false, "text": "<%: \"<script>alert('Hello XSS')</script>\" %> \n <%= Html.Encode(\"<script>alert('Hello XSS')</script>\")%> \n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1293/" ]
28,224
<p>Is there a way to run a regexp-string replace on the current line in the bash?</p> <p>I find myself rather often in the situation, where I have typed a long commandline and then realize, that I would like to change a word somewhere in the line.</p> <p>My current approach is to finish the line, press <kbd>Ctrl</kbd>+<kbd>A</kbd> (to get to the start of the line), insert a # (to comment out the line), press enter and then use the <code>^oldword^newword</code> syntax (<code>^oldword^newword</code> executes the previous command after substituting oldword by newword).</p> <p>But there has to be a better (faster) way to achieve this. (The mouse is not possible, since I am in an ssh-sessions most of the time).</p> <p>Probably there is some emacs-like key-command for this, that I don't know about.</p> <p>Edit: I have tried using vi-mode. Something strange happened. Although I am a loving vim-user, I had serious trouble using my beloved bash. All those finger-movements, that have been burned into my subconscious suddenly stopped working. I quickly returned to emacs-mode and considered, giving emacs a try as my favorite editor (although I guess, the same thing might happen again).</p>
[ { "answer_id": 113250, "author": "Zak Johnson", "author_id": 17052, "author_profile": "https://Stackoverflow.com/users/17052", "pm_score": 2, "selected": true, "text": "~/.inputrc \"\\C-x6\": \"\\C-a#\\C-m^\"\n\"\\C-x7\": \"\\C-m\\C-P\\C-a\\C-d\\C-m\"\n .inputrc C-x C-r ls abcxyz # ^ xyz^def" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1870/" ]
28,235
<p>Using <a href="http://www.oracle.com/technology/products/jdev" rel="noreferrer">JDeveloper</a>, I started developing a set of web pages for a project at work. Since I didn't know much about JDev at the time, I ran over to Oracle to follow some tutorials. The JDev tutorials recommended doing <a href="http://www.fileinfo.net/extension/jspx" rel="noreferrer">JSPX</a> instead of <a href="https://java.sun.com/products/jsp" rel="noreferrer">JSP</a>, but didn't really explain why. Are you developing JSPX pages? Why did you decide to do so? What are the pros/cons of going the JSPX route? </p>
[ { "answer_id": 28472, "author": "Peter Hilton", "author_id": 2670, "author_profile": "https://Stackoverflow.com/users/2670", "pm_score": 7, "selected": true, "text": "<script type=\"text/javascript\">\n if (number &lt; 0) {\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
28,243
<p>I'm trying to install some Ruby Gems so I can use Ruby to notify me when I get twitter messages. However, after doing a <code>gem update --system</code>, I now get a zlib error every time I try and do a <code>gem install</code> of anything. below is the console output I get when trying to install ruby gems. (along with the output from <code>gem environment</code>).</p> <pre><code>C:\data\ruby&gt;gem install twitter ERROR: While executing gem ... (Zlib::BufError) buffer error C:\data\ruby&gt;gem update --system Updating RubyGems ERROR: While executing gem ... (Zlib::BufError) buffer error C:\data\ruby&gt;gem environment RubyGems Environment: - RUBYGEMS VERSION: 1.2.0 - RUBY VERSION: 1.8.6 (2007-03-13 patchlevel 0) [i386-mswin32] - INSTALLATION DIRECTORY: c:/ruby/lib/ruby/gems/1.8 - RUBY EXECUTABLE: c:/ruby/bin/ruby.exe - EXECUTABLE DIRECTORY: c:/ruby/bin - RUBYGEMS PLATFORMS: - ruby - x86-mswin32-60 - GEM PATHS: - c:/ruby/lib/ruby/gems/1.8 - GEM CONFIGURATION: - :update_sources =&gt; true - :verbose =&gt; true - :benchmark =&gt; false - :backtrace =&gt; false - :bulk_threshold =&gt; 1000 - REMOTE SOURCES: - http://gems.rubyforge.org/ </code></pre>
[ { "answer_id": 109708, "author": "srboisvert", "author_id": 6805, "author_profile": "https://Stackoverflow.com/users/6805", "pm_score": 3, "selected": true, "text": "gem update --system\n" }, { "answer_id": 110496, "author": "Asaf Bartov", "author_id": 7483, "author_profile": "https://Stackoverflow.com/users/7483", "pm_score": 1, "selected": false, "text": "gem" }, { "answer_id": 3649716, "author": "azproduction", "author_id": 440419, "author_profile": "https://Stackoverflow.com/users/440419", "pm_score": 1, "selected": false, "text": "gem update --system ruby/bin/zlib1.dll zlib.dll RUBY_DIR\\lib\\ruby\\site_ruby\\1.8\\rubygems.rb def self.gunzip(data) def self.gunzip(data)\n require 'stringio'\n require 'zlib'\n data = StringIO.new data\n\n # Zlib::GzipReader.new(data).read\n data.read(10) # skip the gzip header\n zis = Zlib::Inflate.new(-Zlib::MAX_WBITS)\n is = StringIO.new(zis.inflate(data.read))\n end\n" }, { "answer_id": 5802588, "author": "Martin Vahi", "author_id": 727022, "author_profile": "https://Stackoverflow.com/users/727022", "pm_score": 2, "selected": false, "text": "echo $PATH\n export PATH=\"/home/scoobydoo/ourcompiledruby/bin:/usr/bin\"\n export PATH=\"/usr/bin:/home/scoobydoo/ourcompiledruby/bin\"\n export PATH=\"/home/scoobydoo/ourcompiledruby/bin:$PATH\"\n mkdir /home/scoobydoo/ourcompiledruby\nmkdir -p /home/scoobydoo/lib/our_gems\n export PATH=\"/home/scoobydoo/ourcompiledruby/bin:$PATH\"\nexport GEM_HOME=\"/home/scoobydoo/lib/our_gems\"\n bash\n apt-get install zlibc zlib1g-dev zlib1g\n ./configure --prefix=/home/scoobydoo/ourcompiledruby\nmake\nmake install\n which ruby\n /home/scoobydoo/ourcompiledruby/bin/ruby\n ruby --help\n ruby `which gem` install rake\nruby `which irb`\n ruby `which gem` install rake\n alias gem=\"`which ruby` `which gem` \"\nalias irb=\"`which ruby` `which irb` \"\n alias irb=\"`which ruby` -KU \"\n" }, { "answer_id": 11721575, "author": "user3931649", "author_id": 3931649, "author_profile": "https://Stackoverflow.com/users/3931649", "pm_score": 2, "selected": false, "text": "ruby extendconf.rb make make install" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1726/" ]
28,256
<p>I've developed an equation parser using a simple stack algorithm that will handle binary (+, -, |, &amp;, *, /, etc) operators, unary (!) operators, and parenthesis.</p> <p>Using this method, however, leaves me with everything having the same precedence - it's evaluated left to right regardless of operator, although precedence can be enforced using parenthesis.</p> <p>So right now &quot;1+11*5&quot; returns 60, not 56 as one might expect.</p> <p>While this is suitable for the current project, I want to have a general purpose routine I can use for later projects.</p> <p><strong>Edited for clarity:</strong></p> <p>What is a good algorithm for parsing equations with precedence?</p> <p>I'm interested in something simple to implement and understand that I can code myself to avoid licensing issues with available code.</p> <p><strong>Grammar:</strong></p> <p>I don't understand the grammar question - I've written this by hand. It's simple enough that I don't see the need for YACC or Bison. I merely need to calculate strings with equations such as &quot;2+3 * (42/13)&quot;.</p> <p><strong>Language:</strong></p> <p>I'm doing this in C, but I'm interested in an algorithm, not a language specific solution. C is low level enough that it'll be easy to convert to another language should the need arise.</p> <p><strong>Code Example</strong></p> <p>I posted the <a href="http://web.archive.org/web/20171012060859/http://www.ubasics.com/simple_c_equation_parser" rel="noreferrer">test code for the simple expression parser</a> I was talking about above. The project requirements altered and so I never needed to optimize the code for performance or space as it wasn't incorporated into the project. It's in the original verbose form, and should be readily understandable. If I do anything further with it in terms of operator precedence, I'll probably choose <a href="https://stackoverflow.com/questions/28256/equation-expression-parser-with-precedence/783132#783132">the macro hack</a> because it matches the rest of the program in simplicity. If I ever use this in a real project, though, I'll be going for a more compact/speedy parser.</p> <p><strong>Related question</strong></p> <blockquote> <p><a href="https://stackoverflow.com/questions/114586/smart-design-of-a-math-parser">Smart design of a math parser?</a></p> </blockquote> <p>-Adam</p>
[ { "answer_id": 28272, "author": "OysterD", "author_id": 2638, "author_profile": "https://Stackoverflow.com/users/2638", "pm_score": 4, "selected": false, "text": "<Exp> ::= <Exp> + <Term> |\n <Exp> - <Term> |\n <Term>\n\n<Term> ::= <Term> * <Factor> |\n <Term> / <Factor> |\n <Factor>\n\n<Factor> ::= x | y | ... |\n ( <Exp> ) |\n - <Factor> |\n <Number>\n <Exp> :: <Leaf> | <Exp> <Op> <Leaf>\n\n<Op> :: + | - | * | /\n\n<Leaf> :: <Number> | (<Exp>)\n" }, { "answer_id": 29124, "author": "Jared Updike", "author_id": 2543, "author_profile": "https://Stackoverflow.com/users/2543", "pm_score": 7, "selected": true, "text": "1+11*5\n 1 11 11 * 5 1 + (11 * 5) 11 aexpr = expr `chainl1` toOp\nexpr = optChainl1 term addop (toScalar 0)\nterm = factor `chainl1` mulop\nfactor = sexpr `chainr1` powop\nsexpr = parens aexpr\n <|> scalar\n <|> ident\n\npowop = sym \"^\" >>= return . (B Pow)\n <|> sym \"^-\" >>= return . (\\x y -> B Pow x (B Sub (toScalar 0) y))\n\ntoOp = sym \"->\" >>= return . (B To)\n\nmulop = sym \"*\" >>= return . (B Mul)\n <|> sym \"/\" >>= return . (B Div)\n <|> sym \"%\" >>= return . (B Mod)\n <|> return . (B Mul)\n\naddop = sym \"+\" >>= return . (B Add) \n <|> sym \"-\" >>= return . (B Sub)\n\nscalar = number >>= return . toScalar\n\nident = literal >>= return . Lit\n\nparens p = do\n lparen\n result <- p\n rparen\n return result\n" }, { "answer_id": 47717, "author": "Pramod", "author_id": 1386292, "author_profile": "https://Stackoverflow.com/users/1386292", "pm_score": 7, "selected": false, "text": "* * +" }, { "answer_id": 114961, "author": "bart", "author_id": 19966, "author_profile": "https://Stackoverflow.com/users/19966", "pm_score": 4, "selected": false, "text": "// operator table\nvar ops = {\n '+' : {op: '+', precedence: 10, assoc: 'L', exec: function(l,r) { return l+r; } },\n '-' : {op: '-', precedence: 10, assoc: 'L', exec: function(l,r) { return l-r; } },\n '*' : {op: '*', precedence: 20, assoc: 'L', exec: function(l,r) { return l*r; } },\n '/' : {op: '/', precedence: 20, assoc: 'L', exec: function(l,r) { return l/r; } },\n '**' : {op: '**', precedence: 30, assoc: 'R', exec: function(l,r) { return Math.pow(l,r); } }\n};\n\n// constants or variables\nvar vars = { e: Math.exp(1), pi: Math.atan2(1,1)*4 };\n\n// input for parsing\n// var r = { string: '123.45+33*8', offset: 0 };\n// r is passed by reference: any change in r.offset is returned to the caller\n// functions return the parsed/calculated value\nfunction parseVal(r) {\n var startOffset = r.offset;\n var value;\n var m;\n // floating point number\n // example of parsing (\"lexing\") without aid of regular expressions\n value = 0;\n while(\"0123456789\".indexOf(r.string.substr(r.offset, 1)) >= 0 && r.offset < r.string.length) r.offset++;\n if(r.string.substr(r.offset, 1) == \".\") {\n r.offset++;\n while(\"0123456789\".indexOf(r.string.substr(r.offset, 1)) >= 0 && r.offset < r.string.length) r.offset++;\n }\n if(r.offset > startOffset) { // did that work?\n // OK, so I'm lazy...\n return parseFloat(r.string.substr(startOffset, r.offset-startOffset));\n } else if(r.string.substr(r.offset, 1) == \"+\") { // unary plus\n r.offset++;\n return parseVal(r);\n } else if(r.string.substr(r.offset, 1) == \"-\") { // unary minus\n r.offset++;\n return negate(parseVal(r));\n } else if(r.string.substr(r.offset, 1) == \"(\") { // expression in parens\n r.offset++; // eat \"(\"\n value = parseExpr(r);\n if(r.string.substr(r.offset, 1) == \")\") {\n r.offset++;\n return value;\n }\n r.error = \"Parsing error: ')' expected\";\n throw 'parseError';\n } else if(m = /^[a-z_][a-z0-9_]*/i.exec(r.string.substr(r.offset))) { // variable/constant name \n // sorry for the regular expression, but I'm too lazy to manually build a varname lexer\n var name = m[0]; // matched string\n r.offset += name.length;\n if(name in vars) return vars[name]; // I know that thing!\n r.error = \"Semantic error: unknown variable '\" + name + \"'\";\n throw 'unknownVar'; \n } else {\n if(r.string.length == r.offset) {\n r.error = 'Parsing error at end of string: value expected';\n throw 'valueMissing';\n } else {\n r.error = \"Parsing error: unrecognized value\";\n throw 'valueNotParsed';\n }\n }\n}\n\nfunction negate (value) {\n return -value;\n}\n\nfunction parseOp(r) {\n if(r.string.substr(r.offset,2) == '**') {\n r.offset += 2;\n return ops['**'];\n }\n if(\"+-*/\".indexOf(r.string.substr(r.offset,1)) >= 0)\n return ops[r.string.substr(r.offset++, 1)];\n return null;\n}\n\nfunction parseExpr(r) {\n var stack = [{precedence: 0, assoc: 'L'}];\n var op;\n var value = parseVal(r); // first value on the left\n for(;;){\n op = parseOp(r) || {precedence: 0, assoc: 'L'}; \n while(op.precedence < stack[stack.length-1].precedence ||\n (op.precedence == stack[stack.length-1].precedence && op.assoc == 'L')) { \n // precedence op is too low, calculate with what we've got on the left, first\n var tos = stack.pop();\n if(!tos.exec) return value; // end reached\n // do the calculation (\"reduce\"), producing a new value\n value = tos.exec(tos.value, value);\n }\n // store on stack and continue parsing (\"shift\")\n stack.push({op: op.op, precedence: op.precedence, assoc: op.assoc, exec: op.exec, value: value});\n value = parseVal(r); // value on the right\n }\n}\n\nfunction parse (string) { // wrapper\n var r = {string: string, offset: 0};\n try {\n var value = parseExpr(r);\n if(r.offset < r.string.length){\n r.error = 'Syntax error: junk found at offset ' + r.offset;\n throw 'trailingJunk';\n }\n return value;\n } catch(e) {\n alert(r.error + ' (' + e + '):\\n' + r.string.substr(0, r.offset) + '<*>' + r.string.substr(r.offset));\n return;\n } \n}\n" }, { "answer_id": 783132, "author": "Adam Davis", "author_id": 2915, "author_profile": "https://Stackoverflow.com/users/2915", "pm_score": 3, "selected": false, "text": "#include <stdio.h>\nint main(int argc, char *argv[]){\n printf(\"((((\");\n for(int i=1;i!=argc;i++){\n if(argv[i] && !argv[i][1]){\n switch(argv[i]){\n case '^': printf(\")^(\"); continue;\n case '*': printf(\"))*((\"); continue;\n case '/': printf(\"))/((\"); continue;\n case '+': printf(\")))+(((\"); continue;\n case '-': printf(\")))-(((\"); continue;\n }\n }\n printf(\"%s\", argv[i]);\n }\n printf(\"))))\\n\");\n return 0;\n}\n $ cc -o parenthesise parenthesise.c\n$ ./parenthesise a \\* b + c ^ d / e\n((((a))*((b)))+(((c)^(d))/((e))))\n" }, { "answer_id": 799702, "author": "Zifre", "author_id": 83871, "author_profile": "https://Stackoverflow.com/users/83871", "pm_score": 3, "selected": false, "text": "group = '(' >> expression >> ')';\nfactor = integer | group;\nterm = factor >> *(('*' >> factor) | ('/' >> factor));\nexpression = term >> *(('+' >> term) | ('-' >> term));\n" }, { "answer_id": 1377838, "author": "PaulMcG", "author_id": 165216, "author_profile": "https://Stackoverflow.com/users/165216", "pm_score": 2, "selected": false, "text": "infixNotation operatorPrecedence" }, { "answer_id": 22297417, "author": "Josh S", "author_id": 1137626, "author_profile": "https://Stackoverflow.com/users/1137626", "pm_score": 1, "selected": false, "text": "#lang racket\n;cool the algorithm fits in 100 lines!\n(define MIN-PREC -10000)\n;format (pre prec name) (left prec name) (right prec name) (nonassoc prec name) (post prec name) (data name) (grouped exp)\n;for example \"not a*-7+5 < b*b or c >= 4\"\n;which groups as: not ((((a*(-7))+5) < (b*b)) or (c >= 4))\"\n;is represented as '((pre 0 not)(data a)(left 4 *)(pre 5 -)(data 7)(left 3 +)(data 5)(nonassoc 2 <)(data b)(left 4 *)(data b)(right 1 or)(data c)(nonassoc 2 >=)(data 4)) \n;higher numbers are higher precedence\n;\"(a+b)*c\" is represented as ((grouped (data a)(left 3 +)(data b))(left 4 *)(data c))\n\n(struct prec-parse ([data-stack #:mutable #:auto]\n [op-stack #:mutable #:auto])\n #:auto-value '())\n\n(define (pop-data stacks)\n (let [(data (car (prec-parse-data-stack stacks)))]\n (set-prec-parse-data-stack! stacks (cdr (prec-parse-data-stack stacks)))\n data))\n\n(define (pop-op stacks)\n (let [(op (car (prec-parse-op-stack stacks)))]\n (set-prec-parse-op-stack! stacks (cdr (prec-parse-op-stack stacks)))\n op))\n\n(define (push-data! stacks data)\n (set-prec-parse-data-stack! stacks (cons data (prec-parse-data-stack stacks))))\n\n(define (push-op! stacks op)\n (set-prec-parse-op-stack! stacks (cons op (prec-parse-op-stack stacks))))\n\n(define (process-prec min-prec stacks)\n (let [(op-stack (prec-parse-op-stack stacks))]\n (cond ((not (null? op-stack))\n (let [(op (car op-stack))]\n (cond ((>= (cadr op) min-prec) \n (apply-op op stacks)\n (set-prec-parse-op-stack! stacks (cdr op-stack))\n (process-prec min-prec stacks))))))))\n\n(define (process-nonassoc min-prec stacks)\n (let [(op-stack (prec-parse-op-stack stacks))]\n (cond ((not (null? op-stack))\n (let [(op (car op-stack))]\n (cond ((> (cadr op) min-prec) \n (apply-op op stacks)\n (set-prec-parse-op-stack! stacks (cdr op-stack))\n (process-nonassoc min-prec stacks))\n ((= (cadr op) min-prec) (error \"multiply applied non-associative operator\"))\n ))))))\n\n(define (apply-op op stacks)\n (let [(op-type (car op))]\n (cond ((eq? op-type 'post)\n (push-data! stacks `(,op ,(pop-data stacks) )))\n (else ;assume infix\n (let [(tos (pop-data stacks))]\n (push-data! stacks `(,op ,(pop-data stacks) ,tos))))))) \n\n(define (finish input min-prec stacks)\n (process-prec min-prec stacks)\n input\n )\n\n(define (post input min-prec stacks)\n (if (null? input) (finish input min-prec stacks)\n (let* [(cur (car input))\n (input-type (car cur))]\n (cond ((eq? input-type 'post)\n (cond ((< (cadr cur) min-prec)\n (finish input min-prec stacks))\n (else \n (process-prec (cadr cur)stacks)\n (push-data! stacks (cons cur (list (pop-data stacks))))\n (post (cdr input) min-prec stacks))))\n (else (let [(handle-infix (lambda (proc-fn inc)\n (cond ((< (cadr cur) min-prec)\n (finish input min-prec stacks))\n (else \n (proc-fn (+ inc (cadr cur)) stacks)\n (push-op! stacks cur)\n (start (cdr input) min-prec stacks)))))]\n (cond ((eq? input-type 'left) (handle-infix process-prec 0))\n ((eq? input-type 'right) (handle-infix process-prec 1))\n ((eq? input-type 'nonassoc) (handle-infix process-nonassoc 0))\n (else error \"post op, infix op or end of expression expected here\"))))))))\n\n;alters the stacks and returns the input\n(define (start input min-prec stacks)\n (if (null? input) (error \"expression expected\")\n (let* [(cur (car input))\n (input-type (car cur))]\n (set! input (cdr input))\n ;pre could clearly work with new stacks, but could it reuse the current one?\n (cond ((eq? input-type 'pre)\n (let [(new-stack (prec-parse))]\n (set! input (start input (cadr cur) new-stack))\n (push-data! stacks \n (cons cur (list (pop-data new-stack))))\n ;we might want to assert here that the cdr of the new stack is null\n (post input min-prec stacks)))\n ((eq? input-type 'data)\n (push-data! stacks cur)\n (post input min-prec stacks))\n ((eq? input-type 'grouped)\n (let [(new-stack (prec-parse))]\n (start (cdr cur) MIN-PREC new-stack)\n (push-data! stacks (pop-data new-stack)))\n ;we might want to assert here that the cdr of the new stack is null\n (post input min-prec stacks))\n (else (error \"bad input\"))))))\n\n(define (op-parse input)\n (let [(stacks (prec-parse))]\n (start input MIN-PREC stacks)\n (pop-data stacks)))\n\n(define (main)\n (op-parse (read)))\n\n(main)\n" }, { "answer_id": 46722767, "author": "user4617883", "author_id": 4617883, "author_profile": "https://Stackoverflow.com/users/4617883", "pm_score": 1, "selected": false, "text": "public class ExpressionParser {\n\npublic double eval(String exp){\n int bracketCounter = 0;\n int operatorIndex = -1;\n\n for(int i=0; i<exp.length(); i++){\n char c = exp.charAt(i);\n if(c == '(') bracketCounter++;\n else if(c == ')') bracketCounter--;\n else if((c == '+' || c == '-') && bracketCounter == 0){\n operatorIndex = i;\n break;\n }\n else if((c == '*' || c == '/') && bracketCounter == 0 && operatorIndex < 0){\n operatorIndex = i;\n }\n }\n if(operatorIndex < 0){\n exp = exp.trim();\n if(exp.charAt(0) == '(' && exp.charAt(exp.length()-1) == ')')\n return eval(exp.substring(1, exp.length()-1));\n else\n return Double.parseDouble(exp);\n }\n else{\n switch(exp.charAt(operatorIndex)){\n case '+':\n return eval(exp.substring(0, operatorIndex)) + eval(exp.substring(operatorIndex+1));\n case '-':\n return eval(exp.substring(0, operatorIndex)) - eval(exp.substring(operatorIndex+1));\n case '*':\n return eval(exp.substring(0, operatorIndex)) * eval(exp.substring(operatorIndex+1));\n case '/':\n return eval(exp.substring(0, operatorIndex)) / eval(exp.substring(operatorIndex+1));\n }\n }\n return 0;\n}\n" }, { "answer_id": 48446000, "author": "Viktor Shepel", "author_id": 8244545, "author_profile": "https://Stackoverflow.com/users/8244545", "pm_score": 1, "selected": false, "text": "#include <stdio.h>\n#include <ctype.h>\n\n/*\n * expression -> sum\n * sum -> product | product \"+\" sum\n * product -> term | term \"*\" product\n * term -> number | expression\n * number -> [0..9]+\n */\n\ntypedef struct {\n int value;\n const char* context;\n} expression_t;\n\nexpression_t expression(int value, const char* context) {\n return (expression_t) { value, context };\n}\n\n/* begin: parsers */\n\nexpression_t eval_expression(const char* symbols);\n\nexpression_t eval_number(const char* symbols) {\n // number -> [0..9]+\n double number = 0; \n while (isdigit(*symbols)) {\n number = 10 * number + (*symbols - '0');\n symbols++;\n }\n return expression(number, symbols);\n}\n\nexpression_t eval_term(const char* symbols) {\n // term -> number | expression\n expression_t number = eval_number(symbols);\n return number.context != symbols ? number : eval_expression(symbols);\n}\n\nexpression_t eval_product(const char* symbols) {\n // product -> term | term \"*\" product\n expression_t term = eval_term(symbols);\n if (*term.context != '*')\n return term;\n\n expression_t product = eval_product(term.context + 1);\n return expression(term.value * product.value, product.context);\n}\n\nexpression_t eval_sum(const char* symbols) {\n // sum -> product | product \"+\" sum\n expression_t product = eval_product(symbols);\n if (*product.context != '+')\n return product;\n\n expression_t sum = eval_sum(product.context + 1);\n return expression(product.value + sum.value, sum.context);\n}\n\nexpression_t eval_expression(const char* symbols) {\n // expression -> sum\n return eval_sum(symbols);\n}\n\n/* end: parsers */\n\nint main() {\n const char* expression = \"1+11*5\";\n printf(\"eval(\\\"%s\\\") == %d\\n\", expression, eval_expression(expression).value);\n\n return 0;\n}\n number -> [0..9]+\n number sum \"*\" sum sum -> number | sum \"+\" sum\n number sum \"+\" sum number \"+\" number [0..9]+ \"+\" [0..9]+ 1+8 sum \"+\" sum number \"+\" sum number \"+\" sum \"+\" sum number \"+\" sum \"+\" number number \"+\" number \"+\" number 12+3+5 expression -> sum\nsum -> difference | difference \"+\" sum\ndifference -> product | difference \"-\" product\nproduct -> fraction | fraction \"*\" product\nfraction -> term | fraction \"/\" term\nterm -> \"(\" expression \")\" | number\nnumber -> digit+ \n * + product sum expression_t eval_product(const char* symbols) {\n // product -> term | term \"*\" product\n expression_t term = eval_term(symbols);\n if (*term.context != '*')\n return term;\n\n expression_t product = eval_product(term.context + 1);\n return expression(term.value * product.value, product.context);\n}\n term * term.value * product.value term \"*\" product" }, { "answer_id": 64399150, "author": "Charles Owen", "author_id": 4151175, "author_profile": "https://Stackoverflow.com/users/4151175", "pm_score": 0, "selected": false, "text": " internal double Compute(string sequence)\n {\n int priority = 0;\n int sequenceCount = sequence.Length; \n for (int i = 0; i < sequenceCount; i++) {\n char s = sequence[i]; \n if (Char.IsDigit(s)) {\n double value = ParseNextNumber(sequence, i);\n numberStack.Push(value);\n i = i + value.ToString().Length - 1;\n } else if (s == '+' || s == '-' || s == '*' || s == '/') { \n Operator op = ParseNextOperator(sequence, i, priority);\n CollapseTop(op, numberStack, operatorStack);\n operatorStack.Push(op);\n } if (s == '(') { priority++; ; continue; }\n else if (s == ')') { priority--; continue; }\n }\n if (priority != 0) { throw new ApplicationException(\"Parens not balanced\"); }\n CollapseTop(new Operator(' ', 0), numberStack, operatorStack);\n if (numberStack.Count == 1 && operatorStack.Count == 0) {\n return numberStack.Pop();\n }\n return 0;\n } \n Calculator c = new Calculator();\ndouble value = c.Compute(\"89.8+((9*3)+8)+(9*2)+1\");\nConsole.WriteLine(string.Format(\"The sum of the expression is: {0}\", (float)value));\n//prints out The sum of the expression is: 143.8\n" }, { "answer_id": 68577842, "author": "Carson", "author_id": 9935654, "author_profile": "https://Stackoverflow.com/users/9935654", "pm_score": 0, "selected": false, "text": "function Parse(str) {\n try {\n return parseExpr(str.replaceAll(\" \", \"\")) // Implement? See full code.\n } catch (e) {\n alert(e.message)\n }\n}\n\nParse(\"123.45+3*22*4\")\n const testArray = [\n // Basic Test\n [\"(3+5)*4\", \"\"],\n [\"123.45+3*22*4\", \"\"],\n [\"8%2\", \"\"],\n [\"8%3\", \"\"],\n [\"7/3\", \"\"],\n [\"2*pi*e\", 2 * Math.atan2(0, -1) * Math.exp(1)],\n [\"2**3\", \"\"],\n\n // unary Test\n [\"3+(-5)\", \"\"],\n [\"3+(+5)\", \"\"],\n\n // Function Test\n [\"pow{2,3}*2\", 16],\n [\"4*sqrt{16}\", 16],\n [\"round{3.4}\", 3],\n [\"round{3.5}\", 4],\n [\"((1+e)*3/round{3.5})%2\", ((1 + Math.exp(1)) * 3 / Math.round(3.5)) % 2],\n [\"round{3.5}+pow{2,3}\", Math.round(3.5)+Math.pow(2,3)],\n]\n // Main\n(() => {\n window.onload = () => {\n const nativeConsoleLogFunc = window.console.error\n window.console.error = (...data) => { // Override native function, just for test.\n const range = document.createRange()\n const frag = range.createContextualFragment(`<div>${data}</div>`)\n document.querySelector(\"body\").append(frag)\n nativeConsoleLogFunc(...data)\n }\n\n // Add Enter event\n document.querySelector(`input`).onkeyup = (keyboardEvent) => {\n if (keyboardEvent.key === \"Enter\") {\n const result = Parse(document.getElementById('expr').value)\n if (result !== undefined) {\n alert(result)\n }\n }\n }\n\n const testArray = [\n // Basic Test\n [\"(3+5)*4\", \"\"],\n [\"123.45+3*22*4\", \"\"],\n [\"8%2\", \"\"],\n [\"8%3\", \"\"],\n [\"7/3\", \"\"],\n [\"2*pi*e\", 2 * Math.atan2(0, -1) * Math.exp(1)],\n [\"2**3\", \"\"],\n\n // unary\n [\"3+(-5)\", \"\"],\n [\"3+(+5)\", \"\"],\n\n // Function Test\n [\"pow{2,3}*2\", 16],\n [\"4*sqrt{16}\", 16],\n [\"round{3.4}\", 3],\n [\"round{3.5}\", 4],\n [\"((1+e)*3/round{3.5})%2\", ((1 + Math.exp(1)) * 3 / Math.round(3.5)) % 2],\n [\"round{3.5}+pow{2,3}\", Math.round(3.5) + Math.pow(2, 3)],\n\n // error test\n [\"21+\", ValueMissingError],\n [\"21+*\", ParseError],\n [\"(1+2\", ParseError], // miss \")\"\n [\"round(3.12)\", MissingParaError], // should be round{3.12}\n [\"help\", UnknownVarError],\n ]\n\n for (let [testString, expected] of testArray) {\n if (expected === \"\") {\n expected = eval(testString) // Why don't you use eval instead of writing the function yourself? Because the browser may disable eval due to policy considerations. [CSP](https://content-security-policy.com/)\n }\n const actual = Parse(testString, false)\n\n if (actual !== expected) {\n if (actual instanceof Error && actual instanceof expected) {\n continue\n }\n console.error(`${testString} = ${actual}, value <code>${expected}</code> expected`)\n }\n }\n }\n})()\n\n// Script\nclass UnknownVarError extends Error {\n}\n\nclass ValueMissingError extends Error {\n}\n\nclass ParseError extends Error {\n}\n\nclass MissingParaError extends Error {\n}\n\n/**\n * @description Operator\n * @param {string} sign \"+\", \"-\", \"*\", \"/\", ...\n * @param {number} precedence\n * @param {\"L\"|\"R\"} assoc associativity left or right\n * @param {function} exec\n * */\nfunction Op(sign, precedence, assoc, exec = undefined) {\n this.sign = sign\n this.precedence = precedence\n this.assoc = assoc\n this.exec = exec\n}\n\nconst OpArray = [\n new Op(\"+\", 10, \"L\", (l, r) => l + r),\n new Op(\"-\", 10, \"L\", (l, r) => l - r),\n new Op(\"*\", 20, \"L\", (l, r) => l * r),\n new Op(\"/\", 20, \"L\", (l, r) => l / r),\n new Op(\"%\", 20, \"L\", (l, r) => l % r),\n new Op(\"**\", 30, \"R\", (l, r) => Math.pow(l, r))\n]\n\nconst VarTable = {\n e: Math.exp(1),\n pi: Math.atan2(0, -1), // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/atan2\n pow: (x, y) => Math.pow(x, y),\n sqrt: (x) => Math.sqrt(x),\n round: (x) => Math.round(x),\n}\n\n/**\n * @param {Op} op\n * @param {Number} value\n * */\nfunction Item(op, value = undefined) {\n this.op = op\n this.value = value\n}\n\nclass Stack extends Array {\n constructor(...items) {\n super(...items)\n this.push(new Item(new Op(\"\", 0, \"L\")))\n }\n\n GetLastItem() {\n return this[this.length - 1] // fast then pop // https://stackoverflow.com/a/61839489/9935654\n }\n}\n\nfunction Cursor(str, pos) {\n this.str = str\n this.pos = pos\n this.MoveRight = (step = 1) => {\n this.pos += step\n }\n this.PeekRightChar = (step = 1) => {\n return this.str.substring(this.pos, this.pos + step)\n }\n\n /**\n * @return {Op}\n * */\n this.MoveToNextOp = () => {\n const opArray = OpArray.sort((a, b) => b.precedence - a.precedence)\n for (const op of opArray) {\n const sign = this.PeekRightChar(op.sign.length)\n if (op.sign === sign) {\n this.MoveRight(op.sign.length)\n return op\n }\n }\n return null\n }\n}\n\n/**\n * @param {Cursor} cursor\n * */\nfunction parseVal(cursor) {\n let startOffset = cursor.pos\n\n const regex = /^(?<OpOrVar>[^\\d.])?(?<Num>[\\d.]*)/g\n const m = regex.exec(cursor.str.substr(startOffset))\n if (m) {\n const {groups: {OpOrVar, Num}} = m\n if (OpOrVar === undefined && Num) {\n cursor.pos = startOffset + Num.length\n\n if (cursor.pos > startOffset) {\n return parseFloat(cursor.str.substring(startOffset, startOffset + cursor.pos - startOffset)) // do not use string.substr() // It will be removed in the future. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features#string_methods\n }\n }\n\n if (\"+-(\".indexOf(OpOrVar) !== -1) {\n cursor.pos++\n switch (OpOrVar) {\n case \"+\": // unary plus, for example: (+5)\n return parseVal(cursor)\n case \"-\":\n return -(parseVal(cursor))\n case \"(\":\n const value = parseExpr(cursor)\n if (cursor.PeekRightChar() === \")\") {\n cursor.MoveRight()\n return value\n }\n throw new ParseError(\"Parsing error: ')' expected\")\n }\n }\n }\n\n\n // below is for Variable or Function\n const match = cursor.str.substring(cursor.pos).match(/^[a-z_][a-z0-9_]*/i) // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match\n\n if (match) {\n // Variable\n const varName = match[0]\n cursor.MoveRight(varName.length)\n const bracket = cursor.PeekRightChar(1)\n if (bracket !== \"{\") {\n if (varName in VarTable) {\n const val = VarTable[varName]\n if (typeof val === \"function\") {\n throw new MissingParaError(`${varName} is a function, it needs big curly brackets`)\n }\n return val\n }\n }\n\n // is function\n const regex = /{(?<Para>[^{]*)}/gm\n const m = regex.exec(cursor.str.substring(cursor.pos))\n if (m && m.groups.Para !== undefined) {\n const paraString = m.groups.Para\n const para = paraString.split(',')\n cursor.MoveRight(paraString.length + 2) // 2 = { + }\n return VarTable[varName](...para)\n }\n throw new UnknownVarError(`unknown variable ${varName}`)\n }\n\n // Handle Error\n if (cursor.str.length === cursor.pos) { // example: 1+2+\n throw new ValueMissingError(`Parsing error at end of string: value expected.`)\n } else { // example: 1+2+*\n throw new ParseError(\"Parsing error: unrecognized value\")\n }\n}\n\n/**\n * @param {string|Cursor} expr\n * */\nfunction parseExpr(expr) {\n const stack = new Stack()\n const cursor = (expr instanceof Cursor) ? expr : new Cursor(expr, 0)\n while (1) {\n let rightValue = parseVal(cursor)\n const op = cursor.MoveToNextOp() ?? new Op(\"\", 0, \"L\")\n\n while (\n op.precedence < stack.GetLastItem().op.precedence ||\n (op.precedence === stack.GetLastItem().op.precedence && op.assoc === 'L')) {\n const lastItem = stack.pop()\n if (!lastItem.op.exec) { // end reached\n return rightValue\n }\n rightValue = lastItem.op.exec(lastItem.value, rightValue)\n }\n\n stack.push(new Item(op, rightValue))\n }\n}\n\nfunction Parse(str, alertError = true) {\n try {\n return parseExpr(str.replaceAll(\" \", \"\"))\n } catch (e) {\n if (alertError) {\n alert(e.message)\n return undefined\n }\n return e\n }\n} <input type=\"text\" id=\"expr\" name=\"expr\" placeholder=\"123.45+3*22*4\">\n<button onclick=\"const x = Parse(document.getElementById('expr').value); if(x != null) alert(x);\">\n Calculate!\n</button>" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28256", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2915/" ]
28,293
<p>I have an XML document with a DTD, and would love to be able to access the XML model, something like this:</p> <pre><code>title = Thing.Items[0].Title </code></pre> <p>Is there a way, in Ruby, to generate this kind of object model based on a DTD? Or am I stuck using REXML?</p> <p>Thanks!</p>
[ { "answer_id": 1462093, "author": "David Richards", "author_id": 177363, "author_profile": "https://Stackoverflow.com/users/177363", "pm_score": 1, "selected": false, "text": "require 'rubygems'\nrequire 'activesupport' # For xml-simple\nrequire 'ostruct' \n\nh = Hash.from_xml File.read('some.xml')\no = OpenStruct.new h\no.thing.items[0].title \n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28293", "https://Stackoverflow.com", "https://Stackoverflow.com/users/722/" ]
28,301
<p>I'm unsure whether the following code would ensure all conditions given in Comparator's Javadoc. </p> <pre><code>class TotalOrder&lt;T&gt; implements Comparator&lt;T&gt; { public boolean compare(T o1, T o2) { if (o1 == o2 || equal(o1, o2)) return 0; int h1 = System.identityHashCode(o1); int h2 = System.identityHashCode(o2); if (h1 != h2) { return h1 &lt; h2 ? -1 : 1; } // equals returned false but identity hash code was same, assume o1 == o2 return 0; } boolean equal(Object o1, Object o2) { return o1 == null ? o2 == null : o1.equals(o2); } } </code></pre> <p>Will the code above impose a total ordering on all instances of any class, even if that class does not implement Comparable?</p>
[ { "answer_id": 28394, "author": "Cem Catikkas", "author_id": 3087, "author_profile": "https://Stackoverflow.com/users/3087", "pm_score": 0, "selected": false, "text": "System.identityHashCode(Object) Object.hashCode() Object.equals(Object)" }, { "answer_id": 28439, "author": "nlucaroni", "author_id": 157, "author_profile": "https://Stackoverflow.com/users/157", "pm_score": 1, "selected": false, "text": "return 0 int h1 = System.identityHashCode(o1);\n int h2 = System.identityHashCode(o2);\n if (h1 != h2) {\n return h1 < h2 ? -1 : 1;\n }\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28301", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3071/" ]
28,353
<p>We have a couple of mirrored SQL Server databases.</p> <p>My first problem - the key problem - is to get a notification when the db fails over. I don't <em>need</em> to know because, erm, its mirrored and so it (almost) all carries on working automagically but it would useful to be advised and I'm currently getting failovers when I don't think I should be so it want to know when they occur (without too much digging) to see if I can determine why.</p> <p>I have services running that I could fairly easily use to monitor this - so the alternative question would be "How do I programmatically determine which is the principal and which is the mirror" - preferably in a more intelligent fashion than just attempting to connect each in turn (which would mostly work but...).</p> <p>Thanks, Murph</p> <p>Addendum: </p> <p>One of the answers queries why I don't need to know when it fails over - the answer is that we're developing using ADO.NET and that has automatic failover support, all you have to do is add <code>Failover Partner=MIRRORSERVER</code> (where MIRRORSERVER is the name of your mirror server instance) to your connection string and your code will fail over transparently - you may get some errors depending on what connections are active but in our case very few.</p>
[ { "answer_id": 37116, "author": "Murph", "author_id": 1070, "author_profile": "https://Stackoverflow.com/users/1070", "pm_score": 3, "selected": true, "text": "using System;\nusing System.Data.SqlClient;\n\nnamespace FailoverMonitorConcept\n{\n class Program\n {\n static void Main(string[] args)\n {\n string server = args[0];\n string failover = args[1];\n string database = args[2];\n\n string connStr = string.Format(\"Integrated Security=SSPI;Persist Security Info=True;Data Source={0};Failover Partner={1};Packet Size=4096;Initial Catalog={2}\", server, failover, database);\n string sql = \"EXEC sp_helpserver\";\n\n SqlConnection dc = new SqlConnection(connStr);\n SqlCommand cmd = new SqlCommand(sql, dc);\n Console.WriteLine(\"Connection string: \" + connStr);\n Console.WriteLine(\"Press any key to test, press q to quit\");\n\n string priorServerName = \"\";\n char key = ' ';\n\n while(key.ToString().ToLower() != \"q\")\n {\n dc.Open();\n try\n {\n string serverName = cmd.ExecuteScalar() as string;\n Console.WriteLine(DateTime.Now.ToLongTimeString() + \" - Server name: \" + serverName);\n if (priorServerName == \"\")\n {\n priorServerName = serverName;\n }\n else if (priorServerName != serverName)\n {\n Console.WriteLine(\"***** SERVER CHANGED *****\");\n Console.WriteLine(\"New server: \" + serverName);\n priorServerName = serverName;\n }\n }\n catch (System.Data.SqlClient.SqlException ex)\n {\n Console.WriteLine(\"Error: \" + ex.ToString());\n }\n finally\n {\n dc.Close();\n }\n key = Console.ReadKey(true).KeyChar;\n\n }\n\n Console.WriteLine(\"Finis!\");\n\n }\n }\n}\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1070/" ]
28,369
<p>I'm looking for a "safe" eval function, to implement spreadsheet-like calculations (using numpy/scipy).</p> <p>The functionality to do this (the <a href="http://docs.python.org/lib/module-rexec.html" rel="nofollow noreferrer">rexec module</a>) has been removed from Python since 2.3 due to apparently unfixable security problems. There are several third-party hacks out there that purport to do this - the most thought-out solution that I have found is <a href="http://code.activestate.com/recipes/496746/" rel="nofollow noreferrer">this Python Cookbok recipe</a>, "safe_eval". </p> <p>Am I reasonably safe if I use this (or something similar), to protect from malicious code, or am I stuck with writing my own parser? Does anyone know of any better alternatives?</p> <p>EDIT: I just discovered <a href="http://pypi.python.org/pypi/RestrictedPython" rel="nofollow noreferrer">RestrictedPython</a>, which is part of Zope. Any opinions on this are welcome.</p>
[ { "answer_id": 32028, "author": "Aaron Maenpaa", "author_id": 2603, "author_profile": "https://Stackoverflow.com/users/2603", "pm_score": 3, "selected": true, "text": ">>> names['f'] = open('foo', 'w+')\n>>> safe_eval.safe_eval(\"baz = type(f)('baz', 'w+')\", names)\n>>> names['baz']\n<open file 'baz', mode 'w+' at 0x413da0>\n >>> import compiler\n>>> ast = compiler.parse(\"print 'Hello world!'\")\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28369", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3002/" ]
28,377
<p>In Visual Basic, is there a performance difference when using the <code>IIf</code> function instead of the <code>If</code> statement?</p>
[ { "answer_id": 28421, "author": "Tom Mayfield", "author_id": 2314, "author_profile": "https://Stackoverflow.com/users/2314", "pm_score": 6, "selected": false, "text": "IIf() Module Module1\n Sub Main()\n Dim test As Boolean = False\n Dim result As String = IIf(test, Foo(), Bar())\n End Sub\n\n Public Function Foo() As String\n Console.WriteLine(\"Foo!\")\n Return \"Foo\"\n End Function\n\n Public Function Bar() As String\n Console.WriteLine(\"Bar!\")\n Return \"Bar\"\n End Function\nEnd Module\n Foo!\nBar!\n" }, { "answer_id": 28435, "author": "rjzii", "author_id": 1185, "author_profile": "https://Stackoverflow.com/users/1185", "pm_score": 4, "selected": false, "text": "string results = IIf(Not oraData.IsDBNull(ndx), oraData.GetString(ndx), string.Empty)\n" }, { "answer_id": 28452, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 8, "selected": true, "text": "If ' Usage 1\nDim result = If(a > 5, \"World\", \"Hello\")\n' Usage 2\nDim foo = If(result, \"Alternative\")\n result Nothing \"Alternative\" If IIf If IIf Dim len = If(text Is Nothing, 0, text.Length)\n" }, { "answer_id": 1459868, "author": "Larry", "author_id": 24472, "author_profile": "https://Stackoverflow.com/users/24472", "pm_score": 3, "selected": false, "text": "Dim Keywords = If(String.IsNullOrEmpty(SelectedKeywords), \"N/A\", SelectedKeywords)\n Dim Keywords = IIf(String.IsNullOrEmpty(SelectedKeywords), \"N/A\", SelectedKeywords)\n" }, { "answer_id": 29085777, "author": "titol", "author_id": 4193860, "author_profile": "https://Stackoverflow.com/users/4193860", "pm_score": 1, "selected": false, "text": "Sub main()\n counter = 0\n bln = True\n s = iif(bln, f1, f2)\nEnd Sub\n\nFunction f1 As String\n counter = counter + 1\n Return \"YES\"\nEnd Function\n\nFunction f2 As String\n counter = counter + 1\n Return \"NO\"\nEnd Function\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/299/" ]
28,380
<p>Has anybody managed to get the Android Emulator working behind a proxy that requires authentication?</p> <p>I've tried setting the -http-proxy argument to</p> <pre><code>http://DOMAIN/USERNAME:PASSWORD@IP:PORT </code></pre> <p>but am having no success.</p> <p>I've tried following the docs to no avail. I've also tried the <code>-verbose-proxy</code> setting but this no longer seems to exist.</p> <p>Any pointers?</p>
[ { "answer_id": 28406, "author": "dlamblin", "author_id": 459, "author_profile": "https://Stackoverflow.com/users/459", "pm_score": 2, "selected": false, "text": "http://$USER:[email protected]:80" }, { "answer_id": 40189, "author": "Naseer", "author_id": 907, "author_profile": "https://Stackoverflow.com/users/907", "pm_score": 4, "selected": false, "text": "1. > adb shell\n2. # sqlite3 /data/data/com.android.providers.settings/databases/settings.db\n3. sqlite> INSERT INTO system VALUES(99,’http_proxy', 'proxy:port');\n4. sqlite>.exit\n" }, { "answer_id": 1641977, "author": "Deepak Sarda", "author_id": 143438, "author_profile": "https://Stackoverflow.com/users/143438", "pm_score": 5, "selected": false, "text": "-http-proxy Home > Menu > Settings > Wireless Controls > Mobile Networks > Access Point Names" }, { "answer_id": 3869611, "author": "Sandeep Singh", "author_id": 467571, "author_profile": "https://Stackoverflow.com/users/467571", "pm_score": 7, "selected": true, "text": "Go to \"Settings\" -> \"Wireless & Networks\" -> \"Mobile Networks\" -> \"Access Point Names\" -> \"Telkila\"\n" }, { "answer_id": 5556686, "author": "Taranttini", "author_id": 693547, "author_profile": "https://Stackoverflow.com/users/693547", "pm_score": 3, "selected": false, "text": "androidtool.cfg C:\\Documents and Settings\\YOUR USER NAME\\.android\\ http.proxyLogin=USER@PASSWORD\n" }, { "answer_id": 5648741, "author": "prasad", "author_id": 662336, "author_profile": "https://Stackoverflow.com/users/662336", "pm_score": 2, "selected": false, "text": "emulator -avd <avd name> -http-proxy <server>:<proxy>\n" }, { "answer_id": 29368559, "author": "Shahyad Sharghi", "author_id": 216812, "author_profile": "https://Stackoverflow.com/users/216812", "pm_score": 1, "selected": false, "text": "emulator-x86.exe -http-proxy domain\\user:password@proxyIP:port -avd MyAVD\n emulator-x86.exe -http-proxy 127.0.0.1:3128 -avd MyAVD\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1281/" ]
28,395
<p>How do you pass <code>$_POST</code> values to a page using <code>cURL</code>?</p>
[ { "answer_id": 28411, "author": "Ross", "author_id": 2025, "author_profile": "https://Stackoverflow.com/users/2025", "pm_score": 8, "selected": true, "text": "$data = array('name' => 'Ross', 'php_master' => true);\n\n// You can POST a file by prefixing with an @ (for <input type=\"file\"> fields)\n$data['file'] = '@/home/user/world.jpg';\n\n$handle = curl_init($url);\ncurl_setopt($handle, CURLOPT_POST, true);\ncurl_setopt($handle, CURLOPT_POSTFIELDS, $data);\ncurl_exec($handle);\ncurl_close($handle)\n CURLOPT_POST CURLOPT_POSTFIELDS POST <form> curl_setopt($handle, CURLOPT_POSTFIELDS, $data); $data array() multipart/form-data $data = array('name' => 'Ross', 'php_master' => true);\ncurl_setopt($handle, CURLOPT_POSTFIELDS, $data);\n $data application/x-www-form-urlencoded $data = array('name' => 'Ross', 'php_master' => true);\ncurl_setopt($handle, CURLOPT_POSTFIELDS, http_build_query($data));\n curl_init curl_setopt" }, { "answer_id": 28438, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 5, "selected": false, "text": "$xml = '<?xml version=\"1.0\"?><stuff><child>foo</child><child>bar</child></stuff>';\n$httpRequest = curl_init();\n\ncurl_setopt($httpRequest, CURLOPT_RETURNTRANSFER, 1);\ncurl_setopt($httpRequest, CURLOPT_HTTPHEADER, array(\"Content-Type: text/xml\"));\ncurl_setopt($httpRequest, CURLOPT_POST, 1);\ncurl_setopt($httpRequest, CURLOPT_HEADER, 1);\n\ncurl_setopt($httpRequest, CURLOPT_URL, $url);\ncurl_setopt($httpRequest, CURLOPT_POSTFIELDS, $xml);\n\n$returnHeader = curl_exec($httpRequest);\ncurl_close($httpRequest);\n CURLOPT_RETURNTRANSFER CURLOPT_HEADER" }, { "answer_id": 17662491, "author": "Sapnandu", "author_id": 746270, "author_profile": "https://Stackoverflow.com/users/746270", "pm_score": 2, "selected": false, "text": "$query_string = \"\";\n\nif ($_POST) {\n $kv = array();\n foreach ($_POST as $key => $value) {\n $kv[] = stripslashes($key) . \"=\" . stripslashes($value);\n }\n $query_string = join(\"&\", $kv);\n}\n\nif (!function_exists('curl_init')){\n die('Sorry cURL is not installed!');\n}\n\n$url = 'https://www.abcd.com/servlet/';\n\n$ch = curl_init();\n\ncurl_setopt($ch, CURLOPT_URL, $url);\ncurl_setopt($ch, CURLOPT_POST, count($kv));\ncurl_setopt($ch, CURLOPT_POSTFIELDS, $query_string);\n\ncurl_setopt($ch, CURLOPT_HEADER, FALSE);\ncurl_setopt($ch, CURLOPT_RETURNTRANSFER, FALSE);\ncurl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);\n\n$result = curl_exec($ch);\n\ncurl_close($ch);\n" }, { "answer_id": 20651956, "author": "Mohammad Faisal Islam", "author_id": 1615812, "author_profile": "https://Stackoverflow.com/users/1615812", "pm_score": 0, "selected": false, "text": "<?php\n function executeCurl($arrOptions) {\n\n $mixCH = curl_init();\n\n foreach ($arrOptions as $strCurlOpt => $mixCurlOptValue) {\n curl_setopt($mixCH, $strCurlOpt, $mixCurlOptValue);\n }\n\n $mixResponse = curl_exec($mixCH);\n curl_close($mixCH);\n return $mixResponse;\n }\n\n // If any HTTP authentication is needed.\n $username = 'http-auth-username';\n $password = 'http-auth-password';\n\n $requestType = 'POST'; // This can be PUT or POST\n\n // This is a sample array. You can use $arrPostData = $_POST\n $arrPostData = array(\n 'key1' => 'value-1-for-k1y-1',\n 'key2' => 'value-2-for-key-2',\n 'key3' => array(\n 'key31' => 'value-for-key-3-1',\n 'key32' => array(\n 'key321' => 'value-for-key321'\n )\n ),\n 'key4' => array(\n 'key' => 'value'\n )\n );\n\n // You can set your post data\n $postData = http_build_query($arrPostData); // Raw PHP array\n\n $postData = json_encode($arrPostData); // Only USE this when request JSON data.\n\n $mixResponse = executeCurl(array(\n CURLOPT_URL => 'http://whatever-your-request-url.com/xyz/yii',\n CURLOPT_RETURNTRANSFER => true,\n CURLOPT_HTTPGET => true,\n CURLOPT_VERBOSE => true,\n CURLOPT_AUTOREFERER => true,\n CURLOPT_CUSTOMREQUEST => $requestType,\n CURLOPT_POSTFIELDS => $postData,\n CURLOPT_HTTPHEADER => array(\n \"X-HTTP-Method-Override: \" . $requestType,\n 'Content-Type: application/json', // Only USE this when requesting JSON data\n ),\n\n // If HTTP authentication is required, use the below lines.\n CURLOPT_HTTPAUTH => CURLAUTH_BASIC,\n CURLOPT_USERPWD => $username. ':' . $password\n ));\n\n // $mixResponse contains your server response.\n" }, { "answer_id": 22474056, "author": "Julian", "author_id": 1280520, "author_profile": "https://Stackoverflow.com/users/1280520", "pm_score": 2, "selected": false, "text": "<?php\n $ch = curl_init(); // Initiate cURL\n $url = \"http://www.somesite.com/curl_example.php\"; // Where you want to post data\n curl_setopt($ch, CURLOPT_URL,$url);\n curl_setopt($ch, CURLOPT_POST, true); // Tell cURL you want to post something\n curl_setopt($ch, CURLOPT_POSTFIELDS, \"var1=value1&var2=value2&var_n=value_n\"); // Define what you want to post\n curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return the output in string format\n $output = curl_exec ($ch); // Execute\n\n curl_close ($ch); // Close cURL handle\n\n var_dump($output); // Show output\n?>\n curl_setopt curl_setopt_array" }, { "answer_id": 37318643, "author": "Aniket B", "author_id": 6355133, "author_profile": "https://Stackoverflow.com/users/6355133", "pm_score": 2, "selected": false, "text": "$url='Your url'; // Specify your url\n$data= array('parameterkey1'=>value,'parameterkey2'=>value); // Add parameters in key value\n$ch = curl_init(); // Initialize cURL\ncurl_setopt($ch, CURLOPT_URL,$url);\ncurl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));\ncurl_setopt($ch, CURLOPT_RETURNTRANSFER, true);\ncurl_exec($ch);\ncurl_close($ch);\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2863/" ]
28,428
<p>I want to bring up a file dialog in Java that defaults to the application installation directory.</p> <p>What's the best way to get that information programmatically?</p>
[ { "answer_id": 28454, "author": "Rich Lawrence", "author_id": 1281, "author_profile": "https://Stackoverflow.com/users/1281", "pm_score": 4, "selected": true, "text": "System.getProperty(\"user.dir\") \n" }, { "answer_id": 28726, "author": "McDowell", "author_id": 304, "author_profile": "https://Stackoverflow.com/users/304", "pm_score": 2, "selected": false, "text": "System.getProperty(\"user.dir\");\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1288/" ]
28,478
<p>I recently asked a question about <a href="https://stackoverflow.com/questions/28377/iif-vs-if">IIf vs. If</a> and found out that there is another function in VB called <strong>If</strong> which basically does the same thing as <strong>IIf</strong> but is a short-circuit.</p> <p>Does this <strong>If</strong> function perform better than the <strong>IIf</strong> function? Does the <strong>If</strong> statement trump the <strong>If</strong> and <strong>IIf</strong> functions?</p>
[ { "answer_id": 28498, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 5, "selected": true, "text": "If Dim result = If(a > 0, Math.Sqrt(a), -1.0)\n\n' versus\n\nDim result As Double ' Redundant default initialization!\nIf a > 0 Then\n result = Math.Sqrt(a)\nElse\n result = -1\nEnd If\n" }, { "answer_id": 23395769, "author": "BateTech", "author_id": 2054866, "author_profile": "https://Stackoverflow.com/users/2054866", "pm_score": 2, "selected": false, "text": "IIf() If() Option Infer On IIf Object Dim val As Integer = -1\n Dim iifVal As Object, ifVal As Object\n iifVal = IIf(val >= 0, val, Nothing)\n ifVal = If(val >= 0, val, Nothing)\n iifVal ifVal" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/299/" ]
28,529
<p>When using <a href="http://jquery.com/" rel="nofollow noreferrer">jQuery</a>'s <a href="http://docs.jquery.com/Ajax/jQuery.ajax#options" rel="nofollow noreferrer">ajax method</a> to submit form data, what is the best way to handle errors? This is an example of what a call might look like:</p> <pre><code>$.ajax({ url: "userCreation.ashx", data: { u:userName, p:password, e:email }, type: "POST", beforeSend: function(){disableSubmitButton();}, complete: function(){enableSubmitButton();}, error: function(xhr, statusText, errorThrown){ // Work out what the error was and display the appropriate message }, success: function(data){ displayUserCreatedMessage(); refreshUserList(); } }); </code></pre> <p>The request might fail for a number of reasons, such as duplicate user name, duplicate email address etc, and the ashx is written to throw an exception when this happens.</p> <p>My problem seems to be that by throwing an exception the ashx causes the <code>statusText</code> and <code>errorThrown</code> to be <strong>undefined</strong>.</p> <p>I can get to the <code>XMLHttpRequest.responseText</code> which contains the HTML that makes up the standard .net error page.</p> <p>I am finding the page title in the responseText and using the title to work out which error was thrown. Although I have a suspicion that this will fall apart when I enable custom error handling pages.</p> <p>Should I be throwing the errors in the ashx, or should I be returning a status code as part of the data returned by the call to <code>userCreation.ashx</code>, then using this to decide what action to take?<br> How do you handle these situations?</p>
[ { "answer_id": 28545, "author": "travis", "author_id": 1414, "author_profile": "https://Stackoverflow.com/users/1414", "pm_score": 4, "selected": false, "text": "<div id=\"error\"></div> error: function (XMLHttpRequest, textStatus, errorThrown) {\n $(\"#error\").html(XMLHttpRequest.status + \"\\n<hr />\" + XMLHttpRequest.responseText);\n}\n if (XMLHttpRequest.status === 404) // display some page not found error\nif (XMLHttpRequest.status === 500) // display some server error\n XMLHttpRequest.responseText XMLHttpRequest.responseText {\n\"Message\":\"Index was out of range. Must be non-negative and less than the size of the collection.\\r\\n\nParameter name: index\",\n\"StackTrace\":\" at System.ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource)\\r\\n \nat etc...\",\n\"ExceptionType\":\"System.ArgumentOutOfRangeException\"\n}\n <WebMethod()> _\n<ScriptMethod()> _\n" }, { "answer_id": 29915, "author": "AidenMontgomery", "author_id": 1403, "author_profile": "https://Stackoverflow.com/users/1403", "pm_score": 2, "selected": false, "text": "success: function(data){\n var created = $(\"result\", data).attr(\"success\");\n if (created == \"OK\"){\n resetNewUserForm();\n listUsers('');\n } else {\n var errorMessage = $(\"result\", data).attr(\"message\");\n $(\"#newUserErrorMessage\").text(errorMessage).show();\n }\n enableNewUserForm();\n}\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28529", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1403/" ]
28,542
<p>My C code snippet takes the address of an argument and stores it in a volatile memory location (preprocessed code):</p> <pre><code>void foo(unsigned int x) { *(volatile unsigned int*)(0x4000000 + 0xd4) = (unsigned int)(&amp;x); } int main() { foo(1); while(1); } </code></pre> <p>I used an SVN version of GCC for compiling this code. At the end of function <code>foo</code> I would expect to have the value <code>1</code> stored in the stack and, at <code>0x40000d4</code>, an address pointing to that value. When I compile without optimizations using the flag <code>-O0</code>, I get the expected ARM7TMDI assembly output (commented for your convenience):</p> <pre><code> .align 2 .global foo .type foo, %function foo: @ Function supports interworking. @ args = 0, pretend = 0, frame = 8 @ frame_needed = 0, uses_anonymous_args = 0 @ link register save eliminated. sub sp, sp, #8 str r0, [sp, #4] @ 3. Store the argument on the stack mov r3, #67108864 add r3, r3, #212 add r2, sp, #4 @ 4. Address of the stack variable str r2, [r3, #0] @ 5. Store the address at 0x40000d4 add sp, sp, #8 bx lr .size foo, .-foo .align 2 .global main .type main, %function main: @ Function supports interworking. @ args = 0, pretend = 0, frame = 0 @ frame_needed = 0, uses_anonymous_args = 0 stmfd sp!, {r4, lr} mov r0, #1 @ 1. Pass the argument in register 0 bl foo @ 2. Call function foo .L4: b .L4 .size main, .-main .ident "GCC: (GNU) 4.4.0 20080820 (experimental)" </code></pre> <p>It clearly stores the argument first on the stack and from there stores it at <code>0x40000d4</code>. When I compile with optimizations using <code>-O1</code>, I get something unexpected:</p> <pre><code> .align 2 .global foo .type foo, %function foo: @ Function supports interworking. @ args = 0, pretend = 0, frame = 8 @ frame_needed = 0, uses_anonymous_args = 0 @ link register save eliminated. sub sp, sp, #8 mov r2, #67108864 add r3, sp, #4 @ 3. Address of *something* on the stack str r3, [r2, #212] @ 4. Store the address at 0x40000d4 add sp, sp, #8 bx lr .size foo, .-foo .align 2 .global main .type main, %function main: @ Function supports interworking. @ args = 0, pretend = 0, frame = 0 @ frame_needed = 0, uses_anonymous_args = 0 stmfd sp!, {r4, lr} mov r0, #1 @ 1. Pass the argument in register 0 bl foo @ 2. Call function foo .L4: b .L4 .size main, .-main .ident "GCC: (GNU) 4.4.0 20080820 (experimental)" </code></pre> <p>This time the argument is never stored on the stack even though <em>something</em> from the stack is still stored at <code>0x40000d4</code>.</p> <p>Is this just expected/undefined behaviour? Have I done something wrong or have I in fact found a Compiler Bug&trade;?</p>
[ { "answer_id": 28651, "author": "Will Dean", "author_id": 987, "author_profile": "https://Stackoverflow.com/users/987", "pm_score": 1, "selected": false, "text": "void foo(unsigned int x) \n{\n volatile unsigned int* pArg = &x;\n *(volatile unsigned int*)(0x4000000 + 0xd4) = (unsigned int)pArg;\n}\n" }, { "answer_id": 28725, "author": "Tomi Kyöstilä", "author_id": 616, "author_profile": "https://Stackoverflow.com/users/616", "pm_score": 0, "selected": false, "text": "0x40000d4 void foo(unsigned int x) \n{\n volatile unsigned int* pArg = &x;\n *(volatile unsigned int*)(0x4000000 + 0xd4) = (unsigned int)pArg;\n}\n -O0 -O1 -O1" }, { "answer_id": 69454, "author": "Ben Combee", "author_id": 1323, "author_profile": "https://Stackoverflow.com/users/1323", "pm_score": 2, "selected": false, "text": "void foo(unsigned int x) {\n volatile int y = x;\n *(volatile unsigned int*)(0x4000000 + 0xd4) = (unsigned int)(&y);\n}\n" }, { "answer_id": 293385, "author": "zaphod", "author_id": 13871, "author_profile": "https://Stackoverflow.com/users/13871", "pm_score": 3, "selected": false, "text": "foo() x x foo() x x main() x malloc()" }, { "answer_id": 293387, "author": "Evan Teran", "author_id": 13430, "author_profile": "https://Stackoverflow.com/users/13430", "pm_score": 2, "selected": false, "text": "void foo(unsigned int x) {\n volatile unsigned int* ptr = (unsigned int*)(0x4000000 + 0xd4);\n *ptr = (unsigned int)(&x);\n}\n\nint main() {\n foo(1);\n while(1);\n}\n void foo(unsigned int *x) {\n volatile unsigned int* ptr = (unsigned int*)(0x4000000 + 0xd4);\n *ptr = (unsigned int)(x);\n}\n\nint main() {\n int x = 1;\n foo(&x);\n while(1);\n}\n" }, { "answer_id": 801152, "author": "old_timer", "author_id": 16007, "author_profile": "https://Stackoverflow.com/users/16007", "pm_score": 0, "selected": false, "text": "*(volatile unsigned int *)0x12345 = someuintvariable;\n *(volatile unsigned int *)0x12345 = 0x12;\n .globl PUT32\nPUT32:\n str r1,[r0]\n bx lr\n\n\n\n\n\n PUT32(0x12345,0x12);\n" }, { "answer_id": 5316968, "author": "David Cary", "author_id": 238320, "author_profile": "https://Stackoverflow.com/users/238320", "pm_score": 1, "selected": false, "text": "// Warning: untested code.\nvoid foo(unsigned int x) {\n static volatile unsigned int color = x; // \"static\" so it's not on the stack\n volatile unsigned int** dma_register =\n (volatile unsigned int**)(0x4000000 + 0xd4);\n *dma_register = &color;\n}\n\nint main() {\n foo(1);\n while(1);\n}\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/616/" ]
28,559
<p>What's the best Python idiom for this C construct?</p> <pre><code>while ((x = next()) != END) { .... } </code></pre> <p>I don't have the ability to recode next().</p> <p>update: and the answer from seems to be:</p> <pre><code>for x in iter(next, END): .... </code></pre>
[ { "answer_id": 28563, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 2, "selected": false, "text": "x = next()\nwhile x != END:\n do_something_with_x\n x = next()\n" }, { "answer_id": 28566, "author": "FreeMemory", "author_id": 2132, "author_profile": "https://Stackoverflow.com/users/2132", "pm_score": 1, "selected": false, "text": "for e in L [ e for e in L if e % 2 == 0 ]" }, { "answer_id": 28568, "author": "Johannes Hoff", "author_id": 3102, "author_profile": "https://Stackoverflow.com/users/3102", "pm_score": 3, "selected": false, "text": "def next():\n for num in range(10):\n yield num\n\nfor x in next():\n print x\n" }, { "answer_id": 28580, "author": "dF.", "author_id": 3002, "author_profile": "https://Stackoverflow.com/users/3002", "pm_score": 1, "selected": false, "text": "for x in iternext():\n do_something_with_x\n iternext def iternext():\n x = next()\n while x != END:\n yield x\n x = next() \n" }, { "answer_id": 28714, "author": "FreeMemory", "author_id": 2132, "author_profile": "https://Stackoverflow.com/users/2132", "pm_score": 3, "selected": true, "text": "while x=next():\n // do something here!\n while 1:\n x = next()\n if x != END:\n // Blah\n else:\n break\n class Pita( object ):\n __slots__ = ('pocket',)\n marker = object()\n def __init__(self, v=marker):\n if v is not self.marker:\n self.pocket = v\n def __call__(self, v=marker):\n if v is not self.marker:\n self.pocket = v\n return self.pocket\n p = Pita()\nwhile p( next() ) != END:\n // do stuff with p.pocket!\n __call__" }, { "answer_id": 28780, "author": "Eli Courtwright", "author_id": 1694, "author_profile": "https://Stackoverflow.com/users/1694", "pm_score": 1, "selected": false, "text": "for x in everything():\n ...\n" }, { "answer_id": 426415, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 4, "selected": false, "text": "for x in iter(next_, END):\n ....\n iter(o[, sentinel])\n sentinel o o next() sentinel StopIteration" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/116/" ]
28,577
<p>I need to store products for an e-commerce solution in a database. Each product should have descriptive information, such as name, description etc.</p> <p>I need any product to be localized to x number of languages.</p> <p>What I've done so far, is to make any column that should be localized and <code>nvarchar(MAX)</code> and then i store an XML string like this:</p> <pre><code>&lt;cultures&gt; &lt;culture code="en-us"&gt;Super fast laptop&lt;/culture&gt; &lt;culture code="da-dk"&gt;Super hurtig bærbar&lt;/culture&gt; &lt;/cultures&gt; </code></pre> <p>And when I load it from the database, into my business logic objects, I parse the XML string to a <code>Dictionary&lt;string, string&gt;</code> where the key is the culture/language code.</p> <p>So when I want to display the name of a product, I do this:</p> <pre><code>lblName.Text = product.Name["en-us"]; </code></pre> <p>Does anyone have a better solution?</p>
[ { "answer_id": 28871, "author": "Luke", "author_id": 327, "author_profile": "https://Stackoverflow.com/users/327", "pm_score": 3, "selected": true, "text": "public class Product\n{\n private idType id;\n public string Name\n {\n get\n {\n return Localizer.Instance.GetLocalString(id, \"Name\");\n }\n }\n}\n public string GetLocalString(idType objectId, string fieldName)\n {\n switch (_currentLanguage)\n {\n case Language.English:\n // db access code to retrieve your string, may need to include the table\n // the object is in (e.g. \"Products\" \"Orders\" etc.)\n db.GetValue(objectId, fieldName, \"en-us\");\n break;\n }\n }\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28577", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2972/" ]
28,588
<p>I want to log onto Stack Overflow using OpenID, but I thought I'd set up my own OpenID provider, just because it's harder :) How do you do this in Ubuntu?</p> <p>Edit: Replacing 'server' with the correct term OpenID provider (Identity provider would also be correct according to <a href="http://en.wikipedia.org/wiki/Openid#Using_OpenID" rel="noreferrer">wikipedia</a>).</p>
[ { "answer_id": 35659, "author": "tonygambone", "author_id": 3344, "author_profile": "https://Stackoverflow.com/users/3344", "pm_score": 3, "selected": false, "text": "<link rel=\"openid.server\" href=\"http://openid.claimid.com/server\" />\n<link rel=\"openid.delegate\" href=\"http://openid.claimid.com/USERNAME\" />\n" }, { "answer_id": 1688731, "author": "Tom", "author_id": 42754, "author_profile": "https://Stackoverflow.com/users/42754", "pm_score": 0, "selected": false, "text": "<mydocumentroot>/OpenID http://<mywebsite>/OpenID echo -n '<myUserNam>:phpMyID:<myPassword>' | openssl md5 http://<mywebsite>/OpenID/" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28588", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3102/" ]
28,637
<p>I need to find a bottleneck and need to accurately as possible measure time.</p> <p>Is the following code snippet the best way to measure the performance?</p> <pre><code>DateTime startTime = DateTime.Now; // Some execution process DateTime endTime = DateTime.Now; TimeSpan totalTimeTaken = endTime.Subtract(startTime); </code></pre>
[ { "answer_id": 28648, "author": "Markus Olsson", "author_id": 2114, "author_profile": "https://Stackoverflow.com/users/2114", "pm_score": 10, "selected": true, "text": "System.Diagnostics Stopwatch sw = Stopwatch.StartNew();\nPerformWork();\nsw.Stop();\n\nConsole.WriteLine(\"Time taken: {0}ms\", sw.Elapsed.TotalMilliseconds);\n DateTime.Now DateTime.UtcNow DateTime.Now DateTime.UtcNow" }, { "answer_id": 28649, "author": "rp.", "author_id": 2536, "author_profile": "https://Stackoverflow.com/users/2536", "pm_score": 4, "selected": false, "text": "Stopwatch sw = new Stopwatch();\nsw.Start();\n\n// Do some code.\n\nsw.Stop();\n\n// sw.ElapsedMilliseconds = the time your \"do some code\" took.\n" }, { "answer_id": 28657, "author": "mmcdole", "author_id": 2635, "author_profile": "https://Stackoverflow.com/users/2635", "pm_score": 7, "selected": false, "text": "Stopwatch sw = new Stopwatch();\nsw.Start();\n// Do Work\nsw.Stop();\n\nConsole.WriteLine(\"Elapsed time: {0}\", sw.Elapsed.TotalMilliseconds);\n" }, { "answer_id": 28674, "author": "Adam Haile", "author_id": 194, "author_profile": "https://Stackoverflow.com/users/194", "pm_score": 3, "selected": false, "text": "System.Timers.Timer aTimer;\npublic static void Main()\n{\n // Create a timer with a ten second interval.\n aTimer = new System.Timers.Timer(10000);\n\n // Hook up the Elapsed event for the timer.\n aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);\n\n // Set the Interval to 2 seconds (2000 milliseconds).\n aTimer.Interval = 2000;\n aTimer.Enabled = true;\n\n Console.WriteLine(\"Press the Enter key to exit the program.\");\n Console.ReadLine();\n}\n\n// Specify what you want to happen when the Elapsed event is \n// raised.\nprivate static void OnTimedEvent(object source, ElapsedEventArgs e)\n{\n Console.WriteLine(\"The Elapsed event was raised at {0}\", e.SignalTime);\n}\n" }, { "answer_id": 39798, "author": "Anthony Mastrean", "author_id": 3619, "author_profile": "https://Stackoverflow.com/users/3619", "pm_score": 4, "selected": false, "text": "StopWatch Disposed Stopped public partial class With\n{\n public static long Benchmark(Action action)\n {\n var stopwatch = Stopwatch.StartNew();\n action();\n stopwatch.Stop();\n return stopwatch.ElapsedMilliseconds;\n }\n}\n public void Execute(Action action)\n{\n var time = With.Benchmark(action);\n log.DebugFormat(“Did action in {0} ms.”, time);\n}\n public static class Extensions\n{\n public static long Benchmark(this Action action)\n {\n return With.Benchmark(action);\n }\n}\n public void Execute(Action action)\n{\n var time = action.Benchmark()\n log.DebugFormat(“Did action in {0} ms.”, time);\n}\n" }, { "answer_id": 184906, "author": "OwenP", "author_id": 2547, "author_profile": "https://Stackoverflow.com/users/2547", "pm_score": 3, "selected": false, "text": "StopWatch" }, { "answer_id": 5211719, "author": "jiya jain", "author_id": 647090, "author_profile": "https://Stackoverflow.com/users/647090", "pm_score": 3, "selected": false, "text": "using System;\nusing System.Diagnostics;\n\nclass Program\n{\n public static void Main()\n {\n Stopwatch stopWatch = Stopwatch.StartNew();\n\n // some other code\n\n stopWatch.Stop();\n\n // this not correct to get full timer resolution\n Console.WriteLine(\"{0} ms\", stopWatch.ElapsedMilliseconds);\n\n // Correct way to get accurate high precision timing\n Console.WriteLine(\"{0} ms\", stopWatch.Elapsed.TotalMilliseconds);\n }\n}\n" }, { "answer_id": 6986472, "author": "Valentin Kuzub", "author_id": 514382, "author_profile": "https://Stackoverflow.com/users/514382", "pm_score": 6, "selected": false, "text": "Stopwatch DateTime.Now DateTime.UtcNow Stopwatch UtcNow" }, { "answer_id": 24822240, "author": "Blackvault", "author_id": 3602240, "author_profile": "https://Stackoverflow.com/users/3602240", "pm_score": 3, "selected": false, "text": "Stopwatch sw = new Stopwatch();\nsw.Start();\n\n\n// Critical lines of code\n\nlong elapsedMs = sw.Elapsed.TotalMilliseconds;\n" }, { "answer_id": 25836121, "author": "Bye StackOverflow", "author_id": 4039900, "author_profile": "https://Stackoverflow.com/users/4039900", "pm_score": 2, "selected": false, "text": "Stopwatch sw = Stopwatch.StartNew();\nPerformWork();\nsw.Stop();\n\nConsole.WriteLine(\"Time taken: {0}ms\", sw.Elapsed.TotalMilliseconds);\n PerformWork();\n\nint repeat = 1000;\n\nStopwatch sw = Stopwatch.StartNew();\nfor (int i = 0; i < repeat; i++)\n{\n PerformWork();\n}\n\nsw.Stop();\n\nConsole.WriteLine(\"Time taken: {0}ms\", sw.Elapsed.TotalMilliseconds / repeat);\n" }, { "answer_id": 64469019, "author": "Tono Nam", "author_id": 637142, "author_profile": "https://Stackoverflow.com/users/637142", "pm_score": 0, "selected": false, "text": " int iterations = 5000000;\n\n // Test using datetime.now\n {\n var date = DateTime.UtcNow.AddHours(DateTime.UtcNow.Second);\n\n var now = DateTime.UtcNow;\n\n for (int i = 0; i < iterations; i++)\n {\n if (date == DateTime.Now)\n Console.WriteLine(\"it is!\");\n }\n Console.WriteLine($\"Done executing {iterations} iterations using datetime.now. It took {(DateTime.UtcNow - now).TotalSeconds} seconds\");\n }\n\n // Test using datetime.utcnow\n {\n var date = DateTime.UtcNow.AddHours(DateTime.UtcNow.Second);\n\n var now = DateTime.UtcNow;\n\n for (int i = 0; i < iterations; i++)\n {\n if (date == DateTime.UtcNow)\n Console.WriteLine(\"it is!\");\n }\n Console.WriteLine($\"Done executing {iterations} iterations using datetime.utcnow. It took {(DateTime.UtcNow - now).TotalSeconds} seconds\");\n }\n\n // Test using stopwatch\n {\n Stopwatch sw = new Stopwatch();\n sw.Start();\n\n var now = DateTime.UtcNow;\n\n for (int i = 0; i < iterations; i++)\n {\n if (sw.ElapsedTicks == DateTime.Now.Ticks)\n Console.WriteLine(\"it is!\");\n }\n Console.WriteLine($\"Done executing {iterations} iterations using stopwatch. It took {(DateTime.UtcNow - now).TotalSeconds} seconds\");\n }\n Done executing 5000000 iterations using datetime.now. It took 0.8685502 seconds \nDone executing 5000000 iterations using datetime.utcnow. It took 0.1074324 seconds \nDone executing 5000000 iterations using stopwatch. It took 0.9625021 seconds\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28637", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2469/" ]
28,642
<p>Having a heckuva time with this one, though I feel I'm missing something obvious. I have a control that inherits from <code>System.Web.UI.WebControls.Button</code>, and then implements an interface that I have set up. So think...</p> <pre><code>public class Button : System.Web.UI.WebControls.Button, IMyButtonInterface { ... } </code></pre> <p>In the codebehind of a page, I'd like to find all instances of this button from the ASPX. Because I don't really know what the <em>type</em> is going to be, just the <em>interface</em> it implements, that's all I have to go on when looping through the control tree. Thing is, I've never had to determine if an object uses an interface versus just testing its type. <strong>How can I loop through the control tree and yank anything that implements <code>IMyButtonInterface</code> in a clean way</strong> (Linq would be fine)?</p> <p>Again, know it's something obvious, but just now started using interfaces heavily and I can't seem to focus my Google results enough to figure it out :)</p> <p><strong>Edit:</strong> <code>GetType()</code> returns the actual class, but doesn't return the interface, so I can't test on that (e.g., it'd return "<code>MyNamespace.Button</code>" instead of "<code>IMyButtonInterface</code>"). In trying to use "<code>as</code>" or "<code>is</code>" in a recursive function, the <em><code>type</code></em> parameter doesn't even get recognized within the function! It's rather bizarre. So</p> <pre><code>if(ctrl.GetType() == typeToFind) //ok if(ctrl is typeToFind) //typeToFind isn't recognized! eh? </code></pre> <p>Definitely scratching my head over this one.</p>
[ { "answer_id": 28662, "author": "bdukes", "author_id": 2688, "author_profile": "https://Stackoverflow.com/users/2688", "pm_score": 1, "selected": false, "text": "foreach (Control c in this.Page.Controls) {\n IMyButtonInterface myButton = c as IMyButtonInterface;\n if (myButton != null) {\n // do something\n }\n}\n if (c is IMyButtonInterface) {\n ...\n}\n" }, { "answer_id": 28663, "author": "Sean Chambers", "author_id": 2993, "author_profile": "https://Stackoverflow.com/users/2993", "pm_score": 1, "selected": false, "text": "if (myControl is ISomeInterface)\n{\n // do something\n}\n" }, { "answer_id": 28666, "author": "David Basarab", "author_id": 2469, "author_profile": "https://Stackoverflow.com/users/2469", "pm_score": 3, "selected": false, "text": "private List<Control> FindControlsByType(ControlCollection controls, Type typeToFind)\n{\n List<Control> foundList = new List<Control>();\n\n foreach (Control ctrl in this.Page.Controls)\n {\n if (ctrl.GetType() == typeToFind)\n {\n // Do whatever with interface\n foundList.Add(ctrl);\n }\n\n // Check if the Control has Child Controls and use Recursion\n // to keep checking them\n if (ctrl.HasControls())\n {\n // Call Function to \n List<Control> childList = FindControlsByType(ctrl.Controls, typeToFind);\n\n foundList.AddRange(childList);\n }\n }\n\n return foundList;\n}\n\n// Pass it this way\nFindControlsByType(Page.Controls, typeof(IYourInterface));\n" }, { "answer_id": 28671, "author": "hometoast", "author_id": 2009, "author_profile": "https://Stackoverflow.com/users/2009", "pm_score": 0, "selected": false, "text": "Dim c as IInterface = TryCast(obj, IInterface)\nIf c IsNot Nothing\n 'do work\nEnd if\n" }, { "answer_id": 28712, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 0, "selected": false, "text": "c as IMyButtonInterface;\n\nif (c != null)\n{\n // c is an IMyButtonInterface\n}\n" }, { "answer_id": 28715, "author": "Daniel Auger", "author_id": 1644, "author_profile": "https://Stackoverflow.com/users/1644", "pm_score": 4, "selected": true, "text": "ctrl is IInterfaceToFind\n ctrl.GetType() == aTypeVariable \n .GetType() .GetType() GetType() if(ctrl is typeToFind) \n typeToFind System.RuntimeType foo foo" }, { "answer_id": 28809, "author": "Jason Diller", "author_id": 2187, "author_profile": "https://Stackoverflow.com/users/2187", "pm_score": 2, "selected": false, "text": "private List<T> FindControlsByType<T>(ControlCollection controls )\n{\n List<T> foundList = new List<T>();\n\n foreach (Control ctrl in this.Page.Controls)\n {\n if (ctrl as T != null )\n {\n // Do whatever with interface\n foundList.Add(ctrl as T);\n }\n\n // Check if the Control has Child Controls and use Recursion\n // to keep checking them\n if (ctrl.HasControls())\n {\n // Call Function to \n List<T> childList = FindControlsByType<T>( ctrl.Controls );\n\n foundList.AddRange( childList );\n }\n }\n\n return foundList;\n}\n\n// Pass it this way\nFindControlsByType<IYourInterface>( Page.Controls );\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1212/" ]
28,675
<p>I'm using <code>ByteBuffers</code> and <code>FileChannels</code> to write binary data to a file. When doing that for big files or successively for multiple files, I get an <code>OutOfMemoryError</code> exception. I've read elsewhere that using <code>Bytebuffers</code> with NIO is broken and should be avoided. Does any of you already faced this kind of problem and found a solution to efficiently save large amounts of binary data in a file in java?</p> <p>Is the jvm option <code>-XX:MaxDirectMemorySize</code> the way to go?</p>
[ { "answer_id": 28690, "author": "Marcin", "author_id": 3105, "author_profile": "https://Stackoverflow.com/users/3105", "pm_score": 1, "selected": false, "text": "java.io.FileOutputStream DataOutputStream ObjectOutputStream" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2612/" ]
28,708
<p>My code needs to determine how long a particular process has been running. But it continues to fail with an access denied error message on the <code>Process.StartTime</code> request. This is a process running with a User's credentials (ie, not a high-privilege process). There's clearly a security setting or a policy setting, or <em>something</em> that I need to twiddle with to fix this, as I can't believe the StartTime property is in the Framework just so that it can fail 100% of the time.</p> <p>A Google search indicated that I could resolve this by adding the user whose credentials the querying code is running under to the "Performance Log Users" group. However, no such user group exists on this machine.</p>
[ { "answer_id": 31792, "author": "TheSmurf", "author_id": 1975282, "author_profile": "https://Stackoverflow.com/users/1975282", "pm_score": 3, "selected": false, "text": "using System.Management;\nString queryString = \"select CreationDate from Win32_Process where ProcessId='\" + ProcessId + \"'\";\nSelectQuery query = new SelectQuery(queryString);\n\nManagementScope scope = new System.Management.ManagementScope(@\"\\\\.\\root\\CIMV2\");\nManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);\nManagementObjectCollection processes = searcher.Get();\n\n //... snip ... logic to figure out which of the processes in the collection is the right one goes here\n\nDateTime startTime = ManagementDateTimeConverter.ToDateTime(processes[0][\"CreationDate\"].ToString());\nTimeSpan uptime = DateTime.Now.Subtract(startTime);\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28708", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1975282/" ]
28,709
<p>In Eclipse 3.2.2 on Linux content assist is not finding classes within the same project. Upgrading above 3.2 is not an option as SWT is not available above 3.2 for Solaris.</p> <p>I have seen suggestions to clean the workspace, reopen the workspace, run eclipse with the <code>-clean</code> command, none of which has worked.</p>
[ { "answer_id": 549032, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": true, "text": "package FG::CatalogueFichier;\nuse FG::Catalogue;\nour @ISA = qw(FG::Catalogue);\nuse strict;\n" }, { "answer_id": 4280953, "author": "Mark", "author_id": 237888, "author_profile": "https://Stackoverflow.com/users/237888", "pm_score": 0, "selected": false, "text": "[Workspace]\\.metadata\\.plugins\\org.eclipse.core.runtime\\.settings\n\norg.eclipse.jdt.ui.prefs\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28709", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1539/" ]
28,713
<p>Is there a simple way of getting a HTML textarea and an input type="text" to render with (approximately) equal width (in pixels), that works in different browsers?</p> <p>A CSS/HTML solution would be brilliant. I would prefer not to have to use Javascript.</p> <p>Thanks /Erik</p>
[ { "answer_id": 28728, "author": "Re0sless", "author_id": 2098, "author_profile": "https://Stackoverflow.com/users/2098", "pm_score": 5, "selected": true, "text": ".mywidth {\n width: 100px; \n} <input class=\"mywidth\">\n<br>\n<textarea class=\"mywidth\"></textarea>" }, { "answer_id": 28730, "author": "James B", "author_id": 2951, "author_profile": "https://Stackoverflow.com/users/2951", "pm_score": 1, "selected": false, "text": "<textarea style=\"width:80%\"> </textarea>\n<input type=\"text\" style=\"width:80%\" />\n" }, { "answer_id": 28755, "author": "John Sheehan", "author_id": 1786, "author_profile": "https://Stackoverflow.com/users/1786", "pm_score": 2, "selected": false, "text": "input[type=text], textarea { width: 80%; }\n" }, { "answer_id": 28857, "author": "Peter Hilton", "author_id": 2670, "author_profile": "https://Stackoverflow.com/users/2670", "pm_score": 2, "selected": false, "text": "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\n<html>\n<head>\n<title>width</title>\n<style type=\"text/css\">\ntextarea, input { padding:2px; border:2px inset #ccc; width:20em; }\n</style>\n</head>\n<body>\n<p><input/><br/><textarea></textarea></p>\n</body>\n</html>\n" }, { "answer_id": 32606, "author": "Lee Theobald", "author_id": 1900, "author_profile": "https://Stackoverflow.com/users/1900", "pm_score": 3, "selected": false, "text": ".mywidth {\n width: 35em;\n font-family: Verdana;\n font-size: 1em;\n} <input type=\"text\" class=\"mywidth\"/><br/>\n<textarea class=\"mywidth\"></textarea>" }, { "answer_id": 17811701, "author": "vitaj", "author_id": 2610809, "author_profile": "https://Stackoverflow.com/users/2610809", "pm_score": -1, "selected": false, "text": ".mywidth{\nwidth:100px;\n}\ntextarea{\nwidth:100px;\n}\n <input class=\"mywidth\" >\n<textarea></textarea>\n" }, { "answer_id": 24154873, "author": "Justin", "author_id": 922522, "author_profile": "https://Stackoverflow.com/users/922522", "pm_score": 2, "selected": false, "text": ".textarea, .textbox {\n width: 200px;\n -webkit-box-sizing: border-box;\n -moz-box-sizing: border-box;\n box-sizing: border-box; \n}\n" }, { "answer_id": 24937975, "author": "themeindia.org", "author_id": 3873639, "author_profile": "https://Stackoverflow.com/users/3873639", "pm_score": 0, "selected": false, "text": "input[type=\"text\"] { width: 60%; } \ninput[type=\"email\"] { width: 60%; }\ntextarea { width: 60%; }\ntextarea { height: 40%; }\n" }, { "answer_id": 50309496, "author": "Kurt Van den Branden", "author_id": 4746087, "author_profile": "https://Stackoverflow.com/users/4746087", "pm_score": 0, "selected": false, "text": "form-control <label for=\"display-name\">Display name</label>\n<input type=\"text\" class=\"form-control\" name=\"displayname\" placeholder=\"\">\n\n<label for=\"about-me\">About me</label>\n<textarea class=\"form-control\" rows=\"5\" id=\"about-me\" name=\"aboutMe\"></textarea>\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/276/" ]
28,723
<p>In handling a form post I have something like</p> <pre><code> public ActionResult Insert() { Order order = new Order(); BindingHelperExtensions.UpdateFrom(order, this.Request.Form); this.orderService.Save(order); return this.RedirectToAction("Details", new { id = order.ID }); } </code></pre> <p>I am not using explicit parameters in the method as I anticipate having to adapt to variable number of fields etc. and a method with 20+ parameters is not appealing.</p> <p>I suppose my only option here is mock up the whole HttpRequest, equivalent to what Rob Conery has done. Is this a best practice? Hard to tell with a framework which is so new.</p> <p>I've also seen solutions involving using an ActionFilter so that you can transform the above method signature to something like</p> <pre><code>[SomeFilter] public Insert(Contact contact) </code></pre>
[ { "answer_id": 35299, "author": "Joseph Kingry", "author_id": 3046, "author_profile": "https://Stackoverflow.com/users/3046", "pm_score": 2, "selected": true, "text": " public ActionResult Insert(Contact contact)\n {\n\n if (this.ViewData.ModelState.IsValid)\n {\n this.contactService.SaveContact(contact);\n\n return this.RedirectToAction(\"Details\", new { id = contact.ID });\n }\n else\n {\n return this.RedirectToAction(\"Create\");\n }\n }\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28723", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3046/" ]
28,739
<p>I recently ran out of disk space on a drive on a FreeBSD server. I truncated the file that was causing problems but I'm not seeing the change reflected when running <code>df</code>. When I run <code>du -d0</code> on the partition it shows the correct value. Is there any way to force this information to be updated? What is causing the output here to be different?</p>
[ { "answer_id": 447740, "author": "Dave C", "author_id": 55504, "author_profile": "https://Stackoverflow.com/users/55504", "pm_score": 2, "selected": false, "text": "cp /bin/cat /tmp/cat-test\n/tmp/cat-test &\nrm /tmp/cat-test\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/72/" ]
28,756
<p>Whats the best/easiest way to obtain a count of items within an IEnumerable collection without enumerating over all of the items in the collection?</p> <p>Possible with LINQ or Lambda?</p>
[ { "answer_id": 28761, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 4, "selected": false, "text": "Count var result = myenum.Count();\n" }, { "answer_id": 28762, "author": "Greg Hurlman", "author_id": 35, "author_profile": "https://Stackoverflow.com/users/35", "pm_score": 0, "selected": false, "text": "List<MyTableItem> myList = dataContext.MyTable.ToList();\nint myTableCount = myList.Count;\n\nforeach (MyTableItem in myList)\n{\n ...\n}\n" }, { "answer_id": 28919, "author": "ICR", "author_id": 214, "author_profile": "https://Stackoverflow.com/users/214", "pm_score": 4, "selected": false, "text": "foreach (int item in Series.Generate(5))\n{\n Console.WriteLine(item + \"(\" + myEnumerable.Count() + \")\");\n}\n List<int> seriesAsList = Series.Generate(5).ToList();\n" }, { "answer_id": 32131, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 0, "selected": false, "text": "Any()" }, { "answer_id": 14139728, "author": "Mukesh", "author_id": 1945660, "author_profile": "https://Stackoverflow.com/users/1945660", "pm_score": 3, "selected": false, "text": "IEnumerable list =..........;\n\nlist.OfType<T>().Count()\n" }, { "answer_id": 65133304, "author": "Mike Meinz", "author_id": 3146215, "author_profile": "https://Stackoverflow.com/users/3146215", "pm_score": 0, "selected": false, "text": "IList<string> FileServerVideos = Directory.GetFiles(VIDEOSERVERPATH, \"*.mp4\"); \nif (FileServerVideos.Count == 0)\n return;\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2993/" ]
28,765
<p>I recently upgraded a VS2005 web deployment project to VS2008 - and now I get the following error when building:</p> <pre><code>The specified task executable location "bin\aspnet_merge.exe" is invalid. </code></pre> <p>Here is the source of the error (from the web deployment targets file):</p> <pre><code>&lt;Target Name="AspNetMerge" Condition="'$(UseMerge)' == 'true'" DependsOnTargets="$(MergeDependsOn)"&gt; &lt;AspNetMerge ExePath="$(FrameworkSDKDir)bin" ApplicationPath="$(TempBuildDir)" KeyFile="$(_FullKeyFile)" DelaySign="$(DelaySign)" Prefix="$(AssemblyPrefixName)" SingleAssemblyName="$(SingleAssemblyName)" Debug="$(DebugSymbols)" Nologo="$(NoLogo)" ContentAssemblyName="$(ContentAssemblyName)" ErrorStack="$(ErrorStack)" RemoveCompiledFiles="$(DeleteAppCodeCompiledFiles)" CopyAttributes="$(CopyAssemblyAttributes)" AssemblyInfo="$(AssemblyInfoDll)" MergeXmlDocs="$(MergeXmlDocs)" ErrorLogFile="$(MergeErrorLogFile)" /&gt; </code></pre> <p>What is the solution to this problem?</p> <p>Note - I also created a web deployment project from scratch in VS2008 and got the same error.</p>
[ { "answer_id": 28822, "author": "Adam", "author_id": 1341, "author_profile": "https://Stackoverflow.com/users/1341", "pm_score": 4, "selected": true, "text": "SET FrameworkSDKDir=\"C:\\Program Files\\Microsoft SDKs\\Windows\\v6.1\"\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1341/" ]
28,817
<p>There is a legacy CVS repository, which contains a large number of directories, sub-directories, and paths. There is also a large number of branches and tags that do not necessarilly cover all paths &amp; files - usually a subset. How can I find out, which branch / tag covers, which files and paths?</p> <p>CVS log already provides the list of tags per file. The task requires me to transpose this into files per tag. I could not find such functionality in current WinCVS (CVSNT) implementation. Given ample empty cycles I can write a Perl script that would do that, the algorithm is not complex, but it needs to be done.</p> <p>I would imagine there are some people who needed such information and solved this problem. Thus, I think should be a readily available (open source / free) tool for this.</p>
[ { "answer_id": 34953, "author": "John Meagher", "author_id": 3535, "author_profile": "https://Stackoverflow.com/users/3535", "pm_score": 4, "selected": true, "text": "cvs log <filename>\n cvs update -r <tagname>\ncvs co <modulename> -r <tagname>\ncvs export <modulename> -r <tagname>\n" }, { "answer_id": 268124, "author": "Oliver Giesen", "author_id": 9784, "author_profile": "https://Stackoverflow.com/users/9784", "pm_score": 2, "selected": false, "text": "cvs -n co -rTagName ModuleName\n" }, { "answer_id": 1035192, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "cvs -q rdiff -s -D 2000-01-01 -r yourTagName\n" }, { "answer_id": 1035262, "author": "Joakim Elofsson", "author_id": 109869, "author_profile": "https://Stackoverflow.com/users/109869", "pm_score": 4, "selected": false, "text": "cvs status -v <file>\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28817", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2877/" ]
28,832
<p>If I call <code>finalize()</code> on an object from my program code, will the <strong>JVM</strong> still run the method again when the garbage collector processes this object?</p> <p>This would be an approximate example:</p> <pre><code>MyObject m = new MyObject(); m.finalize(); m = null; System.gc() </code></pre> <p>Would the explicit call to <code>finalize()</code> make the <strong>JVM</strong>'s garbage collector not to run the <code>finalize()</code> method on object <code>m</code>?</p>
[ { "answer_id": 28856, "author": "John Topley", "author_id": 1450, "author_profile": "https://Stackoverflow.com/users/1450", "pm_score": 2, "selected": false, "text": "public void cleanUp() {\n .\n .\n .\n}\n\nmyInstance.cleanUp();\n" }, { "answer_id": 28906, "author": "Tim Frey", "author_id": 1471, "author_profile": "https://Stackoverflow.com/users/1471", "pm_score": 6, "selected": true, "text": "private static class Blah\n{\n public void finalize() { System.out.println(\"finalizing!\"); }\n}\n\nprivate static void f() throws Throwable\n{\n Blah blah = new Blah();\n blah.finalize();\n}\n\npublic static void main(String[] args) throws Throwable\n{\n System.out.println(\"start\");\n f();\n System.gc();\n System.out.println(\"done\");\n}\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2697/" ]
28,858
<p>Saw a post about hidden features in C# but not a lot of people have written linq/lambdas example so... I wonder...</p> <blockquote> <p>What's the coolest (as in the most elegant) use of the C# LINQ and/or Lambdas/anonymous delegates you have ever saw/written?</p> </blockquote> <p>Bonus if it has went into production too!</p>
[ { "answer_id": 28973, "author": "Chris Ammerman", "author_id": 2729, "author_profile": "https://Stackoverflow.com/users/2729", "pm_score": 4, "selected": false, "text": "public static class Functionals\n{\n // One-argument Y-Combinator.\n public static Func<T, TResult> Y<T, TResult>(Func<Func<T, TResult>, Func<T, TResult>> F)\n {\n return t => F(Y(F))(t);\n }\n\n // Two-argument Y-Combinator.\n public static Func<T1, T2, TResult> Y<T1, T2, TResult>(Func<Func<T1, T2, TResult>, Func<T1, T2, TResult>> F)\n {\n return (t1, t2) => F(Y(F))(t1, t2);\n }\n\n // Three-arugument Y-Combinator.\n public static Func<T1, T2, T3, TResult> Y<T1, T2, T3, TResult>(Func<Func<T1, T2, T3, TResult>, Func<T1, T2, T3, TResult>> F)\n {\n return (t1, t2, t3) => F(Y(F))(t1, t2, t3);\n }\n\n // Four-arugument Y-Combinator.\n public static Func<T1, T2, T3, T4, TResult> Y<T1, T2, T3, T4, TResult>(Func<Func<T1, T2, T3, T4, TResult>, Func<T1, T2, T3, T4, TResult>> F)\n {\n return (t1, t2, t3, t4) => F(Y(F))(t1, t2, t3, t4);\n }\n\n // Curry first argument\n public static Func<T1, Func<T2, TResult>> Curry<T1, T2, TResult>(Func<T1, T2, TResult> F)\n {\n return t1 => t2 => F(t1, t2);\n }\n\n // Curry second argument.\n public static Func<T2, Func<T1, TResult>> Curry2nd<T1, T2, TResult>(Func<T1, T2, TResult> F)\n {\n return t2 => t1 => F(t1, t2);\n }\n\n // Uncurry first argument.\n public static Func<T1, T2, TResult> Uncurry<T1, T2, TResult>(Func<T1, Func<T2, TResult>> F)\n {\n return (t1, t2) => F(t1)(t2);\n }\n\n // Uncurry second argument.\n public static Func<T1, T2, TResult> Uncurry2nd<T1, T2, TResult>(Func<T2, Func<T1, TResult>> F)\n {\n return (t1, t2) => F(t2)(t1);\n }\n}\n" }, { "answer_id": 311750, "author": "Bryan Watts", "author_id": 37815, "author_profile": "https://Stackoverflow.com/users/37815", "pm_score": 0, "selected": false, "text": "private void WriteMemberDescriptions(Type type)\n{\n var descriptions =\n from member in type.GetMembers()\n let attributes = member.GetAttributes<DescriptionAttribute>(true)\n let attribute = attributes.FirstOrDefault()\n where attribute != null\n select new\n {\n Member = member.Name,\n Text = attribute.Description\n };\n\n foreach(var description in descriptions)\n {\n Console.WriteLine(\"{0}: {1}\", description.Member, description.Text);\n }\n}\n GetAttributes public static class AttributeSelection\n{\n public static IEnumerable<T> GetAttributes<T>(this ICustomAttributeProvider provider, bool inherit) where T : Attribute\n {\n if(provider == null)\n {\n throw new ArgumentNullException(\"provider\");\n }\n\n return provider.GetCustomAttributes(typeof(T), inherit).Cast<T>();\n }\n}\n AttributeSelection GetAttribute HasAttribute let where" }, { "answer_id": 1296623, "author": "Thomas Dufour", "author_id": 371593, "author_profile": "https://Stackoverflow.com/users/371593", "pm_score": 2, "selected": false, "text": "Func<T,R> Action<T> Expression<Func<T,R>> Expression<Action<T>> public static class PropertyChangedExtensions\n{\n public static void Raise(this PropertyChangedEventHandler handler, Expression<Func<object>> propertyExpression)\n {\n if (handler != null)\n {\n // Retrieve lambda body\n var body = propertyExpression.Body as MemberExpression;\n if (body == null)\n throw new ArgumentException(\"'propertyExpression' should be a member expression\");\n\n // Extract the right part (after \"=>\")\n var vmExpression = body.Expression as ConstantExpression;\n if (vmExpression == null)\n throw new ArgumentException(\"'propertyExpression' body should be a constant expression\");\n\n // Create a reference to the calling object to pass it as the sender\n LambdaExpression vmlambda = Expression.Lambda(vmExpression);\n Delegate vmFunc = vmlambda.Compile();\n object vm = vmFunc.DynamicInvoke();\n\n // Extract the name of the property to raise a change on\n string propertyName = body.Member.Name;\n var e = new PropertyChangedEventArgs(propertyName);\n handler(vm, e);\n }\n }\n}\n INotifyPropertyChanged if (PropertyChanged != null)\n PropertyChanged.Raise( () => MyProperty );\n" }, { "answer_id": 2729591, "author": "Krisc", "author_id": 299946, "author_profile": "https://Stackoverflow.com/users/299946", "pm_score": 1, "selected": false, "text": "SqlDevice device = GetDevice();\n\nreturn device.GetMultiple<Post>(\n \"GetPosts\",\n (s) => {\n s.Parameters.AddWithValue(\"@CreatedOn\", DateTime.Today);\n\n return true;\n },\n (r, p) => {\n p.Title = r.Get<string>(\"Title\");\n\n // Fill out post object\n\n return true;\n }\n);\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3055/" ]
28,878
<p>I'm translating my C# code for YouTube video comments into PHP. In order to properly nest comment replies, I need to re-arrange XML nodes. In PHP I'm using DOMDocument and DOMXPath which closely corresponds to C# XmlDocument. I've gotten pretty far in my translation but now I'm stuck on getting the parent node of a DOMElement. A DOMElement does not have a parent_node() property, only a DOMNode provides that property.</p> <p>After determining that a comment is a reply to a previous comment based in the string "in-reply-to" in a link element, I need to get its parent node in order to nest it beneath the comment it is in reply to:</p> <pre><code>// Get the parent entry node of this link element $importnode = $objReplyXML-&gt;importNode($link-&gt;parent_node(), true); </code></pre>
[ { "answer_id": 28998, "author": "Marius", "author_id": 1585, "author_profile": "https://Stackoverflow.com/users/1585", "pm_score": 1, "selected": false, "text": "$link->parent_node() $link**s**->parent_node() s" }, { "answer_id": 49586651, "author": "Dimas Lanjaka", "author_id": 6404439, "author_profile": "https://Stackoverflow.com/users/6404439", "pm_score": 2, "selected": false, "text": "parent_node() parentNode" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2601/" ]
28,881
<p>Using the same <strong>sort</strong> command with the same input produces different results on different machines. How do I fix that?</p>
[ { "answer_id": 28893, "author": "Jon Ericson", "author_id": 1438, "author_profile": "https://Stackoverflow.com/users/1438", "pm_score": 3, "selected": false, "text": "$ echo 'CO2_\nCO_' | env LC_ALL=C sort\nCO2_\nCO_\n\n\n$ echo 'CO2_\nCO_' | env LC_ALL=en_US sort\nCO_\nCO2_\n" }, { "answer_id": 28901, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 2, "selected": false, "text": "sort sort" }, { "answer_id": 28903, "author": "Henrik Gustafsson", "author_id": 2010, "author_profile": "https://Stackoverflow.com/users/2010", "pm_score": 6, "selected": true, "text": "LC_ALL=C" }, { "answer_id": 29315, "author": "Jörg W Mittag", "author_id": 2988, "author_profile": "https://Stackoverflow.com/users/2988", "pm_score": 2, "selected": false, "text": "sort sort sort" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1438/" ]
28,894
<p>For years I have been using the DEBUG compiler constant in VB.NET to write messages to the console. I've also been using System.Diagnostics.Debug.Write in similar fashion. It was always my understanding that when RELEASE was used as the build option, that all of these statements were left out by the compiler, freeing your production code of the overhead of debug statements. Recently when working with Silverlight 2 Beta 2, I noticed that Visual Studio actually attached to a RELEASE build that I was running off of a public website and displayed DEBUG statements which I assumed weren't even compiled! Now, my first inclination is to assume that that there is something wrong with my environment, but I also want to ask anyone with deep knowledge on System.Diagnostics.Debug and the DEBUG build option in general what I may be misunderstanding here.</p>
[ { "answer_id": 28913, "author": "juan", "author_id": 1782, "author_profile": "https://Stackoverflow.com/users/1782", "pm_score": 1, "selected": false, "text": "public void Debug(string s)\n{\n#if DEBUG\n System.Diagnostics.Debug(...);\n#endif\n}\n" }, { "answer_id": 28934, "author": "Chris Karcher", "author_id": 2773, "author_profile": "https://Stackoverflow.com/users/2773", "pm_score": 1, "selected": false, "text": "#if DEBUG\n System.Diagnostics.Debug.Write(...);\n#endif\n" }, { "answer_id": 28947, "author": "Mike", "author_id": 2848, "author_profile": "https://Stackoverflow.com/users/2848", "pm_score": 6, "selected": true, "text": "[ Conditional(\"Debug\") ]\nprivate void WriteDebug(string debugString)\n{\n // do stuff\n}\n" }, { "answer_id": 29021, "author": "Bjorn Reppen", "author_id": 1324220, "author_profile": "https://Stackoverflow.com/users/1324220", "pm_score": 3, "selected": false, "text": "[Conditional(\"DEBUG\")]\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28894", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3059/" ]
28,896
<p>I'm currently designing a program that will involve some physics (nothing too fancy, a few balls crashing to each other)</p> <p>What's the most exact datatype I can use to represent position (without a feeling of discrete jumps) in c#?</p> <p>Also, what's the smallest ammount of time I can get between t and t+1? One tick?</p> <p>EDIT: Clarifying: What is the smallest unit of time in C#? <code>[TimeSpan].Tick</code>?</p>
[ { "answer_id": 28917, "author": "tghw", "author_id": 2363, "author_profile": "https://Stackoverflow.com/users/2363", "pm_score": 4, "selected": true, "text": "decimal public class Position\n{\n decimal x;\n decimal y;\n decimal z;\n}\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28896", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1782/" ]
28,922
<p>I have an SQL server database that I am querying and I only want to get the information when a specific row is null. I used a where statement such as:</p> <pre><code>WHERE database.foobar = NULL </code></pre> <p>and it does not return anything. However, I know that there is at least one result because I created an instance in the database where 'foobar' is equal to null. If I take out the where statement it shows data so I know it is not the rest of the query.</p> <p>Can anyone help me out?</p>
[ { "answer_id": 28929, "author": "Farinha", "author_id": 2841, "author_profile": "https://Stackoverflow.com/users/2841", "pm_score": 1, "selected": false, "text": "IS NULL" }, { "answer_id": 28966, "author": "Mark Harrison", "author_id": 116, "author_profile": "https://Stackoverflow.com/users/116", "pm_score": 2, "selected": false, "text": "x = NULL -- always false\nx <> NULL -- always false\n\nx IS NULL -- these do what you want\nx IS NOT NULL\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28922", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2486/" ]
28,932
<p>What is the the best JavaScript compressor available? I'm looking for a tool that:</p> <ul> <li>is easy to use</li> <li>has a high compression rate</li> <li>Produce reliable end results (doesn't mess up the code)</li> </ul>
[ { "answer_id": 3541878, "author": "mishoo", "author_id": 154985, "author_profile": "https://Stackoverflow.com/users/154985", "pm_score": 8, "selected": true, "text": "Node.js foo[\"bar\"] foo.bar" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1363/" ]
28,949
<p>After reading <a href="https://stackoverflow.com/questions/28832/java-and-manually-executing-finalize">this question</a>, I was reminded of when I was taught Java and told never to call finalize() or run the garbage collector because "it's a big black box that you never need to worry about". Can someone boil the reasoning for this down to a few sentences? I'm sure I could read a technical report from Sun on this matter, but I think a nice, short, simple answer would satisfy my curiosity.</p>
[ { "answer_id": 30567, "author": "Derek Park", "author_id": 872, "author_profile": "https://Stackoverflow.com/users/872", "pm_score": 2, "selected": false, "text": "finalize() finalize() close() FileInputStream.close() finalize()" }, { "answer_id": 5388006, "author": "Leo", "author_id": 665792, "author_profile": "https://Stackoverflow.com/users/665792", "pm_score": 1, "selected": false, "text": "SomeStream s = null;\n...\ntry{\n s = openStream();\n ....\n s.io();\n ...\n} finally {\n if (s != null) {\n s.close();\n s = null;\n }\n}\n Graphics[2D] BufferedImage.getGrpahics()" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28949", "https://Stackoverflow.com", "https://Stackoverflow.com/users/572/" ]
28,950
<p>Does anyone have links to documentation or guides on making the decision between REST vs. SOAP? I understand both of these but am looking for some references on the key decision points, eg, security, which may make you lean towards one or the other.</p>
[ { "answer_id": 19463563, "author": "kapil das", "author_id": 2041542, "author_profile": "https://Stackoverflow.com/users/2041542", "pm_score": 2, "selected": false, "text": "REST uses standard HTTP so it is simplerto creating clients, developing APIs \nREST permits many different data formats like XML, plain text, JSON, HTML where as SOAP only permits XML.\nREST has better performance and scalability.\nRest and can be cached and SOAP can't \nBuilt-in error handling where SOAP has No error handling\nREST is particularly useful PDA and other mobile devices.\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/28950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/636/" ]