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
45,898,184
Can I safely convert struct of floats into float array in C++?
<p>For example I have this struct</p> <pre><code>struct A { float x; float y; float z; }; </code></pre> <p>Can I do this? <code>A a; float* array = (float*)&amp;a;</code> And use a as float array?</p>
45,898,422
5
11
null
2017-08-26 17:51:14.98 UTC
5
2017-08-27 13:04:06.407 UTC
2017-08-26 18:33:17.637 UTC
null
4,426,075
null
4,426,075
null
1
30
c++
4,534
<p>In a practical sense, <strong>yes you can do that</strong> and it will work in all the mostly used architectures and compilers.</p> <p>See <a href="https://en.wikipedia.org/wiki/Data_structure_alignment#Typical_alignment_of_C_structs_on_x86" rel="noreferrer">"Typical alignment of C structs on x86"</a> section on Wikipedia.</p> <p>More details:</p> <ul> <li><p>floats are 4 bytes and no padding will be inserted (<strong>in <em>practically all</em> cases</strong>).</p></li> <li><p>also most compilers have the option to specify the packing of structures and you can enforce that no padding is inserted( i.e. #pragma pack from visual studio )</p></li> <li><p>arrays are guarantied to be contiguous in memory.</p></li> </ul> <p>Can you guarantee that it will work in all CPUs in the world with all the compilers? No.. but I would definitely like to see a platform where this fails :)</p> <p>EDIT: adding <code>static_assert(sizeof(A) == 3*sizeof(float))</code> will make this code not compile if there are padding bytes. So then you'll be sure it works when it compiles.</p>
5,562,461
Refresh a section after adding HTML dynamically to jquery mobile
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/4214538/dynamically-adding-collapsible-elements">Dynamically adding collapsible elements</a> </p> </blockquote> <p>I've seen a few posts on this but none of them really seem to apply, or I could just be reading it wrong. I've got some HTML that's fed to me from a server that I can't really get changed. What I want to do is, grab that HTML, insert it into a div element &amp; have jQuery mobile do it's styling thing on it. I potentially need to do that multiple times, and that's where the pain happens.</p> <p>When I insert it the 1st time, it's all fine, jqm picks up the addition &amp; styles it perfectly. If I try a 2nd time, jqm doesn't pick it up at all. I've tried making a 'template' that I copy and modify or just inserting static html &amp; neither work.</p> <p>I've got a test case below, as you'll see, click add new list once, and it's fine, click it again &amp; you get an unstyled select. I've read somewhere that using the live event may work, but that doesn't work in this case either.</p> <p>Also, I know about the select list selectmenu method in jQuery mobile, but the item I get back could be single/multiple select lists, a bunch of radio buttons or even a set of free text fields. As you can see, I've also tried running the page method on the topmost element, I've also tried running page on the element I'm about to add, all to no avail. :(</p> <p>Test:</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"&gt; &lt;head&gt; &lt;title&gt;List insert test&lt;/title&gt; &lt;meta http-equiv="Pragma" content="no-cache" /&gt; &lt;meta content="text/html; charset=utf-8" http-equiv="Content-Type" /&gt; &lt;!-- include jQuery --&gt; &lt;script type="text/javascript" src="http://code.jquery.com/jquery-1.5.2.js"&gt;&lt;/script&gt; &lt;!-- include jQuery Mobile Framework --&gt; &lt;script type="text/javascript" src="http://code.jquery.com/mobile/1.0a4/jquery.mobile-1.0a4.js"&gt;&lt;/script&gt; &lt;link rel="stylesheet" href="http://code.jquery.com/mobile/1.0a4/jquery.mobile-1.0a4.css" /&gt; &lt;/head&gt; &lt;body&gt; &lt;div data-role="page" data-theme="b" id="Dashboard"&gt; &lt;button id='addlist'&gt;add new list&lt;/button&gt; &lt;button id='addips'&gt;add templated list&lt;/button&gt; &lt;button id='clearall'&gt;clear&lt;/button&gt; &lt;div id='theplace'&gt;&lt;/div&gt; &lt;div id='newtemp'&gt; &lt;select id='thelisttemplate'&gt; &lt;option value="1"&gt;1&lt;/option&gt; &lt;option value="2"&gt;2&lt;/option&gt; &lt;option value="3"&gt;3&lt;/option&gt; &lt;option value="4"&gt;4&lt;/option&gt; &lt;option value="5"&gt;5&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;div id="thelist"&gt; jkghjkgh &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;script type="text/javascript"&gt; $('#addips').live('click', (function() { l = $('#thelisttemplate').clone() $('#thelist').html('') $('#thelist').append($(l)) $('#thelist').page() })) $('#addlist').click(function() { l = $("&lt;select id='thelisttemplate'&gt;&lt;option value='1'&gt;1&lt;/option&gt;&lt;option value='2'&gt;2&lt;/option&gt;&lt;option value='3'&gt;3&lt;/option&gt;&lt;option value='4'&gt;4&lt;/option&gt;&lt;option value='5'&gt;5&lt;/option&gt;&lt;/select&gt;") $('#thelist').html('') $('#thelist').append($(l)) $('#thelist').page() //$('#theplace').after($("&lt;select id='thelisttemplate'&gt;&lt;option value='1'&gt;1&lt;/option&gt;&lt;option value='2'&gt;2&lt;/option&gt;&lt;option value='3'&gt;3&lt;/option&gt;&lt;option value='4'&gt;4&lt;/option&gt;&lt;option value='5'&gt;5&lt;/option&gt;&lt;/select&gt;")) //$('#thelisttemplate').page() }) $('#clearall').click(function() { $('#thelist').html('') }) &lt;/script&gt; &lt;/html&gt; </code></pre> <p>Update: Using naugur's answer below, the add new list function would look like...</p> <pre><code> $('#addlist').click(function() { l = $("&lt;select id='thelisttemplate'&gt;&lt;option value='1'&gt;1&lt;/option&gt;&lt;option value='2'&gt;2&lt;/option&gt;&lt;option value='3'&gt;3&lt;/option&gt;&lt;option value='4'&gt;4&lt;/option&gt;&lt;option value='5'&gt;5&lt;/option&gt;&lt;/select&gt;") $('#thelist').html('&lt;div data-role="collapsible-set" id="newstuff"&gt;&lt;/div&gt;'); $("#newstuff").html(l).page(); }) </code></pre> <p>Update #2: Apparently this is now deprecated, see below for some ideas on how to fix in beta2.</p>
5,562,842
2
1
null
2011-04-06 06:50:32.74 UTC
9
2016-11-15 22:42:40.85 UTC
2017-05-23 11:53:35.447 UTC
null
-1
null
80,460
null
1
26
javascript|jquery|jquery-mobile
89,803
<p><strong>update</strong></p> <p>As of jquery mobile beta2 you trigger an event - <code>.trigger('create')</code></p> <p>FAQ updated: <a href="http://demos.jquerymobile.com/1.3.2/faq/injected-content-is-not-enhanced.html" rel="nofollow noreferrer">http://demos.jquerymobile.com/1.3.2/faq/injected-content-is-not-enhanced.html</a></p> <p>This is deprecated:</p> <p>use <code>.page()</code> function.</p> <p>I suggest:</p> <ol> <li>empty the div you populate</li> <li>create a new div inside</li> <li>populate the new div</li> <li>call <code>.page()</code> on that new div</li> </ol>
5,318,415
Which browsers support document.activeElement?
<p>Which web browsers / versions have support for <code>document.activeElement</code>? </p> <p>This property lets you see which element is active / has focus.</p> <p>Are there any main gotchas/difference between implementations?</p>
5,323,330
2
0
null
2011-03-15 21:40:12.28 UTC
3
2014-01-23 17:49:43.51 UTC
null
null
null
null
137,067
null
1
47
javascript|browser|focus
13,711
<p>document.activeElement is supported by IE6+, FF3+, Safari 4+, Opera 9+, Chrome 9+. (FF2, Saf3 don't support this property)</p>
16,087,331
How to remove square brackets in a Javascript array?
<p>I have an array called <code>value</code> and when I <code>console.log(value)</code> I get about 30 lines of code with the following <code>[6.443663, 3.419248]</code></p> <p>The numbers change as they are Latitudes and Longitudes. But I need to somehow get rid of the square brackets around each one.</p> <p>I tried <code>var replaced = value.toString().replace(/\[.*\]/g,'');</code> but this changed the above example to <code>6.443407,3.419035000000008</code> and failed my code.</p> <p>In other words I need help getting rid of square brackets in an array in order to plot points on my map.</p> <p>My array is made up from the following code because each latitude and longitude value is held within <code>onClick</code> functions within <code>a</code> links. So a member on here kindly supplied the below code to get my values into an array but now I'm struggling to get the values out without any brackets ruining it.</p> <pre><code>var obj = {}; $('.choice-location-inner a').each(function(){ var $this = $(this); var text = $this.attr('onClick').replace('findLocation(\'', '').replace('\');return false;', ''); var array = text.split(',') obj[this.id]= [parseFloat(array[0]), parseFloat(array[1])]; }); </code></pre> <p>The array is trying to plot markers on my Google Map using the following code</p> <pre><code>$.each(obj , function(index, value){ geocoder = new google.maps.Geocoder(); geocoder.geocode( { 'address': value}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { map.setCenter(results[0].geometry.location); marker = new google.maps.Marker({ map: map, icon: image, position: results[0].geometry.location }); } else if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) { wait = true; setTimeout("wait = false", 1000); } else { alert("Geocode was not successful for the following reason: " + status); } }); }); </code></pre>
16,087,478
5
13
null
2013-04-18 15:39:20.733 UTC
2
2021-02-21 02:36:58.717 UTC
2013-04-18 15:49:25.813 UTC
null
206,403
null
1,152,045
null
1
7
javascript|jquery|google-maps|google-maps-api-3
44,510
<p>Unless I've misread and the item is an object rather than a string with brackets contained, the you could just access it by its sub array poition</p> <pre><code>lat = obj[this.id][0] lng = obj[this.id][1] </code></pre> <p>perhaps?</p>
16,568,343
How to check whether a MIME type is of JPG, PNG, BMP or GIF?
<p>I have written this code:</p> <pre><code>$filename = "some/path/where/the/file/can/be/found.some_extension"; $buffer = file_get_contents($filename); $finfo = new finfo(FILEINFO_MIME_TYPE); var_dump($finfo-&gt;buffer($buffer)); finfo_close($finfo); </code></pre> <p>Possible outputs were of:</p> <pre><code>"image/jpeg", "image/png", "image/gif", "image/x-ms-bmp" </code></pre> <p>I would like to know, what are the possible outputs of <code>$finfo-&gt;buffer($buffer)</code>, if the file is a png, gif, bmp, or jpg?</p> <p>I have seen <a href="http://php.net/manual/en/function.mime-content-type.php" rel="noreferrer">here</a> a <code>returnMIMEType</code> function, which, for instance will not detect <code>"image/x-ms-bmp"</code> to be a bmp.</p>
16,652,755
2
9
null
2013-05-15 14:53:01.507 UTC
2
2019-12-26 11:29:12.89 UTC
null
null
null
null
436,560
null
1
8
php|mime-types|fileinfo
45,625
<p>We can view the possible MIME types of file extensions by searching for the file extension at the link provided by Pitchinnate. For instance BMP MIME types can be found at: filext.com/file-extension/BMP</p>
667,426
Resize event firing multiple times while dragging the resize handle
<p>I was hoping this jQuery plug-in would work, but it didn't:</p> <p><a href="http://andowebsit.es/blog/noteslog.com/post/how-to-fix-the-resize-event-in-ie" rel="nofollow noreferrer">http://andowebsit.es/blog/noteslog.com/post/how-to-fix-the-resize-event-in-ie</a> (old link was noteslog.com/post/how-to-fix-the-resize-event-in-ie ).</p> <p>I added a comment to his site, but they're moderated, so you might not see it yet.</p> <p>But anyhow, let me explain my desire. I want a &quot;resize&quot; type of event to be fired when the user either pauses his resize, and/or completes his resize, not <em>while</em> the user is actively dragging the browser's window resize handle. I have a fairly complex and time consuming <code>OnResizeHandled</code> function I need to run, but not run 100 times just because the user widened the window by 100px and the event was fired for ever pixel of movement. I guess a best bet would be to handle it once the user has completed the resize.</p>
19,429,378
7
1
null
2009-03-20 18:41:44.04 UTC
16
2021-02-24 19:19:20.953 UTC
2021-02-24 19:19:20.953 UTC
null
4,370,109
null
52,087
null
1
21
jquery|resize|window|jquery-events
35,792
<p>If you are into libraries, you should checkout underscore, underscore already handles your need and many more you will probably have in your projects.</p> <p>here is an example of how underscore debouncer works:</p> <pre><code>// declare Listener function var debouncerListener = _.debounce( function(e) { // all the actions you need to happen when this event fires }, 300 ); // the amount of milliseconds that you want to wait before this function is called again </code></pre> <p>then just call that debouncer function on the resize of the window</p> <pre><code>window.addEventListener("resize", debouncerListener, false); </code></pre> <p>checkout all the underscore functions available here <a href="http://underscorejs.org/" rel="nofollow">http://underscorejs.org/</a></p>
1,184,518
Getting existing git branches to track remote branches
<p>My usual workflow when working with git, is something like this:</p> <ol> <li>create a local repository</li> <li>do some work in that repository, add/change files etc.</li> <li>decide that I want a central remote location for the repository, and create one</li> <li>push all the commits from my local repository to this new remote repository</li> </ol> <p>Now, however, I want to be able to <code>push</code> and <code>pull</code> from this remote repository without having to specify where I'm pushing to or pulling from; I want my local master to track the remote master.</p> <p>The <em>proper</em> way to do this isn't clear to me, and I've been unable to determine it from the documentation, even though it shouldn't really be more than one command.</p> <p>Because it's something that's only ever done once per repository, I've generally employed one of two simple, but hacky, solutions:</p> <ol> <li>used <code>git clone</code> to make a new local repository, and deleted the old one. After git cloning, the new repository is setup to track the origin.</li> <li>manually edited .git/config to make master track origin.</li> </ol> <p>I think I should be able to run a command, probably some form of <code>git remote</code> to setup an existing repository to have master track a remote master. Can anyone tell me what that command is?</p>
5,172,032
7
4
null
2009-07-26 12:58:11.343 UTC
31
2020-05-31 14:15:13.887 UTC
null
null
null
null
1,577,190
null
1
84
git
86,132
<p>Use the set-upstream arg:</p> <pre><code>git branch --set-upstream local-branch-name origin/remote-branch-name </code></pre> <p>Running the above command updates your .git/config file correctly and even verifies with this output:</p> <p><em>"Branch local-branch-name set up to track remote branch remote-branch-name from origin."</em></p> <p><strong>EDIT:</strong> As <a href="https://stackoverflow.com/users/951064/martijn">martijn</a> said: "In version Git v1.8.0, --set-upstream is deprecated. Use --set-upstream-to instead."</p> <pre><code>git branch --set-upstream-to local-branch-name origin/remote-branch-name </code></pre> <p>See <a href="https://git-scm.com/book/en/v2/Git-Branching-Remote-Branches" rel="noreferrer">this</a> for more information.</p>
523,684
What is the state of the art in computer chess tree searching?
<p>I'm not interested in tiny optimizations giving few percents of the speed. I'm interested in the most important heuristics for alpha-beta search. And most important components for evaluation function.</p> <p>I'm particularly interested in algorithms that have greatest (improvement/code_size) ratio. (NOT (improvement/complexity)).</p> <p>Thanks.</p> <p>PS Killer move heuristic is a perfect example - easy to implement and powerful. Database of heuristics is too complicated.</p>
523,698
8
0
null
2009-02-07 12:38:36.613 UTC
9
2009-02-11 00:31:12.33 UTC
2009-02-07 19:45:23.863 UTC
RoadWarrior
13,118
Łukasz Lew
61,342
null
1
15
algorithm|search|heuristics|chess
3,522
<p>Not sure if you're already aware of it, but check out the <a href="https://chessprogramming.wikispaces.com/" rel="noreferrer">Chess Programming Wiki</a> - it's a great resource that covers just about every aspect of modern chess AI. In particular, relating to your question, see the Search and Evaluation sections (under Principle Topics) on the main page. You might also be able to discover some interesting techniques used in some of the programs listed <a href="https://chessprogramming.wikispaces.com/Engines" rel="noreferrer">here</a>. If your questions still aren't answered, I would definitely recommend you ask in the <a href="https://chessprogramming.wikispaces.com/Computer+Chess+Forums" rel="noreferrer">Chess Programming Forums</a>, where there are likely to be many more specialists around to answer. (Not that you won't necessarily get good answers here, just that it's rather more likely on topic-specific expert forums).</p>
762,512
Is it bad practice to have more than one assertion in a unit test?
<p>Is it bad practice to have more than one assertion in a unit test? Does it matter?</p>
762,582
8
3
null
2009-04-17 23:03:41.477 UTC
12
2017-04-07 08:17:21.887 UTC
2014-05-08 16:58:28.54 UTC
null
634,576
null
4,653
null
1
55
unit-testing|assert
28,763
<p>Sometimes I have exactly one <code>assert</code> per test case, but I think more often I have several <code>assert</code> statements.</p> <p>I've seen the case that @Arkain eludes to, where a very large piece of code has a single unit test suite with just a few test cases, and they are all labeled <code>testCase1</code>, <code>testCase2</code>, etc, and each test case has hundreds of asserts. And even better, each condition usually depends upon the side-effects of previous execution. Whenever the build fails, invariably in such a unit test, it takes quite some time to determine where the problem was.</p> <p>But the other extreme is what your question suggests: a separate test case for each possible condition. Depending on what you're testing, this might make sense, but often I have several <code>assert</code>s per test case.</p> <p>For instance, if you wrote <code>java.lang.Integer</code>, you might have some cases that look like:</p> <pre><code>public void testValueOf() { assertEquals(1, Integer.valueOf("1").intValue()); assertEquals(0, Integer.valueOf("0").intValue()); assertEquals(-1, Integer.valueOf("-1").intValue()); assertEquals(Integer.MAX_VALUE, Integer.valueOf("2147483647").intValue()); assertEquals(Integer.MIN_VALUE, Integer.valueOf("-2147483648").intValue()); .... } public void testValueOfRange() { assertNumberFormatException("2147483648"); assertNumberFormatException("-2147483649"); ... } public void testValueOfNotNumbers() { assertNumberFormatException(""); assertNumberFormatException("notanumber"); ... } private void assertNumberFormatException(String numstr) { try { int number = Integer.valueOf(numstr).intValue(); fail("Expected NumberFormatException for string \"" + numstr + "\" but instead got the number " + number); } catch(NumberFormatException e) { // expected exception } } </code></pre> <p>Some simple rules that I can think of off hand for how many assert's to put in a test case:</p> <ul> <li>Don't have more than one <code>assert</code> that depends on the side-effects of previous execution.</li> <li>Group <code>assert</code>s together that test the same function/feature or facet thereof--no need for the overhead of multiple unit test cases when it's not necessary.</li> <li>Any of the above rules should be overridden by practicality and common sense. You probably don't want a thousand unit test cases with a single assert in each (or even several asserts) and you don't want a single test case with hundreds of <code>assert</code> statements.</li> </ul>
1,279,643
ASP.NET MVC redirect to an access denied page using a custom role provider
<p>I'm creating a custom role provider and I set a Authorize attribute specifying a role in my controller and it's working just fine, like this:</p> <pre><code>[Authorize(Roles="SuperAdmin")] public class SuperAdminController : Controller ... </code></pre> <p>But when an user doens't have access to this controller, he's redirected to login page. How can I redirect him to a "AcessDenied.aspx" page?</p>
1,279,854
9
0
null
2009-08-14 19:10:07.6 UTC
38
2020-04-27 15:33:58.32 UTC
2013-01-20 03:33:37.507 UTC
null
1,437,962
null
60,286
null
1
31
asp.net-mvc|asp.net-membership|roleprovider
42,353
<pre><code>[AccessDeniedAuthorize(Roles="SuperAdmin")] public class SuperAdminController : Controller </code></pre> <p>AccessDeniedAuthorizeAttribute.cs:</p> <pre><code>public class AccessDeniedAuthorizeAttribute : AuthorizeAttribute { public override void OnAuthorization(AuthorizationContext filterContext) { base.OnAuthorization(filterContext); if(filterContext.Result is HttpUnauthorizedResult) { filterContext.Result = new RedirectResult("~/AcessDenied.aspx"); } } } </code></pre>
484,137
Is it possible to format an HTML tooltip (title attribute)?
<p>Is it possible to format an HTML tooltip?</p> <p>E.g. I have a DIV with attribute title="foo!". When I have text-size of my browser zoomed in or out in, the text size of the tooltip remains unchanged. Is there a way to make the tooltip font scale with the browser setting?</p>
484,144
9
0
null
2009-01-27 16:39:01.71 UTC
18
2018-01-12 16:46:49.763 UTC
2014-07-02 09:31:04.08 UTC
null
759,452
sunflowerpower
55,992
null
1
91
html|tooltip
205,430
<p>No. But there are other options out there like <a href="https://github.com/overlib/overlib" rel="noreferrer">Overlib</a>, and <a href="http://www.jquery.com" rel="noreferrer">jQuery</a> that allow you this freedom.</p> <ul> <li>jTip : <a href="http://www.codylindley.com/blogstuff/js/jtip/" rel="noreferrer">http://www.codylindley.com/blogstuff/js/jtip/</a></li> <li>jQuery Tooltip : <a href="https://jqueryui.com/tooltip/" rel="noreferrer">https://jqueryui.com/tooltip/</a></li> </ul> <p>Personally, I would suggest jQuery as the route to take. It's typically very unobtrusive, and requires no additional setup in the markup of your site (with the exception of adding the jquery script tag in your &lt;head&gt;).</p>
143,622
Exception thrown inside catch block - will it be caught again?
<p>This may seem like a programming 101 question and I had thought I knew the answer but now find myself needing to double check. In this piece of code below, will the exception thrown in the first catch block then be caught by the general Exception catch block below?</p> <pre><code>try { // Do something } catch(IOException e) { throw new ApplicationException("Problem connecting to server"); } catch(Exception e) { // Will the ApplicationException be caught here? } </code></pre> <p>I always thought the answer would be no, but now I have some odd behaviour that could be caused by this. The answer is probably the same for most languages but I'm working in Java.</p>
143,628
9
3
null
2008-09-27 13:10:51.74 UTC
37
2015-02-18 19:32:47.26 UTC
2012-08-07 02:30:02.267 UTC
null
390,278
Rory
270
null
1
233
java|exception
256,220
<p>No, since the new <code>throw</code> is not in the <code>try</code> block directly.</p>
872,323
Method call if not null in C#
<p>Is it possible to somehow shorten this statement?</p> <pre><code>if (obj != null) obj.SomeMethod(); </code></pre> <p>because I happen to write this a lot and it gets pretty annoying. The only thing I can think of is to implement <strong>Null Object</strong> pattern, but that's not what I can do every time and it's certainly not a solution to shorten syntax.</p> <p>And similar problem with events, where </p> <pre><code>public event Func&lt;string&gt; MyEvent; </code></pre> <p>and then invoke</p> <pre><code>if (MyEvent != null) MyEvent.Invoke(); </code></pre>
872,328
11
8
null
2009-05-16 12:15:04.997 UTC
31
2020-10-08 01:40:59.247 UTC
2016-02-15 07:31:50.75 UTC
null
4,519,059
null
72,583
null
1
128
c#|null
266,239
<p>From C# 6 onwards, you can just use:</p> <pre><code>MyEvent?.Invoke(); </code></pre> <p>or:</p> <pre><code>obj?.SomeMethod(); </code></pre> <p>The <code>?.</code> is the null-propagating operator, and will cause the <code>.Invoke()</code> to be short-circuited when the operand is <code>null</code>. The operand is only accessed once, so there is no risk of the "value changes between check and invoke" problem.</p> <p>===</p> <p>Prior to C# 6, no: there is no null-safe magic, with one exception; extension methods - for example:</p> <pre><code>public static void SafeInvoke(this Action action) { if(action != null) action(); } </code></pre> <p>now this is valid:</p> <pre><code>Action act = null; act.SafeInvoke(); // does nothing act = delegate {Console.WriteLine("hi");} act.SafeInvoke(); // writes "hi" </code></pre> <p>In the case of events, this has the advantage of also removing the race-condition, i.e. you don't need a temporary variable. So normally you'd need:</p> <pre><code>var handler = SomeEvent; if(handler != null) handler(this, EventArgs.Empty); </code></pre> <p>but with:</p> <pre><code>public static void SafeInvoke(this EventHandler handler, object sender) { if(handler != null) handler(sender, EventArgs.Empty); } </code></pre> <p>we can use simply:</p> <pre><code>SomeEvent.SafeInvoke(this); // no race condition, no null risk </code></pre>
287,713
How do I remove carriage returns with Ruby?
<p>I thought this code would work, but the regular expression doesn't ever match the \r\n. I have viewed the data I am reading in a hex editor and verified there really is a hex D and hex A pattern in the file.</p> <p>I have also tried the regular expressions /\xD\xA/m and /\x0D\x0A/m but they also didn't match.</p> <p>This is my code right now:</p> <pre><code> lines2 = lines.gsub( /\r\n/m, "\n" ) if ( lines == lines2 ) print "still the same\n" else print "made the change\n" end </code></pre> <p>In addition to alternatives, it would be nice to know what I'm doing wrong (to facilitate some learning on my part). :)</p>
287,890
14
0
null
2008-11-13 18:00:41.843 UTC
16
2018-03-22 09:30:50.8 UTC
2008-12-12 22:53:55.817 UTC
mat
42,083
Jeremy Mullin
7,893
null
1
81
ruby|regex
141,471
<p>What do you get when you do <code>puts lines</code>? That will give you a clue.</p> <p>By default <code>File.open</code> opens the file in text mode, so your <code>\r\n</code> characters will be automatically converted to <code>\n</code>. Maybe that's the reason <code>lines</code> are always equal to <code>lines2</code>. To prevent Ruby from parsing the line ends use the <code>rb</code> mode:</p> <pre>C:\> copy con lala.txt a file with many lines ^Z C:\> irb irb(main):001:0> text = File.open('lala.txt').read => "a\nfile\nwith\nmany\nlines\n" irb(main):002:0> bin = File.open('lala.txt', 'rb').read => "a\r\nfile\r\nwith\r\nmany\r\nlines\r\n" irb(main):003:0> </pre> <p>But from your question and code I see you simply need to open the file with the default modifier. You don't need any conversion and may use the shorter <code>File.read</code>.</p>
6,371
How do you manage databases in development, test, and production?
<p>I've had a hard time trying to find good examples of how to manage database schemas and data between development, test, and production servers.</p> <p>Here's our setup. Each developer has a virtual machine running our app and the MySQL database. It is their personal sandbox to do whatever they want. Currently, developers will make a change to the SQL schema and do a dump of the database to a text file that they commit into SVN.</p> <p>We're wanting to deploy a continuous integration development server that will always be running the latest committed code. If we do that now, it will reload the database from SVN for each build.</p> <p>We have a test (virtual) server that runs "release candidates." Deploying to the test server is currently a very manual process, and usually involves me loading the latest SQL from SVN and tweaking it. Also, the data on the test server is inconsistent. You end up with whatever test data the last developer to commit had on his sandbox server.</p> <p>Where everything breaks down is the deployment to production. Since we can't overwrite the live data with test data, this involves manually re-creating all the schema changes. If there were a large number of schema changes or conversion scripts to manipulate the data, this can get really hairy.</p> <p>If the problem was just the schema, It'd be an easier problem, but there is "base" data in the database that is updated during development as well, such as meta-data in security and permissions tables.</p> <p>This is the biggest barrier I see in moving toward continuous integration and one-step-builds. How do <strong><em>you</em></strong> solve it?</p> <hr> <p>A follow-up question: how do you track database versions so you know which scripts to run to upgrade a given database instance? Is a version table like Lance mentions below the standard procedure?</p> <hr> <p>Thanks for the reference to Tarantino. I'm not in a .NET environment, but I found their <a href="http://code.google.com/p/tarantino/wiki/DatabaseChangeManagement" rel="noreferrer">DataBaseChangeMangement wiki page</a> to be very helpful. Especially this <a href="http://tarantino.googlecode.com/svn/docs/Database-Change-Management.ppt" rel="noreferrer">Powerpoint Presentation (.ppt)</a></p> <p>I'm going to write a Python script that checks the names of <code>*.sql</code> scripts in a given directory against a table in the database and runs the ones that aren't there in order based on a integer that forms the first part of the filename. If it is a pretty simple solution, as I suspect it will be, then I'll post it here.</p> <hr> <p>I've got a working script for this. It handles initializing the DB if it doesn't exist and running upgrade scripts as necessary. There are also switches for wiping an existing database and importing test data from a file. It's about 200 lines, so I won't post it (though I might put it on pastebin if there's interest).</p>
6,380
14
2
2009-01-31 20:51:15.907 UTC
2008-08-08 20:50:02.93 UTC
80
2020-06-25 08:29:24.153 UTC
2011-10-18 13:56:08.697 UTC
Matt Miller
496,830
null
763
null
1
181
mysql|svn
39,099
<p>There are a couple of good options. I wouldn't use the "restore a backup" strategy.</p> <ol> <li><p>Script all your schema changes, and have your CI server run those scripts on the database. Have a version table to keep track of the current database version, and only execute the scripts if they are for a newer version.</p></li> <li><p>Use a migration solution. These solutions vary by language, but for .NET I use Migrator.NET. This allows you to version your database and move up and down between versions. Your schema is specified in C# code.</p></li> </ol>
188,892
glob pattern matching in .NET
<p>Is there a built-in mechanism in .NET to match patterns other than Regular Expressions? I'd like to match using UNIX style (glob) wildcards (* = any number of any character). </p> <p>I'd like to use this for a end-user facing control. I fear that permitting all RegEx capabilities will be very confusing.</p>
190,297
15
8
null
2008-10-09 19:45:51.13 UTC
20
2022-07-11 10:55:55.27 UTC
2008-10-09 20:11:13.263 UTC
dmo
1,807
dmo
1,807
null
1
59
c#|.net|glob
31,031
<p>I found the actual code for you:</p> <pre><code>Regex.Escape( wildcardExpression ).Replace( @"\*", ".*" ).Replace( @"\?", "." ); </code></pre>
767,486
How do I check if a variable is an array in JavaScript?
<p>How do I check if a variable is an array in JavaScript?</p> <pre><code>if (variable.constructor == Array) </code></pre>
26,633,883
24
8
null
2009-04-20 09:02:59.553 UTC
298
2022-06-02 13:11:48.15 UTC
2022-04-10 12:59:04.193 UTC
null
365,102
null
3,362
null
1
2,006
javascript|arrays|list|variables
1,130,616
<p>There are several ways of checking if an variable is an array or not. The best solution is the one you have chosen.</p> <pre><code>variable.constructor === Array </code></pre> <p>This is the fastest method on Chrome, and most likely all other browsers. All arrays are objects, so checking the constructor property is a fast process for JavaScript engines.</p> <p>If you are having issues with finding out if an objects property is an array, you must first check if the property is there.</p> <pre><code>variable.prop &amp;&amp; variable.prop.constructor === Array </code></pre> <p>Some other ways are:</p> <pre><code>Array.isArray(variable) </code></pre> <p><strong>Update May 23, 2019 using Chrome 75, shout out to @AnduAndrici for having me revisit this with his question</strong> This last one is, in my opinion the ugliest, and it is one of the <s>slowest</s> fastest. <s>Running about 1/5 the speed as the first example.</s> This guy is about 2-5% slower, but it's pretty hard to tell. Solid to use! Quite impressed by the outcome. Array.prototype, is actually an array. you can read more about it here <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray" rel="noreferrer">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray</a></p> <pre><code>variable instanceof Array </code></pre> <p>This method runs about <s>1/3 the speed</s> as the first example. Still pretty solid, looks cleaner, if you're all about pretty code and not so much on performance. Note that checking for numbers does not work as <code>variable instanceof Number</code> always returns <code>false</code>. <strong>Update: <code>instanceof</code> now goes 2/3 the speed!</strong></p> <p><strong>So yet another update</strong></p> <pre><code>Object.prototype.toString.call(variable) === '[object Array]'; </code></pre> <p>This guy is the slowest for trying to check for an Array. However, this is a one stop shop for any type you're looking for. However, since you're looking for an array, just use the fastest method above.</p> <p>Also, I ran some test: <a href="http://jsperf.com/instanceof-array-vs-array-isarray/35" rel="noreferrer">http://jsperf.com/instanceof-array-vs-array-isarray/35</a> So have some fun and check it out.</p> <p>Note: @EscapeNetscape has created another test as jsperf.com is down. <a href="http://jsben.ch/#/QgYAV" rel="noreferrer">http://jsben.ch/#/QgYAV</a> I wanted to make sure the original link stay for whenever jsperf comes back online.</p>
476,348
That A-Ha Moment for Understanding OO Design in C#
<p>I've been studying C# for a couple of years, reading voraciously, even taking a few C# data access courses from Microsoft. I've also been reading books on OOP. I'm coding a web-based database application at work. While my job title is not "programmer", I'm fortunate enough to be able to work on this as a side project. I coded in Basic in the early 80's and was even good at utilizing pokes and peeks to manipulate the Apple ][ + and the TRS-80 to astound and amaze my friends. But that was a very linear approach to coding. </p> <p>All this being said, something is just not clicking with me. I haven't had that a-ha moment with either C# or OOP that gives me the ability to sit down, open up VS2008, and start coding. I have to study other people's code so much that it simply seems like I'm not doing anything on my own. I'm getting discouraged.</p> <p>It's not like I'm not capable of it. I picked up t-sql really quickly. Someone can tell me what information they want out of the database and I can code out the tsql in a matter of a few minutes to give them what they want. SQL is something that I get. This isn't happening for me with OOP or C#. Granted, C# is inherently more complex, but at some point it has to click. Right?</p> <p>I read over stackoverflow and I'm overwhelmed at how infinitely smart you all are.</p> <p>What was it for you that made it click?</p> <p><strong>Edited to add:</strong> A lot of the answers here were outstanding. However, one in particular seemed to have risen to the top and that's the one I marked as the "answer". I also hate not marking my questions with the answer.</p>
476,374
30
8
2009-01-24 18:30:35.147 UTC
2009-01-24 17:11:44.54 UTC
16
2009-01-29 21:36:20.433 UTC
2009-01-27 21:14:25.757 UTC
GregD
38,317
GregD
38,317
null
1
19
c#|oop
5,302
<p>Learning about interfaces did it for me. Coming from a scripting background and switching to OO, I didn't see how creating all these classes was any more efficient. Then I read <a href="http://oreilly.com/catalog/9780596007126/" rel="noreferrer">Head First Design Patterns</a>, and suddenly I saw the why. It's not the most detailed book, but it's a fantastic first step to explaining the "why" of OO programming, something that I struggled with immensely. </p> <p>Hope this helps.</p>
208,193
Why should I use an IDE?
<p>In another question, <a href="https://stackoverflow.com/users/26310/mark">Mark</a> speaks highly of IDEs, saying "some people still just dont know "why" they should use one...". As someone who uses vim for programming, and works in an environment where most/all of my colleagues use either vim or emacs for all of their work, what are the advantages of IDEs? Why should I use one?</p> <p>I'm sure this is a charged issue for some people, and I'm not interested in starting a flame war, so <strong>please only reply with the reasons you believe an IDE-based approach is superior</strong>. I'm not interested in hearing about why I shouldn't use an IDE; I already don't use one. I'm interested in hearing from "the other side of the fence", so to speak.</p> <p>If you think that IDEs may be suitable for some types of work but not others, I'm also interested to hear why.</p>
208,221
36
6
2008-11-27 22:33:25.233 UTC
2008-10-16 11:41:46.35 UTC
122
2017-09-07 08:08:23.837 UTC
2017-05-23 12:10:08.013 UTC
harriyott
-1
null
24,806
null
1
397
vim|emacs|ide
120,530
<p>It really depends on what language you're using, but in C# and Java I find IDEs beneficial for:</p> <ul> <li>Quickly navigating to a type without needing to worry about namespace, project etc</li> <li>Navigating to members by treating them as hyperlinks</li> <li>Autocompletion when you can't remember the names of all members by heart</li> <li>Automatic code generation</li> <li>Refactoring (massive one)</li> <li>Organise imports (automatically adding appropriate imports in Java, using directives in C#)</li> <li>Warning-as-you-type (i.e. some errors don't even require a compile cycle)</li> <li>Hovering over something to see the docs</li> <li>Keeping a view of files, errors/warnings/console/unit tests etc and source code all on the screen at the same time in a useful way</li> <li>Ease of running unit tests from the same window</li> <li>Integrated debugging</li> <li>Integrated source control</li> <li>Navigating to where a compile-time error or run-time exception occurred directly from the error details.</li> <li>Etc!</li> </ul> <p>All of these save time. They're things I could do manually, but with more pain: I'd rather be coding.</p>
6,619,020
How can I define the DIRECTORY_SEPARATOR for both Windows and Linux platforms?
<p>Now I create a small PHP Application, here I have problem for using file path, because in Windows use this type location <code>C:\Some\Location\index</code> but in <code>Linux /www/app/index</code> so when I define the path using this <code>/</code> but when the application run in window machine it should be problem for this <code>/</code>. </p> <p>So here I want to define the DIRECTORY_SEPARATOR both Windows and Linux platform.</p>
6,619,053
7
0
null
2011-07-08 01:29:35.547 UTC
9
2022-04-08 03:42:14.417 UTC
2016-08-15 09:18:37.917 UTC
null
2,926,103
null
631,915
null
1
24
php|windows|linux
44,420
<p>PHP accepts both <code>\</code> and <code>/</code> as valid path separators in all OS. So just use <code>/</code> in your code</p>
6,902,237
CSS unwanted spacing between anchor-tag elements
<p>I have this stylesheet:</p> <pre><code>*{ padding: 0px; margin: 0px; } a{ background:yellow; } </code></pre> <p>and this webpage:</p> <pre><code>&lt;a href="/blog/"&gt;Home&lt;/a&gt; &lt;a href="/about/"&gt;About&lt;/a&gt; &lt;a href="/contact/"&gt;Contact&lt;/a&gt; </code></pre> <p>Results in:</p> <p><img src="https://i.stack.imgur.com/vBe1a.jpg" alt="enter image description here"> </p> <p>How do I make those anchor tag to "touch" each other,removing that unwanted space in-between?</p> <p>thanks Luca</p>
6,902,279
7
1
null
2011-08-01 17:43:17.907 UTC
4
2021-01-26 21:27:20.787 UTC
2012-06-10 18:22:28.33 UTC
null
709,626
null
505,762
null
1
30
html|css|anchor|margin
37,791
<p>You need to remove the whitespace (in this case the newline) between your tags. Some browsers render it as a space.</p>
6,946,435
Devise: Why doesn't my logout link work?
<p>the problem: In a nutshell, when I try to install a logout link to my app it fails to work. Here's as much context as I can think to put here (if you want anything else, please poke me)...</p> <p>I've got this in a haml view:</p> <pre><code>= link_to("Logout", destroy_user_session_path, :method =&gt; :delete) </code></pre> <p>It generates this in the view:</p> <pre><code>&lt;a href="/users/sign_out" data-method="delete" rel="nofollow"&gt;Logout&lt;/a&gt; </code></pre> <p>I verified that in my config/initializers/devise.rb I have this setting uncommented and correct:</p> <pre><code>config.sign_out_via = :delete </code></pre> <p>I validated the following route:</p> <pre><code>destroy_user_session DELETE /users/sign_out(.:format) {:action=&gt;"destroy", :controller=&gt;"devise/sessions"} </code></pre> <p>I also have this bit of trickery in my routes.rb, and I suspect this is related to my issue:</p> <pre><code>devise_for :users, :controllers =&gt; {:sessions =&gt; "devise/sessions", :registrations =&gt; "users"} resources :users </code></pre> <p>This last bit is because I want to manage (edit, create and delete) users in my own controller. </p> <p>The error message I'm getting is as follows: </p> <pre><code>ActiveRecord::RecordNotFound in UsersController#show Couldn't find User with ID=sign_out Rails.root: /home/jaydel/projects/mbsquared-projects/Wilson-Goldrick app/controllers/users_controller.rb:16:in `show' </code></pre> <p>In my server logs I see this for the request:</p> <pre><code>Started GET "/users/sign_out" for 127.0.0.1 at 2011-08-04 13:08:51 -0500 Processing by UsersController#show as HTML Parameters: {"id"=&gt;"sign_out"} </code></pre> <p>Anyone have any ideas?</p>
6,947,032
19
0
null
2011-08-04 18:11:40.617 UTC
15
2022-02-14 22:36:24.153 UTC
2012-11-12 21:47:43.627 UTC
null
1,238,994
null
483,040
null
1
49
ruby-on-rails|devise
43,747
<p>The problem lies in the fact that in your logs the signout request is a GET request.</p> <pre><code>Started GET "/users/sign_out" </code></pre> <p>But the signout route is a DELETE</p> <pre><code>destroy_user_session DELETE /users/sign_out(.:format) </code></pre> <p>The reason why you are getting the exception is that is it getting confused with one of the routes created by <code>resources :users</code> which would be something like</p> <pre><code>edit_user GET /users/(:id)(.:format) {:action=&gt;"edit", :controller=&gt;"users"} </code></pre> <p>Basically 'sign_out' is being mistaken as a id.</p> <p>I'm not sure why the delete link is not going through as a DELETE request. Though changing</p> <pre><code>config.sign_out_via = :delete </code></pre> <p>to be <code>:get</code> might solve the problem.</p>
41,264,716
Jenkins and Groovy and Regex
<p>I am very new to using groovy. Especially when it comes to Jenkins+Groovy+Pipelines.</p> <p>I have a string variable that can change from time to time and want to apply a regex to accomodate the 2 or 3 possible results the string may return.</p> <p>In my groovy code I have:</p> <pre><code>r = &quot;Some text that will always end in either running, stopped, starting.&quot; def regex = ~/(.*)running(.*)/ assert regex.matches(r) </code></pre> <p>But I receive an error in the jenkins output:</p> <blockquote> <p>hudson.remoting.ProxyException: groovy.lang.MissingMethodException: No signature of method: java.util.regex.Pattern.matches() is applicable for argument types: (java.lang.String)</p> </blockquote> <p>UPDATE: I was able to create a pretty nifty jenking groovy while loop in a pipeline job i am creating to wait for a remote process using the regex info here and a tip in a different post (<a href="https://stackoverflow.com/q/8188641/1741264">How do I iterate over all bytes in an inputStream using Groovy, given that it lacks a do-while statement?</a>).</p> <pre><code> while({ def r = sh returnStdout: true, script: 'ssh &quot;Insert your remote ssh command that returns text' println &quot;Process still running. Waiting on Stop&quot; println &quot;Status returned: $r&quot; r =~ /running|starting|partial/ }()); </code></pre>
41,265,053
3
1
null
2016-12-21 14:08:37 UTC
null
2022-09-05 08:26:14.557 UTC
2022-09-05 08:26:14.557 UTC
null
580,346
null
1,741,264
null
1
6
jenkins|groovy
40,172
<p>Straight-forward would be:</p> <pre><code>String r = "Some text that will always end in either running, stopped, starting." assert r =~ /(.*)running(.*)/ </code></pre>
15,814,526
MongoDB - Aggregation - To get unique items in array
<p>Here's my MongoDB collection:</p> <pre><code>{ "_id" : ObjectId("515d8f53175b8ecb053425c2"), "category" : "Batteries", "products" : [ { "brand" : "Duracell", "item" : [ "AA", "AAA" ] }, { "brand" : "Everyday", "item" : [ "9V", "AA", "12V" ] } ] } </code></pre> <p>The output that I need is </p> <p>1) Unique list of all items</p> <pre><code>{["AA", "AAA", "9V", "12V"]} </code></pre> <p>and 2. unique list of items per product</p> <pre><code>{ "category" : "Batteries", "item": ["AA", "AAA", "9V", "12V"] } </code></pre> <p>I'm very new to MongoDB, and I tried different aggregations functions and nothing seems to work. Please help. </p>
15,823,520
4
0
null
2013-04-04 14:46:18.327 UTC
10
2020-08-03 12:06:32.48 UTC
null
null
null
null
1,933,554
null
1
21
mongodb|mongodb-php|mongodb-query
21,611
<p>After few more tries, I had solved this. Here's the commands:</p> <pre><code>db.xyz.aggregate( {$project: {a: '$products.item'}}, {$unwind: '$a'}, {$unwind: '$a'}, {$group: {_id: 'a', items: {$addToSet: '$a'}}}); </code></pre> <p>and</p> <pre><code>db.xyz.aggregate( {$project: {category: 1, a: '$products.item'}}, {$unwind: '$a'}, {$unwind: '$a'}, {$group: {_id: '$category', items: {$addToSet: '$a'}}}); </code></pre>
15,821,969
What is the proper way to modify OpenGL vertex buffer?
<p>I'm setting up a vertex buffer in OpenGL, like this:</p> <pre><code>int vboVertexHandle = glGenBuffers(); glBindBuffer(GL_ARRAY_BUFFER, vboVertexHandle); glBufferData(GL_ARRAY_BUFFER, vertexData, GL_DYNAMIC_DRAW); </code></pre> <p>Later, if I want to add or remove vertices to "vertexData", what is the proper way to do this? Is it even possible? I'm assuming I can't just modify the array directly without re-sending it to the GPU.</p> <p>If I modify the vertexData array, then call this again:</p> <pre><code>glBindBuffer(GL_ARRAY_BUFFER, vboVertexHandle); glBufferData(GL_ARRAY_BUFFER, vertexData, GL_DYNAMIC_DRAW); </code></pre> <p>...will that overwrite the old buffer with my new data? Or do I also have to delete the old one? Is there a better way?</p>
15,823,859
3
0
null
2013-04-04 21:22:36.677 UTC
19
2020-05-03 05:41:59.11 UTC
null
null
null
null
188,204
null
1
41
opengl
38,996
<p>The size of any OpenGL buffer object is set when you call <code>glBufferData</code>. That is, OpenGL will allocate the amount of memory you specify in the second argument of <code>glBufferData</code> (which isn't listed in the OP). In fact, if you call, for example <code>glBufferData( GL_ARRAY_BUFFER, bufferSize, NULL, GL_DYNAMIC_DRAW );</code> OpenGL will create a buffer of <code>bufferSize</code> bytes of <em>uninitialized data</em>. </p> <p>You can load any amount of data (up to the size of the buffer) using <code>glBufferSubData</code>, <code>glMapBuffer</code>, or any of the other routines for passing data. The only way to resize the buffer is to call <code>glBufferData</code> with a new size for the same buffer id (the value returned from <code>glGenBuffers</code>).</p> <p>That said, you can always use a subset of the data in the buffer (which would be akin to deleting vertices), and if you render using <code>glDrawElements</code>, you can randomly access elements in the buffer. Adding vertices to a buffer would require allocating a larger buffer, and then you'd need to reload all of the data in the buffer.</p>
15,813,851
Checking user's homepage in Internet Explorer
<p>Google displays a popup that asks if you want to set your home page as google.com. It's quite normal, when I say OK it sets it as google.com. After that however, I don't get the popup anymore. As far as I know, nobody should be able to retrieve the value of my homepage because it's a private info. But somehow Google is tracking it. I get the popup back when I set my homepage as a different site. I deleted the cookies but even then it is only displayed when I set homepage as another site.</p> <p>I tested this behavior on IE8 &amp; IE9. The popup never shows up in Firefox and Chrome.</p>
15,814,600
3
25
null
2013-04-04 14:19:06.557 UTC
17
2014-01-28 15:09:59.983 UTC
2014-01-28 15:09:59.983 UTC
null
205,859
null
205,859
null
1
94
javascript|internet-explorer
4,016
<p>Internet Explorer makes it possible to ask it whether a given URL is the home page, it's detailed on <a href="http://msdn.microsoft.com/en-us/library/ms531418%28v=vs.85%29.aspx">this MSDN page</a>. That links to <a href="http://samples.msdn.microsoft.com/workshop/samples/author/behaviors/homepage1.htm">this example page</a> demonstrating the API.</p>
10,686,333
Save array in mysql database
<p>I want to save extra information before sending the total order to Paypal. For each item I have created a single column in my MySQL database where I want to store it. Now I was thinking to save it as an array which I can read later for creating a PHP page. Extra fields are taken from input form fields.</p> <p>By using an array can I be sure not to mixup information?</p>
10,686,474
7
3
null
2012-05-21 13:37:04.55 UTC
14
2021-02-26 06:52:25.457 UTC
2012-05-22 02:35:26.95 UTC
null
680,925
null
1,343,454
null
1
33
php|mysql|arrays
131,260
<p>You can store the array using <a href="http://php.net/serialize" rel="noreferrer"><code>serialize</code></a>/<a href="http://php.net/unserialize" rel="noreferrer"><code>unserialize</code></a>. With that solution they cannot easily be used from other programming languages, so you may consider using <a href="http://php.net/json_encode" rel="noreferrer"><code>json_encode</code></a>/<a href="http://php.net/json_decode" rel="noreferrer"><code>json_decode</code></a> instead (which gives you a widely supported format). <em>Avoid</em> using <code>implode</code>/<code>explode</code> for this since you'll probably end up with bugs or security flaws.</p> <p>Note that this makes your table non-normalized, which may be a bad idea since you cannot easily query the data. Therefore consider this carefully before going forward. May you need to query the data for statistics or otherwise? Are there other reasons to normalize the data?</p> <p>Also, don't save the raw <code>$_POST</code> array. Someone can easily make their own web form and post data to your site, thereby sending a really large form which takes up lots of space. Save those fields you want and make sure to validate the data before saving it (so you won't get invalid values).</p>
10,482,721
How can I restart git bash?
<p>Various documentation such as</p> <p><a href="http://confluence.atlassian.com/display/BITBUCKET/Set+up+SSH+for+Git" rel="noreferrer">http://confluence.atlassian.com/display/BITBUCKET/Set+up+SSH+for+Git</a></p> <p>and</p> <p><a href="http://help.github.com/ssh-key-passphrases/" rel="noreferrer">http://help.github.com/ssh-key-passphrases/</a></p> <p>Refer to restarting git bash. How do I do this from Linux?</p>
10,482,760
1
4
null
2012-05-07 13:10:28.617 UTC
null
2012-05-07 13:18:45.757 UTC
null
null
null
null
144,152
null
1
7
git
41,363
<p>This is referring to the Git Bash shell which is installed via Cygwin on Windows systems. If you need to do this on Linux, simply close and reopen your terminal window. Often you can replace this step with <code>source ~/.bashrc</code></p>
10,762,287
How can I format axis labels with exponents with ggplot2 and scales?
<p>With the new version ggplot2 and scales, I can't figure out how to get axis label in scientific notation. For example:</p> <pre><code>x &lt;- 1:4 y &lt;- c(0, 0.0001, 0.0002, 0.0003) dd &lt;- data.frame(x, y) ggplot(dd, aes(x, y)) + geom_point() </code></pre> <p>gives me</p> <p><img src="https://i.stack.imgur.com/jvLLM.png" alt="Example ggplot with scales"></p> <p>I'd like the axis labels to be 0, 5 x 10^-5, 1 x 10^-4, 1.5 x 10^-4, etc. I can't figure out the correct combination of <code>scale_y_continuous()</code> and <code>math_format()</code> (at least I think those are what I need). </p> <p><code>scale_y_log10()</code> log transforms the axis, which I don't want. <code>scale_y_continuous(label = math_format())</code> just gives me 10^0, 10^5e-5, etc. I see why the latter gives that result, but it's not what I'm looking for.</p> <p>I am using ggplot2_0.9.1 and scales_0.2.1</p>
18,530,540
7
4
null
2012-05-25 23:05:02.177 UTC
15
2021-09-15 14:28:45.647 UTC
2012-05-25 23:12:02.36 UTC
null
168,137
null
168,137
null
1
32
r|ggplot2
32,179
<p>I adapted Brian's answer and I think I got what you're after. </p> <p>Simply by adding a parse() to the scientific_10() function (and changing 'x' to the correct 'times' symbol), you end up with this:</p> <pre><code>x &lt;- 1:4 y &lt;- c(0, 0.0001, 0.0002, 0.0003) dd &lt;- data.frame(x, y) scientific_10 &lt;- function(x) { parse(text=gsub("e", " %*% 10^", scales::scientific_format()(x))) } ggplot(dd, aes(x, y)) + geom_point()+scale_y_continuous(label=scientific_10) </code></pre> <p><img src="https://i.stack.imgur.com/nuLjE.png" alt="enter image description here"></p> <p>You might still want to smarten up the function so it deals with 0 a little more elegantly, but I think that's it!</p>
10,472,393
OpenCV won't compile due to unresolved externals -- LNK2019
<p>I am brand new to OpenCV and have been trying to set it up in Visual Studios 2010 Ultimate. I have followed the documentation exactly, and linked the files as it said. Here are the additional libraries that I am using:</p> <pre><code>opencv_core231d.lib opencv_imgproc231d.lib opencv_highgui231d.lib opencv_ml231d.lib opencv_video231d.lib opencv_features2d231d.lib opencv_calib3d231d.lib opencv_objdetect231d.lib opencv_contrib231d.lib opencv_legacy231d.lib opencv_flann231d.lib </code></pre> <p>And all of their Release counterparts. However, when I try to debug &amp; compile the sample code given to me, I get the following errors. (I read somewhere that you have to compile and publish the project in order for it to work properly? Is that true as well?)</p> <pre><code>1&gt;------ Build started: Project: openCVTest, Configuration: Debug Win32 ------ 1&gt;Build started 5/6/2012 10:39:03 AM. 1&gt;InitializeBuildStatus: 1&gt; Touching "Debug\openCVTest.unsuccessfulbuild". 1&gt;ClCompile: 1&gt; All outputs are up-to-date. 1&gt;ManifestResourceCompile: 1&gt; All outputs are up-to-date. 1&gt;openCVTest.obj : error LNK2019: unresolved external symbol _cvWaitKey referenced in function _main 1&gt;openCVTest.obj : error LNK2019: unresolved external symbol "void __cdecl cv::imshow(class std::basic_string&lt;char,struct std::char_traits&lt;char&gt;,class std::allocator&lt;char&gt; &gt; const &amp;,class cv::_InputArray const &amp;)" (?imshow@cv@@YAXABV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@ABV_InputArray@1@@Z) referenced in function _main 1&gt;openCVTest.obj : error LNK2019: unresolved external symbol "public: __thiscall cv::_InputArray::_InputArray(class cv::Mat const &amp;)" (??0_InputArray@cv@@QAE@ABVMat@1@@Z) referenced in function _main 1&gt;openCVTest.obj : error LNK2019: unresolved external symbol _cvMoveWindow referenced in function _main 1&gt;openCVTest.obj : error LNK2019: unresolved external symbol "void __cdecl cv::namedWindow(class std::basic_string&lt;char,struct std::char_traits&lt;char&gt;,class std::allocator&lt;char&gt; &gt; const &amp;,int)" (?namedWindow@cv@@YAXABV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@H@Z) referenced in function _main 1&gt;openCVTest.obj : error LNK2019: unresolved external symbol "public: virtual double __thiscall cv::VideoCapture::get(int)" (?get@VideoCapture@cv@@UAENH@Z) referenced in function _main 1&gt;openCVTest.obj : error LNK2019: unresolved external symbol "public: virtual __thiscall cv::VideoCapture::~VideoCapture(void)" (??1VideoCapture@cv@@UAE@XZ) referenced in function _main 1&gt;openCVTest.obj : error LNK2019: unresolved external symbol "public: virtual bool __thiscall cv::VideoCapture::isOpened(void)const " (?isOpened@VideoCapture@cv@@UBE_NXZ) referenced in function _main 1&gt;openCVTest.obj : error LNK2019: unresolved external symbol "public: __thiscall cv::VideoCapture::VideoCapture(class std::basic_string&lt;char,struct std::char_traits&lt;char&gt;,class std::allocator&lt;char&gt; &gt; const &amp;)" (??0VideoCapture@cv@@QAE@ABV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z) referenced in function _main 1&gt;openCVTest.obj : error LNK2019: unresolved external symbol "void __cdecl cv::fastFree(void *)" (?fastFree@cv@@YAXPAX@Z) referenced in function "public: __thiscall cv::Mat::~Mat(void)" (??1Mat@cv@@QAE@XZ) 1&gt;openCVTest.obj : error LNK2019: unresolved external symbol "public: void __thiscall cv::Mat::deallocate(void)" (?deallocate@Mat@cv@@QAEXXZ) referenced in function "public: void __thiscall cv::Mat::release(void)" (?release@Mat@cv@@QAEXXZ) 1&gt;openCVTest.obj : error LNK2019: unresolved external symbol "class cv::Scalar_&lt;double&gt; __cdecl cv::sum(class cv::_InputArray const &amp;)" (?sum@cv@@YA?AV?$Scalar_@N@1@ABV_InputArray@1@@Z) referenced in function "double __cdecl getPSNR(class cv::Mat const &amp;,class cv::Mat const &amp;)" (?getPSNR@@YANABVMat@cv@@0@Z) 1&gt;openCVTest.obj : error LNK2019: unresolved external symbol "public: class cv::MatExpr __thiscall cv::Mat::mul(class cv::_InputArray const &amp;,double)const " (?mul@Mat@cv@@QBE?AVMatExpr@2@ABV_InputArray@2@N@Z) referenced in function "double __cdecl getPSNR(class cv::Mat const &amp;,class cv::Mat const &amp;)" (?getPSNR@@YANABVMat@cv@@0@Z) 1&gt;openCVTest.obj : error LNK2019: unresolved external symbol "public: void __thiscall cv::Mat::convertTo(class cv::_OutputArray const &amp;,int,double,double)const " (?convertTo@Mat@cv@@QBEXABV_OutputArray@2@HNN@Z) referenced in function "double __cdecl getPSNR(class cv::Mat const &amp;,class cv::Mat const &amp;)" (?getPSNR@@YANABVMat@cv@@0@Z) 1&gt;openCVTest.obj : error LNK2019: unresolved external symbol "void __cdecl cv::absdiff(class cv::_InputArray const &amp;,class cv::_InputArray const &amp;,class cv::_OutputArray const &amp;)" (?absdiff@cv@@YAXABV_InputArray@1@0ABV_OutputArray@1@@Z) referenced in function "double __cdecl getPSNR(class cv::Mat const &amp;,class cv::Mat const &amp;)" (?getPSNR@@YANABVMat@cv@@0@Z) 1&gt;openCVTest.obj : error LNK2019: unresolved external symbol "public: __thiscall cv::_OutputArray::_OutputArray(class cv::Mat &amp;)" (??0_OutputArray@cv@@QAE@AAVMat@1@@Z) referenced in function "double __cdecl getPSNR(class cv::Mat const &amp;,class cv::Mat const &amp;)" (?getPSNR@@YANABVMat@cv@@0@Z) 1&gt;openCVTest.obj : error LNK2019: unresolved external symbol "class cv::Scalar_&lt;double&gt; __cdecl cv::mean(class cv::_InputArray const &amp;,class cv::_InputArray const &amp;)" (?mean@cv@@YA?AV?$Scalar_@N@1@ABV_InputArray@1@0@Z) referenced in function "class cv::Scalar_&lt;double&gt; __cdecl getMSSIM(class cv::Mat const &amp;,class cv::Mat const &amp;)" (?getMSSIM@@YA?AV?$Scalar_@N@cv@@ABVMat@2@0@Z) 1&gt;openCVTest.obj : error LNK2019: unresolved external symbol "class cv::_OutputArray const &amp; __cdecl cv::noArray(void)" (?noArray@cv@@YAABV_OutputArray@1@XZ) referenced in function "class cv::Scalar_&lt;double&gt; __cdecl getMSSIM(class cv::Mat const &amp;,class cv::Mat const &amp;)" (?getMSSIM@@YA?AV?$Scalar_@N@cv@@ABVMat@2@0@Z) 1&gt;openCVTest.obj : error LNK2019: unresolved external symbol "void __cdecl cv::divide(class cv::_InputArray const &amp;,class cv::_InputArray const &amp;,class cv::_OutputArray const &amp;,double,int)" (?divide@cv@@YAXABV_InputArray@1@0ABV_OutputArray@1@NH@Z) referenced in function "class cv::Scalar_&lt;double&gt; __cdecl getMSSIM(class cv::Mat const &amp;,class cv::Mat const &amp;)" (?getMSSIM@@YA?AV?$Scalar_@N@cv@@ABVMat@2@0@Z) 1&gt;openCVTest.obj : error LNK2019: unresolved external symbol "class cv::MatExpr __cdecl cv::operator+(class cv::Mat const &amp;,class cv::Mat const &amp;)" (??Hcv@@YA?AVMatExpr@0@ABVMat@0@0@Z) referenced in function "class cv::Scalar_&lt;double&gt; __cdecl getMSSIM(class cv::Mat const &amp;,class cv::Mat const &amp;)" (?getMSSIM@@YA?AV?$Scalar_@N@cv@@ABVMat@2@0@Z) 1&gt;openCVTest.obj : error LNK2019: unresolved external symbol "class cv::MatExpr __cdecl cv::operator+(class cv::MatExpr const &amp;,class cv::Scalar_&lt;double&gt; const &amp;)" (??Hcv@@YA?AVMatExpr@0@ABV10@ABV?$Scalar_@N@0@@Z) referenced in function "class cv::Scalar_&lt;double&gt; __cdecl getMSSIM(class cv::Mat const &amp;,class cv::Mat const &amp;)" (?getMSSIM@@YA?AV?$Scalar_@N@cv@@ABVMat@2@0@Z) 1&gt;openCVTest.obj : error LNK2019: unresolved external symbol "class cv::MatExpr __cdecl cv::operator*(double,class cv::Mat const &amp;)" (??Dcv@@YA?AVMatExpr@0@NABVMat@0@@Z) referenced in function "class cv::Scalar_&lt;double&gt; __cdecl getMSSIM(class cv::Mat const &amp;,class cv::Mat const &amp;)" (?getMSSIM@@YA?AV?$Scalar_@N@cv@@ABVMat@2@0@Z) 1&gt;openCVTest.obj : error LNK2019: unresolved external symbol "void __cdecl cv::GaussianBlur(class cv::_InputArray const &amp;,class cv::_OutputArray const &amp;,class cv::Size_&lt;int&gt;,double,double,int)" (?GaussianBlur@cv@@YAXABV_InputArray@1@ABV_OutputArray@1@V?$Size_@H@1@NNH@Z) referenced in function "class cv::Scalar_&lt;double&gt; __cdecl getMSSIM(class cv::Mat const &amp;,class cv::Mat const &amp;)" (?getMSSIM@@YA?AV?$Scalar_@N@cv@@ABVMat@2@0@Z) 1&gt;openCVTest.obj : error LNK2019: unresolved external symbol "public: void __thiscall cv::Mat::copySize(class cv::Mat const &amp;)" (?copySize@Mat@cv@@QAEXABV12@@Z) referenced in function "public: __thiscall cv::Mat::Mat(class cv::Mat const &amp;)" (??0Mat@cv@@QAE@ABV01@@Z) 1&gt;openCVTest.obj : error LNK2019: unresolved external symbol "void __cdecl cv::subtract(class cv::_InputArray const &amp;,class cv::_InputArray const &amp;,class cv::_OutputArray const &amp;,class cv::_InputArray const &amp;,int)" (?subtract@cv@@YAXABV_InputArray@1@0ABV_OutputArray@1@0H@Z) referenced in function "class cv::Mat &amp; __cdecl cv::operator-=(class cv::Mat const &amp;,class cv::Mat const &amp;)" (??Zcv@@YAAAVMat@0@ABV10@0@Z) 1&gt;C:\Users\Logan\documents\visual studio 2010\Projects\openCVTest\Debug\openCVTest.exe : fatal error LNK1120: 25 unresolved externals 1&gt; 1&gt;Build FAILED. 1&gt; 1&gt;Time Elapsed 00:00:00.40 ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ========== </code></pre> <p>I went through all my directories and made sure that the libraries, did in fact, exist in my OpenCV files, and my download didn't corrupt or anything. Any help would be appreciated!</p> <p>-Logantf17</p>
10,474,630
2
6
null
2012-05-06 16:56:38.503 UTC
2
2013-09-20 21:17:12.12 UTC
2012-05-06 17:54:54.137 UTC
null
589,206
null
1,378,308
null
1
8
c++|visual-studio-2010|opencv|unresolved-external|lnk2019
39,450
<p>shambool in <a href="https://stackoverflow.com/questions/10474218/unresolved-external-symbol-error-when-importing-libraries-for-opencv2-3-in-visua">another thread</a> just pointed that you should maybe read <a href="http://docs.opencv.org/trunk/doc/tutorials/introduction/windows_visual_studio_Opencv/windows_visual_studio_Opencv.html#windows-visual-studio-how-to" rel="nofollow noreferrer">this</a>.</p>
37,895,592
How to use multiple ssh keys for multiple gitlab accounts with the same host
<p>I want to use 2 accounts in <a href="https://gitlab.com/" rel="noreferrer">Gitlab</a> website, every account with a different ssh key</p> <p>I generated the keys successfully and add them in <code>~/.ssh</code> folder I created <code>~/.ssh/config</code> file and use one of them , it's works good I can also make swapping between the two keys by editing the <code>~/.ssh/config</code> file</p> <p><strong>The problem is :</strong> I want to use them in the same time , but all the tutorials i found taking about different hosts :/ </p> <p>actually my two accounts are in the same host</p> <p>how can i edit the <code>~/.ssh/config</code> file to accept two accounts for the same host</p> <p><strong>Note:</strong> I read <a href="https://stackoverflow.com/q/14888056/3185456">this question</a> but i can't get help from it</p> <p>My two accounts are <code>username1</code> and <code>username2</code> repo URL looks like : <a href="http://[email protected]:username1/test-project.git" rel="noreferrer">[email protected]:username1/test-project.git</a></p> <p>My current <code>~/.ssh/config</code> file:</p> <pre><code>Host gitlab.com-username1 HostName gitlab.com User git IdentityFile ~/.ssh/id_rsa Host gitlab.com-username2 HostName gitlab.com User git IdentityFile ~/.ssh/id_rsa_username2 </code></pre> <p><strong>Update 1:</strong> </p> <p>1) When I use one key in the <code>~/.ssh/config</code> file , everything works perfect (but it's very boring to update it every time i want to change the user i use)</p> <p>2) When i use this lines <code>ssh -T [email protected] ssh -T [email protected]</code> its works good and return a welcoming message</p> <p>From 1) and 2) , i think the problem is definitely from the <code>~/.ssh/config</code> file , specifically in <code>Host</code> variable </p> <p><strong>Update 2: (the solving)</strong> the solving was to edit the <code>.git/config</code> file from <code>[remote "origin"] url = [email protected]:username1/test-project.git</code> to <code>[remote "origin"] url = [email protected]:username1/test-project.git</code></p> <p>and do the same for the <code>username2</code></p>
37,901,351
2
10
null
2016-06-18 09:48:53.787 UTC
12
2016-06-18 22:06:55.873 UTC
2017-05-23 12:02:05.5 UTC
null
-1
null
3,185,456
null
1
22
git|ssh|gitlab|ssh-keys
11,472
<p>You have got complete <code>ssh</code> configuration. First of all, check if it works:</p> <pre><code>ssh -T [email protected] ssh -T [email protected] </code></pre> <p>should succeed in both cases. If not, the keys are not set up correctly. Verify that the keys are on gitlab for respective users.</p> <p>If it works, move on to your git repository and open <code>.git/config</code>. It will have some part like:</p> <pre><code>[remote "origin"] url = [email protected]:username1/test-project.git </code></pre> <p>Replace it with </p> <pre><code>[remote "origin"] url = [email protected]:username1/test-project.git </code></pre> <p>(or <code>username1</code> if you want to connect using this username). Then it should allow you to push.</p>
24,972,437
Error: org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'text/plain;charset=UTF-8' not supported
<p>I'm newbie in Spring Data. I keep getting the error: <code>org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'text/plain;charset=UTF-8' not supported</code> I've tried to change consumes inside <code>@RequestMapping</code> annotation to <code>text/plain</code> but unfortunately it didn't help.*</p> <p>Any ideas?</p> <p>Thanks,</p> <p>My Code looks like this:</p> <pre><code>package com.budget.processing.application; import com.budget.business.service.Budget; import com.budget.business.service.BudgetItem; import com.budget.business.service.BudgetService; import com.budget.processing.dto.BudgetDTO; import com.budget.processing.dto.BudgetPerConsumerDTO; import com.utils.Constants; import com.common.utils.config.exception.GeneralException; import org.apache.log4j.Logger; import org.joda.time.YearMonth; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.*; import javax.ws.rs.core.MediaType; import java.text.ParseException; import java.util.ArrayList; import java.util.Collection; import java.util.List; @Controller("budgetManager") @RequestMapping(value = "budget", produces = Constants.RESPONSE_APP_JSON) @Transactional(propagation = Propagation.REQUIRED) public class BudgetManager { private static final Logger logger = Logger.getLogger(BudgetManager.class); @Autowired private BudgetService budgetService; @RequestMapping(method = RequestMethod.GET) public @ResponseBody Collection&lt;BudgetDTO&gt; getBudgetMonthlyAllConsumers() throws GeneralException { List&lt;Budget&gt; budgetList = budgetService.getBudgetForAllConsumers(); List&lt;BudgetDTO&gt; bugetDtos = new ArrayList&lt;&gt;(); for (Budget budget : budgetList) { BudgetDTO budgetDTO = generateBudgetDto(budget); bugetDtos.add(budgetDTO); } return bugetDtos; } @RequestMapping(method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON) public @ResponseBody Collection&lt;BudgetDTO&gt; updateConsumerBudget(@RequestParam(value = "budgetPerDate", required = false) ArrayList&lt;BudgetPerConsumerDTO&gt; budgetPerDate) throws GeneralException, ParseException { List&lt;BudgetItem&gt; budgetItemList = new ArrayList&lt;&gt;(); List&lt;Budget&gt; budgets = new ArrayList&lt;&gt;(); if (budgetPerDate != null) { for (BudgetPerConsumerDTO budgetPerConsumerDTO : budgetPerDate) { budgetItemList.add(budgetService.createBudgetItemForConsumer(budgetPerConsumerDTO.getId(), new YearMonth(budgetPerConsumerDTO.getDate()), budgetPerConsumerDTO.getBudget())); } } budgets = budgetService.getBudgetForAllConsumers(); List&lt;BudgetDTO&gt; budgetDTOList = new ArrayList&lt;&gt;(); for (Budget budget : budgets) { BudgetDTO budgetDto = generateBudgetDto(budget); budgetDTOList.add(budgetDto); } return budgetDTOList; } </code></pre> <p>}</p> <p>Here is the exception I get: </p> <pre><code>ERROR 2014-07-26 18:05:10.737 (GlobalExceptionHandler.eITFMSException: 86) Error executing Web Service org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'text/plain;charset=UTF-8' not supported at org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping.handleNoMatch(RequestMappingInfoHandlerMapping.java:215) at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.lookupHandlerMethod(AbstractHandlerMethodMapping.java:289) at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.getHandlerInternal(AbstractHandlerMethodMapping.java:229) at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.getHandlerInternal(AbstractHandlerMethodMapping.java:56) at org.springframework.web.servlet.handler.AbstractHandlerMapping.getHandler(AbstractHandlerMapping.java:298) at org.springframework.web.servlet.DispatcherServlet.getHandler(DispatcherServlet.java:1091) </code></pre> <p>The request looks like that: i'm using Simple Rest Template Google Extension. the Request looks like the following:</p> <pre><code>localhost:8080/rest 1 requests ❘ 140 B transferred HeadersPreviewResponseCookiesTiming Remote Address:localhost:8080 Request URL: localhost:8080/rest/budget Request Method:PUT Status Code:500 Internal Server Error Request Headersview source Accept:*/* Accept-Encoding:gzip,deflate,sdch Accept-Language:en-US,en;q=0.8,he;q=0.6 Connection:keep-alive Content-Length:331 Content-Type:text/plain;charset=UTF-8 Cookie:JSESSIONID=AE87EEB7A73B9F9E81956231C1735814 Host:10.23.204.204:8080 Origin:chrome-extension://fhjcajmcbmldlhcimfajhfbgofnpcjmb User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36 Request Payloadview parsed { "budgetPerDate": [ { "id":942, "date":[ 2014, 1, 1 ], "budget": 100 }, { "id":942, "date":[ 2014, 2, 1 ], "budget": 150 } ] } </code></pre>
24,973,845
5
14
null
2014-07-26 15:12:15.193 UTC
7
2022-03-23 15:24:16.427 UTC
2017-07-21 13:56:21.207 UTC
null
1,553,874
null
1,553,874
null
1
49
java|spring|spring-mvc
206,697
<p>Building on what is mentioned in the comments, the simplest solution would be:</p> <pre><code>@RequestMapping(method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public Collection&lt;BudgetDTO&gt; updateConsumerBudget(@RequestBody SomeDto someDto) throws GeneralException, ParseException { //whatever } class SomeDto { private List&lt;WhateverBudgerPerDateDTO&gt; budgetPerDate; //getters setters } </code></pre> <p>The solution assumes that the HTTP request you are creating actually has</p> <p><code>Content-Type:application/json</code> instead of <code>text/plain</code></p>
22,722,575
git remove file from stash
<p>I have a stash with a bunch of files in it.</p> <p>But I can't apply my stash because of a conflicting file. I've identified the problematic file in my stash and I want to remove it.</p> <p>How can I remove a single file from a stash without destroying the entire thing?</p>
22,723,131
5
2
null
2014-03-28 20:25:08.123 UTC
9
2021-11-16 14:28:14.683 UTC
2015-05-07 15:37:06.73 UTC
null
2,936,460
user773737
null
null
1
54
git|git-stash|merge-conflict-resolution
46,929
<p>A stash is a commit (or really, two or even sometimes three commits) and you cannot change a commit. The literal answer to your question, then, is "you can't". Fortunately, you don't <em>need</em> to.</p> <p>You say you can't apply your stash because of a conflicting file. But you <em>can</em> apply it, you just get a merge conflict. All you need to do is resolve the merge conflict.</p> <p>Let's say the conflict is in file <code>README.txt</code>, just so there's something to write about here.</p> <p>If you want to resolve it by keeping the on-branch version, apply the stash, then check out the on-branch version to resolve the conflict:</p> <pre><code>git stash apply git checkout --ours -- README.txt # or git checkout HEAD -- README.txt </code></pre> <p>If you want to keep the in-stash version, extract that one:</p> <pre><code>git checkout --theirs -- README.txt # or git checkout stash -- README.txt </code></pre> <p>Or, use any old merge resolution tool (I just use a text editor), and then "git add" the result.</p> <p>Once you are all done with the stash, <code>git stash drop</code> will "forget" the commits that make up the stash. (Don't do this until you are sure you are done with it; it's very hard to get it back afterward.)</p>
22,643,032
Anchor tag doesn't work in iPhone Safari
<p>I'm having an issue with a named anchor tag in iPhone Safari browser. It works well in desktop browsers including Safari, but not working in mobile Safari. Weird!</p> <p>For example my URL looks like:</p> <pre><code>http://www.example.com/my-example-article-url-is-like.php#articlebottom </code></pre> <p>the above URL is from a newsletter and it should go to the bottom paragraph in article page which I gave id like this:</p> <pre><code>&lt;p id="articlebottom"&gt;paragraph is here&lt;/p&gt; </code></pre> <p>When I click the above URL from Newsletter it goes to the article page, but not the bottom para where I specify id. Although I can see that the #articlebottom part is missing from URL when it came into the targeted page in Safari.</p> <p>Any thoughts would be appreciated!</p>
22,643,441
5
3
null
2014-03-25 18:16:08.013 UTC
1
2020-08-22 21:41:44.14 UTC
2015-05-19 16:02:51.037 UTC
null
1,486,275
null
852,602
null
1
8
html|css|iphone|mobile-safari|anchor
44,545
<p>Opera, IE, Chrome and Firefox will carry over the anchor to the new page. However, Safari loses the anchor on the redirect.</p> <p>So what if you add <code>/</code> just before the <code>ID Tag</code>?</p> <p>Old URL Path: <code>http://www.example.com/my-example-article-url-is-like.php#articlebottom</code></p> <p>New URL Path: <code>http://www.example.com/my-example-article-url-is-like.php/#articlebottom</code></p> <p>Another solution is that you'd have to delete both "www." from the domain and add a forward slash before the <code>anchor tag</code> in the URL/pathname before Safari would respond properly. Firefox doesn't seem to care, and I haven't gotten to testing on IE yet.</p>
13,587,464
Excel find cells from range where search value is within the cell
<p>Once again I'm struggling to find my answer on Google, but I'm sure it must exist. Sorry if I come across as a novice: I am when it comes to Excel it seems!</p> <p>What I'd like to be able to do is tell it to search a range, then find cells within that range that contain text that is in my search function. I don't need any kind of result from it other than either TRUE or >1 (if it matches, obviously).</p> <p>In this instance I'm searching a RANGE that is comprised of years, one year in each cell, and trying to find cells in that range that contain a year from a list of years that are all in one cell.</p> <p>Basically I'm wanting to use a function similar to the Search function I think.</p> <pre><code>=SEARCH(text to find, find within text) </code></pre> <p>However, I'd like it to do the opposite and find cells that contain some of the text within the source cell:</p> <pre><code>=SEARCH(find within text, text to find) </code></pre> <p>Or, more specifically</p> <pre><code>=SEARCH("2001,2002,2003,2004,2005", "2003") </code></pre> <p>Is this possible without the use of a Macro? I'd prefer to avoid it if at all possible. All cells in question are formatted as Text.</p> <p>I have been experimenting with COUNTIF, but again it works in the reverse of what I need. </p> <p>Sorry if this question is unclear. Hope someone can help, thanks in advance.</p> <p>Joe </p>
13,587,684
1
1
null
2012-11-27 15:27:51.48 UTC
null
2012-11-27 15:37:42.727 UTC
null
null
null
null
1,266,648
null
1
6
excel
68,701
<p>I'm sure there is a better way, but if I'm understanding correctly, you could try <code>SUM</code> in combination with an array formula (enter with <code>Ctrl+Shift+Enter</code>):</p> <pre><code>=IF(SUM(IFERROR(FIND(A1:E1,G1),0))&gt;0, "FOUND", "NOT FOUND") </code></pre> <p>Here, <code>A1:E1</code> contained the individual years and <code>G1</code> contained the single cell of years. This runs <code>FIND</code> on each cell in the range, returning a position if it finds a match in the target cell and returning 0 if not (<code>IFERROR</code> is a 2007 function - if you don't have Excel 2007, we can rewrite). You then sum the results of the <code>FIND</code> function and if it is greater than 0, it means you found a match somewhere.</p> <p><img src="https://i.stack.imgur.com/9JB8z.png" alt="enter image description here"></p>
13,716,731
HTML5 audio not playing multiple times in Android 4.0.4 device Native Browser
<p>I am currently working on an <strong>HTML5</strong> project.</p> <p>There is an issue on <strong>playing same audio file multiple times</strong> in the same page in <strong>Android native browser</strong>. The issue is specifically noticed on <strong>Android ICS 4.0.4</strong> version. In this version the <strong>audio will be played once</strong>, but when <strong>initiated again audio will not be played</strong>. The same thing is <strong>working perfectly in Android ICS 4.0.3</strong> Version and on the newer <strong>4.1.1</strong> version.</p> <p>Tested Devices:<br /> <strong>Samsung Galaxy Tab (Android 4.0.4)</strong>: Playing first time only then it doesn't play<br /> <strong>HTC One (Android 4.0.4)</strong>: Playing first time only then it doesn't play<br /> <strong>Sony Tab (Android 4.0.3)</strong>: Perfectly fine, playing audio multiple times<br /> <strong>HTC Sensation (Android 4.0.3)</strong>: Perfectly fine, playing audio multiple times<br /> <strong>Samsung Nexus Phone (Android 4.1.1)</strong>: Perfectly fine, playing audio multiple times</p> <p>Based on some research on Internet it seems like an <strong>issue with Android version 4.0.4</strong></p> <p>Please help me to find some solution to make it work in all devices.</p> <p><a href="http://www.w3schools.com/html/tryit.asp?filename=tryhtml5_audio_all" rel="noreferrer">Please use this W3 Schools HTML5 audio link for try outs</a></p>
13,737,207
3
10
null
2012-12-05 05:14:11.377 UTC
14
2014-03-27 04:43:04.24 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
1,877,874
null
1
21
android|html|html5-audio|android-browser
4,874
<p>I got a working solution..</p> <p>The problem was in Android 4.0.4 browser when audio is played once(ended) then the <strong>seek time will not be reset</strong> to starting position, it will stay at the end itself. So by setting <strong>currentTime = 0</strong> after the audio <strong>ended</strong> will reset it to starting position and in this way we can play the same audio as many times as we want with out any page refresh.<br> Tested working perfectly in all devices.</p> <p><strong>HTML Code:</strong></p> <pre><code>&lt;audio id="movie_audio"&gt; &lt;source src="my_audio_location/movie_audio.mp3" type='audio/mpeg; codecs="mp3"' /&gt; &lt;source src="my_audio_location/movie_audio.ogg" type='audio/ogg; codecs="vorbis"' /&gt; &lt;/audio&gt; </code></pre> <p><strong>JavaScript Code:</strong></p> <pre><code>var movie_audio = document.getElementById('movie_audio'); movie_audio.addEventListener('ended', function(){ movie_audio.currentTime = 0; } </code></pre>
13,542,855
Algorithm to find the minimum-area-rectangle for given points in order to compute the major and minor axis length
<p>I have a set of points (black dots in geographic coordinate value) derived from the convex hull (blue) of a polygon (red). see Figure:<img src="https://i.stack.imgur.com/YYiH9.png" alt="enter image description here"></p> <pre><code>[(560023.44957588764,6362057.3904932579), (560023.44957588764,6362060.3904932579), (560024.44957588764,6362063.3904932579), (560026.94957588764,6362068.3904932579), (560028.44957588764,6362069.8904932579), (560034.94957588764,6362071.8904932579), (560036.44957588764,6362071.8904932579), (560037.44957588764,6362070.3904932579), (560037.44957588764,6362064.8904932579), (560036.44957588764,6362063.3904932579), (560034.94957588764,6362061.3904932579), (560026.94957588764,6362057.8904932579), (560025.44957588764,6362057.3904932579), (560023.44957588764,6362057.3904932579)] </code></pre> <p>I need to calculate the the major and minor axis length following these steps (form this <a href="https://gis.stackexchange.com/questions/22895/how-to-find-the-minimum-area-rectangle-for-given-points">post</a> write in R-project and in <a href="http://opencarto.svn.sourceforge.net/viewvc/opencarto/trunk/server/src/main/java/org/opencarto/server/algo/SmallestSurroundingRectangle.java?revision=924&amp;view=markup" rel="noreferrer">Java</a>) or following the <a href="http://cgm.cs.mcgill.ca/~orm/maer.html" rel="noreferrer">this example procedure</a> </p> <p><img src="https://i.stack.imgur.com/XiPFa.png" alt="enter image description here"></p> <ol> <li>Compute the convex hull of the cloud.</li> <li>For each edge of the convex hull: 2a. compute the edge orientation, 2b. rotate the convex hull using this orientation in order to compute easily the bounding rectangle area with min/max of x/y of the rotated convex hull, 2c. Store the orientation corresponding to the minimum area found,</li> <li>Return the rectangle corresponding to the minimum area found.</li> </ol> <p>After that we know the The <strong>angle Theta</strong> (represented the orientation of the bounding rectangle relative to the y-axis of the image). The minimum and maximum of <strong>a</strong> and <strong>b</strong> over all boundary points are found:</p> <ul> <li>a(xi,yi) = xi*cos Theta + yi sin Theta </li> <li>b(xi,yi) = xi*sin Theta + yi cos Theta</li> </ul> <p>The values (a_max - a_min) and (b_max - b_min) defined the length and width, respectively, of the bounding rectangle for a direction Theta.</p> <p><img src="https://i.stack.imgur.com/AzsJz.png" alt="enter image description here"></p>
13,545,089
6
10
null
2012-11-24 15:59:37.123 UTC
21
2020-02-01 00:03:17.39 UTC
2019-07-17 14:18:28.89 UTC
null
7,851,470
null
1,493,192
null
1
26
python|geometry
31,260
<p>Given a clockwise-ordered list of n points in the convex hull of a set of points, it is an O(n) operation to find the minimum-area enclosing rectangle. (For convex-hull finding, in O(n log n) time, see <a href="http://code.activestate.com/recipes/66527-finding-the-convex-hull-of-a-set-of-2d-points/" rel="noreferrer">activestate.com recipe 66527</a> or see the quite compact <a href="http://tixxit.net/2010/03/graham-scan/" rel="noreferrer">Graham scan code at tixxit.net</a>.)</p> <p>The following python program uses techniques similar to those of the usual O(n) algorithm for computing maximum diameter of a convex polygon. That is, it maintains three indexes (iL, iP, iR) to the leftmost, opposite, and rightmost points relative to a given baseline. Each index advances through at most n points. Sample output from the program is shown next (with an added header):</p> <pre><code> i iL iP iR Area 0 6 8 0 203.000 1 6 8 0 211.875 2 6 8 0 205.800 3 6 10 0 206.250 4 7 12 0 190.362 5 8 0 1 203.000 6 10 0 4 201.385 7 0 1 6 203.000 8 0 3 6 205.827 9 0 3 6 205.640 10 0 4 7 187.451 11 0 4 7 189.750 12 1 6 8 203.000 </code></pre> <p>For example, the i=10 entry indicates that relative to the baseline from point 10 to 11, point 0 is leftmost, point 4 is opposite, and point 7 is rightmost, yielding an area of 187.451 units.</p> <p>Note that the code uses <code>mostfar()</code> to advance each index. The <code>mx, my</code> parameters to <code>mostfar()</code> tell it what extreme to test for; as an example, with <code>mx,my = -1,0</code>, <code>mostfar()</code> will try to maximize -rx (where rx is the rotated x of a point), thus finding the leftmost point. Note that an epsilon allowance probably should be used when <code>if mx*rx + my*ry &gt;= best</code> is done in inexact arithmetic: when a hull has numerous points, rounding error may be a problem and cause the method to incorrectly not advance an index.</p> <p>Code is shown below. The hull data is taken from the question above, with irrelevant large offsets and identical decimal places elided.</p> <pre><code>#!/usr/bin/python import math hull = [(23.45, 57.39), (23.45, 60.39), (24.45, 63.39), (26.95, 68.39), (28.45, 69.89), (34.95, 71.89), (36.45, 71.89), (37.45, 70.39), (37.45, 64.89), (36.45, 63.39), (34.95, 61.39), (26.95, 57.89), (25.45, 57.39), (23.45, 57.39)] def mostfar(j, n, s, c, mx, my): # advance j to extreme point xn, yn = hull[j][0], hull[j][1] rx, ry = xn*c - yn*s, xn*s + yn*c best = mx*rx + my*ry while True: x, y = rx, ry xn, yn = hull[(j+1)%n][0], hull[(j+1)%n][1] rx, ry = xn*c - yn*s, xn*s + yn*c if mx*rx + my*ry &gt;= best: j = (j+1)%n best = mx*rx + my*ry else: return (x, y, j) n = len(hull) iL = iR = iP = 1 # indexes left, right, opposite pi = 4*math.atan(1) for i in range(n-1): dx = hull[i+1][0] - hull[i][0] dy = hull[i+1][1] - hull[i][1] theta = pi-math.atan2(dy, dx) s, c = math.sin(theta), math.cos(theta) yC = hull[i][0]*s + hull[i][1]*c xP, yP, iP = mostfar(iP, n, s, c, 0, 1) if i==0: iR = iP xR, yR, iR = mostfar(iR, n, s, c, 1, 0) xL, yL, iL = mostfar(iL, n, s, c, -1, 0) area = (yP-yC)*(xR-xL) print ' {:2d} {:2d} {:2d} {:2d} {:9.3f}'.format(i, iL, iP, iR, area) </code></pre> <p><em>Note:</em> To get the length and width of the minimal-area enclosing rectangle, modify the above code as shown below. This will produce an output line like </p> <pre><code>Min rectangle: 187.451 18.037 10.393 10 0 4 7 </code></pre> <p>in which the second and third numbers indicate the length and width of the rectangle, and the four integers give index numbers of points that lie upon sides of it.</p> <pre><code># add after pi = ... line: minRect = (1e33, 0, 0, 0, 0, 0, 0) # area, dx, dy, i, iL, iP, iR # add after area = ... line: if area &lt; minRect[0]: minRect = (area, xR-xL, yP-yC, i, iL, iP, iR) # add after print ... line: print 'Min rectangle:', minRect # or instead of that print, add: print 'Min rectangle: ', for x in ['{:3d} '.format(x) if isinstance(x, int) else '{:7.3f} '.format(x) for x in minRect]: print x, print </code></pre>
13,227,697
How to restart service in android to call service oncreate again
<p>I have a service in my Android Application which runs always.Now i have a settings from my server through GCM and update these settings to my service. I put my settings in oncreate of service. So i need to restart my service to fetch latest settings. How to restart my service?</p>
13,228,222
7
0
null
2012-11-05 07:23:36.907 UTC
6
2021-02-04 13:42:29.043 UTC
null
null
null
null
884,079
null
1
36
android|android-service
43,106
<p>Call this two methods right after each other, which will causes the <code>Service</code> to stop and start. Don't know any method that "restarts" it. This is how I have implemented it in my application.</p> <pre><code>stopService(new Intent(this, YourService.class)); startService(new Intent(this, YourService.class)); </code></pre>
13,762,152
Load rake files and run tasks from other files
<p>Currently I'm trying split up my rake files to organize them better. For this, I've added a <code>rake</code> folder to my <code>assets</code> dir, that holds one rake file for each group of tasks.</p> <p>As I'm coming from PHP, I've only <em>very basic</em> knowledge of Ruby/Rake and can't get my namespaces default action running after loading the file. </p> <p>The commmented out <code>Rake :: Task ...</code>-string inside <code>app:init</code> throws an error at the CL at me:</p> <blockquote> <pre><code>rake aborted! uninitialized constant TASK </code></pre> </blockquote> <p>Here's the namespace/class (if this is the right word).</p> <pre><code>task :default =&gt; [ 'app:init' ] namespace :app do rake_dir = "#{Dir.pwd}/assets/rake/" rake_files = FileList.new( "#{rake_dir}*" ) desc "Loads rake modules (Default action)" task :init do puts "\t Importing rake files for processing" puts "\t loading..." rake_files.each() { |rake| puts "\t #{rake}" require rake # @link rubular.com name = rake.split( rake_dir ).last.gsub( /.rb\z/, '' ) puts "\t #{name}" #Rake :: Task[ "#{name}:default" ].invoke } end end </code></pre> <p>Thanks in advance.</p> <p><strong>Edit:</strong> At least, I can be sure the file gets loaded, as the plain <code>puts "file loaded"</code> at the beginning of those files gets echoed. The problem seems to <em>only</em> be that the <code>:default</code> action for the namespace in the loaded rake file isn't loading.</p>
28,362,084
3
0
null
2012-12-07 11:26:50.373 UTC
9
2016-01-04 10:15:36.517 UTC
2012-12-07 12:08:00.213 UTC
null
376,483
null
376,483
null
1
37
rake|rakefile
22,588
<p>You can either put your tasks into <code>rakelib/</code> folder which <code>rake</code> loads by default or add a specific folder in your <code>Rakefile</code> via:</p> <pre><code>Rake.add_rakelib 'lib/tasks' </code></pre>
13,352,677
Python equivalent for #ifdef DEBUG
<p>In C we write code like</p> <pre><code>#ifdef DEBUG printf("Some debug log... This could probably be achieved by python logging.Logger"); /* Do some sanity check code */ assert someCondition /* More complex sanitycheck */ while(list-&gt;next){ assert fooCheck(list) } #endif </code></pre> <p>Is there a way to do this in python?</p> <p>Edit: I got my answer, and more :) Paolo, Steven Rumbalski and J Sebastian gave me the information I was looking for. Thanks das for the detailed answer, although I'll probably not use a preprocessor right now.</p> <p>J Sebastian, whose comment got deleted because the answer in which he posted his comment, deleted his answer I think. He said I could use the isEnabledFor() method in Logger to feed a conditional.</p> <p>Thanks everyone for your inputs. This is my first question. I wish I could accept paolo, or j sebastian's answers. But since those were offered as comments, I'll accept das' answer.</p> <p>I will probably use either <a href="http://nestedinfiniteloops.wordpress.com/2012/01/15/if-debug-python-flavoured/" rel="noreferrer">http://nestedinfiniteloops.wordpress.com/2012/01/15/if-debug-python-flavoured/</a> or Logger.isEnabledFor()</p>
13,352,837
6
2
null
2012-11-12 22:33:08.16 UTC
16
2022-09-22 06:37:19.35 UTC
2012-11-12 23:04:32.09 UTC
null
1,804,124
null
1,804,124
null
1
56
python|debugging
43,719
<p>What you are looking for is a <strong>preprocessor</strong> for python. Generally you have three options:</p> <ol> <li>Write a <strong>selfmade script/program</strong> which replaces parts of your sourcecode based on certain templates before passing the result on to the interpreter (May be difficult)</li> <li>Use a special purpose python preprocessor like <a href="https://github.com/pinard/Pymacs/blob/master/pppp" rel="nofollow noreferrer">pppp - Poor's Python Pre-Processor</a></li> <li>Use a general purpose preprocessor like <a href="http://en.nothingisreal.com/wiki/GPP" rel="nofollow noreferrer">GPP</a></li> </ol> <p>I recommend trying pppp first ;)</p> <p>The main advantage of a preprocessor compared to setting a <code>DEBUG</code> flag and running code <code>if (DEBUG == True)</code> is that conditional checks also cost CPU cycles, so it is better to remove code that does not need to be run (if the python interpreter doesn't do that anyway), instead of skipping it.</p>
13,591,374
Command output redirect to file and terminal
<p>I am trying to throw command output to file plus console also. This is because i want to keep record of output in file. I am doing following and it appending to file but not printing <code>ls</code> output on terminal. </p> <pre><code>$ls 2&gt;&amp;1 &gt; /tmp/ls.txt </code></pre>
13,591,423
3
0
null
2012-11-27 19:13:50.58 UTC
29
2019-01-30 10:15:48.06 UTC
2019-01-30 10:15:48.06 UTC
null
608,639
null
1,159,538
null
1
88
linux|bash|redirect
129,766
<p>Yes, if you redirect the output, it won't appear on the console. Use <code>tee</code>.</p> <pre><code>ls 2&gt;&amp;1 | tee /tmp/ls.txt </code></pre>
13,547,007
fancybox2 / fancybox causes page to to jump to the top
<p>I have implemented fancybox2 on a dev site.</p> <p>When I engage the fancybox (click the link etc) the whole html shifts behind it - and goes to the top. I have it working fine in another demo, but when I drag the same code to this project it jumps to the top. Not only with the links to inline divs, but also for simple image gallery.</p> <p>Has anyone experienced this?</p>
15,306,863
11
2
null
2012-11-25 00:13:06.103 UTC
37
2021-10-29 05:23:42.243 UTC
2015-03-09 21:46:08.833 UTC
null
1,399,456
null
1,399,456
null
1
108
jquery|css|fancybox-2
83,458
<p>This can actually be done with a helper in Fancybox 2.</p> <pre><code>$('.image').fancybox({ helpers: { overlay: { locked: false } } }); </code></pre> <p><a href="http://davekiss.com/prevent-fancybox-from-jumping-to-the-top-of-the-page/" rel="noreferrer">http://davekiss.com/prevent-fancybox-from-jumping-to-the-top-of-the-page/</a></p>
20,825,531
How to access Chrome's online bookmarks?
<p>Google Chrome allows you to sign in with your Google account to sync bookmarks and settings. Those bookmarks are then stored along with my account on their servers.</p> <p>I want to create another client for the bookmarks. Please note that I am not interested in reading the local bookmarks file from hard disk. Instead I want to connect with the online servers directly.</p> <p>So I need to access the same API as Chrome uses for synching. Is there a way to find out how to use that API?</p>
32,365,488
1
3
null
2013-12-29 13:15:31.037 UTC
12
2015-10-06 15:43:04.53 UTC
null
null
null
null
1,079,110
null
1
20
api|google-chrome|sync|reverse-engineering|bookmarks
9,578
<p>Whilst not using an API directly it allows you to query data from google bookmarks online (directly via REST call), and parse it yourself.</p> <pre><code>http://www.google.com/bookmarks/?output=xml&amp;num=10000 </code></pre> <p>I have included a link on how you may parse this data from the "Lite Bookmarks" chrome extension repository. <a href="https://github.com/miscalencu/Google-Chrome-Google-Bookmarks/blob/master/js/core.js#L70" rel="noreferrer">http://www.google.com/bookmarks/?output=xml&amp;num=10000</a></p>
4,030,959
Will a "variableName;" C++ statement be a no-op at all times?
<p>In C++ sometimes a variable will be defined, but not used. Here's an example - a function for use with <a href="http://msdn.microsoft.com/en-us/library/5b6w5bwx(VS.80).aspx" rel="noreferrer"><code>COM_INTERFACE_ENTRY_FUNC_BLIND</code></a> ATL macro:</p> <pre><code>HRESULT WINAPI blindQuery( void* /*currentObject*/, REFIID iid, void** ppv, DWORD_PTR /*param*/ ) { DEBUG_LOG( __FUNCTION__ ); //DEBUG_LOG macro expands to an empty string in non-debug DEBUG_LOG( iid ); iid; // &lt;&lt;&lt;&lt;&lt;&lt;&lt;----silence compiler warning if( ppv == 0 ) { return E_POINTER; } *ppv = 0; return E_NOINTERFACE; } </code></pre> <p>In the above example <code>iid</code> parameter is used with <code>DEBUG_LOG</code> macro that expands into an empty string in non-debug configurations. So commenting out or removing the <code>iid</code> variable name in the signature is not an option. When non-debug configurations are being compiled the compiler spawns a <code>C4100: 'iid' : unreferenced formal parameter</code> warning, so in order to silence the warning the <code>iid;</code> statement that is believed to be a no-op is added.</p> <p>The question is the following: if we have any of the following declarations:</p> <pre><code> CSomeType variableName; //or CSomeType&amp; variableName; //or CSomeType* variableName; </code></pre> <p>will the following statement in C++ code:</p> <pre><code>variableName; </code></pre> <p>be a no-op at all times independent of what <code>CSomeType</code> is?</p>
4,030,983
2
7
null
2010-10-27 07:45:41.21 UTC
13
2011-02-04 02:16:44.027 UTC
2010-10-27 07:50:52.833 UTC
null
57,428
null
57,428
null
1
21
c++|compiler-warnings
3,506
<p>Yes, but you'll likely get another warning.</p> <p>The standard way of doing this is: <code>(void)iid;</code>.</p> <hr> <p>Very technically, this could still load <code>iid</code> into a register and do nothing. Granted that's extremely stupid on the compilers part (I doubt any would ever do that, if it does delete the compiler), but it's a more serious issue if the expression to be ignored is something concerning observable behavior, like calls to IO functions or the reading and writing of <code>volatile</code> variables.</p> <p>This brings up an interesting question: Can we take an expression and <em>completely</em> ignore it?</p> <p>That is, what we have now is this:</p> <pre><code>#define USE(x) (void)(x) // use iid in an expression to get rid of warning, but have no observable effect USE(iid); // hm, result of expression is gone but expression is still evaluated USE(std::cout &lt;&lt; "hmmm" &lt;&lt; std::endl); </code></pre> <p>This is close to a solution: <strike></p> <pre><code>// sizeof doesn't evaluate the expression #define USE(x) (void)(sizeof(x)) </code></pre> <p>But fails with:</p> <pre><code>void foo(); // oops, cannot take sizeof void USE(foo()); </code></pre> <p>The solution is to simply:</p> <pre><code>// use expression as sub-expression, // then make type of full expression int, discard result #define USE(x) (void)(sizeof((x), 0)) </code></pre> <p>Which guarantees no operation. </strike></p> <p><strong>Edit:</strong> The above indeed guaranteed no effect, but I posted without testing. Upon testing, it generates a warning again, at least in MSVC 2010, because the <em>value</em> isn't used. That's no good, time for more tricks!</p> <hr> <p>Reminder: We want to "use" an expression without evaluating it. How can this be done? Like this:</p> <pre><code>#define USE(x) ((void)(true ? 0 : (x))) </code></pre> <p>This has a simple problem like last time (worse actually), in that <code>(x)</code> needs to be be convertible to <code>int</code>. This is, again, trivial to fix:</p> <pre><code>#define USE(x) ((void)(true ? 0 : ((x), 0))) </code></pre> <p>And we're back to same kind of effect we had last time (none), but this time <code>x</code> is "used" so we don't get any warnings. Done, right?</p> <p>There is actually still one problem with this solution (and was present in the last un-solution as well, but went unnoticed), and it comes up in this example:</p> <pre><code>struct foo {}; void operator,(const foo&amp;, int) {} foo f; USE(f); // oops, void isn't convertible to int! </code></pre> <p>That is, if the type of the expression <code>(x)</code> overloads the comma operator to something not convertible to <code>int</code>, the solution fails. Sure, unlikely, but for the sake of going completely overboard, we can fix it with:</p> <pre><code>#define USE(x) ((void)(true ? 0 : ((x), void(), 0))) </code></pre> <p>To make sure we really end up with zero. <a href="https://stackoverflow.com/questions/75538/hidden-features-of-c/2176258#2176258">This trick brought to you by Johannes</a>.</p> <hr> <p>Also as noted, if the above wasn't enough, a stupid enough compiler could potentially "load" the expression <code>0</code> (into a register or something), then disregard it.</p> <p>I think it's impossible to be rid of that, since we ultimately need an expression to result in a type of some sort to ignore, but if I ever think of it I'll add it.</p>
9,083,096
Drawing an Image to a JPanel within a JFrame
<p>I am designing a program that contains two JPanels within a JFrame, one is for holding an image, the other for holding GUI components(Searchfields etc). I am wondering how do I draw the Image to the first JPanel within the JFrame?</p> <p>Here is a sample code from my constructor : </p> <pre><code>public UITester() { this.setTitle("Airplane"); Container container = getContentPane(); container.setLayout(new FlowLayout()); searchText = new JLabel("Enter Search Text Here"); container.add(searchText); imagepanel = new JPanel(new FlowLayout()); imagepanel.paintComponents(null); //other constructor code </code></pre> <p>}</p> <pre><code>public void paintComponent(Graphics g){ super.paintComponents(g); g.drawImage(img[0], -50, 100, null); } </code></pre> <p>I was trying to override the paintComponent method of JPanel to paint the image, but this causes a problem in my constructor when I try to write : </p> <pre><code>imagepanel.paintComponents(null); </code></pre> <p>As it will only allow me to pass the method null, and not Graphics g, anybody know of a fix to this method or another method i can use to draw the image in the JPanel? Help is appreciated! :) </p> <p>All the best and thanks in advance! Matt</p>
9,083,287
3
2
null
2012-01-31 16:26:04.11 UTC
6
2012-01-31 17:13:51.877 UTC
null
null
null
null
1,180,782
null
1
10
java|image|swing|jframe|jpanel
68,219
<p>I'd like to suggest a more simple way, </p> <pre><code> image = ImageIO.read(new File(path)); JLabel picLabel = new JLabel(new ImageIcon(image)); </code></pre> <p>Yayy! Now your image is a swing component ! add it to a frame or panel or anything like you usually do! Probably need a repainting too , like</p> <pre><code> jpanel.add(picLabel); jpanel.repaint(); </code></pre>
16,306,416
Sort PHP multi-dimensional array based on value in inner array?
<p>I'm trying to sort my PHP hashtable based on a specific value in the inner array. The data structure looks like this:</p> <pre><code>print_r($mydata); Array( [0] =&gt; Array ( [type] =&gt; suite [name] =&gt; A-Name ) [1] =&gt; Array ( [type] =&gt; suite [name] =&gt; C-Name ) [2] =&gt; Array ( [type] =&gt; suite [name] =&gt; B-Name ) ) </code></pre> <p>I've tried <strong>ksort</strong>, <strong>sort</strong>, <strong>usort</strong> but nothing seems to work. I'm trying to sort based on the <strong>name key</strong> two-levels down.</p> <p>This was my attempt using usort:</p> <pre><code>function cmp($a, $b) { return $b['name'] - $a['name']; } usort($mydata, "cmp"); </code></pre> <p>Is there an easy way to do this or do I need to write a custom sort function?</p>
16,306,693
6
3
null
2013-04-30 18:15:59.217 UTC
8
2019-11-08 06:52:10.483 UTC
2019-11-08 06:52:10.483 UTC
null
4,901,390
null
1,216,398
null
1
26
php|sorting
59,569
<p>Thinking,more useful and practical <a href="http://php.net/manual/en/function.sort.php">http://php.net/manual/en/function.sort.php</a></p> <pre><code>function array_sort($array, $on, $order=SORT_ASC){ $new_array = array(); $sortable_array = array(); if (count($array) &gt; 0) { foreach ($array as $k =&gt; $v) { if (is_array($v)) { foreach ($v as $k2 =&gt; $v2) { if ($k2 == $on) { $sortable_array[$k] = $v2; } } } else { $sortable_array[$k] = $v; } } switch ($order) { case SORT_ASC: asort($sortable_array); break; case SORT_DESC: arsort($sortable_array); break; } foreach ($sortable_array as $k =&gt; $v) { $new_array[$k] = $array[$k]; } } return $new_array; } </code></pre> <p>How to use</p> <pre><code> $list = array( array( 'type' =&gt; 'suite', 'name'=&gt;'A-Name'), array( 'type' =&gt; 'suite', 'name'=&gt;'C-Name'), array( 'type' =&gt; 'suite', 'name'=&gt;'B-Name') ); $list = array_sort($list, 'name', SORT_ASC); array(3) { [0]=&gt; array(2) { ["type"]=&gt; string(5) "suite" ["name"]=&gt; string(6) "A-Name" } [2]=&gt; array(2) { ["type"]=&gt; string(5) "suite" ["name"]=&gt; string(6) "B-Name" } [1]=&gt; array(2) { ["type"]=&gt; string(5) "suite" ["name"]=&gt; string(6) "C-Name" } } </code></pre>
57,944,894
How to format Vuetify data table date column?
<p>I have a simple data table using <em>Vuetify</em> data table. One of the column is a <code>createdOn</code> (date time), I want to format it. How can I do it ?</p> <p>This is what i get now:</p> <p><img src="https://i.stack.imgur.com/1rexA.png" alt="This is what i get now"></p> <pre><code>&lt;template&gt; &lt;v-layout&gt; &lt;v-data-table :headers="headers" :items="logs"&gt; &lt;/v-data-table&gt; &lt;v-layout&gt; &lt;/template&gt; &lt;script&gt; headers: [ { text: "Time", value: "createdOn", dataType: "Date" }, { text: "Event Source", value: "eventSourceName" }, { text: "Event Details", value: "eventDetails" }, { text: "User", value: "user" } ], items: [], &lt;/script&gt; </code></pre>
57,945,017
5
2
null
2019-09-15 14:09:43.087 UTC
6
2022-01-16 07:45:31.043 UTC
2022-01-16 07:45:31.043 UTC
null
8,172,857
null
10,955,632
null
1
39
javascript|html|vue.js|nuxt.js|vuetify.js
38,527
<p>You should use a <a href="https://vuetifyjs.com/en/components/data-tables#customizing-default-rows" rel="noreferrer"><code>custom row cell</code></a> :</p> <pre class="lang-html prettyprint-override"><code>&lt;v-data-table :headers=&quot;headers&quot; :items=&quot;logs&quot;&gt; &lt;template v-slot:item.createdOn=&quot;{ item }&quot;&gt; &lt;span&gt;{{ new Date(item.createdOn).toLocaleString() }}&lt;/span&gt; &lt;/template&gt; &lt;/v-data-table&gt; </code></pre>
17,543,389
Android image map. - displaying an .svg and using it as an image map (touch zones)
<p>I am looking for a way to display an image and have the user tap on different parts of the image to navigate and perform actions.</p> <p>I was considering using an <a href="http://blahti.wordpress.com/2012/06/26/images-with-clickable-areas/" rel="noreferrer">invisible color map</a> to check which parts have been touched.</p> <p>But since i also want to highlight the selected areas, i was thinking of using vectors. There is a nice library to render svg files into an image view <a href="https://code.google.com/p/svg-android/" rel="noreferrer">here</a>, but it doesn't handle touches.<br> Is there a library out there that does? Or any smarter way of doing this?</p> <p>(I also checked out <a href="https://github.com/catchthecows/AndroidImageMap" rel="noreferrer">this project</a> but it won't swallow .svg files and my vector image is far too complex to insert all the data by hand)</p>
17,685,065
3
2
null
2013-07-09 08:23:52.893 UTC
9
2018-04-28 22:35:51.03 UTC
2013-07-17 12:37:10.077 UTC
null
1,393,894
null
723,421
null
1
19
android|graphics|vector|svg|imagemap
10,295
<p>Interesting problem! I'm not convinced you can't use a combination of the libraries you mentioned.</p> <p>What I would do is first use SVG-Android to programmatically read in your SVG file. Looking at SVG-Android, it looks like it returns the final product as a <code>PictureDrawable</code>, which is a subclass of Drawable. </p> <p>Right after SVG-Android finishes processing the SVG graphics, I'd use <a href="http://developer.android.com/reference/android/widget/ImageView.html#setImageDrawable%28android.graphics.drawable.Drawable%29">ImageView.setImageDrawable</a> to load the main <code>ImageView</code> with the <code>PictureDrawable</code> we just generated. Then I'd just use that <code>ImageView</code> as the base for the implementation of <a href="http://blahti.wordpress.com/2012/06/26/images-with-clickable-areas/">"Images with Clickable Areas"</a> you linked in the original question.</p> <p>Honestly, I think the hardest part will be getting SVG-Android to work correctly (I've played with it a bit, and it's a bit finicky). However, I don't think you'll have much difficulty combining the SVG-generated drawable with the clickable areas. It's a simple change in the source of the base image.</p> <p>Good luck!</p>
17,544,819
How to know if a dialog is dismissed in Android?
<p>If the dialog is dismissed,I want to do something for my background.So I want to know if the dialog is dismissed</p>
17,544,849
4
1
null
2013-07-09 09:33:01.307 UTC
5
2020-06-16 20:01:29.427 UTC
null
null
null
null
2,095,649
null
1
33
android|dialog|dismiss
25,879
<p>You can use an <code>onDismissListener</code></p> <p><a href="http://developer.android.com/reference/android/content/DialogInterface.OnDismissListener.html">http://developer.android.com/reference/android/content/DialogInterface.OnDismissListener.html</a></p> <pre><code>public Dialog createDialog() { Dialog d = new Dialog(this); d.setOnDismissListener(new OnDismissListener() { @Override public void onDismiss(final DialogInterface arg0) { // do something } }); return d; } </code></pre> <p>If you are using a <code>DialogFragment</code> just override <code>onDismiss()</code></p> <p><a href="http://developer.android.com/reference/android/app/DialogFragment.html#onDismiss%28android.content.DialogInterface%29">http://developer.android.com/reference/android/app/DialogFragment.html#onDismiss(android.content.DialogInterface)</a></p>
18,237,987
Show that Shiny is busy (or loading) when changing tab panels
<p>(Code follows after problem description)</p> <p>I am working on making a web app with Shiny, and some of the R commands that I am executing take minutes to complete. I found that I need to provide the user with some indication that Shiny is working, or they will continuously change the parameters I provide in the side panel, which just causes Shiny to reactively restart the calculations once the initial run is completed.</p> <p>So, I created a conditional panel that shows a "Loading" message (referred to as a modal) with the following (thanks to Joe Cheng on the Shiny Google group for the conditional statement):</p> <pre><code># generateButton is the name of my action button loadPanel &lt;- conditionalPanel("input.generateButton &gt; 0 &amp;&amp; $('html').hasClass('shiny-busy')"), loadingMsg) </code></pre> <p>This is working as intended if the user remains on the current tab. However, the user can switch to another tab (that may contain some calculations that need to be run for some time), but the loading panel appears and disappears immediately, all while R chugs away at the calculations, and then refreshing the content only after it is done.</p> <p>Since this may be hard to visualize, I provided some code to run below. You will notice that clicking the button to start the calculations will produce a nice loading message. However, when you switch to tab 2, R starts running some calculations, but fails to show the loading message (maybe Shiny does not register as being busy?). If you restart the calculations by pressing the button again, the loading screen will show up correctly. </p> <p>I want the loading message to appear when switching to a tab that is loading!</p> <p><strong>ui.R</strong></p> <pre><code>library(shiny) # Code to make a message that shiny is loading # Make the loading bar loadingBar &lt;- tags$div(class="progress progress-striped active", tags$div(class="bar", style="width: 100%;")) # Code for loading message loadingMsg &lt;- tags$div(class="modal", tabindex="-1", role="dialog", "aria-labelledby"="myModalLabel", "aria-hidden"="true", tags$div(class="modal-header", tags$h3(id="myModalHeader", "Loading...")), tags$div(class="modal-footer", loadingBar)) # The conditional panel to show when shiny is busy loadingPanel &lt;- conditionalPanel(paste("input.goButton &gt; 0 &amp;&amp;", "$('html').hasClass('shiny-busy')"), loadingMsg) # Now the UI code shinyUI(pageWithSidebar( headerPanel("Tabsets"), sidebarPanel( sliderInput(inputId="time", label="System sleep time (in seconds)", value=1, min=1, max=5), actionButton("goButton", "Let's go!") ), mainPanel( tabsetPanel( tabPanel(title="Tab 1", loadingPanel, textOutput("tabText1")), tabPanel(title="Tab 2", loadingPanel, textOutput("tabText2")) ) ) )) </code></pre> <p><strong>server.R</strong></p> <pre><code>library(shiny) # Define server logic for sleeping shinyServer(function(input, output) { sleep1 &lt;- reactive({ if(input$goButton==0) return(NULL) return(isolate({ Sys.sleep(input$time) input$time })) }) sleep2 &lt;- reactive({ if(input$goButton==0) return(NULL) return(isolate({ Sys.sleep(input$time*2) input$time*2 })) }) output$tabText1 &lt;- renderText({ if(input$goButton==0) return(NULL) return({ print(paste("Slept for", sleep1(), "seconds.")) }) }) output$tabText2 &lt;- renderText({ if(input$goButton==0) return(NULL) return({ print(paste("Multiplied by 2, that is", sleep2(), "seconds.")) }) }) }) </code></pre>
18,624,844
3
0
null
2013-08-14 17:07:29.85 UTC
18
2016-11-03 07:22:34.287 UTC
2013-08-15 16:07:24.423 UTC
null
1,773,432
null
1,773,432
null
1
40
r|shiny
20,334
<p>Via the <a href="https://groups.google.com/d/msg/shiny-discuss/ZfPCt0QqUuA/KS6yBD6vMv4J">Shiny Google group</a>, Joe Cheng pointed me to the <a href="https://github.com/rstudio/shiny-incubator"><code>shinyIncubator</code></a> package, where there is a progress bar function that is being implemented (see <code>?withProgress</code> after installing the <code>shinyIncubator</code> package). </p> <p>Maybe this function will be added to the Shiny package in the future, but this works for now.</p> <p>Example:</p> <p><strong>UI.R</strong></p> <pre><code>library(shiny) library(shinyIncubator) shinyUI(pageWithSidebar( headerPanel("Testing"), sidebarPanel( # Action button actionButton("aButton", "Let's go!") ), mainPanel( progressInit(), tabsetPanel( tabPanel(title="Tab1", plotOutput("plot1")), tabPanel(title="Tab2", plotOutput("plot2"))) ) )) </code></pre> <p><strong>SERVER.R</strong></p> <pre><code>library(shiny) library(shinyIncubator) shinyServer(function(input, output, session) { output$plot1 &lt;- renderPlot({ if(input$aButton==0) return(NULL) withProgress(session, min=1, max=15, expr={ for(i in 1:15) { setProgress(message = 'Calculation in progress', detail = 'This may take a while...', value=i) print(i) Sys.sleep(0.1) } }) temp &lt;- cars + matrix(rnorm(prod(dim(cars))), nrow=nrow(cars), ncol=ncol(cars)) plot(temp) }) output$plot2 &lt;- renderPlot({ if(input$aButton==0) return(NULL) withProgress(session, min=1, max=15, expr={ for(i in 1:15) { setProgress(message = 'Calculation in progress', detail = 'This may take a while...', value=i) print(i) Sys.sleep(0.1) } }) temp &lt;- cars + matrix(rnorm(prod(dim(cars))), nrow=nrow(cars), ncol=ncol(cars)) plot(temp) }) }) </code></pre>
18,584,439
how does form_for know the difference when submitting :new :edit
<p>I've generated a scaffold, let's call it scaffold test. Within that scaffold, I've got a _form.html.erb thats being render for action's :new => :create and :edit => :update</p> <p>Rails does a lot of magic sometimes and I cannot figure out how the form_for knows how to call the proper :action when pressing submit between :new and :edit</p> <p>Scaffolded Form</p> <pre><code>&lt;%= form_for(@test) do |f| %&gt; &lt;div class="actions"&gt; &lt;%= f.submit %&gt; &lt;/div&gt; &lt;% end %&gt; </code></pre> <p>vs. Un-scaffolded Form</p> <pre><code> &lt;% form_for @test :url =&gt; {:action =&gt; "new"}, :method =&gt; "post" do |f| %&gt; &lt;%= f.submit %&gt; &lt;% end %&gt; </code></pre> <h1>Edit template</h1> <pre><code>&lt;h1&gt;Editing test&lt;/h1&gt; &lt;%= render 'form' %&gt; </code></pre> <h1>New template</h1> <pre><code>&lt;h1&gt;New test&lt;/h1&gt; &lt;%= render 'form' %&gt; </code></pre> <p>As you can see theres no difference between the forms How can both templates render the same form but use different actions?</p>
18,584,468
3
0
null
2013-09-03 05:05:23.327 UTC
8
2013-09-03 05:28:34.98 UTC
2013-09-03 05:13:49.503 UTC
null
1,191,635
null
1,191,635
null
1
32
ruby-on-rails|forms|model-view-controller
16,112
<p>It checks <a href="http://api.rubyonrails.org/classes/ActiveRecord/Persistence.html#method-i-persisted-3F"><code>@test.persisted?</code></a> If it is persisted then it is an edit form. If it isn't, it is a new form.</p>
4,967,418
Using shared preferences editor
<p>I'm slowly working through an Android learning book and was given the following code to assign user data:</p> <pre><code>package com.androidbook.triviaquiz; import android.app.Activity; import android.content.SharedPreferences; public class QuizActivity extends Activity { public static final String GAME_PREFERENCES = "GamePrefs"; SharedPreferences settings = getSharedPreferences(GAME_PREFERENCES, MODE_PRIVATE); SharedPreferences.Editor prefEditor = settings.edit(); prefeditor.putString("UserName", "John Doe"); //**syntax error on tokens** prefEditor.putInt("UserAge", 22); //**syntax error on tokens** prefEditor.commit(); } </code></pre> <p>However, I get an error (lines indicated with comments) that underlines the period and says "misplaced construct" and also that underlines the arguments saying "delete these tokens". I have seen this done in other applications in the same format, I don't understand what is wrong.</p>
4,967,446
3
0
null
2011-02-11 09:29:27.633 UTC
3
2018-02-23 19:06:25.213 UTC
2011-02-11 09:31:28.787 UTC
null
299,924
null
612,812
null
1
22
android|sharedpreferences
51,273
<p>Edit: Of course! Those statements cannot be put directly into the class at that level and must be inside a method, something like this:</p> <pre><code>public class QuizActivity extends Activity { public static final String GAME_PREFERENCES = "GamePrefs"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); SharedPreferences settings = getSharedPreferences(GAME_PREFERENCES, MODE_PRIVATE); SharedPreferences.Editor prefEditor = settings.edit(); prefEditor.putString("UserName", "John Doe"); prefEditor.putInt("UserAge", 22); prefEditor.putString("Gender", "Male"); prefEditor.commit(); } } </code></pre>
5,331,270
Why doesn't Xcode 4 create any products?
<p>Regardless of build configuration, building my iPad app does not actually output a .app file. It does run in the iPad simulator and on a device, but when I hit build or build and run, the binary appears under Products in red and is not created in the "build" folder as designated in build settings.</p> <p>Any ideas?</p>
5,331,427
3
1
null
2011-03-16 20:20:49.907 UTC
21
2015-01-22 16:26:50.117 UTC
2011-03-16 20:30:11.927 UTC
null
469,563
null
513,075
null
1
79
xcode|ios|xcode4
35,385
<p>Xcode 4 places its build products and other intermediaries/temporary files/indexes in a derived data directory now instead of a "build" directory that is mixed in with your product files. It does this to deal with the new workspaces and also so that you can have clean builds of different projects in different workspaces without contaminating each other.</p> <p>If your original template was old, your built product is probably relative to your source directory instead of relative to your built products directory, which is why it's showing up red. By default, your derived data directory will be under ~/Library/Developer/Xcode/DerivedData. To see where your current workspace/project is placing these files, you can <strong>File->Workspace Settings...</strong> and take a look at the <em>Build Location</em>.</p>
43,407,318
How to suppress the "Avoid using bundled version of Google Play services SDK" warning?
<p>I'm using the Google Play services in my Android app so I have the dependency in my <code>build.gradle</code>.</p> <pre><code>compile 'com.google.android.gms:play-services:10.2.1' </code></pre> <p>But Android Studio shows a warning for it: <code>Avoid using bundled version of Google Play services SDK</code>.</p> <p><a href="https://i.stack.imgur.com/aXdwq.png" rel="noreferrer"><img src="https://i.stack.imgur.com/aXdwq.png" alt="Android warning"></a></p> <p>What does this warning mean? How should I avoid it? I've googled a lot without finding much related info. </p>
43,407,421
2
4
null
2017-04-14 07:40:38.187 UTC
15
2020-08-09 12:46:58.863 UTC
2017-05-23 10:55:40.677 UTC
null
440,921
null
2,487,227
null
1
69
android|android-studio|google-play-services
29,133
<blockquote> <p><strong>In versions of Google Play services prior to 6.5</strong>, you had to compile the entire package of APIs into your app. In some cases, doing so made it more difficult to keep the number of methods in your app (including framework APIs, library methods, and your own code) under the 65,536 limit. <strong>From version 6.5</strong>, you can instead selectively compile Google Play service APIs into your app</p> </blockquote> <p>inside compile <code>com.google.android.gms:play-services:12.0.0</code> contains alot of dependencies.. see below.. using play-services may cause dex problem and heavy app. Select only which want do you really depends to :)</p> <pre><code>Google Play services API Description in build.gradle Google+ com.google.android.gms:play-services-plus:12.0.0 Google Account Login com.google.android.gms:play-services-auth:12.0.0 Google Actions, Base Client Library com.google.android.gms:play-services-base:12.0.0 Google Address API com.google.android.gms:play-services-identity:12.0.0 Google Analytics com.google.android.gms:play-services-analytics:12.0.0 Google Awareness com.google.android.gms:play-services-awareness:12.0.0 Google Cast com.google.android.gms:play-services-cast:12.0.0 Google Cloud Messaging com.google.android.gms:play-services-gcm:12.0.0 Google Drive com.google.android.gms:play-services-drive:12.0.0 Google Fit com.google.android.gms:play-services-fitness:12.0.0 Google Location and Activity Recognition com.google.android.gms:play-services-location:12.0.0 Google Maps com.google.android.gms:play-services-maps:12.0.0 Google Mobile Ads com.google.android.gms:play-services-ads:12.0.0 Google Places com.google.android.gms:play-services-places:12.0.0 Mobile Vision com.google.android.gms:play-services-vision:12.0.0 Google Nearby com.google.android.gms:play-services-nearby:12.0.0 Google Panorama Viewer com.google.android.gms:play-services-panorama:12.0.0 Google Play Game com.google.android.gms:play-services-games:12.0.0 SafetyNet com.google.android.gms:play-services-safetynet:12.0.0 Android Pay com.google.android.gms:play-services-wallet:12.0.0 Android Wear com.google.android.gms:play-services-wearable:12.0.0 </code></pre> <p>Firebase</p> <pre><code>Firebase API Description in build.gradle Analytics com.google.firebase:firebase-core:12.0.0 Realtime Database com.google.firebase:firebase-database:12.0.0 Cloud Firestore com.google.firebase:firebase-firestore:12.0.0 Storage com.google.firebase:firebase-storage:12.0.0 Crash Reporting com.google.firebase:firebase-crash:12.0.0 Authentication com.google.firebase:firebase-auth:12.0.0 Cloud Messaging com.google.firebase:firebase-messaging:12.0.0 Remote Config com.google.firebase:firebase-config:12.0.0 Invites and Dynamic Links com.google.firebase:firebase-invites:12.0.0 AdMob com.google.firebase:firebase-ads:12.0.0 App Indexing com.google.firebase:firebase-appindexing:12.0.0 Performance Monitoring com.google.firebase:firebase-perf:12.0.0 </code></pre> <p><strong>EDIT</strong> <strong>Above version is already deprecated. They use individual versioning.</strong> Please refer Link Below<br><br> Google Play Service - <a href="https://developers.google.com/android/guides/setup" rel="noreferrer">https://developers.google.com/android/guides/setup</a><Br> Firebase - <a href="https://firebase.google.com/docs/android/setup" rel="noreferrer">https://firebase.google.com/docs/android/setup</a><br></p>
43,221,208
iterate over pandas dataframe using itertuples
<p>I am iterating over a pandas dataframe using itertuples. I also want to capture the row number while iterating:</p> <pre><code>for row in df.itertuples(): print row['name'] </code></pre> <p>Expected output :</p> <pre><code>1 larry 2 barry 3 michael </code></pre> <p>1, 2, 3 are row numbers. I want to avoid using a counter and getting the row number. Is there an easy way to achieve this using pandas?</p>
43,221,445
3
5
null
2017-04-05 03:20:51.373 UTC
8
2021-02-21 10:03:12.103 UTC
2019-03-11 09:57:44.443 UTC
null
2,345,870
null
7,257,168
null
1
48
python|pandas
88,382
<p>When using <code>itertuples</code> you get a named <code>tuple</code> for every row. By default, you can access the index value for that row with <code>row.Index</code>. </p> <p>If the index value isn't what you were looking for then you can use <code>enumerate</code></p> <pre><code>for i, row in enumerate(df.itertuples(), 1): print(i, row.name) </code></pre> <p><code>enumerate</code> takes the place of an ugly counter construct</p>
9,025,288
XmlWriter to write Element String with Attribute
<p>I am using XmlWriter and I am wondering if some one ever tried to write the xml element string (leaf node) with attributes so that the output would look like</p> <pre><code>&lt;book id='1' author='j.k.rowling' year='2010'&gt;999&lt;/book&gt; </code></pre> <p>instead of</p> <pre><code>&lt;book id='1' author='j.k.rowling' year='2010'&gt; &lt;book&gt;999&lt;/book&gt; &lt;/book&gt; </code></pre>
9,025,756
1
4
null
2012-01-26 21:01:49.233 UTC
4
2015-06-17 14:18:57.513 UTC
2012-01-27 15:03:53.683 UTC
null
1,171,865
null
1,171,865
null
1
23
xml
58,503
<p>You can use <a href="http://msdn.microsoft.com/en-us/library/system.xml.xmlwriter.writestring.aspx">WriteString</a>...</p> <pre><code>using (XmlWriter writer = XmlWriter.Create("books.xml")) { writer.WriteStartElement("book"); writer.WriteAttributeString("author", "j.k.rowling"); writer.WriteAttributeString("year", "1990"); writer.WriteString("99"); writer.WriteEndElement(); } </code></pre>
18,493,427
MouseOver and MouseOut In CSS
<p>For using mouse into one element we use the <code>:hover</code> CSS attribute. How about for mouse out of the element?</p> <p>I added a transition effect on the element to change the color. The hover effect works fine, but what CSS attribute should I use for mouse out to apply the effect? I'm looking for a CSS solution, not a JavaScript or JQuery solution.</p>
31,159,485
4
0
null
2013-08-28 16:27:48.273 UTC
16
2021-08-10 12:07:42.097 UTC
2013-08-28 16:39:52.583 UTC
null
1,615
null
539,693
null
1
21
css|html
99,757
<p>Here is the best solution, i think.</p> <p><strong>CSS onomouseout:</strong></p> <pre><code>div:not( :hover ){ ... } </code></pre> <p><strong>CSS onmouseover:</strong></p> <pre><code>div:hover{ ... } </code></pre> <p>It's better, because if you need to set some styles ONLY onmouseout and trying to do this in this way</p> <pre><code>div { ... } </code></pre> <p>you will set your styles and for onmouseover too.</p>
19,913,596
C++ 2D array to 1D array
<p>I am attempting to convert a 2D array to 1D. I'm extremely new to C/C++ but I think it's very important to learn how to convert a 2D array to 1D. So here I am stumbling upon this problem.</p> <p>My code so far is <a href="http://ideone.com/zvjKwP" rel="noreferrer">http://ideone.com/zvjKwP</a></p> <pre><code>#include&lt;iostream&gt; using namespace std; int main() { int n=0,m=0; // 2D array nRow, nCol int a[n][m]; int i,j; // цикъл въвеждане 2D int q,p,t; // for 2D=&gt;1D int b[100]; int r; // for cout cout&lt;&lt;"Enter the array's number of rows and columns: "; cin&gt;&gt;n&gt;&gt;m; // entering values for the 2D array for (i = 0;i&lt;=n;i++) { for (j = 0;j&lt;=m;j++) { cout&lt;&lt;"a["&lt;&lt;i&lt;&lt;"]["&lt;&lt;j&lt;&lt;"]="&lt;&lt;endl; cin&gt;&gt;a[i][j]; cin.ignore(); } } // Most likely the failzone IMO for (q = 0;q&lt;=i;q++) { for (t = 0;t&lt;=i*j+j;t++) { b[t] = a[i][j]; } } // attempting to print the 1D values cout&lt;&lt;"The values in the array are"&lt;&lt;"\n"; for(r=0;r&lt;=t;r++) { cout&lt;&lt;"b["&lt;&lt;r&lt;&lt;"] = "&lt;&lt;b[r]&lt;&lt;endl; } cin.get(); return 0; } </code></pre> <p>I wrote a comment at where I think I fail. </p> <p>I must also limit the numbers that get into the 1D to numbers who's value^2 is greater than 50. But for sure I must solve the problem with the conversion 2D=>1D Can you help me out?</p>
19,913,649
6
2
null
2013-11-11 18:48:58.34 UTC
4
2021-12-03 20:49:44.167 UTC
null
null
null
null
2,980,299
null
1
7
c++|arrays|multidimensional-array
47,049
<p>You are right with your supposition:</p> <p>The cycle should be like:</p> <pre><code>for (q = 0; q &lt; n; q++) { for (t = 0; t &lt; m; t++) { b[q * m + t] = a[q][t]; } } </code></pre> <p>It is always easier to consider such conversions from the view point of the higher dimension array. Furthermore with your code you did not actually modify <code>i</code> or <code>j</code> in the <code>b</code> assigning cycle, so you should not expect different values to be assigned to the different array members of <code>b</code>.</p>
15,383,666
Installing VTK for Python
<p>I'm trying to install VTK module for python, I am however unsuccesful in doing so. I have downloaded a VTK tar-file, but I'm unable to extract it. I'm capable of extracting other tar-files, so there must be something specific with this file I suppose.</p> <p>This is my error:</p> <p>gzip: stdin: invalid compressed data--format violated tar: Child returned status 1 tar: Error is not recoverable: exiting now</p> <p>I hope somebody can help me with this.</p>
15,394,873
5
2
null
2013-03-13 11:12:31.02 UTC
4
2022-06-17 08:31:40.327 UTC
null
null
null
null
1,658,072
null
1
18
python|tar|vtk
63,145
<p>The answer depends on the operating system you are using. This will be a lot easier if you can find a package or installer for your specific operating system and/or distribution. </p> <h3>Linux</h3> <p>If you are using Linux then look for the corresponding package in the distribution's package manager. For example, on Ubuntu Linux you should be able to install it using the following command:</p> <pre><code>sudo apt-get install python-vtk </code></pre> <h3>Microsoft Windows</h3> <p>If you are using Microsoft Windows, the easiest way would be to install <a href="https://code.google.com/p/pythonxy/" rel="noreferrer">Python(x,y)</a>. It comes with VTK support.</p> <p>Additionally, <a href="https://www.anaconda.com/" rel="noreferrer">Anaconda</a> also includes VTK package as well as support for virtual environments. It might be a good option for some folks. </p> <h3>Mac OS X</h3> <p>If you are using Mac OS X, try installing everything via <a href="http://www.macports.org/" rel="noreferrer">MacPorts</a>. </p> <hr> <p><s>As @Nil mentioned in comments below, a standalone python interface to VTK is now provided by VTK developers. You may download it for Windows, Darwin, and Linux from <a href="https://www.vtk.org/download/#latestcand" rel="noreferrer">here</a>.</s></p> <hr> <p>As mentioned by @Nil, VTK used to offer <code>vtkpython</code> binaries on their <a href="https://vtk.org/download/" rel="noreferrer">download</a> page. However, they've dropped this since VTK-8.x.x as mentioned <a href="https://blog.kitware.com/vtk-8-0-0/" rel="noreferrer">here</a>:</p> <blockquote> <p>Sorry, about that. We decided to drop the vtkpython binaries for 8. I want to focus our energies on supporting python wheel installs instead. There’s no timeline yet for a complete solution but we’ve made some good progress toward that recently here: <a href="https://github.com/jcfr/VTKPythonPackage" rel="noreferrer">https://github.com/jcfr/VTKPythonPackage</a>.</p> </blockquote> <p>Thus, the recommended way of installing <code>vtkpython</code> now is (see <a href="https://github.com/KitwareMedical/VTKPythonPackage" rel="noreferrer">this</a> page):</p> <pre><code>$ python -m pip install --upgrade pip $ python -m pip install vtk </code></pre>
15,130,311
HighCharts: Labels visible over tooltip
<p>Labels on my chart are showing over tooltip, which doesn't look very nice. I tried to play with <code>zIndex</code>, but to no result. How can I make tooltips not transparent? Here's my jsFiddle: <a href="http://www.jsfiddle.net/4scfH/3/" rel="noreferrer">http://www.jsfiddle.net/4scfH/3/</a></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$(function() { var chart; $(document).ready(function() { chart = new Highcharts.Chart({ chart: { renderTo: 'graf1', plotBackgroundColor: null, plotBorderWidth: null, plotShadow: false }, title: { margin: 40, text: 'Podíl všech potřeb' }, tooltip: { //pointFormat: '&lt;b&gt;{point.y} Kč [{point.percentage}%]&lt;/b&gt;', percentageDecimals: 2, backgroundColor: "rgba(255,255,255,1)", formatter: function() { return this.point.name + '&lt;br /&gt;' + '&lt;b&gt;' + Highcharts.numberFormat(this.y).replace(",", " ") + ' Kč [' + Highcharts.numberFormat(this.percentage, 2) + '%]&lt;/b&gt;'; } }, plotOptions: { pie: { allowPointSelect: true, cursor: 'pointer', dataLabels: { enabled: true, color: '#000000', connectorWidth: 2, useHTML: true, formatter: function() { return '&lt;span style="color:' + this.point.color + '"&gt;&lt;b&gt;' + this.point.name + '&lt;/b&gt;&lt;/span&gt;'; } } } }, series: [{ type: 'pie', name: 'Potřeba', data: [ ['Firefox', 45.0], ['IE', 26.8], { name: 'Chrome', y: 12.8, sliced: true, selected: true }, ['Safari', 8.5], ['Opera', 6.2], ['Others', 0.7] ] }] }); }); });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="http://code.highcharts.com/highcharts.js"&gt;&lt;/script&gt; &lt;div id="graf1" style="width: 400px; height: 250px; float:left"&gt;&lt;/div&gt;</code></pre> </div> </div> </p>
15,132,550
7
1
null
2013-02-28 07:57:44.3 UTC
9
2019-05-24 18:30:40.627 UTC
2016-05-22 18:57:20.293 UTC
null
6,083,675
null
1,573,630
null
1
18
javascript|jquery|highcharts|tooltip|label
35,503
<p>You can set <a href="http://api.highcharts.com/highcharts#series&lt;pie&gt;.dataLabels.useHTML" rel="nofollow noreferrer"><code>useHTML</code></a> and define your own tooltip via css: </p> <p><a href="http://jsfiddle.net/4scfH/4/" rel="nofollow noreferrer">http://jsfiddle.net/4scfH/4/</a></p> <pre class="lang-js prettyprint-override"><code>tooltip: { borderWidth: 0, backgroundColor: "rgba(255,255,255,0)", borderRadius: 0, shadow: false, useHTML: true, percentageDecimals: 2, formatter: function () { return '&lt;div class="tooltip"&gt;' + this.point.name + '&lt;br /&gt;' + '&lt;b&gt;' + Highcharts.numberFormat(this.y).replace(",", " ") + ' Kč [' + Highcharts.numberFormat(this.percentage, 2) + '%]&lt;/b&gt;&lt;/div&gt;'; } }, </code></pre> <p>CSS</p> <pre class="lang-css prettyprint-override"><code>.label { z-index: 1 !important; } .highcharts-tooltip span { background-color: white; border:1 px solid green; opacity: 1; z-index: 9999 !important; } .tooltip { padding: 5px; } </code></pre> <p>Explanation: when you set <code>useHTML</code> to true, it displays the tooltip text as HTML on the HTML layer, but still draws an SVG shape in the highcharts display SVG for the box and arrow. You would end up with data labels looking like they were drawn on top of the tooltip, but the tooltip text itself on top of the data labels. The config options above effectively hide the SVG tooltip shape and build and style the tooltip purely with HTML/CSS. The only down-side is that you lose the little "arrow" pointer.</p>
15,307,623
Can't compare naive and aware datetime.now() <= challenge.datetime_end
<p>I am trying to compare the current date and time with dates and times specified in models using comparison operators:</p> <pre><code>if challenge.datetime_start &lt;= datetime.now() &lt;= challenge.datetime_end: </code></pre> <p>The script errors out with: </p> <pre><code>TypeError: can't compare offset-naive and offset-aware datetimes </code></pre> <p>The models look like this:</p> <pre><code>class Fundraising_Challenge(models.Model): name = models.CharField(max_length=100) datetime_start = models.DateTimeField() datetime_end = models.DateTimeField() </code></pre> <p>I also have django using locale date and times.</p> <p>What I haven't been able to find is the format django uses for DateTimeField(). Is it naive or aware? And how do I get datetime.now() to recognize locale datetime?</p>
15,307,743
10
3
null
2013-03-09 05:38:56.167 UTC
32
2022-09-07 14:15:31.857 UTC
2019-06-05 22:48:12.163 UTC
null
6,862,601
null
1,975,277
null
1
279
python|django|datetime|comparison
312,413
<p>By default, the <code>datetime</code> object is <code>naive</code> in Python, so you need to make both of them either naive or aware <code>datetime</code> objects. This can be done using:</p> <pre><code>import datetime import pytz utc=pytz.UTC challenge.datetime_start = utc.localize(challenge.datetime_start) challenge.datetime_end = utc.localize(challenge.datetime_end) # now both the datetime objects are aware, and you can compare them </code></pre> <p>Note: This would raise a <code>ValueError</code> if <code>tzinfo</code> is already set. If you are not sure about that, just use</p> <pre><code>start_time = challenge.datetime_start.replace(tzinfo=utc) end_time = challenge.datetime_end.replace(tzinfo=utc) </code></pre> <p>BTW, you could format a UNIX timestamp in datetime.datetime object with timezone info as following</p> <pre><code>d = datetime.datetime.utcfromtimestamp(int(unix_timestamp)) d_with_tz = datetime.datetime( year=d.year, month=d.month, day=d.day, hour=d.hour, minute=d.minute, second=d.second, tzinfo=pytz.UTC) </code></pre>
15,113,413
How do I concatenate strings and variables in PowerShell?
<p>Suppose I have the following snippet:</p> <pre class="lang-powershell prettyprint-override"><code>$assoc = New-Object PSObject -Property @{ Id = 42 Name = &quot;Slim Shady&quot; Owner = &quot;Eminem&quot; } Write-Host $assoc.Id + &quot; - &quot; + $assoc.Name + &quot; - &quot; + $assoc.Owner </code></pre> <p>I'd expect this snippet to show:</p> <blockquote> <p><code>42 - Slim Shady - Eminem</code></p> </blockquote> <p>But instead it shows:</p> <blockquote> <p><code>42 + - + Slim Shady + - + Eminem</code></p> </blockquote> <p>Which makes me think the <code>+</code> operator isn't appropriate for concatenating strings and variables.</p> <p>How should you approach this with PowerShell?</p>
15,113,467
22
2
null
2013-02-27 13:34:02.987 UTC
114
2022-03-17 00:26:35.863 UTC
2020-06-27 10:36:21.207 UTC
null
63,550
null
1,389,663
null
1
849
powershell|string-concatenation
1,981,750
<pre><code>Write-Host "$($assoc.Id) - $($assoc.Name) - $($assoc.Owner)" </code></pre> <p>See the <a href="https://www.microsoft.com/en-us/download/details.aspx?id=36389">Windows PowerShell Language Specification Version 3.0</a>, p34, sub-expressions expansion.</p>
15,051,121
the name <...> does not exist in the namespace clr-namespace <...>
<p>I have a small WPF application which used to compile just fine but is not anymore. I can't really say at which point it stopped building. It just worked fine one day, and the next it's not.</p> <p>Here's the project structure:</p> <p><img src="https://i.stack.imgur.com/wDvfJ.png" alt="enter image description here"></p> <p>There is no other projects or external references other than standard .net dlls.</p> <p>Here's the user control where the problem originated:</p> <pre><code>&lt;UserControl x:Class="TimeRecorder.HistoryUserControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:TimeRecorder.ViewModel" xmlns:framework="clr-namespace:TimeRecorder.Framework" mc:Ignorable="d" Height="Auto" Width="Auto" Padding="5"&gt; &lt;UserControl.Resources&gt; &lt;local:HistoryViewModel x:Key="ViewModel"/&gt; &lt;framework:BoolToColorConverter x:Key="ColorConverter"/&gt; &lt;/UserControl.Resources&gt; &lt;StackPanel DataContext="{StaticResource ViewModel}"&gt; </code></pre> <p>And here's the error I get: <img src="https://i.stack.imgur.com/fAsA0.png" alt="http://i48.tinypic.com/5u1u8w.png"></p> <p><strong>Please note that this is not just the one file in the screenshot, but all references I add in similar fashion in xaml in all user control/window files in this project.</strong></p> <p>So the file is there, the namespace in the file is correct, the namespace/class name in the xaml file is (to my understanding) correct. I get intellisense when I type in the xaml so it finds the files ok then but not when it compiles.</p> <p>The most common solution for this in other posts has been the .net framework version. It is currently set to .Net Framework 4 for both my main and test project. The full version not the client profile.</p> <p><strong>Here's what I think I messed up:</strong> In the configuration manager, both projects have their Platform set to Any CPU, but at one point when trying to solve this I noticed that the main project was set to x86 and the test project was set to Any CPU. So I added Any CPU manually for the main project in the configuration manager. However I honestly don't know if I did this correctly or even if I should do it. So as an additional question, is there a way I can reset the configuration manager to its default state? Will this have anything to say for the main problem? I don't know if the main project was always set to x86 or not or if I somehow changed it to x86 and then it broke. As mentioned this project was compiling just fine for a while. </p>
15,247,754
31
6
null
2013-02-24 11:05:05.987 UTC
20
2022-06-30 12:30:39.843 UTC
2019-11-17 10:57:20.103 UTC
null
472,495
null
1,136,963
null
1
98
c#|.net|wpf|xaml|namespaces
105,105
<p>Every time it happend to me i just restarted visual studio, re-built the solution and it worked just fine.. can't say why</p>
15,081,542
Python, creating objects
<p>I'm trying to learn python and I now I am trying to get the hang of classes and how to manipulate them with instances.</p> <p>I can't seem to understand this practice problem:</p> <p>Create and return a student object whose name, age, and major are the same as those given as input</p> <pre><code>def make_student(name, age, major) </code></pre> <p>I just don't get what it means by object, do they mean I should create an array inside the function that holds these values? or create a class and let this function be inside it, and assign instances? (before this question i was asked to set up a student class with name, age, and major inside)</p> <pre><code>class Student: name = "Unknown name" age = 0 major = "Unknown major" </code></pre>
15,081,667
4
2
null
2013-02-26 04:47:18.34 UTC
34
2018-06-28 17:25:27.137 UTC
null
null
null
null
2,109,791
null
1
152
python
556,103
<pre><code>class Student(object): name = "" age = 0 major = "" # The class "constructor" - It's actually an initializer def __init__(self, name, age, major): self.name = name self.age = age self.major = major def make_student(name, age, major): student = Student(name, age, major) return student </code></pre> <p>Note that even though one of the principles in Python's philosophy is <em>"there should be one—and preferably only one—obvious way to do it"</em>, there are still multiple ways to do this. You can also use the two following snippets of code to take advantage of Python's dynamic capabilities:</p> <pre><code>class Student(object): name = "" age = 0 major = "" def make_student(name, age, major): student = Student() student.name = name student.age = age student.major = major # Note: I didn't need to create a variable in the class definition before doing this. student.gpa = float(4.0) return student </code></pre> <p>I prefer the former, but there are instances where the latter can be useful – one being when working with document databases like MongoDB. </p>
28,250,081
When should I rerun cmake?
<p>After running the <code>cmake</code> command once to generate a build system, when, if ever, should I rerun the <code>cmake</code> command?</p> <p>The generated build systems can detect changes in the associated <code>CMakeLists.txt</code> files and behave accordingly. You can see the logic for doing so in generated Makefiles. The exact rules for when this will happen successfully are mysterious to me.</p> <p>When should I rerun <code>cmake</code>? Does the answer depend on the generator used?</p> <p><a href="http://voices.canonical.com/jussi.pakkanen/2013/03/26/a-list-of-common-cmake-antipatterns/">This blog post</a> (under heading: "Invoking CMake multiple times") points out the confusion over this issue and states that the answer is actually 'never', regardless of generator, but I find that surprising. Is it true?</p>
28,251,332
2
4
null
2015-01-31 09:24:32.803 UTC
9
2020-04-17 12:25:14.287 UTC
2015-01-31 09:51:28.36 UTC
null
1,128,289
null
1,128,289
null
1
41
cmake
16,204
<p>The answer is simple: The <code>cmake</code> binary of course needs to re-run each time you make changes to any build setting, but <em>you</em> wont need to do it by design; hence "never" is correct regarding commands you have to issue.</p> <p>The build targets created by cmake <em>automatically include</em> checks for each file subsequently [=starting from the main CMakeLists.txt file] involved or included generating the current set of Makefiles/VS projects/whatever. When invoking <code>make</code> (assuming unix here) this automatically triggers a previous execution of <code>cmake</code> if necessary; so your generated projects include logic to invoke cmake itself! As all command-line parameters initially passed (e.g. <code>cmake -DCMAKE_BUILD_TYPE=RELEASE ..</code> will be stored in the <code>CMakeCache.txt</code>, you dont need to re-specify any of those on subsequent invocations, which is why the projects also can just run <code>cmake</code> and know it still does what you intended.</p> <p>Some more detail: CMake generates book-keeping files containing all files that were involved in Makefile/Project generation, see e.g. these sample contents of my <code>&lt;binary-dir&gt;/CMakeFiles/Makefile.cmake</code> file using MSYS makefiles:</p> <pre><code># The top level Makefile was generated from the following files: set(CMAKE_MAKEFILE_DEPENDS "CMakeCache.txt" "C:/Program Files (x86)/CMake/share/cmake-3.1/Modules/CMakeCCompiler.cmake.in" "C:/Program Files (x86)/CMake/share/cmake-3.1/Modules/RepositoryInfo.txt.in" "&lt;my external project bin dir&gt;/release/ep_tmp/IRON-cfgcmd.txt.in" "../CMakeFindModuleWrappers/FindBLAS.cmake" "../CMakeFindModuleWrappers/FindLAPACK.cmake" "../CMakeLists.txt" "../CMakeScripts/CreateLocalConfig.cmake" "../Config/Variables.cmake" "../Dependencies.cmake" "CMakeFiles/3.1.0/CMakeCCompiler.cmake" "CMakeFiles/3.1.0/CMakeRCCompiler.cmake") </code></pre> <p>Any modification to any of these files will trigger another cmake run <em>whenever you choose to start a build of a target</em>. I honestly dont know how fine-grained those dependencies tracking goes in CMake, i.e. if a target will just be build if any changes somewhere else wont affect the target's compilation. I wouldn't expect it as this can get messy quite quickly, and repeated CMake runs (correctly using the Cache capabilities) are very fast anyways.</p> <p>The only case where you need to re-run <code>cmake</code> is when you change the compiler after you started a <code>project(MyProject)</code>; but even this case is handled by newer CMake versions automatically now (with some yelling :-)).</p> <h2>additional comment responding to comments:</h2> <p>There are cases where you will need to manually re-run cmake, and that is whenever you write your configure scripts so badly that cmake cannot possibly detect files/dependencies you're creating. A typical scenario would be that your first cmake run creates files using e.g. <code>execute_process</code> and you would then include them using <code>file(GLOB ..)</code>. This is BAD style and the <a href="http://www.cmake.org/cmake/help/v3.1/command/file.html" rel="noreferrer">CMake Docs for file</a> explicitly say</p> <blockquote> <p>Note: We do not recommend using GLOB to collect a list of source files from your source tree. If no CMakeLists.txt file changes when a source is added or removed then the generated build system cannot know when to ask CMake to regenerate.</p> </blockquote> <p>Btw this comment also sheds light on the above explained self-invocation by the generated build system :-)</p> <p>The "proper" way to treat this kind of situations where you create source files during configure time is to use <code>add_custom_command(OUTPUT ...)</code>, so that CMake is "aware" of a file being generated and tracks changes correctly. If for some reason you can't/won't use <code>add_custom_command</code>, you can still let CMake know of your file generation using the source file property <a href="http://www.cmake.org/cmake/help/v3.1/prop_sf/GENERATED.html" rel="noreferrer">GENERATED</a>. Any source file with this flag set can be hard-coded into target source files and CMake wont complain about missing files at configure time (and expects this file to be generated some time during the (first!) cmake run.</p>
27,986,204
Can't convert to color: type=0x2 error when inflating layout in fragment but only on Samsung Galaxy and Note 4
<p>I am working on a simple app with an activity and i use fragments.One screen with some elements. When i compile and run the app it works fine, except on Samsung Galaxy s3 and note 4. I don't get it from the stacktrace what is wrong.</p> <pre><code>01-16 16:25:05.915: E/AndroidRuntime(23174): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.test/com.test.MainActivity}: android.view.InflateException: Binary XML file line #37: Error inflating class com.android.internal.widget.ActionBarView 01-16 16:25:05.915: E/AndroidRuntime(23174): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2292) 01-16 16:25:05.915: E/AndroidRuntime(23174): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2350) 01-16 16:25:05.915: E/AndroidRuntime(23174): at android.app.ActivityThread.access$800(ActivityThread.java:163) 01-16 16:25:05.915: E/AndroidRuntime(23174): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1257) 01-16 16:25:05.915: E/AndroidRuntime(23174): at android.os.Handler.dispatchMessage(Handler.java:102) 01-16 16:25:05.915: E/AndroidRuntime(23174): at android.os.Looper.loop(Looper.java:157) 01-16 16:25:05.915: E/AndroidRuntime(23174): at android.app.ActivityThread.main(ActivityThread.java:5335) 01-16 16:25:05.915: E/AndroidRuntime(23174): at java.lang.reflect.Method.invokeNative(Native Method) 01-16 16:25:05.915: E/AndroidRuntime(23174): at java.lang.reflect.Method.invoke(Method.java:515) 01-16 16:25:05.915: E/AndroidRuntime(23174): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265) 01-16 16:25:05.915: E/AndroidRuntime(23174): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081) 01-16 16:25:05.915: E/AndroidRuntime(23174): at dalvik.system.NativeStart.main(Native Method) 01-16 16:25:05.915: E/AndroidRuntime(23174): Caused by: android.view.InflateException: Binary XML file line #37: Error inflating class com.android.internal.widget.ActionBarView 01-16 16:25:05.915: E/AndroidRuntime(23174): at android.view.LayoutInflater.createView(LayoutInflater.java:626) 01-16 16:25:05.915: E/AndroidRuntime(23174): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:702) 01-16 16:25:05.915: E/AndroidRuntime(23174): at android.view.LayoutInflater.rInflate(LayoutInflater.java:761) 01-16 16:25:05.915: E/AndroidRuntime(23174): at android.view.LayoutInflater.rInflate(LayoutInflater.java:769) 01-16 16:25:05.915: E/AndroidRuntime(23174): at android.view.LayoutInflater.inflate(LayoutInflater.java:498) 01-16 16:25:05.915: E/AndroidRuntime(23174): at android.view.LayoutInflater.inflate(LayoutInflater.java:398) 01-16 16:25:05.915: E/AndroidRuntime(23174): at android.view.LayoutInflater.inflate(LayoutInflater.java:354) 01-16 16:25:05.915: E/AndroidRuntime(23174): at com.android.internal.policy.impl.PhoneWindow.generateLayout(PhoneWindow.java:3253) 01-16 16:25:05.915: E/AndroidRuntime(23174): at com.android.internal.policy.impl.PhoneWindow.installDecor(PhoneWindow.java:3327) 01-16 16:25:05.915: E/AndroidRuntime(23174): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:336) 01-16 16:25:05.915: E/AndroidRuntime(23174): at android.app.Activity.setContentView(Activity.java:1973) 01-16 16:25:05.915: E/AndroidRuntime(23174): at com.test.MainActivity.onCreate(MainActivity.java:28) 01-16 16:25:05.915: E/AndroidRuntime(23174): at android.app.Activity.performCreate(Activity.java:5389) 01-16 16:25:05.915: E/AndroidRuntime(23174): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105) 01-16 16:25:05.915: E/AndroidRuntime(23174): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2256) 01-16 16:25:05.915: E/AndroidRuntime(23174): ... 11 more 01-16 16:25:05.915: E/AndroidRuntime(23174): Caused by: java.lang.reflect.InvocationTargetException 01-16 16:25:05.915: E/AndroidRuntime(23174): at java.lang.reflect.Constructor.constructNative(Native Method) 01-16 16:25:05.915: E/AndroidRuntime(23174): at java.lang.reflect.Constructor.newInstance(Constructor.java:423) 01-16 16:25:05.915: E/AndroidRuntime(23174): at android.view.LayoutInflater.createView(LayoutInflater.java:600) 01-16 16:25:05.915: E/AndroidRuntime(23174): ... 25 more 01-16 16:25:05.915: E/AndroidRuntime(23174): Caused by: android.view.InflateException: Binary XML file line #35: Error inflating class android.widget.TextView 01-16 16:25:05.915: E/AndroidRuntime(23174): at android.view.LayoutInflater.createView(LayoutInflater.java:626) 01-16 16:25:05.915: E/AndroidRuntime(23174): at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56) 01-16 16:25:05.915: E/AndroidRuntime(23174): at android.view.LayoutInflater.onCreateView(LayoutInflater.java:675) 01-16 16:25:05.915: E/AndroidRuntime(23174): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:700) 01-16 16:25:05.915: E/AndroidRuntime(23174): at android.view.LayoutInflater.rInflate(LayoutInflater.java:761) 01-16 16:25:05.915: E/AndroidRuntime(23174): at android.view.LayoutInflater.rInflate(LayoutInflater.java:769) 01-16 16:25:05.915: E/AndroidRuntime(23174): at android.view.LayoutInflater.inflate(LayoutInflater.java:498) 01-16 16:25:05.915: E/AndroidRuntime(23174): at android.view.LayoutInflater.inflate(LayoutInflater.java:398) 01-16 16:25:05.915: E/AndroidRuntime(23174): at com.android.internal.widget.ActionBarView.initTitle(ActionBarView.java:1131) 01-16 16:25:05.915: E/AndroidRuntime(23174): at com.android.internal.widget.ActionBarView.setDisplayOptions(ActionBarView.java:947) 01-16 16:25:05.915: E/AndroidRuntime(23174): at com.android.internal.widget.ActionBarView.&lt;init&gt;(ActionBarView.java:392) 01-16 16:25:05.915: E/AndroidRuntime(23174): ... 28 more 01-16 16:25:05.915: E/AndroidRuntime(23174): Caused by: java.lang.reflect.InvocationTargetException 01-16 16:25:05.915: E/AndroidRuntime(23174): at java.lang.reflect.Constructor.constructNative(Native Method) 01-16 16:25:05.915: E/AndroidRuntime(23174): at java.lang.reflect.Constructor.newInstance(Constructor.java:423) 01-16 16:25:05.915: E/AndroidRuntime(23174): at android.view.LayoutInflater.createView(LayoutInflater.java:600) 01-16 16:25:05.915: E/AndroidRuntime(23174): ... 38 more 01-16 16:25:05.915: E/AndroidRuntime(23174): Caused by: java.lang.UnsupportedOperationException: Can't convert to color: type=0x2 01-16 16:25:05.915: E/AndroidRuntime(23174): at android.content.res.TypedArray.getColor(TypedArray.java:327) 01-16 16:25:05.915: E/AndroidRuntime(23174): at android.widget.TextView.&lt;init&gt;(TextView.java:945) 01-16 16:25:05.915: E/AndroidRuntime(23174): at android.widget.TextView.&lt;init&gt;(TextView.java:863) 01-16 16:25:05.915: E/AndroidRuntime(23174): ... 41 more </code></pre> <p>And the layout from the fragment:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/layout" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" tools:context="com.locker.theme.one.MainActivity$PlaceholderFragment" &gt; &lt;RelativeLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight=".14" android:clickable="true" android:gravity="center" &gt; &lt;DigitalClock android:id="@+id/digitalClock" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:textAppearance="?android:attr/textAppearanceLarge" android:textColor="@android:color/white" android:textSize="66sp" /&gt; &lt;/RelativeLayout&gt; &lt;RelativeLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight=".14" android:gravity="center" &gt; &lt;ProgressBar android:id="@+id/progress" style="?android:attr/progressBarStyleInverse" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:layout_gravity="center" android:layout_marginBottom="8dp" android:visibility="gone" /&gt; &lt;Button android:id="@+id/activateBtn" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="@color/material_deep_teal_200" android:gravity="center" android:layout_marginLeft="@dimen/activity_horizontal_margin" android:layout_marginRight="@dimen/activity_horizontal_margin" android:text="Test" /&gt; &lt;/RelativeLayout&gt; &lt;/LinearLayout&gt; </code></pre> <p>This is the style i use:</p> <pre><code>&lt;resources&gt; &lt;!-- Base application theme, dependent on API level. This theme is replaced by AppBaseTheme from res/values-vXX/styles.xml on newer devices. --&gt; &lt;style name="AppBaseTheme" parent="android:Theme.Light"&gt; &lt;!-- Theme customizations available in newer API levels can go in res/values-vXX/styles.xml, while customizations related to backward-compatibility can go here. --&gt; &lt;/style&gt; &lt;!-- Application theme. --&gt; &lt;style name="AppTheme" parent="android:Theme.Material"&gt; &lt;!-- Main theme colors --&gt; &lt;/style&gt; &lt;/resources&gt; </code></pre> <p>I did google a bit, but didn't find an idea that could tell me what is happening. Any points would be great. Thank you</p>
34,279,007
4
4
null
2015-01-16 14:32:03.967 UTC
5
2019-12-11 09:15:34.447 UTC
2015-01-16 14:48:00.15 UTC
null
1,140,656
null
1,140,656
null
1
40
android|android-layout|android-fragments
16,534
<p>I faced the same issue, that was caused by using <code>attributes</code> as a reference to <code>color</code> in an XML drawable. </p> <p>As mentioned <a href="https://stackoverflow.com/a/13471695/3212712">here</a> on <strong>API &lt; 21</strong> you can't use attrs to <code>color</code> in the XML drawable. So only way is to use a reference to a color resource (<code>@color/YOURS_COLOR</code>) or use <code>#RGB</code> format.</p> <p>So if you want to use an XML drawable with theme depended colors you should create a drawable for each theme.</p>
19,659,210
Could not find default endpoint element that references contract 'IAuthenticationService' in the ServiceModel client configuration section
<p>I tried creating a simple WCF application, I haven't changed any of the existing default configurations. I have tried consuming the service using the <code>TestClient</code> generated by using <code>svcutil.exe</code>. It is showing an error message <code>"Could not find default endpoint element that references contract 'IAuthenticationService' in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this contract could be found in the client element."</code> I tried putting endpoint to localhost:port number/test.svc but its showing the same error.</p> <p><p>this code is being shown after i execute the web test client. I couldnt trace out the error after searching for long hours over internet<p></p> <p><p> Here is my testClients clientdll.config<p></p> <pre class="lang-xml prettyprint-override"><code>&lt;configuration&gt; &lt;system.serviceModel&gt; &lt;bindings&gt; &lt;wsHttpBinding&gt; &lt;binding name="wsHttpBinding" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true" allowCookies="false"&gt; &lt;readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" /&gt; &lt;reliableSession ordered="true" inactivityTimeout="00:10:00" enabled="false" /&gt; &lt;security mode="Message"&gt; &lt;transport clientCredentialType="Windows" proxyCredentialType="None" realm="" /&gt; &lt;message clientCredentialType="Windows" negotiateServiceCredential="true" algorithmSuite="Default" establishSecurityContext="true" /&gt; &lt;/security&gt; &lt;/binding&gt; &lt;/wsHttpBinding&gt; &lt;/bindings&gt; &lt;client&gt; &lt;endpoint address="http://localhost:2490/AuthenticationService.svc" binding="wsHttpBinding" bindingConfiguration="wsHttpBinding" contract="IAuthenicationService" name="wsHttpBinding"&gt; &lt;identity&gt; &lt;dns value="localhost" /&gt; &lt;/identity&gt; &lt;/endpoint&gt; &lt;/client&gt; &lt;/system.serviceModel&gt; &lt;/configuration&gt; </code></pre>
19,674,713
2
8
null
2013-10-29 13:12:23.093 UTC
1
2016-05-31 12:55:47.997 UTC
2016-05-31 12:55:47.997 UTC
null
443,310
null
2,911,047
null
1
9
c#|wcf|error-handling
63,033
<p>try removing the end points there and use <br></p> <pre><code> compilation debug=true </code></pre> <p>in web.config. then after trying </p> <pre><code>svcutil.exe http://your_wsdl </code></pre> <p>you will generate an output.config. Try putting in servicemodel nodes replacing your client website or application with the output.config service model. It will work</p>
8,525,765
load parameters from a file in Python
<p>I am writing a Python class to model a process and I want to initialized the parameters from a file, say <code>'input.dat'</code>. The format of the input file looks like this.</p> <p><code>'input.dat'</code> file:</p> <pre class="lang-none prettyprint-override"><code>Z0: 0 0 k: 0.1 g: 1 Delta: 20 t_end: 300 </code></pre> <p>The code I wrote is the following. It works but appears redundant and inflexible. Is there a better way to do the job? Such as a loop to do readline() and then match the keyword?</p> <pre><code>def load(self,filename="input.dat"): FILE = open(filename) s = FILE.readline().split() if len(s) is 3: self.z0 = [float(s[1]),float(s[2])] # initial state s = FILE.readline().split() if len(s) is 2: self.k = float(s[1]) # kappa s = FILE.readline().split() if len(s) is 2: self.g = float(s[1]) s = FILE.readline().split() if len(s) is 2: self.D = float(s[1]) # Delta s = FILE.readline().split() if len(s) is 2: self.T = float(s[1]) # end time </code></pre>
8,526,061
9
4
null
2011-12-15 19:51:25.873 UTC
6
2015-08-05 11:00:12.343 UTC
2011-12-15 22:29:46.217 UTC
null
355,230
null
534,298
null
1
22
python|file|serialization|input
54,077
<ul> <li>If you are open to some other kind of file where you can keep your parameters, I would suggest you to use <a href="http://www.yaml.org/" rel="noreferrer">YAML</a> file. </li> <li>The python lib is <a href="http://pyyaml.org/" rel="noreferrer">PyYAML</a> <a href="http://pyyaml.org/wiki/PyYAMLDocumentation" rel="noreferrer">This</a> is how you can easily use it with Python</li> <li>For better introduction, look at the wiki article : <a href="http://en.wikipedia.org/wiki/YAML" rel="noreferrer">http://en.wikipedia.org/wiki/YAML</a> </li> <li>The benefit is you can read the parameter values as list, maps</li> <li>You would love it!</li> </ul>
31,070,563
Find all local Maxima and Minima when x and y values are given as numpy arrays
<p>I have two arrays <code>x</code> and <code>y</code> as :</p> <pre><code>x = np.array([6, 3, 5, 2, 1, 4, 9, 7, 8]) y = np.array([2, 1, 3, 5, 3, 9, 8, 10, 7]) </code></pre> <p>I am finding index of local minima and maxima as follows:</p> <pre><code>sortId = np.argsort(x) x = x[sortId] y = y[sortId] minm = np.array([]) maxm = np.array([]) while i &lt; y.size-1: while(y[i+1] &gt;= y[i]): i = i + 1 maxm = np.insert(maxm, 0, i) i++ while(y[i+1] &lt;= y[i]): i = i + 1 minm = np.insert(minm, 0, i) i++ </code></pre> <p>What is the problem in this code? The answer should be index of <code>minima = [2, 5, 7]</code> and that of <code>maxima = [1, 3, 6]</code>.</p>
31,073,798
3
9
null
2015-06-26 10:12:49.127 UTC
7
2018-11-22 07:30:38.92 UTC
2016-03-06 20:43:35.03 UTC
null
1,534,017
null
5,047,699
null
1
14
python|numpy|derivative
46,509
<p>You do not need this <code>while</code> loop at all. The code below will give you the output you want; it finds all local minima and all local maxima and stores them in <code>minm</code> and <code>maxm</code>, respectively. Please note: When you apply this to large datasets, make sure to smooth the signals first; otherwise you will end up with tons of extrema.</p> <pre><code>import numpy as np from scipy.signal import argrelextrema import matplotlib.pyplot as plt x = np.array([6, 3, 5, 2, 1, 4, 9, 7, 8]) y = np.array([2, 1, 3 ,5 ,3 ,9 ,8, 10, 7]) # sort the data in x and rearrange y accordingly sortId = np.argsort(x) x = x[sortId] y = y[sortId] # this way the x-axis corresponds to the index of x plt.plot(x-1, y) plt.show() maxm = argrelextrema(y, np.greater) # (array([1, 3, 6]),) minm = argrelextrema(y, np.less) # (array([2, 5, 7]),) </code></pre> <p>This should be far more efficient than the above <code>while</code> loop.</p> <p>The plot looks like this; I shifted the x-values so that they correspond to the returned indices in <code>minm</code> and <code>maxm</code>):</p> <p><img src="https://i.stack.imgur.com/FqTEe.png" alt="enter image description here"></p> <p>As of SciPy version 1.1, you can also use <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.find_peaks.html" rel="noreferrer">find_peaks</a>:</p> <pre><code>from scipy.signal import find_peaks peaks, _ = find_peaks(y) # this way the x-axis corresponds to the index of x plt.plot(x-1, y) plt.plot(peaks, y[peaks], "x") plt.show() </code></pre> <p>That yields</p> <p><a href="https://i.stack.imgur.com/VeMdQ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/VeMdQ.png" alt="enter image description here"></a></p> <p>The nice thing is, that you can now also easily also set a minimum peak height (e.g. 8):</p> <pre><code>peaks, _ = find_peaks(y, height=8) # this way the x-axis corresponds to the index of x plt.plot(x-1, y) plt.plot(peaks, y[peaks], "x") plt.show() </code></pre> <p><a href="https://i.stack.imgur.com/bhDVp.png" rel="noreferrer"><img src="https://i.stack.imgur.com/bhDVp.png" alt="enter image description here"></a></p> <p>Note that now the first peak is excluded as its height is below 8. </p> <p>Furthermore, you can set also the minimal distance between peaks (e.g. 5):</p> <pre><code>peaks, _ = find_peaks(y, distance=5) # this way the x-axis corresponds to the index of x plt.plot(x-1, y) plt.plot(peaks, y[peaks], "x") plt.show() </code></pre> <p><a href="https://i.stack.imgur.com/uaFhD.png" rel="noreferrer"><img src="https://i.stack.imgur.com/uaFhD.png" alt="enter image description here"></a></p> <p>Now the middle peak is excluded as its distance to the other two peaks is less than 5. </p>
5,313,143
Run multiple WorkerRoles per instance
<p>I have several <code>WorkerRole</code> that only do job for a short time, and it would be a waste of money to put them in a single instance each. We could merge them in a single one, but it'd be a mess and in the far future they are supposed to work independently when the load increases.</p> <p>Is there a way to create a "multi role" <code>WorkerRole</code> in the same way you can create a "multi site" <code>WebRole</code>?</p> <p>In negative case, I think I can create a "master worker role", that is able to load the assemblies from a given folder, look for RoleEntryPoint derivated classes with reflection, create instances and invoke the <code>.Run()</code> or <code>.OnStart()</code> method. This "master worker role" will also rethrown unexpected exceptions, and call <code>.OnStop()</code> in all sub <code>RoleEntryPoint</code>s when <code>.OnStop()</code> is called in the master one. Would it work? What should I be aware of?</p>
5,315,626
4
1
null
2011-03-15 14:22:38.307 UTC
13
2012-01-28 05:50:35.85 UTC
2011-03-16 21:53:04.833 UTC
null
11,635
null
307,976
null
1
17
azure|azure-worker-roles
9,755
<p>As mentioned by others, this is a very common technique for maximizing utilization of your instances. There may examples and "frameworks" that abstract the worker infrastructure and the actual work you want to be done, including one in this (our) sample: <a href="http://msdn.microsoft.com/en-us/library/ff966483.aspx">http://msdn.microsoft.com/en-us/library/ff966483.aspx</a> (scroll down to "inside the implementation")</p> <p>Te most common ways of triggering work are:</p> <ol> <li>Time scheduled workers (like "cron" jobs)</li> <li>Message baseds workers (work triggered by the presence of a message).</li> </ol> <p>The code sample mentioned above implements further abstractions for #2 and is easily extensible for #1. </p> <p>Bear in mind though that all interactions with queues are based on polling. The worker will not wake up with a new message on the queue. You need to actively query the queue for new messages. Querying too often will make Microsoft happy, but probably not you :-). Each query counts as a transaction that is billed (10K of those = $0.01). A good practice is to poll the queue for messages with some kind of delayed back-off. Also, get messages in batches.</p> <p>Finally, taking this to an extreme, you can also combine web roles and worker roles in a single instance. See here for an example: <a href="http://blog.smarx.com/posts/web-page-image-capture-in-windows-azure">http://blog.smarx.com/posts/web-page-image-capture-in-windows-azure</a> </p>
4,950,245
in entity framework code first, how to use KeyAttribute on multiple columns
<p>I'm creating a POCO model to use with entity framework code first CTP5. I'm using the decoration to make a property map to a PK column. But how can I define a PK on more then one column, and specifically, how can I control order of the columns in the index? Is it a result of the order of properties in the class?</p> <p>Thanks!</p>
4,950,571
4
0
null
2011-02-09 20:45:03.803 UTC
17
2018-02-25 15:49:30.03 UTC
null
null
null
null
149,769
null
1
103
entity-framework|code-first|entity-framework-ctp5
73,666
<p>You can specify the column order in the attributes, for instance:</p> <pre><code>public class MyEntity { [Key, Column(Order=0)] public int MyFirstKeyProperty { get; set; } [Key, Column(Order=1)] public int MySecondKeyProperty { get; set; } [Key, Column(Order=2)] public string MyThirdKeyProperty { get; set; } // other properties } </code></pre> <p>If you are using the <code>Find</code> method of a <code>DbSet</code> you must take this order for the key parameters into account.</p>
5,419,453
Getting upper and lower byte of an integer in C# and putting it as a char array to send to a com port, how?
<p>In C I would do this</p> <blockquote> <p>int number = 3510;</p> <p>char upper = number &gt;&gt; 8;</p> <p>char lower = number &amp;&amp; 8;</p> <p>SendByte(upper);</p> <p>SendByte(lower);</p> </blockquote> <p>Where upper and lower would both = 54</p> <p>In C# I am doing this:</p> <blockquote> <pre><code> int number = Convert.ToInt16(&quot;3510&quot;); byte upper = byte(number &gt;&gt; 8); byte lower = byte(number &amp; 8); char upperc = Convert.ToChar(upper); char lowerc = Convert.ToChar(lower); data = &quot;GETDM&quot; + upperc + lowerc; comport.Write(data); </code></pre> </blockquote> <p>However in the debugger number = 3510, upper = 13 and lower = 0 this makes no sense, if I change the code to &gt;&gt; 6 upper = 54 which is absolutely strange.</p> <p>Basically I just want to get the upper and lower byte from the 16 bit number, and send it out the com port after &quot;GETDM&quot;</p> <p>How can I do this? It is so simple in C, but in C# I am completely stumped.</p>
5,419,500
5
0
null
2011-03-24 12:54:16.17 UTC
3
2015-07-15 08:34:36.39 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
434,537
null
1
17
c#|char|bytearray|bit-shift|bitmask
50,919
<p>Your masking is incorrect - you should be masking against 255 (0xff) instead of 8. Shifting works in terms of "bits to shift by" whereas bitwise and/or work against the value to mask against... so if you want to only keep the bottom 8 bits, you need a mask which just has the bottom 8 bits set - i.e. 255.</p> <p>Note that if you're trying to split a number into two bytes, it should really be a short or ushort to start with, not an <code>int</code> (which has <em>four</em> bytes).</p> <pre><code>ushort number = Convert.ToUInt16("3510"); byte upper = (byte) (number &gt;&gt; 8); byte lower = (byte) (number &amp; 0xff); </code></pre> <p>Note that I've used <code>ushort</code> here instead of <code>byte</code> as bitwise arithmetic is easier to think about when you don't need to worry about sign extension. It wouldn't actually matter in this case due to the way the narrowing conversion to <code>byte</code> works, but it's the kind of thing you should be thinking about.</p>
5,433,691
How to repeat string n times in idiomatic clojure way?
<p>In Ruby, <code>"str" * 3</code> will give you "strstrstr". In Clojure, the closest I can think of is <code>(map (fn [n] "str") (range 3))</code> Is there a more idiomatic way of doing it?</p>
5,433,727
6
0
null
2011-03-25 14:20:47.69 UTC
4
2018-05-15 09:42:39.95 UTC
2015-10-05 03:40:52.597 UTC
null
1,305,344
null
10,771
null
1
42
clojure
11,575
<p>How about this?</p> <pre><code>(apply str (repeat 3 "str")) </code></pre> <p>Or just</p> <pre><code>(repeat 3 "str") </code></pre> <p>if you want a sequence instead of a string.</p>
5,176,596
Struggle against habits formed by Java when migrating to Scala
<p>What are the most common mistakes that Java developers make when migrating to Scala?</p> <p>By mistakes I mean writing a code that does not conform to Scala spirit, for example using loops when map-like functions are more appropriate, excessive use of exceptions etc.</p> <p>EDIT: one more is using own getters/setters instead of methods kindly generated by Scala</p>
5,181,156
7
10
2011-03-24 12:29:51.927 UTC
2011-03-03 04:18:26.653 UTC
9
2012-01-22 12:14:22.197 UTC
2012-01-22 12:14:22.197 UTC
null
21,234
null
531,567
null
1
13
java|scala|migration
1,572
<p>One obvious one is to not take advantage of the nested scoping that scala allows, plus the delaying of side-effects (or realising that everything in scala is an expression):</p> <pre><code>public InputStream foo(int i) { final String s = String.valueOf(i); boolean b = s.length() &gt; 3; File dir; if (b) { dir = new File("C:/tmp"); } else { dir = new File("/tmp"); } if (!dir.exists()) dir.mkdirs(); return new FileInputStream(new File(dir, "hello.txt")); } </code></pre> <p>Could be converted as:</p> <pre><code>def foo(i : Int) : InputStream = { val s = i.toString val b = s.length &gt; 3 val dir = if (b) { new File("C:/tmp") } else { new File("/tmp") } if (!dir.exists) dir.mkdirs() new FileInputStream(new File(dir, "hello.txt")) } </code></pre> <p>But this can be improved upon a lot. It could be:</p> <pre><code>def foo(i : Int) = { def dir = { def ensuring(d : File) = { if (!d.exists) require(d.mkdirs); d } def b = { def s = i.toString s.length &gt; 3 } ensuring(new File(if (b) "C:/tmp" else "/tmp")); } new FileInputStream(dir, "hello.txt") } </code></pre> <p>The latter example does not "export" any variable beyond the scope which it is needed. In fact, it does not declare any variables <em>at all</em>. This means it is easier to refactor later. Of course, this approach <em>does</em> lead to hugely bloated class files!</p>
5,254,396
Best strategy to use HAML template with Backbone.js
<p>Im getting into Backbone.js to structure the javascript code for my project and I love HAML for templating on the backend(rails), so Id like to use it for Backbone Views templating. I know there is several HAML ports to Javascript, like <a href="https://github.com/creationix/haml-js">https://github.com/creationix/haml-js</a> and backbone supports JST and mustache with ease. </p> <p>Whats the best way to use haml templating instead.</p> <p>Are there any downsides to using HAML on the client side? Performance, extra script load time(taken care by asset packaging tools like jammit)</p>
5,427,160
8
0
null
2011-03-10 01:22:30.79 UTC
27
2014-08-19 21:00:46.93 UTC
null
null
null
null
218,248
null
1
38
javascript|templates|haml|backbone.js
16,978
<p>I know you already mentioned it but I would suggest using haml-js with Jammit. Simply include haml.js in your javascripts and in your assets.yml add <code>template_function: Haml</code> as well as including your template files in to a package. e.g.</p> <pre><code> javascript_templates: - app/views/**/*.jst.haml </code></pre> <p>Then in your views you can include this package (<code>= include_javascripts :javascript_templates</code>) and Jammit will package any .jst.haml files in to <code>window.JST['file/path']</code>. (If you view page source you should see a javascript file like <code>&lt;script src="/assets/javascript_templates.jst" type="text/javascript"&gt;&lt;/script&gt;</code>)</p> <p>To use these templates simply call one of those JSTs Jammit created. i.e.</p> <pre><code>$('div').html(JST['file/path']({ foo: 'Hello', bar: 'World' })); </code></pre> <p>And Jammit will use the Haml-js template function function to render the template.</p> <p>Note: Be sure to point to the github repo of Jammit in your Gemfile to get the latest version that supports newline characters necessary for haml-js to work.</p>
4,908,193
Create a reverse LinkedList in C++ from a given LinkedList
<p>I'm having some trouble create a linkedlist in reverse order from a given linkedlist.</p> <p>I come from a java background, and just started doing some C++.</p> <p>Can you check out my code and see what's wrong? I'm guessing I'm just manipulating pointer and not creating anything new.</p> <pre><code>//this is a method of linkedlist class, it creates a reverse linkedlist //and prints it void LinkedList::reversedLinkedList() { Node* revHead; //check if the regular list is empty if(head == NULL) return; //else start reversing Node* current = head; while(current != NULL) { //check if it's the first one being added if(revHead == NULL) revHead = current; else { //just insert at the beginning Node* tempHead = revHead; current-&gt;next = tempHead; revHead = current; } current = current-&gt;next; }//end while //now print it cout &lt;&lt; "Reversed LinkedList: " &lt;&lt; endl; Node* temp = revHead; while(temp != NULL) { cout &lt;&lt; temp-&gt;firstName &lt;&lt; endl; cout &lt;&lt; temp-&gt;lastName &lt;&lt; endl; cout &lt;&lt; endl; temp = temp-&gt;next; } }//end method </code></pre>
4,908,881
10
3
null
2011-02-05 16:58:43.547 UTC
6
2021-05-20 02:23:12.02 UTC
2011-05-12 12:28:35.13 UTC
null
301,832
user445338
null
null
1
5
c++|linked-list
71,188
<p>Easier one: Go through your linked list, save the previous and the next node and just let the current node point at the previous one:</p> <pre><code>void LinkedList::reversedLinkedList() { if(head == NULL) return; Node *prev = NULL, *current = NULL, *next = NULL; current = head; while(current != NULL){ next = current-&gt;next; current-&gt;next = prev; prev = current; current = next; } // now let the head point at the last node (prev) head = prev; } </code></pre>
5,534,748
Eclipse comment/uncomment shortcut?
<p>I thought this would be easy to achieve, but so far I haven't found solutions for comment/uncomment shortcut on both <code>Java class editor</code> and <code>jsf faceted webapp XHTML file editor</code> :</p> <ol> <li>to quickly comment/uncomment a line (like <kbd>ctrl</kbd> + <kbd>d</kbd> is for removing single line)</li> <li>being able to choose multiple lines and comment/uncomment it</li> </ol> <hr> <p><strong>For example :</strong></p> <p><strong>single line java code</strong>, from :</p> <pre><code>private String name; </code></pre> <p>into</p> <pre><code>//private String name; </code></pre> <hr> <p><strong>multiple line java code</strong>, from :</p> <pre><code>private String name; private int age; </code></pre> <p>into</p> <pre><code>/*private String name; private int age;*/ </code></pre> <hr> <p><strong>single line xhtml code</strong>, from :</p> <pre><code>&lt;h:inputText ... /&gt; </code></pre> <p>into</p> <pre><code>&lt;!-- h:inputText ... / --&gt; </code></pre> <hr> <p><strong>multiple line xhtml code</strong>, from :</p> <pre><code>&lt;h:inputTextarea rows="xx" cols="yy" ... /&gt; </code></pre> <p>into</p> <pre><code>&lt;!-- h:inputTextarea rows="xx" cols="yy" ... / --&gt; </code></pre> <hr>
5,534,773
18
4
null
2011-04-04 05:04:24.52 UTC
80
2021-11-16 13:14:40.267 UTC
2016-01-27 10:28:11.54 UTC
null
863,110
null
500,451
null
1
281
java|eclipse|keyboard-shortcuts|shortcut
613,929
<p>For single line comment you can use <kbd>Ctrl</kbd> + <kbd>/</kbd> and for multiple line comment you can use <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>/</kbd> after selecting the lines you want to comment in java editor.</p> <p>On Mac/OS X you can use <kbd>⌘</kbd> + <kbd>/</kbd> to comment out single lines or selected blocks.</p>
17,021,647
How do I make a background image scroll and not be tiled on the page?
<p>I have a background image for my website, and when I sourced the image in Html it tiles across the page and stops in the same place. How can I resize the image to fill the window and scroll down the page so that the text and stuff just appears to be travelling up the page? I've used the code in your answer and the image shows and isnt tiled but it repeats down the page instead of scrolling down?</p> <pre><code>&lt;body background="D:\Documents and Settings\HOME\Desktop\Nathan Taylor\Mancuerda\Web Page\Background copy.jpg" background style="fixed"&gt; &lt;style type="text/css"&gt; html{ background-image: url(D:\Documents and Settings\HOME\Desktop\Nathan Taylor\Mancuerda\Web Page\Background copy.jpg) no-repeat center center fixed; background-repeat: no-repeat; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; } &lt;/style&gt; </code></pre> <p>There's the script I'm using.</p>
17,021,718
4
0
null
2013-06-10 10:23:15.297 UTC
3
2018-10-01 17:15:36.953 UTC
2015-05-13 21:21:27.193 UTC
null
4,526,171
null
2,431,706
null
1
9
html|css
43,592
<p><strong>*Updated</strong> with jsFiddle: <a href="http://jsfiddle.net/q5WKg/1/" rel="nofollow noreferrer">http://jsfiddle.net/q5WKg/1/</a></p> <p>To stop the background from repeating you want to do in your CSS:</p> <pre><code>background-repeat:no-repeat; </code></pre> <p>To have the background always fill use the css3 property:</p> <pre><code>background-size: cover; </code></pre> <p>Because its not been widely implemented you will probably need to use vendor prefixes:</p> <pre><code>-webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; </code></pre> <p>In addition to your comments - in full it would look something like this:</p> <pre><code>&lt;style type="text/css"&gt; html { background-image: url('path/to/imagefile.jpg'); background-position:center center; background-repeat:no-repeat; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; } &lt;/style&gt; </code></pre> <p>If your background image was on the html element.</p> <p><strong>*Update 2</strong></p> <p>I would correct your code above, move your style declaration in to the head of the document (although where you put it will work fine in most browsers) and remove any info regarding the background image from the body tag.</p> <p>Also the url you are providing is an absolute path to the file on your computer - you need to be using relative paths really, and not paths that are dependant on your computers file structure, I'm assuming that the HTML document is in the same folder as "Background copy.jpg". Therefore your code should read as follows:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;style type="text/css"&gt; html{ background: url('Background copy.jpg') no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; width:100%; height:100%; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; CONTENT &lt;/body&gt; &lt;/html&gt; </code></pre> <p>In addition to the updates to your code, I would change the name of any images you use to all be lowercase and to contain no spaces in their filenames - this will save you a lot of headache further down the line...</p> <p>If you want to better understand how HTML/CSS works, and how to structure them properly I would read up at w3cschools, they have the option to "try it yourself" on a lot of pages which means you can see how the code should be structured and test out different things with CSS &amp; HTML.</p> <p>w3schools css tutorials - <a href="http://www.w3schools.com/css/default.asp" rel="nofollow noreferrer">http://www.w3schools.com/css/default.asp</a></p>
12,402,549
Check if socket is connected or not
<p>I have an application which needs to send some data to a server at some time. The easy way would be to close the connection and then open it again when I want to send something. But I want to keep the connection open so when I want to send data, I first check the connection using this function:</p> <pre><code>bool is_connected(int sock) { unsigned char buf; int err = recv(sock,&amp;buf,1,MSG_PEEK); return err == -1 ? false : true; } </code></pre> <p>The bad part is that this doesn't work. It hangs when there is no data to receive. What can I do? How can I check if the connection is still open? </p>
12,411,808
3
1
null
2012-09-13 08:43:29.933 UTC
4
2016-02-25 05:52:17.457 UTC
2016-02-25 05:52:17.457 UTC
null
514,235
null
478,687
null
1
26
c++|c|sockets|connection
107,262
<p>Don't check first and then send. It's wasted effort and won't work anyway -- the status can change between when you check and when you send. Just do what you want to do and handle the error if it fails.</p> <p>To check status, use:</p> <pre><code>int error_code; int error_code_size = sizeof(error_code); getsockopt(socket_fd, SOL_SOCKET, SO_ERROR, &amp;error_code, &amp;error_code_size); </code></pre>
12,222,417
Why should I initialize member variables in the order they're declared in?
<p>I was writing some code today and got a weird compile error, which seems to be caused by initializing member variables in a different order than they were declared.</p> <p>Example:</p> <pre><code>class Test { int a; int b; public: Test() : b(1), a(2) { } }; int main() { Test test; return 0; } </code></pre> <p>Then if I compile it with <code>-Werror -Wall</code>:</p> <pre><code>$ g++ -Werror -Wall test.cpp test.cpp: In constructor ‘Test::Test()’: test.cpp:3:9: error: ‘Test::b’ will be initialized after [-Werror=reorder] test.cpp:2:9: error: ‘int Test::a’ [-Werror=reorder] test.cpp:6:5: error: when initialized here [-Werror=reorder] cc1plus: all warnings being treated as errors </code></pre> <p>I realize that <code>-Wall</code> is explicitly asking GCC to go over-the-top with warnings, but I assume there's a reason for all of them. So, how could the order of initializing member variables matter?</p>
12,222,509
6
0
null
2012-08-31 21:01:19.837 UTC
18
2019-09-06 11:50:04.053 UTC
null
null
null
null
212,555
null
1
81
c++|g++|compiler-warnings
32,893
<p>The reason is because they're initialized in the order they're declared in your class, not the order you initialize them in the constructor and it's warning you that your constructor's order won't be used.</p> <p>This is to help prevent errors where the initialization of <code>b</code> depends on <code>a</code> or vice-versa.</p> <p>The reason for this ordering is because there is only one destructor, and it has to pick a "reverse order" to destroy the class member. In this case, the simplest solution was to use the order of declaration within the class to make sure that attributes were always destroyed in the correct reverse order.</p>
44,270,239
how to get socket.id of a connection on client side?
<p>Im using the following code in index.js</p> <pre><code>io.on('connection', function(socket){ console.log('a user connected'); console.log(socket.id); }); </code></pre> <p>the above code lets me print the socket.id in console.</p> <p>But when i try to print the socket.id on client side using the following code</p> <pre><code>&lt;script&gt; var socket = io(); var id = socket.io.engine.id; document.write(id); &lt;/script&gt; </code></pre> <p>it gives 'null' as output in the browser.</p>
44,270,370
4
3
null
2017-05-30 19:17:24.33 UTC
15
2019-05-21 15:25:57.36 UTC
null
null
null
null
8,088,207
null
1
24
javascript|node.js|socket.io
67,779
<p>You should wait for the event <code>connect</code> before accessing the <code>id</code> field:</p> <p>With this parameter, you will access the sessionID</p> <pre><code>socket.id </code></pre> <p>Edit with:</p> <p><strong>Client-side:</strong></p> <pre><code>var socketConnection = io.connect(); socketConnection.on('connect', function() { const sessionID = socketConnection.socket.sessionid; // ... }); </code></pre> <p><strong>Server-side:</strong></p> <pre><code>io.sockets.on('connect', function(socket) { const sessionID = socket.id; ... }); </code></pre>
18,860,620
Cannot establish connection to sql-server using pyodbc on Windows 7
<p>I'm using ActivePython 2.7.2.5 on Windows 7.</p> <p>While trying to connect to a sql-server database with the pyodbc module using the below code, I receive the subsequent Traceback. Any ideas on what I'm doing wrong?</p> <p>CODE:</p> <pre><code>import pyodbc driver = 'SQL Server' server = '**server-name**' db1 = 'CorpApps' tcon = 'yes' uname = 'jnichol3' pword = '**my-password**' cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=server;DATABASE=db1;UID=uname;PWD=pword;Trusted_Connection=yes') cursor = cnxn.cursor() cursor.execute("select * from appaudit_q32013") rows = cursor.fetchall() for row in rows: print row </code></pre> <p>TRACEBACK:</p> <pre><code>Traceback (most recent call last): File "pyodbc_test.py", line 9, in &lt;module&gt; cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=server;DATABASE=db1;UID=uname;PWD=pword;Trusted_Connection=yes') pyodbc.Error: ('08001', '[08001] [Microsoft][ODBC SQL Server Driver][DBNETLIB]SQL Server does not exist or access denied. (17) (SQLDriverConnect); [01000] [Microsoft][ODBC SQL Server Driver][DBNETLIB]ConnectionOpen (Connect()). (53)') </code></pre>
18,860,926
6
3
null
2013-09-17 21:59:18.243 UTC
4
2022-02-02 13:58:55.78 UTC
null
null
null
null
2,668,737
null
1
17
python|sql|sql-server|pyodbc|activepython
96,741
<p>You're using a connection string of <code>'DRIVER={SQL Server};SERVER=server;DATABASE=db1;UID=uname;PWD=pword;Trusted_Connection=yes'</code>, you're trying to connect to a server called <code>server</code>, a database called <code>db1</code>, etc. It doesn't use the variables you set before, they're not used.</p> <p>It's possible to pass the connection string parameters as keyword arguments to the <a href="http://code.google.com/p/pyodbc/wiki/Module#connect" rel="noreferrer"><code>connect</code></a> function, so you could use:</p> <pre><code>cnxn = pyodbc.connect(driver='{SQL Server}', host=server, database=db1, trusted_connection=tcon, user=uname, password=pword) </code></pre>
18,904,561
Programmatically convert Excel 2003 files to 2007+
<p>I'm looking for a way to essentially take a folder of excel files that are the old 2003 file extension .xls and convert them into .xlsm. I realize you can go into the excel sheet yourself and manually do it, but is there anyway to do it with code? Specifically using any sort of library?</p>
18,904,633
1
4
null
2013-09-19 20:43:05.247 UTC
10
2019-05-24 15:50:53.9 UTC
null
null
null
null
1,322,858
null
1
11
c#|.net|excel
24,023
<p>This is not my code, but I have used ClosedXML before and it is awesome. I found this on the FAQ asking if it supports Excel 2003 which looks like it should work for you...</p> <p>To clarify, this uses the Office Interop library not closedXML, but I mentioned it incase you had any additional modifications you needed.</p> <pre><code>public void Convert(String filesFolder) { files = Directory.GetFiles(filesFolder); var app = new Microsoft.Office.Interop.Excel.Application(); var wb = app.Workbooks.Open(file); wb.SaveAs(Filename: file + "x", FileFormat: Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLWorkbook); wb.Close(); app.Quit(); } </code></pre> <p><a href="http://closedxml.codeplex.com/wikipage?title=Does%20it%20support%20Excel%202003%20and%20prior%20formats%20%28.xls%29%3F&amp;referringTitle=Documentation" rel="noreferrer">Here is the link</a></p> <p>hope it helps :D</p>
22,530,978
How get next date by passing current Date in java
<p>How do I get the next date(2014/03/21) given the current date(2014/03/20) in Java?</p> <h2>Code:</h2> <pre><code> public static String getNextDate(String curDate) { String nextDate=""; try { //here logic to get nextDate } catch (Exception e) { return nextDate; } return nextDate; } </code></pre>
22,531,179
4
5
null
2014-03-20 11:05:13.99 UTC
1
2014-03-20 11:28:21.587 UTC
2014-03-20 11:11:40.267 UTC
null
2,058,368
null
2,119,934
null
1
2
java|date
43,056
<p>Use SimpleDateFormat to get a Date-object from your string representation, then use Calendar for arithmetics followed by SimpleDateformat to convert the Date-object back to a string representation. (And handle the Exceptions I didn't do)</p> <pre><code>public static String getNextDate(String curDate) { final SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd"); final Date date = format.parse(curDate); final Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.add(Calendar.DAY_OF_YEAR, 1); return format.format(calendar.getTime()); } </code></pre>
8,985,497
Use custom fonts when creating pdf using iReport
<blockquote> <p>iReport Version : 3.7.1</p> </blockquote> <p>I approached this problem in two ways.</p> <blockquote> <p><strong>My first method</strong></p> </blockquote> <p>I am creating a <code>pdf</code> page in <code>iReport</code> and I have one of the fields (from database) set to a font <strong>Gujarati-Salarl</strong> (A font for a regional language of India).</p> <p>This font is available in the font list of <code>iReport</code>. When I hit preview I get the desired output , with the field in the required font style.</p> <p>Everything till here is fine.</p> <p>But the <code>pdf</code> file generated still contains the same original font in English characters.</p> <p>The result is same whether i call the report from the application or from a <code>JAVA</code> file.</p> <blockquote> <p>After a bit of study I found this , <strong>a second method</strong></p> </blockquote> <pre><code>JRProperties.setProperty("net.sf.jasperreports.default.pdf.font.name", "C:\\Gujrati-Saral-1.ttf"); </code></pre> <p>This sets the font of the <code>pdf</code> to the <code>ttf</code> font provided but now the entire <code>pdf</code> comes in the Guarati-saral font which is not what I am looking for..</p> <p>Is there a way to specifically apply this font only to that one particular field?</p> <p>or </p> <p>when going by the second method is there a way to not applying the font <strong>Guarati-saral</strong> to all other fields except the required one ?</p>
8,999,021
4
12
null
2012-01-24 10:48:46.523 UTC
7
2020-07-28 06:00:11.95 UTC
2012-01-24 11:11:18.017 UTC
null
876,298
null
603,633
null
1
19
java|pdf|jasper-reports|itext|ireport
50,796
<p>You should use the <code>Font Extensions</code> mechanism. </p> <p>After creating the font and exporting it as a jar file you should add generated jar file to the application classpath.</p> <p><h3>a) Creating new font in <em>iReport</em> (via Options -> Fonts -> "Install Font" Button)</h3></p> <p><img src="https://i.stack.imgur.com/xOHgV.png" alt="Creating the new font descriptor in iReport"></p> <p><h3>b) Exporting the new font (or the existing one) as jar file in iReport (via Options -> Fonts -> "Export as extension" Button)</h3><img src="https://i.stack.imgur.com/gbdxj.png" alt="enter image description here"></p> <p><h3>a) Creating new font in <em>JasperReports Studio</em> (via Window -> Preferences -> JasperStudio -> Fonts -> "Add" Button)</h3></p> <p><h3>b) Configure your fonts</h3></p> <p><img src="https://i.stack.imgur.com/SpY4p.png" alt="Exporting font as jar file"></p> <p><h3>c) Create JAR with your fonts in it</h3></p> <p><img src="https://i.stack.imgur.com/Ep4ez.png" alt="Export Font Jar"></p> <p><img src="https://i.stack.imgur.com/vVElM.png" alt="enter image description here"></p> <p>You can find more information about using <code>Font Extensions</code> <a href="http://jasperreports.sourceforge.net/sample.reference/fonts/index.html#fontextensions" rel="noreferrer">here</a>.</p>
11,277,117
Selecting a select option by a value passed through a variable
<p>I have an html file that contains the following code :</p> <pre><code>&lt;select id="gouv" name="gouv"&gt; ...some options here... &lt;/select&gt; </code></pre> <p>and the following jQuery code :</p> <pre><code>$('#gouv option[value="myvalue"]').attr("checked","checked"); </code></pre> <p>this as you certainly know sets the option with the value "myvalue" to checked which works perfectly.</p> <p>Now the problem is, I don't know the value of the option I want to set as checked because this value is a result of some function which is stored within a global variable. For simplification sake, after long debugging, I reduced the problem to the following :</p> <pre><code>var ident="myvalue"; $('#gouv option[value=ident]').attr("checked","checked"); </code></pre> <p>and this code doesn't work !</p> <p>I would like to know why it doesn't work, can't we pass a value as a variable ? And is there any workaround to this ?</p>
11,277,122
3
6
null
2012-06-30 19:43:45.617 UTC
2
2022-09-01 15:12:24.933 UTC
2022-09-01 15:12:24.933 UTC
null
1,007,220
null
1,128,583
null
1
6
jquery|html-select
40,310
<pre><code>var ident="myvalue"; $('#gouv option[value="' + ident + '"]').attr("selected", "selected"); </code></pre> <p><code>selected</code> is for <code>&lt;option&gt;</code>, <code>checked</code> is for radio!</p> <p>And better use <code>prop</code> if your jQuery version is > 1.6</p> <pre><code>$('#gouv option[value="' + ident +'"]').prop("selected", true); </code></pre> <p>Note that you better use <code>filter</code> instead of attribute selector:</p> <pre><code>$('#gouv option').filter(function(){ return this.value == indent; }).prop("selected", true); </code></pre> <p><a href="https://stackoverflow.com/a/10651376/601179">Why you should use <code>filter</code> for value</a></p> <p>If you need to support blackberry, they have bug with option.value that jQuery handle:</p> <pre><code>$('#gouv option').filter(function(){ return $(this).val() == indent; }).prop("selected", true); </code></pre>
11,266,150
How to get threshold value from histogram?
<p>I'm writing an Android app in OpenCV to detect blobs. One task is to threshold the image to differentiate the foreground objects from the background (see image). </p> <p>It works fine as long as the image is known and I can manually pass a threshold value to threshold()--in this particular image say, 200. But assuming that the image is not known with the only knowledge that there would be a dark solid background and lighter foreground objects how can I dynamically figure out the threshold value?</p> <p>I've come across the histogram where I can compute the intensity distribution of the grayscale image. But I couldn't find a method to analyze the histogram and choose the value where the objects of interest (lighter) lies. That is; I want to differ the obviously dark background spikes from the lighter foreground spikes--in this case above 200, but in another case could be say, 100 if the objects are grayish.</p> <p><img src="https://i.stack.imgur.com/QU6mZ.jpg" alt="enter image description here"></p>
11,267,991
3
2
null
2012-06-29 17:16:26.797 UTC
9
2018-01-18 16:28:40.023 UTC
null
null
null
null
1,192,843
null
1
12
image-processing|opencv|computer-vision
20,764
<p>If all your images are like this, or can be brought to this style, i think cv2.THRESHOLD_OTSU, ie otsu's tresholding algorithm is a good shot.</p> <p>Below is a sample using Python in command terminal :</p> <pre><code>&gt;&gt;&gt; import cv2 &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; img2 = cv2.imread('D:\Abid_Rahman_K\work_space\sofeggs.jpg',0) &gt;&gt;&gt; ret,thresh = cv2.threshold(img2,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU) &gt;&gt;&gt; ret 122.0 </code></pre> <p><code>ret</code> is the threshold value which is automatically calculated. We just pass '0' as threshold value for this. </p> <p>I got 124 in GIMP ( which is comparable to result we got). And it also removes the noise. See result below:</p> <p><img src="https://i.stack.imgur.com/FTc84.jpg" alt="enter image description here"></p>
10,954,652
Can't change font size for GD imagestring()
<p>I'm trying to follow <a href="http://designgala.com/how-to-add-text-in-an-image/" rel="noreferrer"> this example </a> to generate an image with dynamic text.</p> <p>I wanted to change the size of the font, I put even 100 instead of 4, but it still appears same as before. </p> <p>I'm not very good at PHP. Any sort of help would be appreciated.</p> <p>Here's <a href="http://sushi.usask.ca/passimagemodels/levAclue1.png" rel="noreferrer">an example</a> how small it appears :(</p> <p>Here's my example code -</p> <pre><code> $font = 'arial.ttf'; //FONT SIZE $width = imagefontwidth($font) * strlen($string) ; $height = imagefontheight($font) ; $im = imagecreatefrompng($imageO); $x = imagesx($im) / 2; //PLACEMENT CENTERISH – X $y = imagesy($im) / 2; //PLACEMENT CENTERISH – Y // $backgroundColor = imagecolorallocate ($im, 255, 255, 255); $transparency = 25; imagesavealpha($im, true); $background = imagecolorallocatealpha($im, background_r, background_g, background_b, $transparency); $textColor = imagecolorallocate ($im, 0,0,0); imagestring ($im, $font, $x, $y, $string, $textColor); imagepng($im,$imageN[$k]); $w = imagesx($im); $h = imagesy($im); </code></pre> <p>Thanks </p> <h2>ADDED LATER</h2> <p>Ok now here it is what I have done but as a result, no text is visible in the callout box.</p> <pre><code> $font = 'arial.ttf'; //YOUR FONT SIZE $im = imagecreatefrompng($imageO); $string = "My Text"; $imageN ="NewImage.png"; $transparency = 25; imagesavealpha($im, true); $background = imagecolorallocatealpha($im, background_r, background_g, background_b, $transparency); $textColor = imagecolorallocate ($im, 0,0,0); //imagestring ($im, 5, $x, $y, $string, $textColor); imagettftext($im, 36, 0, 10, 20, $textColor, $font, $string); imagepng($im,$imageN); </code></pre>
10,954,691
5
1
null
2012-06-08 19:03:50.917 UTC
5
2018-04-01 18:30:22.543 UTC
2013-09-27 04:09:41.713 UTC
null
188,331
null
400,859
null
1
19
php|image
51,066
<p>You can't put 100 - <a href="http://php.net/manual/en/function.imagestring.php">http://php.net/manual/en/function.imagestring.php</a></p> <p>Only 1-5 (by default)</p> <p><strong>UPDATE</strong></p> <p>To be able fully control the font size you might want to use <a href="http://php.net/manual/en/function.imagettftext.php">http://php.net/manual/en/function.imagettftext.php</a></p> <p>Example (from the same site):</p> <pre><code>&lt;?php // Set the content-type header('Content-Type: image/png'); // Create the image $im = imagecreatetruecolor(400, 30); // Create some colors $white = imagecolorallocate($im, 255, 255, 255); $grey = imagecolorallocate($im, 128, 128, 128); $black = imagecolorallocate($im, 0, 0, 0); imagefilledrectangle($im, 0, 0, 399, 29, $white); // The text to draw $text = 'Testing...'; // Replace path by your own font path $font = 'arial.ttf'; // Add some shadow to the text imagettftext($im, 20, 0, 11, 21, $grey, $font, $text); // Add the text imagettftext($im, 20, 0, 10, 20, $black, $font, $text); // Using imagepng() results in clearer text compared with imagejpeg() imagepng($im); imagedestroy($im); ?&gt; </code></pre>
10,887,893
Twitter Bootstrap - checkbox columns / columns within form
<p>I have a form field which has a number of checkboxes - how can I display the checkboxes as 3 columns instead of 1?</p> <p>Something similar to this:</p> <p><img src="https://i.stack.imgur.com/iw6CQ.png" alt="enter image description here"></p> <p>I've tried adding a row/span divs inside the <code>&lt;div class="controls"&gt;</code> but it seems to be adding a left padding.</p> <p>I know there is the inline checkbox example in the docs but elements aren't aligned.</p>
10,890,155
1
0
null
2012-06-04 20:28:33.273 UTC
13
2013-10-26 16:31:50.393 UTC
null
null
null
null
528,813
null
1
20
twitter-bootstrap
71,951
<p>You can achieve such a setup by separating the checkbox blocks within the <code>.control-group</code> container instead of each <code>.control</code> container like so:</p> <pre><code>&lt;div class="control-group"&gt; &lt;p class="pull-left"&gt;Payment Types&lt;/p&gt; &lt;div class="controls span2"&gt; &lt;label class="checkbox"&gt; &lt;input type="checkbox" value="option1" id="inlineCheckbox1"&gt; Cash &lt;/label&gt; &lt;label class="checkbox"&gt; &lt;input type="checkbox" value="option2" id="inlineCheckbox2"&gt; Invoice &lt;/label&gt; &lt;label class="checkbox"&gt; &lt;input type="checkbox" value="option3" id="inlineCheckbox3"&gt; Discover &lt;/label&gt; &lt;label class="checkbox"&gt; &lt;input type="checkbox" value="option3" id="inlineCheckbox3"&gt; Financing &lt;/label&gt; &lt;/div&gt; &lt;div class="controls span2"&gt; &lt;label class="checkbox"&gt; &lt;input type="checkbox" value="option1" id="inlineCheckbox1"&gt; Check &lt;/label&gt; &lt;label class="checkbox"&gt; &lt;input type="checkbox" value="option2" id="inlineCheckbox2"&gt; American Express &lt;/label&gt; &lt;label class="checkbox"&gt; &lt;input type="checkbox" value="option3" id="inlineCheckbox3"&gt; MasterCard &lt;/label&gt; &lt;label class="checkbox"&gt; &lt;input type="checkbox" value="option3" id="inlineCheckbox3"&gt; Google Checkout &lt;/label&gt; &lt;/div&gt; &lt;div class="controls span2"&gt; &lt;label class="checkbox"&gt; &lt;input type="checkbox" value="option1" id="inlineCheckbox1"&gt; Traveler's Check &lt;/label&gt; &lt;label class="checkbox"&gt; &lt;input type="checkbox" value="option2" id="inlineCheckbox2"&gt; Diner's Club &lt;/label&gt; &lt;label class="checkbox"&gt; &lt;input type="checkbox" value="option3" id="inlineCheckbox3"&gt; Visa &lt;/label&gt; &lt;label class="checkbox"&gt; &lt;input type="checkbox" value="option3" id="inlineCheckbox3"&gt; Paypal &lt;/label&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Demo: <a href="http://jsfiddle.net/LVFzK/468/show/">http://jsfiddle.net/LVFzK/468/show/</a></p>
11,244,553
Any detailed and specific reasons for Why MongoDB is much faster than SQL DBs?
<p>Ok, there are questions about <a href="https://stackoverflow.com/questions/5186707/why-is-mongodb-so-fast">Why Is MongoDB So Fast</a></p> <p>I appreciate those answers, however, they are quite general. Yes, I know: </p> <ul> <li>MongoDB is document-based, then why being document-based can lead to much higher speed?</li> <li>MongoDB is noSQL, but why noSQL means higher performance?</li> <li>SQL does a lot more than MongoDB for consistency, ACID, etc, but I believe MongoDB is also doing something similar to keep data safe, maintain indexing, etc, right?</li> </ul> <p>Ok, I write this question just in order to find out </p> <ol> <li><strong>what are the detailed and specific reasons</strong> for MongoDB's high performance?</li> <li>What <strong>exactly</strong> SQL does, but MongoDB does not do, so it gains very high performance?</li> <li>If an interviewer (a MongoDB and SQL expert) asks you <code>"Why MongoDB is so fast"</code>, how would you answer? Obviously just answering: <code>"because MongoDB is noSQL"</code> is not enough.</li> </ol> <p>Thanks</p>
11,244,674
3
1
null
2012-06-28 12:21:59.347 UTC
28
2017-07-08 06:56:27.753 UTC
2017-09-22 18:01:22.247 UTC
null
-1
null
759,076
null
1
47
sql|mongodb|performance|nosql
18,730
<p>First, let's compare apples with apples: <strong>Reads and writes with MongoDB are like single reads and writes by primary key on a table with no non-clustered indexes in an RDBMS.</strong></p> <p>So lets benchmark exactly that: <a href="http://mysqlha.blogspot.de/2010/09/mysql-versus-mongodb-yet-another-silly.html" rel="noreferrer">http://mysqlha.blogspot.de/2010/09/mysql-versus-mongodb-yet-another-silly.html</a></p> <p>And it turns out, the speed difference in a fair comparison of exactly the same primitive operation is not big. <strong>In fact, MySQL is slightly faster.</strong> I'd say, they are equivalent.</p> <p>Why? Because actually, both systems are doing similar things in this particular benchmark. Returning a single row, searched by primary key, is actually not that much work. It is a very fast operation. I suspect that cross-process communication overheads are a big part of it.</p> <p>My guess is, that the more tuned code in MySQL outweighs the slightly less systematic overheads of MongoDB (no logical locks and probably some other small things).</p> <p>This leads to an interesting conclusion: <strong>You can use MySQL like a document database and get excellent performance out of it.</strong></p> <hr/> <p>If the interviewer said: "We don't care about documents or styles, we just need a much faster database, do you think we should use MySQL or MongoDB?", what would I answer?</p> <p>I'd recommend to disregard performance for a moment and look at the relative strength of the two systems. Things like scaling (way up) and replication come to mind for MongoDB. For MySQL, there are a lot more features like rich queries, concurrency models, better tooling and maturity and lots more.</p> <p>Basically, you can trade features for performance. Are willing to do that? That is a choice that cannot be made generally. If you opt for performance at any cost, consider tuning MySQL first before adding another technology.</p> <hr/> <p>Here is what happens when a client retrieves a single row/document by primary key. I'll annotate the differences between both systems:</p> <ol> <li>Client builds a binary command (same)</li> <li>Client sends it over TCP (same)</li> <li>Server parses the command (same)</li> <li>Server accesses query plan from cache (SQL only, not MongoDB, not HandlerSocket)</li> <li>Server asks B-Tree component to access the row (same)</li> <li>Server takes a physical readonly-lock on the B-Tree path leading to the row (same)</li> <li>Server takes a logical lock on the row (SQL only, not MongoDB, not HandlerSocket)</li> <li>Server serializes the row and sends it over TCP (same)</li> <li>Client deserializes it (same)</li> </ol> <p>There are only two additional steps for typical SQL-bases RDBMS'es. <strong>That's why there isn't really a difference.</strong></p>
11,213,125
What is the PHP syntax to check "is not null" or an empty string?
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/2659837/check-if-a-variable-is-empty">Check if a variable is empty</a> </p> </blockquote> <p>Simple PHP question:</p> <p>I have this stement:</p> <pre><code>if (isset($_POST["password"]) &amp;&amp; ($_POST["password"]=="$password")) { ...//IF PASSWORD IS CORRECT STUFF WILL HAPPEN HERE } </code></pre> <p>Somewhere above this statement I use the following line in my JavaScript to set the username as a variable both in my JavaScript and in my PHP:</p> <pre><code>uservariable = &lt;?php $user = $_POST['user']; print ("\"" . $user . "\"")?&gt;; </code></pre> <p>What I want to do is add a condition to make sure $user is not null or an empty string (it doesn't have to be any particular value, I just don't want it to be empty. What is the proper way to do this?</p> <p>I know this is a sill question but I have no experience with PHP. Please advise, Thank you!</p>
11,213,171
2
1
null
2012-06-26 17:51:01.073 UTC
17
2012-06-26 22:48:01.11 UTC
2017-05-23 12:00:21.113 UTC
null
-1
null
1,444,609
null
1
66
php|variables|null|conditional-statements
239,517
<p>Null OR an empty string?</p> <pre><code>if (!empty($user)) {} </code></pre> <p>Use empty().</p> <hr> <p>After realizing that $user ~= $_POST['user'] (thanks matt):</p> <pre><code>var uservariable='&lt;?php echo ((array_key_exists('user',$_POST)) || (!empty($_POST['user']))) ? $_POST['user'] : 'Empty Username Input'; ?&gt;'; </code></pre>
11,002,820
Why should we include ttf, eot, woff, svg,... in a font-face
<p>In CSS3 <code>font-face</code>, there are multiple font types included like <code>ttf</code>, <code>eot</code>, <code>woff</code>, <code>svg</code> and <code>cff</code>.</p> <p>Why should we use all of these types?</p> <p>If they are special to different browsers, why is the number of them greater than the number of the major web browsers?</p>
11,002,874
3
0
null
2012-06-12 18:42:07.497 UTC
108
2022-04-07 21:18:51.14 UTC
2022-04-07 21:18:51.14 UTC
null
12,860,895
null
1,440,116
null
1
359
css|fonts|font-face|webfonts
168,290
<h3>Answer in 2019:</h3> <p>Only use WOFF2, or if you need legacy support, WOFF. <a href="https://stackoverflow.com/questions/36105194/are-eot-ttf-and-svg-still-necessary-in-the-font-face-declaration/36110385#36110385">Do not use any other format</a></p> <p>(<code>svg</code> and <code>eot</code> are dead formats, <code>ttf</code> and <code>otf</code> are full system fonts, and should not be used for web purposes)</p> <h3>Original answer from 2012:</h3> <p>In short, font-face is very old, but only recently has been supported by more than IE.</p> <ul> <li><p><code>eot</code> is needed for Internet Explorers that are older than IE9 - they invented the spec, but eot was a proprietary solution.</p></li> <li><p><code>ttf</code> and <code>otf</code> are normal old fonts, so some people got annoyed that this meant anyone could download expensive-to-license fonts for free.</p></li> <li><p>Time passes, SVG 1.1 adds a "fonts" chapter that explains how to model a font purely using SVG markup, and people start to use it. More time passes and it turns out that they are <em>absolutely terrible</em> compared to just a normal font format, and SVG 2 wisely removes the entire chapter again.</p></li> <li><p>Then, <code>woff</code> gets invented by people with quite a bit of domain knowledge, which makes it possible to host fonts in a way that throws away bits that are critically important for system installation, but irrelevant for the web (making people worried about piracy happy) and allows for internal compression to better suit the needs of the web (making users and hosts happy). This becomes the preferred format.</p></li> <li><p><strong>2019 edit</strong> A few years later, <code>woff2</code> gets drafted and accepted, which improves the compression, leading to even smaller files, along with the ability to load a single font "in parts" so that a font that supports 20 scripts can be stored as "chunks" on disk instead, with browsers automatically able to load the font "in parts" as needed, rather than needing to transfer the entire font up front, further improving the typesetting experience.</p></li> </ul> <p>If you don't want to support IE 8 and lower, and iOS 4 and lower, and android 4.3 or earlier, then you can just use WOFF (and WOFF2, a more highly compressed WOFF, for the newest browsers that support it.)</p> <pre><code>@font-face { font-family: 'MyWebFont'; src: url('myfont.woff2') format('woff2'), url('myfont.woff') format('woff'); } </code></pre> <p>Support for <code>woff</code> can be checked at <a href="http://caniuse.com/woff" rel="noreferrer">http://caniuse.com/woff</a><br> Support for <code>woff2</code> can be checked at <a href="http://caniuse.com/woff2" rel="noreferrer">http://caniuse.com/woff2</a> </p>
11,211,007
How do you pass custom environment variable on Amazon Elastic Beanstalk (AWS EBS)?
<p>The Amazon Elastic Beanstalk blurb says:</p> <blockquote> <p>Elastic Beanstalk lets you "open the hood" and retain full control ... even pass environment variables through the Elastic Beanstalk console.</p> </blockquote> <p><a href="http://aws.amazon.com/elasticbeanstalk/">http://aws.amazon.com/elasticbeanstalk/</a></p> <p>How to pass other environment variables besides the one in the Elastic Beanstalk configuration?</p>
17,878,600
7
1
null
2012-06-26 15:42:26.053 UTC
44
2016-11-17 00:32:06.853 UTC
2013-06-07 00:26:37.513 UTC
null
366,967
null
247,474
null
1
133
amazon-web-services|app-config|amazon-elastic-beanstalk
93,172
<p>As a heads up to anyone who uses the <code>.ebextensions/*.config</code> way: nowadays you can <strong>add, edit and remove</strong> environment variables in the Elastic Beanstalk web interface.</p> <p>The variables are under Configuration → Software Configuration:</p> <p><img src="https://i.stack.imgur.com/T1iAv.png" alt="Environment Properties"></p> <p>Creating the vars in <code>.ebextensions</code> like in <a href="https://stackoverflow.com/a/14491294/454094">Onema's answer</a> still works.</p> <p>It can even be preferable, e.g. if you will deploy to another environment later and are afraid of forgetting to manually set them, or if you are ok with committing the values to source control. I use a mix of both.</p>
13,046,899
Unicode symbol that represent "download"
<p>I'm searching for a Unicode char that I can use to symbolize downloads. This is one (U+2B07) looks quite good, but it doesn't seem to be available in default fonts: <a href="http://www.fileformat.info/info/unicode/char/2b07/browsertest.htm" rel="noreferrer">http://www.fileformat.info/info/unicode/char/2b07/browsertest.htm</a></p> <p>Does anyone have an alternative?</p>
13,046,957
2
3
null
2012-10-24 09:59:50.43 UTC
5
2020-02-12 08:55:23.387 UTC
2020-02-12 08:55:23.387 UTC
null
5,891,719
null
242,019
null
1
38
unicode
50,466
<p>You could use ↓ (U+2193), it is available in Arial font. To see a complete list run charmap.exe from windows. It will show you all unicode characters available.</p>
13,087,872
Test Azure Service Bus locally without any subscription or login
<p>Is there a way to play with and discover <strong>Azure Service Bus</strong> on the local emulator without registering to the real Azure Services?</p> <p>I was following a tutorial on the use of the <strong>Azure Service Bus</strong> but at a certain point a <code>Namespace</code> and an <code>Issuer Name</code> and <code>Key</code> is required. I don't have that data since I'm not registered to Azure Services and I don't want to do it now (<em>I will get my trial when I will feel ready to develop/test something real</em>). </p>
13,089,271
2
0
null
2012-10-26 13:26:18.643 UTC
9
2021-11-20 21:48:47.793 UTC
2012-10-26 14:54:14.61 UTC
null
175,679
null
319,135
null
1
42
azure|namespaces|azureservicebus|azure-acs
27,237
<p>Unfortunately there is not an emulated <strong>Azure Service Bus</strong> you can run locally. The Azure Service Bus requires an <a href="https://www.windowsazure.com/en-us/pricing/purchase-options/" rel="nofollow noreferrer">active Azure Subscription</a>. You will need a trial, MSDN subscription, or pay for a pay-as-you go subscription. The relay itself is extremely cheap - <a href="https://www.windowsazure.com/en-us/pricing/details/#header-6" rel="nofollow noreferrer"><code>$0.01 per 10,000 messages</code></a>. Dive in and <a href="https://www.windowsazure.com/en-us/pricing/free-trial/" rel="nofollow noreferrer">start experimenting with your Azure 90 day trial</a>. If you run out of trial, I'm sure MS would work with you if you could justify the extension.</p> <p>One of the reasons I expect that it doesn't work without a subscription is that the service bus requires <a href="http://msdn.microsoft.com/en-us/library/windowsazure/gg429786.aspx" rel="nofollow noreferrer"><strong>Azure ACS</strong></a> for authentication (<em>this is the source of the <code>Issuer Name</code> and <code>Key</code> you are looking for</em>) which <a href="https://stackoverflow.com/questions/11602428/implementing-acs-on-emulator-web-application/11602802#11602802">also lacks emulation</a> to my knowledge.</p>
13,131,400
Logging variable data with new format string
<p>I use logging facility for python 2.7.3. <a href="http://docs.python.org/2/howto/logging.html" rel="noreferrer">Documentation for this Python version say</a>:</p> <blockquote> <p>the logging package pre-dates newer formatting options such as str.format() and string.Template. These newer formatting options are supported...</p> </blockquote> <p>I like 'new' format with curly braces. So i'm trying to do something like:</p> <pre><code> log = logging.getLogger("some.logger") log.debug("format this message {0}", 1) </code></pre> <p>And get error:</p> <blockquote> <p>TypeError: not all arguments converted during string formatting</p> </blockquote> <p>What I miss here?</p> <p>P.S. I don't want to use </p> <pre><code>log.debug("format this message {0}".format(1)) </code></pre> <p>because in this case the message is always being formatted regardless of logger level.</p>
13,131,690
10
7
null
2012-10-30 00:00:38.677 UTC
33
2021-10-02 01:30:59.183 UTC
2017-12-22 14:35:45.303 UTC
null
42,223
null
548,894
null
1
94
python|python-2.7|string-formatting
71,527
<p><strong>EDIT:</strong> take a look at the <a href="https://stackoverflow.com/a/24683360/4279"><code>StyleAdapter</code> approach in @Dunes' answer</a> unlike this answer; it allows to use alternative formatting styles without the boilerplate while calling logger's methods (debug(), info(), error(), etc).</p> <hr> <p>From the docs — <a href="http://docs.python.org/3/howto/logging-cookbook.html#use-of-alternative-formatting-styles" rel="noreferrer">Use of alternative formatting styles</a>:</p> <blockquote> <p>Logging calls (logger.debug(), logger.info() etc.) only take positional parameters for the actual logging message itself, with keyword parameters used only for determining options for how to handle the actual logging call (e.g. the exc_info keyword parameter to indicate that traceback information should be logged, or the extra keyword parameter to indicate additional contextual information to be added to the log). So you cannot directly make logging calls using str.format() or string.Template syntax, because internally the logging package uses %-formatting to merge the format string and the variable arguments. There would no changing this while preserving backward compatibility, since all logging calls which are out there in existing code will be using %-format strings.</p> </blockquote> <p>And:</p> <blockquote> <p>There is, however, a way that you can use {}- and $- formatting to construct your individual log messages. Recall that for a message you can use an arbitrary object as a message format string, and that the logging package will call str() on that object to get the actual format string.</p> </blockquote> <p>Copy-paste this to <code>wherever</code> module:</p> <pre><code>class BraceMessage(object): def __init__(self, fmt, *args, **kwargs): self.fmt = fmt self.args = args self.kwargs = kwargs def __str__(self): return self.fmt.format(*self.args, **self.kwargs) </code></pre> <p>Then:</p> <pre><code>from wherever import BraceMessage as __ log.debug(__('Message with {0} {name}', 2, name='placeholders')) </code></pre> <p>Note: actual formatting is delayed until it is necessary e.g., if DEBUG messages are not logged then the formatting is not performed at all.</p>
11,412,410
Losing scope when using ng-include
<p>I have this module routes:</p> <pre><code>var mainModule = angular.module('lpConnect', []). config(['$routeProvider', function ($routeProvider) { $routeProvider. when('/home', {template:'views/home.html', controller:HomeCtrl}). when('/admin', {template:'views/admin.html', controller:AdminCtrl}). otherwise({redirectTo:'/connect'}); }]); </code></pre> <p>Home HTML:</p> <pre><code>&lt;div ng-include src="views.partial1"&gt;&lt;/div&gt; </code></pre> <p><code>partial1</code> HTML:</p> <pre><code>&lt;form ng-submit="addLine()"&gt; &lt;input type="text" ng-model="lineText" size="30" placeholder="Type your message here"&gt; &lt;/form&gt; </code></pre> <p><code>HomeCtrl</code>:</p> <pre><code>function HomeCtrl($scope, $location, $window, $http, Common) { ... $scope.views = { partial1:"views/partial1.html" }; $scope.addLine = function () { $scope.chat.addLine($scope.lineText); $scope.lines.push({text:$scope.lineText}); $scope.lineText = ""; }; ... } </code></pre> <p>In the <code>addLine</code> function <code>$scope.lineText</code> is <code>undefined</code>, this can be resolved by adding <code>ng-controller="HomeCtrl"</code> to <code>partial1.html</code>, however it causes the controller to be called twice. What am I missing here?</p>
11,417,113
4
0
null
2012-07-10 11:31:06.283 UTC
62
2017-09-06 10:18:05.797 UTC
2017-09-06 10:15:30 UTC
null
4,642,212
null
1,115,237
null
1
181
javascript|html|angularjs|angularjs-scope|angularjs-ng-include
113,821
<p>This is because of <code>ng-include</code> which creates a new child scope, so <code>$scope.lineText</code> isn’t changed. I think that <code>this</code> refers to the current scope, so <code>this.lineText</code> should be set.</p>
16,775,207
Search multiple models at once with Ransack
<p>I have a search form in the header of my app and I would like to use this search form to search through multiple models within the application.</p> <p>For example a request like <code>/search?q=rails</code> should trigger a search through multiple models like <code>Work</code>, <code>Project</code>, <code>User</code> and their defined attributes. I wanted to use Ransack because I already use it on the <code>Work</code> model in a different area of the app.</p> <p>I think I don't quite understand Ransack yet and the documentation always points out that you have to define <code>@q = MyModel.search(params[:q])</code> to use it in the form <code>search_form_for @q</code>. Is there a way where you don't have to define a specific model in advance? And just pass in the parameter name like <code>search_form_for :q</code>?</p>
16,775,326
1
0
null
2013-05-27 14:20:41.143 UTC
10
2021-07-23 07:18:42.05 UTC
null
null
null
null
587,320
null
1
20
ruby-on-rails|ruby|search|ransack
8,631
<p>Okay, after asking the question the answer popped into my head.</p> <p>Instead of the <code>search_form_for</code> helper I'm now just using the <code>form_tag</code> helper in the following way:</p> <pre><code>&lt;%= form_tag search_path, method: :get do %&gt; &lt;%= text_field_tag :q, params[:q] %&gt; &lt;%= end %&gt; </code></pre> <p>and in the search action I just do:</p> <pre><code>q = params[:q] @works = Work.search(name_cont: q).result @projects = Project.search(name_cont: q).result @users = User.search(name_cont: q).result </code></pre> <p>This works for me. I hope this also helps someone else.</p>
25,887,799
Using Source Tree, rebase with conflict, rebase doesn't work after conflict resovled
<p>I'm using <a href="http://www.sourcetreeapp.com/">SourceTree</a> as my git tool on Windows.</p> <p>I have a <em>main</em> branch and a <em>feature</em> branch and I can't get SourceTree to perform a rebase when I have a conflict.</p> <p><em>main</em> looks like:</p> <blockquote> <p>c1 -> c2 -> c4 -> c5</p> </blockquote> <p><em>feature</em> looks like:</p> <blockquote> <p>c1-> c2 -> c3</p> </blockquote> <p>I want to rebase <em>feature</em> so it will be:</p> <blockquote> <p>c1 -> c2-> c4-> c5-> c3</p> </blockquote> <p>There is a conflict between <em>c3</em> and <em>c5</em>. I can resolve the conflict, but when I commit the changes I get a <em>HEAD</em> tag and looking at my graph I can see that <em>feature</em> branch wasn't rebased. </p> <p>How can I get the rebase to work?</p>
25,888,325
2
4
null
2014-09-17 10:11:02.997 UTC
19
2020-08-30 16:37:50.3 UTC
null
null
null
user4007604
null
null
1
77
git|rebase|atlassian-sourcetree|merge-conflict-resolution
33,521
<p>Unfortunately the UX path for the resolving conflicts during a rebase is quite poor in <a href="/questions/tagged/atlassian-sourcetree" class="post-tag" title="show questions tagged &#39;atlassian-sourcetree&#39;" rel="tag">atlassian-sourcetree</a>. </p> <p>After you have resolved the conflict and have all of your changes in the staging area, instead of clicking <em>commit</em>, go to <em>Actions</em>-> <em>Continue Rebase</em>:</p> <p><img src="https://i.stack.imgur.com/1N2JB.png" alt="enter image description here"></p>
4,106,031
Rspec: how can I check if a call to a method of another class is called?
<p>I can I check if FeedItem::populate_from_friend_to_user is called inside the user class?</p> <pre><code> it "should auto populate feed after user.add_friend" do @user.add_friend(@friend1) @user.should_receive('FeedItem::populate_from_friend_to_user').with(@friend1, @user) end </code></pre> <p>With the above code I get:</p> <pre><code>undefined method `populate_from_friend_to_user' for :FeedItem:Symbol </code></pre>
4,106,154
2
0
null
2010-11-05 13:00:44.27 UTC
4
2018-08-12 21:43:57.54 UTC
2010-11-05 13:15:27.6 UTC
null
285,289
null
87,610
null
1
34
ruby-on-rails|rspec2
44,661
<p>You should not know <strong>where</strong> the method is called, just <strong>if</strong> the method is called.. You just know if the method is call:</p> <p><strong>Before RSpec 3</strong></p> <pre><code> it "should auto populate feed after user.add_friend" do FeedItem.should_receive(:populate_from_friend_to_user).with(@friend1, @user) @user.add_friend(@friend1) end </code></pre> <p><strong>In RSpec 3</strong> the syntax is </p> <pre><code>expect(Object).to receive(:method).with(params) </code></pre>