id
int64
4
73.8M
title
stringlengths
10
150
body
stringlengths
17
50.8k
accepted_answer_id
int64
7
73.8M
answer_count
int64
1
182
comment_count
int64
0
89
community_owned_date
stringlengths
23
27
creation_date
stringlengths
23
27
favorite_count
int64
0
11.6k
last_activity_date
stringlengths
23
27
last_edit_date
stringlengths
23
27
last_editor_display_name
stringlengths
2
29
last_editor_user_id
int64
-1
20M
owner_display_name
stringlengths
1
29
owner_user_id
int64
1
20M
parent_id
null
post_type_id
int64
1
1
score
int64
-146
26.6k
tags
stringlengths
1
125
view_count
int64
122
11.6M
answer_body
stringlengths
19
51k
1,231,985
When to use interfaces or abstract classes? When to use both?
<p>While certain guidelines state that you should use an interface when you want to define a contract for a class where inheritance is not clear (<code>IDomesticated</code>) and inheritance when the class is an extension of another (<code>Cat : Mammal</code>, <code>Snake : Reptile</code>), there are cases when (in my opinion) these guidelines enter a gray area.</p> <p>For example, say my implementation was <code>Cat : Pet</code>. <code>Pet</code> is an abstract class. Should that be expanded to <code>Cat : Mammal, IDomesticated</code> where <code>Mammal</code> is an abstract class and <code>IDomesticated</code> is an interface? Or am I in conflict with the <a href="http://en.wikipedia.org/wiki/KISS_principle" rel="noreferrer">KISS</a>/<a href="http://en.wikipedia.org/wiki/YAGNI" rel="noreferrer">YAGNI</a> principles (even though I'm not sure whether there will be a <code>Wolf</code> class in the future, which would not be able to inherit from <code>Pet</code>)?</p> <p>Moving away from the metaphorical <code>Cat</code>s and <code>Pet</code>s, let's say I have some classes that represent sources for incoming data. They all need to implement the same base somehow. I could implement some generic code in an abstract <code>Source</code> class and inherit from it. I could also just make an <code>ISource</code> interface (which feels more "right" to me) and re-implement the generic code in each class (which is less intuitive). Finally, I could "have the cake and eat it" by making both the abstract class and the interface. What's best?</p> <p>These two cases bring up points for using only an abstract class, only an interface and using both an abstract class and an interface. Are these all valid choices, or are there "rules" for when one should be used over another?</p> <hr> <p>I'd like to clarify that by "using both an abstract class and an interface" that includes the case when they essentially represent the same thing (<code>Source</code> and <code>ISource</code> both have the same members), but the class adds generic functionality while the interface specifies the contract.</p> <p>Also worth noting is that this question is mostly for languages that do not support multiple inheritance (such as .NET and Java).</p>
1,232,759
7
3
null
2009-08-05 08:56:03.203 UTC
22
2016-11-20 14:45:29.643 UTC
2016-11-20 13:51:43.173 UTC
null
63,550
null
119,081
null
1
33
oop|interface|abstract-class
40,547
<p>As a first rule of thumb, I prefer abstract classes over interfaces, <a href="https://msdn.microsoft.com/en-us/library/ms229013(v=vs.100).aspx" rel="noreferrer">based on the .NET Design Guidelines</a>. The reasoning applies much wider than .NET, but is better explained in the book <a href="https://rads.stackoverflow.com/amzn/click/com/0321246756" rel="noreferrer" rel="nofollow noreferrer">Framework Design Guidelines</a>.</p> <p>The main reasoning behind the preference for abstract base classes is versioning, because you can always add a new virtual member to an abstract base class without breaking existing clients. That's not possible with interfaces.</p> <p>There are scenarios where an interface is still the correct choice (particularly when you don't care about versioning), but being aware of the advantages and disadvantages enables you to make the correct decision.</p> <p>So as a partial answer before I continue: Having both an interface and a base class only makes sense if you decide to code against an interface in the first place. If you allow an interface, you must code against that interface only, since otherwise you would be violating the Liskov Substitution Principle. In other words, even if you provide a base class that implements the interface, you cannot let your code consume that base class.</p> <p>If you decide to code against a base class, having an interface makes no sense.</p> <p>If you decide to code against an interface, having a base class that provides default functionality is optional. It is not necessary, but may speed up things for implementers, so you can provide one as a courtesy.</p> <p>An example that springs to mind is in ASP.NET MVC. The request pipeline works on IController, but there's a Controller base class that you typically use to implement behavior.</p> <p>Final answer: If using an abstract base class, use only that. If using an interface, a base class is an optional courtesy to implementers.</p> <hr> <p><strong>Update:</strong> I <em>no longer</em> prefer abstract classes over interfaces, and I haven't for a long time; instead, I favour composition over inheritance, using SOLID as a guideline.</p> <p>(While I could edit the above text directly, it would radically change the nature of the post, and since a few people have found it valuable enough to up-vote it, I'd rather let the original text stand, and instead add this note. The latter part of the post is still meaningful, so it would be a shame to delete it, too.)</p>
611,704
How can I achieve a consistent layout in all browsers?
<p>I'm near ending the repetitive alarms at my <a href="http://www.my-clock.net" rel="nofollow noreferrer">little learning project</a>. It's still full of bugs, but as it is a weekend project I'm correcting them slowly. My problem is inconsistency of layout across browsers.</p> <p>At the moment, I'm trying to improve the &quot;<code>My Alarms</code>&quot; box after login (Just don't try to hack my website, it's still very unstable).</p> <h3>Question</h3> <p>What kind of tricks, hacks, tips, etc. can you give me to ensure cross-browser layout compatibility?</p>
611,713
8
1
2009-03-09 11:56:35.933 UTC
2009-03-04 17:52:40.657 UTC
11
2010-07-10 00:35:15.507 UTC
2020-06-20 09:12:55.06 UTC
null
-1
fmsf
26,004
null
1
18
javascript|jquery|html|css
2,638
<p>I find the best policy to avoid pain is to follow these rules:</p> <ol> <li>Build in a more-compliant and developer-friendly browser like firefox first, test thoroughly in IE (and safari/chrome(webkit) and opera) periodically.</li> <li>Use a strict doctype- you don't necessarily need <em>perfect</em> markup, but it should be very good &mdash; good enough to avoid browser quirks modes, since quirks are by definition not standard</li> <li>Use a <a href="https://stackoverflow.com/questions/167531/is-it-ok-to-use-a-css-reset-stylesheet">reset style sheet</a>. Note that depending on the sheet's contents this item may be incompatible with the goal of #2.</li> <li>Use a javascript framework like jQuery or Prototype - they can hide some javascript and DOM incompatibilities.</li> <li>Use good semantic layout- it's more likely to degrade nicely for a mis-behaving browser</li> <li>Accept that it won't be perfect and don't sweat the really small variances</li> </ol> <p>Follow those rules and there aren't as many problems in the first place.</p> <p>For a TODO reference, see this question:<br> <a href="https://stackoverflow.com/questions/72394/what-should-a-developer-know-before-building-a-public-web-site">https://stackoverflow.com/questions/72394/what-should-a-developer-know-before-building-a-public-web-site</a></p>
299,437
Visual Studio - tips for managing work on many open files
<p>How do you feel about VS making you hunt for a tab that you used just minutes ago when you have a bazillion open tabs? What about constantly dragging tabs around to keep the ones you use close together?</p> <p>Oh, so you think <em>AARGH</em>, too? Then read on.</p> <p>I work on a piece of software with dozens of projects and hundreds of files. It's really easy to get the tab bar to fill up - like when debugging, which can open a lot of files, most of which are just boilerplate, or not really interesting for the task at hand.<br> This makes the few files that are <em>relevant</em> to 'fall off' the tab bar, or a pain to find by skimming the visible tabs. </p> <p>There are some solutions, some more widely known than others. Here's my top 3:</p> <p><strong>III.</strong> This works if you can <strong>exactly</strong> remember the file name (or at least the first letters): use the 'find box':</p> <pre><code>type: Ctrl-D &gt;of yourFileName </code></pre> <p>As you type the file name, you get autocomplete on the file names in the solution. More details <a href="http://www.alteridem.net/2007/09/11/quickly-findopen-a-file-in-visual-studio/" rel="noreferrer">here</a>.</p> <p><strong>II.</strong> The most obvious one: using the 'active files' drop-down on the right of the tab bar which is alphabetically ordered. <br> Lesser known fact: use <strong><code>Ctrl-Alt-DownArrow</code></strong> to open that drop-down, then start typing the file name. You get the added benefit of visualizing the available choices. [info shamelessly stolen from <a href="http://www.chinhdo.com/20070920/top-11-visual-studio-2005-ide-tips-and-tricks-to-make-you-a-more-productive-developer/" rel="noreferrer">here</a>]</p> <p><strong>I.</strong> <code>&lt;drum roll/&gt;</code> This one is my personal favourite, and it's based on an undocumented feature of VS 2005/2008. When activated, it does one simple thing: clicking a tab moves it to the left-most side of the window. This basic action usually lets me find the tab I'm looking for in the first 3 to 5 tabs. It goes like this:</p> <p><em>removed dead ImageShack link - sample animation</em></p> <p>In order to enable this functionality, you have to get your hands dirty with the Windows registry.<br> Compulsory edit-registry-at-your-own-risk warning: <br><em>Editing the registry may make your network card drop packets on the floor. You have been warned.</em> </p> <p>Add this key to the registry for VS 2005:</p> <pre><code>[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\8.0] "UseMRUDocOrdering"=dword:00000001 </code></pre> <p>or this for VS 2008:</p> <pre><code>[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\9.0] "UseMRUDocOrdering"=dword:00000001 </code></pre> <p>You don't even have to restart VS to see it work! [plagiarized from <a href="http://blogs.msdn.com/msbuild/archive/2007/04/13/window-tab-management-in-visual-studio.aspx" rel="noreferrer">here</a>]<br> Now go on, give it a try! </p> <p><strong>Update:</strong> This trick no longer works in VS2010 Pro :(</p> <hr> <p>This wraps up my part. Now it's your turn to share how you deal with tab hunting!</p>
300,154
8
5
null
2008-11-18 17:17:10.307 UTC
12
2021-07-08 01:31:49.497 UTC
2015-08-24 17:05:37.263 UTC
null
4,374,739
Cristi Diaconescu
11,545
null
1
29
visual-studio|tabs
20,249
<p>ReSharper and its Recent Files feature works a lot better for me.</p>
1,194,309
Why are many ports of languages to .net prefixed with 'Iron'?
<p>Was discussing over lunch why several ports of languages to the .net framework are prefixed with 'Iron'.</p> <p>e.g.</p> <ul> <li>IronPython</li> <li>IronRuby</li> <li>IronLisp </li> <li>IronScheme</li> <li>IronPHP</li> </ul> <p>Anyone out there know?</p> <p>(language list sourced from <a href="http://www.dotnetpowered.com/languages.aspx" rel="noreferrer">http://www.dotnetpowered.com/languages.aspx</a>)</p>
1,194,349
8
1
null
2009-07-28 14:03:23.807 UTC
8
2017-03-06 03:12:57.33 UTC
2017-03-06 03:12:57.33 UTC
null
23,528
null
83,083
null
1
50
.net|naming-conventions
3,836
<p>IronPython came first and the rest followed. As for why IronPython is called IronPython, Jim Hugunin goes into that in <a href="http://channel9.msdn.com/pdc2008/TL10/" rel="noreferrer">this video</a> (at about 14:00). He says it was partly to avoid calling it Language.NET or Language#, and the idea is that Iron languages are:</p> <ul> <li><p>True language implementations</p> <ul> <li>True to the language</li> <li>True to the community</li> <li>True to the experience</li> <li>Excellent performance</li> </ul></li> <li><p>Great integration with .NET</p> <ul> <li>Easy to use .NET libraries</li> <li>Easy to use other .NET languages</li> <li>Easy to use in .NET hosts</li> <li>Easy to use with .NET tools</li> </ul></li> </ul> <p>And a slightly specious acronym explanation, which came after the name:</p> <p><strong>I</strong>mplementation <strong>R</strong>unning <strong>O</strong>n .<strong>N</strong>ET.</p>
73,781
Sending mail via sendmail from python
<p>If I want to send mail not via SMTP, but rather via sendmail, is there a library for python that encapsulates this process?</p> <p>Better yet, is there a good library that abstracts the whole 'sendmail -versus- smtp' choice?</p> <p>I'll be running this script on a bunch of unix hosts, only some of which are listening on localhost:25; a few of these are part of embedded systems and can't be set up to accept SMTP.</p> <p>As part of Good Practice, I'd really like to have the library take care of header injection vulnerabilities itself -- so just dumping a string to <code>popen('/usr/bin/sendmail', 'w')</code> is a little closer to the metal than I'd like.</p> <p>If the answer is 'go write a library,' so be it ;-)</p>
74,084
8
0
null
2008-09-16 15:46:43.1 UTC
21
2020-11-02 13:14:24.787 UTC
2008-09-16 16:03:56.803 UTC
null
12,779
null
12,779
null
1
81
python|email|sendmail
90,322
<p>Header injection isn't a factor in how you send the mail, it's a factor in how you construct the mail. Check the <a href="https://docs.python.org/2/library/email.html" rel="noreferrer">email</a> package, construct the mail with that, serialise it, and send it to <code>/usr/sbin/sendmail</code> using the <a href="https://docs.python.org/2/library/subprocess.html" rel="noreferrer">subprocess</a> module:</p> <pre><code>import sys from email.mime.text import MIMEText from subprocess import Popen, PIPE msg = MIMEText(&quot;Here is the body of my message&quot;) msg[&quot;From&quot;] = &quot;[email protected]&quot; msg[&quot;To&quot;] = &quot;[email protected]&quot; msg[&quot;Subject&quot;] = &quot;This is the subject.&quot; p = Popen([&quot;/usr/sbin/sendmail&quot;, &quot;-t&quot;, &quot;-oi&quot;], stdin=PIPE) # Both Python 2.X and 3.X p.communicate(msg.as_bytes() if sys.version_info &gt;= (3,0) else msg.as_string()) # Python 2.X p.communicate(msg.as_string()) # Python 3.X p.communicate(msg.as_bytes()) </code></pre>
386,294
What is the maximum length of a valid email address?
<p>What is the maximum length of a valid email address? Is it defined by any standard?</p>
574,698
8
2
null
2008-12-22 13:57:54.06 UTC
251
2021-11-10 07:09:42.177 UTC
2014-01-07 14:17:29.533 UTC
null
771,978
volatilevoid
20,305
null
1
1,161
validation|email|max|email-address
457,544
<p>An email address must not exceed <strong>254</strong> characters.</p> <p>This was accepted by the IETF following <a href="http://www.rfc-editor.org/errata_search.php?rfc=3696&amp;eid=1690" rel="noreferrer">submitted erratum</a>. A full diagnosis of any given address is available <a href="http://isemail.info/" rel="noreferrer">online</a>. The original version of RFC 3696 described 320 as the maximum length, but John Klensin subsequently accepted an incorrect value, since a Path is defined as</p> <pre><code>Path = &quot;&lt;&quot; [ A-d-l &quot;:&quot; ] Mailbox &quot;&gt;&quot; </code></pre> <p>So the Mailbox element (i.e., the email address) has angle brackets around it to form a Path, which a maximum length of 254 characters to restrict the Path length to 256 characters or fewer.</p> <p>The maximum length specified in <a href="https://www.rfc-editor.org/rfc/rfc5321#section-4.5.3" rel="noreferrer">RFC 5321</a> states:</p> <blockquote> <p>The maximum total length of a reverse-path or forward-path is 256 characters.</p> </blockquote> <p>RFC 3696 was corrected <a href="http://www.rfc-editor.org/errata_search.php?rfc=3696" rel="noreferrer">here</a>.</p> <p>People should be aware of the <a href="http://www.rfc-editor.org/errata_search.php?rfc=3696" rel="noreferrer">errata against RFC 3696</a> in particular. Three of the canonical examples are in fact invalid addresses.</p> <p>I've collated a couple hundred test addresses, which you can find at <a href="http://www.dominicsayers.com/isemail" rel="noreferrer">http://www.dominicsayers.com/isemail</a></p>
264,720
gdi+ Graphics::DrawImage really slow~~
<p>I am using a GDI+ Graphic to draw a 4000*3000 image to screen, but it is really slow. It takes about 300ms. I wish it just occupy less than 10ms.</p> <pre><code>Bitmap *bitmap = Bitmap::FromFile("XXXX",...); </code></pre> <p>//-------------------------------------------- // this part takes about 300ms, terrible!</p> <pre><code>int width = bitmap-&gt;GetWidth(); int height = bitmap-&gt;GetHeight(); DrawImage(bitmap,0,0,width,height); </code></pre> <p>//------------------------------------------</p> <p>I cannot use CachedBitmap, because I want to edit the bitmap later.</p> <p>How can I improve it? Or is any thing wrong? </p> <p>This native GDI function also draws the image into the screen, and it just take 1 ms:</p> <pre><code>SetStretchBltMode(hDC, COLORONCOLOR); StretchDIBits(hDC, rcDest.left, rcDest.top, rcDest.right-rcDest.left, rcDest.bottom-rcDest.top, 0, 0, width, height, BYTE* dib, dibinfo, DIB_RGB_COLORS, SRCCOPY); </code></pre> <p>//--------------------------------------------------------------</p> <p>If I want to use StretchDIBits, I need to pass BITMAPINFO, But how can I get BITMAPINFO from a Gdi+ Bitmap Object? I did the experiment by FreeImage lib, I call StretchDIBits using FreeImageplus object, it draw really fast. But now I need to draw Bitmap, and write some algorithm on Bitmap's bits array, how can I get BITMAPINFO if I have an Bitmap object? It's really annoying -___________-|</p>
264,818
9
4
null
2008-11-05 09:53:15.267 UTC
10
2020-02-17 08:11:00.923 UTC
2009-10-24 12:49:51.333 UTC
null
12,597
null
25,749
null
1
18
gdi+|performance|drawimage
24,903
<p>You have a screen of 4000 x 3000 resolution? Wow!</p> <p>If not, you should draw only the visible part of the image, it would be much faster...</p> <p>[EDIT after first comment] My remark is indeed a bit stupid, I suppose DrawImage will mask/skip unneeded pixels.</p> <p>After your edit (showing StretchDIBits), I guess a possible source of speed difference might come from the fact that <a href="http://msdn.microsoft.com/en-us/library/ms532289.aspx" rel="nofollow noreferrer" title="StretchDIBits">StretchDIBits</a> is hardware accelerated ("<em>If the driver cannot support the JPEG or PNG file image</em>" is a hint...) while DrawImage might be (I have no proof for that!) coded in C, relying on CPU power instead of GPU's one...</p> <p>If I recall correctly, DIB images are fast (despite being "device independent"). See <a href="http://www.drdobbs.com/cpp/184403210?pgno=5" rel="nofollow noreferrer" title="High Speed Win32 Animation">High Speed Win32 Animation</a>: "<em>use CreateDIBSection to do high speed animation</em>". OK, it applies to DIB vs. GDI, in old Windows version (1996!) but I think it is still true.</p> <p>[EDIT] Maybe <a href="http://msdn.microsoft.com/en-us/library/ms536295(VS.85).aspx" rel="nofollow noreferrer">Bitmap::GetHBITMAP</a> function might help you to use StretchDIBits (not tested...).</p>
193,092
C# - How to add an Excel Worksheet programmatically - Office XP / 2003
<p>I am just starting to fiddle with Excel via C# to be able to automate the creation, and addition to an Excel file.</p> <p>I can open the file and update its data and move through the existing worksheets. My problem is how can I add new sheets?</p> <p>I tried:</p> <pre><code>Excel.Worksheet newWorksheet; newWorksheet = (Excel.Worksheet)excelApp.ThisWorkbook.Worksheets.Add( Type.Missing, Type.Missing, Type.Missing, Type.Missing); </code></pre> <p>But I get below <em>COM Exception</em> and my googling has not given me any answer.</p> <blockquote> <p>Exception from HRESULT: 0x800A03EC Source is: "Interop.Excel"</p> </blockquote> <p>I am hoping someone maybe able to put me out of my misery.</p>
193,323
9
1
null
2008-10-10 21:30:56.227 UTC
11
2017-08-22 13:57:18.957 UTC
2017-08-22 13:47:17.343 UTC
null
4,519,059
Jon
6,486
null
1
24
c#|excel|com|office-interop|worksheet
111,007
<p>You need to add a COM reference in your project to the <strong>"<code>Microsoft Excel 11.0 Object Library</code>"</strong> - or whatever version is appropriate.</p> <p>This code works for me:</p> <pre><code>private void AddWorksheetToExcelWorkbook(string fullFilename,string worksheetName) { Microsoft.Office.Interop.Excel.Application xlApp = null; Workbook xlWorkbook = null; Sheets xlSheets = null; Worksheet xlNewSheet = null; try { xlApp = new Microsoft.Office.Interop.Excel.Application(); if (xlApp == null) return; // Uncomment the line below if you want to see what's happening in Excel // xlApp.Visible = true; xlWorkbook = xlApp.Workbooks.Open(fullFilename, 0, false, 5, "", "", false, XlPlatform.xlWindows, "", true, false, 0, true, false, false); xlSheets = xlWorkbook.Sheets as Sheets; // The first argument below inserts the new worksheet as the first one xlNewSheet = (Worksheet)xlSheets.Add(xlSheets[1], Type.Missing, Type.Missing, Type.Missing); xlNewSheet.Name = worksheetName; xlWorkbook.Save(); xlWorkbook.Close(Type.Missing,Type.Missing,Type.Missing); xlApp.Quit(); } finally { Marshal.ReleaseComObject(xlNewSheet); Marshal.ReleaseComObject(xlSheets); Marshal.ReleaseComObject(xlWorkbook); Marshal.ReleaseComObject(xlApp); xlApp = null; } } </code></pre> <blockquote> <p>Note that you want to be very careful about <a href="https://stackoverflow.com/questions/158706/how-to-properly-clean-up-excel-interop-objects-in-c">properly cleaning up and releasing your COM object references</a>. Included in that StackOverflow question is a useful rule of thumb: <em>"Never use 2 dots with COM objects"</em>. In your code; you're going to have real trouble with that. <em>My demo code above does NOT properly clean up the Excel app, but it's a start!</em></p> </blockquote> <p>Some other links that I found useful when looking into this question:</p> <ul> <li><a href="http://www.codeproject.com/KB/office/csharp_excel.aspx" rel="nofollow noreferrer">Opening and Navigating Excel with C#</a></li> <li><a href="http://msdn.microsoft.com/en-us/library/ms173186(VS.80).aspx" rel="nofollow noreferrer">How to: Use COM Interop to Create an Excel Spreadsheet (C# Programming Guide)</a></li> <li><a href="http://msdn.microsoft.com/en-us/library/6fczc37s(VS.80).aspx" rel="nofollow noreferrer">How to: Add New Worksheets to Workbooks</a></li> </ul> <p>According to MSDN </p> <blockquote> <p>To use COM interop, you must have administrator or Power User security permissions.</p> </blockquote> <p>Hope that helps.</p>
647,969
Detect exact OS version from browser
<p>I was wondering if there is a way I can detect the exact Operating System version from my browser using PHP/JS/ASP?</p> <p>I know I can detect the type of OS (Windows XP,Windows Vista,OS X,etc) but I need to detect the exact version: Vista Business, Vista Ultimate, Windows XP Home, Windows XP Pro, etc...</p>
647,979
11
0
null
2009-03-15 15:19:51.96 UTC
7
2017-05-22 07:29:38.357 UTC
2014-03-04 10:06:04.537 UTC
Vasil
2,123,139
Roy Peleg
59,361
null
1
18
php|javascript|browser
57,972
<p><strong>Short answer:</strong> You can't.</p> <p><strong>Long answer:</strong></p> <p>All you have is the information in the HTTP User-Agent header, which usually contains the OS name and version.</p> <p>Usually, browsers running on Mac OS and Linux send enough information to identify the exact OS. For example, here's my User-Agent header:</p> <blockquote> <p>Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.0.7) Gecko/2009030423 Ubuntu/8.10 (intrepid) Firefox/3.0.7</p> </blockquote> <p>You can see that I'm running Ubuntu 8.10 Intrepid Ibex.</p> <p>And here's what Firefox and Safari 4 Beta report on my MacBook Pro:</p> <blockquote> <p>Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.0.7) Gecko/2009021906 Firefox/3.0.7</p> <p>Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_5_6; en-us) AppleWebKit/528.16 (KHTML, like Gecko) Version/4.0 Safari/528.16</p> </blockquote> <p>Windows browsers, on the other hand, usually only report the OS version and not the specific package (Pro, Business, etc.):</p> <blockquote> <p>Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:x.x.x) Gecko/20041107 Firefox/x.x</p> </blockquote>
222,017
what is JMS good for?
<p>I'm looking for (simple) examples of problems for which JMS is a good solution, and also reasons why JMS is a good solution in these cases. In the past I've simply used the database as a means of passing messages from A to B when the message cannot necessarily be processed by B immediately.</p> <p>A hypothetical example of such a system is where all newly registered users should be sent a welcome e-mail within 24 hours of registration. For the sake of argument, assume the DB does not record the time when each user registered, but instead a reference (foreign key) to each new user is stored in the pending_email table. The e-mail sender job runs once every 24 hours, sends an e-mail to all the users in this table, then deletes all the pending_email records.</p> <p>This seems like the kind of problem for which JMS should be used, but it's not clear to me what benefit JMS would have over the approach I've described. One advantage of the DB approach is that the messages are persistent. I understand that JMS message queues can also be persisted, but in that case there seems to be little difference between JMS and the "database as message queue" approach I've described?</p> <p>What am I missing? - Don</p>
222,215
11
1
null
2008-10-21 14:11:33.203 UTC
37
2018-09-23 17:16:21.47 UTC
null
null
null
Don
2,648
null
1
71
java|jms|messaging
30,113
<p>JMS and messaging is really about 2 totally different things.</p> <ul> <li>publish and subscribe (sending a message to as many consumers as are interested - a bit like sending an email to a mailing list, the sender does not need to know who is subscribed</li> <li>high performance reliable load balancing (message queues)</li> </ul> <p>See more info on <a href="http://activemq.apache.org/how-does-a-queue-compare-to-a-topic.html" rel="noreferrer">how a queue compares to a topic</a></p> <p>The case you are talking about is the second case, where yes you can use a database table to kinda simulate a message queue. </p> <p>The main difference is a JMS message queue is a high performance highly concurrent load balancer designed for huge throughput; you can send usually tens of thousands of messages per second to many concurrent consumers in many processes and threads. The reason for this is that a message queue is basically highly asynchronous - a <a href="http://activemq.apache.org/what-is-the-prefetch-limit-for.html" rel="noreferrer">good JMS provider will stream messages ahead of time to each consumer</a> so that there are thousands of messages available to be processed in RAM as soon as a consumer is available. This leads to massive throughtput and very low latency.</p> <p>e.g. imagine writing a web load balancer using a database table :)</p> <p>When using a database table, typically one thread tends to lock the whole table so you tend to get very low throughput when trying to implement a high performance load balancer.</p> <p>But like most middleware it all depends on what you need; if you've a low throughput system with only a few messages per second - feel free to use a database table as a queue. But if you need low latency and high throughput - then JMS queues are highly recommended.</p>
586,436
Double.TryParse or Convert.ToDouble - which is faster and safer?
<p>My application reads an Excel file using VSTO and adds the read data to a <code>StringDictionary</code>. It adds only data that are numbers with a few digits (1000 1000,2 1000,34 - comma is a delimiter in Russian standards).</p> <p>What is better to check if the current string is an appropriate number?</p> <pre><code>object data, string key; // data had read try { Convert.ToDouble(regionData, CultureInfo.CurrentCulture); dic.Add(key, regionData.ToString()); } catch (InvalidCastException) { // is not a number } </code></pre> <p>or</p> <pre><code>double d; string str = data.ToString(); if (Double.TryParse(str, out d)) // if done, then is a number { dic.Add(key, str); } </code></pre> <p>I have to use <code>StringDictionary</code> instead of <code>Dictionary&lt;string, double&gt;</code> because of the following parsing algorithm issues.</p> <p>My questions: Which way is faster? Which is safer?</p> <p>And is it better to call <code>Convert.ToDouble(object)</code> or <code>Convert.ToDouble(string)</code> ?</p>
586,539
11
2
null
2009-02-25 15:23:35.007 UTC
13
2018-12-05 02:02:36.78 UTC
2014-10-09 07:26:29.887 UTC
null
4,090,370
abatishchev
41,956
null
1
81
c#|.net|parsing|double
122,275
<p>I did a quick non-scientific test in Release mode. I used two inputs: "2.34523" and "badinput" into both methods and iterated 1,000,000 times.</p> <p>Valid input:</p> <pre><code>Double.TryParse = 646ms Convert.ToDouble = 662 ms </code></pre> <p>Not much different, as expected. For all intents and purposes, for valid input, these are the same.</p> <p>Invalid input:</p> <pre><code>Double.TryParse = 612ms Convert.ToDouble = .. </code></pre> <p>Well.. it was running for a long time. I reran the entire thing using 1,000 iterations and <code>Convert.ToDouble</code> with bad input took 8.3 seconds. Averaging it out, it would take over 2 hours. I don't care how basic the test is, in the invalid input case, <code>Convert.ToDouble</code>'s exception raising will ruin your performance.</p> <p>So, here's another vote for <code>TryParse</code> with some numbers to back it up.</p>
129,036
Unit testing code with a file system dependency
<p>I am writing a component that, given a ZIP file, needs to:</p> <ol> <li>Unzip the file.</li> <li>Find a specific dll among the unzipped files.</li> <li>Load that dll through reflection and invoke a method on it.</li> </ol> <p>I'd like to unit test this component.</p> <p>I'm tempted to write code that deals directly with the file system:</p> <pre class="lang-cs prettyprint-override"><code>void DoIt() { Zip.Unzip(theZipFile, "C:\\foo\\Unzipped"); System.IO.File myDll = File.Open("C:\\foo\\Unzipped\\SuperSecret.bar"); myDll.InvokeSomeSpecialMethod(); } </code></pre> <p>But folks often say, "Don't write unit tests that rely on the file system, database, network, etc."</p> <p>If I were to write this in a unit-test friendly way, I suppose it would look like this:</p> <pre class="lang-cs prettyprint-override"><code>void DoIt(IZipper zipper, IFileSystem fileSystem, IDllRunner runner) { string path = zipper.Unzip(theZipFile); IFakeFile file = fileSystem.Open(path); runner.Run(file); } </code></pre> <p>Yay! Now it's testable; I can feed in test doubles (mocks) to the DoIt method. But at what cost? I've now had to define 3 new interfaces just to make this testable. And what, exactly, am I testing? I'm testing that my DoIt function properly interacts with its dependencies. It doesn't test that the zip file was unzipped properly, etc.</p> <p>It doesn't feel like I'm testing functionality anymore. It feels like I'm just testing class interactions.</p> <p><strong>My question is this</strong>: what's the proper way to unit test something that is dependent on the file system?</p> <p><em>edit</em> I'm using .NET, but the concept could apply Java or native code too.</p>
129,204
11
2
null
2008-09-24 18:46:56.943 UTC
39
2016-12-07 13:07:57.163 UTC
2016-12-07 13:06:44.197 UTC
Judah Himango
452,775
Judah Himango
536
null
1
153
unit-testing|dependency-injection|dependencies
55,088
<p>There's really nothing wrong with this, it's just a question of whether you call it a unit test or an integration test. You just have to make sure that if you do interact with the file system, there are no unintended side effects. Specifically, make sure that you clean up after youself -- delete any temporary files you created -- and that you don't accidentally overwrite an existing file that happened to have the same filename as a temporary file you were using. Always use relative paths and not absolute paths.</p> <p>It would also be a good idea to <code>chdir()</code> into a temporary directory before running your test, and <code>chdir()</code> back afterwards.</p>
855,139
How can I get a row count in DBI without running two separate calls to process?
<p>I'm running DBI in Perl and can't figure out how, when I run a prepared statement, I can figure out if the returned row count is 0.</p> <p>I realize I can set a counter inside my while loop where I fetch my rows, but I was hoping there was a less ugly way to do it.</p>
860,479
12
0
null
2009-05-12 22:13:24.953 UTC
null
2021-01-13 11:35:37.383 UTC
2010-02-25 01:19:49.863 UTC
null
2,766,176
null
59,947
null
1
12
perl|dbi
45,379
<p>In order to find out how many rows are in a result set you have exactly two options:</p> <ol> <li><code>select count(*)</code></li> <li>Iterate over the result set and count the rows.</li> </ol> <p>You can introduce some magic via a stored procedure that returns an array or something more fancy, but ultimately one of those two things will need to happen.</p> <p>So, there is no fancypants way to get that result. You just have to count them :-)</p>
1,065,774
Initialization of all elements of an array to one default value in C++?
<p><a href="http://www.fredosaurus.com/notes-cpp/arrayptr/array-initialization.html" rel="noreferrer">C++ Notes: Array Initialization</a> has a nice list over initialization of arrays. I have a</p> <pre><code>int array[100] = {-1}; </code></pre> <p>expecting it to be full with -1's but its not, only first value is and the rest are 0's mixed with random values.</p> <p>The code</p> <pre><code>int array[100] = {0}; </code></pre> <p>works just fine and sets each element to 0.</p> <p>What am I missing here.. Can't one initialize it if the value isn't zero ?</p> <p>And 2: Is the default initialization (as above) faster than the usual loop through the whole array and assign a value or does it do the same thing?</p>
1,065,800
12
6
null
2009-06-30 20:10:25.1 UTC
120
2022-09-22 22:20:49.367 UTC
2020-02-26 16:10:40.8 UTC
null
12,139,179
null
62,570
null
1
312
c++|arrays|initialization|variable-assignment|default-value
538,407
<p>Using the syntax that you used,</p> <pre><code>int array[100] = {-1}; </code></pre> <p>says "set the first element to <code>-1</code> and the rest to <code>0</code>" since all omitted elements are set to <code>0</code>.</p> <p>In C++, to set them all to <code>-1</code>, you can use something like <a href="http://en.cppreference.com/w/cpp/algorithm/fill_n" rel="noreferrer"><code>std::fill_n</code></a> (from <code>&lt;algorithm&gt;</code>):</p> <pre><code>std::fill_n(array, 100, -1); </code></pre> <p>In portable C, you have to roll your own loop. There are compiler-extensions or you can depend on implementation-defined behavior as a shortcut if that's acceptable.</p>
98,610
How can I get Eclipse to show .* files?
<p>By default, Eclipse won't show my .htaccess file that I maintain in my project. It just shows an empty folder in the Package Viewer tree. How can I get it to show up? No obvious preferences.</p>
98,634
13
0
null
2008-09-19 01:23:28.97 UTC
81
2021-02-20 12:10:18.723 UTC
2008-09-19 01:37:21.26 UTC
jodonnell
4,223
jodonnell
4,223
null
1
535
eclipse|file|hidden
196,543
<p>In the package explorer, in the upper right corner of the view, there is a little down arrow. Tool tip will say view menu. From that menu, select filters</p> <p><img src="https://i.stack.imgur.com/NWo2x.jpg" alt="filters menu"></p> <p>From there, uncheck .* resources.</p> <p>So <code>Package Explorer -&gt; View Menu -&gt; Filters -&gt; uncheck .* resources</code>.</p> <p>With Eclipse Kepler and OS X this is a bit different:</p> <pre><code>Package Explorer -&gt; Customize View -&gt; Filters -&gt; uncheck .* resources </code></pre>
660,554
How to automatically select all text on focus in WPF TextBox?
<p>If I call <code>SelectAll</code> from a <code>GotFocus</code> event handler, it doesn't work with the mouse - the selection disappears as soon as mouse is released.</p> <p>EDIT: People are liking Donnelle's answer, I'll try to explain why I did not like it as much as the accepted answer.</p> <ul> <li>It is more complex, while the accepted answer does the same thing in a simpler way.</li> <li>The usability of accepted answer is better. When you click in the middle of the text, text gets unselected when you release the mouse allowing you to start editing instantly, and if you still want to select all, just press the button again and this time it will not unselect on release. Following Donelle's recipe, if I click in the middle of text, I have to click second time to be able to edit. If I click somewhere within the text versus outside of the text, this most probably means I want to start editing instead of overwriting everything.</li> </ul>
660,617
34
6
null
2009-03-18 23:54:50.507 UTC
81
2022-09-04 04:16:49.407 UTC
2014-12-08 15:13:28.91 UTC
null
1,278,704
saldoukhov
58,463
null
1
256
.net|wpf|silverlight|textbox
169,322
<p>Don't know why it loses the selection in the <code>GotFocus</code> event.</p> <p>But one solution is to do the selection on the <code>GotKeyboardFocus</code> and the <code>GotMouseCapture</code> events. That way it will always work.</p> <p>-- Edit --</p> <p>Adding an example here to show people how to work around some the mentioned drawbacks:</p> <pre><code>private void TextBox_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) { // Fixes issue when clicking cut/copy/paste in context menu if (textBox.SelectionLength == 0) textBox.SelectAll(); } private void TextBox_LostMouseCapture(object sender, MouseEventArgs e) { // If user highlights some text, don't override it if (textBox.SelectionLength == 0) textBox.SelectAll(); // further clicks will not select all textBox.LostMouseCapture -= TextBox_LostMouseCapture; } private void TextBox_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) { // once we've left the TextBox, return the select all behavior textBox.LostMouseCapture += TextBox_LostMouseCapture; } </code></pre>
34,552,653
Execute terminal commands in python3
<p>I am on a Raspberry Pi, and I am using a program called <code>fswebcam</code>, which allows you to take pictures with a webcam.</p> <pre><code>~$ fswebcam image.jpg </code></pre> <p>That command if entered in terminal takes a picture and saves it to your computer, however I want to build a simple python program that can access the terminal and execute that same command as I have listed above.</p> <p>I have tried to <code>import os</code> and use <code>os.system('fswebcam image.jpg')</code> But it isn't working for me. </p> <p>How can I have python execute terminal commands?</p>
34,552,734
1
5
null
2016-01-01 00:21:42.613 UTC
3
2016-01-01 04:22:06.95 UTC
2016-01-01 04:22:06.95 UTC
null
4,279
null
5,597,730
null
1
43
python|python-3.x|raspberry-pi|subprocess|raspbian
14,525
<p>Use the subprocess module:</p> <pre><code>import subprocess subprocess.Popen(["fswebcam", "image.jpg"]) </code></pre>
34,731,869
Wait for Angular 2 to load/resolve model before rendering view/template
<p>In Angular 1.x, UI-Router was my primary tool for this. By returning a promise for "resolve" values, the router would simply wait for the promise to complete before rendering directives.</p> <p>Alternately, in Angular 1.x, a null object will not crash a template - so if I don't mind a temporarily incomplete render, I can just use <code>$digest</code> to render after the <code>promise.then()</code> populates an initially empty model object.</p> <p>Of the two approaches, if possible I'd prefer to wait to load the view, and cancel route navigation if the resource cannot be loaded. This saves me the work of "un-navigating". <em>EDIT: Note this specifically means this question requests an Angular 2 futures-compatible or best-practice method to do this, and asks to avoid the "Elvis operator" if possible! Thus, I did not select that answer.</em></p> <p>However, neither of these two methods work in Angular 2.0. Surely there is a standard solution planned or available for this. Does anyone know what it is?</p> <pre><code>@Component() { template: '{{cats.captchans.funniest}}' } export class CatsComponent { public cats: CatsModel; ngOnInit () { this._http.get('/api/v1/cats').subscribe(response =&gt; cats = response.json()); } } </code></pre> <p>The following question may reflect the same issue: <a href="https://stackoverflow.com/questions/33136954/angular-2-render-template-after-the-promise-with-data-is-loaded?rq=1">Angular 2 render template after the PROMISE with data is loaded</a> . Note that question has no code or accepted answer in it.</p>
38,212,664
6
7
null
2016-01-11 21:55:24.06 UTC
24
2018-06-21 07:30:44.103 UTC
2017-05-23 11:55:00.137 UTC
null
-1
null
608,220
null
1
75
angular|promise|observable|dependency-resolver
103,185
<p>The package <code>@angular/router</code> has the <code>Resolve</code> property for routes. So you can easily resolve data before rendering a route view.</p> <p>See: <a href="https://angular.io/docs/ts/latest/api/router/index/Resolve-interface.html" rel="noreferrer">https://angular.io/docs/ts/latest/api/router/index/Resolve-interface.html</a></p> <p>Example from docs as of today, August 28, 2017:</p> <pre><code>class Backend { fetchTeam(id: string) { return 'someTeam'; } } @Injectable() class TeamResolver implements Resolve&lt;Team&gt; { constructor(private backend: Backend) {} resolve( route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable&lt;any&gt;|Promise&lt;any&gt;|any { return this.backend.fetchTeam(route.params.id); } } @NgModule({ imports: [ RouterModule.forRoot([ { path: 'team/:id', component: TeamCmp, resolve: { team: TeamResolver } } ]) ], providers: [TeamResolver] }) class AppModule {} </code></pre> <p>Now your route will not be activated until the data has been resolved and returned.</p> <p><strong>Accessing Resolved Data In Your Component</strong></p> <p>To access the resolved data from within your component at runtime, there are two methods. So depending on your needs, you can use either:</p> <ol> <li><code>route.snapshot.paramMap</code> which returns a string, or the </li> <li><code>route.paramMap</code> which returns an Observable you can <code>.subscribe()</code> to. </li> </ol> <p>Example:</p> <pre><code> // the no-observable method this.dataYouResolved= this.route.snapshot.paramMap.get('id'); // console.debug(this.licenseNumber); // or the observable method this.route.paramMap .subscribe((params: ParamMap) =&gt; { // console.log(params); this.dataYouResolved= params.get('id'); return params.get('dataYouResolved'); // return null }); console.debug(this.dataYouResolved); </code></pre> <p>I hope that helps.</p>
6,865,185
javascript string compression with localStorage
<p>I am using <code>localStorage</code> in a project, and it will need to store <em>lots</em> of data, mostly of type int, bool and string. I know that javascript strings are unicode, but when stored in <code>localStorage</code>, do they stay unicode? If so, is there a way I could compress the string to use all of the data in a unicode byte, or should i just use base64 and have less compression? All of the data will be stored as one large string.</p> <p>EDIT: Now that I think about it, base64 wouldn't do much compression at all, the data is already in base 64, <code>a-zA-Z0-9 ;:</code> is 65 characters.</p>
7,411,549
5
8
null
2011-07-28 20:21:55.763 UTC
14
2013-06-11 08:39:17.817 UTC
2011-07-28 20:36:07.047 UTC
null
462,266
null
462,266
null
1
20
javascript|unicode|compression|base64|local-storage
11,739
<p><strong>"when stored in localStorage, do they stay unicode?"</strong></p> <p>The <a href="http://www.w3.org/TR/webstorage/#the-storage-interface" rel="nofollow noreferrer">Web Storage working draft</a> defines local storage values as DOMString. <a href="http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-C74D1578" rel="nofollow noreferrer">DOMStrings are defined</a> as sequences of 16-bit units using the <a href="http://en.wikipedia.org/wiki/UTF-16/UCS-2" rel="nofollow noreferrer">UTF-16 encoding</a>. So yes, they stay Unicode.</p> <p><strong>is there a way I could compress the string to use all of the data in a unicode byte</strong>...<strong>?</strong></p> <p>"Base32k" encoding should give you 15 bits per character. A base32k-type encoding takes advantage of the full 16 bits in UTF-16 characters, but loses a bit to avoid tripping on double-word characters. If your original data is base64 encoded, it only uses 6 bits per character. Encoding those 6 bits into base32k should compress it to 6/15 = 40% of its original size. See <a href="http://lists.xml.org/archives/xml-dev/200307/msg00505.html" rel="nofollow noreferrer">http://lists.xml.org/archives/xml-dev/200307/msg00505.html</a> and <a href="http://lists.xml.org/archives/xml-dev/200307/msg00507.html" rel="nofollow noreferrer">http://lists.xml.org/archives/xml-dev/200307/msg00507.html</a>.</p> <p>For even further reduction in size, you can decode your base64 strings into their full 8-bit binary, compress them with some known compression algorithm (e.g. see <a href="https://stackoverflow.com/questions/294297/javascript-implementation-of-gzip">javascript implementation of gzip</a>), and then base32k encode the compressed output.</p>
6,917,906
Return Type for jdbcTemplate.queryForList(sql, object, classType)
<p>I'm executing a named query using jdbcTemplate.queryForList in the following manner:</p> <pre><code>List&lt;Conversation&gt; conversations = jdbcTemplate.queryForList( SELECT_ALL_CONVERSATIONS_SQL_FULL, new Object[] {userId, dateFrom, dateTo}); </code></pre> <p>The SQL query is:</p> <pre><code>private final String SELECT_ALL_CONVERSATIONS_SQL_FULL = "select conversation.conversationID, conversation.room, " + "conversation.isExternal, conversation.startDate, " + "conversation.lastActivity, conversation.messageCount " + "from openfire.ofconversation conversation " + "WHERE conversation.conversationid IN " + "(SELECT conversation.conversationID " + "FROM openfire.ofconversation conversation, " + "openfire.ofconparticipant participant " + "WHERE conversation.conversationID = participant.conversationID " + "AND participant.bareJID LIKE ? " + "AND conversation.startDate between ? AND ?)"; </code></pre> <p>But when extracting the content of the list in the following manner: </p> <pre><code>for (Conversation conversation : conversations) { builder.append(conversation.getId()); builder.append(","); builder.append(conversation.getRoom()); builder.append(","); builder.append(conversation.getIsExternal()); builder.append(","); builder.append(conversation.getStartDate()); builder.append(","); builder.append(conversation.getEndDate()); builder.append(","); builder.append(conversation.getMsgCount()); out.write(builder.toString()); } </code></pre> <p>I get an error: </p> <pre><code>java.util.LinkedHashMap cannot be cast to net.org.messagehistory.model.Conversation </code></pre> <p>How do I convert this linkedMap into the desired Object??</p> <p>Thanks</p>
6,920,243
5
0
null
2011-08-02 20:03:59.623 UTC
11
2019-08-05 02:44:30.253 UTC
null
null
null
null
372,366
null
1
25
java|spring-ws|jdbctemplate
208,461
<p>In order to map a the result set of query to a particular Java class you'll probably be best (assuming you're interested in using the object elsewhere) off with a RowMapper to convert the columns in the result set into an object instance.</p> <p>See <a href="http://static.springsource.org/spring/docs/3.0.x/reference/jdbc.html" rel="noreferrer">Section 12.2.1.1 of Data access with JDBC</a> on how to use a row mapper.</p> <p>In short, you'll need something like:</p> <pre><code>List&lt;Conversation&gt; actors = jdbcTemplate.query( SELECT_ALL_CONVERSATIONS_SQL_FULL, new Object[] {userId, dateFrom, dateTo}, new RowMapper&lt;Conversation&gt;() { public Conversation mapRow(ResultSet rs, int rowNum) throws SQLException { Conversation c = new Conversation(); c.setId(rs.getLong(1)); c.setRoom(rs.getString(2)); [...] return c; } }); </code></pre>
6,919,292
pointerIndex out of range Android multitouch
<p>I have a touch event exception that is causing my game to crash on tablets (or more specifically, honeycomb)... My game works fine on my phone and I haven't heard of this happening to anyone that isn't running Android 3.0 or higher. Here is the relevant log info...</p> <pre><code>E/AndroidRuntime(26487): java.lang.IllegalArgumentException: pointerIndex out of range E/AndroidRuntime(26487): at android.view.MotionEvent.nativeGetAxisValue(Native Method) E/AndroidRuntime(26487): at android.view.MotionEvent.getX(MotionEvent.java:1549) E/AndroidRuntime(26487): at kieran.android.asteroids.GameUI.onTouchEvent(GameUI.java:665) E/AndroidRuntime(26487): at android.view.View.dispatchTouchEvent(View.java:4616) E/AndroidRuntime(26487): at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:1560) E/AndroidRuntime(26487): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1291) E/AndroidRuntime(26487): at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:1560) E/AndroidRuntime(26487): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1291) E/AndroidRuntime(26487): at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:1560) E/AndroidRuntime(26487): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1291) </code></pre> <p>... And here is the code that is calling it. Seems fine to me, but maybe there is a bug in honeycomb that hasn't been fixed yet? The line number 665 from the log above corresponds to the <code>float x = event.getX(id);</code> line. It must have something to do with the way I am getting the <code>which</code> variable maybe? But it works fine on the phones/2.3 and lower...</p> <pre><code>int action = event.getAction(); int actionCode = action &amp; MotionEvent.ACTION_MASK; if(actionCode == MotionEvent.ACTION_POINTER_UP || action == MotionEvent.ACTION_UP) { int which = action &gt;&gt; MotionEvent.ACTION_POINTER_ID_SHIFT; int id = event.getPointerId(which); float x = event.getX(id); float y = event.getY(id); </code></pre> <p>Any help/ideas would be greatly appreciated as I am trying to make my game available to tablet users as well. Thanks.</p>
7,339,216
6
1
null
2011-08-02 22:07:18.763 UTC
11
2021-12-21 13:47:52.16 UTC
2011-09-06 01:13:43.123 UTC
null
573,595
null
573,595
null
1
44
java|android|exception|multi-touch
47,172
<p>My problem was that it was actually calling event.getX(1) when there wasn't actually two ids. So I made sure that there were two ids with event.getPointerCount() >= 2 and it now works. Maybe you'll have the same luck!</p>
6,638,504
Why serve 1x1 pixel GIF (web bugs) data at all?
<p>Many analytic and tracking tools are requesting 1x1 GIF image (web bug, invisible for the user) for cross-domain event storing/processing.</p> <p><b>Why to serve this GIF image at all?</b> Wouldn't it be <b>more efficient</b> to simply return some error code such as <em>503 Service Temporary Unavailable</em> or empty file?</p> <p><em>Update:</em> To be more clear, I'm asking why to serve GIF image data when all information required <b>has been already sent</b> in request headers. The GIF image itself does not return any useful information.</p>
6,644,226
8
0
null
2011-07-10 01:00:44.8 UTC
49
2019-08-13 15:18:40.707 UTC
2011-07-13 13:51:35.427 UTC
null
172,322
null
154,467
null
1
83
javascript|html|google-analytics
39,516
<p>Doug's answer is pretty comprehensive; I thought I'd add in an additional note (at the OP's request, off of my comment)</p> <p>Doug's answer explains why 1x1 pixel beacons are used for the purpose they are used for; I thought I'd outline a potential alternative approach, which is to use HTTP Status Code 204, No Content, for a response, and not send an image body. </p> <blockquote> <p><strong>204 No Content</strong></p> <p>The server has fulfilled the request but does not need to return an entity-body, and might want to return updated metainformation. The response MAY include new or updated metainformation in the form of entity-headers, which if present SHOULD be associated with the requested variant.</p> </blockquote> <p>Basically, the server receives the request, and decides to not send a body (in this case, to not send an image). But it replies with a code to inform the agent that this was a conscious decision; basically, its just a shorter way to respond affirmatively. </p> <p>From <a href="http://code.google.com/speed/page-speed/docs/rtt.html" rel="noreferrer">Google's Page Speed documentation</a>:</p> <blockquote> <p>One popular way of recording page views in an asynchronous fashion is to include a JavaScript snippet at the bottom of the target page (or as an onload event handler), that notifies a logging server when a user loads the page. The most common way of doing this is to construct a request to the server for a "beacon", and encode all the data of interest as parameters in the URL for the beacon resource. To keep the HTTP response very small, a transparent 1x1-pixel image is a good candidate for a beacon request. A slightly more optimal beacon would use an HTTP 204 response ("no content") which is marginally smaller than a 1x1 GIF.</p> </blockquote> <p>I've never tried it, but in theory it should serve the same purpose without requiring the gif itself to be transmitted, saving you 35 bytes, in the case of Google Analytics. (In the scheme of things, unless you're Google Analytics serving many trillions of hits per day, 35 bytes is really nothing.)</p> <p>You can test it with this code:</p> <pre><code>var i = new Image(); i.src = "http://httpstat.us/204"; </code></pre>
6,490,252
Vertically centering a div inside another div
<p>I want to center a div which is inside another div.</p> <pre><code>&lt;div id=&quot;outerDiv&quot;&gt; &lt;div id=&quot;innerDiv&quot;&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>This is the CSS I am currently using.</p> <pre><code> #outerDiv { width: 500px; height: 500px; position: relative; } #innerDiv { width: 284px; height: 290px; position: absolute; top: 50%; left: 50%; margin-top: -147px; margin-left: -144px; } </code></pre> <p>As you can see, the approach I use now depends on the width and height of <code>#innerDiv</code>. If the width/height changes, I will have to modify the <code>margin-top</code> and <code>margin-left</code> values. Is there any generic solution that I can use to center the <code>#innerDiv</code> independently of its size?</p> <p>I figured out that using <code>margin: auto</code> can horizontally align the <code>#innerDiv</code> to the middle. But what about vertical alignment?</p>
6,490,283
24
4
null
2011-06-27 08:22:03.747 UTC
206
2021-12-01 07:03:49.627 UTC
2021-12-01 07:03:49.627 UTC
null
157,397
null
700,284
null
1
636
html|css
787,396
<p><a href="http://codepen.io/meodai/pen/XbEqZw?editors=010" rel="noreferrer"><strong>tl;dr</strong></a></p> <p>Vertical align middle works, but you will have to use <code>table-cell</code> on your parent element and <code>inline-block</code> on the child.</p> <p>This solution is not going to work in IE6 &amp; 7. <br>Yours is the safer way to go for those. <br>But since you tagged your question with CSS3 and HTML5 I was thinking that you don't mind using a modern solution.</p> <p><strong>The classic solution (table layout)</strong></p> <p>This was my original answer. It still works fine and is the solution with the widest support. Table-layout will <a href="http://www.stubbornella.org/content/2009/03/27/reflows-repaints-css-performance-making-your-javascript-slow/#tables" rel="noreferrer">impact your rendering performance</a> so I would suggest that you use one of the more modern solutions.</p> <p><a href="http://jsfiddle.net/mcSfe/" rel="noreferrer">Here is an example</a></p> <hr> <p><strong>Tested in:</strong> </p> <ul> <li>FF3.5+</li> <li>FF4+</li> <li>Safari 5+</li> <li>Chrome 11+</li> <li>IE9+</li> </ul> <hr> <p><strong>HTML</strong></p> <pre><code>&lt;div class="cn"&gt;&lt;div class="inner"&gt;your content&lt;/div&gt;&lt;/div&gt; </code></pre> <p><strong>CSS</strong></p> <pre><code>.cn { display: table-cell; width: 500px; height: 500px; vertical-align: middle; text-align: center; } .inner { display: inline-block; width: 200px; height: 200px; } </code></pre> <hr> <p><strong>Modern solution (transform)</strong></p> <p>Since transforms are <a href="http://caniuse.com/#search=2d%20transforms" rel="noreferrer">fairly well supported now</a> there is an easier way to do it.</p> <p><strong>CSS</strong></p> <pre><code>.cn { position: relative; width: 500px; height: 500px; } .inner { position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%); width: 200px; height: 200px; } </code></pre> <p><a href="http://jsfiddle.net/0tc6ycvo/1/" rel="noreferrer">Demo</a> </p> <hr> <p><strong>♥ my favourite modern solution (flexbox)</strong></p> <p>I started to use flexbox more and more <a href="http://caniuse.com/#search=flexbox" rel="noreferrer">its also well supported now</a> Its by far the easiest way.</p> <p><strong>CSS</strong></p> <pre><code>.cn { display: flex; justify-content: center; align-items: center; } </code></pre> <p><a href="http://codepen.io/meodai/pen/PqRebp?editors=110" rel="noreferrer">Demo</a></p> <p>More examples &amp; possibilities: <a href="http://codepen.io/meodai/pen/XbEqZw?editors=110" rel="noreferrer">Compare all the methods on one pages</a> </p>
15,868,114
How to add a device to an existing Ad-Hoc Provisioning Profile?
<p>Have just noticed that Apple redesigned iOS Dev Center this weekend.</p> <p>I need to add a couple of devices to an existing Ad-Hoc provisioning profile. But when I push Edit button, I can change only Name and App ID.</p> <p>Is it any way to do it except of the obvious one: to delete the existing profile and create a new one with all required devices?</p> <p><strong>UPD.</strong></p> <p>Now I can edit the list of devices for development profiles, but not for distribution.</p> <p><strong>UPD. 2</strong></p> <p>Can edit devices for new distribution profiles, but can't do it for old.</p>
15,895,247
3
3
null
2013-04-07 21:34:56.4 UTC
8
2013-04-09 12:40:31.473 UTC
2013-04-09 12:40:31.473 UTC
null
775,779
null
775,779
null
1
16
ios|provisioning-profile|ad-hoc-distribution
7,954
<h2>It Works!</h2> <p>Apple fixed it. So it was a bug. Now you can edit your embedded device list, even if it's an Ad Hoc distribution profile.</p>
15,804,425
Curl on Ruby on Rails
<p>how to use curl on ruby on rails? Like this one</p> <pre><code>curl -d 'params1[name]=name&amp;params2[email]' 'http://mydomain.com/file.json' </code></pre>
15,826,765
3
5
null
2013-04-04 06:53:15.693 UTC
4
2017-07-26 21:48:40.85 UTC
2013-10-07 11:00:46.607 UTC
null
1,077,754
null
1,522,983
null
1
17
ruby-on-rails|ruby-on-rails-3|curl|ruby-on-rails-3.1
38,840
<p>Just in case you don't know, it requires 'net/http'</p> <pre class="lang-rb prettyprint-override"><code>require 'net/http' uri = URI.parse("http://example.org") # Shortcut #response = Net::HTTP.post_form(uri, {"user[name]" =&gt; "testusername", "user[email]" =&gt; "[email protected]"}) # Full control http = Net::HTTP.new(uri.host, uri.port) request = Net::HTTP::Post.new(uri.request_uri) request.set_form_data({"user[name]" =&gt; "testusername", "user[email]" =&gt; "[email protected]"}) response = http.request(request) render :json =&gt; response.body </code></pre> <p>Hope it'll helps others.. :)</p>
37,601,942
Firebase 3 - We have blocked all requests from this device due to unusual activity
<p>I was testing my login/sign up feature and for some reason I can't understand Firebase now is blocking all requests from my device.</p> <p>I've waited one day to try again, but I still have the same problem.</p> <blockquote> <p>ERROR: "We have blocked all requests from this device due to unusual activity. Try again later."</p> </blockquote> <p>What should I do to have access to my database again?</p>
37,896,958
14
9
null
2016-06-02 20:54:43.527 UTC
4
2022-08-16 17:26:35.98 UTC
2019-11-30 07:30:52.287 UTC
null
5,660,517
null
1,097,284
null
1
99
firebase|firebase-authentication
93,503
<p>One of the possible solutions: </p> <ol> <li><p>Go to your Firebase console -> Auth -> Users table</p></li> <li><p>Locate the user you are testing.</p></li> <li><p>Delete this user.</p></li> <li><p>Retest.</p></li> </ol>
22,847,410
Swap two values in a numpy array.
<p>Is there something more efficient than the following code to swap two values of a numpy 1D array?</p> <pre><code>input_seq = arange(64) ix1 = randint(len(input_seq)) ixs2 = randint(len(input_seq)) temp = input_seq[ix2] input_seq[ix2] = input_seq[ix1] input_seq[ix1] = temp </code></pre>
22,847,433
2
3
null
2014-04-03 19:41:18.977 UTC
3
2017-12-23 10:43:18.78 UTC
null
null
null
null
1,828,017
null
1
28
python|numpy|scipy|swap
51,139
<p>You can use tuple unpacking. Tuple unpacking allows you to avoid the use of a temporary variable in your code (in actual fact I believe the Python code itself uses a temp variable behind the scenes but it's at a much lower level and so is much faster).</p> <pre><code>input_seq[ix1], input_seq[ix2] = input_seq[ix2], input_seq[ix1] </code></pre> <p>I have flagged this question as a duplicate, the answer in <a href="https://stackoverflow.com/questions/14836228/is-there-a-standardized-method-to-swap-two-variables-in-python">the dupe post</a> has a lot more detail.</p>
13,233,878
make hover on <li>item</li> change text colour too... CSS trick?
<p>I have some menu bars, and at the moment, the Background changes to black when hovering over an </p> <pre><code> &lt;li&gt;content&lt;/li&gt; </code></pre> <p>and the text changes from black to white when it is hovered over.</p> <p>I need to make it so the text color changes when the whole <code>&lt;li&gt;content&lt;/li&gt;</code> is hovered, not just when the the text is highlighted.</p> <p><strong>here is the css</strong></p> <pre><code> &lt;style type="text/css"&gt; body{margin:0px; font-family:Tahoma, Sans-Serif; font-size:13px;} /* dock */ #dock{margin:0px; padding:0px; list-style:none; position:fixed; top:0px; height:100%; z-index:100; background-color:; left:0px;} #dock &gt; li {width:40px; height:120px; margin: 0 0 1px 0; background-color:#; background-repeat:no-repeat; background-position:left center;} #dock #Menu {background-image:url(Menu.png);} #dock &gt; li:hover {background-position:-40px 0px;} /* panels */ #dock ul li {padding:5px; border: solid 0px #879b17;} #dock ul li:hover {padding:5px; background:#879b17 url(item_bkg.png) repeat-x; border: solid 0x #879b17; font-weight: bold; color: #000; } #dock ul li.header, #dock ul li .header:hover { background:#fff url(header_bkg.png) repeat-x; border:solid 10px #879b17; border-top-left-radius: 10px; border-top-right-radius: 10px; color: #FFF; font-weight: bold; text-align: center; } #dock &gt; li:hover ul { display:block; color: #FFF; } #dock &gt; li ul {position:absolute; top:0px; left:-180px; z-index:-1;width:180px; display:none; background-color:#fff; border:solid 10px #000; border-top-left-radius: 20px; border-top-right-radius: 20px; padding:0px; margin:0px; list-style:none;} #dock &gt; li ul.docked { display:block;z-index:-2;} .dock,.undock{} .undock {display:none; } #content {margin: 10px 0 0 60px; } body,td,th { color: #333; } a:link { color: #000; text-decoration: none; } a:visited { text-decoration: none; color: #000; } a:hover { text-decoration: underline; color: #FFF; } a:active { text-decoration: none; color: #FFF; text-align: center; } #dock #Menu .free .header .dock { color: #FFF; font-weight: bold; } #dock #Menu .free .header .undock { color: #FFFFFF; } &lt;/style&gt; </code></pre> <p><strong>and here is the HTML</strong></p> <pre><code> &lt;li id="Menu"&gt; &lt;ul class="free"&gt; &lt;li class="header"&gt;&lt;a href="#" class="dock"&gt;DOCK&lt;/a&gt;&lt;a href="#" class="undock"&gt;UN-DOCK&lt;/a&gt;&lt;/li&gt; &lt;li&gt; &lt;/li&gt; &lt;li class="header"&gt;CAMPAIGNS&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Link Data&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Search&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Summary Sheet&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Add New Client&lt;/a&gt;&lt;/li&gt; &lt;li class="header"&gt;LINKS&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Record Transactions&lt;/a&gt;&lt;/li&gt; &lt;li class="header"&gt;REPORTS&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Handover Sheets&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Handover Summary&lt;/a&gt;&lt;/li&gt; &lt;li class="header" &gt;MAINTENANCE&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Logout&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Manage Users&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; </code></pre> <p>Thanks in advance if you are able to help</p> <p>Regards</p> <p>Henry</p>
13,234,049
2
13
null
2012-11-05 14:13:43.433 UTC
3
2014-02-04 10:56:33.683 UTC
2012-11-05 14:20:51.123 UTC
null
1,703,780
null
1,711,666
null
1
16
html|css|html-lists
110,436
<p>I'd recommend making the hover work on the 'A' elements instead of the LI elements.</p> <p>In order to make the LI elements flly clickable you need to set the 'A' element within it to display:block (or inline-block) as 'A' tags are display:inline by default.</p> <p>SO...</p> <pre><code>&lt;ul&gt; &lt;li&gt;&lt;a href="#"&gt;My Link&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; ul li a { display:block; } ul li a:hover, ul li a:focus { color:red; } </code></pre>
13,596,531
How to search for non-ASCII characters with bash tools?
<p>I have a large text file that contains a few unicode characters that make LaTeX crash. How can I find non-ASCII characters in a file with sed, and the like in a Linux bash?</p>
13,596,664
2
1
null
2012-11-28 01:56:07.743 UTC
8
2018-04-10 16:33:57.867 UTC
2018-04-10 16:33:57.867 UTC
null
6,862,601
null
1,749,675
null
1
31
bash|unicode|grep
24,267
<p>Try:</p> <pre><code>nonascii() { LANG=C grep --color=always '[^ -~]\+'; } </code></pre> <p>Which can be used like:</p> <pre><code>printf 'ŨTF8\n' | nonascii </code></pre> <p>Within <code>[]</code> <code>^</code> means "not". So <code>[^ -~]</code> means characters not between space and ~. So excluding control chars, this matches non ASCII characters, and is a more portable though slightly less accurate version of <code>[^\x00-\x7f]</code> below. The <code>\+</code> means <code>1 or more</code> and will get multibye characters to have a color shown around the complete character(s), rather than interspersed in each byte, thus corrupting the multibyte sequence </p>
13,400,323
Why are there two colons here? span::before
<p>This is the full line of code I'm looking at, and here is its context: <a href="http://acidmartin.wordpress.com/2011/02/24/custom-crossbrowser-styling-for-checkboxes-and-radio-buttons">http://acidmartin.wordpress.com/2011/02/24/custom-crossbrowser-styling-for-checkboxes-and-radio-buttons</a></p> <pre><code>input[type="radio"] + span::before { content: ""; display: inline-block; width: 20px; height: 20px; background: url("sprite.png") no-repeat -20px 0; vertical-align: middle; } </code></pre> <p>I have a decent understanding of how this works, but I don't understand why there are two colons, rather than one between span and before.</p> <p>The before selector, from what I've read should use one colon. </p> <p><a href="http://www.w3schools.com/cssref/sel_before.asp">http://www.w3schools.com/cssref/sel_before.asp</a></p> <p>On w3c, I can't find any selectors that have two colons, nor can I figure out why span would have a colon following it, in addition to the colon preceding "before".</p> <p><a href="http://www.w3.org/TR/CSS2/selector.html">http://www.w3.org/TR/CSS2/selector.html</a></p>
13,400,379
3
2
null
2012-11-15 15:08:52.863 UTC
4
2020-09-13 18:06:05.817 UTC
null
null
null
null
1,803,405
null
1
32
css|css-selectors
11,660
<p>It's a <em>pseudo-element</em>, as defined by the <a href="http://www.w3.org/TR/selectors/#gen-content" rel="noreferrer">CSS Selectors Level 3</a> spec:</p> <blockquote> <p>The <code>::before</code> and <code>::after</code> pseudo-elements can be used to describe generated content before or after an element's content.</p> </blockquote> <p>It is effectively the same as the single-colon syntax defined by the level 2 spec. The level 3 spec introduces an extra colon to differentiate between pseudo-elements and pseudo-classes (which use a single colon).</p> <p>Both syntaxes will work in newer browsers, but older browsers will not recognise the newer <code>::</code> style.</p> <hr> <p>For even more detail, you can look at the <a href="http://www.w3.org/TR/selectors/#grammar" rel="noreferrer">grammar</a> from the level 3 spec, which states:</p> <blockquote> <p>'::' starts a pseudo-element, ':' a pseudo-class</p> </blockquote>
13,782,277
CSS3 transforms and transitions (Webkit)
<p>Consider the following <a href="http://jsfiddle.net/6TMcS/" rel="noreferrer">fiddle</a></p> <pre><code>p { -webkit-transform: translate(-100%, 0); -moz-transform: translate(-100%, 0); -ms-transform: translate(-100%, 0); -o-transform: translate(-100%, 0); transform: translate(-100%, 0); -webkit-transition: transform 1s ease-in; -moz-transition: transform 1s ease-in; -o-transition: transform 1s ease-in; transition: transform 1s ease-in; } a:hover + p { -webkit-transform: translate(0, 0); -moz-transform: translate(0, 0); -ms-transform: translate(0, 0); -o-transform: translate(0, 0); transform: translate(0, 0); } </code></pre> <p>The transition works smoothly in FF but there is no transition at all in Safari or Chrome (on my Mac).</p> <p>Has the transition property to be prefixed or is there some kind of syntax error in my code?</p>
13,782,443
1
2
null
2012-12-08 21:47:10.94 UTC
7
2017-09-21 12:18:16.487 UTC
2017-09-21 12:18:16.487 UTC
null
7,641,196
null
930,107
null
1
42
css|webkit|css-transitions|css-transforms
89,886
<p>Add the vendor prefix in the transitions:</p> <pre><code>p { -webkit-transform: translate(-100%, 0); -moz-transform: translate(-100%, 0); -ms-transform: translate(-100%, 0); -o-transform: translate(-100%, 0); transform: translate(-100%, 0); -webkit-transition: -webkit-transform 1s ease-in; /* Changed here */ -moz-transition: -moz-transform 1s ease-in; -o-transition: -o-transform 1s ease-in; transition: transform 1s ease-in; } a:hover + p { -webkit-transform: translate(0, 0); -moz-transform: translate(0, 0); -ms-transform: translate(0, 0); -o-transform: translate(0, 0); transform: translate(0, 0); } </code></pre> <p><strong>Update (05/06/2014)</strong></p> <p>To answer some comments, the reason for omitting <code>-ms-transition</code>, is that it has never existed.</p> <p>Check:</p> <p><a href="http://caniuse.com/css-transitions">Can I Use? Transitions</a>,</p> <p><a href="http://caniuse.com/transforms2d">Can I Use? Transforms</a>,</p> <p><a href="https://developer.mozilla.org/en-US/docs/Web/CSS/transition#Browser_compatibility">MDN transitions</a>,</p> <p><a href="https://developer.mozilla.org/en-US/docs/Web/CSS/transform#Browser_compatibility">MDN transforms</a></p>
13,321,335
Load index.html every time from the server and NOT from cache
<p>I have a webpage <strong>index.html</strong> hosted on a particular server. I have pointed <code>example.com</code> to <code>example.com/index.html</code>. So when I make changes in index.html and save it, and then try to open example.com, the changes are not reflected. Reason that the webpages are being cached.</p> <p>Then I manually refresh the page and since it loads the fresh copies and not from cache, it works fine. But I cannot ask my client to do so, and they want everything to be perfect. So my question is that is there a trick or technique as to how I can make the file load every time from the server and not from cache?</p> <p>P.S: I know the trick for CSS, JS and images files, i.e. appending <code>?v=1</code> but don't know how to do it for index.html.</p> <p>Any help would be appreciated. Thanks!</p>
13,321,364
8
1
null
2012-11-10 10:45:05.253 UTC
8
2022-08-24 16:15:03.777 UTC
null
null
null
null
1,355,611
null
1
59
html|caching|webserver
45,993
<p>by this: </p> <pre><code>&lt;meta http-equiv="expires" content="0"&gt; </code></pre> <p>Setting the content to "0" tells the browsers to always load the page from the web server. </p>
13,303,449
urllib2.HTTPError: HTTP Error 403: Forbidden
<p>I am trying to automate download of historic stock data using python. The URL I am trying to open responds with a CSV file, but I am unable to open using urllib2. I have tried changing user agent as specified in few questions earlier, I even tried to accept response cookies, with no luck. Can you please help. </p> <p><em>Note: The same method works for yahoo Finance.</em></p> <p><strong>Code:</strong></p> <pre><code>import urllib2,cookielib site= "http://www.nseindia.com/live_market/dynaContent/live_watch/get_quote/getHistoricalData.jsp?symbol=JPASSOCIAT&amp;fromDate=1-JAN-2012&amp;toDate=1-AUG-2012&amp;datePeriod=unselected&amp;hiddDwnld=true" hdr = {'User-Agent':'Mozilla/5.0'} req = urllib2.Request(site,headers=hdr) page = urllib2.urlopen(req) </code></pre> <p><strong>Error</strong></p> <blockquote> <p>File "C:\Python27\lib\urllib2.py", line 527, in http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) urllib2.HTTPError: HTTP Error 403: Forbidden</p> </blockquote> <p>Thanks for your assistance</p>
13,303,773
6
1
null
2012-11-09 06:51:02.91 UTC
52
2021-05-13 23:20:18.657 UTC
2012-11-09 07:14:12.07 UTC
null
24,949
null
1,190,270
null
1
124
python|http|urllib
216,953
<p>By adding a few more headers I was able to get the data:</p> <pre><code>import urllib2,cookielib site= "http://www.nseindia.com/live_market/dynaContent/live_watch/get_quote/getHistoricalData.jsp?symbol=JPASSOCIAT&amp;fromDate=1-JAN-2012&amp;toDate=1-AUG-2012&amp;datePeriod=unselected&amp;hiddDwnld=true" hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3', 'Accept-Encoding': 'none', 'Accept-Language': 'en-US,en;q=0.8', 'Connection': 'keep-alive'} req = urllib2.Request(site, headers=hdr) try: page = urllib2.urlopen(req) except urllib2.HTTPError, e: print e.fp.read() content = page.read() print content </code></pre> <p>Actually, it works with just this one additional header:</p> <pre><code>'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', </code></pre>
13,314,433
Batch file to copy directories recursively
<p>Is there a way to copy directories recursively inside a .bat file? Is an example of this available?</p>
13,314,452
4
3
null
2012-11-09 19:12:19.257 UTC
25
2021-12-16 14:42:43.23 UTC
2021-04-03 22:57:55.91 UTC
null
472,495
null
57,997
null
1
155
batch-file|copy
276,517
<p>Look into <a href="https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/xcopy" rel="noreferrer">xcopy</a>, which will recursively copy files and subdirectories.</p> <p>There are examples, 2/3 down the page. Of particular use is:</p> <blockquote> <p>To copy all the files and subdirectories (including any empty subdirectories) from drive A to drive B, type:</p> <p><code>xcopy a: b: /s /e</code></p> </blockquote>
51,713,497
Can't add script component because the script class cannot be found?
<p>Yesterday I updated unity from unity5 to 2018.2.2f1. Unity scripts are not loading after Update 2018.2.2f1.</p> <p>Once I try to play the Scene the scripts are not loaded and I can't add the script again it gives this error:</p> <blockquote> <p>Can't add script component 'CubeScript' because the script class cannot be found. Make sure that there are no compile errors and that the file name and class name match.</p> </blockquote> <p><a href="https://i.stack.imgur.com/1CNsf.png" rel="noreferrer"><img src="https://i.stack.imgur.com/1CNsf.png" alt="Error"></a></p>
51,714,475
11
6
null
2018-08-06 18:18:10.717 UTC
8
2022-05-12 23:24:20.393 UTC
2018-08-07 13:34:04.843 UTC
null
3,785,314
null
4,061,346
null
1
36
c#|unity3d|updates
140,176
<p>If you still have the old copy of the project, upgrade the Unity project to <em>Unity 2017</em> first then to <em>2018.2.2f1</em>. </p> <p>Here are the few possible reasons you may get this error(Ordered from very likely)</p> <p><strong>1</strong>.Script name does not match class name.</p> <p>If script name is called <code>MyClass</code>, the class name must be <code>MyClass</code>. This is also case-sensitive. Double check to make sure that this is not the issue. To make sure that's not the issue, copy the class name and paste it as the script name to make sure that this is not the issue. </p> <p>Note that if you have have multiple classes in one script, the class name that should match with the script name is the class that derives from <code>MonoBehaviour</code>.</p> <hr> <p><strong>2</strong>.There is an error in your script. Since this is an upgrade, there is a chance you're using an API that is now deprecated and removed. Open your script with Visual Studio and see if there is an error there then fix it. There is usually a red line under a code that indicates there is an error.</p> <hr> <p><strong>3</strong>.Bad import with the Unity importer and its automatic upgrade script.</p> <p>Things to try:</p> <p><strong>A</strong>.The first thing to do is restart the Unity Editor.</p> <p><strong>B</strong>.Right click on the Project Tab then click <em>"Reimport All"</em></p> <p><strong>C</strong>.If there is still issue, the only left is deleting the problematic script and creating a new one. There is an easier way to do this if the script is attached to many GameObjects in your scene.</p> <p><strong>A</strong>.Open the script, copy its content into notepad.</p> <p><strong>B</strong>.From the Editor and on the <em>Project</em> tab right click on the script "CubeScript", select <em>"Find References In Scene"</em>. </p> <p><strong>C</strong>.Unity will now only show all the GameObjects that has this script attached to them. Delete the old script. Create a new one then copy the content from the notepad to this new script. Now, you can just drag the new script to all the filtered GameObject in the scene. Do this for every script effected. This is a manual work but should fix your issues when completed.</p>
39,576,257
How to limit file size on commit?
<p>Is there an option to limit the file size when committing?</p> <p>For example: file sizes above 500K would produce a warning. File sizes above 10M would stop the commit.</p> <p><em>I'm fully aware of <a href="https://stackoverflow.com/questions/7147699/limiting-file-size-in-git-repository">this question</a> which technically makes this a duplicate but the answers only offer a solution <strong>on push</strong>, which would be too late for my requirements.</em></p>
39,578,014
5
4
null
2016-09-19 14:57:59.123 UTC
10
2021-09-11 11:52:04.173 UTC
2020-04-11 10:59:12.357 UTC
null
2,476,373
null
2,476,373
null
1
16
linux|git|github|filesize
10,197
<p>This pre-commit hook will do the file size check:</p> <p><strong>.git/hooks/pre-commit</strong></p> <pre class="lang-sh prettyprint-override"><code>#!/bin/sh hard_limit=$(git config hooks.filesizehardlimit) soft_limit=$(git config hooks.filesizesoftlimit) : ${hard_limit:=10000000} : ${soft_limit:=500000} list_new_or_modified_files() { git diff --staged --name-status|sed -e '/^D/ d; /^D/! s/.\s\+//' } unmunge() { local result="${1#\"}" result="${result%\"}" env echo -e "$result" } check_file_size() { n=0 while read -r munged_filename do f="$(unmunge "$munged_filename")" h=$(git ls-files -s "$f"|cut -d' ' -f 2) s=$(git cat-file -s "$h") if [ "$s" -gt $hard_limit ] then env echo -E 1&gt;&amp;2 "ERROR: hard size limit ($hard_limit) exceeded: $munged_filename ($s)" n=$((n+1)) elif [ "$s" -gt $soft_limit ] then env echo -E 1&gt;&amp;2 "WARNING: soft size limit ($soft_limit) exceeded: $munged_filename ($s)" fi done [ $n -eq 0 ] } list_new_or_modified_files | check_file_size </code></pre> <p>Above script must be saved as <code>.git/hooks/pre-commit</code> with execution permissions enabled (<code>chmod +x .git/hooks/pre-commit</code>).</p> <p>The default soft (warning) and hard (error) size limits are set to 500,000 and 10,000,000 bytes but can be overriden through the <code>hooks.filesizesoftlimit</code> and <code>hooks.filesizehardlimit</code> settings respectively:</p> <pre><code>$ git config hooks.filesizesoftlimit 100000 $ git config hooks.filesizehardlimit 4000000 </code></pre>
3,869,830
Near and Far pointers
<p>What is difference between our usual pointers(ones which we normally use), near pointers and far pointers and is there a practical usage for near and far pointers in present day C/C++ systems? Any practical scenario which necessiates use of these specific pointers and not other c,c++ semantics will be very helpful.</p>
3,869,852
2
3
null
2010-10-06 06:00:06.533 UTC
10
2018-11-22 23:49:44.88 UTC
null
null
null
null
452,307
null
1
46
c++|c|pointers
33,789
<p>The near and far keywords have their origin in the segmented memory model that Intel had before. The near pointers could only access a block of memory originally around 64Kb in size called a segment whereas the far pointers could go outside of that range consisting of a segment and offset in that segment. The near pointers were much faster than far pointers so therefore in some contexts it paid off to use them.</p> <p>Nowadays with virtual memory near and far pointers have no use.</p> <p>EDIT:Sorry if I am not using the correct terms, but this is how I remembered it when I was working with it back in the day :-)</p>
29,583,849
Save a plot in an object
<p>In <code>ggplot2</code>, one can easily save a graphic into a R object.</p> <pre><code>p = ggplot(...) + geom_point() # does not display the graph p # displays the graph </code></pre> <p>The standard function <code>plot</code> produces the graphic as a void function and returns NULL.</p> <pre><code>p = plot(1:10) # displays the graph p # NULL </code></pre> <p>Is it possible to save a graphic created by <code>plot</code> in an object?</p>
29,583,945
4
4
null
2015-04-11 22:34:25.587 UTC
30
2019-09-30 12:10:39.027 UTC
2018-02-07 22:06:36.14 UTC
null
2,051,137
null
2,051,137
null
1
100
r|plot
67,729
<p>base graphics draw directly on a device. </p> <p>You could use</p> <p>1- <code>recordPlot</code></p> <p>2- the recently introduced <a href="https://www.stat.auckland.ac.nz/~paul/Reports/gridGraphics/gridGraphics.pdf" rel="noreferrer"><code>gridGraphics</code> package</a>, to convert base graphics to their grid equivalent</p> <p>Here's a minimal example,</p> <pre><code>plot(1:10) p &lt;- recordPlot() plot.new() ## clean up device p # redraw ## grab the scene as a grid object library(gridGraphics) library(grid) grid.echo() a &lt;- grid.grab() ## draw it, changes optional grid.newpage() a &lt;- editGrob(a, vp=viewport(width=unit(2,"in")), gp=gpar(fontsize=10)) grid.draw(a) </code></pre>
16,453,465
multi-column factorize in pandas
<p>The pandas <code>factorize</code> function assigns each unique value in a series to a sequential, 0-based index, and calculates which index each series entry belongs to.</p> <p>I'd like to accomplish the equivalent of <code>pandas.factorize</code> on multiple columns:</p> <pre><code>import pandas as pd df = pd.DataFrame({'x': [1, 1, 2, 2, 1, 1], 'y':[1, 2, 2, 2, 2, 1]}) pd.factorize(df)[0] # would like [0, 1, 2, 2, 1, 0] </code></pre> <p>That is, I want to determine each unique tuple of values in several columns of a data frame, assign a sequential index to each, and compute which index each row in the data frame belongs to.</p> <p><code>Factorize</code> only works on single columns. Is there a multi-column equivalent function in pandas?</p>
16,457,573
4
2
null
2013-05-09 02:39:55.703 UTC
8
2020-09-17 18:35:45.603 UTC
2013-05-09 03:08:40.813 UTC
null
1,332,492
null
1,332,492
null
1
13
python|pandas|enumeration|data-cleaning
9,043
<p>You need to create a ndarray of tuple first, <code>pandas.lib.fast_zip</code> can do this very fast in cython loop. </p> <pre><code>import pandas as pd df = pd.DataFrame({'x': [1, 1, 2, 2, 1, 1], 'y':[1, 2, 2, 2, 2, 1]}) print pd.factorize(pd.lib.fast_zip([df.x, df.y]))[0] </code></pre> <p>the output is:</p> <pre><code>[0 1 2 2 1 0] </code></pre>
16,290,365
Start ruby debugger if rspec test fails
<p>Often, when a test fails, I spend quite sometime trying to figure out the what caused it to fail. It'd be useful if RSpec could kick off a Ruby debugger when the test fails, so that I can inspect the local variables immediately to drill down on the cause.</p> <p>The work-around I'm using right now looks something like this:</p> <pre><code># withing some test debugger unless some_variable.nil? expect(some_variable).to be_nil </code></pre> <p>However, this approach is cumbersome, because I first wait for a test to fail, then add the debugger line, fix the issue and then have to remove the debugger line, whereas I want it work more like <code>gdb</code> which has the ability to kick in when an exception is hit, without requiring to pepper your code base with <code>debugger</code> statements.</p> <p>Edit: I've tried Plymouth. It hasn't worked reliably enough for me. Also the development history seems to indicate that it isn't a very well supported gem, so I'd rather not rely on it.</p> <p><strong>Update</strong>: I tried out <code>pry-rescue</code> and find it to be neat. However, I use <a href="https://github.com/burke/zeus" rel="noreferrer">zeus</a> a lot and was wondering if there's a way to make it work with <code>pry-rescue</code>.</p>
16,303,154
7
0
null
2013-04-30 00:26:07.197 UTC
5
2021-10-18 19:49:58.17 UTC
2017-12-15 07:54:50.32 UTC
null
3,787,051
null
724,516
null
1
28
ruby-on-rails|rspec|ruby-debug|pry
7,960
<p>Use <a href="https://github.com/conradirwin/pry-rescue">pry-rescue</a>, it's the spiritual successor to plymouth:</p> <p>From the Readme:</p> <p>If you're using RSpec or respec, you can open a pry session on every test failure using rescue rspec or rescue respec:</p> <pre><code>$ rescue rspec From: /home/conrad/0/ruby/pry-rescue/examples/example_spec.rb @ line 9 : 6: 7: describe "Float" do 8: it "should be able to add" do =&gt; 9: (0.1 + 0.2).should == 0.3 10: end 11: end RSpec::Expectations::ExpectationNotMetError: expected: 0.3 got: 0.30000000000000004 (using ==) [1] pry(main)&gt; </code></pre>
16,513,530
Why is my CSS style not being applied?
<p>I've got this html:</p> <pre><code>&lt;p&gt; &lt;span class="fancify"&gt;Parting is such sweet sorrow!&lt;/span&gt;&lt;span&gt; - Bill Rattleandrollspeer&lt;/span&gt; &lt;/p&gt; </code></pre> <p>...and this css (added to the bottom of Site.css):</p> <pre><code>.fancify { font-size: 1.5em; font-weight: 800; font-family: Consolas, "Segoe UI", Calibri, sans-serif; font-style: italic; } </code></pre> <p>So, I would expect the quote ("Parting is such sweet sorrow!") to be italicized, and of a different font than the name of the quotee (Bill Rattleandrollspeer), since its span tag has the class "fancify" attached to it. The class should certainly be seen, as the file in which it appears references the layout file which uses the Site.css file.</p> <p>What rookie mistake am I making now?</p> <h2>UPDATE</h2> <p>I thought maybe the problem was that I had added the new class in Site.css following this section in that file:</p> <pre><code>/******************** * Mobile Styles * ********************/ @media only screen and (max-width: 850px) { </code></pre> <p>...but I moved it above there, and it is still not working, and not seen via F12 | Inspect element for the label in question.</p> <p>I moved the reference to Site.css below the bootstrap.css file, which does indeed change the appearance of that text, but still not italicized, and still not seen in the element inspector...</p> <h2>UPDATE 2</h2> <p>Here's how the HTML is coming down:</p> <pre><code>&lt;p&gt; &lt;span&gt; &lt;label class="fancify"&gt;Parting is such sweet sorrow!&lt;/label&gt; </code></pre> <p>...and here's my css rule in Site.css:</p> <pre><code>p span label .fancify { font-size: 1.5em; font-weight: 800; font-family: Consolas, "Segoe UI", Calibri, sans-serif; font-style: italic; display: inline; } </code></pre> <p>...but it's not being recognized. I consider this a breech of css/html protocol, and should be adjudicated by some world body. Then again, I could be making some silly mistake somewhere.</p>
16,513,974
16
14
null
2013-05-13 00:51:45.49 UTC
11
2022-03-14 04:48:24.197 UTC
2017-06-22 09:58:58.903 UTC
null
106,224
null
875,317
null
1
58
html|css
299,139
<p>Have you tried forcing the selectors to be in the front of the class?</p> <pre><code>p span label.fancify { font-size: 1.5em; font-weight: 800; font-family: Consolas, "Segoe UI", Calibri, sans-serif; font-style: italic; } </code></pre> <p>Usually it will add more weight to your CSS declaration. My mistake ... There should be no space between the selector and the class. The same goes for the ID. If you have for example:</p> <pre><code>&lt;div id="first"&gt; &lt;p id="myParagraph"&gt;Hello &lt;span class="bolder"&gt;World&lt;/span&gt;&lt;/p&gt; &lt;/div&gt; </code></pre> <p>You would style it like this: </p> <pre><code>div#first p#myParagraph { color : #ff0000; } </code></pre> <p>Just to make a complete example using a class:</p> <pre><code>div#first p#myParagraph span.bolder{ font-weight:900; } </code></pre> <p>For more information about pseudo-selectors and child selectors : <a href="http://www.w3.org/TR/CSS2/selector.html" rel="noreferrer">http://www.w3.org/TR/CSS2/selector.html</a></p> <p>CSS is a whole science :) Beware that some browsers can have incompatibilities and will not show you the proper results. For more information check this site: <a href="http://www.caniuse.com/" rel="noreferrer">http://www.caniuse.com/</a></p>
16,497,938
EF 5 Enable-Migrations : No context type was found in the assembly
<p>I have 4 projects : </p> <pre><code>Toombu.Entities : all models are there Toombu.DataAccess: Mapping, Repository and ToombuContext Toombu.Logique : Logic of my application Toombu.Web : MVC 4 application. With all others DLL. </code></pre> <p>I tried to enable migration in <strong>Toombu.Web</strong> but i had this error :</p> <pre><code>No context type was found in the assembly </code></pre> <p>How can I enable migration ?</p>
16,498,181
28
0
null
2013-05-11 14:09:02.43 UTC
18
2022-09-06 11:43:40.397 UTC
null
null
null
null
1,964,075
null
1
78
c#|entity-framework|asp.net-mvc-4|entity-framework-migrations
164,045
<p>use -ProjectName option in Package Manager Console:</p> <pre><code>Enable-Migrations -ProjectName Toombu.DataAccess -StartUpProjectName Toombu.Web -Verbose </code></pre>
16,519,828
Rails 4: before_filter vs. before_action
<p>In rails >4.0.0 generators creates CRUD operations with <code>before_action</code> not <code>before_filter</code>. It seems to do the same thing. So what's the difference between these two? </p>
16,519,841
6
0
null
2013-05-13 10:26:26.64 UTC
55
2021-06-13 12:39:17.56 UTC
2017-04-06 09:50:53.293 UTC
null
7,822,322
null
1,644,531
null
1
354
ruby-on-rails|ruby|ruby-on-rails-4|crud
171,922
<p>As we can <a href="https://github.com/rails/rails/blob/master/actionpack/lib/abstract_controller/callbacks.rb" rel="noreferrer">see</a> in <code>ActionController::Base</code>, <code>before_action</code> is just a <a href="https://github.com/rails/rails/commit/9d62e04838f01f5589fa50b0baa480d60c815e2c" rel="noreferrer">new syntax</a> for <code>before_filter</code>.</p> <p>However the <code>before_filter</code> syntax <a href="https://github.com/rails/rails/blob/v5.0.0.beta2/actionpack/lib/abstract_controller/callbacks.rb#L190-L193" rel="noreferrer">is deprecated</a> in <strong>Rails 5.0</strong> and will be removed in <strong>Rails 5.1</strong></p>
16,512,761
CALayer with transparent hole in it
<p>I have a simple view (left side of the picture) and i need to create some kind of overlay (right side of the picture) to this view. This overlay should have some opacity, so the view bellow it is still partly visible. Most importantly this overlay should have a circular hole in the middle of it so it doesn't overlay the center of the view (see picture bellow). </p> <p>I can easily create a circle like this :</p> <pre><code>int radius = 20; //whatever CAShapeLayer *circle = [CAShapeLayer layer]; circle.path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0,radius,radius) cornerRadius:radius].CGPath; circle.position = CGPointMake(CGRectGetMidX(view.frame)-radius, CGRectGetMidY(view.frame)-radius); circle.fillColor = [UIColor clearColor].CGColor; </code></pre> <p>And a "full" rectangular overlay like this :</p> <pre><code>CAShapeLayer *shadow = [CAShapeLayer layer]; shadow.path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, view.bounds.size.width, view.bounds.size.height) cornerRadius:0].CGPath; shadow.position = CGPointMake(0, 0); shadow.fillColor = [UIColor grayColor].CGColor; shadow.lineWidth = 0; shadow.opacity = 0.5; [view.layer addSublayer:shadow]; </code></pre> <p>But I have no idea how can I combine these two layers so they create effect I want. Anyone? I've tried really everything... Thanks a lot for help!</p> <p><img src="https://i.stack.imgur.com/o1jyS.png" alt="Image"></p>
16,518,739
5
5
null
2013-05-12 22:39:54.45 UTC
68
2019-07-05 16:52:46.957 UTC
2013-05-12 23:27:14.767 UTC
null
1,226,963
null
1,058,131
null
1
120
ios|objective-c|calayer|quartz-core
59,928
<p>I was able to solve this with Jon Steinmetz suggestion. If any one cares, here's the final solution: </p> <pre><code>int radius = myRect.size.width; UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, self.mapView.bounds.size.width, self.mapView.bounds.size.height) cornerRadius:0]; UIBezierPath *circlePath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, 2.0*radius, 2.0*radius) cornerRadius:radius]; [path appendPath:circlePath]; [path setUsesEvenOddFillRule:YES]; CAShapeLayer *fillLayer = [CAShapeLayer layer]; fillLayer.path = path.CGPath; fillLayer.fillRule = kCAFillRuleEvenOdd; fillLayer.fillColor = [UIColor grayColor].CGColor; fillLayer.opacity = 0.5; [view.layer addSublayer:fillLayer]; </code></pre> <p>Swift 3.x: </p> <pre><code>let radius = myRect.size.width let path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: self.mapView.bounds.size.width, height: self.mapView.bounds.size.height), cornerRadius: 0) let circlePath = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: 2 * radius, height: 2 * radius), cornerRadius: radius) path.append(circlePath) path.usesEvenOddFillRule = true let fillLayer = CAShapeLayer() fillLayer.path = path.cgPath fillLayer.fillRule = kCAFillRuleEvenOdd fillLayer.fillColor = Color.background.cgColor fillLayer.opacity = 0.5 view.layer.addSublayer(fillLayer) </code></pre> <p>Swift 4.2 &amp; 5:</p> <pre class="lang-swift prettyprint-override"><code>let radius: CGFloat = myRect.size.width let path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: self.view.bounds.size.width, height: self.view.bounds.size.height), cornerRadius: 0) let circlePath = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: 2 * radius, height: 2 * radius), cornerRadius: radius) path.append(circlePath) path.usesEvenOddFillRule = true let fillLayer = CAShapeLayer() fillLayer.path = path.cgPath fillLayer.fillRule = .evenOdd fillLayer.fillColor = view.backgroundColor?.cgColor fillLayer.opacity = 0.5 view.layer.addSublayer(fillLayer) </code></pre>
15,203,058
Group the rows that are having the same value in specific field in MySQL
<p>I am having the following data in MySQL table.</p> <pre><code>+--------+----------+------+ | job_id | query_id | done | +--------+----------+------+ | 15145 | a002 | 1 | | 15146 | a002 | 1 | | 15148 | a002 | 1 | | 15150 | a002 | 1 | | 15314 | a003 | 0 | | 15315 | a003 | 1 | | 15316 | a003 | 0 | | 15317 | a003 | 0 | | 15318 | a003 | 1 | | 15319 | a003 | 0 | +--------+----------+------+ </code></pre> <p>I would like to know if it's possible to have a sql query, which can group by query_id <strong>IF ALL 'done' fields are marked as 1</strong>. The possible output I imagine would be:</p> <pre><code>+----------+------+ | query_id | done | +----------+------+ | a002 | 1 | | a003 | 0 | +----------+------+ </code></pre> <p>I've tried the following SQL query:</p> <pre><code>select job_id, query_id, done from job_table group by done having done = 1 ; </code></pre> <p>But no luck. I would really appreciate for any help!</p>
15,203,349
5
0
null
2013-03-04 13:48:52.61 UTC
2
2021-05-18 07:16:02.857 UTC
2013-03-04 13:56:48.05 UTC
null
2,131,907
null
2,131,907
null
1
8
mysql|sql|group-by
43,804
<p>I'm not particullarly proud of this solution because it is not very clear, but at least it's fast and simple. If all of the items have <em>"done" = 1</em> then the sum will be equal to the count SUM = COUNT</p> <pre><code>SELECT query_id, SUM(done) AS doneSum, COUNT(done) AS doneCnt FROM tbl GROUP BY query_id </code></pre> <p>And if you add a having clause you get the items that are "done". </p> <pre><code>HAVING doneSum = doneCnt </code></pre> <p>I'll let you format the solution properly, you can do a DIFERENCE to get the "not done" items or doneSum &lt;> doneCnt.</p> <p>Btw, SQL fiddle <a href="http://sqlfiddle.com/#!2/437f8/3" rel="noreferrer">here</a>.</p>
17,638,826
Make HTML hidden input visible
<p>I want to change an invisible HTML input in to visible when I click a button as shown below.</p> <p>My HTML line that create the hidden input is:</p> <pre><code>&lt;input type="hidden" id="txtHiddenUname" value="invalid input" /&gt; </code></pre> <p>my JavaScript for changing the visibility is:</p> <pre><code>var y = document.getElementById("txtHiddenUname"); y.style.display= "inline"; </code></pre> <p>But this couldn't make the hidden element to be visible.</p> <p>Any ideas?</p>
17,638,840
2
1
null
2013-07-14 11:03:23.147 UTC
2
2020-04-02 16:54:03.147 UTC
2020-04-02 16:54:03.147 UTC
null
4,217,744
null
2,449,168
null
1
7
javascript|html|visibility
51,710
<p>You should change the type of input element as :</p> <pre><code> y.setAttribute('type','text'); //or y.type = 'text'; </code></pre> <p>1) Either user java script inside body tag as below :</p> <pre><code>&lt;input type="hidden" id="txtHiddenUname" value="invalid input" /&gt; &lt;script type="text/javascript"&gt; var y = document.getElementById("txtHiddenUname"); y.type= "text"; &lt;/script&gt; </code></pre> <p><strong>OR</strong> <br /></p> <p>2) Use some event handler such as <code>onload</code> <br /></p> <pre><code>&lt;head&gt; &lt;script type="text/javascript"&gt; function on_load(){ var y = document.getElementById("txtHiddenUname"); y.type= "text"; } &lt;/script&gt; &lt;/head&gt; &lt;body onload = "on_load()"&gt; &lt;input type="hidden" id="txtHiddenUname" value="invalid input" /&gt; ... </code></pre> <p>so that the DOM is ready.</p>
58,224,638
Do I need to explicitly handle negative numbers or zero when summing squared digits?
<p>I recently had a test in my class. One of the problems was the following:</p> <blockquote> <p>Given a number <strong>n</strong>, write a function in C/C++ that returns the sum of the digits of the number <em>squared</em>. (The following is important). The <em>range</em> of <strong>n</strong> is [ -(10^7), 10^7 ]. Example: If <strong>n</strong> = 123, your function should return 14 (1^2 + 2^2 + 3^2 = 14).</p> </blockquote> <p>This is the function that I wrote:</p> <pre><code>int sum_of_digits_squared(int n) { int s = 0, c; while (n) { c = n % 10; s += (c * c); n /= 10; } return s; } </code></pre> <p>Looked right to me. So now the test came back and I found that the teacher didn't give me all the points for a reason that I do not understand. According to him, for my function to be complete, I should've have added the following detail:</p> <pre><code>int sum_of_digits_squared(int n) { int s = 0, c; if (n == 0) { // return 0; // } // // THIS APPARENTLY SHOULD'VE if (n &lt; 0) { // BEEN IN THE FUNCTION FOR IT n = n * (-1); // TO BE CORRECT } // while (n) { c = n % 10; s += (c * c); n /= 10; } return s; } </code></pre> <p>The argument for this is that the number <strong>n</strong> is in the range [-(10^7), 10^7], so it can be a negative number. But I don't see where my own version of the function fails. If I understand correctly, the meaning of <code>while(n)</code> is <code>while(n != 0)</code>, <strong>not</strong> <code>while (n &gt; 0)</code>, so in my version of the function the number <strong>n</strong> wouldn't fail to enter the loop. It would work just the same. </p> <p>Then, I tried both versions of the function on my computer at home and I got exactly the same answers for all the examples that I tried. So, <code>sum_of_digits_squared(-123)</code> is equal to <code>sum_of_digits_squared(123)</code> (which again, is equal to <code>14</code>) (even without the detail that I apparently should've added). Indeed, if I try to print on the screen the digits of the number (from least to greatest in importance), in the <code>123</code> case I get <code>3 2 1</code> and in the <code>-123</code> case I get <code>-3 -2 -1</code> (which is actually kind of interesting). But in this problem it wouldn't matter since we square the digits. </p> <p>So, who's wrong?</p> <p><strong>EDIT</strong>: My bad, I forgot to specify and didn't know it was important. The version of C used in our class and tests has to be C99 or <strong>newer</strong>. So I guess (by reading the comments) that my version would get the correct answer in any way.</p>
58,225,192
9
31
null
2019-10-03 18:06:42.3 UTC
24
2022-08-21 14:45:18.463 UTC
2019-10-23 15:44:02.277 UTC
null
584,518
null
11,641,316
null
1
222
c
30,691
<p>Summarizing a discussion that's been percolating in the comments:</p> <ul> <li>There is no good reason to test in advance for <code>n == 0</code>. The <code>while(n)</code> test will handle that case perfectly.</li> <li>It's likely your teacher is still used to earlier times, when the result of <code>%</code> with negative operands was differently defined. On some old systems (including, notably, early Unix on a PDP-11, where Dennis Ritchie originally developed C), the result of <code>a % b</code> was <em>always</em> in the range <code>[0 .. b-1]</code>, meaning that -123 % 10 was 7. On such a system, the test in advance for <code>n &lt; 0</code> would be necessary.</li> </ul> <p>But the second bullet applies only to earlier times. In the current versions of both the C and C++ standards, integer division is defined to truncate towards 0, so it turns out that <code>n % 10</code> is guaranteed to give you the (possibly negative) last digit of <code>n</code> even when <code>n</code> is negative.</p> <p>So the answer to the question <em>"What is the meaning of <code>while(n)</code>?"</em> is <em>"Exactly the same as <code>while(n != 0)</code>"</em>, and the answer to <em>"Will this code work properly for negative as well as positive <code>n</code>?"</em> is <em>"Yes, under any modern, Standards-conforming compiler."</em> The answer to the question <em>"Then why did the instructor mark it down?"</em> is probably that they're not aware of a significant language redefinition that happened to C in 1999 and to C++ in 2010 or so.</p>
26,745,300
Navigation Drawer semi-transparent over status bar not working
<p>I am working on Android project and I am implementing the Navigation Drawer. I am reading through the new <a href="http://www.google.com/design/spec/patterns/navigation-drawer.html" rel="noreferrer">Material Design Spec</a> and the <a href="http://android-developers.blogspot.co.uk/2014/10/material-design-on-android-checklist.html" rel="noreferrer">Material Design Checklist</a>.<br> The spec says that the slide out pane should float above everything else including the status bar and be semi-transparent over the status bar. </p> <p>My navigation panel is over the status bar but its not got any transparency. I've followed the code from this <strong>SO</strong> post as suggested in the Google developers blog spot, link above <a href="https://stackoverflow.com/questions/26440879/how-do-i-use-drawerlayout-to-display-over-the-actionbar-toolbar-and-under-the-st/26440880">How do I use DrawerLayout to display over the ActionBar/Toolbar and under the status bar?</a>. </p> <p><strong>Below is my XML layout</strong></p> <pre><code>&lt;android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/my_drawer_layout" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true"&gt; &lt;LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"&gt; &lt;android.support.v7.widget.Toolbar android:id="@+id/my_awesome_toolbar" android:layout_height="wrap_content" android:layout_width="match_parent" android:minHeight="?attr/actionBarSize" android:background="@color/appPrimaryColour" /&gt; &lt;/LinearLayout&gt; &lt;LinearLayout android:id="@+id/linearLayout" android:layout_width="304dp" android:layout_height="match_parent" android:layout_gravity="left|start" android:fitsSystemWindows="true" android:background="#ffffff"&gt; &lt;ListView android:id="@+id/left_drawer" android:layout_width="match_parent" android:layout_height="match_parent" android:choiceMode="singleChoice"&gt;&lt;/ListView&gt; &lt;/LinearLayout&gt; &lt;/android.support.v4.widget.DrawerLayout&gt; </code></pre> <p><strong>Below is my apps theme</strong></p> <pre><code>&lt;style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"&gt; &lt;item name="colorPrimary"&gt;@color/appPrimaryColour&lt;/item&gt; &lt;item name="colorPrimaryDark"&gt;@color/appPrimaryColourDark&lt;/item&gt; &lt;item name="colorAccent"&gt;@color/appPrimaryColour&lt;/item&gt; &lt;item name="windowActionBar"&gt;false&lt;/item&gt; &lt;item name="windowActionModeOverlay"&gt;true&lt;/item&gt; &lt;/style&gt; </code></pre> <p><strong>Below is my apps v21 theme</strong></p> <pre><code>&lt;style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"&gt; &lt;item name="colorPrimary"&gt;@color/appPrimaryColour&lt;/item&gt; &lt;item name="colorPrimaryDark"&gt;@color/appPrimaryColourDark&lt;/item&gt; &lt;item name="colorAccent"&gt;@color/appPrimaryColour&lt;/item&gt; &lt;item name="windowActionBar"&gt;false&lt;/item&gt; &lt;item name="windowActionModeOverlay"&gt;true&lt;/item&gt; &lt;item name="android:windowDrawsSystemBarBackgrounds"&gt;true&lt;/item&gt; &lt;item name="android:statusBarColor"&gt;@android:color/transparent&lt;/item&gt; &lt;/style&gt; </code></pre> <p><strong>Below is my onCreate method</strong></p> <pre><code>protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar); setSupportActionBar(toolbar); mDrawerLayout = (DrawerLayout)findViewById(R.id.my_drawer_layout); mDrawerList = (ListView)findViewById(R.id.left_drawer); mDrawerLayout.setStatusBarBackgroundColor( getResources().getColor(R.color.appPrimaryColourDark)); if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.LOLLIPOP) { LinearLayout linearLayout = (LinearLayout)findViewById(R.id.linearLayout); linearLayout.setElevation(30); } </code></pre> <p>Below is a <strong>screenshot</strong> of my navigation drawer showing the top isn't semi transparent</p> <p><img src="https://i.stack.imgur.com/rPnor.png" alt="Screenshot showing non transparent over the status bar"></p>
26,932,228
9
3
null
2014-11-04 21:23:31.52 UTC
47
2020-06-21 19:44:49.747 UTC
2017-05-23 10:31:16.713 UTC
null
-1
null
499,448
null
1
91
android|navigation-drawer|android-5.0-lollipop|material-design
100,297
<p>Your status bar background is white, the background of your drawer <code>LinearLayout</code>. Why? You are settings <code>fitsSystemWindows="true"</code> for your <code>DrawerLayout</code> and the <code>LinearLayout</code> inside it. This causes your <code>LinearLayout</code> to expand <em>behind</em> the status bar (which is transparent). Thus, making the background for the drawer part of the status bar white. </p> <p><img src="https://i.stack.imgur.com/QdaEJ.png" alt="enter image description here"><br> If you don't want your drawer to extend behind the status bar (want to have a semi-transparent background for the whole status bar), you can do two things:</p> <p>1) You can simply remove any background value from your <code>LinearLayout</code> and color the background of your content inside it. Or</p> <p>2) You can remove <code>fitsSystemWindows="true"</code> from your <code>LinearLayout</code>. I think this is a more logical and cleaner approach. You will also avoid having a shadow being cast under the status bar, where your navigation drawer doesn't extend.</p> <p><img src="https://i.stack.imgur.com/144vN.png" alt="enter image description here"><br> If you want your drawer to extend behind the status bar and have a semi-transparent, status bar sized overlay, you can use a <a href="https://github.com/google/iosched/blob/master/android/src/main/java/com/google/samples/apps/iosched/ui/widget/ScrimInsetsFrameLayout.java" rel="noreferrer"><code>ScrimInsetFrameLayout</code></a> as a container for your drawer content (<code>ListView</code>) and set the status bar background using <code>app:insetForeground="#4000"</code>. Of course, you can change <code>#4000</code> to anything you want. Don't forget to keep <code>fitsSystemWindows="true"</code> here!</p> <p>Or if you don't want to overlay your content and only display a solid color, you can just set the background of your <code>LinearLayout</code> to anything you want. Don't forget to set the background of your content separately though!</p> <p><strong>EDIT:</strong> You no longer need to deal with any of this. Please see <a href="http://android-developers.blogspot.com.tr/2015/05/android-design-support-library.html" rel="noreferrer">Design Support Library</a> for a times easier Navigation Drawer/View implementation.</p>
17,618,149
Divide string by line break or period with Python regular expressions
<p>I have a string:</p> <pre><code>"""Hello. It's good to meet you. My name is Bob.""" </code></pre> <p>I'm trying to find the best way to split this into a list divided by periods and linebreaks:</p> <pre><code>["Hello", "It's good to meet you", "My name is Bob"] </code></pre> <p>I'm pretty sure I should use regular expressions, but, having no experience with them, I'm struggling to figure out how to do this.</p>
17,618,181
5
0
null
2013-07-12 15:09:05.18 UTC
3
2013-07-12 17:55:40.617 UTC
null
null
null
null
2,317,459
null
1
20
python|regex|string|split
46,311
<p>You don't need regex.</p> <pre><code>&gt;&gt;&gt; txt = """Hello. It's good to meet you. ... My name is Bob.""" &gt;&gt;&gt; txt.split('.') ['Hello', " It's good to meet you", '\nMy name is Bob', ''] &gt;&gt;&gt; [x for x in map(str.strip, txt.split('.')) if x] ['Hello', "It's good to meet you", 'My name is Bob'] </code></pre>
17,497,075
Efficient way to retrieve all _ids in ElasticSearch
<p>What is the fastest way to get all _ids of a certain index from ElasticSearch? Is it possible by using a simple query? One of my index has around 20,000 documents.</p>
17,497,442
11
1
null
2013-07-05 21:28:10.857 UTC
14
2022-04-26 19:39:49.99 UTC
null
null
null
null
1,336,532
null
1
83
elasticsearch
98,761
<p><em>Edit: Please also read the <a href="https://stackoverflow.com/a/30855670/1164465">answer from Aleck Landgraf</a></em></p> <p>You just want the elasticsearch-internal <code>_id</code> field? Or an <code>id</code> field from within your documents?</p> <p>For the former, try</p> <pre><code>curl http://localhost:9200/index/type/_search?pretty=true -d ' { &quot;query&quot; : { &quot;match_all&quot; : {} }, &quot;stored_fields&quot;: [] } ' </code></pre> <p><strong>Note 2017 Update:</strong> The post originally included <code>&quot;fields&quot;: []</code> but since then the name has changed and <code>stored_fields</code> is the new value.</p> <p>The result will contain only the &quot;metadata&quot; of your documents</p> <pre><code>{ &quot;took&quot; : 7, &quot;timed_out&quot; : false, &quot;_shards&quot; : { &quot;total&quot; : 5, &quot;successful&quot; : 5, &quot;failed&quot; : 0 }, &quot;hits&quot; : { &quot;total&quot; : 4, &quot;max_score&quot; : 1.0, &quot;hits&quot; : [ { &quot;_index&quot; : &quot;index&quot;, &quot;_type&quot; : &quot;type&quot;, &quot;_id&quot; : &quot;36&quot;, &quot;_score&quot; : 1.0 }, { &quot;_index&quot; : &quot;index&quot;, &quot;_type&quot; : &quot;type&quot;, &quot;_id&quot; : &quot;38&quot;, &quot;_score&quot; : 1.0 }, { &quot;_index&quot; : &quot;index&quot;, &quot;_type&quot; : &quot;type&quot;, &quot;_id&quot; : &quot;39&quot;, &quot;_score&quot; : 1.0 }, { &quot;_index&quot; : &quot;index&quot;, &quot;_type&quot; : &quot;type&quot;, &quot;_id&quot; : &quot;34&quot;, &quot;_score&quot; : 1.0 } ] } } </code></pre> <p>For the latter, if you want to include a field from your document, simply add it to the <code>fields</code> array</p> <pre><code>curl http://localhost:9200/index/type/_search?pretty=true -d ' { &quot;query&quot; : { &quot;match_all&quot; : {} }, &quot;fields&quot;: [&quot;document_field_to_be_returned&quot;] } ' </code></pre>
17,508,027
Can't access cookies from document.cookie in JS, but browser shows cookies exist
<p>I can't access any cookie from JavaScript. I need to read some value and send them via JSON for my custom checks.</p> <p>I've tried to access cookies from JS, like it was described at:</p> <ul> <li><a href="http://www.w3schools.com/js/js_cookies.asp" rel="noreferrer">http://www.w3schools.com/js/js_cookies.asp</a></li> <li><a href="https://stackoverflow.com/questions/10730362/javascript-get-cookie-by-name">Get cookie by name</a></li> </ul> <p>As you can see at the code, it's seen as clear as a crystal the next:</p> <pre><code>var c_value = document.cookie; </code></pre> <p>When I'm trying to access the <code>document.cookie</code> value from the Chrome's web-debugger, I see only the empty string at the <strong>Watch expressions</strong>:</p> <p>So I can't read cookies value, which I need.</p> <p>I've checked the cookie name, which I'm sending to get an associated value IS correct. Also, I'm using the <strong>W3Schools</strong> source code for getting cookies, if you're interested (but from the 2nd link, the technique is similar).</p> <p>How can I fix my issue?</p>
17,508,321
6
11
null
2013-07-06 23:35:36.007 UTC
23
2020-07-16 18:03:44.723 UTC
2020-07-16 17:55:54.663 UTC
null
5,446,749
user2402179
null
null
1
88
javascript|cookies|get|document|key-value
89,252
<p>You are most likely dealing with <code>httponly</code> cookies. <code>httponly</code> is a flag you can set on cookies meaning they can not be accessed by JavaScript. This is to prevent malicious scripts stealing cookies with sensitive data or even entire sessions.</p> <p>So you either have to disable the <code>httponly</code> flag or you need to find another way to get the data to your javascript.</p> <p>By looking at your code it should be easy to disable the http only flag:</p> <pre><code>Response.AddHeader("Set-Cookie", "CookieName=CookieValue; path=/;"); Response.SetCookie(new HttpCookie("session-id") { Value = Guid.NewGuid().ToString(), HttpOnly = false }); Response.SetCookie(new HttpCookie("user-name") { Value = data.Login, HttpOnly = false }); </code></pre> <p>Now you should be able to access the cookie information from JavaScript. However I don't know exactly what kind of data you are trying to get so maybe you can go for another approach instead and for example render some data attribute on the page with the information you need instead of trying to read the cookie:</p> <pre><code>&lt;div id="example" data-info="whatever data you are trying to retrieve"&gt;&lt;/div&gt; </code></pre> <p> <pre><code>console.log(document.getElementById('example').getAttribute('data-info')); </code></pre>
17,236,796
How to remove old Docker containers
<p>This question is related to <em><a href="https://stackoverflow.com/questions/17014263/should-i-be-concerned-about-excess-non-running-docker-containers">Should I be concerned about excess, non-running, Docker containers?</a></em>.</p> <p>I'm wondering how to remove old containers. The <code>docker rm 3e552code34a</code> lets you remove a single one, but I have lots already. <code>docker rm --help</code> doesn't give a selection option (like all, or by image name).</p> <p>Maybe there is a directory in which these containers are stored where I can delete them easily manually?</p>
17,237,701
66
7
null
2013-06-21 13:41:42.82 UTC
524
2022-07-10 19:08:20.217 UTC
2017-05-23 11:55:19.593 UTC
null
-1
null
1,449,361
null
1
1,419
docker
823,626
<p>Since <a href="https://github.com/moby/moby/blob/master/CHANGELOG.md#1130-2017-01-18" rel="noreferrer">Docker 1.13.x</a> you can use <a href="https://docs.docker.com/engine/reference/commandline/container_prune/" rel="noreferrer">Docker container prune</a>:</p> <pre><code>docker container prune </code></pre> <p>This will remove all stopped containers and should work on all platforms the same way.</p> <p>There is also a <a href="https://docs.docker.com/engine/reference/commandline/system_prune/" rel="noreferrer">Docker system prune</a>:</p> <pre><code>docker system prune </code></pre> <p>which will clean up all unused containers, networks, images (both dangling and unreferenced), and optionally, volumes, in one command.</p> <hr> <p>For older Docker versions, you can string Docker commands together with other Unix commands to get what you need. Here is an example on how to clean up old containers that are weeks old:</p> <pre><code>$ docker ps --filter "status=exited" | grep 'weeks ago' | awk '{print $1}' | xargs --no-run-if-empty docker rm </code></pre> <p>To give credit, where it is due, this example is from <a href="https://twitter.com/jpetazzo/status/347431091415703552" rel="noreferrer">https://twitter.com/jpetazzo/status/347431091415703552</a>.</p>
18,664,712
Split function add: \xef\xbb\xbf...\n to my list
<p>I want to open my <code>file.txt</code> and split all data from this file.</p> <p>Here is my <code>file.txt</code>:</p> <pre><code>some_data1 some_data2 some_data3 some_data4 some_data5 </code></pre> <p>and here is my python code:</p> <pre><code>&gt;&gt;&gt;file_txt = open("file.txt", 'r') &gt;&gt;&gt;data = file_txt.read() &gt;&gt;&gt;data_list = data.split(' ') &gt;&gt;&gt;print data some_data1 some_data2 some_data3 some_data4 some_data5 &gt;&gt;&gt;print data_list ['\xef\xbb\xbfsome_data1', 'some_data1', "some_data1", 'some_data1', 'some_data1\n'] </code></pre> <p>As you can see here, when I print my <code>data_list</code> it adds to my list this: <code>\xef\xbb\xbf</code> and this: <code>\n</code>. What are these and how can I clean my list from them.</p> <p>Thanks.</p>
18,664,752
3
1
null
2013-09-06 18:58:41.557 UTC
13
2015-12-16 08:42:41.737 UTC
null
null
null
null
2,598,876
null
1
55
python|split
64,873
<p>Your file contains <a href="http://en.wikipedia.org/wiki/Byte_order_mark">UTF-8 BOM</a> in the beginning.</p> <p>To get rid of it, first decode your file contents to unicode.</p> <pre><code>fp = open("file.txt") data = fp.read().decode("utf-8-sig").encode("utf-8") </code></pre> <p>But better don't encode it back to <code>utf-8</code>, but work with <code>unicode</code>d text. There is a good rule: decode all your input text data to unicode as soon as possible, and work only with unicode; and encode the output data to the required encoding as late as possible. This will save you from many headaches.</p> <p>To read bigger files in a certain encoding, use <a href="https://docs.python.org/2/library/io.html#io.open"><code>io.open</code></a> or <a href="http://docs.python.org/2/library/codecs.html#codecs.open"><code>codecs.open</code></a>.</p> <p>Also check <a href="http://docs.python.org/2/howto/unicode.html#reading-and-writing-unicode-data">this</a>.</p> <p>Use <a href="http://docs.python.org/2/library/stdtypes.html#str.strip"><code>str.strip()</code></a> or <a href="http://docs.python.org/2/library/stdtypes.html#str.rstrip"><code>str.rstrip()</code></a> to get rid of the newline character <code>\n</code>.</p>
18,361,689
How to format number of decimal places in wpf using style/template?
<p>I am writing a WPF program and I am trying to figure out a way to format data in a TextBox through some repeatable method like a style or template. I have a lot of TextBoxes (95 to be exact) and each one is bound to its own numeric data which can each have their own resolution defined. For example if the data is 99.123 with a resolution of 2 then it should display 99.12. Similarly a data value of 99 and resolution 3 should be displayed as 99.000 (not 99). Is there a way to do this?</p> <p><strong>Edit:</strong> I should clarify, there are 95 TextBoxes on the current screen I'm working on, but I want every TextBox throughout the various screens in my program to display the correct number of decimal places. Now that I think about it, some of these are TextBoxes (like the screen I'm working on now) and some are DataGrids or ListViews, but if I can figure out how to get it working for TextBoxes I'm sure I can figure it out for the other controls as well.</p> <p>There's not much code to share in this case but I'll attempt to make it clearer:</p> <p>I have a View Model which contains the following properties (vb.net):</p> <pre><code> Public ReadOnly Property Resolution As Integer Get Return _signal.DisplayResolution End Get End Property Public ReadOnly Property Value As Single Get Return Math.Round(_signal.DisplayValue, Resolution) End Get End Property </code></pre> <p>and in the XAML I have:</p> <pre><code>&lt;UserControl.Resources&gt; &lt;vm:SignalViewModel x:Key="Signal" SignalPath="SomeSignal"/&gt; &lt;/UserControl.Resources&gt; &lt;TextBox Grid.Column="3" IsEnabled="False" Text="{Binding Path=Value, Source={StaticResource Signal}, Mode=OneWay}" /&gt; </code></pre> <p><strong>EDIT2 (my solution):</strong> It turns out that after walking away from the computer for a while, I came back to find a simple answer that was staring me in the face. Format the data in the view model!</p> <pre><code> Public ReadOnly Property Value As String Get Return (Strings.FormatNumber(Math.Round(_signal.DisplayValue, _signal.DisplayResolution), _signal.DisplayResolution)) End Get End Property </code></pre>
18,362,876
3
3
null
2013-08-21 15:33:11.203 UTC
19
2018-01-04 09:37:23.28 UTC
2016-03-16 16:22:54.257 UTC
null
479,384
null
2,472,324
null
1
105
wpf|xaml|data-binding|string-formatting
228,075
<p>You should use the <code>StringFormat</code> on the <code>Binding</code>. You can use either <a href="http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx" rel="noreferrer">standard string formats</a>, or <a href="http://msdn.microsoft.com/en-us/library/0c899ak8.aspx" rel="noreferrer">custom string formats</a>:</p> <pre><code>&lt;TextBox Text="{Binding Value, StringFormat=N2}" /&gt; &lt;TextBox Text="{Binding Value, StringFormat={}{0:#,#.00}}" /&gt; </code></pre> <p>Note that the <code>StringFormat</code> only works when the target property is of type string. If you are trying to set something like a <code>Content</code> property (<code>typeof(object)</code>), you will need to use a custom <code>StringFormatConverter</code> (<a href="http://lambert.geek.nz/2009/03/03/stringformatconverter/" rel="noreferrer">like here</a>), and pass your format string as the <code>ConverterParameter</code>.</p> <p><strong>Edit for updated question</strong></p> <p>So, if your <code>ViewModel</code> defines the precision, I'd recommend doing this as a <code>MultiBinding</code>, and creating your own <code>IMultiValueConverter</code>. This is pretty annoying in practice, to go from a simple binding to one that needs to be expanded out to a <code>MultiBinding</code>, but if the precision isn't known at compile time, this is pretty much all you can do. Your <code>IMultiValueConverter</code> would need to take the value, and the precision, and output the formatted string. You'd be able to do this using <code>String.Format</code>.</p> <p>However, for things like a <code>ContentControl</code>, you can much more easily do this with a <code>Style</code>:</p> <pre><code>&lt;Style TargetType="{x:Type ContentControl}"&gt; &lt;Setter Property="ContentStringFormat" Value="{Binding Resolution, StringFormat=N{0}}" /&gt; &lt;/Style&gt; </code></pre> <p>Any control that exposes a <code>ContentStringFormat</code> can be used like this. Unfortunately, <code>TextBox</code> doesn't have anything like that.</p>
18,642,371
Checkbox not binding to scope in angularjs
<p>I am trying to bind a checkbox to scope using ng-model. The checkbox's initial state corresponds to the scope model just fine, but when I check/uncheck the checkbox, the model does not change. Some things to note is that the template is dynamically loaded at runtime using ng-include</p> <pre><code>app.controller "OrdersController", ($scope, $http, $location, $state, $stateParams, Order) -&gt; $scope.billing_is_shipping = false $scope.bind_billing_to_shipping = -&gt; console.log $scope.billing_is_shipping &lt;input type="checkbox" ng-model="billing_is_shipping"/&gt; </code></pre> <p>When I check the box the console logs false, when I uncheck the box, the console again logs false. I also have an order model on the scope, and if I change the checkbox's model to be order.billing_is_shipping, it works fine</p>
23,943,930
4
0
null
2013-09-05 17:23:58.85 UTC
15
2016-04-07 21:28:03.02 UTC
2013-09-05 17:39:16.053 UTC
null
234,867
null
234,867
null
1
63
angularjs|binding|checkbox|coffeescript|angularjs-ng-include
58,121
<p>I struggled with this problem for a while. What worked was to bind the input to an object instead of a primitive.</p> <pre><code>&lt;!-- Partial --&gt; &lt;input type="checkbox" ng-model="someObject.someProperty"&gt; Check Me! // Controller $scope.someObject.someProperty = false </code></pre>
5,205,411
get value of an attribute of the clicked element
<pre><code>&lt;ul id='langs'&gt; &lt;li data-val='en'&gt;english&lt;/li&gt; &lt;li data-val='fr'&gt;francais&lt;/li&gt; &lt;li data-val='it'&gt;italiano&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>when the user clicks on any of these <code>&lt;li&gt;</code> I want to <code>alert()</code> it's data-val attribute value</p> <p>anybody knows how?</p>
5,205,424
3
0
null
2011-03-05 17:20:03.16 UTC
5
2017-02-19 20:33:59.413 UTC
null
null
null
null
112,100
null
1
33
javascript|jquery
58,948
<h2>Original answer - 2011</h2> <pre><code>$('li').click(function () { alert($(this).data('val')); }); </code></pre> <p>See <a href="http://jsfiddle.net/UcHuD/" rel="noreferrer"><strong>DEMO</strong></a>.</p> <h2>Update - 2017</h2> <p>Keep in mind that if you want to use the ES6 <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions" rel="noreferrer">arrow function</a> syntax, you cannot use <code>this</code> and you need to use <code>e.currentTarget</code> instead, where <code>e</code> is the event object passed as the first parameter to the event handler:</p> <pre><code>$('li').click(e =&gt; alert($(e.currentTarget).data('val'))); </code></pre> <p>See <a href="http://jsfiddle.net/rsp/67a75j3b/1/" rel="noreferrer"><strong>DEMO</strong></a>.</p>
9,150,446
compareTo with primitives -> Integer / int
<p>Is it better to write</p> <pre><code>int primitive1 = 3, primitive2 = 4; Integer a = new Integer(primitive1); Integer b = new Integer(primitive2); int compare = a.compareTo(b); </code></pre> <p>or </p> <pre><code>int primitive1 = 3, primitive2 = 4; int compare = (primitive1 &gt; primitive2) ? 1 : 0; if(compare == 0){ compare = (primitive1 == primitive2) ? 0 : -1; } </code></pre> <p>I think the second one is better, should be faster and more memory optimized. But aren't they equal?</p>
9,150,459
8
5
null
2012-02-05 15:30:36.033 UTC
10
2019-01-18 14:21:58.837 UTC
null
null
null
null
492,624
null
1
70
java|performance|compareto
158,488
<p>For performance, it usually best to make the code as simple and clear as possible and this will often perform well (as the JIT will optimise this code best). In your case, the simplest examples are also likely to be the fastest.</p> <hr> <p>I would do either</p> <pre><code>int cmp = a &gt; b ? +1 : a &lt; b ? -1 : 0; </code></pre> <p>or a longer version</p> <pre><code>int cmp; if (a &gt; b) cmp = +1; else if (a &lt; b) cmp = -1; else cmp = 0; </code></pre> <p>or</p> <pre><code>int cmp = Integer.compare(a, b); // in Java 7 int cmp = Double.compare(a, b); // before Java 7 </code></pre> <p>It's best not to create an object if you don't need to.</p> <p>Performance wise, the first is best.</p> <p>If you know for sure that you won't get an overflow you can use</p> <pre><code>int cmp = a - b; // if you know there wont be an overflow. </code></pre> <p>you won't get faster than this.</p>
15,452,081
Kill all processes for a given user
<p>Is there a reliable way to kill all the processes of a given user? <code>kill(-1, SIGKILL)</code> as that user will work, unless a rogue process of that user kills the killing process first. The best I can find so far is to loop through <code>system("ps -u")</code> for that user and kill the processes that way, but that seems really hacky and inefficient.</p> <p>EDIT: To clarify, I'm specifically asking for a POSIX-compatable solution. For some reason I thought tagging the question posix would put that in the title.</p>
15,452,152
5
2
null
2013-03-16 17:04:29.55 UTC
31
2018-02-08 18:27:27.793 UTC
2013-03-16 17:22:34.77 UTC
null
636,917
null
636,917
null
1
78
posix
201,291
<p>Just (temporarily) killed my Macbook with</p> <pre><code>killall -u pu -m . </code></pre> <p>where pu is my userid. Watch the dot at the end of the command.</p> <p>Also try</p> <pre><code>pkill -u pu </code></pre> <p>or </p> <pre><code>ps -o pid -u pu | xargs kill -1 </code></pre>
43,537,958
Change Toolbar overflow icon color
<p>I have an <code>android.support.v7.widget</code> Toolbar in my Android app. The background color of this is bright orange and the best looking color on top of this would be white instead of black.</p> <p>I have the default color on black and not white. Since it would conflict with other stuff, that is almost impossible to override. <strong>I cannot change the primary text color to white!</strong></p> <p>I've managed to change the title color. <strong>What I'm looking for right now is how I can change the action button color as well (to white).</strong></p> <p><a href="https://i.stack.imgur.com/r6gQI.png" rel="noreferrer"><img src="https://i.stack.imgur.com/r6gQI.png" alt="enter image description here"></a></p> <p>My code:</p> <p>Main activity:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" xmlns:app="http://schemas.android.com/apk/res-auto" tools:context=".UI.activities.MainActivity"&gt; &lt;android.support.v7.widget.Toolbar android:id="@+id/r2_toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" android:elevation="4dp" app:titleTextColor="@color/primary_text_material_light" app:subtitleTextColor="@color/primary_text_material_light" android:theme="@style/R2Theme.Toolbar"/&gt; &lt;fragment android:name="com.r2retail.r2retailapp.UI.fragments.SetupFragment" android:layout_below="@+id/r2_toolbar" android:id="@+id/list" android:layout_weight="1" android:layout_width="match_parent" android:layout_height="match_parent" /&gt; &lt;/RelativeLayout&gt; </code></pre> <p>Menu bar:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"&gt; &lt;item android:id="@+id/about" android:icon="@drawable/ic_menu" android:title="About" app:showAsAction="never"/&gt; &lt;/menu&gt; </code></pre> <p>Styles:</p> <pre><code>&lt;resources&gt; &lt;style name="R2Theme" parent="Theme.AppCompat.Light.NoActionBar"&gt;= &lt;item name="colorPrimary"&gt;@color/colorPrimary&lt;/item&gt; &lt;item name="colorPrimaryDark"&gt;@color/colorPrimaryDark&lt;/item&gt; &lt;item name="colorAccent"&gt;@color/colorPrimary&lt;/item&gt; &lt;item name="android:textColorPrimary"&gt;@color/secondary_text_material_dark&lt;/item&gt; &lt;item name="android:textColorSecondaryInverse"&gt;@color/primary_text_material_light&lt;/item&gt; &lt;/style&gt; &lt;style name="R2Theme.Toolbar" parent="R2Theme"&gt; &lt;item name="actionMenuTextColor"&gt;@color/primary_text_material_light&lt;/item&gt; &lt;/style&gt; &lt;/resources&gt; </code></pre>
43,539,097
6
3
null
2017-04-21 08:43:48.84 UTC
11
2021-07-05 22:20:39.163 UTC
2018-12-25 08:13:09.157 UTC
null
1,000,551
null
7,185,011
null
1
27
java|android|android-layout|android-view|android-toolbar
25,381
<p>In styles:</p> <pre><code>&lt;style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"&gt; ... &lt;item name="actionOverflowButtonStyle"&gt;@style/MyOverflowButtonStyle&lt;/item&gt; &lt;/style&gt; &lt;style name="MyOverflowButtonStyle" parent="Widget.AppCompat.ActionButton.Overflow"&gt; &lt;item name="android:tint"&gt;#62ff00&lt;/item&gt; &lt;/style&gt; </code></pre> <p>Result:</p> <p><a href="https://i.stack.imgur.com/KXblW.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/KXblW.gif" alt="enter image description here"></a></p>
8,400,150
How to relate to type from outer context
<p>Let us consider the following code snippet:</p> <pre><code>blah :: a -&gt; b -&gt; a blah x y = ble x where ble :: b -&gt; b ble x = x </code></pre> <p>This compiles fine under GHC, which essentially means that <code>b</code> from the 3rd line is something different than <code>b</code> from the first line. </p> <p>My question is simple: is there a way to somehow relate in the type declaration of <code>ble</code> to a type used in an outer context, i.e. the type declaration of <code>blah</code>?</p> <p>Obviously, this is just an example and not a real-world use-case for type declarations.</p>
8,400,414
2
3
null
2011-12-06 12:50:18.787 UTC
6
2011-12-06 22:47:05.76 UTC
null
null
null
null
475,763
null
1
34
haskell|types|functional-programming|ghc|type-declaration
846
<p>This is possible with the <a href="http://haskell.org/ghc/docs/6.12.2/html/users_guide/other-type-extensions.html#scoped-type-variables">ScopedTypeVariables</a> extension. You need to use explicit forall's to bring the type variables into scope.</p> <pre><code>blah :: forall a b. a -&gt; b -&gt; a blah x y = ble x where ble :: b -&gt; b ble x = x </code></pre> <p>Trying to load this definition with ScopedTypeVariables enabled gives:</p> <pre><code>foo.hs:2:16: Couldn't match type `a' with `b' `a' is a rigid type variable bound by the type signature for blah :: a -&gt; b -&gt; a at foo.hs:2:1 `b' is a rigid type variable bound by the type signature for blah :: a -&gt; b -&gt; a at foo.hs:2:1 In the first argument of `ble', namely `x' In the expression: ble x In an equation for `blah': blah x y = ble x where ble :: b -&gt; b ble x = x </code></pre> <p>You can tell that GHC interprets the two <code>b</code>s as the same type because the error says that <code>a</code> and <code>b</code> are bound on the same line.</p>
8,654,064
Ubuntu-ssh - - WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED
<p>I'm unable to ssh and rysnc to a remote system. It keeps giving this error message:</p> <pre><code>WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY! Someone could be eavesdropping on you right now (man-in-the-middle attack)! It is also possible that a host key has just been changed. The fingerprint for the RSA key sent by the remote host is a3:8f:7c:07:c9:12:d8:aa:cd:c2:ba:b3:27:68:bc:c2. Please contact your system administrator. Add correct host key in /root/.ssh/known_hosts to get rid of this message. Offending RSA key in /root/.ssh/known_hosts:8 RSA host key for xxx.xxx.xxx.xxx has changed and you have requested strict checking. Host key verification failed. rsync: connection unexpectedly closed (0 bytes received so far) [sender] rsync error: unexplained error (code 255) at io.c(601) [sender=3.0.8] </code></pre> <p>I've removed <code>authorized_keys</code> file from <code>/home/user/.ssh</code>.</p>
8,654,121
5
3
null
2011-12-28 09:28:54.563 UTC
21
2015-07-08 15:18:05.937 UTC
2015-07-08 15:18:05.937 UTC
null
660,921
null
1,095,608
null
1
64
ssh|openssh
75,800
<p>The message says "<code>/root/.ssh/known_hosts</code>" not authorized_keys. Remove that file (or at least the corresponding key) from it and you can go again! But be aware that: There must be a reason why the key changed. Was the system reinstalled? Make sure you check that or the whole idea of ssh is void.</p> <p>BTW.: Is there a reason you ssh as root?</p>
8,833,835
Python Selenium WebDriver drag-and-drop
<p>I cannot get drag-and drop working with the Python WebDriver bindings. I am working with Google Chrome and Firefox on Mac OS X. There is a thread <a href="http://code.google.com/p/selenium/issues/detail?id=1279">here</a> where someone had a similar problem.</p> <p>I have tried using <code>ActionsChains</code>:</p> <pre><code>from selenium import webdriver from selenium.webdriver import ActionChains driver = webdriver.Chrome() actionChains = ActionChains(driver) actionChains.drag_and_drop(source, target).perform() </code></pre> <p>Have you managed to get the Python WebDriver drag-and-drop working?</p>
25,087,805
4
4
null
2012-01-12 10:51:26.787 UTC
5
2020-03-24 09:16:18.98 UTC
2012-01-16 20:08:58.917 UTC
null
707,381
null
707,381
null
1
18
python|selenium|webdriver
41,017
<p>For the sake of giving an updated answer, I have verified that this does in fact work on Mac now.</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains driver = webdriver.Firefox() driver.get("your.site.with.dragndrop.functionality.com") source_element = driver.find_element_by_name('your element to drag') dest_element = driver.find_element_by_name('element to drag to') ActionChains(driver).drag_and_drop(source_element, dest_element).perform() </code></pre> <p><a href="http://www.seleniumhq.org/docs/03_webdriver.jsp#drag-and-drop" rel="noreferrer">Reference</a></p>
31,182,637
Delay/Wait in a test case of Xcode UI testing
<p>I am trying to write a test case using the new UI Testing available in Xcode 7 beta 2. The App has a login screen where it makes a call to the server to login. There is a delay associated with this as it is an asynchronous operation.</p> <p>Is there a way to cause a delay or wait mechanism in the XCTestCase before proceeding to further steps?</p> <p>There is no proper documentation available and I went through the Header files of the classes. Was not able to find anything related to this.</p> <p>Any ideas/suggestions?</p>
32,228,104
14
5
null
2015-07-02 10:55:49.91 UTC
44
2022-02-03 08:59:41.403 UTC
2019-07-02 19:10:00.763 UTC
null
4,770,877
null
2,369,370
null
1
213
ios|ios9|xcode-ui-testing|xcode7-beta2|xctwaiter
129,931
<p>Asynchronous UI Testing was introduced in Xcode 7 Beta 4. To wait for a label with the text "Hello, world!" to appear you can do the following:</p> <pre><code>let app = XCUIApplication() app.launch() let label = app.staticTexts["Hello, world!"] let exists = NSPredicate(format: "exists == 1") expectationForPredicate(exists, evaluatedWithObject: label, handler: nil) waitForExpectationsWithTimeout(5, handler: nil) </code></pre> <p>More <a href="http://masilotti.com/ui-testing-xcode-7/">details about UI Testing</a> can be found on my blog.</p>
31,026,741
group by and filter data management using dplyr
<p>Take a simple dataset</p> <pre><code>a &lt;- c(1,2,3,4,5,6,7,8) b &lt;- c(1,2,2,1,2,2,2,2) c &lt;- c(1,1,1,2,2,2,3,3) d &lt;- data.frame(a,b,c) </code></pre> <p>now I want to filter my data, so that we <code>group_by(c)</code> and then remove all data where no <code>b=1</code>occurs.</p> <p>Thus the results (<code>e</code>) should look like <code>d</code> but without the two bottom rows</p> <p>I have tried using</p> <pre><code>e &lt;- d %&gt;% group_by(c) %&gt;% filter(n(b)&gt;1) </code></pre> <p>The output should contain the data in green below and remove the data in red</p> <p><img src="https://i.stack.imgur.com/qIao7.png" alt="enter image description here"></p>
31,027,426
2
6
null
2015-06-24 12:35:11.847 UTC
4
2021-09-01 11:59:47.77 UTC
2015-06-24 12:54:38.947 UTC
null
3,944,231
null
3,944,231
null
1
21
r|dplyr
39,099
<p>Try</p> <pre><code>d %&gt;% group_by(c) %&gt;% filter(any(b == 1)) </code></pre> <p>Which gives:</p> <pre><code>#Source: local data frame [6 x 3] #Groups: c # # a b c #1 1 1 1 #2 2 2 1 #3 3 2 1 #4 4 1 2 #5 5 2 2 #6 6 2 2 </code></pre>
5,532,878
how to copy codes in vi to clipboard
<p>I know how to copy in VI. but I failed to copy it into other application. That means I failed copy those into clipboard. How can I do this?</p> <p>P.S. In order to lean more. I also want to ask how to copy content from clipboard to vi.</p> <p>Edited: I am using MacOs. running Vim.</p> <p>It seems *yy doesn't work here. Any other ways?</p>
5,532,889
4
1
null
2011-04-03 22:08:10.69 UTC
9
2017-11-29 22:08:00.177 UTC
2017-11-29 22:08:00.177 UTC
null
3,885,376
null
435,645
null
1
19
vi
51,905
<p>You need to use the clipboard register, which is <code>*</code>, so to copy a line of text into clipboard:</p> <pre><code>"*yy </code></pre> <p>To paste a line of text from the clipboard:</p> <pre><code> "*p </code></pre>
5,296,445
Split string by char in java
<p>I'm getting a string from the web looking like this:</p> <pre><code>Latest Episode@04x22^Killing Your Number^May/15/2009 </code></pre> <p>Then I need to store <code>04x22</code>, <code>Killing Your Number</code> and <code>May/15/2009</code> in diffent variables, but it won't work.</p> <pre><code>String[] all = inputLine.split("@"); String[] need = all[1].split("^"); show.setNextNr(need[0]); show.setNextTitle(need[1]); show.setNextDate(need[2]); </code></pre> <p>Now it only stores <code>NextNr</code>, with the whole string</p> <pre><code>04x22^Killing Your Number^May/15/2009 </code></pre> <p>What is wrong?</p>
5,296,471
5
0
null
2011-03-14 08:49:37.657 UTC
1
2015-08-05 10:21:52.777 UTC
2011-03-14 08:53:22.473 UTC
null
73,070
null
648,527
null
1
14
java|regex|string|split
64,390
<p><code>String.split(String regex)</code> </p> <p>The argument is a regualr expression, and <code>^</code> has a special meaning there; "anchor to beginning"</p> <p>You need to do:</p> <p><code>String[] need = all[1].split("\\^");</code></p> <p>By escaping the <code>^</code> you're saying "I mean the character '^' "</p>
5,446,647
How can I use var_dump + output buffering without memory errors?
<p>I'm using a debugging aid in an application that uses <code>var_dump()</code> with output buffering to capture variables and display them. However, I'm running into an issue with large objects that end up using up too much memory in the buffer.</p> <pre><code>function getFormattedOutput(mixed $var) { if (isTooLarge($var)) { return 'Too large! Abort!'; // What a solution *might* look like } ob_start(); var_dump($var); // Fatal error: Allowed memory size of 536870912 bytes exhausted $data = ob_get_clean(); // Return the nicely-formated data to use later return $data } </code></pre> <p>Is there a way I can prevent this? Or a work-around to detect that it's about to output a gigantic amount of info for a particular variable? I don't really have control which variables get passed into this function. It could be any type. </p>
13,950,115
5
12
null
2011-03-27 01:41:17.033 UTC
3
2018-06-15 13:19:57.49 UTC
2012-12-13 13:48:06.88 UTC
null
46,675
null
46,675
null
1
42
php|memory
7,240
<p>Well, if the physical memory is limited (you see the fatal error:)</p> <blockquote> <p>Fatal error: Allowed memory size of 536870912 bytes exhausted</p> </blockquote> <p>I would suggest to do the output buffering on disk (see callback parameter on <a href="http://php.net/ob_start" rel="noreferrer"><code>ob_start</code></a>). Output buffering works chunked, that means, if there still is enough memory to keep the single chunk in memory, you can store it into a temporary file.</p> <pre><code>// handle output buffering via callback, set chunksize to one kilobyte ob_start($output_callback, $chunk_size = 1024); </code></pre> <p>However you must keep in mind that this will only prevent the fatal error while buffering. If you now want to return the buffer, you still need to have enough memory <em>or</em> you return the file-handle or file-path so that you can also stream the output.</p> <p>However you can use that file then to obtain the size in bytes needed. The overhead for PHP strings is not much IIRC, so if there still is enough memory free for the filesize this should work well. You can substract offset to have a little room and play safe. Just try and error a little what it makes.</p> <p>Some Example code (PHP 5.4):</p> <pre><code>&lt;?php /** * @link http://stackoverflow.com/questions/5446647/how-can-i-use-var-dump-output-buffering-without-memory-errors/ */ class OutputBuffer { /** * @var int */ private $chunkSize; /** * @var bool */ private $started; /** * @var SplFileObject */ private $store; /** * @var bool Set Verbosity to true to output analysis data to stderr */ private $verbose = true; public function __construct($chunkSize = 1024) { $this-&gt;chunkSize = $chunkSize; $this-&gt;store = new SplTempFileObject(); } public function start() { if ($this-&gt;started) { throw new BadMethodCallException('Buffering already started, can not start again.'); } $this-&gt;started = true; $result = ob_start(array($this, 'bufferCallback'), $this-&gt;chunkSize); $this-&gt;verbose &amp;&amp; file_put_contents('php://stderr', sprintf("Starting Buffering: %d; Level %d\n", $result, ob_get_level())); return $result; } public function flush() { $this-&gt;started &amp;&amp; ob_flush(); } public function stop() { if ($this-&gt;started) { ob_flush(); $result = ob_end_flush(); $this-&gt;started = false; $this-&gt;verbose &amp;&amp; file_put_contents('php://stderr', sprintf("Buffering stopped: %d; Level %d\n", $result, ob_get_level())); } } private function bufferCallback($chunk, $flags) { $chunkSize = strlen($chunk); if ($this-&gt;verbose) { $level = ob_get_level(); $constants = ['PHP_OUTPUT_HANDLER_START', 'PHP_OUTPUT_HANDLER_WRITE', 'PHP_OUTPUT_HANDLER_FLUSH', 'PHP_OUTPUT_HANDLER_CLEAN', 'PHP_OUTPUT_HANDLER_FINAL']; $flagsText = ''; foreach ($constants as $i =&gt; $constant) { if ($flags &amp; ($value = constant($constant)) || $value == $flags) { $flagsText .= (strlen($flagsText) ? ' | ' : '') . $constant . "[$value]"; } } file_put_contents('php://stderr', "Buffer Callback: Chunk Size $chunkSize; Flags $flags ($flagsText); Level $level\n"); } if ($flags &amp; PHP_OUTPUT_HANDLER_FINAL) { return TRUE; } if ($flags &amp; PHP_OUTPUT_HANDLER_START) { $this-&gt;store-&gt;fseek(0, SEEK_END); } $chunkSize &amp;&amp; $this-&gt;store-&gt;fwrite($chunk); if ($flags &amp; PHP_OUTPUT_HANDLER_FLUSH) { // there is nothing to d } if ($flags &amp; PHP_OUTPUT_HANDLER_CLEAN) { $this-&gt;store-&gt;ftruncate(0); } return ""; } public function getSize() { $this-&gt;store-&gt;fseek(0, SEEK_END); return $this-&gt;store-&gt;ftell(); } public function getBufferFile() { return $this-&gt;store; } public function getBuffer() { $array = iterator_to_array($this-&gt;store); return implode('', $array); } public function __toString() { return $this-&gt;getBuffer(); } public function endClean() { return ob_end_clean(); } } $buffer = new OutputBuffer(); echo "Starting Buffering now.\n=======================\n"; $buffer-&gt;start(); foreach (range(1, 10) as $iteration) { $string = "fill{$iteration}"; echo str_repeat($string, 100), "\n"; } $buffer-&gt;stop(); echo "Buffering Results:\n==================\n"; $size = $buffer-&gt;getSize(); echo "Buffer Size: $size (string length: ", strlen($buffer), ").\n"; echo "Peeking into buffer: ", var_dump(substr($buffer, 0, 10)), ' ...', var_dump(substr($buffer, -10)), "\n"; </code></pre> <p>Output:</p> <pre><code>STDERR: Starting Buffering: 1; Level 1 STDERR: Buffer Callback: Chunk Size 1502; Flags 1 (PHP_OUTPUT_HANDLER_START[1]); Level 1 STDERR: Buffer Callback: Chunk Size 1503; Flags 0 (PHP_OUTPUT_HANDLER_WRITE[0]); Level 1 STDERR: Buffer Callback: Chunk Size 1503; Flags 0 (PHP_OUTPUT_HANDLER_WRITE[0]); Level 1 STDERR: Buffer Callback: Chunk Size 602; Flags 4 (PHP_OUTPUT_HANDLER_FLUSH[4]); Level 1 STDERR: Buffer Callback: Chunk Size 0; Flags 8 (PHP_OUTPUT_HANDLER_FINAL[8]); Level 1 STDERR: Buffering stopped: 1; Level 0 Starting Buffering now. ======================= Buffering Results: ================== Buffer Size: 5110 (string length: 5110). Peeking into buffer: string(10) "fill1fill1" ...string(10) "l10fill10\n" </code></pre>
4,909,263
How to efficiently de-interleave bits (inverse Morton)
<p>This question: <a href="https://stackoverflow.com/questions/3137266/how-to-de-interleave-bits-unmortonizing">How to de-interleave bits (UnMortonizing?)</a> has a good answer for extracting one of the two halves of a Morton number (just the odd bits), but I need a solution which extracts both parts (the odd bits and the even bits) in as few operations as possible.</p> <p>For my use I would need to take a 32 bit int and extract two 16 bit ints, where one is the even bits and the other is the odd bits shifted right by 1 bit, e.g.</p> <pre><code>input, z: 11101101 01010111 11011011 01101110 output, x: 11100001 10110111 // odd bits shifted right by 1 y: 10111111 11011010 // even bits </code></pre> <p>There seem to be plenty of solutions using shifts and masks with magic numbers for generating Morton numbers (i.e. interleaving bits), e.g. <a href="http://graphics.stanford.edu/~seander/bithacks.html#InterleaveBMN" rel="noreferrer">Interleave bits by Binary Magic Numbers</a>, but I haven't yet found anything for doing the reverse (i.e. de-interleaving).</p> <p><strong>UPDATE</strong></p> <p>After re-reading the section from Hacker's Delight on perfect shuffles/unshuffles I found some useful examples which I adapted as follows:</p> <pre><code>// morton1 - extract even bits uint32_t morton1(uint32_t x) { x = x &amp; 0x55555555; x = (x | (x &gt;&gt; 1)) &amp; 0x33333333; x = (x | (x &gt;&gt; 2)) &amp; 0x0F0F0F0F; x = (x | (x &gt;&gt; 4)) &amp; 0x00FF00FF; x = (x | (x &gt;&gt; 8)) &amp; 0x0000FFFF; return x; } // morton2 - extract odd and even bits void morton2(uint32_t *x, uint32_t *y, uint32_t z) { *x = morton1(z); *y = morton1(z &gt;&gt; 1); } </code></pre> <p>I think this can still be improved on, both in its current scalar form and also by taking advantage of SIMD, so I'm still interested in better solutions (either scalar or SIMD).</p>
4,925,461
6
7
null
2011-02-05 19:48:42.31 UTC
11
2021-12-10 06:06:57.92 UTC
2018-04-02 06:25:52.783 UTC
null
253,056
null
253,056
null
1
23
bit-manipulation|z-order-curve
8,319
<p>If your processor handles 64 bit ints efficiently, you could combine the operations...</p> <pre><code>int64 w = (z &amp;0xAAAAAAAA)&lt;&lt;31 | (z &amp;0x55555555 ) w = (w | (w &gt;&gt; 1)) &amp; 0x3333333333333333; w = (w | (w &gt;&gt; 2)) &amp; 0x0F0F0F0F0F0F0F0F; ... </code></pre>
5,277,293
Is it possible to play HTML5 video in reverse?
<p>Can HTML5 <code>&lt;video&gt;</code> tag be played in reverse, or do I have to download 2 videos (<em>forward and backward play</em>)?</p> <p>I'm looking for a solution that avoids a user from downloading 2 videos.</p>
5,277,352
6
1
null
2011-03-11 19:13:57.123 UTC
6
2022-08-03 05:57:15.95 UTC
2021-11-21 19:33:41.867 UTC
null
1,197,605
null
69,818
null
1
41
javascript|html|html5-video
45,459
<p>Without even going into HTML5 or Javascript, many video formats are <a href="http://en.wikipedia.org/wiki/Streaming_media" rel="noreferrer">streaming</a> formats that are designed to be played forward. Playing it backwards would require decoding the whole stream, storing each raw frame on the disk to avoid clobbering memory, then rendering the frames backwards.</p> <p>At least one person <a href="http://madcompscientist.blogspot.com/2009/03/sdrawkcab-oediv-gniyalp.html" rel="noreferrer">actually tried that</a> using <code>mplayer</code>, though, so it <em>can</em> be done, at least in principle.</p>
5,182,016
What is the difference between $(window).load and $(document).ready?
<p>I have been having a problem lately with my JavaScript CODE and taking a portion of my code out of my <code>$(document).ready()</code> and putting it within <code>$(window).load()</code> fixed the problem. </p> <p>Now I understand that <code>window.load</code> is fired just after <code>document.ready</code>, but why is it not ready after <code>document.ready</code>, that is after <code>window.load()</code>?</p>
5,182,050
9
2
null
2011-03-03 14:27:32.26 UTC
21
2017-12-22 08:18:07.1 UTC
2012-05-09 15:40:10.73 UTC
null
908,879
null
471,379
null
1
71
javascript|jquery|document-ready
62,327
<p><code>load</code> is called when all assets are done loading, including images. <code>ready</code> is fired when the DOM is ready for interaction.</p> <p>From the MDC, <em><a href="https://developer.mozilla.org/en/DOM/window.onload" rel="noreferrer">window.onload</a></em>:</p> <blockquote> <p>The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images and sub-frames have finished loading.</p> </blockquote> <p>From the jQuery API documentation, <em><a href="http://api.jquery.com/ready/" rel="noreferrer">.ready( handler )</a></em>:</p> <blockquote> <p>While JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code. When using scripts that rely on the value of CSS style properties, it's important to reference external stylesheets or embed style elements before referencing the scripts.</p> </blockquote>
5,503,858
How to get tf.exe (TFS command line client)?
<p>What's the minimum amount of software I need to install to get the 'tf.exe' program?</p>
5,507,337
9
0
null
2011-03-31 17:30:43.047 UTC
18
2022-01-20 15:38:51.917 UTC
2012-08-03 15:35:54.923 UTC
null
29,043
null
618,286
null
1
102
tfs|installation|command-line-interface|tf-cli
131,460
<p>You need to install <a href="http://www.microsoft.com/downloads/en/details.aspx?FamilyID=fe4f9904-0480-4c9d-a264-02fedd78ab38" rel="noreferrer">Team Explorer</a>, it's best to install the version of Team Explorer that matches the version of TFS you are using e.g. if you're using TFS 2010 then install Team Explorer 2010.</p> <p>2012 version <a href="http://www.microsoft.com/en-gb/download/details.aspx?id=30656" rel="noreferrer">http://www.microsoft.com/en-gb/download/details.aspx?id=30656</a></p> <p>2013 version <a href="http://www.microsoft.com/en-us/download/details.aspx?id=40776" rel="noreferrer">http://www.microsoft.com/en-us/download/details.aspx?id=40776</a></p> <p>2019 version <a href="https://visualstudio.microsoft.com/downloads/#visual-studio-team-explorer-2019" rel="noreferrer">https://visualstudio.microsoft.com/downloads/#visual-studio-team-explorer-2019</a></p> <p>You also might be interested in the <a href="http://visualstudiogallery.msdn.microsoft.com/c255a1e4-04ba-4f68-8f4e-cd473d6b971f/" rel="noreferrer">TFS power tools</a>. They add some extra command line features (using <code>tfpt.exe</code>) and also add some extra IDE features.</p>
5,255,657
How can I disable logging while running unit tests in Python Django?
<p>I am using a simple unit test based test runner to test my Django application.</p> <p>My application itself is configured to use a basic logger in settings.py using:</p> <pre><code>logging.basicConfig(level=logging.DEBUG) </code></pre> <p>And in my application code using:</p> <pre><code>logger = logging.getLogger(__name__) logger.setLevel(getattr(settings, 'LOG_LEVEL', logging.DEBUG)) </code></pre> <p>However, when running unittests, I'd like to disable logging so that it doesn't clutter my test result output. Is there a simple way to turn off logging in a global way, so that the application specific loggers aren't writing stuff out to the console when I run tests?</p>
5,255,760
20
1
null
2011-03-10 04:59:55.17 UTC
36
2021-11-17 18:21:36.273 UTC
2015-11-10 18:49:13.727 UTC
null
63,550
null
170,589
null
1
208
python|django|unit-testing|logging
72,675
<pre><code>logging.disable(logging.CRITICAL) </code></pre> <p>will disable all logging calls with levels less severe than or equal to <code>CRITICAL</code>. Logging can be re-enabled with</p> <pre><code>logging.disable(logging.NOTSET) </code></pre>
5,229,023
How do I check/uncheck all checkboxes with a button using jQuery?
<p>I am trying to check/uncheck all checkboxes using jQuery. Now by checking/unchecking the parent checkbox all the child checkboxes are getting selected/deselected also with the text of parent checkbox getting changed to checkall/uncheckall. </p> <p>Now I want to replace parent checkbox with an input button, and change the text also on the button to checkall/uncheckall. THere is the code, can anyone please tweak the code ?</p> <pre><code> $( function() { $( '.checkAll' ).live( 'change', function() { $( '.cb-element' ).attr( 'checked', $( this ).is( ':checked' ) ? 'checked' : '' ); $( this ).next().text( $( this ).is( ':checked' ) ? 'Uncheck All' : 'Check All' ); }); $( '.cb-element' ).live( 'change', function() { $( '.cb-element' ).length == $( '.cb-element:checked' ).length ? $( '.checkAll' ).attr( 'checked', 'checked' ).next().text( 'Uncheck All' ) : $( '.checkAll' ).attr( 'checked', '' ).next().text( 'Check All' ); }); }); &lt;input type="checkbox" class="checkAll" /&gt; &lt;b&gt;Check All&lt;/b&gt; &lt;input type="checkbox" class="cb-element" /&gt; Checkbox 1 &lt;input type="checkbox" class="cb-element" /&gt; Checkbox 2 &lt;input type="checkbox" class="cb-element" /&gt; Checkbox 3 </code></pre>
5,230,781
25
0
null
2011-03-08 06:14:13.157 UTC
34
2021-02-25 17:53:02.533 UTC
2020-08-02 19:15:40.387 UTC
null
100,297
null
481,647
null
1
179
jquery|checkbox
454,073
<p>Try this one :</p> <pre><code>$(document).ready(function(){ $('.check:button').toggle(function(){ $('input:checkbox').attr('checked','checked'); $(this).val('uncheck all'); },function(){ $('input:checkbox').removeAttr('checked'); $(this).val('check all'); }) }) </code></pre> <p><a href="http://jsfiddle.net/gubhaju/Vj6wY/3/" rel="noreferrer">DEMO</a></p>
5,067,604
Determine function name from within that function (without using traceback)
<p>In Python, without using the <code>traceback</code> module, is there a way to determine a function's name from within that function?</p> <p>Say I have a module <code>foo</code> with a function <code>bar</code>. When executing <code>foo.bar()</code>, is there a way for <code>bar</code> to know <code>bar</code>'s name? Or better yet, <code>foo.bar</code>'s name?</p> <pre><code>#foo.py def bar(): print &quot;my name is&quot;, __myname__ # &lt;== how do I calculate this at runtime? </code></pre>
5,067,661
26
0
null
2011-02-21 15:11:36.23 UTC
154
2022-06-09 15:33:07.273 UTC
2021-04-29 11:52:09.793 UTC
null
7,851,470
null
609,158
null
1
674
python|function|introspection|traceback
385,408
<p>Python doesn't have a feature to access the function or its name within the function itself. It has been <a href="http://www.python.org/dev/peps/pep-3130/" rel="noreferrer">proposed</a> but rejected. If you don't want to play with the stack yourself, you should either use <code>"bar"</code> or <code>bar.__name__</code> depending on context.</p> <p>The given rejection notice is:</p> <blockquote> <p>This PEP is rejected. It is not clear how it should be implemented or what the precise semantics should be in edge cases, and there aren't enough important use cases given. response has been lukewarm at best.</p> </blockquote>
12,290,091
Reading XML file and fetching its attributes value in Python
<p>I have this XML file:</p> <pre><code>&lt;domain type='kmc' id='007'&gt; &lt;name&gt;virtual bug&lt;/name&gt; &lt;uuid&gt;66523dfdf555dfd&lt;/uuid&gt; &lt;os&gt; &lt;type arch='xintel' machine='ubuntu'&gt;hvm&lt;/type&gt; &lt;boot dev='hd'/&gt; &lt;boot dev='cdrom'/&gt; &lt;/os&gt; &lt;memory unit='KiB'&gt;524288&lt;/memory&gt; &lt;currentMemory unit='KiB'&gt;270336&lt;/currentMemory&gt; &lt;vcpu placement='static'&gt;10&lt;/vcpu&gt; </code></pre> <p>Now, I want parse this and fetch its attribute value. For instance, I want to fetch the <code>uuid</code> field. So what should be the proper method to fetch it, in Python?</p>
12,293,187
7
2
null
2012-09-05 21:31:11.007 UTC
3
2019-01-17 01:15:14.757 UTC
2018-11-20 19:38:03.413 UTC
user8554766
null
null
1,585,585
null
1
8
python|xml|xml-parsing|python-2.7
118,047
<p>Here's an <strong><a href="http://lxml.de/" rel="noreferrer">lxml</a></strong> snippet that extracts an <em>attribute</em> as well as element <em>text</em> (your question was a little ambiguous about which one you needed, so I'm including both):</p> <pre><code>from lxml import etree doc = etree.parse(filename) memoryElem = doc.find('memory') print memoryElem.text # element text print memoryElem.get('unit') # attribute </code></pre> <p>You asked (in a comment on Ali Afshar's answer) whether <strong>minidom</strong> (<a href="https://docs.python.org/2/library/xml.dom.minidom.html" rel="noreferrer">2.x</a>, <a href="https://docs.python.org/3.0/library/xml.dom.minidom.html" rel="noreferrer">3.x</a>) is a good alternative. Here's the equivalent code using minidom; judge for yourself which is nicer:</p> <pre><code>import xml.dom.minidom as minidom doc = minidom.parse(filename) memoryElem = doc.getElementsByTagName('memory')[0] print ''.join( [node.data for node in memoryElem.childNodes] ) print memoryElem.getAttribute('unit') </code></pre> <p>lxml seems like the winner to me.</p>
12,496,075
TimeZone issue in Java XMLGregorianCalendar
<p>I hope this is not a repeat. I checked other searches here and all of them seem to talk about "displaying" the date in the right TimeZone format using SimpleDateFormat.</p> <p>However, my problem is I obtain an XMLGregorianCalendar Object which is let us say in "CET".</p> <p>I have to find out the format from this object and send the current time also in the same TimeZone as the server.</p> <p>For eg: I need an XMLGregorianCalendar Object that returns me in this format(with Timezone):</p> <p>2012-09-19T15:23:36.421+02:00</p> <p>So I just tried this following snippet which seems to only return the time in local Timezone :(</p> <pre><code>TimeZone utc = TimeZone.getTimeZone("CET"); GregorianCalendar gc = new GregorianCalendar(); DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ"); df.setTimeZone(utc); System.out.println(" - Gregorian UTC [" + df.format(gc.getTime()) + "]") XMLGregorianCalendar currServTime = DatatypeFactory.newInstance().newXMLGregorianCalendar(gc); System.out.println("currServTime is "+currServTime); </code></pre>
12,496,251
1
2
null
2012-09-19 13:45:29.913 UTC
null
2017-10-20 00:17:32.337 UTC
2017-10-20 00:17:32.337 UTC
null
3,641,067
null
907,810
null
1
9
java|time|timezone|datetime-format
38,669
<p>You should include the time zone you're interested in in the <code>GregorianCalendar</code>, either by passing it to <a href="http://docs.oracle.com/javase/7/docs/api/java/util/GregorianCalendar.html#GregorianCalendar%28java.util.TimeZone%29">the constructor</a> or by <a href="http://docs.oracle.com/javase/7/docs/api/java/util/GregorianCalendar.html#setTimeZone%28java.util.TimeZone%29">setting it afterwards</a>. So either of these lines should work for you:</p> <pre><code>GregorianCalendar gc = new GregorianCalendar(utc); gc.setTimeZone(utc); </code></pre>
12,428,989
Facet search using MongoDB
<p>I am contemplating to use MongoDB for my next project. One of the core requirements for this application is to provide facet search. Has anyone tried using MongoDB to achieve a facet search?</p> <p>I have a product model with various attributes like size, color, brand etc. On searching a product, this Rails application should show facet filters on sidebar. Facet filters will look something like this:</p> <pre><code>Size: XXS (34) XS (22) S (23) M (37) L (19) XL (29) Color: Black (32) Blue (87) Green (14) Red (21) White (43) Brand: Brand 1 (43) Brand 2 (27) </code></pre>
12,435,619
5
0
null
2012-09-14 17:05:23.553 UTC
12
2016-12-24 04:15:10.197 UTC
null
null
null
null
1,100,452
null
1
14
mongodb|faceted-search
27,868
<p>I think using Apache Solr or ElasticSearch you get more flexibility and performance, but this is supported using <a href="http://www.mongodb.org/display/DOCS/Aggregation+Framework" rel="noreferrer">Aggregation Framework</a>.</p> <p>The main problem using MongoDB is you have to query it N Times: First for get matching results and then once per group; while using a full text search engine you get it all in one query.</p> <p><strong>Example</strong></p> <pre><code>//'tags' filter simulates the search //this query gets the products db.products.find({tags: {$all: ["tag1", "tag2"]}}) //this query gets the size facet db.products.aggregate( {$match: {tags: {$all: ["tag1", "tag2"]}}}, {$group: {_id: "$size"}, count: {$sum:1}}, {$sort: {count:-1}} ) //this query gets the color facet db.products.aggregate( {$match: {tags: {$all: ["tag1", "tag2"]}}}, {$group: {_id: "$color"}, count: {$sum:1}}, {$sort: {count:-1}} ) //this query gets the brand facet db.products.aggregate( {$match: {tags: {$all: ["tag1", "tag2"]}}}, {$group: {_id: "$brand"}, count: {$sum:1}}, {$sort: {count:-1}} ) </code></pre> <p>Once the user filters the search using facets, you have to add this filter to query predicate and match predicate as follows.</p> <pre><code>//user clicks on "Brand 1" facet db.products.find({tags: {$all: ["tag1", "tag2"]}, brand: "Brand 1"}) db.products.aggregate( {$match: {tags: {$all: ["tag1", "tag2"]}}, brand: "Brand 1"}, {$group: {_id: "$size"}, count: {$sum:1}}, {$sort: {count:-1}} ) db.products.aggregate( {$match: {tags: {$all: ["tag1", "tag2"]}}, brand: "Brand 1"}, {$group: {_id: "$color"}, count: {$sum:1}}, {$sort: {count:-1}} ) db.products.aggregate( {$match: {tags: {$all: ["tag1", "tag2"]}}, brand: "Brand 1"}, {$group: {_id: "$brand"}, count: {$sum:1}}, {$sort: {count:-1}} ) </code></pre>
12,354,947
How to structure the tables of a very simple blog in MySQL?
<p>I want to add a very simple blog feature on one of my existing LAMP sites. It would be tied to a user's existing profile, and they would be able to simply input a title and a body for each post in their blog, and the date would be automatically set upon submission. They would be allowed to edit and delete any blog post and title at any time. The blog would be displayed from most recent to oldest, perhaps 20 posts to a page, with proper pagination above that. Other users would be able to leave comments on each post, which the blog owner would be allowed to delete, but not pre-moderate. That's basically it. Like I said, very simple.</p> <p><strong>How should I structure the MySQL tables for this?</strong> </p> <p>I'm assuming that since there will be blog posts and comments, I would need a separate table for each, is that correct? But then what columns would I need in each table, what data structures should I use, and how should I link the two tables together (e.g. any foreign keys)?</p> <p>I could not find any tutorials for something like this, and what I'm looking to do is really offer my users the simplest version of a blog possible. No tags, no moderation, no images, no fancy formatting, etc. Just a simple diary-type, pure-text blog with commenting by other users.</p>
12,355,287
1
3
null
2012-09-10 15:36:55.587 UTC
13
2017-12-09 14:30:32.73 UTC
2017-12-09 14:30:32.73 UTC
null
4,370,109
null
869,849
null
1
15
mysql|database|database-design|blogs
27,986
<p>I'd say you need the following tables</p> <pre><code>Posts PostID (identity) PostTitle (varchar) PostDate (datetime) Deleted (int) OwnerID (int FK to Users) PostDetails PostDetailID (identity) PostID (FK to Posts) Sequence (int) -&gt; for long posts you order by this PostText (text) Comments CommentID (identity) Comment (text) CommenterID (int FK to Users) CommentDate (datetime) Deleted (int) Users UserID (identity) UserNAme (varchar) UserEmail (varchar) CreatedDate (datetime) Active (int) </code></pre> <p>All datetime fields default to the current time, all identity fields are PK The sequence field in post details is there in case you don't use the text type and go with varchar so you can split a post over several records.</p> <p>Other than this, I'd look at any open source blogging system and see what they did and subtract what I don't need.</p> <p>Hope that helps</p>
12,630,970
Compiling for iOS with CMake
<p>I've compiled a C++ static library by using CMake as my building tool and I want to link it to my iOS app.<br> I created a simple 'Empty' application in Xcode and linked my library called libengine.a to it.<br> I tried to compile my iOS project and the linker gave me this warning:<br></p> <pre><code>ignoring file /Users/.../build/engine/libengine.a, file was built for archive which is not the architecture being linked (i386): /Users/.../build/engine/libengine.a </code></pre> <p>As I understand it, I need to compile my library for ARM processors. The problem is I don't know how.<br> I think CMake really lacks good tutorials.<br> Anyways, my CMake scripts are attached below.<br><br> Any help would be greatly appreciated.<br> Thanks, Tal.<br><br> Here is my main CMake script:</p> <pre><code>cmake_minimum_required(VERSION 2.8) project(movie-night) if (DEFINED PLATFORM) include(toolchains/ios.cmake) endif() add_definitions(-Wall) set(DEBUG) if (DEFINED DEBUG) add_definitions(-g) endif() if (DEFINED RELEASE) add_definitions(-O3) endif() add_subdirectory(engine) add_subdirectory(ui) add_subdirectory(test) </code></pre> <p>Here is my toolchains/ios.cmake file:</p> <pre><code>set(CMAKE_SYSTEM_NAME Darwin) set(CMAKE_SYSTEM_PROCESSOR arm) </code></pre>
12,631,433
4
0
null
2012-09-27 22:29:05.03 UTC
13
2020-04-20 07:57:10.537 UTC
2012-09-27 23:08:14.247 UTC
null
1,246,924
null
1,246,924
null
1
23
c++|ios|compilation|cmake|arm
34,307
<p>Just use this toolchain file: <a href="http://code.google.com/p/ios-cmake/" rel="noreferrer">http://code.google.com/p/ios-cmake/</a> and use it as</p> <pre><code>cmake -DCMAKE_TOOLCHAIN_FILE=path_to_your_toolchain_file </code></pre> <p>Then, in <code>CMakeLists.txt</code>:</p> <pre><code>SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -arch armv7") SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -arch armv7") </code></pre>
12,121,543
Reading and writing integer array to parcel
<p>I could not find any solution for how to treat with integer array in case of parcel (I want to use these two functions <strong>dest.writeIntArray(storeId);</strong> and <strong>in.readIntArray(storeId);</strong>).</p> <p>Here is my code </p> <pre><code>public class ResponseWholeAppData implements Parcelable { private int storeId[]; public int[] getStoreId() { return storeId; } public void setStoreId(int[] storeId) { this.storeId = storeId; } @Override public int describeContents() { return 0; } public ResponseWholeAppData(){ storeId = new int[2]; storeId[0] = 5; storeId[1] = 10; } public ResponseWholeAppData(Parcel in) { if(in.readByte() == (byte)1) in.readIntArray(storeId); //how to do this storeId=in.readIntArray(); ? } } @Override public void writeToParcel(Parcel dest, int flags) { if(storeId!=null&amp;&amp;storeId.length&gt;0) { dest.writeByte((byte)1); dest.writeIntArray(storeId); } else dest.writeByte((byte)0); } public static Parcelable.Creator&lt;ResponseWholeAppData&gt; getCreator() { return CREATOR; } public static void setCreator(Parcelable.Creator&lt;ResponseWholeAppData&gt; creator) { CREATOR = creator; } public static Parcelable.Creator&lt;ResponseWholeAppData&gt; CREATOR = new Parcelable.Creator&lt;ResponseWholeAppData&gt;() { public ResponseWholeAppData createFromParcel(Parcel in) { return new ResponseWholeAppData(in); } public ResponseWholeAppData[] newArray(int size) { return new ResponseWholeAppData[size]; } }; } </code></pre>
13,511,302
2
0
null
2012-08-25 11:28:04.927 UTC
5
2017-06-27 22:46:28.84 UTC
2017-06-27 22:46:28.84 UTC
null
3,885,376
null
1,179,638
null
1
29
android|parcelable
17,437
<p>When I use "<code>in.readIntArray(storeID)</code>", I get an error:</p> <p><em>"Caused by: java.lang.NullPointerException at android.os.Parcel.readIntArray(Parcel.java:672)"</em>.</p> <p>Instead of using "<code>readIntArray</code>" I used the following:</p> <pre><code>storeID = in.createIntArray(); </code></pre> <p>Now there are no errors.</p>
12,372,251
"Don't use StringBuilder or foreach in this hot code path"
<p>I am browsing the source code of the Open Source <a href="http://signalr.net/" rel="noreferrer">SignalR</a> project, and I see <a href="https://github.com/SignalR/SignalR/commit/934e581460e4850f3ee2b58b72183eceb0e223d1" rel="noreferrer">this diff code</a> which is entitled <em>"Don't use StringBuilder or foreach in this hot code path"</em> :</p> <pre><code>- public static string MakeCursor(IEnumerable&lt;Cursor&gt; cursors) + public static string MakeCursor(IList&lt;Cursor&gt; cursors) { - var sb = new StringBuilder(); - bool first = true; - foreach (var c in cursors) + var result = ""; + for (int i = 0; i &lt; cursors.Count; i++) { - if (!first) + if (i &gt; 0) { - sb.Append('|'); + result += '|'; } - sb.Append(Escape(c.Key)); - sb.Append(','); - sb.Append(c.Id); - first = false; + result += Escape(cursors[i].Key); + result += ','; + result += cursors[i].Id; } - return sb.ToString(); + return result; } </code></pre> <p>I understand why foreach could be less efficient sometimes, and why it is replaced by for.</p> <p>However, I learned and experienced that the StringBuilder is the most efficient way to concatenate strings. So I am wondering why the author decided to replace it with standard concatenation.</p> <p>What's wrong in here and in general about using StringBuilder ?</p>
12,378,290
5
7
null
2012-09-11 14:39:33.437 UTC
8
2014-02-22 10:04:50.593 UTC
2012-09-11 14:54:36.213 UTC
null
24,472
null
24,472
null
1
32
.net|optimization|foreach|signalr|stringbuilder
2,015
<p>I made the code change and yes it made a huge difference in number of allocations (GetEnumerator()) calls vs not. Imagine this code is millions of times per second. The number of enumerators allocated is ridiculous and can be avoided. </p> <p>edit: We now invert control in order to avoid any allocations (writing to the writer directly): <a href="https://github.com/SignalR/SignalR/blob/2.0.2/src/Microsoft.AspNet.SignalR.Core/Messaging/Cursor.cs#L36">https://github.com/SignalR/SignalR/blob/2.0.2/src/Microsoft.AspNet.SignalR.Core/Messaging/Cursor.cs#L36</a></p>
12,145,434
How to output loop.counter in python jinja template?
<p>I want to be able to output the current loop iteration to my template.</p> <p>According to <a href="https://jinja.palletsprojects.com/en/3.0.x/templates/" rel="noreferrer">the docs</a>, there is a <code>loop.counter</code> variable that I am trying to use:</p> <pre><code>&lt;ul&gt; {% for user in userlist %} &lt;li&gt; {{ user }} {{loop.counter}} &lt;/li&gt; {% if loop.counter == 1 %} This is the First user {% endif %} {% endfor %} &lt;/ul&gt; </code></pre> <p>But is being outputed to my template. What is the correct syntax?</p>
12,147,197
5
0
null
2012-08-27 16:02:20.463 UTC
36
2021-12-24 03:26:43.197 UTC
2021-12-24 03:26:43.197 UTC
user17242583
null
null
971,888
null
1
250
python|jinja2|templating-engine
240,584
<p>The counter variable inside the loop is called <code>loop.index</code> in Jinja2.</p> <pre><code>&gt;&gt;&gt; from jinja2 import Template &gt;&gt;&gt; s = &quot;{% for element in elements %}{{loop.index}} {% endfor %}&quot; &gt;&gt;&gt; Template(s).render(elements=[&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;]) 1 2 3 4 </code></pre> <p>In addition to <code>loop.index</code>, there is also</p> <ul> <li><code>loop.index0</code> (index starting at <code>0</code>)</li> <li><code>loop.revindex</code> (reverse index; ending at <code>1</code>)</li> <li><code>loop.revindex0</code> (reverse index; ending at <code>0</code>)</li> <li>Even more at <a href="http://jinja.pocoo.org/docs/templates/" rel="noreferrer">http://jinja.pocoo.org/docs/templates/</a>.</li> </ul>
12,533,926
Are class names in CSS selectors case sensitive?
<p>I keep reading everywhere that CSS is not case sensitive, but I have this selector</p> <pre><code>.holiday-type.Selfcatering </code></pre> <p>which when I use in my HTML, like this, gets picked up</p> <pre><code>&lt;div class="holiday-type Selfcatering"&gt; </code></pre> <p>If I change the above selector like this</p> <pre><code>.holiday-type.SelfCatering </code></pre> <p>Then the style does not get picked up.</p> <p>Someone is telling lies.</p>
12,533,957
4
5
null
2012-09-21 15:52:55.69 UTC
41
2020-05-04 05:45:21.55 UTC
2012-09-23 15:10:24.363 UTC
null
53,114
null
991,788
null
1
252
html|css|css-selectors
79,220
<p>CSS selectors are generally case-insensitive; this includes class and ID selectors.</p> <p>But <a href="http://www.w3.org/TR/html4/struct/global.html#h-7.5.2" rel="noreferrer">HTML class names <em>are</em> case-sensitive</a> (see the attribute definition), and that's causing a mismatch in your second example. This has not changed in <a href="http://www.w3.org/TR/html50/disabled-elements.html#case-sensitivity" rel="noreferrer">HTML5</a>.<sup>1</sup></p> <p>This is because the case-sensitivity of selectors <a href="http://www.w3.org/TR/selectors-4/#case-sensitive" rel="noreferrer">is dependent on what the document language says</a>:</p> <blockquote> <p>All Selectors syntax is case-insensitive within the ASCII range (i.e. [a-z] and [A-Z] are equivalent), except for parts that are not under the control of Selectors. The case sensitivity of document language element names, attribute names, and attribute values in selectors depends on the document language.</p> </blockquote> <p>So, given an HTML element with a <code>Selfcatering</code> class but without a <code>SelfCatering</code> class, the selectors <code>.Selfcatering</code> and <code>[class~="Selfcatering"]</code> will match it, while the selectors <code>.SelfCatering</code> and <code>[class~="SelfCatering"]</code> would not.<sup>2</sup></p> <p>If the document type defined class names as case-insensitive, then you would have a match regardless.</p> <hr> <p><sup>1</sup> <sub>In quirks mode for all browsers, classes and IDs are case-insensitive. This means case-mismatching selectors will always match. This behavior is consistent across all browsers for legacy reasons, and is mentioned in <a href="https://www.cs.tut.fi/~jkorpela/quirks-mode.html" rel="noreferrer">this article</a>.</sub></p> <p><sup>2</sup> <sub>For what it's worth, <a href="http://www.w3.org/TR/selectors4/#attribute-case" rel="noreferrer">Selectors level 4</a> contains a proposed syntax for forcing a case-insensitive search on attribute values using <code>[class~="Selfcatering" i]</code> or <code>[class~="SelfCatering" i]</code>. Both selectors will match an HTML or XHTML element with either a <code>Selfcatering</code> class or a <code>SelfCatering</code> class (or, of course, both). However there is no such syntax for class or ID selectors (yet?), presumably because they carry different semantics from regular attribute selectors (which have <em>no</em> semantics associated with them), or because it's difficult to come up with a usable syntax.</sub></p>
19,074,542
Is there a list of 'if' switches anywhere?
<p>Is there a list of all the <code>if</code> switches for use in Bash scripting? Sometimes I see someone using it and I wonder what the switch they're using actually does.</p> <p>An example is the <code>-z</code> in this one. I know how to use it, but I don't know where it was derived from.</p> <pre><code>if [ -z &quot;$BASH_VERSION&quot; ]; then echo -e &quot;Error: this script requires the BASH shell!&quot; exit 1 fi </code></pre> <p>Any references, guides, posts, answers would be appreciated.</p>
19,081,182
5
5
null
2013-09-29 04:51:29.027 UTC
13
2021-10-05 14:59:35.817 UTC
2021-10-05 14:25:43.747 UTC
null
63,550
null
1,163,166
null
1
57
bash|if-statement|switch-statement|shell-exec
33,272
<p>Look at the Bash man page (<code>man bash</code>). The options are specified in the <code>CONDITIONAL EXPRESSIONS</code> section:</p> <pre class="lang-none prettyprint-override"><code>CONDITIONAL EXPRESSIONS Conditional expressions are used by the [[ compound command and the test and [ builtin commands to test file attributes and perform string and arithmetic comparisons. Expressions are formed from the following unary or binary primaries. If any file argument to one of the pri- maries is of the form /dev/fd/n, then file descriptor n is checked. If the file argument to one of the primaries is one of /dev/stdin, /dev/stdout, or /dev/stderr, file descriptor 0, 1, or 2, respectively, is checked. Unless otherwise specified, primaries that operate on files follow sym- bolic links and operate on the target of the link, rather than the link itself. -a file True if file exists. ... more options ... </code></pre> <p>It is also explained in the help:</p> <pre class="lang-none prettyprint-override"><code>$ help [ [: [ arg... ] This is a synonym for the &quot;test&quot; builtin, but the last argument must be a literal `]', to match the opening `['. </code></pre>
24,145,329
How is spec/rails_helper.rb different from spec/spec_helper.rb? Do I need it?
<p>I am doing the Rails Tutorial for the second time. When I enter this </p> <pre><code>rails generate integration_test static_pages </code></pre> <p>I get <code>spec/rails_helper.rb</code> and <code>spec/spec_helper.rb</code> instead of just <code>spec/spec_helper.rb</code></p> <p>Now when I run my tests, they are longer (more "verbose") and slower than when I did this last time. I am wondering what the difference between the two files is, and if I did something wrong. Also, is there a way to get rid of the <code>rails_helper.rb</code> file without messing everything up?</p>
24,145,760
2
4
null
2014-06-10 15:45:06.803 UTC
23
2019-12-23 16:58:26.633 UTC
2016-02-07 02:09:13.733 UTC
null
634,576
null
3,417,583
null
1
96
ruby-on-rails|testing|rspec|rspec-rails|rspec3
29,143
<p>rspec-rails 3 generates <code>spec_helper.rb</code> and <code>rails_helper.rb</code>. <code>spec_helper.rb</code> is for specs which don't depend on Rails (such as specs for classes in the lib directory). <code>rails_helper.rb</code> is for specs which do depend on Rails (in a Rails project, most or all of them). <code>rails_helper.rb</code> requires <code>spec_helper.rb</code>. So no, don't get rid of <code>rails_helper.rb</code>; require it (and not <code>spec_helper.rb</code>) in your specs.</p> <p>If you want your non-Rails-dependent specs to enforce that they're non-Rails-dependent, and to run as fast as possible when you run them by themselves, you could require <code>spec_helper.rb</code> rather than <code>rails_helper.rb</code> in those. But it's very convenient to <code>-r rails_helper</code> in your <code>.rspec</code> rather than requiring one helper or the other in each spec file, so that is sure to be a popular approach.</p> <p>If you're using the spring preloader, each class only needs to be loaded once, and <a href="https://stackoverflow.com/questions/36722038/rspec-doesnt-see-my-class-even-if-it-loads-in-the-rails-console/36723233">spring loads classes eagerly even if you only run a single spec that requires <code>spec_helper</code></a>, so there isn't as much value in requiring only <code>spec_helper</code> in some files.</p> <p>Source: <a href="https://www.relishapp.com/rspec/rspec-rails/docs/upgrade#default-helper-files" rel="noreferrer">https://www.relishapp.com/rspec/rspec-rails/docs/upgrade#default-helper-files</a></p>
3,458,965
Changing the volume without a volume slider on an iphone
<p>I need your help. How should I proceed to change the sound volume in my app. I don't want to use a volume slider. Instead I have an UIImageView which is a volume knob, in which I rotate clockwise to increase, and anti clockwise to decrease the sound volume. The rotation is just an animation and I've already done that part.</p> <p>I need your help and advice on how to increase/decrease the volume. Thanks</p>
3,459,720
3
0
null
2010-08-11 13:47:55.28 UTC
12
2010-08-11 17:19:34.44 UTC
null
null
null
null
399,059
null
1
12
iphone|ipad|avfoundation
12,267
<p>I would be careful calling <code>setValue</code> on an <code>MPVolumeView</code> since it probably won't do anything other than update the <em>appearance</em> of the slider, but not the actual device volume level. You would instead have to call <code>_commitVolumeChange</code> which is private API and will likely get your app rejected.</p> <p>A short answer to how to control volume: It really depends on what you're trying to control the volume of. </p> <p>If you want a "controls every sound within the app" sort of control then you can use an <code>MPVolumeView</code> but you <strong>cannot</strong> change it's value programmatically. You would then only be able to change the volume by either moving the slider with a touch or using the volume buttons on the side of the device. The best thing to do is create a global object that stores the volume level which any of your objects can read before they play their sound. </p> <p>If it's an <code>AVAudioPlayer</code> object, you'd create the object and use <code>[theAudioPlayerObject setVolume: someFloat];</code> where <code>someFloat</code> is a value between 0.0 and 1.0.</p> <p>If it's a <code>SystemSound</code> object, you can't control volume.</p> <p>If it's an <code>AudioQueue</code> you'd change it via <code>AudioQueueSetParameter</code></p> <p>Like I said.. it all depends on <em>how</em> you are playing the sound.</p> <p><strong>Update based on comment</strong></p> <p><a href="http://cocoawithlove.com/2008/09/streaming-and-playing-live-mp3-stream.html" rel="noreferrer">For that particular example</a>, you would set the volume like this:</p> <blockquote> <p>Add to the AudioStreamer.h file</p> </blockquote> <pre><code>- (void)setVolume:(float)Level; </code></pre> <blockquote> <p>Add to the AudioStreamer.m file</p> </blockquote> <pre><code>- (void)setVolume:(float)Level { OSStatus errorMsg = AudioQueueSetParameter(audioQueue, kAudioQueueParam_Volume, Level); if (errorMsg) { NSLog(@"AudioQueueSetParameter returned %d when setting the volume.", errorMsg); } } </code></pre> <blockquote> <p>Add to the view controller for where the volume knob will be (this goes in the .m file.. i just did this as a couple UIButtons real quick, you'll have to do your own) and set up an IBAction to change the volume for a given value (you can pass in 0.0 thru 1.0 as a float)</p> </blockquote> <pre><code>- (IBAction)volumeUp:(id)sender { [streamer setVolume:1.0]; } - (IBAction)volumeDown:(id)sender { [streamer setVolume:0.0]; } </code></pre>
22,794,382
Are C++11 thread_local variables automatically static?
<p>Is there a difference between these two code segments:</p> <pre><code>void f() { thread_local vector&lt;int&gt; V; V.clear(); ... // use V as a temporary variable } </code></pre> <p>and</p> <pre><code>void f() { static thread_local vector&lt;int&gt; V; V.clear(); ... // use V as a temporary variable } </code></pre> <p>Backstory: originally I had a STATIC vector V (for holding some intermediate values, it gets cleared every time I enter the function) and a single-threaded program. I want to turn the program into a multithreading one, so somehow I have to get rid of this static modifier. My idea is to turn every static into thread_local and not worry about anything else? Can this approach backfire?</p>
22,794,640
4
5
null
2014-04-01 18:49:37.187 UTC
32
2015-10-14 18:31:01.853 UTC
null
null
null
null
1,048,214
null
1
101
c++|c++11|thread-local-storage
53,079
<p>According to the C++ Standard</p> <blockquote> <p>When thread_local is applied to a variable of block scope the storage-class-specifier static <strong>is implied</strong> if it does not appear explicitly</p> </blockquote> <p>So it means that this definition</p> <pre><code>void f() { thread_local vector&lt;int&gt; V; V.clear(); ... // use V as a temporary variable } </code></pre> <p>is equivalent to</p> <pre><code>void f() { static thread_local vector&lt;int&gt; V; V.clear(); ... // use V as a temporary variable } </code></pre> <p>However, a static variable is <strong>not</strong> the same as a thread_local variable.</p> <blockquote> <p>1 All variables declared with the thread_local keyword have thread storage duration. The storage for these entities shall last for the duration of the thread in which they are created. There is a distinct object or reference per thread, and use of the declared name refers to the entity associated with the current thread</p> </blockquote> <p>To distinguish these variables the standard introduces a new term <strong><em>thread storage duration</em></strong> along with static storage duration.</p>
18,813,517
Single Sign ON (SSO) in iOS 7
<p>I have a question about one of new features in iOS 7 - Single Sign On.</p> <p>Are there any detailed info about it? Has somebody already tried it for implementation? I searched a lot of articles and docs - but did not find any useful. I also did not find any detailed info on Apple and Developers Apple resources. There are no visual setting for SSO in iOS 7 GM version (I am not sure if it should be there).</p> <p>So my question is - have somebody already investigated it and may be somebody can share some links and useful info? Are there any technical descriptions of this feature and is it existed some how in iOS 7 GM?</p> <p>Thanks in advance.</p>
20,959,862
3
9
null
2013-09-15 14:32:10.367 UTC
21
2017-02-21 12:42:29.197 UTC
2013-09-19 04:46:57.17 UTC
null
650,176
null
1,286,066
null
1
25
ios|single-sign-on|ios7
27,304
<p>I would recommend watching <a href="https://developer.apple.com/videos/play/wwdc2013/301/" rel="nofollow noreferrer">WWDC 2013 Session 301 "Extending Your Apps for Enterprise and Education Use"</a></p> <p>Also, for an overview of an implementation of this functionality <a href="https://blogs.sap.com/2013/09/18/mobile-single-sign-on-from-ios-7-to-sap-netweaver/" rel="nofollow noreferrer">this site</a> helps.</p> <p>Lastly, here is <a href="https://developer.apple.com/library/ios/featuredarticles/iPhoneConfigurationProfileRef/Introduction/Introduction.html" rel="nofollow noreferrer">Apple's documentation (available to developers)</a>. Look for the heading: Single Sign-On Account Payload.</p> <p>Configuring SSO on a device will require Apple Configurator to install the profile or an MDM solution for OTA delivery of the SSO profile.</p>
10,984,453
Compare two DataTables for differences in C#?
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/164144/c-how-to-compare-two-datatables-a-b-how-to-show-rows-which-are-in-b-but-not">C#, how to compare two datatables A + B, how to show rows which are in B but not in A</a> </p> </blockquote> <p>I need to compare two datatables in c# to find the differences. The two datatables have the same schema. What is the best way to do it? Can it be done using linq queries? If yes, How?</p>
10,984,590
1
4
null
2012-06-11 17:00:27.367 UTC
4
2014-06-17 10:08:03.73 UTC
2017-05-23 11:45:46.02 UTC
user166390
-1
null
1,256,789
null
1
6
c#|linq|datatable
41,260
<p>You could use LINQ to join the two <code>DataTable</code> objects, matching every column. Then take the <code>IQueryable</code> and find all the rows in the first two <code>DataTable</code> objects which are not in the <code>IQueryable</code>.</p> <p><strong>Example</strong>:</p> <pre><code>private void SampleSolution(DataTable dt1, DataTable dt2) { //If you have primary keys: var results = from table1 in dt1.AsEnumerable() join table2 in dt2.AsEnumerable() on table1.Field&lt;int&gt;("id") equals table2.Field&lt;int&gt;("id") where table1.Field&lt;int&gt;("ColumnA") != table2.Field&lt;int&gt;("ColumnA") || table1.Field&lt;int&gt;("ColumnB") != table2.Field&lt;int&gt;("ColumnB") || table1.Field&lt;String&gt;("ColumnC") != table2.Field&lt;String&gt;("ColumnC") select table1; //This will give you the rows in dt1 which do not match the rows in dt2. You will need to expand the where clause to include all your columns. //If you do not have primarry keys then you will need to match up each column and then find the missing. var matched = from table1 in dt1.AsEnumerable() join table2 in dt2.AsEnumerable() on table1.Field&lt;int&gt;("ColumnA") equals table2.Field&lt;int&gt;("ColumnA") where table1.Field&lt;int&gt;("ColumnB") == table2.Field&lt;int&gt;("ColumnB") || table1.Field&lt;string&gt;("ColumnC") == table2.Field&lt;string&gt;("ColumnC") || table1.Field&lt;object&gt;("ColumnD") == table2.Field&lt;object&gt;("ColumnD") select table1; var missing = from table1 in dt1.AsEnumerable() where !matched.Contains(table1) select table1; //This should give you the rows which do not have a match. You will need to expand the where clause to include all your columns. } </code></pre> <p>The code above should work, though I did not test it.</p> <p>You could also check out <a href="https://stackoverflow.com/questions/10855/linq-query-on-a-datatable">LINQ query on a DataTable</a> which has some useful information on using LINQ with DataTables.<br> I also find the <a href="http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b" rel="nofollow noreferrer">LINQ samples</a> to be helpful when writting LINQ.</p>
11,175,933
header('Content-type: application/octet-stream') cause 0 byte files
<p>I'm using database query in PHP to retrieve a binary file. But when I'm trying to force download it, the header('Content-type: application/octet-stream') line cause 0 byte files. Without that line I can download the file with full content. It's a binary file that's for sure so I just can't understand why that line causes the problem. The code:</p> <pre><code>$result = mysql_query("SELECT data FROM stored_file WHERE file_name = '$q'"); while($row = mysql_fetch_array($result)) { $file = $row['data']; } header('Content-disposition: attachment; filename='.$q); header('Content-type: application/octet-stream'); header('Content-Length: '.filesize($file)); header("Pragma: no-cache"); header("Expires: 0"); echo $file; </code></pre> <p>Any idea? Thanks.</p>
11,176,761
2
5
null
2012-06-24 08:06:46.897 UTC
3
2013-10-18 10:01:10.117 UTC
null
null
null
null
1,477,803
null
1
7
php|download
39,076
<p><a href="http://php.net/filesize"><code>filesize()</code></a> won't return a meaningful value.</p> <p>You have binary data in <code>$file</code>, <strong>not</strong> an <em>actual filename</em> as required as first parameter. Hence you would get an error. (Enable error_reporting! Not seeing errors, and not having them are two different things.)</p> <p>So what you want to use there is <code>strlen($file)</code>, not <code>filesize()</code>.</p> <p>Btw, <code>application/octet-stream</code> or other fill-ins have no use for forcing downloads. It's the <code>Content-Disposition:</code> header which is most crucial to that effect. You're still allowed to send the correct MIME type.</p>
11,118,486
Python List as variable name
<p>I've been playing with Python and I have this list that I need worked out. Basically I type a list of games into the multidimensional array and then for each one, it will make 3 variables based on that first entry.</p> <p>Array that is made: </p> <pre><code>Applist = [ ['Apple', 'red', 'circle'], ['Banana', 'yellow', 'abnormal'], ['Pear', 'green', 'abnormal'] ] </code></pre> <p>For loop to assign each fruit a name, colour and shape.</p> <pre><code>for i in Applist: i[0] + "_n" = i[0] i[0] + "_c" = i[1] i[0] + "_s" = i[2] </code></pre> <p>When doing this though, I get a cannot assign to operator message. How do I combat this?</p> <p>The expected result would be:</p> <pre><code>Apple_n == "Apple" Apple_c == "red" Apple_s == "circle" </code></pre> <p>Etc for each fruit.</p>
11,118,582
2
3
null
2012-06-20 11:26:23.567 UTC
11
2016-01-12 10:30:08.557 UTC
2012-06-20 11:36:41.38 UTC
null
566,644
null
1,392,697
null
1
8
python|arrays|list|variables|multidimensional-array
81,662
<p>This is a bad idea. You should not dynamically create variable names, use a dictionary instead:</p> <pre><code>variables = {} for name, colour, shape in Applist: variables[name + "_n"] = name variables[name + "_c"] = colour variables[name + "_s"] = shape </code></pre> <p>Now access them as <code>variables["Apple_n"]</code>, etc.</p> <p>What you really want though, is perhaps a dict of dicts:</p> <pre><code>variables = {} for name, colour, shape in Applist: variables[name] = {"name": name, "colour": colour, "shape": shape} print "Apple shape: " + variables["Apple"]["shape"] </code></pre> <p>Or, perhaps even better, a <a href="http://docs.python.org/library/collections.html#collections.namedtuple" rel="noreferrer"><code>namedtuple</code></a>:</p> <pre><code>from collections import namedtuple variables = {} Fruit = namedtuple("Fruit", ["name", "colour", "shape"]) for args in Applist: fruit = Fruit(*args) variables[fruit.name] = fruit print "Apple shape: " + variables["Apple"].shape </code></pre> <p>You can't change the variables of each <code>Fruit</code> if you use a <code>namedtuple</code> though (i.e. no setting <code>variables["Apple"].colour</code> to <code>"green"</code>), so it is perhaps not a good solution, depending on the intended usage. If you like the <code>namedtuple</code> solution but want to change the variables, you can make it a full-blown <code>Fruit</code> class instead, which can be used as a drop-in replacement for the <code>namedtuple</code> <code>Fruit</code> in the above code.</p> <pre><code>class Fruit(object): def __init__(self, name, colour, shape): self.name = name self.colour = colour self.shape = shape </code></pre>
11,311,541
How can I implement a collapsible view like the one from Google Play?
<p>I want to implement a collapsible view, exactly like the one from Google Play market. It displays a number of rows from the content, and an arrow, and tapping on the arrow reveals the whole content. Is this implemented with the ExpandableListView or is there any other solution?</p> <p>Screen shots attached with highlighting what I am looking for. Thanks.<img src="https://i.stack.imgur.com/lTX3C.png" alt="enter image description here"></p>
11,313,816
3
2
null
2012-07-03 13:04:22.257 UTC
22
2018-08-08 11:33:22.743 UTC
null
null
null
null
1,459,573
null
1
19
android|android-layout
23,939
<p>There is a simpler way:</p> <pre><code> final TextView descriptionText = (TextView) view.findViewById(R.id.detail_description_content); final TextView showAll = (TextView) view.findViewById(R.id.detail_read_all); showAll.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { showAll.setVisibility(View.INVISIBLE); descriptionText.setMaxLines(Integer.MAX_VALUE); } }); </code></pre> <p>XML:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"&gt; &lt;LinearLayout android:id="@+id/detail_description_container" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" &gt; &lt;TextView android:id="@+id/detail_description_content" android:maxLines="5" android:layout_width="match_parent" android:layout_height="wrap_content"/&gt; &lt;TextView android:id="@+id/detail_read_all" android:clickable="true" android:layout_width="wrap_content" android:layout_height="wrap_content"/&gt; &lt;/LinearLayout&gt; &lt;/ScrollView&gt; </code></pre> <p>The important part is maxlines and scrollview. This doesn't give a slow animation (that would be a bid more complex) but an instant open effect.</p>
10,953,686
Can I keep my settings upgrading Eclipse from Indigo to Juno?
<p>How can I upgrade Eclipse from Indigo to Juno without losing all of my customizations?</p> <p>I've tried two different things, neither of which worked:</p> <ul> <li>Export prefs from Indigo and import into Juno</li> <li>Run Juno on a copy of the Indigo workspace</li> </ul> <p>It's so annoying to have to start from scratch with every upgrade...</p>
11,226,651
9
2
null
2012-06-08 17:51:43.9 UTC
23
2016-03-12 14:33:36.4 UTC
2016-03-12 14:33:36.4 UTC
null
63,550
null
945,226
null
1
79
eclipse|eclipse-juno
35,900
<p>I am no expert, but I just added new sites to my "Available Software Sites" (help -> install new software -> Available Software Sites)</p> <p><code>http://download.eclipse.org/releases/juno</code></p> <p><code>http://download.eclipse.org/tools/cdt/releases/juno</code></p> <p>and updated (help -> install updates).</p> <p>After the update</p> <p><code>http://download.eclipse.org/eclipse/updates/4.2</code> had been added <code>http://download.eclipse.org/eclipse/updates/3.7</code> had been disabled <code>http://download.eclipse.org/tools/cdt/releases/indigo</code> had been disabled</p> <p>maybe other changes that I didn't notice.</p> <p>Everything seems to work as expected - project list remains - perspectives remain - the only thing that wasn't preserved seemed to be the editor tabs that were open in the workspace, but that is small loss. So hopefully that was the right way to do it - unless someone wants to tell me differently.</p> <p>Alan</p>
10,973,766
Understanding the map function
<p>The Python 2 documentation says:</p> <blockquote> <h3><a href="https://docs.python.org/2.7/library/functions.html#map" rel="nofollow noreferrer">Built-in Functions: <code>map(function, iterable, ...)</code></a></h3> <p>Apply function to every item of iterable and return a list of the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel.</p> <p>If one iterable is shorter than another it is assumed to be extended with None items.</p> <p>If function is <code>None</code>, the identity function is assumed; if there are multiple arguments, <code>map()</code> returns a list consisting of tuples containing the corresponding items from all iterables (a kind of transpose operation).</p> <p>The iterable arguments may be a sequence or any iterable object; the result is always a list.</p> </blockquote> <p>What role does this play in making a Cartesian product?</p> <pre><code>content = map(tuple, array) </code></pre> <p>What effect does putting a tuple anywhere in there have? I also noticed that without the map function the output is <code>abc</code> and with it, it's <code>a, b, c</code>.</p> <p>I want to fully understand this function. The reference definitions is also hard to understand. Too much fancy fluff.</p>
10,973,817
6
14
null
2012-06-11 01:39:42.863 UTC
152
2022-08-05 10:38:54.573 UTC
2022-08-05 10:38:54.573 UTC
null
5,349,916
null
1,447,992
null
1
336
python|higher-order-functions|map-function
504,576
<p><code>map</code> isn't particularly pythonic. I would recommend using list comprehensions instead:</p> <pre><code>map(f, iterable) </code></pre> <p>is basically equivalent to:</p> <pre><code>[f(x) for x in iterable] </code></pre> <p><code>map</code> on its own can't do a Cartesian product, because the length of its output list is always the same as its input list. You can trivially do a Cartesian product with a list comprehension though:</p> <pre><code>[(a, b) for a in iterable_a for b in iterable_b] </code></pre> <p>The syntax is a little confusing -- that's basically equivalent to:</p> <pre><code>result = [] for a in iterable_a: for b in iterable_b: result.append((a, b)) </code></pre>
11,386,586
How to show <div> tag literally in <code>/<pre> tag?
<p>I'm using <code>&lt;code&gt;</code> tag inside of a <code>&lt;pre&gt;</code> tag to show code on my blogger blog. Unfortunately it doesn't work with HTML tags. Is there any way to show "<code>&lt;div&gt;</code>" inside of <code>&lt;pre&gt;</code> or <code>&lt;code&gt;</code> tag without actually interpreting it as HTML? This is what I do right now:</p> <pre><code>&lt;pre&gt; &lt;code&gt; .class { color:red; } // I would like HTML code inside this &lt;/code&gt; &lt;/pre&gt; </code></pre> <p>Which works ok for everything except HTML. Any idea how to achieve this? Thanks.</p>
11,386,602
11
2
null
2012-07-08 20:49:15.353 UTC
20
2022-09-16 23:30:48.933 UTC
null
null
null
null
163,799
null
1
89
html|blogger
67,695
<blockquote> <p>Unfortunately it doesn't work with HTML tags.</p> </blockquote> <p><code>&lt;code&gt;</code> means "This is code", <code>&lt;pre&gt;</code> means "White space in this markup is significant". Neither means "The content of this element should not be treated as HTML", so both work perfectly, even if they don't mean what you want them to mean.</p> <blockquote> <p>Is there any way to show "<code>&lt;div&gt;</code>" inside of <code>&lt;pre&gt;</code> or <code>&lt;code&gt;</code> tag without actually interpreting it as HTML? </p> </blockquote> <p>If you want to render a <code>&lt;</code> character then use <code>&amp;lt;</code>, with <code>&amp;gt;</code> for <code>&gt;</code> and <code>&amp;amp;</code> for <code>&amp;</code>.</p> <p>You can't (in modern HTML) write markup and have it be interpreted as text.</p>
12,841,438
Remove enclosing brackets from a string in C#
<p>I need to remove enclosing brackets from a string in C# in <a href="https://en.wiktionary.org/wiki/code-behind" rel="nofollow noreferrer">code-behind</a>.</p> <p>For example, if I have a string as <code>[My [] Groups]</code>, I want to turn it into <code>My [] Groups</code>.</p>
12,841,480
8
2
null
2012-10-11 14:05:13.373 UTC
1
2021-06-13 23:36:03.387 UTC
2021-06-13 23:36:03.387 UTC
null
63,550
null
687,398
null
1
8
c#|brackets
40,716
<p>The simplest way of addressing this using the string from your example would be taking a substring:</p> <pre><code>if (s.Length &gt; 2) { s = s.Substring(1, s.Length-2); } </code></pre> <p>This works only when you are 100% certain that the first and the last characters are indeed square brackets. If they are not, for example, when the string is untrimmed, you may need to perform additional string manipulations (e.g. trimming the string).</p>
12,695,563
Crystal Reports for VS2012 - VS2013 - VS2015 - VS2017 - VS2019
<p>I have installed VS2012 Ultimate on a fresh PC. I tried adding the Crystal Reports file in my project but there is no crystal report .crt Item avaliable into Add New Item menu of the VS2012</p> <p>Is there a version for VS2012? or do I have to install an extra setup file for crystal reports which is redundant since I already have VS2012 installed.</p>
14,384,613
4
1
null
2012-10-02 17:51:56.06 UTC
25
2019-11-05 15:42:00.003 UTC
2019-11-05 11:57:09.98 UTC
null
497,040
null
869,233
null
1
62
visual-studio|crystal-reports
187,462
<h2>Here it is! - SP 25 works on Visual Studio 2019, SP 21 on Visual Studio 2017</h2> <p>SAP released <strong>SAP Crystal Reports, developer version for Microsoft Visual Studio</strong></p> <h2><a href="http://www.crystalreports.com/crvs/confirm/" rel="noreferrer">You can get it here</a> (click &quot;Installation package for Visual Studio IDE&quot;)</h2> <blockquote> <p>To integrate “SAP Crystal Reports, developer version for Microsoft Visual Studio” you must <strong>run the Install Executable</strong>. Running the MSI will not fully integrate Crystal Reports into VS. MSI files by definition are for runtime distribution only.</p> </blockquote> <h2></h2> <blockquote> <p>New In SP25 Release</p> <p>Visual Studio 2019, Addressed incidents, Win10 1809, Security update</p> </blockquote>
12,690,128
How to instantiate non static inner class within a static method?
<p>I have the following piece of code:</p> <pre><code>public class MyClass { class Inner { int s, e, p; } public static void main(String args[]) { Inner in; } } </code></pre> <p>Up to this part the code is fine, but I am not able to instantiate 'in' within the main method like <code>in = new Inner()</code> as it is showing <code>non static field cannot be referenced in static context</code>.</p> <p>What is the way I can do it? I do not want to make my <code>Inner</code> class <em>static</em>.</p>
12,690,151
4
2
null
2012-10-02 12:21:15.453 UTC
32
2019-11-03 17:45:35.567 UTC
2019-11-03 17:45:35.567 UTC
null
814,702
null
1,601,336
null
1
136
java|static|inner-classes
94,541
<p>You have to have a reference to the other outer class as well.</p> <pre><code>Inner inner = new MyClass().new Inner(); </code></pre> <p>If Inner was static then it would be </p> <pre><code>Inner inner = new MyClass.Inner(); </code></pre>
12,893,566
Passing multiple variables in @RequestBody to a Spring MVC controller using Ajax
<p>Is it necessary to wrap in a backing object? I want to do this:</p> <pre><code>@RequestMapping(value = "/Test", method = RequestMethod.POST) @ResponseBody public boolean getTest(@RequestBody String str1, @RequestBody String str2) {} </code></pre> <p>And use a JSON like this:</p> <pre><code>{ "str1": "test one", "str2": "two test" } </code></pre> <p>But instead I have to use: </p> <pre><code>@RequestMapping(value = "/Test", method = RequestMethod.POST) @ResponseBody public boolean getTest(@RequestBody Holder holder) {} </code></pre> <p>And then use this JSON:</p> <pre><code>{ "holder": { "str1": "test one", "str2": "two test" } } </code></pre> <p>Is that correct? My other option would be to change the <code>RequestMethod</code> to <code>GET</code> and use <code>@RequestParam</code> in query string or use <code>@PathVariable</code> with either <code>RequestMethod</code>. </p>
12,897,632
16
1
null
2012-10-15 10:17:44.657 UTC
57
2021-11-30 14:05:45.18 UTC
2017-03-21 20:05:42.187 UTC
null
1,535,071
null
106,261
null
1
144
java|spring|http|spring-mvc
299,774
<p>You are correct, @RequestBody annotated parameter is expected to hold the entire body of the request and bind to one object, so you essentially will have to go with your options.</p> <p>If you absolutely want your approach, there is a custom implementation that you can do though:</p> <p>Say this is your json:</p> <pre><code>{ "str1": "test one", "str2": "two test" } </code></pre> <p>and you want to bind it to the two params here:</p> <pre><code>@RequestMapping(value = "/Test", method = RequestMethod.POST) public boolean getTest(String str1, String str2) </code></pre> <p>First define a custom annotation, say <code>@JsonArg</code>, with the JSON path like path to the information that you want:</p> <pre><code>public boolean getTest(@JsonArg("/str1") String str1, @JsonArg("/str2") String str2) </code></pre> <p>Now write a Custom <a href="http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/web/method/support/HandlerMethodArgumentResolver.html" rel="noreferrer">HandlerMethodArgumentResolver</a> which uses the <a href="http://code.google.com/p/json-path/" rel="noreferrer">JsonPath</a> defined above to resolve the actual argument:</p> <pre><code>import java.io.IOException; import javax.servlet.http.HttpServletRequest; import org.apache.commons.io.IOUtils; import org.springframework.core.MethodParameter; import org.springframework.http.server.ServletServerHttpRequest; import org.springframework.web.bind.support.WebDataBinderFactory; import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.method.support.ModelAndViewContainer; import com.jayway.jsonpath.JsonPath; public class JsonPathArgumentResolver implements HandlerMethodArgumentResolver{ private static final String JSONBODYATTRIBUTE = "JSON_REQUEST_BODY"; @Override public boolean supportsParameter(MethodParameter parameter) { return parameter.hasParameterAnnotation(JsonArg.class); } @Override public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { String body = getRequestBody(webRequest); String val = JsonPath.read(body, parameter.getMethodAnnotation(JsonArg.class).value()); return val; } private String getRequestBody(NativeWebRequest webRequest){ HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.class); String jsonBody = (String) servletRequest.getAttribute(JSONBODYATTRIBUTE); if (jsonBody==null){ try { String body = IOUtils.toString(servletRequest.getInputStream()); servletRequest.setAttribute(JSONBODYATTRIBUTE, body); return body; } catch (IOException e) { throw new RuntimeException(e); } } return ""; } } </code></pre> <p>Now just register this with Spring MVC. A bit involved, but this should work cleanly.</p>
37,318,922
Espresso test recording feature in Android Studio 2.2
<p>In Android Studio 2.2 there is supposed to be a test recording function? Where do I find it and how do I use it?</p>
37,322,177
3
9
null
2016-05-19 09:18:58.763 UTC
14
2019-04-30 18:34:15.663 UTC
2016-06-10 01:52:29.15 UTC
null
4,626,831
null
900,743
null
1
31
android|automated-tests|android-espresso|android-studio-2.2|android-espresso-recorder
8,979
<p>Update june 9th:<br> <a href="http://tools.android.com/recent/androidstudio22preview3available?pli=1">It is now available with android studio 2.2 preview 3!</a></p> <blockquote> <p>Espresso Test Recorder<br> Demo of the Espresso Test Recorder shown at IO is now included in Preview 3</p> </blockquote> <p>Screenshot of my pc:<br> <a href="https://i.stack.imgur.com/1P1F6.png"><img src="https://i.stack.imgur.com/1P1F6.png" alt="enter image description here"></a></p> <p>Download it <a href="http://tools.android.com/download/studio/builds/2-2-preview-3">here</a> or patch directly from android studio preview 2.2</p> <hr> <p>Update may 30:<br> Android Studio 2.2 preview 2 is out, but no 'Record Espresso Test' option yet.</p> <blockquote> <p>Unfortunately the Espresso Test Recorder is still not in this build; we're addressing a few more issues and then hope to have it ready in the next build!</p> </blockquote> <p>From the <a href="http://tools.android.com/recent">changelog</a>.</p> <hr> <p>Update:<br> It was not in the <em>Advanced Espresso</em> presentation as I expected, but in <a href="https://www.youtube.com/watch?v=csaXml4xtN8">What's new in Android development tools</a> (credit to flackery). They show where to find it:</p> <p><a href="https://i.stack.imgur.com/JFzaj.png"><img src="https://i.stack.imgur.com/JFzaj.png" alt="enter image description here"></a></p> <p>It's also explained in the <a href="http://android-developers.blogspot.nl/2016/05/android-studio-22-preview-new-ui.html">latest android-developers blog</a></p> <blockquote> <p>Espresso Test Recorder: Sometimes writing UI tests can be tedious. With the Record Espresso UI tests feature, creating tests is now as easy as just using your app. Android Studio will capture all your UI interactions and convert them into a fully reusable Espresso Test that you can run locally or even on Firebase Test lab. <em>To use the recorder, go to the Run menu and select Record Espresso Test.</em></p> </blockquote> <p>However there is no way to get that option in the current release, updating all (platform)tools etc won't make a difference either.</p> <p>For now we can only assume that this was unintentionally left out, and will be included in the first next release. </p> <hr> <p><s>The only sensible thing I could find about this is</p> <blockquote> <p>Creating tests is now as easy as using your app. <strong>Run your app in debug mode and enable recording</strong>, and this feature will capture UI events and convert them into Espresso Tests that you can run locally or even in the Firebase Test lab.</p> </blockquote> <p><sub>From <a href="http://venturebeat.com/2016/05/18/google-launches-android-studio-2-2-preview-with-layout-editor-firebase-plugin-and-apk-analyzer/">venturebeat</a></sub></p> <p>Running in debug is simple, but enabling recording.. I'm not sure what they mean by that. There is a recording option, but that is for capturing the screen and saving it to a mp4 file.</p> <p>There is currently nothing to be found on the net, and nothing in android studio itself either, that explains this feature in more detail than "it's there".</p> <hr> <p>There will however be a talk at Google I/O today, <a href="https://events.google.com/io2016/schedule?sid=1ac924f1-0bef-e511-a517-00155d5066d7#day2/1ac924f1-0bef-e511-a517-00155d5066d7">Advanced Espresso</a>, where they will talk about this new feature and I expect it to be clearer after that.</p> <p>I will update my answer once I've seen the presentation.</s></p>