qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
288,424
<p>I was wondering if there is a good IRC channel around somewhere that allows iPhone developers to get together and talk about code and etc.</p> <p>Any channel already around that people are using?</p>
[ { "answer_id": 289178, "author": "wisequark", "author_id": 33159, "author_profile": "https://Stackoverflow.com/users/33159", "pm_score": 1, "selected": false, "text": "#iphonedev irc.freenode.net" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288424", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35478/" ]
288,441
<p>I long thought that in C, all variables had to be declared at the beginning of the function. I know that in C99, the rules are the same as in C++, but what are the variable declaration placement rules for C89/ANSI C?</p> <p>The following code compiles successfully with <code>gcc -std=c89</code> and <code>gcc -ansi</code>:</p> <pre><code>#include &lt;stdio.h&gt; int main() { int i; for (i = 0; i &lt; 10; i++) { char c = (i % 95) + 32; printf("%i: %c\n", i, c); char *s; s = "some string"; puts(s); } return 0; } </code></pre> <p>Shouldn't the declarations of <code>c</code> and <code>s</code> cause an error in C89/ANSI mode?</p>
[ { "answer_id": 288455, "author": "mipadi", "author_id": 28804, "author_profile": "https://Stackoverflow.com/users/28804", "pm_score": 8, "selected": true, "text": "s -pedantic c { }" }, { "answer_id": 288479, "author": "Kiley Hykawy", "author_id": 22727, "author_profile": "https://Stackoverflow.com/users/22727", "pm_score": 6, "selected": false, "text": "char c char *s" }, { "answer_id": 288515, "author": "Adam Liss", "author_id": 29157, "author_profile": "https://Stackoverflow.com/users/29157", "pm_score": 5, "selected": false, "text": "fork()" }, { "answer_id": 50822486, "author": "Philippe Carphin", "author_id": 5795941, "author_profile": "https://Stackoverflow.com/users/5795941", "pm_score": 2, "selected": false, "text": "int foo = 0;\n<code that uses foo>\n\nint bar = 1;\n<code that uses bar>\n\n<code that uses foo>\n {\n int foo = 0;\n <code that uses foo>\n}\n\nint bar = 1;\n<code that uses bar>\n\n>>> First compilation error here\n<code that uses foo>\n {\n int foo = 0;\n <code that uses foo>\n}\n\n<code that uses foo>\n\nint bar = 1;\n<code that uses bar>\n int i;\n\nfor(i = 0; i < 8; ++i){\n ...\n}\n\n<some stuff>\n\nfor(i = 3; i < 32; ++i){\n ...\n}\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30323/" ]
288,445
<p>I have a swf file that's embedded in a html page, and I have a close button in the swf page, I want the swf to disappear when I click on the button, what is the best way to do that? Thanks.</p>
[ { "answer_id": 1176547, "author": "Yens", "author_id": 71772, "author_profile": "https://Stackoverflow.com/users/71772", "pm_score": 3, "selected": true, "text": "function removeFlashFromHTML() \n{\n swfobject.removeSWF(\"id_of_your_html_object\");\n}\n function buttonClicked(evt:MouseEvent) \n{\n if (ExternalInterface.available) {\n ExternalInterface.call(\"removeFlashFromHTML()\");\n }\n}\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288445", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34797/" ]
288,465
<p>I'm building an XML DOM document in C++. My problem is this: I execute an XPATH query from an Element in my Document, which I know will return another Element. The elementPtr->selectSingleNode call returns an IXMLDOMNode. How can I gain access to the attributes of this node?</p> <p>Part of me wants to downcast the Node to an Element, but I couldn't get the cast to work.</p> <p>I tried</p> <pre><code>MSXML2::IXMLDOMElementPtr pParentElement; pParentNode-&gt;QueryInterface(__uuidof(MSXML2::IXMLDOMElement), (void**) &amp;pParentElement); </code></pre> <p>Which results in the following runtime error: </p> <pre><code>0x0057cc58 _com_error::`scalar deleting destructor'(unsigned int) </code></pre> <p>The other route I tried was to just use nodes:</p> <pre><code>MSXML2::IXMLDOMNodePtr pParentNode = pParameterElement-&gt;selectSingleNode("parent"); MSXML2::IXMLDOMNamedNodeMap* pParentAttributes; pParentNode-&gt;get_attributes(&amp;pParentAttributes); MSXML2::IXMLDOMNodePtr pCategoryNameNode = pParentAttributes-&gt;getNamedItem("Category"); VARIANT value; pCategoryNameNode-&gt;get_nodeValue(&amp;value); CString categoryName = value; </code></pre> <p>This fails at "parentNode->get_attributes()".</p> <p>It seems like I'm missing something; the API should not be this hard to use.</p> <p>--edit--</p> <p>What I was missing was that the selectSingleNode call was failing, leaving me with a NULL pointer. You can't call QueryInterface on that, neither can you call get_attributes on it :P</p> <p>I've selected the answer that fits the question that I asked, not the answer that helped me to realise that I asked the wrong question.</p>
[ { "answer_id": 288518, "author": "DavidK", "author_id": 31394, "author_profile": "https://Stackoverflow.com/users/31394", "pm_score": 1, "selected": false, "text": "MSXML2::IXMLDOMElementPtr pParentElement(pParentNode);\n" }, { "answer_id": 289207, "author": "Greg Domjan", "author_id": 37558, "author_profile": "https://Stackoverflow.com/users/37558", "pm_score": 4, "selected": true, "text": "MSXML2::IXMLDOMNodePtr pParentNode = pParameterElement->selectSingleNode(\"parent\");\nMSXML2::IXMLDOMElementPtr pParentElement( pParentNode );\n CComPtr<IXMLDOMNode> node = ...;\nCComQIPtr<IXMLDOMElement> elementNode( node );\n\nif( elementNode ) { \n// it was an element!\n} else { \n// it's something else try again? \n}\n CComPtr<IXMLDOMNamedNodeMap> attributes;\nnode->get_attributes( &attributes );\nif( attributes ) {\n _bstr_t name( L\"category\" );\n attributes->getNamedItem(name);\n}\n" }, { "answer_id": 67619504, "author": "xianzhi gao", "author_id": 15150609, "author_profile": "https://Stackoverflow.com/users/15150609", "pm_score": 0, "selected": false, "text": "CComPtr IXMLDOMNamedNodeMap IXMLDOMNamedNodeMap" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288465", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37481/" ]
288,500
<p>I am having an issue with SSH hanging on my Mac Book Pro. This only happens to me once I get home from work after I have used SSH while at work. The three factors I have narrowed the issue down to are SSH, our work AFS network drive and the method of network connectivity.</p> <p>At work we use an AFS drive with Kerberos Authentication to do all of our software development work on. I authenticate with Kerberos in order to gain access to the AFS drive where all my source code lives, but I open a local editor (Eclipse) which references the files on the AFS drive. Whenever I need to compile my code, I SSH in to my development server (which is also authenticated to the AFS drive) and compile from there. (Sanity Note: I know that it is a super wacky setup, but I promise I had NOTHING to do with it. I'm just making do with what I've got.)</p> <p>For my Network Preferences, I use the Automatic location all the time. For that configuration I have Built-in Ethernet en1 configured to use DHCP and our company's DNS server for when I'm at work (there is no wireless available). When I go home I connect to my home network via wireless, again using DHCP.</p> <p>I have a hunch that the AFS connection/Ethernet configuration is somehow the culprit here. Restarting the SSH daemon doesn't correct the problem. The only way I have found to correct the issue is by restarting the computer each time I want to use SSH. Keep in mind that I have no other (known) networking issues while at home after I've had the laptop at work. </p> <p>I have a co-worker who has reported to me the same issue on his MBP.</p> <p>I'm truly stumped on this one. Please provide some guidance. Thanks! </p>
[ { "answer_id": 339741, "author": "Paul Ivanov", "author_id": 36303, "author_profile": "https://Stackoverflow.com/users/36303", "pm_score": 2, "selected": false, "text": "Supported escape sequences:\n~. - terminate connection\n~B - send a BREAK to the remote system\n~C - open a command line\n~R - Request rekey (SSH protocol 2 only)\n~^Z - suspend ssh\n~# - list forwarded connections\n~& - background ssh (when waiting for connections to terminate)\n~? - this message\n~~ - send the escape character by typing it twice\n(Note that escapes are only recognized immediately after newline.)\n EscapeChar ~\n killall ssh\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29690/" ]
288,508
<p>Does Xcode support anything akin to Visual Studio style <code>#region</code> directives for arbitrary code folding?</p>
[ { "answer_id": 288530, "author": "Jason Coco", "author_id": 34218, "author_profile": "https://Stackoverflow.com/users/34218", "pm_score": 7, "selected": true, "text": "#pragma mark\n // MARK:\n// TODO:\n// FIXME:\n// !!!:\n// ???:\n" }, { "answer_id": 716751, "author": "willc2", "author_id": 23973, "author_profile": "https://Stackoverflow.com/users/23973", "pm_score": 4, "selected": false, "text": "#define FOLD 1\n if(FOLD) {\n // your code to hide\n // more code\n}\n" }, { "answer_id": 11116240, "author": "Norbert Nemec", "author_id": 295690, "author_profile": "https://Stackoverflow.com/users/295690", "pm_score": -1, "selected": false, "text": "namespace myproj { // members of class MyClassA\n\nvoid MyClassA::dosomething()\n{\n}\n\nvoid MyClassA::dosomethingelse()\n{\n}\n\n} // members of class MyClassA\nnamespace myproj { // members of MyClassB\n\nvoid MyClassB::dosomething()\n{\n}\n\nvoid MyClassB::dosomethingelse()\n{\n}\n\n} // members of MyClassB\n" }, { "answer_id": 23259651, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "//region title1\n{\n //region Subtitl1\n {\n\n }\n //region Subtitl2\n {\n\n }\n}\n" }, { "answer_id": 71515421, "author": "Rob Barber", "author_id": 4313998, "author_profile": "https://Stackoverflow.com/users/4313998", "pm_score": 1, "selected": false, "text": "#colorLiteral()" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288508", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13932/" ]
288,512
<p>Anyone knows a good way to resize any window to for example 640x480?</p> <p>Reason is, of course, screencasting.</p> <p>Under windows I've used ZoneSize from donationcoder. (Btw: For Firefox it's easy, just use the web developer toolbar.)</p>
[ { "answer_id": 288537, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 7, "selected": true, "text": "$ wmctrl -l\n0x00c00003 -1 rgamble-desktop Bottom Expanded Edge Panel\n0x00c00031 -1 rgamble-desktop Top Expanded Edge Panel\n0x00e00022 -1 rgamble-desktop Desktop\n0x0260007c 0 rgamble-desktop Google - Mozilla Firefox\n wmctrl -r Firefox -e 0,0,0,640,480\n gravity,X,Y,width,height" }, { "answer_id": 59234259, "author": "NVRM", "author_id": 2494754, "author_profile": "https://Stackoverflow.com/users/2494754", "pm_score": 2, "selected": false, "text": "maximized -e -b wmctrl -r Firefox -b toggle,maximized_horz\n wmctrl -r Firefox -b toggle,maximized_vert\n ----- ---------------\n remove modal\n add sticky\n toggle maximized_vert\n maximized_horz\n shaded\n skip_taskbar\n skip_pager\n hidden\n fullscreen\n above\n below\n // gravity,x,y,w,h\nwmctrl -r \"Resizing\" -e 0,0,0,640,480\n" }, { "answer_id": 63075575, "author": "BZZZZ", "author_id": 13989171, "author_profile": "https://Stackoverflow.com/users/13989171", "pm_score": 1, "selected": false, "text": "#!/usr/bin/sh\nwmctrl -l\necho \"\"\nread -p \"window id -> \" wid\nread -p \"width -> \" ww\nread -p \"height -> \" wh\nwmctrl -i -r $wid -e 0,0,0,$ww,$wh\necho \"Done!\"\n" }, { "answer_id": 71535848, "author": "user18510353", "author_id": 18510353, "author_profile": "https://Stackoverflow.com/users/18510353", "pm_score": 2, "selected": false, "text": "wmctrl -r \":ACTIVE:\" -e \"0,$(xdotool getactivewindow getwindowgeometry|egrep -o '[0-9]+,[^ ]+'),970,600\"" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288512", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9987/" ]
288,513
<p>Here is what I am trying to do: Given a date, a day of the week, and an integer <code>n</code>, determine whether the date is the <code>n</code>th day of the month.</p> <p>For example:</p> <ul> <li><p>input of <code>1/1/2009,Monday,2</code> would be false because <code>1/1/2009</code> is not the second Monday</p></li> <li><p>input of <code>11/13/2008,Thursday,2</code> would return true because it is the second Thursday</p></li> </ul> <p>How can I improve this implementation?</p> <pre><code>private bool NthDayOfMonth(DateTime date, DayOfWeek dow, int n) { int d = date.Day; return date.DayOfWeek == dow &amp;&amp; (d/ 7 == n || (d/ 7 == (n - 1) &amp;&amp; d % 7 &gt; 0)); } </code></pre>
[ { "answer_id": 288529, "author": "Robert Wagner", "author_id": 10784, "author_profile": "https://Stackoverflow.com/users/10784", "pm_score": 5, "selected": true, "text": "private bool NthDayOfMonth(DateTime date, DayOfWeek dow, int n){\n int d = date.Day;\n return date.DayOfWeek == dow && (d-1)/7 == (n-1);\n}\n" }, { "answer_id": 288542, "author": "George Stocker", "author_id": 16587, "author_profile": "https://Stackoverflow.com/users/16587", "pm_score": 3, "selected": false, "text": "public static DateTime FindTheNthSpecificWeekday(int year, int month,int nth, System.DayOfWeek day_of_the_week)\n{\n // validate month value\n if(month < 1 || month > 12)\n {\n throw new ArgumentOutOfRangeException(\"Invalid month value.\");\n }\n\n // validate the nth value\n if(nth < 0 || nth > 5)\n {\n throw new ArgumentOutOfRangeException(\"Invalid nth value.\");\n }\n\n // start from the first day of the month\n DateTime dt = new DateTime(year, month, 1);\n\n // loop until we find our first match day of the week\n while(dt.DayOfWeek != day_of_the_week)\n {\n dt = dt.AddDays(1);\n }\n\n if(dt.Month != month)\n {\n // we skip to the next month, we throw an exception\n throw new ArgumentOutOfRangeException(string.Format(\"The given month has less than {0} {1}s\", nth, day_of_the_week));\n }\n\n // Complete the gap to the nth week\n dt = dt.AddDays((nth - 1) * 7);\n\n return dt;\n}\n" }, { "answer_id": 291797, "author": "waynecolvin", "author_id": 35658, "author_profile": "https://Stackoverflow.com/users/35658", "pm_score": 1, "selected": false, "text": "N (* first try, this code sucks *)\n\nfunction isNthGivenDayInMonth(date : dateTime;\n dow : dayOfWeek;\n N : integer) : boolean;\n var B, A : integer (* on or before and after day of month *)\n var Day : integer (* day of month *)\n begin\n B := (N-1)*7 + 1; A := (N-1)*7 + 6;\n D := getDayOfMonth(date);\n if (dow <> getDayOfWeek(date) \n then return(false)\n else return( (B <= Day) and (A >= Day) );\n end; (* function *)\n (N-1)*7 + 7 d/ 7 == n\n (either 0 or 1)/7 == 1 || (n-1) (Day-1) mod 7 (Day-1) div 7" }, { "answer_id": 520728, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "// Complete the gap to the nth week\ndt = dt.AddDays((nth - 1) * 7);\n\nif(dt.Month != month)\n{\n// we skip to the next month, we throw an exception\nthrow new ArgumentOutOfRangeException(”The given month has less than ” nth.ToString() ” ”\nday_of_the_week.ToString() “s”);\n}\n" }, { "answer_id": 26392656, "author": "reexmonkey", "author_id": 914512, "author_profile": "https://Stackoverflow.com/users/914512", "pm_score": 0, "selected": false, "text": " public static bool IsNthDayofMonth(this DateTime date, DayOfWeek weekday, int N)\n {\n if (N > 0)\n {\n var first = new DateTime(date.Year, date.Month, 1);\n return (date.Day - first.Day)/ 7 == N - 1 && date.DayOfWeek == weekday;\n }\n else\n {\n\n var last = new DateTime(date.Year, date.Month, 1).AddMonths(1).AddDays(-1);\n return (last.Day - date.Day) / 7 == (Math.Abs(N) - 1) && date.DayOfWeek == weekday;\n }\n" }, { "answer_id": 35584324, "author": "B. Clay Shannon-B. Crow Raven", "author_id": 875317, "author_profile": "https://Stackoverflow.com/users/875317", "pm_score": 0, "selected": false, "text": "internal static List<DateTime> GetDatesForNthDOWOfMonth(int weekNum, DayOfWeek DOW, DateTime beginDate, DateTime endDate)\n{\n List<DateTime> datesForNthDOWOfMonth = new List<DateTime>();\n int earliestDayOfMonth = 1;\n int latestDayOfMonth = 7;\n DateTime currentDate = beginDate;\n\n switch (weekNum)\n {\n case 1:\n earliestDayOfMonth = 1;\n latestDayOfMonth = 7;\n break;\n case 2:\n earliestDayOfMonth = 8;\n latestDayOfMonth = 14;\n break;\n case 3:\n earliestDayOfMonth = 15;\n latestDayOfMonth = 21;\n break;\n case 4:\n earliestDayOfMonth = 22;\n latestDayOfMonth = 28;\n break;\n }\n\n while (currentDate < endDate)\n {\n DateTime dateToInc = currentDate;\n DateTime endOfMonth = new DateTime(dateToInc.Year, dateToInc.Month, DateTime.DaysInMonth(dateToInc.Year, dateToInc.Month));\n bool dateFound = false;\n while (!dateFound)\n {\n dateFound = dateToInc.DayOfWeek.Equals(DOW);\n if (dateFound)\n {\n if ((dateToInc.Day >= earliestDayOfMonth) && \n (dateToInc.Day <= latestDayOfMonth))\n {\n datesForNthDOWOfMonth.Add(dateToInc);\n }\n }\n if (dateToInc.Date.Equals(endOfMonth.Date)) continue;\n dateToInc = dateToInc.AddDays(1);\n }\n currentDate = new DateTime(currentDate.Year, currentDate.Month, 1);\n currentDate = currentDate.AddMonths(1);\n }\n return datesForNthDOWOfMonth;\n}\n // This is to get the 1st Monday in each month from today through one year from today\nDateTime beg = DateTime.Now;\nDateTime end = DateTime.Now.AddYears(1);\nList<DateTime> dates = GetDatesForNthDOWOfMonth(1, DayOfWeek.Monday, beg, end);\n// To see the list of dateTimes, for verification\nforeach (DateTime d in dates)\n{\n MessageBox.Show(string.Format(\"Found {0}\", d.ToString()));\n}\n List<DateTime> dates = GetDatesForNthDOWOfMonth(2, DayOfWeek.Friday, beg, end);\n" }, { "answer_id": 72108598, "author": "Darrel K.", "author_id": 2746057, "author_profile": "https://Stackoverflow.com/users/2746057", "pm_score": 0, "selected": false, "text": "/// <summary>\n/// Gets the Nth occurrence of the specified weekday in the month.\n/// </summary>\npublic static DateTime GetNthOfWeekDayInMonth(this DateTime dt, DayOfWeek dayOfWeek, int n)\n{\n //Get the first day of the month\n DateTime fd = dt.AddDays(-dt.Day).AddDays(1);\n // Get the FIRST occurrence of the specified weekday in the month.\n fd = dayOfWeek >= fd.DayOfWeek ? fd.AddDays(dayOfWeek - fd.DayOfWeek) : fd.AddDays((7 + ((int)dayOfWeek)) - ((int)fd.DayOfWeek));\n // Get the nth occurrence by adding the weeks\n fd = fd.AddDays((n-1) * 7);\n //Throw exception if you do not want to go past the specified month?\n if (fd.Month != dt.Month) throw new Exception($\"There is no {n} week in this month\");\n return fd;\n}\n new DateTime(2022, 05, 12).GetNthOfWeekDayInMonth(DayOfWeek.Tuesday, 2);\n// Output: [2022/05/10 00:00:00]\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19038/" ]
288,540
<p>C#: How do you tell which item index is selected in ListView?</p>
[ { "answer_id": 288551, "author": "Cristian Libardo", "author_id": 16526, "author_profile": "https://Stackoverflow.com/users/16526", "pm_score": 2, "selected": false, "text": "myListView.SelectedIndices\n" }, { "answer_id": 288555, "author": "Nathan W", "author_id": 6335, "author_profile": "https://Stackoverflow.com/users/6335", "pm_score": 3, "selected": true, "text": "ListView mylistv = new ListView();\nvar index = mylistv.SelectedIndices();\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288540", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
288,546
<p>I need to connect to an Exchange mailbox in a Python script, without using any profile setup on the local machine (including using Outlook). If I use win32com to create a MAPI.Session I could logon (with the Logon() method) with an existing profile, but I want to just provide a username &amp; password.</p> <p>Is this possible? If so, could someone provide example code? I would prefer if it only used the standard library and the pywin32 package. Unfortunately, enabling IMAP access for the Exchange server (and then using imaplib) is not possible.</p> <p>In case it is necessary: all the script will be doing is connecting to the mailbox, and running through the messages in the Inbox, retrieving the contents. I can handle writing the code for that, if I can get a connection in the first place!</p> <p>To clarify regarding Outlook: Outlook will be installed on the local machine, but it does not have any accounts setup (i.e. all the appropriate libraries will be available, but I need to operate independently from anything setup inside of Outlook).</p>
[ { "answer_id": 3072491, "author": "Erik Cederstrand", "author_id": 219640, "author_profile": "https://Stackoverflow.com/users/219640", "pm_score": 7, "selected": false, "text": "from exchangelib import DELEGATE, Account, Credentials\n\ncredentials = Credentials(\n username='MYWINDOMAIN\\\\myusername', # Or myusername@example.com for O365\n password='topsecret'\n)\na = Account(\n primary_smtp_address='john@example.com', \n credentials=credentials, \n autodiscover=True, \n access_type=DELEGATE\n)\n# Print first 100 inbox messages in reverse order\nfor item in a.inbox.all().only('subject').order_by('-datetime_received')[:100]:\n print(item.subject)\n" }, { "answer_id": 24020665, "author": "Kyle Roux", "author_id": 3704005, "author_profile": "https://Stackoverflow.com/users/3704005", "pm_score": 5, "selected": false, "text": "import smtplib\n\nurl = YOUR_EXCHANGE_SERVER\nconn = smtplib.SMTP(url,587)\nconn.starttls()\nuser,password = (EXCHANGE_USER,EXCHANGE_PASSWORD)\nconn.login(user,password)\n message = 'From: FROMADDR\\nTo: TOADDRLIST\\nSubject: Your subject\\n\\n{}'\nfrom, to = fromaddr,toaddrs\ntxt = 'This is my message'\nconn.sendmail(fromaddr,toaddrs,msg.format(txt))\n import imaplib\n\nurl = YOUR_EXCHANGE_URL\nconn = imaplib.IMAP4_SSL(url,993)\nuser,password = (EXCHANGE_USER,EXCHANGE_PASSWORD)\nconn.login(user,password)\nconn.select('INBOX')\nresults,data = conn.search(None,'ALL')\nmsg_ids = data[0]\nmsg_id_list = msg_ids.split()\n latest_email_id = msg_id_list[-1]\nresult,data = conn.fetch(latest_email_id,\"(RFC822)\")\nraw_email = data[0][1]\n from email.parser import Parser\n\np = Parser()\nmsg = p.parsestr(raw_email)\n msg.get('From')\nmsg.get('Subject')\n msg.get_payload()\n def process_multipart_message(message):\n rtn = ''\n if message.is_multipart():\n for m in message.get_payload():\n rtn += process_multipart_message(m)\n else:\n rtn += message.get_payload()\n return rtn\n msg_contant = process_multipart_message(msg)\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288546", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4966/" ]
288,550
<p>How can I create a Sidebar form in delphi.</p> <p>I try the <code>ScreenSnap</code> and <code>Align</code> properties but I need that the form stay visible even if the user maximize other forms, without been on top. Just like the windows sidebar do.</p> <p><strong>Update</strong>: From the comments: if a window is maximized, it maximizes next to the window, not in front of or behind.</p>
[ { "answer_id": 288588, "author": "Kluge", "author_id": 8752, "author_profile": "https://Stackoverflow.com/users/8752", "pm_score": 0, "selected": false, "text": "SetWindowPos(Handle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);\n" }, { "answer_id": 288980, "author": "Rob Kennedy", "author_id": 33732, "author_profile": "https://Stackoverflow.com/users/33732", "pm_score": 4, "selected": true, "text": "ShAppBarMessage" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24293/" ]
288,559
<p>Even though error_reporting is set to 0, database errors are still being printed to screen. Is there a setting somewhere I can change to disable database error reporting? This is for CodeIgniter v1.6.x</p> <p><strong>EDIT</strong>: Re: Fixing errors - Um, yes. I want to fix the errors. I get error notices from my error log, not from what my visitors see printed to their screen. That helps no one, and hurts my system's security.</p> <p><strong>EDIT 2</strong>: Setting error_reporting to 0 does not affect CodeIgniter's built-in error logging class from writing to the error log.</p>
[ { "answer_id": 288748, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "config/database.php: // ['db_debug'] TRUE/FALSE - Whether database errors should be displayed.\n $db['default']['db_debug'] = FALSE;\n" }, { "answer_id": 15292463, "author": "NaturalBornCamper", "author_id": 1046013, "author_profile": "https://Stackoverflow.com/users/1046013", "pm_score": 4, "selected": false, "text": "$db_debug = $this->db->db_debug;\n$this->db->db_debug = false;\n\n// Do your sketchy stuff here\n\n$this->db->db_debug = $db_debug;\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
288,560
<p>I have the following structure:</p> <pre><code> &lt;StructLayout(LayoutKind.Sequential)&gt; _ Public Structure _WTS_CLIENT_ADDRESS Public AddressFamily As Integer &lt;MarshalAs(UnmanagedType.ByValArray, SizeConst:=20)&gt; _ Public Address() As Byte End Structure </code></pre> <p>Which is populated by the following call:</p> <pre><code> Dim _ClientIPAddress As New _WTS_CLIENT_ADDRESS Dim rtnPtr As IntPtr Dim rtncount As Int32 NativeMethods.WTSQuerySessionInformation(CInt(NativeMethods.WTS_CURRENT_SERVER_HANDLE), NativeMethods.WTS_CURRENT_SESSION, NativeMethods.WTS_INFO_CLASS.WTSClientAddress, rtnPtr, rtncount) '_ClientIPAddress() _ClientIPAddress = _ CType(System.Runtime.InteropServices.Marshal.PtrToStructure(rtnPtr, GetType(_WTS_CLIENT_ADDRESS)), _WTS_CLIENT_ADDRESS) </code></pre> <p>The address byte array is being populated, but I have no idea how to convert it into a useful string or integer values. The MDSN documentation is sparse: <a href="http://msdn.microsoft.com/en-us/library/aa383857(VS.85).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/aa383857(VS.85).aspx</a></p>
[ { "answer_id": 311934, "author": "Jérôme Laban", "author_id": 26346, "author_profile": "https://Stackoverflow.com/users/26346", "pm_score": 3, "selected": true, "text": "IPAddress address = new IPAddress(_ClientIPAddress.Address.Skip(2).Take(4).ToArray());\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13338/" ]
288,564
<p>I have a web application project (wap) that is successfully being deployed to a development server by our tfsbuild server.</p> <p>I'd like the build server to run our collection of webtests after deployment.</p> <p>What is a best practice (or ANY practice) for doing this?</p>
[ { "answer_id": 311934, "author": "Jérôme Laban", "author_id": 26346, "author_profile": "https://Stackoverflow.com/users/26346", "pm_score": 3, "selected": true, "text": "IPAddress address = new IPAddress(_ClientIPAddress.Address.Skip(2).Take(4).ToArray());\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288564", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2424/" ]
288,573
<p>When using regular expressions in Ruby, what is the difference between $1 and \1?</p>
[ { "answer_id": 288595, "author": "Avdi", "author_id": 20487, "author_profile": "https://Stackoverflow.com/users/20487", "pm_score": 7, "selected": true, "text": "sub gsub \"foobar\".sub(/foo(.*)/, '\\1\\1') # => \"barbar\"\n if \"foobar\" =~ /foo(.*)/ then \n puts \"The matching word was #{$1}\"\nend\n \"The matching word was bar\"\n# => nil\n" }, { "answer_id": 288685, "author": "Brian Carper", "author_id": 23070, "author_profile": "https://Stackoverflow.com/users/23070", "pm_score": 5, "selected": false, "text": "sub \"foobar\".sub(/(.*)/, $1.reverse) # WRONG: either uses a PREVIOUS value of $1, \n # or gives an error if $1 is unbound\n \\1 sub \\1 \"foobar\".sub(/(.*)/, '\\1'.reverse) # WRONG: returns '1\\'\n sub \"foobar\".sub(/.*/){|m| m.reverse} # => returns 'raboof'\n\"foobar\".sub(/(...)(...)/){$1.reverse + $2.reverse} # => returns 'oofrab'\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4883/" ]
288,575
<p>I inherited a project that uses SQL Server 200x, wherein a column that stores a value that is always considered as a percentage in the problem domain is stored as its greater than 1 decimal equivalent. For example, <em>70%</em> (0.7, literally) is stored as <em>70</em>, <em>100%</em> as <em>100</em>, etc. Aside from the need to remember to * 0.01 on retrieved values and * 100 before persisting values, it doesn't seem to be a problem in and of itself. <strike>It does make my head explode though</strike>... so is there a good reason for it that I'm missing? Are there compelling reasons to fix it, given that there is a fair amount of code written to work with the pseudo-percentages?</p> <p>There are a few cases where greater than 100% occurs, but I don't see why the value wouldn't just be stored as 1.05, for example, in those cases.</p> <p>EDIT: Head feeling better, and slightly smarter. Thanks for all the insights.</p>
[ { "answer_id": 288643, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 2, "selected": false, "text": "(0.3==3*.1)\n abs( 0.3 - 3*.1 )\n (column-SomeValue) BETWEEN -0.0001 AND 0.0001 ABS(column-SomeValue) < 0.0001 column = SomeValue" }, { "answer_id": 288727, "author": "P Daddy", "author_id": 36388, "author_profile": "https://Stackoverflow.com/users/36388", "pm_score": 4, "selected": true, "text": "decimal principle * integerPercentage / 100\n decimal" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4296/" ]
288,582
<p>Here's the scenario - a client uploads a Sybase dump file to (gzipped) to our local FTP server. We have an automated process which picks these up and then moves them to different server within the network where the database server resides. Unfortunately, this transfer is over a WAN, which for large files takes a long time, and sometimes our clients forget to FTP in binary mode, which results in 10GB of transfer over our WAN all for nothing as the dump file can't be loaded at the other end. What I'd like to do, is verify the integrity of the dump file on the local server before sending it out over the WAN, but I can't just try and "load" the dump file, as we don't have Sybase installed (and can't install it). Are there any tools or bits of code that I can use to do this?</p>
[ { "answer_id": 555574, "author": "brianegge", "author_id": 14139, "author_profile": "https://Stackoverflow.com/users/14139", "pm_score": 3, "selected": true, "text": "$ md5sum *.dmp\n2bddf3cd8b04010183dd3295ce7594ff pubs_1.dmp\n7510e0250c8d68bae3e0e794c211e60b pubs_2.dmp\n091fe54fa5fd81d8c109cc7835d37f4a pubs_3.dmp\n $ gunzip --test *.dmp\ngunzip: pubs_3.dmp: unexpected end of file\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1030/" ]
288,584
<p>I want to use <a href="http://code.google.com/apis/visualization/documentation/gallery/annotatedtimeline.html" rel="nofollow noreferrer">Google's Annotated Time Line Visualization</a>. It is very easy to make this work by manually adding the lines for column &amp; row data. This is all done through attributes of google.visualization.DataTable(). I would like to update this data table dynamically, but I do not know how. The data is on a server running MS SQL Server 2005. </p> <p>I found a <a href="http://groups.google.com/group/google-visualization-api/browse_thread/thread/4dc84221fbd3ade5/d57109c9b45fd741?lnk=raot&amp;pli=1" rel="nofollow noreferrer">post</a> to accomplish this with PHP and MySQL, but I do not know how to translate this to VB .NET or C# (either is fine).</p> <p>Does anyone know how to make this use MS SQL Server data in .NET or of a better way to have the code dynamically generated so new data does not have to have the lines manually added every day?</p> <p>Thanks!</p>
[ { "answer_id": 369245, "author": "jjclarkson", "author_id": 46425, "author_profile": "https://Stackoverflow.com/users/46425", "pm_score": 1, "selected": false, "text": "$connectionstring = odbc_connect($db, $user, $pass) or die(\"Connection Failed\");\n$query = \"...\";\n$result = odbc_do($connectionstring, $query) or die(\"Query Failed\");\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16771/" ]
288,603
<p>I am getting </p> <pre><code>Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in *filename* on line 81 </code></pre> <p>While running a query to build a chart. The query gets data from the mysql db and uses it to build the chart.</p> <p>Usually, I get this error and go to the code and find where I've screwed up, fix it, and move on. The tricky part about this problem is that the query is actually running and the chart is being built and displayed accurately. Why is my server (localhost on xampp) telling me that the query result is bad when it can utilize the resource just fine?</p> <p>Here is the full query:</p> <pre><code>$chart=array(); $roll=array(); //select used terms $rosh=mysql_query("select distinct term from search_terms"); while($roshrow=mysql_fetch_assoc($rosh)){ extract($roshrow); $roll[]=$term; } //select term_number for each term foreach($roll as $sterm){ $termarray=array(); **//following is line 81** $bashq="select term_number from search_terms where term ='$sterm'"; $bash=mysql_query($bashq); while($brow=mysql_fetch_assoc($bash)){ extract($brow); //put results into array to sum $termarray[]=$term_number; } $termsum=array_sum($termarray); //put term=&gt;number array for chart script $chart[$sterm]=$termsum; } //sort array so high numbers at beginning arsort($chart); //slice top 10 terms $chart=array_slice($chart,0,10); </code></pre>
[ { "answer_id": 288610, "author": "mercutio", "author_id": 1951, "author_profile": "https://Stackoverflow.com/users/1951", "pm_score": 3, "selected": true, "text": "$rosh=mysql_query(\"select distinct term from search_terms\")\n or die(\"Error with query: \" . mysql_error());\n $bash=mysql_query($bashq)\n or die(\"Error with query: \" . mysql_error();\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288603", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1149/" ]
288,612
<p>I have a form that excepts a file upload in ASP.NET. I need to increase the max upload size to above the 4 MB default.</p> <p>I have found in certain places referencing the below code at <a href="http://msdn.microsoft.com/en-us/library/system.web.configuration.httpruntimesection.maxrequestlength.aspx" rel="noreferrer">msdn</a>. </p> <pre><code>[ConfigurationPropertyAttribute("maxRequestLength", DefaultValue = )] </code></pre> <p>None of the references actually describe how to use it, and I have tried several things with no success. I only want to modify this attribute for certain pages that are asking for file upload.</p> <p>Is this the correct route to take? And how do I use this?</p>
[ { "answer_id": 288667, "author": "ben", "author_id": 7561, "author_profile": "https://Stackoverflow.com/users/7561", "pm_score": 4, "selected": false, "text": "Web.config <system.web>\n\n <httpRuntime maxRequestLength=\"600000\"/>\n</system.web>\n" }, { "answer_id": 288675, "author": "Eric Rosenberger", "author_id": 36979, "author_profile": "https://Stackoverflow.com/users/36979", "pm_score": 10, "selected": true, "text": "<configuration>\n <system.web>\n <httpRuntime maxRequestLength=\"xxx\" />\n </system.web>\n</configuration>\n" }, { "answer_id": 15679792, "author": "Massimo Zerbini", "author_id": 940939, "author_profile": "https://Stackoverflow.com/users/940939", "pm_score": 3, "selected": false, "text": "<system.web>\n <httpRuntime executionTimeout=\"3600\" maxRequestLength=\"102400\" \n appRequestQueueLimit=\"100\" requestValidationMode=\"2.0\"\n requestLengthDiskThreshold=\"10024000\"/>\n</system.web>\n System.Web.UI.HtmlControls.HtmlInputFile" }, { "answer_id": 18531025, "author": "4imble", "author_id": 180420, "author_profile": "https://Stackoverflow.com/users/180420", "pm_score": 8, "selected": false, "text": " <system.webServer>\n <security>\n <requestFiltering>\n <requestLimits maxAllowedContentLength=\"52428800\" /> <!--50MB-->\n </requestFiltering>\n </security>\n </system.webServer>\n" }, { "answer_id": 23910210, "author": "user3683243", "author_id": 3683243, "author_profile": "https://Stackoverflow.com/users/3683243", "pm_score": 2, "selected": false, "text": "<httpRuntime maxRequestLength=\"2048576000\" />\n<sessionState timeout=\"3600\" />\n" }, { "answer_id": 31516339, "author": "damir", "author_id": 1030264, "author_profile": "https://Stackoverflow.com/users/1030264", "pm_score": 3, "selected": false, "text": "<system.web> <!-- 3GB Files / in kilobyte (3072*1024) -->\n<httpRuntime targetFramework=\"4.5\" maxRequestLength=\"3145728\"/>\n <system.webServer> <security>\n <requestFiltering>\n\n <!-- 3GB Files / in byte (3072*1024*1024) -->\n <requestLimits maxAllowedContentLength=\"3221225472\" />\n\n </requestFiltering>\n</security>\n" }, { "answer_id": 32519833, "author": "cangosta", "author_id": 797252, "author_profile": "https://Stackoverflow.com/users/797252", "pm_score": 4, "selected": false, "text": "<system.web>\n <compilation debug=\"true\" targetFramework=\"4.5\" />\n <httpRuntime targetFramework=\"4.5\" maxRequestLength=\"2147483647\" executionTimeout=\"1600\" requestLengthDiskThreshold=\"2147483647\" />\n</system.web>\n\n<system.webServer>\n <security>\n <requestFiltering>\n <requestLimits maxAllowedContentLength=\"2147483647\" />\n </requestFiltering>\n </security>\n</system.webServer>\n" }, { "answer_id": 37475722, "author": "Malik Khalil", "author_id": 4859919, "author_profile": "https://Stackoverflow.com/users/4859919", "pm_score": 6, "selected": false, "text": "<system.web>\n <!-- maxRequestLength for asp.net, in KB --> \n <httpRuntime maxRequestLength=\"15360\" ></httpRuntime> \n</system.web>\n <system.web>\n <!-- maxRequestLength for asp.net, in KB --> \n <httpRuntime maxRequestLength=\"15360\" ></httpRuntime> \n</system.web>\n\n<system.webServer> \n <security> \n <requestFiltering> \n <!-- maxAllowedContentLength, for IIS, in bytes --> \n <requestLimits maxAllowedContentLength=\"15728640\" ></requestLimits>\n </requestFiltering> \n </security>\n</system.webServer>\n" }, { "answer_id": 46450705, "author": "mbadeveloper", "author_id": 3752193, "author_profile": "https://Stackoverflow.com/users/3752193", "pm_score": 2, "selected": false, "text": "<httpRuntime targetFramework=\"4.6.1\" requestValidationMode=\"2.0\" maxRequestLength=\"10485760\" />\n" }, { "answer_id": 52671089, "author": "Martin", "author_id": 355272, "author_profile": "https://Stackoverflow.com/users/355272", "pm_score": 3, "selected": false, "text": "<location path=\"YourAreaName/YourControllerName>/YourActionName>\">\n <system.web>\n <!-- 15MB maxRequestLength for asp.net, in KB 15360 -->\n <httpRuntime maxRequestLength=\"15360\" />\n </system.web>\n <system.webServer>\n <security>\n <requestFiltering>\n <!-- 15MB maxAllowedContentLength, for IIS, in bytes 15728640 -->\n <requestLimits maxAllowedContentLength=\"15728640\" />\n </requestFiltering>\n </security>\n </system.webServer>\n</location>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/576/" ]
288,614
<p>How would I go about creating a real world form creation class that I can use to display a new form with fields of different types, as how many fields I want, I can use drop downs and I can do all of this by using OOP?</p>
[ { "answer_id": 288706, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 4, "selected": true, "text": "method action enctype class Form {\n var $attributes, // array, with keys ['method' => 'post', 'action' => 'mypage.php'...]\n $heading,\n $description,\n $inputs // array of FormInput elements\n ;\n\n function render() {\n $output = \"<form \" . /* insert attributes here */ \">\"\n . \"<h1>\" . $this->heading . \"</h1>\"\n . \"<p>\" . $this->description . \"</p>\"\n ;\n // wrap your inputs in whatever output style you prefer:\n // ordered list, table, etc.\n foreach ($this->inputs as $input) {\n $output .= $input->render();\n }\n $output .= \"</form>\";\n return $output;\n }\n}\n" }, { "answer_id": 288798, "author": "starmonkey", "author_id": 29854, "author_profile": "https://Stackoverflow.com/users/29854", "pm_score": 3, "selected": false, "text": "echo QuickFormHelper::renderFromConfig(array(\n 'name' => 'area_edit',\n 'elements' => array(\n 'area_id' => array('type' => 'hidden'),\n 'active' => array('type' => 'toggle'),\n 'site_name' => array('type' => 'text'),\n 'base_url' => array('type' => 'text'),\n 'email' => array('type' => 'text'),\n 'email_admin' => array('type' => 'text'),\n 'email_financial' => array('type' => 'text'),\n 'cron_enabled' => array('type' => 'toggle'),\n 'address' => array('type' => 'address'),\n ),\n 'groups' => array(\n 'Basic Details' => array('site_name', 'base_url'),\n 'Address Details' => array('address'),\n 'Misc Details' => array(), // SM: Display the rest with this heading.\n ),\n 'defaults' => $site,\n 'callback_on_success' => array(\n 'object' => $module,\n 'function' => 'saveSite',\n ),\n));\n" }, { "answer_id": 10885443, "author": "Andrew Odri", "author_id": 574904, "author_profile": "https://Stackoverflow.com/users/574904", "pm_score": 0, "selected": false, "text": "$form = new Form(\"Register\", \"form.php\"); \n\n$personal = new Block(\"Personal Information\"); \n\n$name = new Text(\"name\", \"Your name\"); \n$name->setDescription(\"this is my description\"); \n$name->addValidator(new MaxLengthValidator(\"The name you have entered is too long\", 30)); \n\n...\n" }, { "answer_id": 40190467, "author": "JG Estiot", "author_id": 964292, "author_profile": "https://Stackoverflow.com/users/964292", "pm_score": 2, "selected": false, "text": "$fm = new form('myform');\n$fm->binding(FORM_DATABASE);\n$fm->state(FORM_RETRIEVE); \n$fm->set_recno(1);\n$fm->add(new form_heading(\"My form\"));\n$fm->add($el=new form_input(\"name\",40));\n$el->bind_data('mytable','mycolumn');\n$el->set_attribute('size', 25);\n$el->set_default('Name');\n$fm->add($el=new form_submit(\"submit_btn\",\"Submit\"));\nif($fm->manage())\n {\n redirect or do something else here. The interaction with the form is done. The initial state for the form was FORM_RETRIEVE. If it had been FORM_NEW it would have displayed default values instead of the retrieved record and saved the form as a new record in the table. \n }\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37418/" ]
288,619
<p>Say I have a sql query </p> <pre><code>SELECT fname, lname, dob, ssn, address1, address2, zip, phone,state from users </code></pre> <p>Now say the records are now either in dictionary base or a strongly typed collection.</p> <p>I have a grid view control and i want to bind it to my collection but I only want to display fname, lname, dob and ssn and not the other columns.</p> <p>Is there an easy way to extract the columns and then bind to the extracted item? Not sure if LINQ would be helpful here.</p> <p>This is a test project as I am getting familiar with the web world wqith VS-2008</p>
[ { "answer_id": 288627, "author": "Cristian Libardo", "author_id": 16526, "author_profile": "https://Stackoverflow.com/users/16526", "pm_score": 2, "selected": false, "text": "from user in UserCollection\nselect new { FirstName=user.fname, LastName=user.lname, Dob=user.dob, SSN=user.ssn }\n" }, { "answer_id": 288632, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 0, "selected": false, "text": "var filteredUser = from U in Users\n select new { U.fname, U.lname, U.dob, U.SSN };\n" }, { "answer_id": 288635, "author": "lomaxx", "author_id": 493, "author_profile": "https://Stackoverflow.com/users/493", "pm_score": 1, "selected": false, "text": "<asp:GridView ID=\"gvwExample\" runat=\"server\" AutoGenerateColumns=\"False\" >\n<columns>\n<asp:BoundField DataField=\"firstname\" HeaderText=\"First Name\" />\n<asp:BoundField DataField=\"lastname\" HeaderText=\"Last Name\" />\n<asp:BoundField DataField=\"hiredate\" HeaderText=\"Date Hired\" />\n</columns>\n</asp:GridView> \n" }, { "answer_id": 288648, "author": "Nathan W", "author_id": 6335, "author_profile": "https://Stackoverflow.com/users/6335", "pm_score": 0, "selected": false, "text": "Dim _records = From user in users _\n Select New With {.FirstName = user.fname,_\n .Lastname = user.lname,.dob = user.dob,.ssn = user.ssn}\n\n{gridcontrol}.datasource = _records\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288619", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
288,637
<p>I need to construct some rather simple SQL, I suppose, but as it's a rare event that I work with DBs these days I can't figure out the details.</p> <p>I have a table 'posts' with the following columns:</p> <blockquote> <p>id, caption, text</p> </blockquote> <p>and a table 'comments' with the following columns:</p> <blockquote> <p>id, name, text, post_id</p> </blockquote> <p>What would the (single) SQL statement look like which retrieves the captions of all posts which have one or more comments associated with it through the 'post_id' key? The DBMS is MySQL if it has any relevance for the SQL query.</p>
[ { "answer_id": 288655, "author": "hark", "author_id": 34826, "author_profile": "https://Stackoverflow.com/users/34826", "pm_score": -1, "selected": false, "text": "SELECT p.caption FROM posts p WHERE (SELECT COUNT(*) FROM comments c WHERE c.post_id=p.id) > 1; SELECT COUNT(*) comment_count posts comments SELECT p.caption FROM posts p WHERE comment_count > 1" }, { "answer_id": 288660, "author": "lomaxx", "author_id": 493, "author_profile": "https://Stackoverflow.com/users/493", "pm_score": -1, "selected": false, "text": "SELECT caption FROM posts WHERE id IN (SELECT post_id FROM comments HAVING count(*) > 0)\n" }, { "answer_id": 288676, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 2, "selected": false, "text": "SELECT DISTINCT p.caption, p.id\n FROM posts p, \n comments c \n WHERE c.post_ID = p.ID \n" }, { "answer_id": 288701, "author": "Tjofras", "author_id": 37486, "author_profile": "https://Stackoverflow.com/users/37486", "pm_score": 0, "selected": false, "text": "SELECT caption FROM posts \nINNER JOIN comments ON comments.post_id = posts.id \nGROUP BY posts.id;\n having count() inner join" }, { "answer_id": 288784, "author": "James", "author_id": 16282, "author_profile": "https://Stackoverflow.com/users/16282", "pm_score": 0, "selected": false, "text": "SELECT DISTINCT caption\nFROM posts\n INNER JOIN comments ON posts.id = comments.post_id\n" }, { "answer_id": 289038, "author": "Ian Varley", "author_id": 37539, "author_profile": "https://Stackoverflow.com/users/37539", "pm_score": 0, "selected": false, "text": "SELECT * FROM posts P \n WHERE EXISTS (SELECT * FROM Comments WHERE post_id = P.id)\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288637", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4055/" ]
288,687
<p>I've written a cheap &amp; cheerful sound board in for my Mac, and I play the various sounds with NSSound like this:</p> <pre><code>-(void)play:(NSSound *)soundEffect:(BOOL)stopIfPlaying { BOOL wasPlaying = FALSE; if([nowPlaying isPlaying]) { [nowPlaying stop]; wasPlaying = TRUE; } if(soundEffect != nowPlaying) { [soundEffect play]; nowPlaying = soundEffect; } else if(soundEffect == nowPlaying &amp;&amp; ![nowPlaying isPlaying] &amp;&amp; !wasPlaying) { [nowPlaying play]; } } </code></pre> <p>Rather than just stop it dead, I'd like it to fade out over a couple of seconds or so.</p>
[ { "answer_id": 289386, "author": "Chris Blackwell", "author_id": 1329401, "author_profile": "https://Stackoverflow.com/users/1329401", "pm_score": 0, "selected": false, "text": "if([nowPlaying isPlaying]) {\n for(int i = 1; i < 100; ++i)\n {\n [nowPlaying setVolume: (1.0 / i)];\n Sleep(20);\n }\n [nowPlaying stop];\n wasPlaying = TRUE;\n}\n" }, { "answer_id": 294399, "author": "Stuart Grimshaw", "author_id": 11470, "author_profile": "https://Stackoverflow.com/users/11470", "pm_score": 2, "selected": true, "text": "-(void)play:(NSSound *)soundEffect:(BOOL)stopIfPlaying {\n BOOL wasPlaying = FALSE;\n\n if([nowPlaying isPlaying]) {\n struct timespec ts;\n ts.tv_sec = 0;\n ts.tv_nsec = 25000000;\n\n // If the sound effect is the same, fade it out.\n if(soundEffect == nowPlaying)\n {\n for(int i = 1; i < 30; ++i)\n {\n [nowPlaying setVolume: (1.0 / i )];\n nanosleep(&ts, &ts);\n } \n }\n\n [nowPlaying stop];\n [nowPlaying setVolume:1];\n wasPlaying = TRUE;\n } \n\n if(soundEffect != nowPlaying)\n {\n [soundEffect play];\n nowPlaying = soundEffect;\n } else if(soundEffect == nowPlaying && ![nowPlaying isPlaying] && !wasPlaying) {\n [nowPlaying play];\n }\n}\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288687", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11470/" ]
288,695
<p>I want to parse an Apache <strong>access.log</strong> file with a python program in a certain way, and though I am completely new to object-oriented programming, I want to start doing it now.</p> <p>I am going to create a class <strong>ApacheAccessLog</strong>, and the only thing I can imagine now, it will be doing is '<strong>readline</strong>' method. Is it conventionally correct to inherit from the builtin <strong>file</strong> class in this case, so the class will behave just like an instance of the <strong>file</strong> class itself, or not? What is the best way of doing that?</p>
[ { "answer_id": 288807, "author": "Adam Byrtek", "author_id": 36656, "author_profile": "https://Stackoverflow.com/users/36656", "pm_score": 5, "selected": true, "text": "readline readline" }, { "answer_id": 307776, "author": "Francis Stephens", "author_id": 39476, "author_profile": "https://Stackoverflow.com/users/39476", "pm_score": 3, "selected": false, "text": "ArrayList public class CountingList extends ArrayList {\n int counter = 0;\n\n public void add(Object o) {\n counter++;\n super.add(0);\n }\n\n public void addAll(Collection c) {\n count += c.size();\n super.addAll(c);\n }\n\n // Etc.\n}\n ArrayList addAll Collection addAll addAll ArrayList List CountingList" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37511/" ]
288,699
<p>Can someone show me how to get the <code>top</code> &amp; <code>left</code> position of a <code>div</code> or <code>span</code> element when one is not specified?</p> <p>ie:</p> <pre><code>&lt;span id='11a' style='top:55px;' onmouseover=&quot;GetPos(this);&quot;&gt;stuff&lt;/span&gt; &lt;span id='12a' onmouseover=&quot;GetPos(this);&quot;&gt;stuff&lt;/span&gt; </code></pre> <p>In the above, if I do:</p> <pre><code>document.getElementById('11a').style.top </code></pre> <p>The value of <code>55px</code> is returned. However, if I try that for <code>span</code> '12a', then nothing gets returned.</p> <p>I have a bunch of <code>div</code>/<code>span</code>s on a page that I cannot specify the <code>top</code>/<code>left</code> properties for, but I need to display a <code>div</code> directly under that element.</p>
[ { "answer_id": 288708, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 8, "selected": true, "text": "function getPos(el) {\n // yay readability\n for (var lx=0, ly=0;\n el != null;\n lx += el.offsetLeft, ly += el.offsetTop, el = el.offsetParent);\n return {x: lx,y: ly};\n}\n var x = el.offsetLeft, y = el.offsetTop;\n var yPositionOfNewElement = el.offsetTop + el.offsetHeight + someMargin;\n" }, { "answer_id": 288731, "author": "alex", "author_id": 31671, "author_profile": "https://Stackoverflow.com/users/31671", "pm_score": 8, "selected": false, "text": "getBoundingClientRect() top left right bottom var offsets = document.getElementById('11a').getBoundingClientRect();\nvar top = offsets.top;\nvar left = offsets.left;\n var offsets = $('#11a').offset();\nvar top = offsets.top;\nvar left = offsets.left;\n" }, { "answer_id": 7207965, "author": "Dylan Valade", "author_id": 638452, "author_profile": "https://Stackoverflow.com/users/638452", "pm_score": 4, "selected": false, "text": "document.ready window.load load load $(window).load(function(){ \n // Log the position with jQuery\n var position = $('#myDivInQuestion').position();\n console.log('X: ' + position.left + \", Y: \" + position.top );\n});\n" }, { "answer_id": 13019016, "author": "Jens Frandsen", "author_id": 1451951, "author_profile": "https://Stackoverflow.com/users/1451951", "pm_score": 3, "selected": false, "text": "function getTopPos(el) {\n for (var topPos = 0;\n el != null;\n topPos += el.offsetTop, el = el.offsetParent);\n return topPos;\n}\n function getLeftPos(el) {\n for (var leftPos = 0;\n el != null;\n leftPos += el.offsetLeft, el = el.offsetParent);\n return leftPos;\n}\n" }, { "answer_id": 27809127, "author": "lukeed", "author_id": 3577474, "author_profile": "https://Stackoverflow.com/users/3577474", "pm_score": 2, "selected": false, "text": "element.getBoundingClientRect() $(element).offset()" }, { "answer_id": 30949389, "author": "Benjamin Intal", "author_id": 174172, "author_profile": "https://Stackoverflow.com/users/174172", "pm_score": 4, "selected": false, "text": "var rect = el.getBoundingClientRect();\n\nvar position = {\n top: rect.top + window.pageYOffset,\n left: rect.left + window.pageXOffset\n};\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26685/" ]
288,707
<p>I'm working with large numbers that I can't have rounded off. Using Lua's standard math library, there seem to be no convenient way to preserve precision past some internal limit. I also see there are several libraries that can be loaded to work with big numbers:</p> <ol> <li><a href="http://oss.digirati.com.br/luabignum/" rel="noreferrer">http://oss.digirati.com.br/luabignum/</a></li> <li><a href="http://www.tc.umn.edu/~ringx004/mapm-main.html" rel="noreferrer">http://www.tc.umn.edu/~ringx004/mapm-main.html</a></li> <li><a href="http://lua-users.org/lists/lua-l/2002-02/msg00312.html" rel="noreferrer">http://lua-users.org/lists/lua-l/2002-02/msg00312.html</a> (might be identical to #2)</li> <li><a href="http://www.gammon.com.au/scripts/doc.php?general=lua_bc" rel="noreferrer">http://www.gammon.com.au/scripts/doc.php?general=lua_bc</a> (but I can't find any source)</li> </ol> <p>Further, there are <a href="http://en.wikipedia.org/wiki/Arbitrary-precision_arithmetic#Arbitrary-precision_software" rel="noreferrer">many libraries</a> in C that could be called from Lua, if the bindings where established.</p> <p>Have you had any experience with one or more of these libraries?</p>
[ { "answer_id": 620789, "author": "Jon Ericson", "author_id": 1438, "author_profile": "https://Stackoverflow.com/users/1438", "pm_score": 3, "selected": false, "text": "PLAT src/Makefile linux none libmapm.a /usr/local/lib/ m_apm.h m_apm_lc.h /usr/local/include/ LUA LUAINC LUALIB LUABIN MAMP mapm.so /usr/local/lib/lua/5.1/" }, { "answer_id": 863538, "author": "lhf", "author_id": 107090, "author_profile": "https://Stackoverflow.com/users/107090", "pm_score": 4, "selected": false, "text": "local bc = require\"bc\"\ns=bc.pow(2,1000):tostring()\nz=0\nfor i=1,#s do\n z=z+s:byte(i)-(\"0\"):byte(1)\nend\nprint(z)\n" }, { "answer_id": 62824599, "author": "Eduardo Bart", "author_id": 13902049, "author_profile": "https://Stackoverflow.com/users/13902049", "pm_score": 1, "selected": false, "text": "local bint = require 'bint'(1024)\nlocal n = bint(1) << 1000\nlocal digits = tostring(n)\nlocal sum = 0\nfor i=1,#digits do\n sum = sum + tonumber(digits:sub(i,i))\nend\nprint(sum) -- should output 1366\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1438/" ]
288,715
<p>How can I check whether a variable is defined in Ruby? Is there an <code>isset</code>-type method available?</p>
[ { "answer_id": 288724, "author": "digitalsanctum", "author_id": 22436, "author_profile": "https://Stackoverflow.com/users/22436", "pm_score": 4, "selected": false, "text": "defined?(your_var) your_var.nil?" }, { "answer_id": 288726, "author": "Ricardo Acras", "author_id": 19224, "author_profile": "https://Stackoverflow.com/users/19224", "pm_score": 11, "selected": true, "text": "defined? nil >> a = 1\n => 1\n>> defined? a\n => \"local-variable\"\n>> defined? b\n => nil\n>> defined? nil\n => \"nil\"\n>> defined? String\n => \"constant\"\n>> defined? 1\n => \"expression\"\n >> n = nil \n>> defined? n\n => \"local-variable\"\n" }, { "answer_id": 288729, "author": "danmayer", "author_id": 27738, "author_profile": "https://Stackoverflow.com/users/27738", "pm_score": 7, "selected": false, "text": "def get_var\n @var ||= SomeClass.new()\nend\n" }, { "answer_id": 3724712, "author": "Sardathrion - against SE abuse", "author_id": 232794, "author_profile": "https://Stackoverflow.com/users/232794", "pm_score": 3, "selected": false, "text": "require 'rubygems'\nrequire 'rainbow'\nif defined?(var).nil? # .nil? is optional but might make for clearer intent.\n print \"var is not defined\\n\".color(:red)\nelse\n print \"car is defined\\n\".color(:green)\nend\n" }, { "answer_id": 6152507, "author": "foomip", "author_id": 773112, "author_profile": "https://Stackoverflow.com/users/773112", "pm_score": 6, "selected": false, "text": "if (defined?(var)).nil? # will now return true or false\n print \"var is not defined\\n\".color(:red)\nelse\n print \"var is defined\\n\".color(:green)\nend\n var" }, { "answer_id": 9728836, "author": "Bruno Barros", "author_id": 1272706, "author_profile": "https://Stackoverflow.com/users/1272706", "pm_score": 3, "selected": false, "text": "unless defined?(var)\n #ruby code goes here\nend\n=> true\n" }, { "answer_id": 10049018, "author": "user761856", "author_id": 761856, "author_profile": "https://Stackoverflow.com/users/761856", "pm_score": 4, "selected": false, "text": "a = \"apple\"\n# Note that b is not declared\nc = nil\n\nunless defined? a\n puts \"a is not defined\"\nend\n\nunless defined? b\n puts \"b is not defined\"\nend\n\nunless defined? c\n puts \"c is not defined\"\nend\n" }, { "answer_id": 16238957, "author": "Saqib R.", "author_id": 932733, "author_profile": "https://Stackoverflow.com/users/932733", "pm_score": 3, "selected": false, "text": "defined? YourVariable" }, { "answer_id": 27445810, "author": "Robert Klemme", "author_id": 131583, "author_profile": "https://Stackoverflow.com/users/131583", "pm_score": 2, "selected": false, "text": "$ ruby -e 'def f; if 1>2; x=99; end;p x, defined? x; end;f'\nnil\n\"local-variable\"\n" }, { "answer_id": 33307520, "author": "Elliott", "author_id": 4561506, "author_profile": "https://Stackoverflow.com/users/4561506", "pm_score": 0, "selected": false, "text": "puts \"Is array1 defined and what type is it? #{defined?(@array1)}\"\n" }, { "answer_id": 41532508, "author": "donnoman", "author_id": 5220436, "author_profile": "https://Stackoverflow.com/users/5220436", "pm_score": 3, "selected": false, "text": "› irb\n>> a = nil\n=> nil\n>> defined?(a)\n=> \"local-variable\"\n>> defined?(b)\n=> nil\n>> !!defined?(a)\n=> true\n>> !!defined?(b)\n=> false\n >> (!!defined?(a) ? \"var is defined\".colorize(:green) : \"var is not defined\".colorize(:red)) == (defined?(a) ? \"var is defined\".colorize(:green) : \"var is not defined\".colorize(:red))\n=> true\n >> puts \"var is defined? #{!!defined?(a)} vs #{defined?(a)}\"\nvar is defined? true vs local-variable\n=> nil\n" }, { "answer_id": 44982213, "author": "BenKoshy", "author_id": 4880924, "author_profile": "https://Stackoverflow.com/users/4880924", "pm_score": 4, "selected": false, "text": "defined? def method1\n @x ||= method2\n end\n\n def method2\n nil\n end\n method2 nil method1 @x method2 method2 @x nil method1 method2 defined? def method1\n return @x if defined? @x\n @x = method2\n end\n" }, { "answer_id": 45691059, "author": "leberknecht", "author_id": 1466713, "author_profile": "https://Stackoverflow.com/users/1466713", "pm_score": 2, "selected": false, "text": "defined var = {}\nif defined? var['unknown']\n puts 'this is unexpected'\nend\n# will output \"this is unexpected\"\n defined? var['unknown'] \"method\" if if var.key?('unknown')\n" }, { "answer_id": 50395751, "author": "John Donner", "author_id": 4411487, "author_profile": "https://Stackoverflow.com/users/4411487", "pm_score": 2, "selected": false, "text": "defined? try foo = 1\nmy_foo = \"foo\"\nmy_bar = \"bar\"\ntry(:foo) # => 1\ntry(:bar) # => nil\ntry(my_foo) # => 1\ntry(my_bar) # => nil\n" }, { "answer_id": 66048871, "author": "stevec", "author_id": 5783745, "author_profile": "https://Stackoverflow.com/users/5783745", "pm_score": 0, "selected": false, "text": "if defined? a then \"hi\" end\n# => nil\n a = 2\nif defined? a then \"hi\" end\n# => \"hi\"\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288715", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4883/" ]
288,732
<p>I'm working on a program that searches entire drives for a given file. At the moment, I calculate an MD5 hash for the known file and then scan all files recursively, looking for a match.</p> <p>The only problem is that MD5 is painfully slow on large files. Is there a faster alternative that I can use while retaining a very small probablity of false positives?</p> <p>All code is in C#.</p> <p>Thank you.</p> <p><strong>Update</strong></p> <p>I've read that even MD5 can be pretty quick and that disk I/O should be the limiting factor. That leads me to believe that my code might not be optimal. Are there any problems with this approach?</p> <pre><code> MD5 md5 = MD5.Create(); StringBuilder sb = new StringBuilder(); try { using (FileStream fs = File.Open(fileName, FileMode.Open, FileAccess.Read)) { foreach (byte b in md5.ComputeHash(fs)) sb.Append(b.ToString("X2")); } return sb.ToString(); } catch (Exception) { return ""; } </code></pre>
[ { "answer_id": 17743934, "author": "Sergey Grischenko", "author_id": 2599083, "author_profile": "https://Stackoverflow.com/users/2599083", "pm_score": 0, "selected": false, "text": " using (FileStream stream = File.OpenRead(filePath))\n {\n using (var bufferedStream = new BufferedStream(stream, 1024 * 32))\n {\n var sha = new MD5CryptoServiceProvider();\n byte[] checksum = sha.ComputeHash(bufferedStream);\n return BitConverter.ToString(checksum).Replace(\"-\", String.Empty);\n }\n }\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14333/" ]
288,739
<p>I need to generate random numbers within a specified interval, [max;min].</p> <p>Also, the random numbers should be uniformly distributed over the interval, not located to a particular point.</p> <p>Currenly I am generating as:</p> <pre><code>for(int i=0; i&lt;6; i++) { DWORD random = rand()%(max-min+1) + min; } </code></pre> <p>From my tests, random numbers are generated around one point only.</p> <pre><code>Example min = 3604607; max = 7654607; </code></pre> <p>Random numbers generated:</p> <pre><code>3631594 3609293 3630000 3628441 3636376 3621404 </code></pre> <p>From answers below: OK, RAND_MAX is 32767. I am on C++ Windows platform. Is there any other method to generate random numbers with a uniform distribution?</p>
[ { "answer_id": 288753, "author": "Jason Coco", "author_id": 34218, "author_profile": "https://Stackoverflow.com/users/34218", "pm_score": 2, "selected": false, "text": "rand() random()" }, { "answer_id": 288760, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 2, "selected": false, "text": "RAND_MAX" }, { "answer_id": 288769, "author": "abelenky", "author_id": 34824, "author_profile": "https://Stackoverflow.com/users/34824", "pm_score": 3, "selected": false, "text": "RAND_MAX rand() RAND_MAX" }, { "answer_id": 288786, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 3, "selected": false, "text": "RAND_MAX int BigRand()\n{\n assert(INT_MAX/(RAND_MAX+1) > RAND_MAX);\n return rand() * (RAND_MAX+1) + rand();\n}\n" }, { "answer_id": 288816, "author": "anand", "author_id": 33411, "author_profile": "https://Stackoverflow.com/users/33411", "pm_score": -1, "selected": false, "text": "DWORD random = ((min) + rand()/(RAND_MAX + 1.0) * ((max) - (min) + 1));\n" }, { "answer_id": 288844, "author": "calandoa", "author_id": 26074, "author_profile": "https://Stackoverflow.com/users/26074", "pm_score": 0, "selected": false, "text": "j = 1 + (int) (10.0 * (rand() / (RAND_MAX + 1.0)));\n j = min + (int) ((max-min+1) * (rand() / (RAND_MAX + 1.0)));\n" }, { "answer_id": 288869, "author": "peterchen", "author_id": 31317, "author_profile": "https://Stackoverflow.com/users/31317", "pm_score": 6, "selected": false, "text": "rand() ((double) rand() / (RAND_MAX+1)) * (max-min+1) + min\n" }, { "answer_id": 288929, "author": "Jeff Thomas", "author_id": 1561, "author_profile": "https://Stackoverflow.com/users/1561", "pm_score": 3, "selected": false, "text": "uniform_int" }, { "answer_id": 20136256, "author": "Shoe", "author_id": 493122, "author_profile": "https://Stackoverflow.com/users/493122", "pm_score": 9, "selected": true, "text": "rand rand RAND_MAX std::uniform_int_distribution #include <iostream>\n#include <random>\nint main()\n{ \n const int range_from = 0;\n const int range_to = 1000;\n std::random_device rand_dev;\n std::mt19937 generator(rand_dev());\n std::uniform_int_distribution<int> distr(range_from, range_to);\n\n std::cout << distr(generator) << '\\n';\n}\n template<typename T>\nT random(T range_from, T range_to) {\n std::random_device rand_dev;\n std::mt19937 generator(rand_dev());\n std::uniform_int_distribution<T> distr(range_from, range_to);\n return distr(generator);\n}\n <random> std::shuffle #include <iostream>\n#include <random>\n#include <vector>\nint main()\n{ \n std::vector<int> vec = {4, 8, 15, 16, 23, 42};\n \n std::random_device random_dev;\n std::mt19937 generator(random_dev());\n \n std::shuffle(vec.begin(), vec.end(), generator);\n std::for_each(vec.begin(), vec.end(), [](auto i){std::cout << i << '\\n';});\n}\n" }, { "answer_id": 21478635, "author": "Ritualmaster", "author_id": 3256548, "author_profile": "https://Stackoverflow.com/users/3256548", "pm_score": 0, "selected": false, "text": "((double) rand() / (RAND_MAX+1)) * (max-min+1) + min" }, { "answer_id": 24628873, "author": "user3503711", "author_id": 3503711, "author_profile": "https://Stackoverflow.com/users/3503711", "pm_score": 2, "selected": false, "text": "static double rnd(void)\n{\n return (1.0 / (RAND_MAX + 1.0) * ((double)(rand())));\n}\n\nstatic void InitBetterRnd(unsigned int seed)\n{\n register int i;\n srand(seed);\n for(i = 0; i < POOLSIZE; i++)\n {\n pool[i] = rnd();\n }\n}\n\n // This function returns a number between 0 and 1\n static double rnd0_1(void)\n {\n static int i = POOLSIZE - 1;\n double r;\n\n i = (int)(POOLSIZE*pool[i]);\n r = pool[i];\n pool[i] = rnd();\n return (r);\n}\n" }, { "answer_id": 30738381, "author": "benf", "author_id": 1669250, "author_profile": "https://Stackoverflow.com/users/1669250", "pm_score": 2, "selected": false, "text": "[low, high) uint32_t rand_range_low(uint32_t low, uint32_t high)\n{\n uint32_t val;\n // only for 0 < range <= RAND_MAX\n assert(low < high);\n assert(high - low <= RAND_MAX);\n\n uint32_t range = high-low;\n uint32_t scale = RAND_MAX/range;\n do {\n val = rand();\n } while (val >= scale * range); // since scale is truncated, pick a new val until it's lower than scale*range\n return val/scale + low;\n}\n uint32_t rand_range(uint32_t low, uint32_t high)\n{\n assert(high>low);\n uint32_t val;\n uint32_t range = high-low;\n if (range < RAND_MAX)\n return rand_range_low(low, high);\n uint32_t scale = range/RAND_MAX;\n do {\n val = rand() + rand_range(0, scale) * RAND_MAX; // scale the initial range in RAND_MAX steps, then add an offset to get a uniform interval\n } while (val >= range);\n return val + low;\n}\n" }, { "answer_id": 34316875, "author": "Alberto M", "author_id": 2453661, "author_profile": "https://Stackoverflow.com/users/2453661", "pm_score": 4, "selected": false, "text": "randutils randutils #include <iostream>\n#include \"randutils.hpp\"\nint main() {\n randutils::mt19937_rng rng;\n std::cout << rng.uniform(1,6) << \"\\n\";\n}\n Boost.Random <random> Random random_device random_device boost_random #include <iostream>\n#include <boost/random.hpp>\n#include <boost/nondet_random.hpp>\n\nint main() {\n boost::random::random_device rand_dev;\n boost::random::mt19937 generator(rand_dev());\n boost::random::uniform_int_distribution<> distr(1, 6);\n\n std::cout << distr(generator) << '\\n';\n}\n mt19937 thread_local mt19937 <random> std::random_device entropy() 0 4 #include <iostream>\n#include <random>\n\nint main() {\n std::random_device rand_dev;\n std::mt19937 generator(rand_dev());\n std::uniform_int_distribution<int> distr(1, 6);\n\n std::cout << distr(generator) << '\\n';\n}\n #include <iostream>\n#include <random>\n\nint main() {\n std::cout << std::randint(1,6);\n}\n randint #include <cstdlib>\n#include <ctime>\n#include <iostream>\n\nint main() {\n std::srand(std::time(nullptr));\n std::cout << (std::rand() % 6 + 1);\n}\n #include <iostream>\n\nint main() {\n std::cout << 9; // http://dilbert.com/strip/2001-10-25\n}\n" }, { "answer_id": 56586409, "author": "Michael Haephrati", "author_id": 1592639, "author_profile": "https://Stackoverflow.com/users/1592639", "pm_score": -1, "selected": false, "text": "#define QUICK_RAND(m,n) m + ( std::rand() % ( (n) - (m) + 1 ) )\n int myRand = QUICK_RAND(10, 20);\n srand(time(0)); // Initialize random number generator.\n" }, { "answer_id": 61350542, "author": "Ryan", "author_id": 2266345, "author_profile": "https://Stackoverflow.com/users/2266345", "pm_score": 0, "selected": false, "text": "#include \"<stdlib.h>\"\n\nint32_t RandomRange(int32_t min, int32_t max) {\n return (rand() * (max - min + 1) / (RAND_MAX + 1)) + min;\n}\n rand() / RAND_MAX RAND_MAX * (max - min + 1) int32_t RAND_MAX int64_t int64_t RAND_MAX RAND_MAX rand() RAND_MAX" }, { "answer_id": 70630169, "author": "heothesennoc", "author_id": 12087117, "author_profile": "https://Stackoverflow.com/users/12087117", "pm_score": 2, "selected": false, "text": "#include <random>\n\n// Returns a random integer within the range [min, max]\nint generateRandomInt(const int min, const int max) {\n static bool is_seeded = false;\n static std::mt19937 generator;\n\n // Seed once\n if (!is_seeded) {\n std::random_device rd;\n generator.seed(rd());\n is_seeded = true;\n }\n\n // Use a Mersenne Twister engine to pick a random number\n // within the given range\n std::uniform_int_distribution<int> distribution(min, max);\n return distribution(generator);\n}\n" }, { "answer_id": 74125371, "author": "gatopeich", "author_id": 501336, "author_profile": "https://Stackoverflow.com/users/501336", "pm_score": 0, "selected": false, "text": "#include <random>\n\nint randrange (int min, int max) {\n static std::random_device rd; // Static in case init is costly\n return std::uniform_int_distribution {min, max} (rd);\n}\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33411/" ]
288,752
<p>I have this strange issue with my web app. You see, I'm using jQuery with the Forms API and doing $('#MyForm').ajaxSubmit(api parms and callback function goes here).</p> <p>Randomly when I do this, however, and only on Firefox, the page load icon starts spinning, the page load progress bar runs in the status bar, and the stop button goes red -- but it has already posted the form and brought back a result. If I refresh the page and keep trying to do this, it randomly exhibits the problem, but not consistently.</p> <p>This problem occurred on FF2 on Windows 2008 Server and FF3 on Ubuntu 8.04. The problem is not seen with IE6, IE7, Opera (latest stable, Nov 2008), or Safari (latest stable, Nov 2008).</p> <p>Is this just a known bug in FF with AJAX, or is there something I can do with jQuery to stop the page load issue?</p> <p>EDIT: This <em>might</em> have something to do with TinyMCE. I cannot confirm this 100%, but when I use jQuery to bring back a form with a TinyMCE control on it, the problem seems to exhibit itself more often. I tried doing it with a form that does not have a TinyMCE control on it, several times, and couldn't get the problem to occur. Again, that's nothing conclusive, but might be a factor.</p> <p>EDIT: Okay, I just commented out the TinyMCE stuff and I can confirm that the problem goes away then. If I bring the TinyMCE control back, the problem randomly occurs.</p>
[ { "answer_id": 288753, "author": "Jason Coco", "author_id": 34218, "author_profile": "https://Stackoverflow.com/users/34218", "pm_score": 2, "selected": false, "text": "rand() random()" }, { "answer_id": 288760, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 2, "selected": false, "text": "RAND_MAX" }, { "answer_id": 288769, "author": "abelenky", "author_id": 34824, "author_profile": "https://Stackoverflow.com/users/34824", "pm_score": 3, "selected": false, "text": "RAND_MAX rand() RAND_MAX" }, { "answer_id": 288786, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 3, "selected": false, "text": "RAND_MAX int BigRand()\n{\n assert(INT_MAX/(RAND_MAX+1) > RAND_MAX);\n return rand() * (RAND_MAX+1) + rand();\n}\n" }, { "answer_id": 288816, "author": "anand", "author_id": 33411, "author_profile": "https://Stackoverflow.com/users/33411", "pm_score": -1, "selected": false, "text": "DWORD random = ((min) + rand()/(RAND_MAX + 1.0) * ((max) - (min) + 1));\n" }, { "answer_id": 288844, "author": "calandoa", "author_id": 26074, "author_profile": "https://Stackoverflow.com/users/26074", "pm_score": 0, "selected": false, "text": "j = 1 + (int) (10.0 * (rand() / (RAND_MAX + 1.0)));\n j = min + (int) ((max-min+1) * (rand() / (RAND_MAX + 1.0)));\n" }, { "answer_id": 288869, "author": "peterchen", "author_id": 31317, "author_profile": "https://Stackoverflow.com/users/31317", "pm_score": 6, "selected": false, "text": "rand() ((double) rand() / (RAND_MAX+1)) * (max-min+1) + min\n" }, { "answer_id": 288929, "author": "Jeff Thomas", "author_id": 1561, "author_profile": "https://Stackoverflow.com/users/1561", "pm_score": 3, "selected": false, "text": "uniform_int" }, { "answer_id": 20136256, "author": "Shoe", "author_id": 493122, "author_profile": "https://Stackoverflow.com/users/493122", "pm_score": 9, "selected": true, "text": "rand rand RAND_MAX std::uniform_int_distribution #include <iostream>\n#include <random>\nint main()\n{ \n const int range_from = 0;\n const int range_to = 1000;\n std::random_device rand_dev;\n std::mt19937 generator(rand_dev());\n std::uniform_int_distribution<int> distr(range_from, range_to);\n\n std::cout << distr(generator) << '\\n';\n}\n template<typename T>\nT random(T range_from, T range_to) {\n std::random_device rand_dev;\n std::mt19937 generator(rand_dev());\n std::uniform_int_distribution<T> distr(range_from, range_to);\n return distr(generator);\n}\n <random> std::shuffle #include <iostream>\n#include <random>\n#include <vector>\nint main()\n{ \n std::vector<int> vec = {4, 8, 15, 16, 23, 42};\n \n std::random_device random_dev;\n std::mt19937 generator(random_dev());\n \n std::shuffle(vec.begin(), vec.end(), generator);\n std::for_each(vec.begin(), vec.end(), [](auto i){std::cout << i << '\\n';});\n}\n" }, { "answer_id": 21478635, "author": "Ritualmaster", "author_id": 3256548, "author_profile": "https://Stackoverflow.com/users/3256548", "pm_score": 0, "selected": false, "text": "((double) rand() / (RAND_MAX+1)) * (max-min+1) + min" }, { "answer_id": 24628873, "author": "user3503711", "author_id": 3503711, "author_profile": "https://Stackoverflow.com/users/3503711", "pm_score": 2, "selected": false, "text": "static double rnd(void)\n{\n return (1.0 / (RAND_MAX + 1.0) * ((double)(rand())));\n}\n\nstatic void InitBetterRnd(unsigned int seed)\n{\n register int i;\n srand(seed);\n for(i = 0; i < POOLSIZE; i++)\n {\n pool[i] = rnd();\n }\n}\n\n // This function returns a number between 0 and 1\n static double rnd0_1(void)\n {\n static int i = POOLSIZE - 1;\n double r;\n\n i = (int)(POOLSIZE*pool[i]);\n r = pool[i];\n pool[i] = rnd();\n return (r);\n}\n" }, { "answer_id": 30738381, "author": "benf", "author_id": 1669250, "author_profile": "https://Stackoverflow.com/users/1669250", "pm_score": 2, "selected": false, "text": "[low, high) uint32_t rand_range_low(uint32_t low, uint32_t high)\n{\n uint32_t val;\n // only for 0 < range <= RAND_MAX\n assert(low < high);\n assert(high - low <= RAND_MAX);\n\n uint32_t range = high-low;\n uint32_t scale = RAND_MAX/range;\n do {\n val = rand();\n } while (val >= scale * range); // since scale is truncated, pick a new val until it's lower than scale*range\n return val/scale + low;\n}\n uint32_t rand_range(uint32_t low, uint32_t high)\n{\n assert(high>low);\n uint32_t val;\n uint32_t range = high-low;\n if (range < RAND_MAX)\n return rand_range_low(low, high);\n uint32_t scale = range/RAND_MAX;\n do {\n val = rand() + rand_range(0, scale) * RAND_MAX; // scale the initial range in RAND_MAX steps, then add an offset to get a uniform interval\n } while (val >= range);\n return val + low;\n}\n" }, { "answer_id": 34316875, "author": "Alberto M", "author_id": 2453661, "author_profile": "https://Stackoverflow.com/users/2453661", "pm_score": 4, "selected": false, "text": "randutils randutils #include <iostream>\n#include \"randutils.hpp\"\nint main() {\n randutils::mt19937_rng rng;\n std::cout << rng.uniform(1,6) << \"\\n\";\n}\n Boost.Random <random> Random random_device random_device boost_random #include <iostream>\n#include <boost/random.hpp>\n#include <boost/nondet_random.hpp>\n\nint main() {\n boost::random::random_device rand_dev;\n boost::random::mt19937 generator(rand_dev());\n boost::random::uniform_int_distribution<> distr(1, 6);\n\n std::cout << distr(generator) << '\\n';\n}\n mt19937 thread_local mt19937 <random> std::random_device entropy() 0 4 #include <iostream>\n#include <random>\n\nint main() {\n std::random_device rand_dev;\n std::mt19937 generator(rand_dev());\n std::uniform_int_distribution<int> distr(1, 6);\n\n std::cout << distr(generator) << '\\n';\n}\n #include <iostream>\n#include <random>\n\nint main() {\n std::cout << std::randint(1,6);\n}\n randint #include <cstdlib>\n#include <ctime>\n#include <iostream>\n\nint main() {\n std::srand(std::time(nullptr));\n std::cout << (std::rand() % 6 + 1);\n}\n #include <iostream>\n\nint main() {\n std::cout << 9; // http://dilbert.com/strip/2001-10-25\n}\n" }, { "answer_id": 56586409, "author": "Michael Haephrati", "author_id": 1592639, "author_profile": "https://Stackoverflow.com/users/1592639", "pm_score": -1, "selected": false, "text": "#define QUICK_RAND(m,n) m + ( std::rand() % ( (n) - (m) + 1 ) )\n int myRand = QUICK_RAND(10, 20);\n srand(time(0)); // Initialize random number generator.\n" }, { "answer_id": 61350542, "author": "Ryan", "author_id": 2266345, "author_profile": "https://Stackoverflow.com/users/2266345", "pm_score": 0, "selected": false, "text": "#include \"<stdlib.h>\"\n\nint32_t RandomRange(int32_t min, int32_t max) {\n return (rand() * (max - min + 1) / (RAND_MAX + 1)) + min;\n}\n rand() / RAND_MAX RAND_MAX * (max - min + 1) int32_t RAND_MAX int64_t int64_t RAND_MAX RAND_MAX rand() RAND_MAX" }, { "answer_id": 70630169, "author": "heothesennoc", "author_id": 12087117, "author_profile": "https://Stackoverflow.com/users/12087117", "pm_score": 2, "selected": false, "text": "#include <random>\n\n// Returns a random integer within the range [min, max]\nint generateRandomInt(const int min, const int max) {\n static bool is_seeded = false;\n static std::mt19937 generator;\n\n // Seed once\n if (!is_seeded) {\n std::random_device rd;\n generator.seed(rd());\n is_seeded = true;\n }\n\n // Use a Mersenne Twister engine to pick a random number\n // within the given range\n std::uniform_int_distribution<int> distribution(min, max);\n return distribution(generator);\n}\n" }, { "answer_id": 74125371, "author": "gatopeich", "author_id": 501336, "author_profile": "https://Stackoverflow.com/users/501336", "pm_score": 0, "selected": false, "text": "#include <random>\n\nint randrange (int min, int max) {\n static std::random_device rd; // Static in case init is costly\n return std::uniform_int_distribution {min, max} (rd);\n}\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
288,775
<p>Say I have a method that needs to pull 8 values from a map with 100 elements in it. Which do you think would be preferable:</p> <p>Walk in a for loop from begin to end once, pulling the elements out by switching on the key?</p> <p>Or using find 8 times to get those values?</p>
[ { "answer_id": 288872, "author": "Artelius", "author_id": 31945, "author_profile": "https://Stackoverflow.com/users/31945", "pm_score": 3, "selected": false, "text": "find" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288775", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
288,779
<p>In asp.net mvc, I want to create a action for login.</p> <p>So this is how I am doing it:</p> <ol> <li><p>create a action/view named login that simply displays the view.</p></li> <li><p>create another action, named login2 that will be the page that handles the form post and checks the database if the username/password are correct. If it is, redirect to somepage, if not, redirect back to the login page with the appropriate error message.</p></li> </ol> <p>Is this the best way to do this?</p>
[ { "answer_id": 836940, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": " /// <summary>\n /// Displays the Login screen the first time\n /// to anyone who wishes to view it.\n /// </summary>\n /// <returns></returns>\n [AcceptVerbs(HttpVerbs.Get)]\n public ActionResult Login()\n {\n return View();\n }\n\n /// <summary>\n /// Handles the form postback\n /// </summary>\n /// <returns></returns>\n [AcceptVerbs(HttpVerbs.Post)]\n [ValidateAntiForgeryToken]\n public ActionResult Login(string name, \n string password, \n string ReturnUrl)\n {\n // perform authentication here\n\n if (string.IsNullOrEmpty(ReturnUrl))\n return RedirectToAction(\"Index\", \"Main\");\n\n return Redirect(ReturnUrl);\n }\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288779", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
288,794
<p>For instance, does the compiler know to translate</p> <pre><code>string s = "test " + "this " + "function"; </code></pre> <p>to</p> <pre><code>string s = "test this function"; </code></pre> <p>and thus avoid the performance hit with the string concatenation?</p>
[ { "answer_id": 288913, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 5, "selected": false, "text": "+ string result = x + y + z;\n string result = String.Concat( x, y, z);\n string result = String.Concat( String.Concat( x, y), z);\n" }, { "answer_id": 8864900, "author": "Jed", "author_id": 171142, "author_profile": "https://Stackoverflow.com/users/171142", "pm_score": 3, "selected": false, "text": "class Program\n{\n static void Main(string[] args)\n {\n string s = \"test \" + \"this \" + \"function\";\n string ss = String.Concat(\"test\", \"this\", \"function\");\n }\n}\n .method private hidebysig static void Main(string[] args) cil managed\n{\n .entrypoint\n // Code size 29 (0x1d)\n .maxstack 3\n .locals init (string V_0,\n string V_1)\n IL_0000: nop\n IL_0001: ldstr \"test this function\"\n IL_0006: stloc.0\n IL_0007: ldstr \"test\"\n IL_000c: ldstr \"this\"\n IL_0011: ldstr \"function\"\n IL_0016: call string [mscorlib]System.String::Concat(string,\n string,\n string)\n IL_001b: stloc.1\n IL_001c: ret\n} // end of method Program::Main\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/337/" ]
288,800
<p>I have this naive regex "&lt;([\s]|[^&lt;])+?>" (excluding the quotation marks). It seems so straightforward but it is indeed evil when it works against the below HTML text. It sends the Java regular expression engine to an infinite loop. </p> <p>I have another regex ("&lt;.+?>"), which does somewhat the same thing, but it doesn't kill anything. Do you know why this happens?</p> <pre><code>&lt;script language="JavaScript" type="text/javascript"&gt; var numDivs, layerName; layerName = "lnavLayer"; catLinkName = "category"; numDivs = 2; function toggleLayer(layerID){ if (!(navigator.appName == "Netscape" &amp;&amp; navigator.appVersion.substr(0, 1) &lt; 5)){ thisLayer = document.getElementById(layerName + layerID); categoryLink = document.getElementById(catLinkName + layerID); closeThem(); if (thisLayer.className == 'subnavDefault'){ thisLayer.className = 'subnavToggled'; categoryLink.className = 'leftnavLinkSelectedSection'; } } } function closeThem(){ for(x = 0; x &lt; numDivs; x++){ theLayer = document.getElementById(layerName + (x + 1)); thecategoryLink = document.getElementById(catLinkName + (x + 1)); theLayer.className = 'subnavDefault'; thecategoryLink.className = 'leftnavLink'; } } var flag = 0; var lastClicked = 0 //--&gt; &lt;/script&gt; </code></pre> <p>it even keeps looping with an online Java regex tool (such as <a href="http://www.fileformat.info/tool/regex.htm" rel="noreferrer">www.fileformat.info/tool/regex.htm</a>) or a utility like <a href="http://www.regexbuddy.com/" rel="noreferrer">RegexBuddy</a>.</p>
[ { "answer_id": 288843, "author": "localshred", "author_id": 29690, "author_profile": "https://Stackoverflow.com/users/29690", "pm_score": 2, "selected": false, "text": "([\\s]|[^<]) < < `\"<([^<])+?>\"`\n" }, { "answer_id": 289676, "author": "Jan Goyvaerts", "author_id": 33358, "author_profile": "https://Stackoverflow.com/users/33358", "pm_score": 7, "selected": true, "text": "[\\s]|[^<]\n A|B\n" }, { "answer_id": 291474, "author": "Alan Moore", "author_id": 20938, "author_profile": "https://Stackoverflow.com/users/20938", "pm_score": 2, "selected": false, "text": "(.)+\n (?:.)+\n * +" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288800", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8203/" ]
288,810
<p>Getting the subdomain from a URL sounds easy at first.</p> <pre><code>http://www.domain.example </code></pre> <p>Scan for the first period then return whatever came after the "http://" ...</p> <p>Then you remember</p> <pre><code>http://super.duper.domain.example </code></pre> <p>Oh. So then you think, okay, find the last period, go back a word and get everything before! </p> <p>Then you remember</p> <pre><code>http://super.duper.domain.co.uk </code></pre> <p>And you're back to square one. Anyone have any great ideas besides storing a list of all TLDs?</p>
[ { "answer_id": 288885, "author": "Alnitak", "author_id": 6782, "author_profile": "https://Stackoverflow.com/users/6782", "pm_score": 5, "selected": false, "text": ".uk .co.uk example.co.uk .co.uk .co.uk .uk.com .com" }, { "answer_id": 9790261, "author": "Isak", "author_id": 371698, "author_profile": "https://Stackoverflow.com/users/371698", "pm_score": 1, "selected": false, "text": "(parse \"sub1.sub2.domain.co.uk\") \n;=> {:public-suffix \"co.uk\", :domain \"domain.co.uk\", :rule-used \"*.uk\"}\n" }, { "answer_id": 9917859, "author": "Mike", "author_id": 949747, "author_profile": "https://Stackoverflow.com/users/949747", "pm_score": 0, "selected": false, "text": "echo tld('http://www.example.co.uk/test?123'); // co.uk\n\n/**\n * http://publicsuffix.org/\n * http://www.alandix.com/blog/code/public-suffix/\n * http://tobyinkster.co.uk/blog/2007/07/19/php-domain-class/\n */\nfunction tld($url_or_domain = null)\n{\n $domain = $url_or_domain ?: $_SERVER['HTTP_HOST'];\n preg_match('/^[a-z]+:\\/\\//i', $domain) and \n $domain = parse_url($domain, PHP_URL_HOST);\n $domain = mb_strtolower($domain, 'UTF-8');\n if (strpos($domain, '.') === false) return null;\n\n $url = 'http://mxr.mozilla.org/mozilla-central/source/netwerk/dns/effective_tld_names.dat?raw=1';\n\n if (($rules = file($url)) !== false)\n {\n $rules = array_filter(array_map('trim', $rules));\n array_walk($rules, function($v, $k) use(&$rules) { \n if (strpos($v, '//') !== false) unset($rules[$k]);\n });\n\n $segments = '';\n foreach (array_reverse(explode('.', $domain)) as $s)\n {\n $wildcard = rtrim('*.'.$segments, '.');\n $segments = rtrim($s.'.'.$segments, '.');\n\n if (in_array('!'.$segments, $rules))\n {\n $tld = substr($wildcard, 2);\n break;\n }\n elseif (in_array($wildcard, $rules) or \n in_array($segments, $rules))\n {\n $tld = $segments;\n }\n }\n\n if (isset($tld)) return $tld;\n }\n\n return false;\n}\n" }, { "answer_id": 14688913, "author": "Francois Bourgeois", "author_id": 1703313, "author_profile": "https://Stackoverflow.com/users/1703313", "pm_score": 3, "selected": false, "text": "super.duper.domain.co.uk => no MX record, proceed\nduper.domain.co.uk => no MX record, proceed\ndomain.co.uk => MX record found! assume that's the domain\n function getDomainWithMX($url) {\n //parse hostname from URL \n //http://www.example.co.uk/index.php => www.example.co.uk\n $urlParts = parse_url($url);\n if ($urlParts === false || empty($urlParts[\"host\"])) \n throw new InvalidArgumentException(\"Malformed URL\");\n\n //find first partial name with MX record\n $hostnameParts = explode(\".\", $urlParts[\"host\"]);\n do {\n $hostname = implode(\".\", $hostnameParts);\n if (checkdnsrr($hostname, \"MX\")) return $hostname;\n } while (array_shift($hostnameParts) !== null);\n\n throw new DomainException(\"No MX record found\");\n}\n" }, { "answer_id": 37995140, "author": "Oleksandr Fediashov", "author_id": 6488546, "author_profile": "https://Stackoverflow.com/users/6488546", "pm_score": 2, "selected": false, "text": "$extract = new LayerShifter\\TLDExtract\\Extract();\n\n$result = $extract->parse('super.duper.domain.co.uk');\n$result->getSubdomain(); // will return (string) 'super.duper'\n$result->getSubdomains(); // will return (array) ['super', 'duper']\n$result->getHostname(); // will return (string) 'domain'\n$result->getSuffix(); // will return (string) 'co.uk'\n" }, { "answer_id": 43864208, "author": "xiaoyu2er", "author_id": 5755195, "author_profile": "https://Stackoverflow.com/users/5755195", "pm_score": 0, "selected": false, "text": "tldjs.getDomain('mail.google.co.uk');\n// -> 'google.co.uk'\n var KEY = '__rT_dM__' + (+new Date());\nvar R = new RegExp('(^|;)\\\\s*' + KEY + '=1');\nvar Y1970 = (new Date(0)).toUTCString();\n\nmodule.exports = function getRootDomain() {\n var domain = document.domain || location.hostname;\n var list = domain.split('.');\n var len = list.length;\n var temp = '';\n var temp2 = '';\n\n while (len--) {\n temp = list.slice(len).join('.');\n temp2 = KEY + '=1;domain=.' + temp;\n\n // try to set cookie\n document.cookie = temp2;\n\n if (R.test(document.cookie)) {\n // clear\n document.cookie = temp2 + ';expires=' + Y1970;\n return temp;\n }\n }\n};\n" }, { "answer_id": 63761712, "author": "F. Hauri - Give Up GitHub", "author_id": 1765658, "author_profile": "https://Stackoverflow.com/users/1765658", "pm_score": 1, "selected": false, "text": "wget -O - https://publicsuffix.org/list/public_suffix_list.dat |\n grep '^[^/]' |\n tac > tld-list.txt\n tac .co.uk .uk splitDom() {\n local tld\n while read tld;do\n [ -z \"${1##*.$tld}\" ] &&\n printf \"%s : %s\\n\" $tld ${1%.$tld} && return\n done <tld-list.txt\n}\n splitDom super.duper.domain.co.uk\nco.uk : super.duper.domain\n\nsplitDom super.duper.domain.com\ncom : super.duper.domain\n myvar=$(function..) tlds=($(<tld-list.txt))\nsplitDom() {\n local tld\n local -n result=${2:-domsplit}\n for tld in ${tlds[@]};do\n [ -z \"${1##*.$tld}\" ] &&\n result=($tld ${1%.$tld}) && return\n done\n}\n splitDom super.duper.domain.co.uk myvar\ndeclare -p myvar\ndeclare -a myvar=([0]=\"co.uk\" [1]=\"super.duper.domain\")\n\nsplitDom super.duper.domain.com\ndeclare -p domsplit\ndeclare -a domsplit=([0]=\"com\" [1]=\"super.duper.domain\")\n declare -A TLDS='()'\nwhile read tld ;do\n if [ \"${tld##*.}\" = \"$tld\" ];then\n TLDS[${tld##*.}]+=\"$tld\"\n else\n TLDS[${tld##*.}]+=\"$tld|\"\n fi\ndone <tld-list.txt\n splitDom shopt -s extglob \nsplitDom() {\n local domsub=${1%%.*(${TLDS[${1##*.}]%\\|})}\n local -n result=${2:-domsplit}\n result=(${1#$domsub.} $domsub)\n}\n for dom in dom.sub.example.{,{co,adm,com}.}{com,ac,de,uk};do\n splitDom $dom myvar\n printf \"%-40s %-12s %s\\n\" $dom ${myvar[@]}\ndone\n for dom.sub.example.com com dom.sub.example\ndom.sub.example.ac ac dom.sub.example\ndom.sub.example.de de dom.sub.example\ndom.sub.example.uk uk dom.sub.example\ndom.sub.example.co.com co.com dom.sub.example\ndom.sub.example.co.ac ac dom.sub.example.co\ndom.sub.example.co.de de dom.sub.example.co\ndom.sub.example.co.uk co.uk dom.sub.example\ndom.sub.example.adm.com com dom.sub.example.adm\ndom.sub.example.adm.ac ac dom.sub.example.adm\ndom.sub.example.adm.de de dom.sub.example.adm\ndom.sub.example.adm.uk uk dom.sub.example.adm\ndom.sub.example.com.com com dom.sub.example.com\ndom.sub.example.com.ac com.ac dom.sub.example\ndom.sub.example.com.de com.de dom.sub.example\ndom.sub.example.com.uk uk dom.sub.example.com\n splitDom $tlds ~22s $TLDS Posix version $tldS (array) $TLDS (associative array)\nFile read : 0.04164 0.55507 18.65262\nSplit loop : 114.34360 88.33438 3.38366\nTotal : 114.34360 88.88945 22.03628\n splitDom" }, { "answer_id": 63868511, "author": "muratgozel", "author_id": 695796, "author_profile": "https://Stackoverflow.com/users/695796", "pm_score": 0, "selected": false, "text": "sudo apt install psl\n domain=example.com.tr\noutput=$(psl --print-unreg-domain $domain)\n output example.com.tr: com.tr\n domain # split output by colon\narr=(${output//:/ })\n# remove the suffix from the domain\nname=${1/${arr[1]}/}\n# test\nif [[ $name =~ \\..*\\. ]]; then\n echo \"Yes, it is subdomain.\"\nfi\n is_subdomain() {\n local output=$(psl --print-unreg-domain $1)\n local arr=(${output//:/ })\n local name=${1/${arr[1]}/}\n [[ $name =~ \\..*\\. ]]\n}\n d=example.com.tr\nif is_subdomain $d; then\n echo \"Yes, it is.\"\nfi\n" }, { "answer_id": 65307009, "author": "Venkatesh", "author_id": 7716603, "author_profile": "https://Stackoverflow.com/users/7716603", "pm_score": 0, "selected": false, "text": "private String getSubDomain(Uri url) throws Exception{\n String subDomain =url.getHost();\n String fial=subDomain.replace(\".\",\"/\");\n String[] arr_subDomain =fial.split(\"/\");\n return arr_subDomain[0];\n }\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37522/" ]
288,813
<p>In Delphi 2006, I am showing a modal form. User input in that form can change data that might be displayed currently on the parent form which is the mainform. To reflect those changes I need to force a repaint of some ownerdrawn components on the mainform. I tried to do that like this from the modal form:</p> <pre><code>MainForm := Application.MainForm; MainForm.Invalidate; MainForm.Update; </code></pre> <p>That did not change a bit. I always thought an "update" on the form would always repaint it right away - apparently not so. The painting code itself should be ok since I can move the modal form over those ownerdraw components to force a manual repaint. </p> <p>But how can I force the repaint programmatically when the data changes?</p> <p><b>Edit:</b> I will try Application.ProcessMessages and Refresh next week, thanks for the suggestions.</p> <p>Sorry for taking so long to answer and thanks to all who responded. Calling Refresh() was part of the solution but it had to be done on the custom draw components, not on the form they were on... Now I would like to accept more than one answer ;-)</p>
[ { "answer_id": 288819, "author": "Kluge", "author_id": 8752, "author_profile": "https://Stackoverflow.com/users/8752", "pm_score": 0, "selected": false, "text": "Application.ProcessMessages;\n" }, { "answer_id": 288964, "author": "Jim McKeeth", "author_id": 255, "author_profile": "https://Stackoverflow.com/users/255", "pm_score": 1, "selected": false, "text": "procedure TForm1.Button1Click(Sender: TObject);\nbegin\n Form2.ShowModal;\nend;\n procedure TForm2.Edit1Change(Sender: TObject);\nbegin\n Form1.Button1.Caption := Edit1.Text;\nend;\n" }, { "answer_id": 289535, "author": "Steve", "author_id": 22712, "author_profile": "https://Stackoverflow.com/users/22712", "pm_score": 0, "selected": false, "text": "procedure DoIdle(Sender: TObject; var Done: Boolean);\n for i := 1 to ProcessCount do\n DoProcess(i);\n procedure MyDoIdle(Sender: TObject; var Done: Boolean);\nbegin\n Inc(TaskCount);\n If TaskCount <= ProcessCount then\n DoProcess(TaskCount);\nend;\n TaskCount := 0;\nApplication.Idle := MyDoIdle;\n" }, { "answer_id": 966798, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "procedure UpdateApplication;\n// Updates (repaints where nesc) all windows of the app\n function UpdateWindow(hWnd: HWND; LParam: longint): bool; stdcall;\n begin\n Result := True;\n Windows.UpdateWindow(hWnd);\n end;\nbegin\n EnumWindows(@UpdateWindow, 0);\nend;\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288813", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35657/" ]
288,814
<p>I have this code in my aspx page;</p> <pre><code>&lt;a href="javascript:void(0);" onclick=&lt;% Print(); %&gt; title="Print listings"&gt;Print&lt;/a&gt; </code></pre> <p>which presents a link to print a listings to a pdf when the user clicks on it; as you can note the script calls a function from the behind code.</p> <p>The problem is that when I coded this it happens that when I go this page it prints to pdf when is loading, I thought it would wait for a click but instead it performs the printing.</p> <p>What is the problem? thanks in advance.</p> <p>PD. I'm working with VS2005 and for the pdf creation I use iTextSharp.</p>
[ { "answer_id": 288848, "author": "Robert Wagner", "author_id": 10784, "author_profile": "https://Stackoverflow.com/users/10784", "pm_score": 1, "selected": false, "text": "<a href=\"PrintMyPdf.ashx?PageID=<%= CurrentPageId %>\">Print</a>\n protected int CurrentPageId { get { return 4; } }\n <a href=\"PrintMyPdf.ashx?PageID=4\">Print</a>\n" }, { "answer_id": 288882, "author": "lubos hasko", "author_id": 275, "author_profile": "https://Stackoverflow.com/users/275", "pm_score": 1, "selected": false, "text": "<a href=\"javascript:void(0);\" onclick=<% Print(); %> title=\"Print listings\">Print</a>\n" }, { "answer_id": 288974, "author": "Avitus", "author_id": 34831, "author_profile": "https://Stackoverflow.com/users/34831", "pm_score": 0, "selected": false, "text": "<a href=\"printPDF.aspx\" title=\"Print listings\">Print</a>\n <a href=\"javascript:void(0);\" onlick=\"javascript:GoToPrint();\" title=\"Print listings\">Print</a>\n <script>\n function GoToPrint()\n {\n window.location = 'printPDF.aspx?var1=x&var2=y';\n }\n</script>\n" }, { "answer_id": 291784, "author": "Nelson Miranda", "author_id": 1130097, "author_profile": "https://Stackoverflow.com/users/1130097", "pm_score": 0, "selected": false, "text": "protected void btnPrint_Click(object sender, EventArgs e)\n{\n ...\n string url = GetUrlWithParameters();\n\n string reportscript = \"<script language='JavaScript'>\" +\n \"window.open('\" + url + \"', 'CustomPopUp', \" +\n \"'width=400, height=400, resizable=yes, scrollbars=yes')\" +\n \"</script>\";\n\n Page.RegisterStartupScript(\"reportscript\", reportscript);\n ...\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/288814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1130097/" ]
288,828
<p>I need to test a JDBC connection to a database. The java code to do that should be as simple as:</p> <pre><code>DriverManager.getConnection("jdbc connection URL", "username", "password"); </code></pre> <p>The driver manager will lookup the appropriate the driver for the given connection URL. However I need to be able to load the JDBC driver (jar) at runtime. I.e I don't have the JDBC driver on the classpath of the java application that runs the snippet of code above.</p> <p>So I can load the driver using this code, for example:</p> <pre><code>URLClassLoader classLoader = new URLClassLoader(new URL[]{"jar URL"}, this.getClass().getClassLoader()); Driver driver = (Driver) Class.forName("jdbc driver class name", true, classLoader).newInstance(); </code></pre> <p>But then the driver manager still won't pick it up as I can't tell it which classloader to use. I tried setting the current thread's context classloader and it still doesn't work.</p> <p>Anyone has any idea on the best way to achieve that?</p>
[ { "answer_id": 288941, "author": "SaM", "author_id": 883, "author_profile": "https://Stackoverflow.com/users/883", "pm_score": 5, "selected": true, "text": "public class DelegatingDriver implements Driver\n{\n private final Driver driver;\n\n public DelegatingDriver(Driver driver)\n {\n if (driver == null)\n {\n throw new IllegalArgumentException(\"Driver must not be null.\");\n }\n this.driver = driver;\n }\n\n public Connection connect(String url, Properties info) throws SQLException\n {\n return driver.connect(url, info);\n }\n\n public boolean acceptsURL(String url) throws SQLException\n {\n return driver.acceptsURL(url);\n }\n\n public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException\n {\n return driver.getPropertyInfo(url, info);\n }\n\n public int getMajorVersion()\n {\n return driver.getMajorVersion();\n }\n\n public int getMinorVersion()\n {\n return driver.getMinorVersion();\n }\n\n public boolean jdbcCompliant()\n { \n return driver.jdbcCompliant();\n }\n}\n DelegatingDriver URLClassLoader classLoader = new URLClassLoader(new URL[]{\"path to my jdbc driver jar\"}, this.getClass().getClassLoader());\nDriver driver = (Driver) Class.forName(\"org.postgresql.Driver\", true, classLoader).newInstance();\nDriverManager.registerDriver(new DelegatingDriver(driver)); // register using the Delegating Driver\n\nDriverManager.getDriver(\"jdbc:postgresql://host/db\"); // checks that the driver is found\n" }, { "answer_id": 289839, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 3, "selected": false, "text": "DriverManager URLClassLoader.newInstance new URLClassLoader" } ]
2008/11/14
[ "https://Stackoverflow.com/questions/288828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/883/" ]
288,850
<p>I am using .Net framework 2.0 / jQuery to make an Ajax call to a 2.0 web service. No matter what I set the contentType to in the ajax call, the service always returns XML. I want it to return Json!</p> <p>Here is the call:</p> <pre><code> $(document).ready(function() { $.ajax({ type: "POST", url: "DonationsService.asmx/GetDate", data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", success: function(msg) { // Hide the fake progress indicator graphic. $('#RSSContent').removeClass('loading'); // Insert the returned HTML into the &lt;div&gt;. $('#RSSContent').html(msg.d); } }); }); </code></pre> <p>Here is what the request header looks like in Fiddler:</p> <pre><code>POST /DonationsService.asmx/GetDate HTTP/1.1 x-requested-with: XMLHttpRequest Accept-Language: en-us Referer: http://localhost:1238/text.htm Accept: application/json, text/javascript, */* Content-Type: application/json; charset=utf-8 Accept-Encoding: gzip, deflate User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; eMusic DLM/4; .NET CLR 2.0.50727) Host: localhost:1238 Content-Length: 2 Connection: Keep-Alive Pragma: no-cache </code></pre> <p>I have tried setting the contentType to 'text/json' and get the same results.</p> <p>Here is the web service method:</p> <pre><code>&lt;WebMethod()&gt; _ Public Function GetDate() As String 'just playing around with Newtonsoft.Json Dim sb As New StringBuilder Dim sw As New IO.StringWriter(sb) Dim strOut As String = String.Empty Using jw As New JsonTextWriter(sw) With jw .WriteStartObject() .WritePropertyName("DateTime") .WriteValue(DateTime.Now.ToString) .WriteEndObject() End With strOut = sw.ToString End Using Return strOut End Function </code></pre> <p>and here is what it returns:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;string xmlns="http://DMS.Webservices.org/"&gt;{"DateTime":"11/13/2008 6:04:22 PM"}&lt;/string&gt; </code></pre> <p>Does anyone know how to force the web service to return Json when I ask for Json?</p> <p>Please don't tell me to upgrade to .Net Framework 3.5 or anything like that (I'm not that stupid). I need a 2.0 solution.</p>
[ { "answer_id": 288938, "author": "Darko", "author_id": 32943, "author_profile": "https://Stackoverflow.com/users/32943", "pm_score": 3, "selected": false, "text": "[ScriptMethod(ResponseFormat = ResponseFormat.Json)]\n" }, { "answer_id": 289078, "author": "redsquare", "author_id": 6440, "author_profile": "https://Stackoverflow.com/users/6440", "pm_score": 2, "selected": false, "text": "<%@ WebHandler Class=\"JayrockWeb.HelloWorld\" %>\n\nnamespace JayrockWeb\n{\n using System;\n using System.Web;\n using Jayrock.Json;\n using Jayrock.JsonRpc;\n using Jayrock.JsonRpc.Web;\n\n public class HelloWorld : JsonRpcHandler\n {\n [ JsonRpcMethod(\"greetings\") ]\n public string Greetings()\n {\n return \"Welcome to Jayrock!\";\n }\n }\n}\n" }, { "answer_id": 5392932, "author": "Tom", "author_id": 671394, "author_profile": "https://Stackoverflow.com/users/671394", "pm_score": 4, "selected": false, "text": "[WebMethod(Description=\"return pure JSON\")]\npublic void retrieveByIdToPureJSON( int id )\n{\n Context.Response.Write( JsonConvert.SerializeObject( mydbtable.getById(id) );\n}\n" }, { "answer_id": 6512416, "author": "Seth", "author_id": 819892, "author_profile": "https://Stackoverflow.com/users/819892", "pm_score": 1, "selected": false, "text": "Dim sb As New StringBuilder(\"{\")\nFor Each p As PropertyInfo In myObject.GetType().GetProperties()\n sb.Append(String.Format(\"\"\"{0}\"\":\"\"{1}\"\",\", p.Name, p.GetValue(myObject, \n Nothing).ToString()))\nNext p\n\n//remove the last \",\" because it's uneeded.\nsb.Remove(sb.Length - 1, 1)\n\nsb.Append(\"}\") \n" } ]
2008/11/14
[ "https://Stackoverflow.com/questions/288850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7232/" ]
288,861
<p>Is there anyway to get Eclipse to automatically look for static imports? For example, now that I've finally upgraded to Junit 4, I'd like to be able to write:</p> <pre><code>assertEquals(expectedValue, actualValue); </code></pre> <p>hit <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>O</kbd> and have Eclipse add:</p> <pre><code>import static org.junit.Assert.assertEquals; </code></pre> <p>Maybe I'm asking too much.</p>
[ { "answer_id": 289289, "author": "Dave L.", "author_id": 3093, "author_profile": "https://Stackoverflow.com/users/3093", "pm_score": 8, "selected": false, "text": "Assert.assertEquals(val1, val2)" }, { "answer_id": 289599, "author": "Bill Michell", "author_id": 7938, "author_profile": "https://Stackoverflow.com/users/7938", "pm_score": 5, "selected": false, "text": "org.junit.Assert" }, { "answer_id": 290756, "author": "Joey Gibson", "author_id": 6645, "author_profile": "https://Stackoverflow.com/users/6645", "pm_score": 10, "selected": true, "text": ".* org.hamcrest.Matchers.*\norg.hamcrest.CoreMatchers.*\norg.junit.*\norg.junit.Assert.*\norg.junit.Assume.*\norg.junit.matchers.JUnitMatchers.*\n assertT assertThat" }, { "answer_id": 29276918, "author": "Sumit Singh", "author_id": 942391, "author_profile": "https://Stackoverflow.com/users/942391", "pm_score": 3, "selected": false, "text": "Java > Editor > Content Assist > Favorites java.util.Arrays.* org.junit.Assert.* Window » Preferences » Java » Editor » Content Assist » Favorites" }, { "answer_id": 32170319, "author": "Neeraj", "author_id": 528757, "author_profile": "https://Stackoverflow.com/users/528757", "pm_score": 3, "selected": false, "text": "org.springframework.test.web.servlet.request.MockMvcRequestBuilders\norg.springframework.test.web.servlet.request.MockMvcResponseBuilders\norg.springframework.test.web.servlet.result.MockMvcResultHandlers\norg.springframework.test.web.servlet.result.MockMvcResultMatchers\norg.springframework.test.web.servlet.setup.MockMvcBuilders\norg.mockito.Mockito\n" }, { "answer_id": 52782688, "author": "teknopaul", "author_id": 870207, "author_profile": "https://Stackoverflow.com/users/870207", "pm_score": 2, "selected": false, "text": "Ctrl + 1 (quick fix)\n" } ]
2008/11/14
[ "https://Stackoverflow.com/questions/288861", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18995/" ]
288,867
<p>I need to replace our <a href="http://en.wikipedia.org/wiki/Ajax_%28programming%29" rel="noreferrer">Ajax</a> Modal Popup controls with a JavaScript equivalent. We use this as a simple context sensitive help type popup. I did a quick browse but didn't see quite what I was looking for. I just need some text and a simple Close button/link, but I would like the page darkened below the popup, as it does with the Ajax modal control.</p> <p>Can anyone suggest a nice JavaScript popup/help type solution that you've used?</p>
[ { "answer_id": 289028, "author": "José Leal", "author_id": 37190, "author_profile": "https://Stackoverflow.com/users/37190", "pm_score": 6, "selected": true, "text": "function myPop() { \n this.square = null;\n this.overdiv = null;\n\n this.popOut = function(msgtxt) {\n //filter:alpha(opacity=25);-moz-opacity:.25;opacity:.25;\n this.overdiv = document.createElement(\"div\");\n this.overdiv.className = \"overdiv\";\n\n this.square = document.createElement(\"div\");\n this.square.className = \"square\";\n this.square.Code = this;\n var msg = document.createElement(\"div\");\n msg.className = \"msg\";\n msg.innerHTML = msgtxt;\n this.square.appendChild(msg);\n var closebtn = document.createElement(\"button\");\n closebtn.onclick = function() {\n this.parentNode.Code.popIn();\n }\n closebtn.innerHTML = \"Close\";\n this.square.appendChild(closebtn);\n\n document.body.appendChild(this.overdiv);\n document.body.appendChild(this.square);\n }\n this.popIn = function() {\n if (this.square != null) {\n document.body.removeChild(this.square);\n this.square = null;\n }\n if (this.overdiv != null) {\n document.body.removeChild(this.overdiv);\n this.overdiv = null;\n }\n\n }\n}\n <html> \n <head>\n <script type=\"text/javascript\" src=\"NAME OF THE PAGE!.js\"></script>\n <style>\n div.overdiv { filter: alpha(opacity=75);\n -moz-opacity: .75;\n opacity: .75;\n background-color: #c0c0c0;\n position: absolute;\n top: 0px;\n left: 0px;\n width: 100%; height: 100%; }\n\n div.square { position: absolute;\n top: 200px;\n left: 200px;\n background-color: Menu;\n border: #f9f9f9;\n height: 200px;\n width: 300px; }\n div.square div.msg { color: #3e6bc2;\n font-size: 15px;\n padding: 15px; }\n </style>\n </head>\n <body>\n <div style=\"background-color: red; width: 200px; height: 300px;\n padding: 20px; margin: 20px;\"></div>\n\n <script type=\"text/javascript\">\n var pop = new myPop();\n pop.popOut(\"Jose leal\");\n </script>\n </body>\n</html>\n" } ]
2008/11/14
[ "https://Stackoverflow.com/questions/288867", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8816/" ]
288,875
<p>C#: How would you cycle through items in a listview using next and previous buttons?</p> <p>Background:</p> <p>Let's say you have 10 items in a listview.</p> <p>Next to the listview there are two buttons titled previos and next.</p> <p>Problem:</p> <p>How would you cycle through those listview items after clicking the Next and or Previous button?</p>
[ { "answer_id": 288896, "author": "Mike Blandford", "author_id": 28643, "author_profile": "https://Stackoverflow.com/users/28643", "pm_score": -1, "selected": false, "text": " for(int i=0;i<listView.Items.Count;i++)\n listView.Items[i]\n" }, { "answer_id": 288905, "author": "Aistina", "author_id": 37472, "author_profile": "https://Stackoverflow.com/users/37472", "pm_score": 1, "selected": false, "text": " if (listView.SelectedIndices.Count > 0)\n {\n int oldSelection = listView.SelectedIndices[0];\n listView.SelectedIndices.Clear();\n\n if (oldSelection + 1 >= listView.Items.Count)\n listView.SelectedIndices.Add(0);\n else\n listView.SelectedIndices.Add(oldSelection + 1);\n }\n" }, { "answer_id": 3478087, "author": "Rob", "author_id": 419680, "author_profile": "https://Stackoverflow.com/users/419680", "pm_score": 0, "selected": false, "text": "int oldSelection = ListView1.SelectedIndices[0];\n\nif(*NextOptionSelected* && oldSelection + 1 < ListView1.Items.Count)\n{\n ListView1.Items[oldSelection + 1].Selected = true;\n ListView1.Items[oldSelection + 1].Focused = true;\n ListView1.Items[oldSelection].Selected = false;\n ListView1.Items[oldSelection].Focused = false;\n}\nelse if(*LastOptionSelected* && oldSelection > 0)\n{\n ListView1.Items[oldSelection - 1].Selected = true;\n ListView1.Items[oldSelection - 1].Focused = true;\n ListView1.Items[oldSelection].Selected = false;\n ListView1.Items[oldSelection].Focused = false;\n}\n\nListView1.EnsureVisible(ListView1.SelectedIndices[0]);\n" }, { "answer_id": 3478183, "author": "msarchet", "author_id": 257250, "author_profile": "https://Stackoverflow.com/users/257250", "pm_score": 0, "selected": false, "text": "//UpOrDown is a +1 or -1\nvoid Page(int UpOrDown){\n //Determine if something is selected\n if (listView.SelectedIndices.Count > 0)\n {\n int oldIndex = listView.SelectedIndices(0);\n listView.SelectedIndices.Clear();\n\n //Use mod!\n int numberOfItems = listView.Items.Count();\n listView.SelectedIndices.Add((oldIndex + UpOrDown) % numberOfItems)\n }\n}\n modulus" }, { "answer_id": 16561683, "author": "Prosenjeet Paul", "author_id": 2385244, "author_profile": "https://Stackoverflow.com/users/2385244", "pm_score": 0, "selected": false, "text": "Dim CurrentRow As Integer\nCurrentRow = Form2.ListView1.Items.IndexOf(Form2.ListView1.FocusedItem)\nCurrentRow =CurrentRow + 1\nForm2.ListView1.Items(CurrentRow).Selected = True\nForm2.ListView1.Items(CurrentRow).Focused = True\n" }, { "answer_id": 19083441, "author": "user2829330", "author_id": 2829330, "author_profile": "https://Stackoverflow.com/users/2829330", "pm_score": 0, "selected": false, "text": "private void Page(int UpOrDown, ListView list)\n {\n //Determine if something is selected\n list.Focus();\n if (list.SelectedIndices.Count == 0)\n {\n if (list.Items.Count > 0)\n {\n list.Items[0].Selected = true;\n list.SelectedIndices.Add(0);\n list.Items[0].Focused = true;\n list.EnsureVisible(list.Items[0].Index);\n list.TopItem = list.Items[0];\n }\n }\n if (list.SelectedIndices.Count > 0)\n {\n if (list.SelectedIndices[0] == null)\n {\n list.SelectedIndices.Add(0);\n }\n int oldIndex = list.SelectedIndices[0];\n list.SelectedIndices.Clear();\n\n //Use mod!\n int numberOfItems = list.Items.Count;\n if (oldIndex + UpOrDown >= 0 && oldIndex + UpOrDown <= list.Items.Count-1)\n {\n list.SelectedIndices.Add((oldIndex + UpOrDown)%numberOfItems);\n list.SelectedItems[0].Selected = true;\n list.SelectedItems[0].Focused = true;\n list.EnsureVisible(list.SelectedItems[0].Index);\n //list.TopItem = list.SelectedItems[0];\n }\n }\n }\n" } ]
2008/11/14
[ "https://Stackoverflow.com/questions/288875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
288,877
<p>Is there a way I can set up callbacks on (or automataically log) method parameters, entries, and exits without making explicit calls within each method? I basically want to log this information to my logger class (which is static) without having to do it manually for each method.</p> <p>Right now I have to call Logger::logEntry() and Logger::logExit() in every method to accomplish this. I would love to not have to do this:</p> <pre><code>class TestClass { public function tester($arg) { Logger::logEntry(); Logger::info('Parameter $arg =&gt; ' . $arg); // Do some stuff... Logger::logExit(); } } </code></pre>
[ { "answer_id": 288888, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": -1, "selected": false, "text": "__call class TestClass {\n public function __call($function, $args) {\n Logger::logEntry();\n Logger::info('Parameters: ' . implode(\", \", $args);\n\n $localFunc = \"_\" . $function;\n $return = $this->$localFunc($args);\n\n Logger::logExit();\n\n return $return;\n }\n\n private function _tester() {\n // do stuff...\n return \"tester called\";\n }\n}\n\n $t = new TestClass();\n echo $t->tester();\n // \"tester called\"\n" }, { "answer_id": 288958, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 5, "selected": true, "text": "class LogWatch {\n function __construct($class) {\n $this->obj = $class;\n }\n\n function __call($method, $args) {\n if (in_array($method, get_class_methods($this->obj) ) ) {\n Logger::logEntry();\n Logger::info('Parameter '.implode(', ', $args) );\n\n call_user_func_array(array($this->obj, $method), $args);\n\n Logger::logExit();\n\n } else {\n throw new BadMethodCallException();\n }\n }\n}\n\n$test = new LogWatch(new TestClass() );\n$test->tester();\n\n// you can use instances of `LogWatch()` just like your watched class\n// including passing appropriate params:\n$test->tester($param1, $param2);\n" } ]
2008/11/14
[ "https://Stackoverflow.com/questions/288877", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5291/" ]
288,893
<p>I'm using a PropertyGrid in a tool app to show a window to monitor an object in a remote app. Every second or so I get an update from the app with the state of any members that have changed, and I update the grid. I call Refresh() to make the changes take. This all works pretty well except one thing.</p> <p>Say the object is too tall to fit in the grid so there's a scrollbar. The user has selected a grid item but has also scrolled up above it so that the selected item is below the bottom of the control.</p> <p>The problem is that on Refresh() the control automatically scrolls the grid item into view (strangely it doesn't do this when the item is above the top of the control).</p> <p>I'm looking for a way to either prevent this, or to save state, do the Refresh(), and then set it back. I tried getting the underlying VScrollBar in the PropertyGridView inside the PropertyGrid, and messing with "Value", but it doesn't stay permanently set. Always pops back so the item is in view.</p> <p>Deselecting the item during scrolling is my fallback (the auto scroll-into-view doesn't happen with no selected grid item) but it hurts the usability a little so I'm looking for another way.</p> <p>Anyone run into something similar?</p>
[ { "answer_id": 12004833, "author": "aalutsyk", "author_id": 1606750, "author_profile": "https://Stackoverflow.com/users/1606750", "pm_score": 2, "selected": false, "text": "var panProp = categ.GridItems[3];\nvar tiltProp = categ.GridItems[4];\npanProp.Select();\ntiltProp.Select();\n" }, { "answer_id": 38038496, "author": "fiaharon", "author_id": 3721377, "author_profile": "https://Stackoverflow.com/users/3721377", "pm_score": 1, "selected": false, "text": "public void SoftRefreshPropertyGrid()\n{\n var peMain = propertyGrid.GetType().GetField(\"peMain\", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(propertyGrid)as System.Windows.Forms.GridItem;\n if (peMain != null)\n {\n var refreshMethod = peMain.GetType().GetMethod(\"Refresh\");\n if (refreshMethod != null)\n {\n refreshMethod.Invoke(peMain, null);\n propertyGrid.Invalidate(true);\n }\n }\n}\n" } ]
2008/11/14
[ "https://Stackoverflow.com/questions/288893", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14582/" ]
288,894
<p>I have a master / detail table and want to update some summary values in the master table against the detail table. I know I can update them like this:</p> <pre><code>update MasterTbl set TotalX = (select sum(X) from DetailTbl where DetailTbl.MasterID = MasterTbl.ID) update MasterTbl set TotalY = (select sum(Y) from DetailTbl where DetailTbl.MasterID = MasterTbl.ID) update MasterTbl set TotalZ = (select sum(Z) from DetailTbl where DetailTbl.MasterID = MasterTbl.ID) </code></pre> <p>But, I'd like to do it in a single statement, something like this:</p> <pre><code>update MasterTbl set TotalX = sum(DetailTbl.X), TotalY = sum(DetailTbl.Y), TotalZ = sum(DetailTbl.Z) from DetailTbl where DetailTbl.MasterID = MasterTbl.ID group by MasterID </code></pre> <p>but that doesn't work. I've also tried versions that omit the "group by" clause. I'm not sure whether I'm bumping up against the limits of my particular database (Advantage), or the limits of my SQL. Probably the latter. Can anyone help?</p>
[ { "answer_id": 288910, "author": "Chris", "author_id": 34942, "author_profile": "https://Stackoverflow.com/users/34942", "pm_score": 3, "selected": false, "text": "update \n MasterTbl\nset\n TotalX = Sum(DetailTbl.X),\n TotalY = Sum(DetailTbl.Y),\n TotalZ = Sum(DetailTbl.Z)\nfrom\n DetailTbl\nwhere\n DetailTbl.MasterID = MasterID\n" }, { "answer_id": 289016, "author": "Milen A. Radev", "author_id": 15785, "author_profile": "https://Stackoverflow.com/users/15785", "pm_score": 2, "selected": false, "text": "UPDATE\n MasterTbl\nSET\n TotalX = (SELECT SUM(X) from DetailTbl where DetailTbl.MasterID = MasterTbl.ID),\n TotalY = (SELECT SUM(Y) from DetailTbl where DetailTbl.MasterID = MasterTbl.ID),\n TotalZ = (SELECT SUM(Z) from DetailTbl where DetailTbl.MasterID = MasterTbl.ID)\nWHERE\n ....\n" }, { "answer_id": 289119, "author": "Charles Bretana", "author_id": 32632, "author_profile": "https://Stackoverflow.com/users/32632", "pm_score": 5, "selected": false, "text": " Update MasterTbl Set\n TotalX = Sum(D.X), \n TotalY = Sum(D.Y), \n TotalZ = Sum(D.Z)\n From MasterTbl M Join DetailTbl D\n On D.MasterID = M.MasterID\n \n Update M Set\n TotalX = Sum(D.X), \n TotalY = Sum(D.Y), \n TotalZ = Sum(D.Z)\n From MasterTbl M Join DetailTbl D\n On D.MasterID = M.MasterID\n" }, { "answer_id": 289146, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 2, "selected": false, "text": "update MasterTbl M,\n (select sum(X) as sX,\n sum(Y) as sY,\n sum(Z) as sZ,\n MasterID\n from DetailTbl\n group by MasterID) A\nset\n M.TotalX=A.sX,\n M.TotalY=A.sY,\n M.TotalZ=A.sZ\nwhere\n M.ID=A.MasterID\n" }, { "answer_id": 290019, "author": "Dave Costa", "author_id": 6568, "author_profile": "https://Stackoverflow.com/users/6568", "pm_score": 2, "selected": false, "text": "UPDATE\n MasterTbl\nSET\n (TotalX,TotalY,TotalZ) =\n (SELECT SUM(X),SUM(Y),SUM(Z)\n from DetailTbl where DetailTbl.MasterID = MasterTbl.ID)\n" }, { "answer_id": 2769025, "author": "andora", "author_id": 113825, "author_profile": "https://Stackoverflow.com/users/113825", "pm_score": 1, "selected": false, "text": "'update x....;update y...;update...z'\n" } ]
2008/11/14
[ "https://Stackoverflow.com/questions/288894", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8752/" ]
288,900
<p>I have a string which holds a decimal value in it and I need to convert that string into a floating point variable. So an example of the string I have is "5.45" and I want a floating point equivalent so I can add .1 to it. I have searched around the internet, but I only see how to convert a string to an integer.</p>
[ { "answer_id": 288907, "author": "Alnitak", "author_id": 6782, "author_profile": "https://Stackoverflow.com/users/6782", "pm_score": 8, "selected": true, "text": "% perl -e 'print \"5.45\" + 0.1;'\n5.55\n" }, { "answer_id": 288967, "author": "Rini", "author_id": 14374, "author_profile": "https://Stackoverflow.com/users/14374", "pm_score": 2, "selected": false, "text": "% perl -e \"print 5.4 . 3.4;\"\n5.43.4\n\n\n% perl -e \"print '5.4' + '3.4';\"\n8.8\n" }, { "answer_id": 289135, "author": "brian d foy", "author_id": 2766176, "author_profile": "https://Stackoverflow.com/users/2766176", "pm_score": 5, "selected": false, "text": "# numeric addition with strings:\nmy $sum = '5.45' + '0.01'; # 5.46\n # string replication with numbers:\nmy $string = ( 45/2 ) x 4; # \"22.522.522.522.5\"\n" }, { "answer_id": 2835835, "author": "Norm", "author_id": 341417, "author_profile": "https://Stackoverflow.com/users/341417", "pm_score": 3, "selected": false, "text": "my @foo = ('1.2', '3.4', '2.1', '4.6');\nmy @foo_sort = sort {$a <=> $b} @foo;\n" }, { "answer_id": 8539065, "author": "porquero", "author_id": 892160, "author_profile": "https://Stackoverflow.com/users/892160", "pm_score": 6, "selected": false, "text": "my $var1 = \"123abc\";\nprint $var1 + 0;\n 123\n my $var2 = \"abc123\";\nprint $var2 + 0;\n 0\n" }, { "answer_id": 12143471, "author": "Steffen Moeller", "author_id": 1627874, "author_profile": "https://Stackoverflow.com/users/1627874", "pm_score": 1, "selected": false, "text": "use strict;\n....\nnext unless $line =~ /and your result is:\\s*(.*)/;\nmy $val = $1;\nif ($val < 0.001) {\n print \"this is small\\n\";\n}\n $val \"2e-77\" $line" }, { "answer_id": 17637567, "author": "indexless", "author_id": 335398, "author_profile": "https://Stackoverflow.com/users/335398", "pm_score": 3, "selected": false, "text": "$var += 0\n my $var = 'abc123';\nprint \"var = $var\\n\";\n$var += 0;\nprint \"var = $var\\n\";\n var = abc123\nArgument \"abc123\" isn't numeric in addition (+) at test.pl line 7.\nvar = 0\n" }, { "answer_id": 17951618, "author": "SzG", "author_id": 1323940, "author_profile": "https://Stackoverflow.com/users/1323940", "pm_score": 0, "selected": false, "text": "$a = 7*6; $b = 7x6; print \"$a $b\\n\"; 42 777777 Data::Dumper $my_hash{$1} = $2 if /(.+)=(.+)\\n/; 'foo' => '42' $my_hash{$1} = $2+0 if /(.+)=(.+)\\n/; 'foo' => 42 $2+0 Data::Dumper" } ]
2008/11/14
[ "https://Stackoverflow.com/questions/288900", "https://Stackoverflow.com", "https://Stackoverflow.com/users/340/" ]
288,942
<p>How to convert last 3 digits of number into 0</p> <p>example 3444678 to 3444000</p> <p>I can do like </p> <p>(int)(3444678/1000) * 1000= 3444000</p> <p>But division and multiplication could be costly...</p> <p>Any other solution????</p>
[ { "answer_id": 288946, "author": "Jesse Beder", "author_id": 112, "author_profile": "https://Stackoverflow.com/users/112", "pm_score": 5, "selected": true, "text": "n - (n % 1000)\n" }, { "answer_id": 288959, "author": "Peter C.", "author_id": 31389, "author_profile": "https://Stackoverflow.com/users/31389", "pm_score": 0, "selected": false, "text": "int takeAway(int num)\n{\n for (int i = 1; i =< 3; i++)\n {\n num = num/10;\n }\n\n return num;\n}\n\nint addZeroes(int num)\n{\n for (int i = 1; i =< 3; i++)\n {\n num = num*10;\n }\n\n return num;\n}\n" }, { "answer_id": 288985, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 0, "selected": false, "text": "Dividing\nTime taken was 7 wallclock secs ( 6.83 usr 0.00 sys + 0.00 cusr 0.00 csys = 6.83 CPU) seconds\n\nMultiplying\nTime taken was 7 wallclock secs ( 6.67 usr 0.00 sys + 0.00 cusr 0.00 csys = 6.67 CPU) seconds\n\nModding\nTime taken was 8 wallclock secs ( 7.87 usr 0.00 sys + 0.00 cusr 0.00 csys = 7.87 CPU) seconds\n\nMultiply + Dividing\nTime taken was 10 wallclock secs (10.18 usr 0.01 sys + 0.00 cusr 0.00 csys = 10.19 CPU) seconds\n 10 ** 7 * 3 10**8 use strict;\nuse warnings;\nuse version;\nour $VERSION = qv('0.1');\n\nsub xround { \n my ( $number, $precision ) = @_ ;\n if ( $precision eq 0 )\n {\n return int( $number + .5 ); \n }\n my $scale = 10 ** abs( $precision ) ;\n\n $number = $number / $scale if $precision > 0; \n $number = $number * $scale if $precision < 0; \n\n $number = int( $number + .5 );\n\n $number = $number * $scale if $precision > 0; \n $number = $number / $scale if $precision < 0; \n return $number;\n}\n\nmy $fmt = \"%s : %s ( %s )\\n\";\nmy $n = 55555.55555;\nfor my $i ( -4 .. 4 )\n{\n\n printf $fmt, $n, xround($n, $i), $i; \n}\n 55555.55555 : 55555.5556 ( -4 )\n55555.55555 : 55555.556 ( -3 )\n55555.55555 : 55555.56 ( -2 )\n55555.55555 : 55555.6 ( -1 )\n55555.55555 : 55556 ( 0 )\n55555.55555 : 55560 ( 1 )\n55555.55555 : 55600 ( 2 )\n55555.55555 : 56000 ( 3 )\n55555.55555 : 60000 ( 4 )\n use strict;\nuse warnings;\nuse version;\nour $VERSION = qv('0.1');\n\nsub xround {\n my ( $number, $precision ) = @_;\n my $ino = int( $number );\n if ( $precision eq 0 ) {\n return $ino; \n }\n my $power = 10**$precision;\n\n if ( $precision > 0 ) {\n return int( $number - ( $number % $power ) );\n }\n return $ino + int( ( $number - $ino ) / $power ) * $power;\n}\n\n\nmy $fmt = \"%s : %s ( %s )\\n\";\nmy $n = 55555.55555;\nfor my $i ( -4 .. 4 )\n{\n printf $fmt, $n, xround($n, $i), $i; \n}\n 55555.55555 : 55555.5555 ( -4 )\n55555.55555 : 55555.555 ( -3 )\n55555.55555 : 55555.55 ( -2 )\n55555.55555 : 55555.5 ( -1 )\n55555.55555 : 55555 ( 0 )\n55555.55555 : 55550 ( 1 )\n55555.55555 : 55500 ( 2 )\n55555.55555 : 55000 ( 3 )\n55555.55555 : 50000 ( 4 )\n" }, { "answer_id": 289018, "author": "Bill K", "author_id": 12943, "author_profile": "https://Stackoverflow.com/users/12943", "pm_score": 1, "selected": false, "text": "int mult10(int val) {\n int tmp_2val = val << 1; // double val\n int tmp_8val = val << 3; // 8x val\n return( tmp_2val + tmp_8val ); // 2x + 8x = 10x\n}\n" }, { "answer_id": 289034, "author": "Artelius", "author_id": 31945, "author_profile": "https://Stackoverflow.com/users/31945", "pm_score": 3, "selected": false, "text": "n >>= 3;\nn -= n % (5 * 5 * 5);\nn <<= 3;\n n -= n % 1000;\n" }, { "answer_id": 289061, "author": "geocar", "author_id": 37507, "author_profile": "https://Stackoverflow.com/users/37507", "pm_score": 1, "selected": false, "text": "x &= ~0777;\n x &= ~0xfff;\n x -= (x % 1000);\n" } ]
2008/11/14
[ "https://Stackoverflow.com/questions/288942", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33411/" ]
288,954
<p>I'm fairly new to WPF and I've come across a problem that seems a bit tricky to solve. Basically I want a 4x4 grid thats scalable but keeps a square (or any other arbitrary) aspect ratio. This actually seems quite tricky to do, which surprises me because I would imagine its a reasonably common requirement.</p> <p>I start with a Grid definition like this:</p> <pre><code>&lt;Grid&gt; &lt;Grid.RowDefinitions&gt; &lt;Grid.RowDefinition Height="*"/&gt; &lt;Grid.RowDefinition Height="*"/&gt; &lt;Grid.RowDefinition Height="*"/&gt; &lt;Grid.RowDefinition Height="*"/&gt; &lt;/Grid.RowDefinitions&gt; &lt;Grid.ColumnDefinitions&gt; &lt;Grid.ColumnDefinition Width="*"/&gt; &lt;Grid.ColumnDefinition Width="*"/&gt; &lt;Grid.ColumnDefinition Width="*"/&gt; &lt;Grid.ColumnDefinition Width="*"/&gt; &lt;/Grid.ColumnDefinition&gt; ... &lt;/Grid&gt; </code></pre> <p>Now if you set that to stretch, it can fill the Window or whatever container you put it in. The rows and column are uniform but the aspect ratio isn't fixed.</p> <p>Then I tried putting it in a StackPanel to use the available space. Didn't help. What did get me most of the way there was when I remembered Viewboxes.</p> <pre><code>&lt;StackPanel Orientation="Horizontal"&gt; &lt;Viewbox&gt; &lt;Grid Height="1000" Width="1000"&gt; &lt;!-- this locks aspect ratio --&gt; &lt;Grid.RowDefinitions&gt; &lt;Grid.RowDefinition Height="*"/&gt; &lt;Grid.RowDefinition Height="*"/&gt; &lt;Grid.RowDefinition Height="*"/&gt; &lt;Grid.RowDefinition Height="*"/&gt; &lt;/Grid.RowDefinitions&gt; &lt;Grid.ColumnDefinitions&gt; &lt;Grid.ColumnDefinition Width="*"/&gt; &lt;Grid.ColumnDefinition Width="*"/&gt; &lt;Grid.ColumnDefinition Width="*"/&gt; &lt;Grid.ColumnDefinition Width="*"/&gt; &lt;/Grid.ColumnDefinition&gt; ... &lt;/Grid&gt; &lt;/viewbox&gt; &lt;Label HorizontalAlignment="Stretch"&gt;Extra Space&lt;/Label&gt; &lt;/StackPanel&gt; </code></pre> <p>Now my content scales and keeps aspect ratio. The problem is that if the window isn't wide enough some of my grid is off the screen. I'd like to be able to scroll to it if that were the case. Likewise, I might need a minimum size, which might lead to vertical scrolling too.</p> <p>Now I've tried putting my StackPanel and Grid (separately) in an appropriate ScrollViewer container but then the content no longer scales to fit the window. It goes to full size, which is no good.</p> <p>So how do I go about doing this? Am I barking up the wrong tree? Is there a better/easier way of doing this?</p>
[ { "answer_id": 289425, "author": "Donnelle", "author_id": 28074, "author_profile": "https://Stackoverflow.com/users/28074", "pm_score": -1, "selected": false, "text": "SizeToContent=\"WidthAndHeight\"" } ]
2008/11/14
[ "https://Stackoverflow.com/questions/288954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18393/" ]
288,955
<p>To send a serial string character to the serial port. I would need to call WriteFile(handle, "A", strlen("A"), ...)</p> <p>However, what if I want to specify and send a hex or binary number? For example, I want to send WriteFile(handle, 0x41, sizeOf(0x41), ...) ?</p> <p>Is there a function that allow me to do this?</p>
[ { "answer_id": 288960, "author": "Pyrolistical", "author_id": 21838, "author_profile": "https://Stackoverflow.com/users/21838", "pm_score": 1, "selected": false, "text": "int buffer[1024];\nbuffer[0] = 42;\n\nWriteFile(handle, buffer, 1);\n" } ]
2008/11/14
[ "https://Stackoverflow.com/questions/288955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28462/" ]
288,966
<p>How would you describe the running time of this sort, given a function <code>sorted</code> which returns True if the list is sorted that runs in O(n):</p> <pre><code>def sort(l): while not sorted(l): random.shuffle(l) </code></pre> <p>Assume shuffling is perfectly random. </p> <p>Would this be written in big-O notation? Or is there some other way of categorizing algorithms with random components?</p>
[ { "answer_id": 289017, "author": "Jörg W Mittag", "author_id": 2988, "author_profile": "https://Stackoverflow.com/users/2988", "pm_score": 4, "selected": true, "text": "O(n·n!)" } ]
2008/11/14
[ "https://Stackoverflow.com/questions/288966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15055/" ]
288,968
<p>Is it possible to perform a named-group match in Perl's regex syntax as with Python's? I always bind the <code>$n</code> values to proper names after matching, so I'd find it more convenient to do it in the regex itself if it's possible.</p> <p>Python does it like so:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; regex = re.compile(r'(?P&lt;count&gt;\d+)') &gt;&gt;&gt; match = regex.match('42') &gt;&gt;&gt; print match.groupdict() {'count': '42'} </code></pre> <p>I know the <code>?P</code> indicates that it's a Python-specific regex feature, but I'm hoping it's in Perl in a different way or was added later on. Is there any way to get a result hash in a similar manner in Perl?</p>
[ { "answer_id": 288983, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 3, "selected": false, "text": "(?'NAME'pattern)\n(?<NAME>pattern)\n" }, { "answer_id": 288989, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 7, "selected": true, "text": "(?<NAME>pattern) %+ $variable =~ /(?<count>\\d+)/;\nprint \"Count is $+{count}\";\n" }, { "answer_id": 289149, "author": "brian d foy", "author_id": 2766176, "author_profile": "https://Stackoverflow.com/users/2766176", "pm_score": 4, "selected": false, "text": "(?<NAME>pattern) (?P<NAME>pattern)\n \\g{NAME} (?P=NAME)\n (?&NAME) (?P>NAME)\n" }, { "answer_id": 1091618, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "my %hash;\n@hash{\"count\", \"something_else\"} = $string =~ /(\\d+)\\s*,\\s*(\\S+)/;\n" }, { "answer_id": 73219617, "author": "Elvin", "author_id": 13762488, "author_profile": "https://Stackoverflow.com/users/13762488", "pm_score": 0, "selected": false, "text": "%{^CAPTURE} %+ #! /usr/bin/env perl\n\nuse v5.32;\nuse warnings;\nuse English;\n\nmy $output = `php -v`;\n\n$output =~ m(PHP (?<version>\\d.\\d.\\d\\d)); # named capture group\n\nsay ${^CAPTURE}{version}; # instead of $1\n \\g{NAME}" } ]
2008/11/14
[ "https://Stackoverflow.com/questions/288968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3594/" ]
288,984
<p>I'm looking to calculate the number of months between 2 date time fields.</p> <p>Is there a better way than getting the Unix timestamp and then dividing by 2 592 000 (seconds) and rounding up within MySQL?</p>
[ { "answer_id": 289032, "author": "Vincent Ramdhanie", "author_id": 27439, "author_profile": "https://Stackoverflow.com/users/27439", "pm_score": 3, "selected": false, "text": "Select period_diff(concat(year(d1),if(month(d1)<10,'0',''),month(d1)), concat(year(d2),if(month(d2)<10,'0',''),month(d2))) as months from your_table;\n" }, { "answer_id": 482572, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "SELECT * \nFROM emp_salaryrevise_view \nWHERE curr_year Between '2008' AND '2009' \n AND MNTH Between '12' AND '1'\n" }, { "answer_id": 562477, "author": "Max Caceres", "author_id": 4842, "author_profile": "https://Stackoverflow.com/users/4842", "pm_score": 7, "selected": false, "text": "select period_diff(date_format(now(), '%Y%m'), date_format(time, '%Y%m')) as months from your_table;\n" }, { "answer_id": 1396503, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "select period_diff(date_format(now(),\"%Y%m\"),date_format(created,\"%Y%m\")) from customers where..\n" }, { "answer_id": 2797268, "author": "Khaleel Rshid", "author_id": 336579, "author_profile": "https://Stackoverflow.com/users/336579", "pm_score": -1, "selected": false, "text": "SELECT * FROM tbl_purchase_receipt\nWHERE purchase_date BETWEEN '2008-09-09' AND '2009-09-09'\n" }, { "answer_id": 3529647, "author": "Stanislav Basovník", "author_id": 261406, "author_profile": "https://Stackoverflow.com/users/261406", "pm_score": 3, "selected": false, "text": "SELECT\n 12 * (YEAR(to) - YEAR(from)) + (MONTH(to) - MONTH(from)) AS months\nFROM\n tab;\n" }, { "answer_id": 4093120, "author": "Rama", "author_id": 496664, "author_profile": "https://Stackoverflow.com/users/496664", "pm_score": 2, "selected": false, "text": "DROP FUNCTION IF EXISTS `calcula_edad` $$\nCREATE DEFINER=`root`@`localhost` FUNCTION `calcula_edad`(pFecha1 date, pFecha2 date, pTipo char(1)) RETURNS int(11)\nBegin\n\n Declare vMeses int;\n Declare vEdad int;\n\n Set vMeses = period_diff( date_format( pFecha1, '%Y%m' ), date_format( pFecha2, '%Y%m' ) ) ;\n\n /* Si el dia de la fecha1 es menor al dia de fecha2, restar 1 mes */\n if day(pFecha1) < day(pFecha2) then\n Set vMeses = VMeses - 1;\n end if;\n\n if pTipo='A' then\n Set vEdad = vMeses div 12 ;\n else\n Set vEdad = vMeses ;\n end if ;\n Return vEdad;\nEnd\n\nselect calcula_edad(curdate(),born_date,'M') -- for number of months between 2 dates\n" }, { "answer_id": 5159675, "author": "Smolla", "author_id": 488794, "author_profile": "https://Stackoverflow.com/users/488794", "pm_score": 5, "selected": false, "text": " SELECT PERIOD_DIFF(EXTRACT(YEAR_MONTH FROM NOW()), EXTRACT(YEAR_MONTH FROM time)) AS months FROM your_table;\n" }, { "answer_id": 6818533, "author": "enor", "author_id": 872829, "author_profile": "https://Stackoverflow.com/users/872829", "pm_score": 2, "selected": false, "text": "DELIMITER $$\n\nCREATE FUNCTION datedifference(date1 DATE, date2 DATE) RETURNS DATE\nNO SQL\n\nBEGIN\n DECLARE dif DATE;\n IF DATEDIFF(date1, DATE(CONCAT(YEAR(date1),'-', MONTH(date1), '-', DAY(date2)))) < 0 THEN\n SET dif=DATE_FORMAT(\n CONCAT(\n PERIOD_DIFF(date_format(date1, '%y%m'),date_format(date2, '%y%m'))DIV 12 , \n '-',\n PERIOD_DIFF(date_format(date1, '%y%m'),date_format(date2, '%y%m'))% 12 , \n '-',\n DATEDIFF(date1, DATE(CONCAT(YEAR(date1),'-', MONTH(DATE_SUB(date1, INTERVAL 1 MONTH)), '-', DAY(date2))))),\n '%Y-%m-%d');\n ELSEIF DATEDIFF(date1, DATE(CONCAT(YEAR(date1),'-', MONTH(date1), '-', DAY(date2)))) < DAY(LAST_DAY(DATE_SUB(date1, INTERVAL 1 MONTH))) THEN\n SET dif=DATE_FORMAT(\n CONCAT(\n PERIOD_DIFF(date_format(date1, '%y%m'),date_format(date2, '%y%m'))DIV 12 , \n '-',\n PERIOD_DIFF(date_format(date1, '%y%m'),date_format(date2, '%y%m'))% 12 , \n '-',\n DATEDIFF(date1, DATE(CONCAT(YEAR(date1),'-', MONTH(date1), '-', DAY(date2))))),\n '%Y-%m-%d');\n ELSE\n SET dif=DATE_FORMAT(\n CONCAT(\n PERIOD_DIFF(date_format(date1, '%y%m'),date_format(date2, '%y%m'))DIV 12 , \n '-',\n PERIOD_DIFF(date_format(date1, '%y%m'),date_format(date2, '%y%m'))% 12 , \n '-',\n DATEDIFF(date1, DATE(CONCAT(YEAR(date1),'-', MONTH(date1), '-', DAY(date2))))),\n '%Y-%m-%d');\n END IF;\n\nRETURN dif;\nEND $$\nDELIMITER;\n" }, { "answer_id": 11716882, "author": "Zane Bien", "author_id": 1446794, "author_profile": "https://Stackoverflow.com/users/1446794", "pm_score": 8, "selected": false, "text": "TIMESTAMP DATETIME DATE MONTH SELECT TIMESTAMPDIFF(MONTH, '2012-05-05', '2012-06-04')\n-- Outputs: 0\n SELECT TIMESTAMPDIFF(MONTH, '2012-05-05', '2012-06-05')\n-- Outputs: 1\n SELECT TIMESTAMPDIFF(MONTH, '2012-05-05', '2012-06-15')\n-- Outputs: 1\n SELECT TIMESTAMPDIFF(MONTH, '2012-05-05', '2012-12-16')\n-- Outputs: 7\n SELECT \n TIMESTAMPDIFF(MONTH, startdate, enddate) +\n DATEDIFF(\n enddate,\n startdate + INTERVAL\n TIMESTAMPDIFF(MONTH, startdate, enddate)\n MONTH\n ) /\n DATEDIFF(\n startdate + INTERVAL\n TIMESTAMPDIFF(MONTH, startdate, enddate) + 1\n MONTH,\n startdate + INTERVAL\n TIMESTAMPDIFF(MONTH, startdate, enddate)\n MONTH\n )\n startdate enddate With startdate = '2012-05-05' AND enddate = '2012-05-27':\n-- Outputs: 0.7097\n With startdate = '2012-05-05' AND enddate = '2012-06-13':\n-- Outputs: 1.2667\n With startdate = '2012-02-27' AND enddate = '2012-06-02':\n-- Outputs: 3.1935\n" }, { "answer_id": 24082154, "author": "Artur Kędzior", "author_id": 275882, "author_profile": "https://Stackoverflow.com/users/275882", "pm_score": 0, "selected": false, "text": "SELECT \nusername\n,date_of_birth\n,DATE_FORMAT(CURDATE(), '%Y') - DATE_FORMAT(date_of_birth, '%Y') - (DATE_FORMAT(CURDATE(), '00-%m-%d') < DATE_FORMAT(date_of_birth, '00-%m-%d')) AS years\n,PERIOD_DIFF( DATE_FORMAT(CURDATE(), '%Y%m') , DATE_FORMAT(date_of_birth, '%Y%m') ) AS months\n,DATEDIFF(CURDATE(),date_of_birth) AS days\nFROM users\n" }, { "answer_id": 44170975, "author": "Michel", "author_id": 7896428, "author_profile": "https://Stackoverflow.com/users/7896428", "pm_score": 1, "selected": false, "text": "SELECT\n '2012-02-27' AS startdate,\n '2012-06-02' AS enddate,\n TIMESTAMPDIFF(DAY, (SELECT startdate), (SELECT enddate)) AS days,\n IF(MONTH((SELECT startdate)) = MONTH((SELECT enddate)), 0, (TIMESTAMPDIFF(DAY, (SELECT startdate), LAST_DAY((SELECT startdate)) + INTERVAL 1 DAY)) / DAY(LAST_DAY((SELECT startdate)))) AS period1, \n TIMESTAMPDIFF(MONTH, LAST_DAY((SELECT startdate)) + INTERVAL 1 DAY, LAST_DAY((SELECT enddate))) AS period2,\n IF(MONTH((SELECT startdate)) = MONTH((SELECT enddate)), (SELECT days), DAY((SELECT enddate))) / DAY(LAST_DAY((SELECT enddate))) AS period3,\n (SELECT period1) + (SELECT period2) + (SELECT period3) AS months\n" }, { "answer_id": 47810408, "author": "Shubham Verma", "author_id": 7193018, "author_profile": "https://Stackoverflow.com/users/7193018", "pm_score": 0, "selected": false, "text": "select MONTH(NOW())-MONTH(table_date) as 'Total Month Difference' from table_name;\n select MONTH(Newer_date)-MONTH(Older_date) as 'Total Month Difference' from table_Name;\n" }, { "answer_id": 48924553, "author": "IanS", "author_id": 4529864, "author_profile": "https://Stackoverflow.com/users/4529864", "pm_score": 4, "selected": false, "text": "SELECT TIMESTAMPDIFF(MONTH, '2018-01-01', '2018-01-31'); => 0\nSELECT TIMESTAMPDIFF(MONTH, '2018-01-01', '2018-02-01'); => 1\n SELECT ROUND(TIMESTAMPDIFF(DAY, '2018-01-01', '2018-01-31')*12/365.24); => 1\nSELECT ROUND(TIMESTAMPDIFF(DAY, '2018-01-01', '2018-01-31')*12/365.24); => 1\n" }, { "answer_id": 52112675, "author": "Amitesh Bharti", "author_id": 2745436, "author_profile": "https://Stackoverflow.com/users/2745436", "pm_score": 1, "selected": false, "text": "SELECT PERIOD_DIFF(200905,200811);\n" }, { "answer_id": 54651629, "author": "Mo Kassab", "author_id": 11051151, "author_profile": "https://Stackoverflow.com/users/11051151", "pm_score": 0, "selected": false, "text": "SELECT convert(TIMESTAMPDIFF(year, ins_frm, ins_to),UNSIGNED) as yrs,\n mod(TIMESTAMPDIFF(MONTH, ins_frm, ins_to),12) mnths\nFROM table_name\n" }, { "answer_id": 55840764, "author": "Maceo", "author_id": 11408173, "author_profile": "https://Stackoverflow.com/users/11408173", "pm_score": 0, "selected": false, "text": "SELECT YEAR(end_date)*12 + MONTH(end_date) - (YEAR(start_date)*12 + MONTH(start_date))\n" }, { "answer_id": 70238213, "author": "Bob Siefkes", "author_id": 655006, "author_profile": "https://Stackoverflow.com/users/655006", "pm_score": 0, "selected": false, "text": "set @from = '2021-09-29 12:00:00';\nset @to = '2021-11-07 00:00:00';\nselect \n/* part 1 */ (unix_timestamp(last_day(@from)) + 86400 - unix_timestamp(@from)) / 86400 / day(last_day(@from))\n/* part 2 */ + PERIOD_DIFF(EXTRACT(YEAR_MONTH FROM @to), EXTRACT(YEAR_MONTH FROM @from)) - 1 +\n/* part 3 */ 1 - (unix_timestamp(last_day(@to)) + 86400 - unix_timestamp(@to)) / 86400 / day(last_day(@to)) \nmonth_fraction;\n select \n/* part 1 */ (unix_timestamp(last_day(periodStart)) + 86400 - unix_timestamp(periodStart)) / 86400 / day(last_day(periodStart))\n/* part 2 */ + PERIOD_DIFF(EXTRACT(YEAR_MONTH FROM periodTill), EXTRACT(YEAR_MONTH FROM periodStart)) - 1 +\n/* part 3 */ 1 - (unix_timestamp(last_day(periodTill)) + 86400 - unix_timestamp(periodTill)) / 86400 / day(last_day(periodTill))\nmonth_fraction\nfrom (select '2021-09-29 12:00:00' periodStart, '2021-11-07 00:00:00' periodTill) period\n unix_timestamp unix_timestamp" } ]
2008/11/14
[ "https://Stackoverflow.com/questions/288984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5441/" ]
288,988
<p>I was trying to follow some instructions today, and it starts with the comment </p> <pre><code> REM In SQLPlus I manually copy in each line and execute it. </code></pre> <p>That's nice, I don't have SQLPlus, I have SQLDeveloper. The lines that were pasted in were of the type:</p> <pre><code> @\\server\dir\dir\dir\commandfile1.txt; COMMIT; </code></pre> <p>...etc.</p> <p>It didn't like it when I tried that in a SQL window. I opened up and pasted in the commands by hand, and it wasn't happy with that either. (Did I mention that I'm not so good with this application nor Oracle, but that everyone else was out today?) The files there started with code like:</p> <pre><code> rem set echo on rem execute procedure_name ('parameter1', 'parameter2'); </code></pre> <p>A co-worker did have SQLPlus, and together we got it resolved. But, is there a way for me to do this with SQLDeveloper, so I'm not stuck if he's out too?</p>
[ { "answer_id": 289086, "author": "David Aldridge", "author_id": 6742, "author_profile": "https://Stackoverflow.com/users/6742", "pm_score": -1, "selected": false, "text": "begin\n procedure_name ('parameter1', 'parameter2');\nend;\n/\n" }, { "answer_id": 3663193, "author": "user313218", "author_id": 313218, "author_profile": "https://Stackoverflow.com/users/313218", "pm_score": 7, "selected": true, "text": "@\"\\Path\\Scriptname.sql\"\n" }, { "answer_id": 54224962, "author": "Jorge Moreno", "author_id": 4139291, "author_profile": "https://Stackoverflow.com/users/4139291", "pm_score": 1, "selected": false, "text": "sqlcl user/password@host:port:sid @file.sql\n" } ]
2008/11/14
[ "https://Stackoverflow.com/questions/288988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22523/" ]
288,998
<p>I was wondering if anyone can help me get started with creating a room in Sandy 3D. I know I can generate the planes, but I am unsure as to how to implement simple physics (i.e. the player cannot walk through a wall). Is there a simple way to do this, or should I look into something like WOW (3D physics engine for Flash)?</p> <p>Thanks, Cameron</p>
[ { "answer_id": 289086, "author": "David Aldridge", "author_id": 6742, "author_profile": "https://Stackoverflow.com/users/6742", "pm_score": -1, "selected": false, "text": "begin\n procedure_name ('parameter1', 'parameter2');\nend;\n/\n" }, { "answer_id": 3663193, "author": "user313218", "author_id": 313218, "author_profile": "https://Stackoverflow.com/users/313218", "pm_score": 7, "selected": true, "text": "@\"\\Path\\Scriptname.sql\"\n" }, { "answer_id": 54224962, "author": "Jorge Moreno", "author_id": 4139291, "author_profile": "https://Stackoverflow.com/users/4139291", "pm_score": 1, "selected": false, "text": "sqlcl user/password@host:port:sid @file.sql\n" } ]
2008/11/14
[ "https://Stackoverflow.com/questions/288998", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21475/" ]
289,001
<p>I have a MySQL table where an indexed <code>INT</code> column is going to be 0 for 90% of the rows. If I change those rows to use <code>NULL</code> instead of 0, will they be left out of the index, making the index about 90% smaller?</p>
[ { "answer_id": 289012, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 3, "selected": false, "text": "NULL" }, { "answer_id": 16637462, "author": "Khanh Van", "author_id": 780763, "author_profile": "https://Stackoverflow.com/users/780763", "pm_score": 5, "selected": false, "text": "col_name IS NULL col_name = constant_value NULL IS NULL" } ]
2008/11/14
[ "https://Stackoverflow.com/questions/289001", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28835/" ]
289,002
<p>I have a static class that I would like to raise an event as part of a try catch block within a static method of that class.</p> <p>For example in this method I would like to raise a custom event in the catch. </p> <pre><code>public static void saveMyMessage(String message) { try { //Do Database stuff } catch (Exception e) { //Raise custom event here } } </code></pre> <p>Thank you.</p>
[ { "answer_id": 289043, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "public static event EventHandler Work;\n" }, { "answer_id": 289044, "author": "Todd", "author_id": 31940, "author_profile": "https://Stackoverflow.com/users/31940", "pm_score": 4, "selected": false, "text": "public class ErrorEventArgs : EventArgs\n{\n private Exception error;\n private string message;\n\n public ErrorEventArgs(Exception ex, string msg)\n {\n error = ex;\n message = msg;\n }\n\n public Exception Error\n {\n get { return error; }\n }\n\n public string Message \n {\n get { return message; }\n }\n}\n\npublic static class Service\n{\n public static EventHandler<ErrorEventArgs> OnError;\n\n public static void SaveMyMessage(String message)\n {\n EventHandler<ErrorEventArgs> errorEvent = OnError;\n if (errorEvent != null)\n {\n errorEvent(null, new ErrorEventArgs(null, message));\n }\n }\n}\n public class Test\n{\n public void OnError(object sender, ErrorEventArgs args)\n {\n Console.WriteLine(args.Message);\n }\n }\n\n Test t = new Test();\n Service.OnError += t.OnError;\n Service.SaveMyMessage(\"Test message\");\n" }, { "answer_id": 289351, "author": "Brian B.", "author_id": 21817, "author_profile": "https://Stackoverflow.com/users/21817", "pm_score": 3, "selected": false, "text": "if(null != ExampleEvent)\n{\n ExampleEvent(/* put parameters here, for events: sender, eventArgs */);\n}\n MyEvent exampleEventCopy = ExampleEvent;\nif(null != exampleEventCopy)\n{\n exampleEventCopy(/* put parameters here, for events: sender, eventArgs */);\n}\n" }, { "answer_id": 289358, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 8, "selected": true, "text": "static public static event EventHandler SomeEvent;\n public static event EventHandler SomeEvent = delegate {};\n SomeEvent(null, EventArgs.Empty);\n" }, { "answer_id": 1926468, "author": "Nelson P. Varghese", "author_id": 229217, "author_profile": "https://Stackoverflow.com/users/229217", "pm_score": 0, "selected": false, "text": "EventHandler<ErrorEventArgs> errorEvent = OnError;\n" }, { "answer_id": 70320777, "author": "Hani", "author_id": 10225176, "author_profile": "https://Stackoverflow.com/users/10225176", "pm_score": 0, "selected": false, "text": "public delegate void CustomeEventHandler(string str);\n public static event CustomeEventHandler ReadLine;\n static void OnLineRead(string currentLine)\n {\n if (ReadLine != null)\n ReadLine(currentLine);\n }\n" } ]
2008/11/14
[ "https://Stackoverflow.com/questions/289002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34831/" ]
289,003
<p>I have an Asp.Net 1.1 application that uses the following code to write out an image file to a pop up web page.</p> <pre><code> Response.ContentType="image/tiff" 'Only for Tif files Dim objStream As Object objStream = Server.CreateObject("ADODB.Stream") objStream.open() objStream.type = 1 objStream.loadfromfile(localfile) Response.BinaryWrite(objStream.read) </code></pre> <p>I'm testing this out with TIF files. The files are being displayed correctly in IE6 and Safari but in IE7 they are not displaying and nothing seems to be returning to the web page. Files with jpg, gif extensions are being displayed properly. What might be the problem here?</p>
[ { "answer_id": 289015, "author": "Michael Stum", "author_id": 91, "author_profile": "https://Stackoverflow.com/users/91", "pm_score": 0, "selected": false, "text": "Response.AppendHeader(\"Content-Disposition\", \"inline\");\n" } ]
2008/11/14
[ "https://Stackoverflow.com/questions/289003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1688440/" ]
289,006
<p>I am trying to write a console app that simply lists the number of lists at the sharepoint root.</p> <p>I tried doing it by using the following code, but the object SPContext.Current is null. Any ideas of how to get the web object?</p> <pre><code> SPWeb web = SPContext.Current.Site.OpenWeb("http://localhost") ; </code></pre>
[ { "answer_id": 289026, "author": "Nat", "author_id": 13813, "author_profile": "https://Stackoverflow.com/users/13813", "pm_score": 3, "selected": true, "text": "SPSite spSite = new SPSite(\"http://myurl\");\nSPWeb spMySite = spSite.Allwebs[\"mysite\"];\nSPWeb spRootsite = spsite.RootWeb;\n" }, { "answer_id": 289382, "author": "Nico", "author_id": 22970, "author_profile": "https://Stackoverflow.com/users/22970", "pm_score": 3, "selected": false, "text": "using (SPSite site = new SPSite(weburl))\n{\n using (SPWeb web = site.OpenWeb())\n {\n // bla bla\n }\n}\n" }, { "answer_id": 290866, "author": "Alex Angas", "author_id": 6651, "author_profile": "https://Stackoverflow.com/users/6651", "pm_score": 0, "selected": false, "text": "site.OpenWeb(webUid);\n site.OpenWeb(relativeUrl);\nsite.OpenWeb(title);\n site.OpenWeb(relativeUrl, true);\n" } ]
2008/11/14
[ "https://Stackoverflow.com/questions/289006", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12497/" ]
289,010
<p>Similar to <a href="https://stackoverflow.com/questions/188141/c-list-orderby-alphabetical-order">List&lt;&gt; OrderBy Alphabetical Order</a>, we want to sort by one element, then another. we want to achieve the functional equivalent of </p> <pre><code>SELECT * from Table ORDER BY x, y </code></pre> <p>We have a class that contains a number of sorting functions, and we have no issues sorting by one element.<br> For example: </p> <pre><code>public class MyClass { public int x; public int y; } List&lt;MyClass&gt; MyList; public void SortList() { MyList.Sort( MySortingFunction ); } </code></pre> <p>And we have the following in the list: </p> <pre><code>Unsorted Sorted(x) Desired --------- --------- --------- ID x y ID x y ID x y [0] 0 1 [2] 0 2 [0] 0 1 [1] 1 1 [0] 0 1 [2] 0 2 [2] 0 2 [1] 1 1 [1] 1 1 [3] 1 2 [3] 1 2 [3] 1 2 </code></pre> <p>Stable sort would be preferable, but not required. Solution that works for .Net 2.0 is welcome.</p>
[ { "answer_id": 289021, "author": "Toby", "author_id": 291137, "author_profile": "https://Stackoverflow.com/users/291137", "pm_score": 7, "selected": false, "text": "OrderBy ThenBy ThenByDescending using System.Linq;\n....\nList<SomeClass>() a;\nList<SomeClass> b = a.OrderBy(x => x.x).ThenBy(x => x.y).ToList();\n" }, { "answer_id": 289040, "author": "Hans Passant", "author_id": 17034, "author_profile": "https://Stackoverflow.com/users/17034", "pm_score": 8, "selected": true, "text": " public void SortList() {\n MyList.Sort(delegate(MyClass a, MyClass b)\n {\n int xdiff = a.x.CompareTo(b.x);\n if (xdiff != 0) return xdiff;\n else return a.y.CompareTo(b.y);\n });\n }\n" }, { "answer_id": 289045, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 3, "selected": false, "text": "public class Widget : IComparable\n{\n int x;\n int y;\n public int X\n {\n get { return x; }\n set { x = value; }\n }\n\n public int Y\n {\n get { return y; }\n set { y = value; }\n }\n\n public Widget(int argx, int argy)\n {\n x = argx;\n y = argy;\n }\n\n public int CompareTo(object obj)\n {\n int result = 1;\n if (obj != null && obj is Widget)\n {\n Widget w = obj as Widget;\n result = this.X.CompareTo(w.X);\n }\n return result;\n }\n\n static public int Compare(Widget x, Widget y)\n {\n int result = 1;\n if (x != null && y != null) \n { \n result = x.CompareTo(y);\n }\n return result;\n }\n}\n public static void InsertionSort<T>(IList<T> list, Comparison<T> comparison)\n { \n int count = list.Count;\n for (int j = 1; j < count; j++)\n {\n T key = list[j];\n\n int i = j - 1;\n for (; i >= 0 && comparison(list[i], key) > 0; i--)\n {\n list[i + 1] = list[i];\n }\n list[i + 1] = key;\n }\n }\n static void Main(string[] args)\n {\n List<Widget> widgets = new List<Widget>();\n\n widgets.Add(new Widget(0, 1));\n widgets.Add(new Widget(1, 1));\n widgets.Add(new Widget(0, 2));\n widgets.Add(new Widget(1, 2));\n\n InsertionSort<Widget>(widgets, Widget.Compare);\n\n foreach (Widget w in widgets)\n {\n Console.WriteLine(w.X + \":\" + w.Y);\n }\n }\n 0:1\n0:2\n1:1\n1:2\nPress any key to continue . . .\n" }, { "answer_id": 4196220, "author": "mofoo", "author_id": 509646, "author_profile": "https://Stackoverflow.com/users/509646", "pm_score": 1, "selected": false, "text": " var data = (from o in database.Orders Where o.ClientId.Equals(clientId) select new {\n OrderId = o.id,\n OrderDate = o.orderDate,\n OrderBoolean = (SomeClass.SomeFunction(o.orderBoolean) ? 1 : 0)\n });\n\n data.Sort((o1, o2) => (o2.OrderBoolean.CompareTo(o1.OrderBoolean) != 0\n o2.OrderBoolean.CompareTo(o1.OrderBoolean) : o1.OrderDate.Value.CompareTo(o2.OrderDate.Value)));\n" } ]
2008/11/14
[ "https://Stackoverflow.com/questions/289010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1811110/" ]
289,029
<p>It seems like the classical way to handle transactions with JDBC is to set auto-commit to false. This creates a new transaction, and each call to commit marks the beginning the next transactions. On multithreading app, I understand that it is common practice to open a new connection for each thread.</p> <p>I am writing a RMI based multi-client server application, so that basically my server is seamlessly spawning one thread for each new connection. To handle transactions correctly should I go and create a new connection for each of those thread ? Isn't the cost of such an architecture prohibitive?</p>
[ { "answer_id": 7625713, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "1. Thread 1 opens statement \n3. Thread 2 opens statement\n4. Thread 1 does something Thread 2 does something\n5. ... ...\n6. Thread 1 closes statement ...\n 7. Thread 2 closes statement\n" } ]
2008/11/14
[ "https://Stackoverflow.com/questions/289029", "https://Stackoverflow.com", "https://Stackoverflow.com/users/446497/" ]
289,030
<p>I am having a Html hyperlink. I need to link this hyperlink to another page.When I place the mouse over the link. It should show the image. how to do this</p>
[ { "answer_id": 289042, "author": "José Leal", "author_id": 37190, "author_profile": "https://Stackoverflow.com/users/37190", "pm_score": 0, "selected": false, "text": " \n\nvar WindowVisible = null;\nfunction WindowShow() { \n this.bind = function(obj,url,height,width) {\n obj.url = url;\n obj.mheight = height;\n obj.mwidth = width;\n obj.onmouseover = function(e) {\n if (WindowVisible == null) {\n if (!e) e = window.event;\n var tmp = document.createElement(\"div\");\n tmp.style.position = 'absolute';\n tmp.style.top = parseInt(e.clientY + 15) + 'px';\n tmp.style.left = parseInt(e.clientX + 15) + 'px';\n var iframe = document.createElement('iframe');\n iframe.src = this.url;\n iframe.style.border = '0px';\n iframe.style.height = parseInt(this.mheight)+'px';\n iframe.style.width = parseInt(this.mwidth)+'px';\n iframe.style.position = 'absolute';\n iframe.style.top = '0px';\n iframe.style.left = '0px';\n tmp.appendChild(iframe);\n tmp.style.display = 'none';\n WindowVisible = tmp;\n document.body.appendChild(tmp);\n tmp.style.height = parseInt(this.mheight) + 'px';\n tmp.style.width = parseInt(this.mwidth) + 'px';\n tmp.style.display = 'block';\n }\n }\n obj.onmouseout = function() {\n if (WindowVisible != null) {\n document.body.removeChild(WindowVisible);\n WindowVisible = null;\n }\n }\n obj.onmousemove = function(e) {\n if (!e) e = window.event;\n WindowVisible.style.top = parseInt(e.clientY + 15) + 'px';\n WindowVisible.style.left = parseInt(e.clientX + 15) + 'px';\n }\n }\n}\n\n\n <script type=\"text/javascript\" src=\"myfile.js\"></script> \n\n<script type=\"text/javascript\">\n var asd = new WindowShow();\n asd.bind(document.getElementById('go1'),'IMAGE URL HERE!',400,480);\n</script>\n\n <html>\n<head>\n <title>test page</title>\n <style>\n div.block { width: 300px; height: 300px; background-color: red; }\n iframe { border: 0px; padding: 0px; margin: 0px; }\n </style>\n <script type=\"text/javascript\" src=\"window_show.js\"></script>\n</head>\n<body>\n <div id=\"go1\" style=\"background-color: red; width: 200px; height: 200px;\"></div>\n\n <script type=\"text/javascript\">\n var asd = new WindowShow();\n asd.bind(document.getElementById('go1'),'IMAGE URL HERE!',400,480);\n </script>\n</body>\n" }, { "answer_id": 289047, "author": "Andrew Van Slaars", "author_id": 8087, "author_profile": "https://Stackoverflow.com/users/8087", "pm_score": 3, "selected": true, "text": "a:link\n{\n background-image:none;\n}\n\na:hover\n{\n background-image:url('images/icon.png');\n background-repeat:no-repeat;\n background-position:right;\n padding-right:10px /*adjust based on icon size*/\n}\n" }, { "answer_id": 289051, "author": "Mischa Kroon", "author_id": 30600, "author_profile": "https://Stackoverflow.com/users/30600", "pm_score": 0, "selected": false, "text": "$(\"li\").hover(\n function () {\n $(this).append($(\"<img src=\"myimage.jpg\"/>\"));\n }, \n function () {\n $(this).find(\"img:last\").remove();\n }\n);\n" } ]
2008/11/14
[ "https://Stackoverflow.com/questions/289030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22162/" ]
289,076
<p>Example C API signature:</p> <p><code>void Func(unsigned char* bytes);</code></p> <p>In C, when I want to pass a pointer to an array, I can do:</p> <pre><code>unsigned char* bytes = new unsigned char[1000]; Func(bytes); // call </code></pre> <p>How do I translate the above API to P/Invoke such that I can pass a pointer to C# byte array?</p>
[ { "answer_id": 289088, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 3, "selected": false, "text": "unsafe \n{\n fixed(byte* pByte = byteArray)\n IntPtr intPtr = new IntPtr((void *) pByte);\n Func(intPtr);\n}\n IntPtr intPtr = Marshal.AllocHGlobal(Marshal.SizeOf(byteArray));\nMarshal.Copy(byteArray, 0, intPtr, Marshal.SizeOf(byteArray));\n\nFunc(intPtr);\n\nMarshal.FreeHGlobal(intPtr);\n" }, { "answer_id": 289105, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 2, "selected": false, "text": "[System.Runtime.InteropServices.DllImportAttribute(\"<Unknown>\", EntryPoint=\"Func\")]\npublic static extern void Func(System.IntPtr bytes) ;\n" }, { "answer_id": 289115, "author": "asponge", "author_id": 19449, "author_profile": "https://Stackoverflow.com/users/19449", "pm_score": 6, "selected": true, "text": "[DllImport EntryPoint=\"func\" CharSet=CharSet.Auto, SetLastError=true]\npublic extern static void Func(byte[]);\n\nbyte[] ar = new byte[1000];\nFunc(ar);\n [DllImport EntryPoint=\"func\" CharSet=CharSet.Auto, SetLastError=true]\npublic extern static void Func(IntPtr p);\n\nbyte[] ar = new byte[1000];\nIntPtr p = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(byte)) * ar.Length);\nMarshal.Copy(ar, 0, p, ar.Length);\nFunc(p);\nMarshal.FreeHGlobal(p);\n" } ]
2008/11/14
[ "https://Stackoverflow.com/questions/289076", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11238/" ]
289,077
<p>When do you call <code>Microsoft.Security.Application.AntiXss.HtmlEncode</code>? Do you do it when the user submits the information or do you do when you're displaying the information? </p> <p>How about for basic stuff like First Name, Last Name, City, State, Zip?</p>
[ { "answer_id": 289094, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 2, "selected": false, "text": "&amp;amp; usFirstName = getUserInput('firstName')\n\nssFirstName = cleanString(usFirstName);\n" } ]
2008/11/14
[ "https://Stackoverflow.com/questions/289077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10352/" ]
289,082
<p>Given the following class, what is your opinion on the best way to handle create/edit where Attributes.Count can be any number.</p> <pre><code>public class Product { public int Id {get;set;} public string Name {get;set;} public IList&lt;Attribute&gt; Attributes {get;set;} } public class Attribute { public string Name {get;set;} public string Value {get;set;} } </code></pre> <p>The user should be able to edit both the Product details (Name) and Attribute details (Name/Value) in the same view, including adding and deleting new attributes.</p> <p>Handling changes in the model is easy, what's the best way to handle the UI and ActionMethod side of things?</p>
[ { "answer_id": 289109, "author": "Kyle West", "author_id": 34133, "author_profile": "https://Stackoverflow.com/users/34133", "pm_score": 0, "selected": false, "text": "public ActionResult Whatever(stirng attr1Name, string attr2Name, string attr3Name ...\n public ActionResult Whatever(ILIst<Attribute> attributes, string productName ...\n" }, { "answer_id": 289112, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 3, "selected": true, "text": "[AcceptVerbs( HttpVerb.POST )]\npublic ActionResult Whatever( FormCollection form )\n{\n ....\n}\n" }, { "answer_id": 917984, "author": "bzlm", "author_id": 7724, "author_profile": "https://Stackoverflow.com/users/7724", "pm_score": 2, "selected": false, "text": "ActionResult Edit(\n int id, \n [ModelBinder(typeof(ProductModelBinder))] Product product\n) ...\n class ProductModelBinder : IModelBinder ...\n" }, { "answer_id": 3202885, "author": "Serge S.", "author_id": 301663, "author_profile": "https://Stackoverflow.com/users/301663", "pm_score": 4, "selected": false, "text": "Product public ActionResult Edit(Product model)\n <!-- Your Product inputs -->\n<!-- ... -->\n\n<!-- Attributes collection edit -->\n<% foreach (Attribute attr in Model.Attributes)\n {\n Html.RenderPartial(\"AttributeEditRow\", attr);\n } %>\n Html.BeginCollectionItem(string) <% using(Html.BeginCollectionItem(\"Attributes\")) { %>\n <!-- Your Attribute inputs -->\n<% } %>\n" } ]
2008/11/14
[ "https://Stackoverflow.com/questions/289082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34133/" ]
289,092
<p>How do I execute a command every time after ssh'ing from one machine to another?</p> <p>e.g</p> <pre><code>ssh mymachine stty erase ^H </code></pre> <p>I'd rather just have "stty erase ^H" execute every time after my ssh connection completes.</p> <p>This command can't simply go into my .zshrc file. i.e. for local sessions, I can't run the command (it screws up my keybindings). But I need it run for my remote sessions.</p>
[ { "answer_id": 289099, "author": "Adam Liss", "author_id": 29157, "author_profile": "https://Stackoverflow.com/users/29157", "pm_score": 0, "selected": false, "text": ".profile" }, { "answer_id": 289100, "author": "Ken Gentle", "author_id": 8709, "author_profile": "https://Stackoverflow.com/users/8709", "pm_score": 1, "selected": false, "text": ".bashrc .profile" }, { "answer_id": 289124, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 3, "selected": false, "text": "if [ -n \"$SSH_CONNECTION\" ]\nthen\n stty erase ^H\nend\n -n SSH_CONNECTION" }, { "answer_id": 289133, "author": "Elijah", "author_id": 33611, "author_profile": "https://Stackoverflow.com/users/33611", "pm_score": 0, "selected": false, "text": "trap 'stty erase ^H; exit 0' 0\n" }, { "answer_id": 289147, "author": "geocar", "author_id": 37507, "author_profile": "https://Stackoverflow.com/users/37507", "pm_score": 4, "selected": false, "text": "~/.ssh/rc" }, { "answer_id": 13806293, "author": "Alois Mahdal", "author_id": 835945, "author_profile": "https://Stackoverflow.com/users/835945", "pm_score": 0, "selected": false, "text": "man 8 sshd ## RUN BYOBU IF SSH'D ##\n## '''''''''''''''''' ##\n# (but only if this is a login shell)\n\nif shopt -q login_shell\nthen\n if [ -n \"$SSH_CONNECTION\" ]\n then\n byobu\n exit\n fi\nfi\n exit byobu" } ]
2008/11/14
[ "https://Stackoverflow.com/questions/289092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34594/" ]
289,098
<p>Given the following domain classes:</p> <pre><code>class Post { SortedSet tags static hasMany = [tags: Tag] } class Tag { static belongsTo = Post static hasMany = [posts: Post] } </code></pre> <p>From my understanding so far, using a <code>hasMany</code> will result in hibernate <code>Set</code> mapping. However, in order to maintain uniqueness/order, Hibernate needs to load the entire set from the database and compare their hashes.</p> <p>This could lead to a significant performance problem with adding and deleting posts/tags if their sets get large. What is the best way to work around this issue?</p>
[ { "answer_id": 290124, "author": "Miguel Ping", "author_id": 22992, "author_profile": "https://Stackoverflow.com/users/22992", "pm_score": 0, "selected": false, "text": "Set SortedSet List SortedSet Comparable Tag Tags Tags SortedSet HashSet" }, { "answer_id": 304141, "author": "Kevin", "author_id": 27163, "author_profile": "https://Stackoverflow.com/users/27163", "pm_score": 0, "selected": false, "text": "def book = new Book(title:\"New Grails Book\")\ndef author = Author.get(1)\nbook.author = author\nbook.save()\n def book = new Book(title:\"New Grails Book\")\ndef author = Author.get(1)\nauthor.addToBooks(book)\nauthor.save()\n" } ]
2008/11/14
[ "https://Stackoverflow.com/questions/289098", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27163/" ]
289,106
<p><a href="https://stackoverflow.com/questions/286584/can-i-specify-interfaces-when-i-declare-a-member#287669">Can I specify interfaces when I declare a member?</a></p> <p>After thinking about this question for a while, it occurred to me that a static-duck-typed language might actually work. Why can't predefined classes be bound to an interface at compile time? Example:</p> <pre><code>public interface IMyInterface { public void MyMethod(); } public class MyClass //Does not explicitly implement IMyInterface { public void MyMethod() //But contains a compatible method definition { Console.WriteLine("Hello, world!"); } } ... public void CallMyMethod(IMyInterface m) { m.MyMethod(); } ... MyClass obj = new MyClass(); CallMyMethod(obj); // Automatically recognize that MyClass "fits" // MyInterface, and force a type-cast. </code></pre> <p>Do you know of any languages that support such a feature? Would it be helpful in Java or C#? Is it fundamentally flawed in some way? I understand you could subclass MyClass and implement the interface or use the Adapter design pattern to accomplish the same thing, but those approaches just seem like unnecessary boilerplate code.</p>
[ { "answer_id": 289168, "author": "mipadi", "author_id": 28804, "author_profile": "https://Stackoverflow.com/users/28804", "pm_score": 4, "selected": true, "text": "MyClass MyMethod()" }, { "answer_id": 312934, "author": "Joh", "author_id": 221933, "author_profile": "https://Stackoverflow.com/users/221933", "pm_score": 3, "selected": false, "text": "let inline speak (a: ^a) =\n let x = (^a : (member speak: unit -> string) (a))\n printfn \"It said: %s\" x\n let y = (^a : (member talk: unit -> string) (a))\n printfn \"Then it said %s\" y\n\ntype duck() =\n member x.speak() = \"quack\"\n member x.talk() = \"quackity quack\"\ntype dog() =\n member x.speak() = \"woof\"\n member x.talk() = \"arrrr\"\n\nlet x = new duck()\nlet y = new dog()\nspeak x\nspeak y\n" }, { "answer_id": 312974, "author": "John Zwinck", "author_id": 4323, "author_profile": "https://Stackoverflow.com/users/4323", "pm_score": 4, "selected": false, "text": "class IMyInterface // Inheritance from this is optional\n{\npublic:\n virtual void MyMethod() = 0;\n}\n\nclass MyClass // Does not explicitly implement IMyInterface\n{\npublic:\n void MyMethod() // But contains a compatible method definition\n {\n std::cout << \"Hello, world!\" \"\\n\";\n }\n}\n\ntemplate<typename MyInterface>\nvoid CallMyMethod(MyInterface& m)\n{\n m.MyMethod(); // instantiation succeeds iff MyInterface has MyMethod\n}\n\nMyClass obj;\nCallMyMethod(obj); // Automatically generate code with MyClass as \n // MyInterface\n" }, { "answer_id": 1616849, "author": "james woodyatt", "author_id": 112191, "author_profile": "https://Stackoverflow.com/users/112191", "pm_score": 2, "selected": false, "text": "open Printf\n\nclass type iMyInterface = object\n method myMethod: unit\nend\n\nclass myClass = object\n method myMethod = printf \"Hello, world!\"\nend\n\nlet callMyMethod: #iMyInterface -> unit = fun m -> m#myMethod\n\nlet myClass = new myClass\n\ncallMyMethod myClass\n callMyMethod iMyInterface" }, { "answer_id": 1948885, "author": "cdiggins", "author_id": 184528, "author_profile": "https://Stackoverflow.com/users/184528", "pm_score": 0, "selected": false, "text": "as MyClass obj = new MyClass();\nCallMyMethod(obj);\n MyClass obj = new MyClass();\nCallMyMethod(obj as IMyInterface);\n MyClass IMyInterface as" }, { "answer_id": 23557902, "author": "leewz", "author_id": 2963903, "author_profile": "https://Stackoverflow.com/users/2963903", "pm_score": 2, "selected": false, "text": "auto plus(auto x, auto y){\n return x+y;\n}\n x+y foo(bar) foo" }, { "answer_id": 37556943, "author": "emlai", "author_id": 3425536, "author_profile": "https://Stackoverflow.com/users/3425536", "pm_score": 2, "selected": false, "text": "def add(x, y)\n x + y\nend\n\nadd(true, false)\n add Error in foo.cr:6: instantiating 'add(Bool, Bool)'\n\nadd(true, false)\n^~~\n\nin foo.cr:2: undefined method '+' for Bool\n\n x + y\n ^\n" } ]
2008/11/14
[ "https://Stackoverflow.com/questions/289106", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32998/" ]
289,108
<p>I prefer to use jQuery with my ASP.NET MVC apps than the Microsoft Ajax library. I have been adding a parameter called "mode" to my actions, which I set in my ajax calls. If it is provided, I return a JsonViewResult. If it isn't supplied, I assume it was a standard Http post and I return a ViewResult.</p> <p>I'd like to be able to use something similar to the IsMvcAjaxRequest in my controllers when using jQuery so I could eliminate the extra parameter in my Actions.</p> <p>Is there anything out there that would provide this capability within my controllers or some simple way to accomplish it? I don't want to go crazy writing code since adding a single parameter works, it just isn't ideal.</p>
[ { "answer_id": 289128, "author": "Eric Schoonover", "author_id": 3957, "author_profile": "https://Stackoverflow.com/users/3957", "pm_score": 2, "selected": false, "text": "IsMvcAjaxRequest Request[\"__MVCASYNCPOST\"] == \"true\" __MVCASYNCPOST IsMvcAjaxRequest IsMvcAjaxRequest IsjQueryAjaxRequest Request[\"__JQUERYASYNCPOST\"] == \"true\" public static class HttpRequestBaseExtensions\n{\n public static bool IsjQueryAjaxRequest(this HttpRequestBase request)\n {\n if (request == null)\n throw new ArgumentNullException(\"request\");\n\n return request[\"__JQUERYASYNCPOST\"] == \"true\";\n }\n}\n if (Request.IsjQueryAjaxRequest())\n //some code here\n $('form input[type=submit]').click(function(evt) {\n //intercept submit button and use AJAX instead\n evt.preventDefault();\n\n $.ajax(\n {\n type: \"POST\",\n url: \"<%= Url.Action(\"Create\") %>\",\n dataType: \"json\",\n data: { \"__JQUERYASYNCPOST\": \"true\" },\n success: function(data) {alert(':)');},\n error: function(res, textStatus, errorThrown) {alert(':(');}\n }\n );\n});\n" }, { "answer_id": 321744, "author": "Andrew Van Slaars", "author_id": 8087, "author_profile": "https://Stackoverflow.com/users/8087", "pm_score": 0, "selected": false, "text": "post: function(url, data, callback, type) {\n var postIdentifier = {};\n if (jQuery.isFunction(data)) {\n callback = data;\n data = {};\n }\n else {\n postIdentifier = { __JQUERYASYNCPOST: true };\n jQuery.extend(data, postIdentifier);\n }\n\n return jQuery.ajax({\n type: \"POST\",\n url: url,\n data: data,\n success: callback,\n dataType: type\n });\n }\n" }, { "answer_id": 321826, "author": "Franck", "author_id": 38072, "author_profile": "https://Stackoverflow.com/users/38072", "pm_score": 2, "selected": false, "text": "if (Request.Headers[\"X-Requested-With\"] == \"XMLHttpRequest\")\n return Json(...);\nelse\n return View();\n" } ]
2008/11/14
[ "https://Stackoverflow.com/questions/289108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8087/" ]
289,122
<p>I have a chart with a series that denotes a large set (1000's) of discrete measurements. Some of these are bad measurements and I want to colour the line for the series based on another set of data that describes how accurate the measurements are. Bad measurements should be red and good measurements green and the in between on some kind of gradient from red to yellow to green. </p> <p>This should be able to be programmed with VBA however I have no idea what to do. Can anyone give me some hints?</p>
[ { "answer_id": 289989, "author": "Fionnuala", "author_id": 2548, "author_profile": "https://Stackoverflow.com/users/2548", "pm_score": 3, "selected": true, "text": "Dim cht As Chart\nDim sc As Series\nDim blnBad As Boolean\nDim j\n\nj = 85 'RGB orange '\nblnBad = False\n\n'This is a chart called Chart 1, it would be possible '\n'to use the charts collection '\nSet cht = ActiveSheet.ChartObjects(\"Chart 1\").Chart\n'A chart is composed of series of data ... '\nFor Each sc In cht.SeriesCollection\n ' ... that you can iterate through to pick up '\n ' the individual data values, or a data range. '\n ' Values in this case. '\n For i = LBound(sc.Values) To UBound(sc.Values)\n ' That can be checked against another set of '\n ' values in the range Bad. '\n With ActiveSheet.Range(\"Bad\")\n ' So, look for the value ... '\n Set c = .Find(sc.Values(i), lookat:=xlWhole, LookIn:=xlValues)\n ' and if it is found ... '\n If Not c Is Nothing Then\n ' ... then set the Bad flag '\n blnBad = True\n End If\n End With\n Next\n ' So, this range contains a Bad value '\n ' and we will colour it red ... '\n If blnBad Then\n sc.Border.Color = RGB(255, 0, 0)\n ' ... not forgetting the markers '\n sc.MarkerForegroundColor = RGB(255, 0, 0)\n Else\n ' Otherwise, use an increasingly yellow colour '\n sc.Border.Color = RGB(255, j, 0)\n sc.MarkerForegroundColor = RGB(255, j, 0)\n\n j = j + 30 ' getting more yellow\n ' Debug.Print j ' uncomment to see j in the immediate window '\n End If\n blnBad = False\nNext\nEnd Sub\n" } ]
2008/11/14
[ "https://Stackoverflow.com/questions/289122", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31045/" ]
289,138
<p>I was really looking at the differences between pass by value and how Java allocates objects and what java does to put objects on the stack.</p> <p>Is there anyway to access objects allocated on the heap? What mechanisms does java enforce to guarantee that the right method can access the right data off the heap?</p> <p>It seems like if you were crafty and maybe even manipulate the java bytecode during runtime, that you might be able to manipulate data off the heap when you aren't supposed to?</p>
[ { "answer_id": 289209, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 3, "selected": false, "text": "new" } ]
2008/11/14
[ "https://Stackoverflow.com/questions/289138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10522/" ]
289,159
<p>I have a form with a <code>&lt;textarea&gt;</code> and I want to capture any line breaks in that textarea on the server-side, and replace them with a <code>&lt;br/&gt;</code>.</p> <p>Is that possible?</p> <p>I tried setting <code>white-space:pre</code> on the <code>textarea</code>'s CSS, but it's still not enough.</p>
[ { "answer_id": 289165, "author": "Marc", "author_id": 37210, "author_profile": "https://Stackoverflow.com/users/37210", "pm_score": 6, "selected": true, "text": "nl2br()" }, { "answer_id": 290564, "author": "Law", "author_id": 6272, "author_profile": "https://Stackoverflow.com/users/6272", "pm_score": 3, "selected": false, "text": "nl2br() str_replace preg_replace $val = str_replace( array(\"\\n\",\"\\r\",\"\\r\\n\"), '<br />', $val );\n $val = preg_replace( \"#\\n|\\r|\\r\\n#\", '<br />', $val );\n" }, { "answer_id": 583571, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "str_replace preg_replace \"\\r\\n\" \\r\\n <br/> \\r \\n $val = str_replace( array(\"\\r\\n\", \"\\n\",\"\\r\"), '<br />', $val );\n $val = preg_replace( \"#\\r\\n|\\n|\\r#\", '<br />', $val );\n" }, { "answer_id": 21612797, "author": "cssyphus", "author_id": 1447509, "author_profile": "https://Stackoverflow.com/users/1447509", "pm_score": 0, "selected": false, "text": "nl2br() $newList = ereg_replace( \"\\n\",'|', $_POST['theTextareaContents']);\n $newList = ereg_replace( \"\\n\",'<br/>', $_POST['theTextareaContents']);\n $newList = ereg_replace( \"\\n\",'|', $_POST['theTextareaContents']);\n $list = str_replace('|', '&#13;&#10;', $r['db_field_name']);\n" } ]
2008/11/14
[ "https://Stackoverflow.com/questions/289159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24744/" ]
289,171
<p>What is the point of an action returning ActionResult?</p>
[ { "answer_id": 289192, "author": "Michael Stum", "author_id": 91, "author_profile": "https://Stackoverflow.com/users/91", "pm_score": 4, "selected": false, "text": "return Redirect(newUrl);\n" } ]
2008/11/14
[ "https://Stackoverflow.com/questions/289171", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
289,176
<p>I keep seeing the phrase "duck typing" bandied about, and even ran across a code example or two. I am way too <strike>lazy</strike> busy to do my own research, can someone tell me, briefly:</p> <ul> <li>the difference between a 'duck type' and an old-skool 'variant type', and </li> <li>provide an example of where I might prefer duck typing over variant typing, and</li> <li>provide an example of something that i would <em>have</em> to use duck typing to accomplish?</li> </ul> <p><img src="https://regmedia.co.uk/2007/05/03/cartoon_duck.jpg" alt="duck typing illustration courtesy of The Register"></p> <p>I don't mean to seem fowl by doubting the power of this 'new' construct, and I'm not ducking the issue by refusing to do the research, but I am quacking up at all the flocking hype i've been seeing about it lately. It looks like <em>no</em> typing (aka dynamic typing) to me, so I'm not seeing the advantages right away.</p> <p>ADDENDUM: Thanks for the examples so far. It seems to me that using something like 'O->can(Blah)' is equivalent to doing a reflection lookup (which is probably not cheap), and/or is about the same as saying (O is IBlah) which the compiler might be able to check for you, but the latter has the advantage of distinguishing my IBlah interface from your IBlah interface while the other two do not. Granted, having a lot of tiny interfaces floating around for every method would get messy, but then again so can checking for a lot of individual methods...</p> <p>...so again i'm just not getting it. Is it a fantastic time-saver, or the same old thing in a brand new sack? Where is the example that <em>requires</em> duck typing?</p>
[ { "answer_id": 289191, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 1, "selected": false, "text": "sub dance { \n my $creature = shift;\n if( $creature->can(\"walk\") ){ \n $creature->walk(\"left\",1);\n $creature->walk(\"right\",1); \n $creature->walk(\"forward\",1);\n $creature->walk(\"back\",1);\n }\n if( $creature->can(\"fly\") ){ \n $creature->fly(\"up\"); \n $creature->fly(\"right\",1); \n $creature->fly(\"forward\",1); \n $creature->fly(\"left\", 1 ); \n $creature->fly(\"back\", 1 ); \n $creature->fly(\"down\");\n } else if ( $creature->can(\"walk\") ) { \n $creature->walk(\"left\",1);\n $creature->walk(\"right\",1); \n $creature->walk(\"forward\",1);\n $creature->walk(\"back\",1);\n } else if ( $creature->can(\"splash\") ) { \n $creature->splash( \"up\" ) for ( 0 .. 4 ); \n }\n if( $creature->can(\"quack\") ) { \n $creature->quack();\n }\n }\n\n my @x = (); \n push @x, new Rhinoceros ; \n push @x, new Flamingo; \n push @x, new Hyena; \n push @x, new Dolphin; \n push @x, new Duck;\n\n for my $creature (@x){\n\n new Thread(sub{ \n dance( $creature ); \n }); \n }\n" }, { "answer_id": 289251, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 2, "selected": false, "text": "public interface ICreature { }\npublic interface IFly { fly();}\npublic interface IWalk { walk(); }\npublic interface IQuack { quack(); }\n// ETC\n\n// Animal Class\npublic class Duck : ICreature, IWalk, IFly, IQuack\n{\n fly() {};\n walk() {};\n quack() {};\n}\n\npublic class Rhino: ICreature, IWalk\n{\n walk();\n}\n\n// In the method\nList<ICreature> creatures = new List<ICreature>();\ncreatures.Add(new Duck());\ncreatures.Add(new Rhino()); \n\nforeach (ICreature creature in creatures)\n{\n if (creature is IFly) \n (creature as IFly).fly(); \n if (creature is IWalk) \n (creature as IWalk).walk(); \n}\n// Etc\n" }, { "answer_id": 289410, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 5, "selected": true, "text": "interface IDuck {\n void Quack();\n}\n class Daffy {\n void Quack() {\n Console.WriteLine(\"Thatsssss dispicable!!!!\");\n }\n}\n IDuck d = new Daffy();\nd.Quack();\n" }, { "answer_id": 289525, "author": "Scott Wisniewski", "author_id": 1737192, "author_profile": "https://Stackoverflow.com/users/1737192", "pm_score": 5, "selected": false, "text": "struct foo\n{\n int x;\n iny y;\n int z;\n}\n\nchar * x = new char[100];\nfoo * pFoo = (foo *)x;\nfoo aRealFoo;\n*pFoo = aRealFoo;\n function Foo(x as object) as object\n return x.Quack()\nend function\n" } ]
2008/11/14
[ "https://Stackoverflow.com/questions/289176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9345/" ]
289,187
<p>I have an Excel macro that deletes a sheet, copies another sheet and renames it to the same name of the deleted sheet. This works fine when run from Excel, but when I run it by calling the macro from Python I get the following error message:</p> <blockquote> <p>Run-time error '1004' - Cannot rename a sheet to the same name as another sheet, a referenced object library or a workbook referenced by VisualBasic.</p> </blockquote> <p>The macro has code like the following:</p> <pre><code>Sheets("CC").Delete ActiveWindow.View = xlPageBreakPreview Sheets("FY").Copy After:=Sheets(Sheets.Count) Sheets(Sheets.Count).Name = "CC" </code></pre> <p>and the debugger highlights the error on the last line where the sheet is renamed. I've also tried putting these calls directly in python but get the same error message.</p> <p>Any suggestions are much appreciated!</p> <p>Thanks.</p>
[ { "answer_id": 289313, "author": "shahkalpesh", "author_id": 23574, "author_profile": "https://Stackoverflow.com/users/23574", "pm_score": 2, "selected": false, "text": "\nSheets(\"CC\").Delete\n Application.DisplayAlerts = False Sheets(\"CC\").Delete Application.DisplayAlerts = True " }, { "answer_id": 289482, "author": "ConcernedOfTunbridgeWells", "author_id": 15401, "author_profile": "https://Stackoverflow.com/users/15401", "pm_score": 1, "selected": false, "text": "import win32com.client\nxl = win32com.client.Dispatch ('Excel.Application')\nxl.Visible = True\nwb = xl.Workbooks.Add()\nwb.Worksheets[0].Delete()\nwb.Worksheets.Add()\nwb.Worksheets[0].Name = 'Sheet1'\n" } ]
2008/11/14
[ "https://Stackoverflow.com/questions/289187", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
289,194
<p>We have an home-brewed XMPP server and I was asked what is our server's MSL (Maximum Segment Lifetime).<br> What does it mean and how can I obtain it? Is it something in the Linux <code>/proc</code> TCP settings?</p>
[ { "answer_id": 35000966, "author": "John Hascall", "author_id": 2040863, "author_profile": "https://Stackoverflow.com/users/2040863", "pm_score": 4, "selected": false, "text": "/proc/sys/net/ipv4/tcp_fin_timeout cat /proc/sys/net/ipv4/tcp_fin_timeout\n echo 5 > /proc/sys/net/ipv4/tcp_fin_timeout\n" }, { "answer_id": 53643838, "author": "Greg Bray", "author_id": 17373, "author_profile": "https://Stackoverflow.com/users/17373", "pm_score": 3, "selected": false, "text": "cat /proc/sys/net/ipv4/tcp_fin_timeout\n3\n\n# See countdown timer for all TIME_WAIT sockets in 192.168.0.0-255\nss --numeric -o state time-wait dst 192.168.0.0/24\n\nNetidRecv-Q Send-Q Local Address:Port Peer Address:Port \ntcp 0 0 192.168.100.1:57516 192.168.0.10:80 timer:(timewait,55sec,0) \ntcp 0 0 192.168.100.1:57356 192.168.0.10:80 timer:(timewait,25sec,0) \ntcp 0 0 192.168.100.1:57334 192.168.0.10:80 timer:(timewait,22sec,0) \ntcp 0 0 192.168.100.1:57282 192.168.0.10:80 timer:(timewait,12sec,0) \ntcp 0 0 192.168.100.1:57418 192.168.0.10:80 timer:(timewait,38sec,0) \ntcp 0 0 192.168.100.1:57458 192.168.0.10:80 timer:(timewait,46sec,0) \ntcp 0 0 192.168.100.1:57252 192.168.0.10:80 timer:(timewait,7.436ms,0) \ntcp 0 0 192.168.100.1:57244 192.168.0.10:80 timer:(timewait,6.536ms,0)\n" } ]
2008/11/14
[ "https://Stackoverflow.com/questions/289194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
289,208
<p>Since upgrading to 2008 I and many people here have noticed that randomly VS will no longer step in to code or jump over breakpoints. Its got to the stage where debugging is becoming a real chore. We are running SP1 but noticed problem on 2008 basic too.</p> <p>In ref to Robert's question: We host WCF and Remoting services inside windows services. Essentially the calls from the clients (generally windows exe) will end up in a thread on the service itself and in our code (as opposed to remoting or WCF infrastructure). Once in our code the break points have this behaviour.</p> <p>Much of the debugging we do here is in service code so ATTACH to process to invaluable and sometimes is impossible to get to the state needed except by attaching to processes after they have started. It happens to developers both with extensions such as resharper and to those who run a vanilla VS.</p> <p>Looking on google doesn't give much help.</p> <h2>Anyone else experience this?</h2> <p>regards, Preet</p> <hr> <p>Spudlo's answer has worked out greatly for us. Thank you. Please download the fix from <a href="http://blogs.msdn.com/jacdavis/archive/2008/11/14/debugger-qfe-for-vs-2008-sp1-released.aspx" rel="nofollow noreferrer">MSDN</a></p>
[ { "answer_id": 289222, "author": "Robert Wagner", "author_id": 10784, "author_profile": "https://Stackoverflow.com/users/10784", "pm_score": 2, "selected": false, "text": "public static void Main(string[] args)\n{\n if (Environment.UserInteractive)\n {\n Console.WriteLine(\"Starting service...\");\n Service1 svc = new Service1();\n svc.OnStart(args);\n Console.WriteLine(\"Started\");\n Console.WriteLine(\"\");\n Console.WriteLine(\"Press any key to stop\");\n Console.Read();\n Console.WriteLine(\"Stopping...\");\n svc.OnStop();\n Console.WriteLine(\"Stopped, Press any key to exit\");\n Console.Read();\n }\n else\n {\n ServiceBase.Run(new Service1());\n }\n}\n" } ]
2008/11/14
[ "https://Stackoverflow.com/questions/289208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30225/" ]
289,220
<p>Below is my (simplified) schema (in MySQL ver. 5.0.51b) and my strategy for updating it. There has got to be a better way. Inserting a new item requires 4 trips to the database and editing/updating an item takes up to <strong>7</strong>!</p> <p><strong>items</strong>: itemId, itemName <br /><strong>categories</strong>: catId, catName <br /><strong>map</strong>: mapId*, itemId, catId <br />* mapId (varchar) is concat of itemId + | + catId</p> <p>1) If inserting: insert item. Get itemId via MySQL API. <br />Else updating: just update the item table. We already have the itemId.</p> <p>2) Conditionally batch insert into <code>categories</code>.</p> <pre><code>INSERT IGNORE INTO categories (catName) VALUES ('each'), ('category'), ('name'); </code></pre> <p>3) Select IDs from <code>categories</code>.</p> <pre><code>SELECT catId FROM categories WHERE catName = 'each' OR catName = 'category' OR catName = 'name'; </code></pre> <p>4) Conditionally batch insert into <code>map</code>.</p> <pre><code>INSERT IGNORE INTO map (mapId, itemId, catId) VALUES ('1|1', 1, 1), ('1|2', 1, 2), ('1|3', 1, 3); </code></pre> <p>If inserting: we're done. Else updating: continue.</p> <p>5) It's possible that we no longer associate a category with this item that we did prior to the update. Delete old categories for this itemId.</p> <pre><code>DELETE FROM MAP WHERE itemId = 2 AND catID &lt;&gt; 2 AND catID &lt;&gt; 3 AND catID &lt;&gt; 5; </code></pre> <p>6) If we have disassociated ourselves from a category, it's possible that we left it orphaned. We do not want categories with no items. Therefore, if <code>affected rows &gt; 0</code>, kill orphaned categories. I haven't found a way to combine these in MySQL, so this is #6 &amp; #7.</p> <pre><code>SELECT categories.catId FROM categories LEFT JOIN map USING (catId) GROUP BY categories.catId HAVING COUNT(map.catId) &lt; 1; </code></pre> <p>7) Delete IDs found in step 6.</p> <pre><code>DELETE FROM categories WHERE catId = 9 AND catId = 10; </code></pre> <p>Please tell me there's a better way that I'm not seeing.</p>
[ { "answer_id": 289233, "author": "too much php", "author_id": 28835, "author_profile": "https://Stackoverflow.com/users/28835", "pm_score": 2, "selected": true, "text": "DELETE categories.*\nFROM categories\nLEFT JOIN map USING (catId)\nWHERE map.catID IS NULL;\n INSERT IGNORE INTO map (mapId, itemId, catId)\n SELECT CONCAT('1|', c.catId), 1, c.catID\n FROM categories AS c\n WHERE c.catName IN('each','category','name');\n" }, { "answer_id": 289247, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 2, "selected": false, "text": "INSERT...ON DUPLICATE KEY UPDATE DELETE FROM map WHERE itemId=2 map.mapID (itemID, catID) DELETE categories.* FROM categories LEFT JOIN map USING (catId) \nWHERE map.catID IS NULL\n" } ]
2008/11/14
[ "https://Stackoverflow.com/questions/289220", "https://Stackoverflow.com", "https://Stackoverflow.com/users/356/" ]
289,225
<p>Is there any HTML5 support in IE8? Is it on the IE8 roadmap?</p>
[ { "answer_id": 289469, "author": "hsivonen", "author_id": 18721, "author_profile": "https://Stackoverflow.com/users/18721", "pm_score": 7, "selected": true, "text": "<canvas> <video>" }, { "answer_id": 1759706, "author": "John", "author_id": 52207, "author_profile": "https://Stackoverflow.com/users/52207", "pm_score": 5, "selected": false, "text": "<article>" }, { "answer_id": 3746162, "author": "goker", "author_id": 440140, "author_profile": "https://Stackoverflow.com/users/440140", "pm_score": 6, "selected": false, "text": "<script type=\"text/javascript\">\n document.createElement('header');\n document.createElement('nav');\n document.createElement('menu');\n document.createElement('section');\n document.createElement('article');\n document.createElement('aside');\n document.createElement('footer');\n</script>\n" }, { "answer_id": 5239843, "author": "Justin", "author_id": 332026, "author_profile": "https://Stackoverflow.com/users/332026", "pm_score": 4, "selected": false, "text": "<!DOCTYPE html>\n" }, { "answer_id": 22461874, "author": "Alfonse", "author_id": 1289350, "author_profile": "https://Stackoverflow.com/users/1289350", "pm_score": 2, "selected": false, "text": "<!--[if lt IE 9 ]> \n <script type=\"text/javascript\">\n var html5Elem = ['header', 'nav', 'menu', 'section', 'article', 'aside', 'footer'];\n for (var i = 0; i < html5Elem.length; i++){\n document.createElement(html5Elem[i]);\n }\n </script>\n<![endif]-->\n" } ]
2008/11/14
[ "https://Stackoverflow.com/questions/289225", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36590/" ]
289,241
<p>Forgive me for a potentially silly question here, but in other programming languages (scripting ones like PHP or Perl) it is often easy to dump everything contained within a variable.</p> <p>For instance, in PHP there are the <code>var_dump()</code> or <code>print_r()</code> functions. Perl has the <code>Data::Dumper</code> CPAN class, etc etc.</p> <p>Is there something like this for Objective-C? It would be very convenient in a few cases to be able to dump everything like that, instead of using gdb to inspect each variable.</p>
[ { "answer_id": 289250, "author": "Jason Coco", "author_id": 34218, "author_profile": "https://Stackoverflow.com/users/34218", "pm_score": 3, "selected": false, "text": "NSData* myData = //... assume this exists\nNSLog(@\"Contents of myData: %@\", myData);\n gdb) po myData\n" }, { "answer_id": 289281, "author": "Barry Wark", "author_id": 2140, "author_profile": "https://Stackoverflow.com/users/2140", "pm_score": 7, "selected": true, "text": "NSLog(@\"%@\", myObj);\n NSString *stringRep = [NSString stringWithFormat:@\"%@\",myObj];\n NSString *stringRep = [myObj description];\n [myObj description] NSObject po myObj [myObj debugDescription] description NSArray NSDictionary NSData description [NSObject description] description debugDescription description debugDescription myDebugDescription po [myObj myDebugDescription]" }, { "answer_id": 289296, "author": "Ben Gottlieb", "author_id": 6694, "author_profile": "https://Stackoverflow.com/users/6694", "pm_score": 4, "selected": false, "text": "po dictionary\n p (char *) [data bytes]\n" }, { "answer_id": 9693606, "author": "TCB13", "author_id": 560745, "author_profile": "https://Stackoverflow.com/users/560745", "pm_score": 2, "selected": false, "text": "NSEnumerator *arrenum = [myarray objectEnumerator];\nid cobj; \nwhile ( cobj = [arrenum nextObject] ) {\n NSLog(@\"%@\", cobj);\n}\n myarray" } ]
2008/11/14
[ "https://Stackoverflow.com/questions/289241", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35478/" ]
289,255
<p>Title says it mostly. I want to add a simple extension method to the base Dictionary class in C#. At first I was going to name it Pop(TKey key), kind of like the Stack method, but it accepts a key to use for lookup.</p> <p>Then I was going to do Take(TKey key), but it coincides with the LINQ method of the same name...and although C# 3.0 lets you do it, I don't like it.</p> <p>So, what do you think, just stick with Pop or is there a better term for "find and remove an element"?</p> <p>(I feel kind of embarrassed to ask this question, it seems like such a trivial matter... but I like to use standards and I don't have wide experience with many languages/environments.)</p> <p>EDIT: Sorry, should have explained more.... In this instance I can't use the term Remove since it's already defined by the class that I'm extending with a new method.</p> <p>EDIT 2: Okay, here's what I have so far, inspired by the wisdom of the crowd as it were:</p> <pre><code>public static TValue Extract&lt;TKey, TValue&gt; ( this Dictionary&lt;TKey, TValue&gt; dict, TKey key ) { TValue value = dict[key]; dict.Remove(key); return value; } public static bool TryExtract&lt;TKey, TValue&gt; ( this Dictionary&lt;TKey, TValue&gt; dict, TKey key, out TValue value ) { if( !dict.TryGetValue(key, out value) ) { return false; } dict.Remove(key); return true; } </code></pre>
[ { "answer_id": 289260, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 1, "selected": false, "text": "object valueRemoved = someDictionary.RemoveElement(key)\n if (!dict.ContainsKey(key))\n{\n return null;\n}\nobject val = dict[key];\ndict.Remove(key);\nreturn val;\n" } ]
2008/11/14
[ "https://Stackoverflow.com/questions/289255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16387/" ]
289,271
<p>How can I decode a base64 encoded message in PHP? I know how to use PHP_base64_decode function, but I wanna know how to write little endian part, like the code below, it is base64 code with little endian: (how to write little endian part in php)</p> <p><strong>Original Base64 Content ( as posted by original poster )</strong> :</p> <p><a href="https://stackoverflow.com/revisions/viewmarkup/374860">https://stackoverflow.com/revisions/viewmarkup/374860</a></p>
[ { "answer_id": 12025216, "author": "John Dvorak", "author_id": 499214, "author_profile": "https://Stackoverflow.com/users/499214", "pm_score": 2, "selected": false, "text": "mb_convert_encoding($input, 'UTF-8', 'UTF-16LE')" } ]
2008/11/14
[ "https://Stackoverflow.com/questions/289271", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
289,274
<p>I have included <code>&lt;zlib.h&gt;</code> in my iphone application and the source code I was mocking up the sample code of Molecules provided by Brad Larson, however, when I build the project, it returns the error as below. Can anyone point out for me whether this is a library linking problem or am I missing something else?</p> <pre><code>"_deflate", referenced from: -[NSData(Gzip) gzipDeflate] in NSData+Gzip.o "_inflateEnd", referenced from: -[NSData(Gzip) initWithGzippedData:] in NSData+Gzip.o "inflateInit2", referenced from: -[NSData(Gzip) initWithGzippedData:] in NSData+Gzip.o "_inflate", referenced from: -[NSData(Gzip) initWithGzippedData:] in NSData+Gzip.o "_deflateEnd", referenced from: -[NSData(Gzip) gzipDeflate] in NSData+Gzip.o "deflateInit2", referenced from: -[NSData(Gzip) gzipDeflate] in NSData+Gzip.o ld: symbol(s) not found collect2: ld returned 1 exit status </code></pre>
[ { "answer_id": 289294, "author": "Ben Gottlieb", "author_id": 6694, "author_profile": "https://Stackoverflow.com/users/6694", "pm_score": 7, "selected": true, "text": "Build Settings Other Linker Flags -lz Clean Product" } ]
2008/11/14
[ "https://Stackoverflow.com/questions/289274", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35405/" ]
289,276
<p>Here's my code (note that this was given by a friend):</p> <pre><code>Private Sub Browse_Click() Dim textfile As String textfile = Space(255) GetFileNameFromBrowseW Me.hWnd, StrPtr(sSave), 255, StrPtr("c:\"), StrPtr("txt"), StrPtr("Apps (*.txt)" + Chr$(0) + "*.txt" + Chr$(0) + "All files (*.*)" + Chr$(0) + "*.*" + Chr$(0)), StrPtr("Select File") Text1 = Left$(textfile, lstrlen(textfile)) End Sub </code></pre> <p>Basically later on I edit the text file selected so later I call it just by using textfile in my function. However I get a path not found so I feel like I'm doing something wrong. Thanks in advance.</p> <p>Edit: All I want to do is select a text file, then later be able to call it and use it.</p>
[ { "answer_id": 289514, "author": "onedaywhen", "author_id": 15354, "author_profile": "https://Stackoverflow.com/users/15354", "pm_score": 0, "selected": false, "text": "sSave textfile Text1 Text1.Text .Text" }, { "answer_id": 289630, "author": "Ant", "author_id": 11529, "author_profile": "https://Stackoverflow.com/users/11529", "pm_score": 3, "selected": false, "text": "CommonDialog.Filter = \"Apps (*.txt)|*.txt|All files (*.*)|*.*\"\nCommonDialog.DefaultExt = \"txt\"\nCommonDialog.DialogTitle = \"Select File\"\nCommonDialog.ShowOpen\n\n'The FileName property gives you the variable you need to use\nMsgBox CommonDialog.FileName\n" }, { "answer_id": 290934, "author": "RS Conley", "author_id": 7890, "author_profile": "https://Stackoverflow.com/users/7890", "pm_score": 1, "selected": true, "text": "Private Const VER_PLATFORM_WIN32_NT = 2\nPrivate Type OSVERSIONINFO\n dwOSVersionInfoSize As Long\n dwMajorVersion As Long\n dwMinorVersion As Long\n dwBuildNumber As Long\n dwPlatformId As Long\n szCSDVersion As String * 128\nEnd Type\nPrivate Declare Function GetVersionEx Lib \"kernel32\" Alias \"GetVersionExA\" (ByRef lpVersionInformation As OSVERSIONINFO) As Long\nPrivate Declare Function GetFileNameFromBrowseW Lib \"shell32\" Alias \"#63\" (ByVal hwndOwner As Long, ByVal lpstrFile As Long, ByVal nMaxFile As Long, ByVal lpstrInitialDir As Long, ByVal lpstrDefExt As Long, ByVal lpstrFilter As Long, ByVal lpstrTitle As Long) As Long\nPrivate Declare Function GetFileNameFromBrowseA Lib \"shell32\" Alias \"#63\" (ByVal hwndOwner As Long, ByVal lpstrFile As String, ByVal nMaxFile As Long, ByVal lpstrInitialDir As String, ByVal lpstrDefExt As String, ByVal lpstrFilter As String, ByVal lpstrTitle As String) As Long\nPrivate Sub Form_Load()\n 'KPD-Team 2001\n 'URL: http://www.allapi.net/\n 'E-Mail: KPDTeam@Allapi.net\n Dim sSave As String\n sSave = Space(255)\n 'If we're on WinNT, call the unicode version of the function\n If IsWinNT Then\n GetFileNameFromBrowseW Me.hWnd, StrPtr(sSave), 255, StrPtr(\"c:\\\"), StrPtr(\"txt\"), StrPtr(\"Text files (*.txt)\" + Chr$(0) + \"*.txt\" + Chr$(0) + \"All files (*.*)\" + Chr$(0) + \"*.*\" + Chr$(0)), StrPtr(\"The Title\")\n 'If we're not on WinNT, call the ANSI version of the function\n Else\n GetFileNameFromBrowseA Me.hWnd, sSave, 255, \"c:\\\", \"txt\", \"Text files (*.txt)\" + Chr$(0) + \"*.txt\" + Chr$(0) + \"All files (*.*)\" + Chr$(0) + \"*.*\" + Chr$(0), \"The Title\"\n End If\n 'Show the result\n MsgBox sSave\nEnd Sub\nPublic Function IsWinNT() As Boolean\n Dim myOS As OSVERSIONINFO\n myOS.dwOSVersionInfoSize = Len(myOS)\n GetVersionEx myOS\n IsWinNT = (myOS.dwPlatformId = VER_PLATFORM_WIN32_NT)\nEnd Function\n Text1 = Left$(textfile, lstrlen(textfile))\n MsgBox \"(\" & Text1 & \")-(\" & textfile & \")\"\n" } ]
2008/11/14
[ "https://Stackoverflow.com/questions/289276", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
289,278
<p>If I have a string "12 23 34 56"</p> <p>What's the easiest way to change it to "\x12 \x23 \x34 \x56"?</p>
[ { "answer_id": 289291, "author": "Jesse Beder", "author_id": 112, "author_profile": "https://Stackoverflow.com/users/112", "pm_score": 2, "selected": false, "text": "string s = \"12 23 34 45\";\nstringstream str(s), out;\nint val;\nwhile(str >> val)\n out << \"\\\\x\" << val << \" \"; // note: this puts an extra space at the very end also\n // you could hack that away if you want\n\n// here's your new string\nstring modified = out.str();\n" }, { "answer_id": 289293, "author": "Klathzazt", "author_id": 35223, "author_profile": "https://Stackoverflow.com/users/35223", "pm_score": 0, "selected": false, "text": "foreach( character in source string)\n{\n if \n character is ' ', write ' \\x' to destination string\n else \n write character to destination string.\n}\n" }, { "answer_id": 289318, "author": "Evan Teran", "author_id": 13430, "author_profile": "https://Stackoverflow.com/users/13430", "pm_score": 2, "selected": false, "text": "std::string s;\nint val;\nstd::stringstream ss(\"12 34 56 78\");\nwhile(ss >> std::hex >> val) {\n s += static_cast<char>(val);\n}\n for(int i = 0; i < s.length(); ++i) {\n printf(\"%02x\\n\", s[i] & 0xff);\n}\n 12\n34\n56\n78\n" } ]
2008/11/14
[ "https://Stackoverflow.com/questions/289278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
289,307
<p>Say I have two lists:</p> <pre><code>var list1 = new int[] {1, 2, 3}; var list2 = new string[] {"a", "b", "c"}; </code></pre> <p>Is it possible to write a LINQ statement that will generate the following list:</p> <pre><code>var result = new []{ new {i = 1, s = "a"}, new {i = 1, s = "b"}, new {i = 1, s = "c"}, new {i = 2, s = "a"}, new {i = 2, s = "b"}, new {i = 2, s = "c"}, new {i = 3, s = "a"}, new {i = 3, s = "b"}, new {i = 3, s = "c"} }; </code></pre> <p>?</p> <p>Edit: I forgot to mention I didn't want it in query syntax. Anyway, based on preetsangha's answer I've got the following:</p> <pre><code>var result = list1.SelectMany(i =&gt; list2.Select(s =&gt; new {i = i, s = s})); </code></pre>
[ { "answer_id": 289310, "author": "Preet Sangha", "author_id": 30225, "author_profile": "https://Stackoverflow.com/users/30225", "pm_score": 5, "selected": false, "text": "var result = from l1 in list1\n from l2 in list2 \n select new { i = l1, s = l2};\n" }, { "answer_id": 289363, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 5, "selected": true, "text": "var result = list1.SelectMany(l1 => list2, (l1, l2) => new { i = l1, s = l2} );\n" } ]
2008/11/14
[ "https://Stackoverflow.com/questions/289307", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3820/" ]
289,311
<p>I want to output a timestamp with a PST offset (e.g., 2008-11-13T13:23:30-08:00). <code>java.util.SimpleDateFormat</code> does not seem to output timezone offsets in the <em>hour:minute</em> format, it excludes the colon. Is there a simple way to get that timestamp in Java?</p> <pre><code>// I want 2008-11-13T12:23:30-08:00 String timestamp = new SimpleDateFormat("yyyy-MM-dd'T'h:m:ssZ").format(new Date()); System.out.println(timestamp); // prints "2008-11-13T12:23:30-0800" See the difference? </code></pre> <p>Also, <code>SimpleDateFormat</code> cannot properly parse the example above. It throws a <code>ParseException</code>.</p> <pre><code>// Throws a ParseException new SimpleDateFormat("yyyy-MM-dd'T'h:m:ssZ").parse("2008-11-13T13:23:30-08:00") </code></pre>
[ { "answer_id": 289322, "author": "FoxyBOA", "author_id": 19347, "author_profile": "https://Stackoverflow.com/users/19347", "pm_score": 2, "selected": false, "text": "SimpleDateFormat format = new SimpleDateFormat(\"yyyy-MM-dd'T'h:m:ss.SZ\");\n" }, { "answer_id": 289927, "author": "Biff", "author_id": 34113, "author_profile": "https://Stackoverflow.com/users/34113", "pm_score": 4, "selected": false, "text": "DateTime dt = new DateTime(2011,1,2,12,45,0,0, DateTimeZone.UTC);\nDateTimeFormatter fmt = ISODateTimeFormat.dateTime();\nString outRfc = fmt.print(dt);\n" }, { "answer_id": 11511199, "author": "jjohn", "author_id": 16513, "author_profile": "https://Stackoverflow.com/users/16513", "pm_score": 4, "selected": false, "text": "// As a private class member\nprivate SimpleDateFormat rfc3339 = new SimpleDateFormat(\"yyyy-MM-dd'T'HH:mm:ssZ\");\n\nString toRFC3339(Date d)\n{\n return rfc3339.format(d).replaceAll(\"(\\\\d\\\\d)(\\\\d\\\\d)$\", \"$1:$2\");\n}\n" }, { "answer_id": 11963257, "author": "crockpotveggies", "author_id": 737455, "author_profile": "https://Stackoverflow.com/users/737455", "pm_score": 1, "selected": false, "text": "// I want 2008-11-13T12:23:30-08:00\nString timestamp = new SimpleDateFormat(\"yyyy-MM-dd'T'h:m:ssZ\").format(new Date());\nSystem.out.println(timestamp); \n// prints \"2008-11-13T12:23:30-0800\" See the difference?\n\n// Throws a ParseException\nnew SimpleDateFormat(\"yyyy-MM-dd'T'h:m:ssZ\").parse(\"2008-11-13T13:23:30-08:00\")\n\nSimpleDateFormat format = new SimpleDateFormat(\"yyyy-MM-dd'T'h:m:ss.SZ\");\n" }, { "answer_id": 22761247, "author": "Daniel Beck", "author_id": 23222, "author_profile": "https://Stackoverflow.com/users/23222", "pm_score": 7, "selected": true, "text": "X XXX System.out.println(new SimpleDateFormat(\"yyyy-MM-dd'T'HH:mm:ssXXX\")\n .format(new Date()));\n 2014-03-31T14:11:29+02:00\n" }, { "answer_id": 30346202, "author": "Rahul Ravindran", "author_id": 4781799, "author_profile": "https://Stackoverflow.com/users/4781799", "pm_score": 4, "selected": false, "text": "String timestamp = new SimpleDateFormat(\"yyyy-MM-dd'T'h:m:ssZZZZZ\").format(new Date());" }, { "answer_id": 60924847, "author": "Vijay Upadhyay", "author_id": 8700476, "author_profile": "https://Stackoverflow.com/users/8700476", "pm_score": 2, "selected": false, "text": "DateTimeFormatter format = DateTimeFormatter.ofPattern(\"yyyy-MM-dd'T'HH:mm:ssxxx\");\nZonedDateTime z2 = ZonedDateTime.now(ZoneOffset.UTC).truncatedTo(ChronoUnit.SECONDS);\nSystem.out.println(\"format =======> \" + z2.format(format));\n" }, { "answer_id": 67923953, "author": "Mahan Hazrati Sagharchi", "author_id": 2412948, "author_profile": "https://Stackoverflow.com/users/2412948", "pm_score": 1, "selected": false, "text": "yyyy-MM-dd'T'HH:mm:ss'Z'" }, { "answer_id": 68363670, "author": "user3541649", "author_id": 3541649, "author_profile": "https://Stackoverflow.com/users/3541649", "pm_score": 0, "selected": false, "text": "DateTimeFormatter rfc3339Formatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME;\n\nDateTimeFormatter rfc3339Parser = new DateTimeFormatterBuilder()\n .parseCaseInsensitive()\n .appendValue(ChronoField.YEAR, 4)\n .appendLiteral('-')\n .appendValue(ChronoField.MONTH_OF_YEAR, 2)\n .appendLiteral('-')\n .appendValue(ChronoField.DAY_OF_MONTH, 2)\n .appendLiteral('T')\n .appendValue(ChronoField.HOUR_OF_DAY, 2)\n .appendLiteral(':')\n .appendValue(ChronoField.MINUTE_OF_HOUR, 2)\n .appendLiteral(':')\n .appendValue(ChronoField.SECOND_OF_MINUTE, 2)\n .optionalStart()\n .appendFraction(ChronoField.NANO_OF_SECOND, 2, 9, true) //2nd parameter: 2 for JRE (8, 11 LTS), 1 for JRE (17 LTS)\n .optionalEnd()\n .appendOffset(\"+HH:MM\",\"Z\")\n .toFormatter()\n .withResolverStyle(ResolverStyle.STRICT)\n .withChronology(IsoChronology.INSTANCE);\n" }, { "answer_id": 68428268, "author": "Arvind Kumar Avinash", "author_id": 10819573, "author_profile": "https://Stackoverflow.com/users/10819573", "pm_score": 0, "selected": false, "text": "java.util SimpleDateFormat java.time ZoneId.of(\"America/Los_Angeles\") ZonedDateTime ZonedDateTime OffsetDateTime ZonedDateTime#toOffsetDateTime OffsetDateTime Instant.now().atOffset(ZoneOffset.of(\"+05:30\")) import java.time.LocalDate;\nimport java.time.LocalDateTime;\nimport java.time.LocalTime;\nimport java.time.OffsetDateTime;\nimport java.time.ZoneId;\nimport java.time.ZonedDateTime;\nimport java.time.temporal.ChronoUnit;\n\npublic class Main {\n public static void main(String[] args) {\n ZoneId zoneIdLosAngeles = ZoneId.of(\"America/Los_Angeles\");\n ZonedDateTime zdtNowLosAngeles = ZonedDateTime.now(zoneIdLosAngeles);\n System.out.println(zdtNowLosAngeles);\n\n // With zone offset but without time zone name\n OffsetDateTime odtNowLosAngeles = zdtNowLosAngeles.toOffsetDateTime();\n System.out.println(odtNowLosAngeles);\n\n // Truncated up to seconds\n odtNowLosAngeles = odtNowLosAngeles.truncatedTo(ChronoUnit.SECONDS);\n System.out.println(odtNowLosAngeles);\n\n // ################ A winter date-time ################\n ZonedDateTime zdtLosAngelesWinter = ZonedDateTime\n .of(LocalDateTime.of(LocalDate.of(2021, 11, 20), LocalTime.of(10, 20)), zoneIdLosAngeles);\n System.out.println(zdtLosAngelesWinter); // 2021-11-20T10:20-08:00[America/Los_Angeles]\n System.out.println(zdtLosAngelesWinter.toOffsetDateTime()); // 2021-11-20T10:20-08:00\n\n // ################ Parsing a date-time string with zone offset ################\n String strDateTime = \"2008-11-13T13:23:30-08:00\";\n OffsetDateTime odt = OffsetDateTime.parse(strDateTime);\n System.out.println(odt); // 2008-11-13T13:23:30-08:00\n }\n}\n 2021-07-18T03:27:15.578028-07:00[America/Los_Angeles]\n2021-07-18T03:27:15.578028-07:00\n2021-07-18T03:27:15-07:00\n2021-11-20T10:20-08:00[America/Los_Angeles]\n2021-11-20T10:20-08:00\n2008-11-13T13:23:30-08:00\n DateTimeFormatter DateTimeFormatter" } ]
2008/11/14
[ "https://Stackoverflow.com/questions/289311", "https://Stackoverflow.com", "https://Stackoverflow.com/users/680/" ]
289,315
<p>In IE6 the paragraph following the empty paragraph is displayed with the background color of the empty paragraph, which I'm guessing is wrong! It works correctly in Firefox, but I haven't checked IE7.</p> <p>Is there a CSS solution to this problem, or do I have to remove the empty element?</p> <p>(I would rather not have to remove empty elements, as that involves writing code to check whether every element is empty before outputting it)</p> <p>The behaviour is unchanged using either strict or transitional doctypes (added this comment in response to answers)</p> <p>Interestingly the effect does not occur with text color, only background color.</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;/head&gt; &lt;body&gt; &lt;p style='background-color:green'&gt;Green content&lt;/p&gt; &lt;p style='background-color:red'&gt;Red content&lt;/p&gt; &lt;p&gt;Unstyled background working because previous red element is not empty&lt;/p&gt; &lt;p style='background-color:green'&gt;Green content&lt;/p&gt; &lt;p style='background-color:red'&gt;&lt;/p&gt; &lt;p&gt;Unstyled background broken because previous red element is empty&lt;/p&gt; &lt;p style='color:green'&gt;Green content&lt;/p&gt; &lt;p style='color:red'&gt;Red content&lt;/p&gt; &lt;p&gt;Unstyled text color working because previous red element is not empty&lt;/p&gt; &lt;p style='color:green'&gt;Green content&lt;/p&gt; &lt;p style='color:red'&gt;&lt;/p&gt; &lt;p&gt;Unstyled text color working even though previous red element is empty&lt;/p&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "answer_id": 289336, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 1, "selected": false, "text": "<p style='background-color:green'>Green content</p>\n<p style='background-color:red; margin-left:50px'></p>\n<p>Unstyled background broken because previous red element is empty</p>\n" }, { "answer_id": 289337, "author": "Gordon Bell", "author_id": 16473, "author_profile": "https://Stackoverflow.com/users/16473", "pm_score": 1, "selected": false, "text": "<p style='color:red'>& nbsp;</p>\n" }, { "answer_id": 293291, "author": "Josh", "author_id": 10902, "author_profile": "https://Stackoverflow.com/users/10902", "pm_score": 1, "selected": false, "text": "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\"\n\"http://www.w3.org/TR/html4/strict.dtd\"> \n" }, { "answer_id": 294667, "author": "John Rees", "author_id": 37572, "author_profile": "https://Stackoverflow.com/users/37572", "pm_score": 0, "selected": false, "text": "<p style='background-color:red;position:relative'></p>\n<p>Unstyled background fine because previous element is 'relative'</p>\n" } ]
2008/11/14
[ "https://Stackoverflow.com/questions/289315", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37572/" ]
289,321
<p>I'm currently using <a href="http://eigenclass.org/hiki.rb?rcov" rel="noreferrer">Rcov</a> to get C0 code coverage analysis for a rails project that I'm working on.</p> <p>However, those results are practically meaningless- I have 100% coverage according to rcov (as it only covers C0 analysis) and I've barely written half the test cases for the functionality that exists thus far.</p> <p>I'm used to the useful results from the code coverage in Visual Studio 2008 Team, which has C1 coverage. Are there any tools that provide similar coverage for ruby?</p>
[ { "answer_id": 53195912, "author": "Marc-André Lafortune", "author_id": 8279, "author_profile": "https://Stackoverflow.com/users/8279", "pm_score": 2, "selected": false, "text": "DeepCover" } ]
2008/11/14
[ "https://Stackoverflow.com/questions/289321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35345/" ]
289,324
<p>I was remote debugging a stack overflow from a recursive function. The Visual Studio IDE only showed the first 1,000 frames (all the same function), but I needed to go up further too see what the cause was.</p> <p>Does anybody know how to get VS to 'move up' in a stack listing?</p> <p>Thanks. </p>
[ { "answer_id": 289474, "author": "David Sykes", "author_id": 259, "author_profile": "https://Stackoverflow.com/users/259", "pm_score": 0, "selected": false, "text": "void f(int rcount /* = 0 */ )\n{\n Assert(rcount < 1000);\n f(count+1);\n}\n" }, { "answer_id": 292231, "author": "Walter Bright", "author_id": 33949, "author_profile": "https://Stackoverflow.com/users/33949", "pm_score": 1, "selected": false, "text": "static int nest; if (++nest == 100) *(char*)0 = 0;\n" } ]
2008/11/14
[ "https://Stackoverflow.com/questions/289324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37574/" ]
289,329
<p>I was trying to create a pseudo super struct to print array of structs. My basic structures are as follows.</p> <pre><code>/* Type 10 Count */ typedef struct _T10CNT { int _cnt[20]; } T10CNT; ... /* Type 20 Count */ typedef struct _T20CNT { long _cnt[20]; } T20CNT; ... </code></pre> <p>I created the below struct to print the array of above mentioned structures. I got dereferencing void pointer error while compiling the below code snippet.</p> <pre><code>typedef struct _CMNCNT { long _cnt[3]; } CMNCNT; static int printCommonStatistics(void *cmncntin, int cmncnt_nelem, int cmncnt_elmsize) { int ii; for(ii=0; ii&lt;cmncnt_nelem; ii++) { CMNCNT *cmncnt = (CMNCNT *)&amp;cmncntin[ii*cmncnt_elmsize]; fprintf(stout,"STATISTICS_INP: %d\n",cmncnt-&gt;_cnt[0]); fprintf(stout,"STATISTICS_OUT: %d\n",cmncnt-&gt;_cnt[1]); fprintf(stout,"STATISTICS_ERR: %d\n",cmncnt-&gt;_cnt[2]); } return SUCCESS; } T10CNT struct_array[10]; ... printCommonStatistics(struct_array, NELEM(struct_array), sizeof(struct_array[0]); ... </code></pre> <p>My intention is to have a common function to print all the arrays. Please let me know the correct way of using it.</p> <p>Appreciate the help in advance.</p> <p>Edit: The parameter name is changed to cmncntin from cmncnt. Sorry it was typo error.</p> <p>Thanks, Mathew Liju</p>
[ { "answer_id": 289334, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 0, "selected": false, "text": "CMNCNT *cmncnt = (CMNCNT *)&cmncnt[ii*cmncnt_elmsize];\n" }, { "answer_id": 289338, "author": "Adam Pierce", "author_id": 5324, "author_profile": "https://Stackoverflow.com/users/5324", "pm_score": 1, "selected": false, "text": "static int printCommonStatistics(char *cmncnt, int cmncnt_nelem, int cmncnt_elmsize)\n" }, { "answer_id": 289339, "author": "Klathzazt", "author_id": 35223, "author_profile": "https://Stackoverflow.com/users/35223", "pm_score": 1, "selected": false, "text": "cmncnt->_cnt[0]\n" }, { "answer_id": 289506, "author": "Windows programmer", "author_id": 23705, "author_profile": "https://Stackoverflow.com/users/23705", "pm_score": 0, "selected": false, "text": "(CMNCNT *)&cmncntin[ii*cmncnt_elmsize]\n" }, { "answer_id": 290095, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 2, "selected": false, "text": "T10CNT* CMNCNT* printCommonStatisticsInt printCommonStatisticsLong printCommonStatisticsChar int* long* struct_array[0]._cnt" }, { "answer_id": 290290, "author": "T.E.D.", "author_id": 29639, "author_profile": "https://Stackoverflow.com/users/29639", "pm_score": -1, "selected": false, "text": "CMNCNT *cmncnt = (CMNCNT *)&cmncntin[ii*cmncnt_elmsize];\n CMNCNT *cmncnt = ((CMNCNT *)(cmncntin + (ii * cmncnt_elmsize));\n CMNCNT *cmncnt = ((CMNCNT *)cmncntin) + ii;\n" }, { "answer_id": 292689, "author": "David Norman", "author_id": 34502, "author_profile": "https://Stackoverflow.com/users/34502", "pm_score": 1, "selected": false, "text": "static int printCommonStatistics(void *cmncntin, int cmncnt_nelem, int cmncnt_elmsize)\n{\n char *cmncntinBytes;\n int ii;\n\n cmncntinBytes = (char *) cmncntin;\n for(ii=0; ii<cmncnt_nelem; ii++)\n {\n CMNCNT *cmncnt = (CMNCNT *)(cmncntinBytes + ii*cmncnt_elmsize); /* Ptr Line */\n fprintf(stdout,\"STATISTICS_INP: %d\\n\",cmncnt->_cnt[0]);\n fprintf(stdout,\"STATISTICS_OUT: %d\\n\",cmncnt->_cnt[1]); \n fprintf(stdout,\"STATISTICS_ERR: %d\\n\",cmncnt->_cnt[2]);\n }\n return SUCCESS;\n}\n" }, { "answer_id": 292703, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 4, "selected": true, "text": "int long sizeof(long) != sizeof(int) int long long int long void * void * typedef struct _CMNCNT\n{\n long count[3];\n} CMNCNT;\n\nstatic void printCommonStatistics(const void *data, size_t nelem, size_t elemsize)\n{\n int i;\n for (i = 0; i < nelem; i++)\n {\n const CMNCNT *cmncnt = (const CMNCNT *)((const char *)data + (i * elemsize));\n fprintf(stdout,\"STATISTICS_INP: %ld\\n\", cmncnt->count[0]);\n fprintf(stdout,\"STATISTICS_OUT: %ld\\n\", cmncnt->count[1]); \n fprintf(stdout,\"STATISTICS_ERR: %ld\\n\", cmncnt->count[2]);\n }\n}\n stout sed 's/^/ /' file.c const void * const char * char * void * i elemsize long %ld fprintf() const sizeof(long) != sizeof(int) int long" }, { "answer_id": 292865, "author": "Mr.Ree", "author_id": 37946, "author_profile": "https://Stackoverflow.com/users/37946", "pm_score": 0, "selected": false, "text": "struct T { int sizeOfArray; int data[1]; };\n T * t = (T *) malloc( sizeof(T) + sizeof(int)*(NUMBER-1) );\n t->sizeOfArray = NUMBER;\n struct T {\n int sizeOfArray;\n enum FOO arrayType;\n union U { short s; int i; long l; float f; double d; } data [1];\n };\n void printCommonStatistics( int * data, int count )\n{\n for( int i=0; i<count; i++ )\n cout << \"FOO: \" << data[i] << endl;\n}\n _T10CNT foo;\nprintCommonStatistics( foo._cnt, 20 );\n int a[10], b[20], c[30];\nprintCommonStatistics( a, 10 );\nprintCommonStatistics( b, 20 );\nprintCommonStatistics( c, 30 );\n struct FOO {\n union {\n int bar [10];\n long biff [20];\n } u;\n}\n template<class TYPE> void printCommonStatistics( TYPE & mystruct, int count )\n{\n for( int i=0; i<count; i++ )\n cout << \"FOO: \" << mystruct._cnt[i] << endl;\n} /* Assumes all mystruct's have a \"_cnt\" member. */\n" } ]
2008/11/14
[ "https://Stackoverflow.com/questions/289329", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18657/" ]
289,335
<p>Can anyone tell me what is the difference between XSDObjectGen.exe &amp; XSD.exe?</p> <p>Is there any way to make XSDObjectGen.exe work in dot net 2.0?</p>
[ { "answer_id": 3004852, "author": "Daniel Fortunov", "author_id": 5975, "author_profile": "https://Stackoverflow.com/users/5975", "pm_score": 3, "selected": false, "text": "xsd.exe XSDObjectGen.exe XSDObjectGen.exe C:\\Program Files\\XSDObjectGenerator" }, { "answer_id": 5044576, "author": "Shankar R10N", "author_id": 190037, "author_profile": "https://Stackoverflow.com/users/190037", "pm_score": 2, "selected": false, "text": "Arrays ArrayLists Generics" } ]
2008/11/14
[ "https://Stackoverflow.com/questions/289335", "https://Stackoverflow.com", "https://Stackoverflow.com/users/747/" ]
289,342
<p>What is the keyboard short cut in Eclipse to jump to the closing brace of a scope?</p>
[ { "answer_id": 378476, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "}" }, { "answer_id": 1637242, "author": "Romain Linsolas", "author_id": 26457, "author_profile": "https://Stackoverflow.com/users/26457", "pm_score": 7, "selected": false, "text": "{ { }" } ]
2008/11/14
[ "https://Stackoverflow.com/questions/289342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3020/" ]
289,347
<p>I have a string that I would like to tokenize. But the C <code>strtok()</code> function requires my string to be a <code>char*</code>. How can I do this simply?</p> <p>I tried:</p> <pre><code>token = strtok(str.c_str(), " "); </code></pre> <p>which fails because it turns it into a <code>const char*</code>, not a <code>char*</code></p>
[ { "answer_id": 289354, "author": "DocMax", "author_id": 6234, "author_profile": "https://Stackoverflow.com/users/6234", "pm_score": 4, "selected": false, "text": "char *dup = strdup(str.c_str());\ntoken = strtok(dup, \" \");\nfree(dup);\n" }, { "answer_id": 289365, "author": "Todd Gamblin", "author_id": 9122, "author_profile": "https://Stackoverflow.com/users/9122", "pm_score": 4, "selected": false, "text": "void split(const string& str, const string& delim, vector<string>& parts) {\n size_t start, end = 0;\n while (end < str.size()) {\n start = end;\n while (start < str.size() && (delim.find(str[start]) != string::npos)) {\n start++; // skip initial whitespace\n }\n end = start;\n while (end < str.size() && (delim.find(str[end]) == string::npos)) {\n end++; // skip to end of word\n }\n if (end-start != 0) { // just ignore zero-length strings.\n parts.push_back(string(str, start, end-start));\n }\n }\n}\n" }, { "answer_id": 289372, "author": "Chris Blackwell", "author_id": 1329401, "author_profile": "https://Stackoverflow.com/users/1329401", "pm_score": 6, "selected": false, "text": "#include <iostream>\n#include <string>\n#include <sstream>\nint main(){\n std::string myText(\"some-text-to-tokenize\");\n std::istringstream iss(myText);\n std::string token;\n while (std::getline(iss, token, '-'))\n {\n std::cout << token << std::endl;\n }\n return 0;\n}\n" }, { "answer_id": 289465, "author": "philant", "author_id": 18804, "author_profile": "https://Stackoverflow.com/users/18804", "pm_score": 2, "selected": false, "text": "strtok() strtok() #include <string>\n#include <iostream>\n\nint main(int ac, char **av)\n{\n std::string theString(\"hello world\");\n std::cout << theString << \" - \" << theString.size() << std::endl;\n\n //--- this cast *only* to illustrate the effect of strtok() on std::string \n char *token = strtok(const_cast<char *>(theString.c_str()), \" \");\n\n std::cout << theString << \" - \" << theString.size() << std::endl;\n\n return 0;\n}\n strtok() >./a.out\nhello world - 11\nhelloworld - 11\n" }, { "answer_id": 289678, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 0, "selected": false, "text": "std::string data(\"The data I want to tokenize\");\n\n// Create a buffer of the correct length:\nstd::vector<char> buffer(data.size()+1);\n\n// copy the string into the buffer\nstrcpy(&buffer[0],data.c_str());\n\n// Tokenize\nstrtok(&buffer[0],\" \");\n" }, { "answer_id": 1592860, "author": "Martin Dimitrov", "author_id": 192885, "author_profile": "https://Stackoverflow.com/users/192885", "pm_score": 3, "selected": false, "text": "\nstd::string str(\"some-text-to-split\");\nchar seps[] = \"-\";\nchar *token;\n\ntoken = strtok( &str[0], seps );\nwhile( token != NULL )\n{\n /* Do your thing */\n token = strtok( NULL, seps );\n}\n" }, { "answer_id": 30782242, "author": "Scott Yeager", "author_id": 4999384, "author_profile": "https://Stackoverflow.com/users/4999384", "pm_score": 0, "selected": false, "text": "std::string input_string(\"hello world\");\nsubbuffer input(input_string);\nsubparser flds(input, ' ', subparser::SKIP_EMPTY);\nwhile (!flds.empty())\n{\n subbuffer fld = flds.next();\n // do something with fld\n}\n\n// or if you know it is only two fields\nsubbuffer fld1 = input.before(' ');\nsubbuffer fld2 = input.sub(fld1.length() + 1).ltrim(' ');\n" }, { "answer_id": 33179190, "author": "maximus", "author_id": 2681348, "author_profile": "https://Stackoverflow.com/users/2681348", "pm_score": -1, "selected": false, "text": "str.c_str() char * strtok (char * str, const char * delimiters ) #include <iostream>\n #include <string>\n #include <string.h> \n using namespace std;\n int main() {\n string s=\"20#6 5, 3\";\n // strtok requires volatile string as it modifies the supplied string in order to tokenize it \n char *str=const_cast< char *>(s.c_str()); \n char *tok;\n tok=strtok(str, \"#, \" ); \n int arr[4], i=0; \n while(tok!=NULL){\n arr[i++]=stoi(tok);\n tok=strtok(NULL, \"#, \" );\n } \n for(int i=0; i<4; i++) cout<<arr[i]<<endl;\n\n\n return 0;\n }\n #include <iostream>\n#include <string>\n#include <string.h> \nusing namespace std;\nint main() {\n string s=\"20#6 5, 3\";\n char *str=const_cast< char *>(s.c_str()); \n char *tok;\n cout<<\"string: \"<<s<<endl;\n tok=strtok(str, \"#, \" ); \n cout<<\"String: \"<<s<<\"\\tToken: \"<<tok<<endl; \n while(tok!=NULL){\n tok=strtok(NULL, \"#, \" );\n cout<<\"String: \"<<s<<\"\\t\\tToken: \"<<tok<<endl;\n }\n return 0;\n}\n string: 20#6 5, 3\n\nString: 206 5, 3 Token: 20\nString: 2065, 3 Token: 6\nString: 2065 3 Token: 5\nString: 2065 3 Token: 3\nString: 2065 3 Token: \n" }, { "answer_id": 57409764, "author": "user7860670", "author_id": 7860670, "author_profile": "https://Stackoverflow.com/users/7860670", "pm_score": 2, "selected": false, "text": "str::string data() strtok #include <string>\n#include <iostream>\n#include <cstring>\n#include <cstdlib>\n\nint main()\n{\n ::std::string text{\"pop dop rop\"};\n char const * const psz_delimiter{\" \"};\n char * psz_token{::std::strtok(text.data(), psz_delimiter)};\n while(nullptr != psz_token)\n {\n ::std::cout << psz_token << ::std::endl;\n psz_token = std::strtok(nullptr, psz_delimiter);\n }\n return EXIT_SUCCESS;\n}\n" }, { "answer_id": 65007344, "author": "khushgrover", "author_id": 13621078, "author_profile": "https://Stackoverflow.com/users/13621078", "pm_score": 0, "selected": false, "text": "token = strtok((char *)str.c_str(), \" \"); \n" }, { "answer_id": 70003020, "author": "Jérôme", "author_id": 4012208, "author_profile": "https://Stackoverflow.com/users/4012208", "pm_score": 0, "selected": false, "text": "template <class CharT> bool tokenizestring(const std::basic_string<CharT> &input, CharT separator, typename std::basic_string<CharT>::size_type &pos, std::basic_string<CharT> &token) {\n if (pos >= input.length()) {\n // if input is empty, or ends with a separator, return an empty token when the end has been reached (and return an out-of-bound position so subsequent call won't do it again)\n if ((pos == 0) || ((pos > 0) && (pos == input.length()) && (input[pos-1] == separator))) {\n token.clear();\n pos=input.length()+1;\n return true;\n }\n return false;\n }\n typename std::basic_string<CharT>::size_type separatorPos=input.find(separator, pos);\n if (separatorPos == std::basic_string<CharT>::npos) {\n token=input.substr(pos, input.length()-pos);\n pos=input.length();\n } else {\n token=input.substr(pos, separatorPos-pos);\n pos=separatorPos+1;\n }\n return true;\n}\n std::basic_string<char16_t> s;\nstd::basic_string<char16_t> token;\nstd::basic_string<char16_t>::size_type tokenPos=0;\nwhile (tokenizestring(s, (char16_t)' ', tokenPos, token)) {\n ...\n}\n" } ]
2008/11/14
[ "https://Stackoverflow.com/questions/289347", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
289,360
<p>I have a large UIScrollView into which I'm placing 3-4 rather large (320x1500 pixels or so) UIImageView image tiles. I'm adding these UIImageViews to the scroll view inside of my NIB files. I have one outlet on my controller, and that is to the UIScrollView. I'm using a property (nonatomic, retain) for this, and sythesizing it.</p> <p>My question is this: When I observe this in Memory Monitor, I can see that the memory used goes up quite a bit when the view with all these images is loaded (as expected). But when I leave the view, it and its controller are dealloc'd, but do not seem to give up anywhere near the memory they had taken up. When I cut one of these views (there are several in my app) down to just 1-3 images that were 320x460 and left everything else the same, it recaptures the memory just fine.</p> <p>Is there some issue with using images this large? Am I doing something wrong in this code (pasted below)?</p> <p>This is a snippet from the viewController that is causing problems.</p> <pre><code>- (CGFloat)findHeight { UIImageView *imageView = nil; NSArray *subviews = [self.scrollView subviews]; CGFloat maxYLoc = 0; for (imageView in subviews) { if ([imageView isKindOfClass:[UIImageView class]]) { CGRect frame = imageView.frame; if ((frame.origin.y + frame.size.height) &gt; maxYLoc) { maxYLoc = frame.origin.y; maxYLoc += frame.size.height; } } } return maxYLoc; } - (void)viewDidLoad { [super viewDidLoad]; [self.scrollView setContentSize:CGSizeMake(320, [self findHeight])]; [self.scrollView setCanCancelContentTouches:NO]; self.scrollView.indicatorStyle = UIScrollViewIndicatorStyleWhite; self.scrollView.clipsToBounds = YES; self.scrollView.scrollEnabled = YES; self.scrollView.pagingEnabled = NO; } - (void)dealloc { NSLog(@"DAY Controller Dealloc'd"); self.scrollView = nil; [super dealloc]; } </code></pre> <p>UPDATE: I've noticed another weird phenomenon. If I don't use the scroll on the view, it seems to be hanging on to the memory. But if I scroll around a bunch and ensure that all of the UIImageViews became visible at one point, it will free up and regain most of the memory it lost.</p> <p>UPDATE2: The reason I'm asking this is my app is actually crashing due to low memory. I wouldn't mind if it were just caching and using up extra memory, but it doesn't seem to ever release it - even in didReceiveMmoryWarning conditions</p>
[ { "answer_id": 289374, "author": "seanalltogether", "author_id": 26986, "author_profile": "https://Stackoverflow.com/users/26986", "pm_score": 0, "selected": false, "text": "- (void)dealloc {\n NSLog(@\"DAY Controller Dealloc'd\");\n [self.scrollView release];\n [super dealloc];\n}\n" }, { "answer_id": 289417, "author": "Kendall Helmstetter Gelner", "author_id": 6330, "author_profile": "https://Stackoverflow.com/users/6330", "pm_score": 2, "selected": false, "text": "UIImage imageNamed imageWithContentsOfFile imageWithData UIImageViews viewDidLoad UIImage" }, { "answer_id": 291225, "author": "Bdebeez", "author_id": 35516, "author_profile": "https://Stackoverflow.com/users/35516", "pm_score": 5, "selected": true, "text": "NSString *fullpath = [[[NSBundle mainBundle] bundlePath];\n NSString *fullpath = [[[NSBundle mainBundle] bundlePath] stringByAppendingString:[NSString stringWithFormat:@\"/%@-%d.png\", self.nibName, imageView.tag]];\nUIImage *loadImage = [UIImage imageWithContentsOfFile:fullpath];\nimageView.image = loadImage;\n - (CGFloat)findHeight \n{\n UIImageView *imageView = nil;\n NSArray *subviews = [self.scrollView subviews];\n\n CGFloat maxYLoc = 0;\n for (imageView in subviews)\n {\n if ([imageView isKindOfClass:[UIImageView class]])\n {\n CGRect frame = imageView.frame;\n\n if ((frame.origin.y + frame.size.height) > maxYLoc) {\n maxYLoc = frame.origin.y;\n maxYLoc += frame.size.height;\n }\n\n NSString *fullpath = [[[NSBundle mainBundle] bundlePath] stringByAppendingString:[NSString stringWithFormat:@\"/%@-%d.png\", self.nibName, imageView.tag]];\n NSLog(fullpath);\n\n\n UIImage *loadImage = [UIImage imageWithContentsOfFile:fullpath];\n imageView.image = loadImage;\n }\n }\n return maxYLoc;\n}\n" }, { "answer_id": 1615307, "author": "Olie", "author_id": 34820, "author_profile": "https://Stackoverflow.com/users/34820", "pm_score": 2, "selected": false, "text": "You should avoid creating UIImage objects that are greater than 1024 x 1024 in size.\nBesides the large amount of memory such an image would consume, you may run into \nproblems when using the image as a texture in OpenGL ES or when drawing the image \nto a view or layer.\n" }, { "answer_id": 1710331, "author": "SEQOY Development Team", "author_id": 137199, "author_profile": "https://Stackoverflow.com/users/137199", "pm_score": 1, "selected": false, "text": "imageNamed: imageWithContentsOfFile: @implementation UIImage(imageNamed_Hack)\n\n+ (UIImage *)imageNamed:(NSString *)name {\n\n return [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@\"%@/%@\", [[NSBundle mainBundle] bundlePath], name ] ];\n}\n\n@end\n" } ]
2008/11/14
[ "https://Stackoverflow.com/questions/289360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35516/" ]
289,362
<p>I'm using the MySQL Query Browser (part of the <a href="http://dev.mysql.com/downloads/gui-tools/" rel="noreferrer">MySQL GUI Tools</a>) and need to change a field to NULL, but I can't figure out how to do it - if I delete the value it tries to update it to <code>''</code>. Typing "NULL" makes it try to update to <code>'NULL'</code> (a string).</p> <p>I know I could just write a query to do it, but that defeats the entire purpose of the tool, no?</p>
[ { "answer_id": 37532738, "author": "Izzy Rodriguez", "author_id": 228160, "author_profile": "https://Stackoverflow.com/users/228160", "pm_score": 3, "selected": false, "text": "Shift + Delete" }, { "answer_id": 62324390, "author": "Andrea Fini", "author_id": 4541788, "author_profile": "https://Stackoverflow.com/users/4541788", "pm_score": 1, "selected": false, "text": "Shift + Delete \n" } ]
2008/11/14
[ "https://Stackoverflow.com/questions/289362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9021/" ]
289,405
<p>When I'm writing some tight loop that needs to work fast I am often bothered by thoughts about how the processor branch prediction is going to behave. For instance I try my best to avoid having an if statement in the most inner loop, especially one with a result which is not somewhat uniform (say evaluates to true or false randomly). </p> <p>I tend to do that because of the somewhat common knowledge that the processor pre-fetches instructions and if it turned out that it mis-predicted a branch then the pre-fetch is useless.</p> <p>My question is - Is this really an issue with modern processors? How good can branch prediction expected to be?<br> What coding patterns can be used to make it better?</p> <p>(For the sake of the discussion, assume that I am beyond the "early-optimization is the root of all evil" phase)</p>
[ { "answer_id": 296684, "author": "AShelly", "author_id": 10396, "author_profile": "https://Stackoverflow.com/users/10396", "pm_score": 0, "selected": false, "text": "if (var >= limit) { otherVar = 0;}\n otherVar *= (var<limit)&1;\n" } ]
2008/11/14
[ "https://Stackoverflow.com/questions/289405", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9611/" ]
289,409
<p>I have a layout that is working, but it has one very annoying problem.. when the content is taller than the screen, the background stops.</p> <p>This is the desired layout in bad-ASCII-art format:</p> <pre><code>_____________________ _ | | long |logo| | | | content | | | | | | | | | | | | | |grad| |grad| | Viewport | | | | | | | | | | | | | | _| | | | | | | | | _____________________ |2em| &lt;-20em-&gt;| 2em| </code></pre> <p>..or with short content..</p> <pre><code>_____________________ _ | | short |logo| | | | content | | | | | | | | | | | | | |grad| |grad| | Viewport | | | | | | | | | | | | | | | | | | | | _____________________ _| </code></pre> <p>Basically it looks like a single column, with a glow as a column either side. Over the left-glow is a logo. When the content is short, it is still the full-height.</p> <p>I have tried using the <a href="http://www.dustindiaz.com/min-height-fast-hack/" rel="nofollow noreferrer">CSS min-height hack</a>, which fixes the middle column, but then the gradients only extend as far as the content (in the left column, a single <code>&amp;nbsp;</code>, in the right column the logo)</p> <hr> <p>Here is what the layout looks like:</p> <p><img src="https://i.stack.imgur.com/CVm4I.png" alt="Layout"></p> <p>And the problem (when the browser window is shrunk vertically):</p> <p><img src="https://i.stack.imgur.com/CVhOL.png" alt="Problem"></p> <p>Finally, the problem HTML/CSS, <a href="http://data.dbrweb.co.uk/tmp/fifestock_layout_problem/" rel="nofollow noreferrer">http://data.dbrweb.co.uk/tmp/fifestock_layout_problem/</a></p>
[ { "answer_id": 289487, "author": "Mikael Söderström", "author_id": 36944, "author_profile": "https://Stackoverflow.com/users/36944", "pm_score": 0, "selected": false, "text": "<div id=\"right\">...</div> <div style=\"clear: both; font-size: 1px; line-height:1px\">&nbsp;</div>\n" }, { "answer_id": 289510, "author": "ARemesal", "author_id": 36599, "author_profile": "https://Stackoverflow.com/users/36599", "pm_score": 1, "selected": false, "text": "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\"\n \"http://www.w3.org/TR/html4/strict.dtd\">\n<html>\n <head>\n <title>Test page</title>\n <style type=\"text/css\" media=\"screen\">\n html, body{\n margin: 0 auto 0 auto;\n padding:0;\n width:22em;\n }\n\n #wrapper{\n background-color:#ccc;\n }\n\n #left{\n float:left;\n width:22em;\n background-color:#00f;\n }\n\n #middle{\n float:right;\n width:18em;\n margin-right:2em;\n background-color:#f00;\n }\n\n #right{\n float: right;\n width:20em;\n background-color:#0f0;\n background-image: url(static/logo.png);\n background-position: top right;\n background-repeat: no-repeat;\n }\n\n </style>\n </head>\n <body>\n <div id=\"wrapper\">\n <div id=\"left\">\n <div id=\"right\">\n <div id=\"middle\">\n Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.<br><br><br> Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.<br><br><br>Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.<br><br><br> Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in oluptate velit esse cillum dolore eu fugiat nulla pariatur.<br><br><br>Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.<br><br><br>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.<br><br><br>\n </div>\n </div>\n </div>\n </div>\n </body>\n</html>\n" }, { "answer_id": 289837, "author": "David Heggie", "author_id": 4309, "author_profile": "https://Stackoverflow.com/users/4309", "pm_score": 0, "selected": false, "text": "<body>\n <div id=\"wrapper\">\n <img src=\"static/fifestock_logo.png\" />\n <div id=\"middle\">\n ... etc ...\n </div>\n </div>\n</body>\n #wrapper{\n height:100%;\n width:805px;\n margin-left:auto;\n margin-right:auto;\n text-align: right;\n}\n\n#middle {\n width:504px;\n padding: 0 44px;\n margin: -154px auto 0 auto;\n background:#000 url(new_bg.png) repeat-y top left;\n}\n" }, { "answer_id": 295718, "author": "dbr", "author_id": 745, "author_profile": "https://Stackoverflow.com/users/745", "pm_score": 2, "selected": false, "text": "padding-bottom margin-bottom overflow:hidden <html>\n<head>\n <title>Yay</title>\n <style type=\"text/css\" media=\"screen\">\n body, html{\n height:100%;\n margin:0;\n background:#1d4b76;\n }\n #contain{\n width:40em;\n margin-left:auto;\n margin-right:auto;\n overflow:hidden;\n }\n #left{\n background-image:url(\"static/grad_left.png\");\n background-repeat:repeat-y;\n background-position:right;\n\n height:100%;\n float:left;\n width:150px;\n\n padding-bottom:10000px;\n margin-bottom:-10000px;\n }\n #middle{\n float:left;\n background:#000;\n color:#fff;\n width:20em;\n\n padding-bottom:100000px;\n margin-bottom:-100000px;\n }\n #right{\n float:left;\n background-image:url(\"static/grad_right.png\");\n background-repeat:repeat-y;\n background-position:left;\n width:150px;\n\n padding-bottom:100000px;\n margin-bottom:-100000px;\n }\n </style>\n</head>\n<body>\n <div id=\"contain\">\n <div id=\"left\">\n &nbsp; \n </div>\n <div id=\"middle\">\n Put lots of text here\n </div>\n <div id=\"right\">\n <img src=\"static/logo.png\" width=\"150\" height=\"150\" alt=\"Logo\">\n </div>\n </div>\n</body>\n</html>\n" } ]
2008/11/14
[ "https://Stackoverflow.com/questions/289409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/745/" ]
289,432
<p>Basically, I'm trying to write the following (pseudocode) in an ASP.NET HttpModule:</p> <pre><code>*pre-code* try { handler.ProcessRequest(...) } catch (Exception) { *error-code* } finally { *post-code* } </code></pre> <p>I've found that I can hook into HttpModule.PreExecuteHandler for "pre-code" and .Error for "error-code". But PostExecuteHandler doesn't seem to be running reliably.</p> <p>BeginRequest and EndRequest run reliably but are too early for the code I need to write, which requires inspection of the handler that was chosen to execute. The handler isn't chosen until after BeginRequest.</p> <p>Is there a best practice for writing this kind of wrapper?</p> <p>Thanks!</p>
[ { "answer_id": 292814, "author": "Timothy Khouri", "author_id": 11917, "author_profile": "https://Stackoverflow.com/users/11917", "pm_score": -1, "selected": false, "text": "protected void Application_PreRequestHandlerExecute(object sender, EventArgs e)\n{\n //\n}\n\nprotected void Application_PostRequestHandlerExecute(object sender, EventArgs e)\n{\n //\n}\n" } ]
2008/11/14
[ "https://Stackoverflow.com/questions/289432", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7104/" ]
289,433
<p>How can I prevent the user from being able to resize an image in designMode? (disable the handles when image is clicked)</p>
[ { "answer_id": 289453, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 4, "selected": true, "text": "document.body.contentEditable = true;\n var imgs = document.getElementsByTagName(\"IMG\");\nfor (var i = 0; i < imgs.length; ++i) {\n imgs[i].contentEditable = false;\n}\n" }, { "answer_id": 515514, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "img {\n width: auto !important;\n height: auto !important;\n}\n" }, { "answer_id": 2134799, "author": "peterm", "author_id": 258692, "author_profile": "https://Stackoverflow.com/users/258692", "pm_score": 1, "selected": false, "text": "<div id=\"myDiv\" contenteditable=\"true\"><p>Sample text!</p></div>\n <div id=\"myDiv\" contenteditable=\"true\"><p>Sample text!</p><img src=\"picture.jpg\" /></div>\n" }, { "answer_id": 2742222, "author": "Brendon Muir", "author_id": 129798, "author_profile": "https://Stackoverflow.com/users/129798", "pm_score": 3, "selected": false, "text": "document.execCommand(\"enableObjectResizing\", false, false);\n" }, { "answer_id": 3028948, "author": "nmb.ten", "author_id": 247075, "author_profile": "https://Stackoverflow.com/users/247075", "pm_score": 4, "selected": false, "text": "document.execCommand(\"enableObjectResizing\", false, false); image.attachEvent(\"onresizestart\", function(e) { e.returnValue = false; }, false);" }, { "answer_id": 22539578, "author": "elture", "author_id": 3441956, "author_profile": "https://Stackoverflow.com/users/3441956", "pm_score": 0, "selected": false, "text": "document.execCommand(\"enableObjectResizing\", false, false);\n" } ]
2008/11/14
[ "https://Stackoverflow.com/questions/289433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26181/" ]