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
16,611,497
How can I get the name of an html page in Javascript?
<p>I have an html page and I would like inside the html page to retrieve the name of the html document via Javascript. Is that possible?</p> <p>e.g. name of html <code>document = &quot;indexOLD.html&quot;</code></p>
16,611,569
11
2
null
2013-05-17 14:26:28.733 UTC
19
2021-12-08 04:54:02.663 UTC
2020-12-17 12:08:36.787 UTC
null
1,783,163
null
805,660
null
1
74
javascript|html
134,287
<pre><code>var path = window.location.pathname; var page = path.split("/").pop(); console.log( page ); </code></pre>
20,409,172
How to display verbatim inline r code with backticks using Rmarkdown?
<p>By doubling the backticks in Markdown, it is easy to render some text in code style including the backticks, such as: <code>`r 2+2`</code>. But how to do that with <em>RMarkdown</em> ? By the same way we can display <code>`t 2+2`</code>, but replacing <code>t</code> with <code>r</code> executes the R code <code>2+2</code>.</p> <p>The only way I have found so far is:</p> <pre><code>&lt;p&gt;&lt;code class="r"&gt;`&lt;/code&gt;&lt;code class="r"&gt;r 2+2`&lt;/code&gt;&lt;/p&gt; </code></pre> <p>Not very convenient. Maybe I should define a new css for doing that more conveniently ?</p>
20,419,016
5
10
null
2013-12-05 19:47:01.76 UTC
7
2020-01-10 12:50:32.153 UTC
2013-12-05 23:52:57.29 UTC
null
1,100,107
null
1,100,107
null
1
37
r|markdown|knitr|r-markdown
11,594
<p>Here is a trick that I use. First, note <code>\x60</code> is <code>`</code>:</p> <pre><code>&gt; cat('\x60', '\n') ` </code></pre> <p>Then you write</p> <pre><code>`r '\x60r foo+bar\x60'` </code></pre> <p>which will give you <code>`r foo+bar`</code> in the markdown output, but that will become <code>r foo+bar</code> in the HTML output, so you need to protect the backticks in markdown, using two (or more) backticks. Then you end up with this hairball:</p> <pre><code>`` `r '\x60r foo+bar\x60'` `` </code></pre> <p>Your own solution is good, but I'd just define</p> <pre><code>rinline &lt;- function(code) { sprintf('``` `r %s` ```', code) } </code></pre> <p>Also see <a href="https://yihui.name/en/2017/11/knitr-verbatim-code-chunk/" rel="noreferrer">this post</a> for another trick.</p>
62,950,667
Is there any need to switch to modules when migrating to Java 9 or later?
<p>We're currently migrating from Java 8 to Java 11. However, upgrading our services was less painful, than we anticipated. We basically only had to change the version number in our <code>build.gradle</code> file and the services were happily up and running. We upgraded libraries as well as (micro) services that use those libs. No problems until now.</p> <p>Is there any <em>need</em> to actually switch to modules? This would generate needless costs IMHO. Any suggestion or further reading material is appreciated.</p> <p>To clarify, are there any consequences if Java 9+ code is used without introducing modules? E.g. can it become incompatible with other code?</p>
62,959,016
2
5
null
2020-07-17 09:01:43.037 UTC
28
2022-06-03 22:09:39.6 UTC
2022-06-03 22:09:39.6 UTC
null
45,112
null
3,705,861
null
1
98
java|java-11|java-9|java-platform-module-system
11,935
<p>No.</p> <p>There is no need to switch to modules.</p> <p>There has never been a need to switch to modules.</p> <p>Java 9 and later releases support traditional JAR files on the traditional class path, via the concept of the unnamed module, and will likely do so until the heat death of the universe.</p> <p>Whether to start using modules is entirely up to you.</p> <p>If you maintain a large legacy project that isn’t changing very much, then it’s probably not worth the effort.</p> <p>If you work on a large project that’s grown difficult to maintain over the years then the clarity and discipline that modularization brings could be beneficial, but it could also be a lot of work, so think carefully before you begin.</p> <p>If you’re starting a new project then I highly recommend starting with modules if you can. Many popular libraries have, by now, been <a href="https://github.com/sormuras/modules" rel="noreferrer">upgraded to be modules</a>, so there’s a good chance that all of the dependencies that you need are already available in modular form.</p> <p>If you maintain a library then I strongly recommend that you upgrade it to be a module if you haven’t done so already, and if all of your library’s dependencies have been converted.</p> <p>All this isn’t to say that you won’t encounter a few stumbling blocks when moving past Java 8. Those that you do encounter will, however, likely have nothing to do with modules <em>per se</em>. The most common migration problems that we’ve heard about since we released Java 9 in 2017 have to do with <a href="https://openjdk.java.net/jeps/322" rel="noreferrer">changes to the syntax of the version string</a> and to the <a href="https://openjdk.java.net/jeps/260" rel="noreferrer">removal or encapsulation of internal APIs</a> (<em>e.g.</em>, <code>sun.misc.Base64Decoder</code>) for which public, supported replacements have been available for years.</p>
4,303,154
Connecting via named pipe from windows service (session#0) to desktop app (session #1)
<p><strong>Given</strong>:<br> - the application - desktop GUI (WPF) .NET app<br> - windows service watching for application (.NET also) </p> <p>The windows service periodically "pings" application to get sure it's healthy (and if it's not winservice will restart it).<br> I was going to implement "pinging" via named pipes. To make things simpler I decided to do it with WCF. The application hosts a WCF-service (one operation Ping returning something). The windows service is a client for this WCF-service, invokes it periodically based on a timer.</p> <p>That's all in Windows 7.<br> Windows service is running under LocalService (in session#0).<br> Desktop application is running under currently logged in user (in session#1). </p> <p><strong>The problem</strong>:<br> Windows service can't see WCF endpoint (with NetNamedPipeBinding) created in and being listened in desktop application. That means that on call via wcf proxy I get this exception: "The pipe endpoint 'net.pipe://localhost/HeartBeat' could not be found on your local machine"</p> <p>I'm sure code is ok, because another desktop application (in session#1) can see the endpoint.</p> <p>Obviously here I'm dealing with some security stuff for Win32 system object isolation. But I believe there should be a way to workaround restrictions I've encountered with.<br> I can sacrifice WCF approach and go the raw NamedPipe way.</p>
4,307,552
2
3
null
2010-11-29 11:07:21.013 UTC
9
2011-09-09 10:56:17.097 UTC
2010-11-29 11:52:55.067 UTC
null
27,703
null
27,703
null
1
8
wcf|security|winapi|named-pipes|netnamedpipebinding
9,470
<p>An easier solution might be to use a WCF duplex contract with the Windows service hosting the WCF service. The client App would call an operation on the service to register itself, when it starts up. The Ping would then be an operation invoked periodically by the service on the client's callback contract, to which the App would respond.</p> <p>Service visibility works this way round, because the Windows service can run with SeCreateGlobalPrivilege, and so the shared memory object via which the pipe name is published by the service can be created in the Global kernel namespace, visible to other sessions. Interactive applications can't easily get that privilege in Windows7, so WCF services in such applications fall back to publishing the pipe in the Local kernel namespace, visible only within their own session.</p>
10,122,696
Dropdownlist Reset SelectedValue
<p>I have a DropDownList connected to an ObjectDataSource. In my page load i set the selectedvalue to a specific value depending on the case. How can I in my method selectedindexchanged "reset" the selectedvalue so you still can choose from the other options? Or should I not use selectedvalue to set the defaultvalue of the dropdownlist?</p> <pre><code> &lt;asp:DropDownList ID="DropDownList" runat="server" DataSourceID="ObjectDataSource" DataTextField="Type" DataValueField="TypeId" AutoPostBack="true" onselectedindexchanged="DropDownList_SelectedIndexChanged" &gt; &lt;/asp:DropDownList&gt; protected void Page_Load(object sender, EventArgs e) { int default = category.TypeId; DropDownList.SelectedIndex = default; } protected void DropDownList_SelectedIndexChanged(object sender, EventArgs e) { int id = int.Parse(DropDownList.SelectedValue); Session["id"] = id; } </code></pre>
10,122,767
4
1
null
2012-04-12 11:32:34.363 UTC
null
2018-10-26 13:22:45.873 UTC
2012-04-12 12:01:24.677 UTC
null
1,242,460
null
1,242,460
null
1
6
asp.net|drop-down-menu|selectedvalue
45,168
<p>You should only <code>DataBind</code> your <code>DropDownList</code> and set its default value <code>if(!IsPostBack)</code>:</p> <pre><code>protected void Page_Load(Object sender, EventArgs e) { if(!IsPostBack) { int default = category.TypeId; DropDownList.SelectedValue = default.ToString(); } } </code></pre> <p><a href="http://msdn.microsoft.com/en-us/library/system.web.ui.page.ispostback.aspx" rel="nofollow"><code>Page.IsPostBack</code> Property</a> </p>
9,856,924
Jquery .when and multiple .load
<p>I want to have one callback function after actions are done, I'm trying something like this:</p> <pre><code>$.when( $('#detail1').load('/getInfo.php'), $('#detail2').load('/getOther.php') ).then(function(a,b){ alert("done"); }); </code></pre> <p>The problem is that the callback function is firing before the actions are finished.</p>
9,857,034
2
2
null
2012-03-25 00:30:59.087 UTC
10
2014-11-12 10:29:47.187 UTC
2012-03-25 00:44:31.76 UTC
null
797,033
null
797,033
null
1
12
javascript|ajax|jquery
6,273
<p>This is because jQuery.when() expects jQuery.Deferred instances while load() returns an jQuery instance (see <a href="http://api.jquery.com/jQuery.when/">http://api.jquery.com/jQuery.when/</a> and <a href="http://api.jquery.com/load/">http://api.jquery.com/load/</a>).</p> <p>You can work around this issue:</p> <pre><code>// Create two Deferred instances that can be handed to $.when() var d1 = new $.Deferred(); var d2 = new $.Deferred(); // Set up the chain of events... $.when(d1, d2).then(function() { alert('done'); }); // And finally: Make the actual ajax calls: $('#detail1').load('/getInfo.php', function() { d1.resolve(); }); $('#detail2').load('/getOther.php', function() { d2.resolve(); }); </code></pre>
9,746,896
Converting a lambda expression into a unique key for caching
<p>I've had a look at other questions similar to this one but I couldn't find any workable answers.</p> <p>I've been using the following code to generate unique keys for storing the results of my linq queries to the cache.</p> <pre><code> string key = ((LambdaExpression)expression).Body.ToString(); foreach (ParameterExpression param in expression.Parameters) { string name = param.Name; string typeName = param.Type.Name; key = key.Replace(name + ".", typeName + "."); } return key; </code></pre> <p>It seems to work fine for simple queries containing integers or booleans but when my query contains nested constant expressions e.g.</p> <pre><code>// Get all the crops on a farm where the slug matches the given slug. (x =&gt; x.Crops.Any(y =&gt; slug == y.Slug) &amp;&amp; x.Deleted == false) </code></pre> <p>The key returned is thus:</p> <blockquote> <p>(True AndAlso (Farm.Crops.Any(y => (value(OzFarmGuide.Controllers.FarmController+&lt;>c__DisplayClassd).slug == y.Slug)) AndAlso (Farm.Deleted == False)))</p> </blockquote> <p>As you can see any crop name I pass will give the same key result. Is there a way I can extract the value of the given parameter so that I can differentiate between my queries?</p> <p>Also converting the <code>y</code> to say the correct type name would be nice.....</p>
9,749,779
4
7
null
2012-03-17 03:01:20.267 UTC
8
2013-08-06 08:10:05.597 UTC
2012-03-19 09:26:50.863 UTC
null
427,899
null
427,899
null
1
12
c#|linq|caching|linq-expressions
4,563
<p>As Polity and Marc said in their comments, what you need is a partial evaluator of the LINQ expression. You can read how to do that using <a href="http://msdn.microsoft.com/en-us/library/system.linq.expressions.expressionvisitor.aspx" rel="noreferrer"><code>ExpressionVisitor</code></a> in <a href="http://blogs.msdn.com/b/mattwar/archive/2007/08/01/linq-building-an-iqueryable-provider-part-iii.aspx" rel="noreferrer">Matt Warren's <em>LINQ: Building an IQueryable Provider - Part III</em></a>. The article <a href="http://petemontgomery.wordpress.com/2008/08/07/caching-the-results-of-linq-queries/" rel="noreferrer"><em>Caching the results of LINQ queries</em> by Pete Montgomery</a> (linked to by Polity) describes some more specifics regarding this kind of caching, e.g. how to represent collections in the query.</p> <p>Also, I'm not sure I would rely on <code>ToString()</code> like this. I think it's meant mostly for debugging purposes and it might change in the future. The alternative would be creating your own <code>IEqualityComparer&lt;Expression&gt;</code> that can create a hash code for any expression and can compare two expressions for equality. I would probably do that using <code>ExpressionVisitor</code> too, but doing so would be quite tedious.</p>
10,203,777
Div opacity based on scrollbar position
<p>Find an example of how to fade out a <code>div</code> when the scroll bar reaches a certain position <a href="http://jsfiddle.net/xXxXR/" rel="nofollow noreferrer">here</a>. But it's not a smooth throttle-type fade. Here is the code from that jsfiddle:</p> <pre><code>var divs = $('.social, .title'); $(window).scroll(function(){ if($(window).scrollTop()&lt;10){ divs.fadeIn("fast"); } else { divs.fadeOut("fast"); } });​ </code></pre> <p>I want the opacity percentage to to reflect the position of the scrollbar. For instance when the scroll bar is at very top position, the div opacity is 100%. When I scroll down 35px I want the opacity of the div to fade down to 0%</p> <p>Perhaps a technique could be when div A is at 35px from top, div B = 100% opacity. When div A is 0px from top, div B = 0% opacity. And have it smoothly fade at all stages in between.</p> <p>Thanks!</p> <p>UPDATE: Thanks for all the help most of them work fairly well, but I really need it to work within the 35px range. So I have created a new example which will make it very clear how it should work.<br> <a href="http://jsfiddle.net/J8XaX/1/" rel="nofollow noreferrer">http://jsfiddle.net/J8XaX/1/</a></p> <p>UPDATE 2: mobile devices: I tried this on my iPhone and the fade doesn't work smoothly. The way it works is if you slide halfway and release your finger, then the opacity goes down. But if you try to scroll smoothly it goes from 100% opacity directly to 0% opacity. Wondering if there is any way to fix this??</p> <p>Thanks!!</p>
10,203,888
4
0
null
2012-04-18 06:12:07.903 UTC
8
2016-08-10 23:32:29.5 UTC
2016-08-10 23:32:29.5 UTC
null
3,257,186
null
433,575
null
1
14
javascript|jquery|scrollbar|opacity|fade
33,027
<p>try something like</p> <pre><code>var divs = $('.social, .title'), limit = 35; /* scrolltop value when opacity should be 0 */ $(window).on('scroll', function() { var st = $(this).scrollTop(); /* avoid unnecessary call to jQuery function */ if (st &lt;= limit) { divs.css({ 'opacity' : (1 - st/limit) }); } }); </code></pre> <p>when scrolltop reaches <code>35px</code> then opacity of divs is <code>1 - 35/35 = 0</code></p> <p>example fiddle: <a href="http://jsfiddle.net/wSkmL/1/" rel="noreferrer">http://jsfiddle.net/wSkmL/1/</a><br> your fiddle updated: <a href="http://jsfiddle.net/J8XaX/2/" rel="noreferrer">http://jsfiddle.net/J8XaX/2/</a> (I've changed 35 to 130px to achieve the effect you wrote in the orange div)</p>
9,648,934
INSERT INTO if not exists SQL server
<p>I have a database structured as follows:</p> <p><strong>users</strong></p> <pre><code>userid (Primary Key) username </code></pre> <p><strong>group</strong></p> <pre><code>groupid (PK) groupName </code></pre> <p><strong>user_groups</strong></p> <pre><code>userid (Foreign Key) groupid (Foreign Key) </code></pre> <p>The first time a user logs in I would like their info to be added to the users table. So essentially the logic I would like to have if</p> <pre><code>if (//users table does not contain username) { INSERT INTO users VALUES (username); } </code></pre> <p>How can I do this intelligently using SQL Server/C# ?</p>
9,649,040
8
0
null
2012-03-10 18:15:27.03 UTC
7
2019-10-17 13:02:03.21 UTC
2012-03-10 18:54:02.033 UTC
null
13,302
null
963,156
null
1
14
c#|sql|sql-server|database-design
47,975
<p>Or using the new MERGE syntax:</p> <pre><code>merge into users u using ( select 'username' as uname ) t on t.uname = u.username when not matched then insert (username) values (t.uname); </code></pre>
9,895,130
Recursively remove empty elements and subarrays from a multi-dimensional array
<p>I can't seem to find a simple, straight-forward solution to the age-old problem of removing empty elements from arrays in PHP.</p> <p>My input array may look like this: </p> <pre><code>Array ( [0] =&gt; Array ( [Name] =&gt; [EmailAddress] =&gt; ) ) </code></pre> <p>(And so on, if there's more data, although there may not be...)</p> <p>If it looks like the above, I want it to be <strong>completely empty</strong> after I've processed it.</p> <p>So <code>print_r($array);</code> would output:</p> <pre><code>Array ( ) </code></pre> <p>If I run <code>$arrayX = array_filter($arrayX);</code> I still get the <strong>same</strong> <code>print_r</code> output. Everywhere I've looked suggests this is the simplest way of removing empty array elements in PHP5, however.</p> <p>I also tried <code>$arrayX = array_filter($arrayX,'empty_array');</code> but I got the following error:</p> <blockquote> <p>Warning: array_filter() [function.array-filter]: The second argument, 'empty_array', should be a valid callback</p> </blockquote> <p>What am I doing wrong?</p>
9,895,183
8
9
null
2012-03-27 18:09:56.393 UTC
10
2022-02-19 16:41:46.423 UTC
2017-10-16 23:28:57.253 UTC
null
2,943,403
null
199,700
null
1
25
php|arrays|multidimensional-array|filtering|is-empty
34,178
<p>Try using <a href="http://php.net/manual/en/function.array-map.php" rel="noreferrer"><code>array_map()</code></a> to apply the filter to every array in <code>$array</code>:</p> <pre><code>$array = array_map('array_filter', $array); $array = array_filter($array); </code></pre> <p>Demo: <a href="http://codepad.org/xfXEeApj" rel="noreferrer">http://codepad.org/xfXEeApj</a></p>
9,760,548
Php Sockets vs Streams
<p>I think php sockets and php streams are overlapping each other.<br> I've managed to make a CLI PHP chat client and a server, using either sockets or streams.</p> <p>Here some illustrating code lines:<br> Using sockets:</p> <pre><code>... $main_socket = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die("Cannot create socket.\n"); @socket_bind($main_socket, $host, $port) or die("Could not bind to socket $host : $port.\n"); @socket_listen($main_socket, 5) or die("Could not set up socket listener\n"); ... </code></pre> <p>Using streams:</p> <pre><code>... $main_socket = @stream_socket_server ("tcp://$host:$port", $errno, $errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN) or die("Cannot create socket.\n"); $clients = array($main_socket); $clients_peername = array(array('port' =&gt; $port)); fputs(STDOUT, "Waiting for connections...\n"); ... </code></pre> <p>The point here is that a client and a server could be made using either sockets functions, either streams functions.</p> <p>I know that Streams is part of PHP core and Sockets is an extension.</p> <p>My question(s) is(are):</p> <ul> <li>What is the difference between sockets and streams when referring to sockets programming?</li> <li>Are there any capabilities, related to sockets programming, that one can have while the other one cannot?</li> </ul>
9,783,856
2
2
null
2012-03-18 17:35:16.86 UTC
18
2015-06-19 14:00:00.553 UTC
2012-03-18 20:32:42.283 UTC
null
383,609
null
598,154
null
1
27
php|sockets|stream
16,182
<p>According to the manual, the sockets extension is more low-level. For instance, whith sockets you have finer-grained control when creating one, and can choose SOCK_STREAM, SOCK_DGRAM, SOCK_SEQPACKET, etc.</p> <blockquote> <p>The socket extension implements a low-level interface to the socket communication functions based on the popular BSD sockets, providing the possibility to act as a socket server as well as a client.</p> <p>For a more generic client-side socket interface, see stream_socket_client(), stream_socket_server(), fsockopen(), and pfsockopen().</p> </blockquote> <p>source: <a href="http://www.php.net/manual/en/intro.sockets.php">http://www.php.net/manual/en/intro.sockets.php</a></p>
9,909,038
Formatting hexadecimal Number to short UUID in JavaScript
<p>I have a hexadecimal number in javascript. For display purposes, I would like to format the string as:</p> <pre><code>ffffffff-ffff-ffff 00000000-0000-01ff </code></pre> <p><code>(8 digits)-(4 digits)-(4 digits)</code> with padded zeros on the front</p> <p>I've been trying to write my own loop to format an arbitrary hexadecimal number into this format, but this seems like something that should be available in JavaScript already.</p> <p>Is there a built-in way to format a hexadecimal number in JavaScript?</p>
9,909,166
7
1
null
2012-03-28 13:57:28.773 UTC
5
2020-04-21 18:55:40.197 UTC
2020-04-21 16:27:13.407 UTC
null
9,801,830
null
1,108,487
null
1
27
javascript|formatting|hex|uuid
43,122
<p>I would do a two-step process:</p> <p>1) convert number to 16 digit hex with leading zeros:</p> <pre class="lang-javascript prettyprint-override"><code>var i = 12345; // your number var h = ("000000000000000" + i.toString(16)).substr(-16); </code></pre> <p>2) add dashes</p> <pre class="lang-javascript prettyprint-override"><code>var result = h.substr(0, 8)+'-'+h.substr(8,4)+'-'+h.substr(12,4); </code></pre>
10,019,050
Couldn't translate Date to spanish with Locale("es_ES")
<p>I'm trying to do a simple date format, it does work great, it's very easy, but the problem is the language. I used the locale "es_ES" to get "Miércoles" instead of "Wednesday" and sorts like that but i failed.</p> <p>Here's my code:</p> <pre><code>SimpleDateFormat formato = new SimpleDateFormat("EEEE d 'de' MMMM 'de' yyyy", new Locale("es_ES")); String fecha = formato.format(new Date()); </code></pre> <p>The EXPECTED value of the <code>fecha</code> string is:</p> <blockquote> <p>Miércoles 4 de Abril de 2012</p> </blockquote> <p>but i'm still getting:</p> <blockquote> <p>Wednesday 4 de April de 2012</p> </blockquote> <p>What am I doing wrong?</p>
10,019,105
5
2
null
2012-04-04 20:51:26.47 UTC
5
2019-11-12 14:45:08.833 UTC
2016-07-11 23:03:51.317 UTC
null
642,706
null
1,056,488
null
1
43
java|date|locale
72,404
<p>"es_ES" is a language + country. You must specify each part separately.</p> <p>The constructors for <a href="http://docs.oracle.com/javase/8/docs/api/java/util/Locale.html" rel="noreferrer"><code>Locale</code></a> are:</p> <ul> <li><a href="http://docs.oracle.com/javase/8/docs/api/java/util/Locale.html#Locale-java.lang.String-" rel="noreferrer">Locale(String language)</a><br />Construct a locale from a language code.</li> <li><a href="http://docs.oracle.com/javase/8/docs/api/java/util/Locale.html#Locale-java.lang.String-java.lang.String-" rel="noreferrer">Locale(String language, String country)</a><br />Construct a locale from language, country.</li> <li><a href="http://docs.oracle.com/javase/8/docs/api/java/util/Locale.html#Locale-java.lang.String-java.lang.String-java.lang.String-" rel="noreferrer">Locale(String language, String country, String variant)</a><br />Construct a locale from language, country, variant.</li> </ul> <p>You want <code>new Locale("es", "ES");</code> to get the Locale that goes with es_ES.</p> <p>However, it would be better to use <a href="https://docs.oracle.com/javase/8/docs/api/java/util/Locale.html#forLanguageTag-java.lang.String-" rel="noreferrer"><code>Locale.forLanguageTag("es-ES")</code></a>, using the well-formed IETF BCP 47 language tag <code>es-ES</code> (with <code>-</code> instead of <code>_</code>), since that method can return a cached <code>Locale</code>, instead of always creating a new one.</p>
10,199,233
Can sphinx link to documents that are not located in directories below the root document?
<p>I am using Sphinx to document a non-Python project. I want to distribute <code>./doc</code> folders in each submodule, containing <code>submodule_name.rst</code> files to document that module. I then want to suck those files into the master hierarchy to create a spec for the entire design. </p> <p>I.e.: </p> <pre><code>Project docs spec project_spec.rst conf.py modules module1 docs module1.rst src module2 docs module2.rst src </code></pre> <p>I attempted to include files in the master <code>project_spec.rst</code> document toctree like this: </p> <pre><code>.. toctree:: :numbered: :maxdepth: 2 Module 1 &lt;../../modules/module1/docs/module1&gt; </code></pre> <p>However this error message results:</p> <blockquote> <p>WARNING: toctree contains reference to nonexisting document u'modules/module1/docs/module1'</p> </blockquote> <p>Is it not possible to use <code>../</code> in a document path somehow?</p> <p>Update: Added conf.py location</p> <p>Update: Other than the include trick below, this is still (2019) not possible. There is an open issue that keeps getting pushed forward: <a href="https://github.com/sphinx-doc/sphinx/issues/701" rel="noreferrer">https://github.com/sphinx-doc/sphinx/issues/701</a></p>
17,217,041
8
4
null
2012-04-17 21:12:24.89 UTC
21
2021-05-06 13:55:12.257 UTC
2020-06-24 23:46:15.037 UTC
null
10,794,031
null
373,348
null
1
115
python|python-sphinx|symlink|toctree
49,124
<p>Yes, you can!</p> <p>In lieu of a symlink (which won't work on Windows), create a stub document that has nothing in it but a <code>.. include::</code> directive.</p> <p>I ran into this trying to link to a README file that was in the top of the source tree. I put the following in a file called <code>readme_link.rst</code>:</p> <pre><code>.. include:: ../README </code></pre> <p>Then in <code>index.rst</code>, I made the toctree look like:</p> <pre><code>Contents: .. toctree:: :maxdepth: 2 readme_link other_stuff </code></pre> <p>And now I have a link to my release notes on my index page.</p> <p>Thanks to <a href="http://reinout.vanrees.org/weblog/2010/12/08/include-external-in-sphinx.html">http://reinout.vanrees.org/weblog/2010/12/08/include-external-in-sphinx.html</a> for the suggestion</p>
7,904,892
Remove form assistant from keyboard in iPhone standalone web app
<p>Is it possible to remove the form assistant from the iPhone popup keyboard in a standalone web app? I know the general consensus is that it's not possible in Mobile Safari, but a standalone app runs in a <code>UIWebView</code>, and functions differently in several ways (<a href="http://www.mobilexweb.com/blog/apple-phonegap-html5-nitro" rel="noreferrer">example</a>), so I'm hoping this might be possible.</p> <p>You can see it here right above the keyboard:</p> <p><img src="https://i.stack.imgur.com/Uz2Ly.png" alt="enter image description here"></p> <p>The Previous and Next buttons cycle between <code>&lt;form&gt;</code> inputs. But I have a single <code>&lt;input&gt;</code> element, so they are disabled. The Done button hides the keyboard, but since I have a height-flexible <code>&lt;ul&gt;</code> (that takes up the space between the keyboard and the <code>&lt;input&gt;</code>), and I have nothing else on this page, it serves no purpose.</p> <p>On a tiny screen, and with almost half the screen taken up by the keyboard, the 44 pixels that make up this toolbar are a huge waste of space (an entire <code>&lt;li&gt;</code>'s worth).</p> <p>Native iOS apps <em>can</em> remove it, so I know it's at least possible on the phone, I've just not discovered a way to do it in a web app. This is from the Facebook app and the page is very similar to mine:</p> <p><img src="https://i.stack.imgur.com/yWuXb.png" alt="enter image description here"></p> <p>I've tried using an <code>&lt;input&gt;</code> not wrapped in a <code>&lt;form&gt;</code> and also using a <code>contenteditable</code> <code>&lt;div&gt;</code>, but the results were the same. There are several custom <code>-webkit-</code> styles to control various aspects of the web app interface, but they are poorly documented, and a search turned up nothing on this.</p> <p>Any way to remove the form assistant in a web app?</p>
9,027,715
3
0
null
2011-10-26 15:20:48.723 UTC
9
2012-10-04 19:54:34.167 UTC
2012-01-28 05:20:30.567 UTC
null
918,414
null
918,414
null
1
16
iphone|html|css|iphone-web-app|iphone-standalone-web-app
9,646
<p>All signs point to this <a href="http://groups.google.com/group/rhomobile/browse_thread/thread/bafefd764b7094fd/4425d2e36e329d4d?show_docid=4425d2e36e329d4d" rel="nofollow noreferrer">not being possible</a>, including <a href="https://stackoverflow.com/q/6485997/848090">several</a> <a href="https://stackoverflow.com/q/7472465/848090">questions</a> <a href="https://stackoverflow.com/q/8459282/848090">here</a>.</p>
11,551,195
Intent from notification does not have extras
<p>This seem to be a common problem and I went through all the related questions I could find already: <a href="https://stackoverflow.com/questions/5628382/activity-isnt-picking-up-new-intent">Activity isn&#39;t picking up new intent</a>, <a href="https://stackoverflow.com/questions/10456655/why-extra-data-integer-is-not-sent-in-android-notification-intent">Why extra data (integer) is not sent in android notification intent?</a>, <a href="https://stackoverflow.com/questions/7370324/notification-passes-old-intent-extras/9330144">Notification passes old Intent Extras</a>, <a href="https://stackoverflow.com/questions/7098893/cant-put-extras-for-an-intent-in-notification">Can&#39;t put extras for an intent in notification</a>, <a href="https://stackoverflow.com/questions/3009059/android-pending-intent-notification-problem">android pending intent notification problem</a>; but still cannot figure this out.</p> <p>Problem is the same. I set a notification with a PendingIntent carrying some extra information and I don't get it on the other side.</p> <p>Here is the code for generating the notification:</p> <pre><code>Notification notification = new Notification(R.drawable.icon, getResources().getString(R.string.notification_ticker), System.currentTimeMillis()); notification.flags = Notification.FLAG_AUTO_CANCEL | Notification.FLAG_ONLY_ALERT_ONCE; Intent start_test = new Intent(this, MyActivity.class); start_test.putExtra("start_test", true); start_test.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent pi = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), start_test, PendingIntent.FLAG_CANCEL_CURRENT); notification.setLatestEventInfo(this, getResources().getString(R.string.notification_title), getResources().getString(R.string.notification_content, expired), pi); nm.notify(NOTIFICATION_ID, notification); </code></pre> <p>And on the other side:</p> <pre><code>boolean start_test=getIntent().getBooleanExtra("start_test", false); </code></pre> <p>The bundle is actually not there (getExtras() returns null).</p> <p>I tried the different flags for <code>PendingIntent.getActivity</code> (<code>FLAG_UPDATE_CURRENT</code>, <code>FLAG_CANCEL_CURRENT</code>, <code>FLAG_ONE_SHOT</code>), none of those helped.</p> <p>As shown in the code, I use getCurrentMillis to make sure the requestID changes....</p> <p>Also found that in MyActivity, <code>onCreate</code> and <code>onNewIntent</code> are not getting called. only <code>onResume</code> is. Even though the <code>FLAG_ACTIVITY_NEW_TASK</code> is set... ?</p> <p>Am I missing something very simple ?</p>
11,563,909
7
6
null
2012-07-18 22:16:59.88 UTC
15
2021-07-27 07:38:45.87 UTC
2017-05-23 12:32:23.14 UTC
null
-1
null
347,565
null
1
57
android|android-intent|android-notifications
40,547
<p>Setting <code>FLAG_ACTIVITY_NEW_TASK</code> for the notification Intent will cause the following:</p> <ul> <li><p>If the activity is <strong>not</strong> already running in a task, a new task will be started and the Intent will be delivered to the activity in <code>onCreate()</code></p></li> <li><p>However, if the activity is already running in a task, that task will be brought to the foreground. That's all. The Intent will <strong>not</strong> be delivered and <code>onNewIntent()</code> will not be called.</p></li> </ul> <p>If you want the Intent to <strong>actually be delivered</strong> you need to specify:</p> <pre><code>start_test.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP); </code></pre> <p>It makes <strong>no difference</strong> whether the <code>launchMode</code> of the activity is <code>singleTop</code> or not, you still must specify <code>Intent.FLAG_ACTIVITY_SINGLE_TOP</code> in the Intent.</p> <p><strong>Note:</strong> If the activity is already running in a task and the activity is <strong>not</strong> on top of the activity stack in that task, the task will be brought to the foreground. That's all. The Intent will <strong>not</strong> be delivered. The only way to make this happen would be to add <code>Intent.FLAG_ACTIVITY_CLEAR_TOP</code> to the other 2 flags, but this may not be what you want to happen (depends on your specific scenario).</p> <p>See my (still) open issue on Google code at <a href="http://code.google.com/p/android/issues/detail?id=17137">http://code.google.com/p/android/issues/detail?id=17137</a></p>
20,055,984
Excel VBA - Union of Ranges and its sub ranges
<p>Consider the following vba macro in excel</p> <pre><code>Sub foo() Dim aRng As Range: Set aRng = ActiveSheet.Range("A1:J1") Dim bRng As Range: Set bRng = ActiveSheet.Range("A4:J4") Dim cRng As Range: Set cRng = ActiveSheet.Range("A10:J10") Dim uRng As Range: Set uRng = Union(aRng, bRng, cRng) uRng.Style = "Good" uRng.Cells(2, 1).Style = "Bad" End sub </code></pre> <p>The results are: Rows 1 <code>"A1:J1", "A4:J4", "A10:J10"</code> are <em>good</em> and cell <code>"A2"</code> is <em>bad</em>. I expected cell <code>"A4"</code> to be <em>bad</em>. "A2" is not in <code>uRng</code>; why would it be returned by <code>uRng.Cells(2,1)</code>?</p> <p>Other oddities: <code>uRng.Rows.Count = 1</code> and <code>uRng.Columns.Count = 10</code>. Am I wrong to expect <code>uRng</code> to be 3x10 range? Or is that undefined because the positions of <code>aRng</code>, <code>bRng</code>, and <code>cRng</code> to each other is not specified?</p>
20,056,378
2
4
null
2013-11-18 19:19:35.46 UTC
null
2016-05-30 21:04:34.03 UTC
2016-05-30 21:04:34.03 UTC
null
396,458
null
2,340,690
null
1
7
vba|excel
38,937
<p>They are actually treated as three separate ranges, accessible from <code>uRng</code> via the <code>Range.Areas</code> property: </p> <p><a href="http://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.range.areas(v=office.11).ASPX" rel="nofollow">http://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.range.areas(v=office.11).ASPX</a></p> <p>Using your example, here's how to get <code>A4</code> included, as the first cell in the second range: </p> <pre><code>Sub foo() Dim aRng As Range: Set aRng = ActiveSheet.Range("A1:J1") Dim bRng As Range: Set bRng = ActiveSheet.Range("A4:J4") Dim cRng As Range: Set cRng = ActiveSheet.Range("A10:J10") Dim uRng As Range: Set uRng = Union(aRng, bRng, cRng) uRng.Style = "Good" uRng.Areas(2).Cells(1, 1).Style = "Bad" End Sub </code></pre> <p>also, the code below will give you same result:</p> <pre><code>Sub foo2() Dim uRng As Range: Set uRng = [A1:J1,A4:J4,A10:J10] uRng.Style = "Good" uRng.Areas(2).Cells(1, 1).Style = "Bad" End Sub </code></pre>
20,165,590
Make a clickable link with onclick but without href=#?
<p>I have a set of clickable identifiers on my page. About hundred, like 'cat1', 'cat2', 'dog1', 'dog2', 'dog3' etc. Then I have a <code>function IDClick(id) {}</code></p> <p>I need those identifiers clickable in HTML, to achieve that I used <code>&lt;a&gt;</code> tag with <code>onclick</code></p> <pre><code>&lt;a onclick=IDClick(id)&gt;id&lt;/a&gt; </code></pre> <p>now it works, but the cursor will not change when it is hovered over the clickable element.</p> <p>So I try to add <code>href=#</code></p> <pre><code>&lt;a href=# onclick=IDClick(id)&gt;id&lt;/a&gt; </code></pre> <p>Now the cursor is OK, but when I click the item, the URL in the browser location bar will change. This is not desired.</p> <p>How to get the mixed behavior?</p> <p>I do not need underline as well.</p>
20,165,637
5
10
null
2013-11-23 17:33:43.923 UTC
5
2020-04-27 23:40:16.2 UTC
2017-05-23 10:23:13.243 UTC
null
1,968,972
null
1,968,972
null
1
35
javascript|html
59,528
<p>You can use CSS to force the cursor to change on hover of the clickable element:</p> <pre><code>.myClickableThingy { cursor: pointer; } </code></pre> <p>And then you can switch back to <code>&lt;span&gt;</code>s or whatever of element you were using before <code>&lt;a&gt;</code> tags.</p>
3,476,963
Windows Phone 7 (WP7) Change a button's background color on click
<p>This seems like a really, really simple problem, but I can't figure it out. The culprit appears to be WP7's default style. It changes the background color to white when a button is clicked, then back to the button's default background.</p> <p>The problem I have is I want to change the button's background when the button is clicked. I can't find any possible way to do this.</p> <p>I've tried setting the background in code, but that does nothing. I think it's being overwritten by the default style.</p> <p>I've tried using a Property Change behavior in Blend, but that has the exact same result.</p> <p>I've tried creating a new visual state for the button and setting that on click, but that's a little buggy and has a large overhead for the number of buttons I'm dealing with. Also, it didn't work.</p> <p>I can set other buttons' background on a click event, just not the button being clicked.</p> <p>This is such an annoying roadblock! I'm sure this is a one line of code kind of answer. :)</p>
3,478,896
4
2
null
2010-08-13 12:51:16.817 UTC
26
2012-12-02 13:02:35.3 UTC
null
null
null
null
295,259
null
1
37
windows|expression-blend|windows-phone-7
33,161
<p>What you need to do is create a button template that modifies the Pressed visual state.</p> <p>In blend, select your button, click the menu item "Object"->"Edit Template"->"Edit a Copy..." and a new template is created. In the States window, select the Pressed visual state in the CommonStates visual state group. Now select ButtonBackground in the object hierarchy and edit the background brush in the Properties window.</p> <p>I edited the Pressed state's background to be a solid Cyan-ish color and ended up with something like this XAML.</p> <pre class="lang-xml prettyprint-override"><code>&lt;phone:PhoneApplicationPage ...&gt; &lt;phone:PhoneApplicationPage.Resources&gt; &lt;Style x:Key="ButtonStyle1" TargetType="Button"&gt; &lt;Setter Property="Template"&gt; &lt;Setter.Value&gt; &lt;ControlTemplate TargetType="Button"&gt; &lt;Grid Background="Transparent"&gt; &lt;VisualStateManager.VisualStateGroups&gt; &lt;VisualStateGroup x:Name="CommonStates"&gt; &lt;VisualState x:Name="Normal"/&gt; &lt;VisualState x:Name="MouseOver"/&gt; &lt;VisualState x:Name="Pressed"&gt; &lt;Storyboard&gt; &lt;ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="ContentContainer"&gt; &lt;DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneBackgroundBrush}"/&gt; &lt;/ObjectAnimationUsingKeyFrames&gt; &lt;ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="BorderBrush" Storyboard.TargetName="ButtonBackground"&gt; &lt;DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneForegroundBrush}"/&gt; &lt;/ObjectAnimationUsingKeyFrames&gt; &lt;ColorAnimation Duration="0" To="Cyan" Storyboard.TargetProperty="(Border.Background).(SolidColorBrush.Color)" Storyboard.TargetName="ButtonBackground" d:IsOptimized="True"/&gt; &lt;/Storyboard&gt; &lt;/VisualState&gt; &lt;VisualState x:Name="Disabled"&gt; &lt;Storyboard&gt; &lt;ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="ContentContainer"&gt; &lt;DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneDisabledBrush}"/&gt; &lt;/ObjectAnimationUsingKeyFrames&gt; &lt;ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="BorderBrush" Storyboard.TargetName="ButtonBackground"&gt; &lt;DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneDisabledBrush}"/&gt; &lt;/ObjectAnimationUsingKeyFrames&gt; &lt;/Storyboard&gt; &lt;/VisualState&gt; &lt;/VisualStateGroup&gt; &lt;/VisualStateManager.VisualStateGroups&gt; &lt;Border x:Name="ButtonBackground" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="0" Margin="{StaticResource PhoneTouchTargetOverhang}" Background="Black"&gt; &lt;ContentControl x:Name="ContentContainer" ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" Foreground="{TemplateBinding Foreground}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Padding="{TemplateBinding Padding}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/&gt; &lt;/Border&gt; &lt;/Grid&gt; &lt;/ControlTemplate&gt; &lt;/Setter.Value&gt; &lt;/Setter&gt; &lt;/Style&gt; &lt;/phone:PhoneApplicationPage.Resources&gt; &lt;Grid x:Name="LayoutRoot" Background="Transparent"&gt; &lt;Button Content="Button" Style="{StaticResource ButtonStyle1}"/&gt; &lt;/Grid&gt; &lt;/phone:PhoneApplicationPage&gt; </code></pre>
3,614,212
jQuery, get html of a whole element
<p>I wish to get the entire html of a selected element not just it's contents. .html() uses javascripts innerHTML() method according to the documentation. HTML:</p> <pre><code>&lt;div id="divs"&gt; &lt;div id="div1"&gt; &lt;p&gt;Some Content&lt;/p&gt; &lt;/div&gt; &lt;div id="div2"&gt; &lt;p&gt;Some Content&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Using <code>$('#divs:first').html();</code> will return just the paragraph element. I want to get the html for the whole element, like so:</p> <pre><code> &lt;div id="div1"&gt; &lt;p&gt;Some Content&lt;/p&gt; &lt;/div&gt; </code></pre> <p>I can't use .parent because this will return html of both child divs.</p>
3,614,218
4
0
null
2010-09-01 00:27:45.193 UTC
24
2019-09-06 12:17:05.937 UTC
2015-08-20 02:55:34.03 UTC
null
13,860
null
181,637
null
1
146
jquery|html
214,542
<p>You can clone it to get the entire contents, like this:</p> <pre><code>var html = $("&lt;div /&gt;").append($("#div1").clone()).html(); </code></pre> <p>Or make it a plugin, most tend to call this "outerHTML", like this:</p> <pre><code>jQuery.fn.outerHTML = function() { return jQuery('&lt;div /&gt;').append(this.eq(0).clone()).html(); }; </code></pre> <p>Then you can just call:</p> <pre><code>var html = $("#div1").outerHTML(); </code></pre>
3,790,728
Performance Tests of Serializations used by WCF Bindings
<p>I have the following object:</p> <pre><code>public partial class Game { public bool Finished { get; set; } public Guid GameGUID { get; set; } public long GameID { get; set; } public bool GameSetup { get; set; } public Nullable&lt;int&gt; MaximumCardsInDeck { get; set; } public Player Player { get; set; } public Player Player1 { get; set; } public bool Player1Connected { get; set; } public bool Player1EnvironmentSetup { get; set; } public long Player1ID { get; set; } public int Player1Won { get; set; } public bool Player2Connected { get; set; } public bool Player2EnvironmentSetup { get; set; } public long Player2ID { get; set; } public int Player2Won { get; set; } public int Round { get; set; } public Nullable&lt;int&gt; RoundsToWin { get; set; } public bool Started { get; set; } public string StateXML { get; set; } public Nullable&lt;DateTime&gt; TimeEnded { get; set; } public Nullable&lt;int&gt; TimeLimitPerTurn { get; set; } public byte[] TimeStamp { get; set; } public Nullable&lt;DateTime&gt; TimeStarted { get; set; } } </code></pre> <p>This class gonna be filled with some <strong>test data</strong>.</p> <p>I need the to compare the <strong>Performance</strong> of different Serializers used by the different forms of bindings for WCF Services: <UL> <LI>basicHttpBinding => <strong>SoapFormatter</strong> (TextFormatter?) <LI>binaryBinding => <strong>BinaryFormatter</strong> <LI><strong>XMLFormatter</strong> </UL></p> <p>What i need to do in detail is: <UL> <LI>Get to now the <strong>size</strong> of the Object being serialized <LI>Get to now the <strong>size</strong> after serizlization <LI><strong>Time</strong> to serialize <LI><strong>Time</strong> to deserialize </UL></p> <p>I already tried some stuff, but i am struggling a bit. Maybe there is already some simple code for this kind of measurement.</p>
3,793,091
5
1
null
2010-09-24 20:26:34.26 UTC
16
2012-11-21 14:46:54.793 UTC
null
null
null
null
247,081
null
1
12
c#|.net|wcf|performance|wcf-binding
14,900
<p>OK; I'll bite... here's some raw <em>serializer</em> metrics (emph: you may need to consider base-64/MTOM to get overall bandwidth requirements, plus whatever fixed overheads (both space and CPU) that WCF adds), however; results first:</p> <pre><code>BinaryFormatter Length: 1314 Serialize: 6746 Deserialize: 6268 XmlSerializer Length: 1049 Serialize: 3282 Deserialize: 5132 DataContractSerializer Length: 911 Serialize: 1411 Deserialize: 4380 NetDataContractSerializer Length: 1139 Serialize: 2014 Deserialize: 5645 JavaScriptSerializer Length: 528 Serialize: 12050 Deserialize: 30558 (protobuf-net v2) Length: 112 Serialize: 217 Deserialize: 250 </code></pre> <p>(so I conclude protobuf-net v2 the winner...)</p> <p>Numbers updated with .NET 4.5 and current library builds, on a newer machine:</p> <pre><code>BinaryFormatter Length: 1313 Serialize: 2786 Deserialize: 2407 XmlSerializer Length: 1049 Serialize: 1265 Deserialize: 2165 DataContractSerializer Length: 911 Serialize: 574 Deserialize: 2011 NetDataContractSerializer Length: 1138 Serialize: 850 Deserialize: 2535 JavaScriptSerializer Length: 528 Serialize: 8660 Deserialize: 8468 (protobuf-net v2) Length: 112 Serialize: 78 Deserialize: 134 </code></pre> <p>with test rig (compiled with optimizations, run at command line):</p> <p>(and note I had to invent the <code>Player</code> class and some sample data):</p> <pre><code>using System; using System.Diagnostics; using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.Text; using System.Web.Script.Serialization; using System.Xml.Serialization; using ProtoBuf.Meta; static class Program { static void Main() { var orig = new Game { Finished = true, GameGUID = Guid.NewGuid(), GameID = 12345, GameSetup = false, MaximumCardsInDeck = 20, Player = new Player { Name = "Fred"}, Player1 = new Player { Name = "Barney"}, Player1Connected = true, Player1EnvironmentSetup = true, Player1ID = 12345, Player1Won = 3, Player2Connected = true, Player2EnvironmentSetup = true, Player2ID = 23456, Player2Won = 0, Round = 4, RoundsToWin = 5, Started = true, StateXML = "not really xml", TimeEnded = null, TimeLimitPerTurn = 500, TimeStamp = new byte[] {1,2,3,4,5,6}, TimeStarted = DateTime.Today}; const int LOOP = 50000; GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced); GC.WaitForPendingFinalizers(); using (var ms = new MemoryStream()) { var ser = new BinaryFormatter(); Console.WriteLine(); Console.WriteLine(ser.GetType().Name); ser.Serialize(ms, orig); Console.WriteLine("Length: " + ms.Length); ms.Position = 0; ser.Deserialize(ms); var watch = Stopwatch.StartNew(); for (int i = 0; i &lt; LOOP; i++) { ms.Position = 0; ms.SetLength(0); ser.Serialize(ms, orig); } watch.Stop(); Console.WriteLine("Serialize: " + watch.ElapsedMilliseconds); watch = Stopwatch.StartNew(); for (int i = 0; i &lt; LOOP; i++) { ms.Position = 0; ser.Deserialize(ms); } watch.Stop(); Console.WriteLine("Deserialize: " + watch.ElapsedMilliseconds); } GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced); GC.WaitForPendingFinalizers(); using (var ms = new MemoryStream()) { var ser = new XmlSerializer(typeof(Game)); Console.WriteLine(); Console.WriteLine(ser.GetType().Name); ser.Serialize(ms, orig); Console.WriteLine("Length: " + ms.Length); ms.Position = 0; ser.Deserialize(ms); var watch = Stopwatch.StartNew(); for (int i = 0; i &lt; LOOP; i++) { ms.Position = 0; ms.SetLength(0); ser.Serialize(ms, orig); } watch.Stop(); Console.WriteLine("Serialize: " + watch.ElapsedMilliseconds); watch = Stopwatch.StartNew(); for (int i = 0; i &lt; LOOP; i++) { ms.Position = 0; ser.Deserialize(ms); } watch.Stop(); Console.WriteLine("Deserialize: " + watch.ElapsedMilliseconds); } GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced); GC.WaitForPendingFinalizers(); using (var ms = new MemoryStream()) { var ser = new DataContractSerializer(typeof(Game)); Console.WriteLine(); Console.WriteLine(ser.GetType().Name); ser.WriteObject(ms, orig); Console.WriteLine("Length: " + ms.Length); ms.Position = 0; ser.ReadObject(ms); var watch = Stopwatch.StartNew(); for (int i = 0; i &lt; LOOP; i++) { ms.Position = 0; ms.SetLength(0); ser.WriteObject(ms, orig); } watch.Stop(); Console.WriteLine("Serialize: " + watch.ElapsedMilliseconds); watch = Stopwatch.StartNew(); for (int i = 0; i &lt; LOOP; i++) { ms.Position = 0; ser.ReadObject(ms); } watch.Stop(); Console.WriteLine("Deserialize: " + watch.ElapsedMilliseconds); } GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced); GC.WaitForPendingFinalizers(); using (var ms = new MemoryStream()) { var ser = new NetDataContractSerializer(); Console.WriteLine(); Console.WriteLine(ser.GetType().Name); ser.Serialize(ms, orig); Console.WriteLine("Length: " + ms.Length); ms.Position = 0; ser.Deserialize(ms); var watch = Stopwatch.StartNew(); for (int i = 0; i &lt; LOOP; i++) { ms.Position = 0; ms.SetLength(0); ser.Serialize(ms, orig); } watch.Stop(); Console.WriteLine("Serialize: " + watch.ElapsedMilliseconds); watch = Stopwatch.StartNew(); for (int i = 0; i &lt; LOOP; i++) { ms.Position = 0; ser.Deserialize(ms); } watch.Stop(); Console.WriteLine("Deserialize: " + watch.ElapsedMilliseconds); } GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced); GC.WaitForPendingFinalizers(); { var sb = new StringBuilder(); var ser = new JavaScriptSerializer(); Console.WriteLine(); Console.WriteLine(ser.GetType().Name); ser.Serialize(orig, sb); Console.WriteLine("Length: " + sb.Length); ser.Deserialize(sb.ToString(), typeof(Game)); var watch = Stopwatch.StartNew(); for (int i = 0; i &lt; LOOP; i++) { sb.Length = 0; ser.Serialize(orig, sb); } watch.Stop(); string s = sb.ToString(); Console.WriteLine("Serialize: " + watch.ElapsedMilliseconds); watch = Stopwatch.StartNew(); for (int i = 0; i &lt; LOOP; i++) { ser.Deserialize(s, typeof(Game)); } watch.Stop(); Console.WriteLine("Deserialize: " + watch.ElapsedMilliseconds); } GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced); GC.WaitForPendingFinalizers(); using (var ms = new MemoryStream()) { var ser = CreateProto(); Console.WriteLine(); Console.WriteLine("(protobuf-net v2)"); ser.Serialize(ms, orig); Console.WriteLine("Length: " + ms.Length); ms.Position = 0; ser.Deserialize(ms, null, typeof(Game)); var watch = Stopwatch.StartNew(); for (int i = 0; i &lt; LOOP; i++) { ms.Position = 0; ms.SetLength(0); ser.Serialize(ms, orig); } watch.Stop(); Console.WriteLine("Serialize: " + watch.ElapsedMilliseconds); watch = Stopwatch.StartNew(); for (int i = 0; i &lt; LOOP; i++) { ms.Position = 0; ser.Deserialize(ms, null, typeof(Game)); } watch.Stop(); Console.WriteLine("Deserialize: " + watch.ElapsedMilliseconds); } Console.WriteLine(); Console.WriteLine("All done; any key to exit"); Console.ReadKey(); } static TypeModel CreateProto() { var meta = TypeModel.Create(); meta.Add(typeof(Game), false).Add(Array.ConvertAll(typeof(Game).GetProperties(),prop=&gt;prop.Name)); meta.Add(typeof(Player), false).Add(Array.ConvertAll(typeof(Player).GetProperties(),prop=&gt;prop.Name)); return meta.Compile(); } } [Serializable, DataContract] public partial class Game { [DataMember] public bool Finished { get; set; } [DataMember] public Guid GameGUID { get; set; } [DataMember] public long GameID { get; set; } [DataMember] public bool GameSetup { get; set; } [DataMember] public Nullable&lt;int&gt; MaximumCardsInDeck { get; set; } [DataMember] public Player Player { get; set; } [DataMember] public Player Player1 { get; set; } [DataMember] public bool Player1Connected { get; set; } [DataMember] public bool Player1EnvironmentSetup { get; set; } [DataMember] public long Player1ID { get; set; } [DataMember] public int Player1Won { get; set; } [DataMember] public bool Player2Connected { get; set; } [DataMember] public bool Player2EnvironmentSetup { get; set; } [DataMember] public long Player2ID { get; set; } [DataMember] public int Player2Won { get; set; } [DataMember] public int Round { get; set; } [DataMember] public Nullable&lt;int&gt; RoundsToWin { get; set; } [DataMember] public bool Started { get; set; } [DataMember] public string StateXML { get; set; } [DataMember] public Nullable&lt;DateTime&gt; TimeEnded { get; set; } [DataMember] public Nullable&lt;int&gt; TimeLimitPerTurn { get; set; } [DataMember] public byte[] TimeStamp { get; set; } [DataMember] public Nullable&lt;DateTime&gt; TimeStarted { get; set; } } [Serializable, DataContract] public class Player { [DataMember] public string Name { get; set; } } </code></pre>
3,899,097
How to find the closest 2 points in a 100 dimensional space with 500,000 points?
<p>I have a database with 500,000 points in a 100 dimensional space, and I want to find the closest 2 points. How do I do it?</p> <p>Update: Space is Euclidean, Sorry. And thanks for all the answers. BTW this is not homework.</p>
3,899,182
5
11
null
2010-10-10 05:06:02.827 UTC
12
2010-10-12 19:34:29.963 UTC
2010-10-12 19:34:29.963 UTC
null
4,279
null
123,574
null
1
16
algorithm|performance|nearest-neighbor|pca|approximate-nn-searching
3,341
<p>You could try the <a href="http://www.cs.umd.edu/~mount/ANN/" rel="noreferrer">ANN library</a>, but that only gives reliable results up to 20 dimensions.</p>
3,633,089
pthread sleep linux
<p>I am creating a program with multiple threads using pthreads. </p> <p>Is <code>sleep()</code> causing the process (all the threads) to stop executing or just the thread where I am calling <code>sleep</code>? </p>
3,633,101
5
0
null
2010-09-03 04:44:34.143 UTC
6
2020-07-04 10:29:30.52 UTC
2015-06-05 12:57:57.403 UTC
null
638,994
null
434,718
null
1
28
c++|multithreading|pthreads
93,600
<p>Just the thread. The <a href="http://www.opengroup.org/onlinepubs/9699919799/functions/sleep.html" rel="noreferrer">POSIX documentation for sleep()</a> says:</p> <blockquote> <p>The <code>sleep()</code> function shall cause the calling <strong>thread</strong> to be suspended from execution...</p> </blockquote>
3,967,644
Django admin: How to display a field that is marked as editable=False' in the model?
<p>Even though a field is marked as <code>'editable=False'</code> in the model, I would like the admin page to display it. Currently it hides the field altogether.. How can this be achieved ?</p>
3,967,891
6
0
null
2010-10-19 11:00:46.35 UTC
27
2022-02-08 08:49:17.603 UTC
null
null
null
null
192,001
null
1
124
django|django-admin
57,521
<p>Use <a href="http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.readonly_fields" rel="noreferrer">Readonly Fields</a>. Like so (for django >= 1.2):</p> <pre><code>class MyModelAdmin(admin.ModelAdmin): readonly_fields=('first',) </code></pre>
3,240,458
How to increment a datetime by one day?
<p>How to increment the day of a datetime?</p> <pre><code>for i in range(1, 35) date = datetime.datetime(2003, 8, i) print(date) </code></pre> <p>But I need pass through months and years correctly? Any ideas?</p>
3,240,486
8
0
null
2010-07-13 18:58:04.683 UTC
40
2020-11-27 01:05:40.643 UTC
2018-11-05 20:21:48.723 UTC
null
674,039
null
375,373
null
1
225
python|datetime
274,524
<pre><code>date = datetime.datetime(2003,8,1,12,4,5) for i in range(5): date += datetime.timedelta(days=1) print(date) </code></pre>
3,404,045
How to protect software from system date-time changes?
<p>I would like to add licensing system to application. For example: user buys license for 1 month and after that program expires (Kinda Anti-Virus style?).</p> <p>Problem is that application is supposed to run in systems which may or <strong>may not be connected to internet</strong>, so how to protect from date-time changes?</p> <p>Storing app startup and close times in encrypted file won't work as date can be changed (with program uptime of 8 hours per day, would be possible to extend license to almost 300% in ideal case - change time to app close time + 1 second before launching program).</p> <p>Another question - is there any way to protect from software like <a href="http://en.wikipedia.org/wiki/Deep_Freeze_(software)" rel="noreferrer">http://en.wikipedia.org/wiki/Deep_Freeze_(software)</a>? (maybe scan drivers?)</p> <p><strong>EDIT:</strong><br> I'm currently using smart card to store licensing information and will use code virtualizer on critical functions (I know about making breakpoints on API calls and inspecting passed data - don't need to hide that data, just to ensure things go as planned)</p>
3,445,947
13
2
null
2010-08-04 09:04:43.39 UTC
14
2014-01-25 14:14:09.983 UTC
2010-08-12 08:04:32.86 UTC
null
421,752
null
421,752
null
1
22
windows|security|datetime|licensing|offline
21,879
<p><strong>Step 1:</strong> Create trial_tracker entry in an encrypted format in a windows registry and in file.</p> <p><strong>Step 2:</strong> Assign app install timestamp ( yyyy-mm-dd-hh-mm-ss ) to trial_tracker</p> <p>Whenever app starts, check if current system timestamp is greater than trial_tracker and less then expected expiry date</p> <ul> <li><p>If yes, update trial_tracker to current system timestamp and continue.</p></li> <li><p>If no, trial_tracker has been tampered or trial time expired. Ask user to purchase full version or exit.</p></li> </ul> <p><strong>Note:</strong> User can get away with this by deleting windows registry entry and encrypted file.( if he is able to find them ). In such case, further checks can be added. For example create secondary windows registry entry which checks for existence of primary registry and encrypted file.</p> <p>Along with these, additional remote checks can be applied which depends on internet connection ( optional )</p>
3,304,795
Can a pointer (address) ever be negative?
<p>I have a function that I would like to be able to return special values for <em>failure</em> and <em>uninitialized</em> (it returns a pointer on success).</p> <p>Currently it returns <code>NULL</code> for failure, and <code>-1</code> for uninitialized, and this seems to work... but I could be cheating the system. IIRC, addresses are always positive, are they not? (although since the compiler is allowing me to set an address to -1, this seems strange).</p> <h1>[update]</h1> <p>Another idea I had (in the event that -1 was risky) is to <code>malloc</code> a char <code>@</code> the global scope, and use that address as a sentinel.</p>
3,304,814
13
4
null
2010-07-21 23:55:55.313 UTC
9
2020-10-14 04:16:42.127 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
290,784
null
1
41
c|pointers|return-value|signed
25,061
<p>No, addresses aren't always positive - on x86_64, pointers are sign-extended and the address space is clustered symmetrically around 0 (though it is usual for the "negative" addresses to be kernel addresses).</p> <p>However the point is mostly moot, since C only defines the meaning of <code>&lt;</code> and <code>&gt;</code> pointer comparisons between pointers that are to part of the same object, or one past the end of an array. Pointers to completely different objects cannot be meaningfully compared other than for exact equality, at least in standard C - <code>if (p &lt; NULL)</code> has no well defined semantics.</p> <p>You should create a dummy object with static storage duration and use its address as your <code>unintialised</code> value:</p> <pre><code>extern char uninit_sentinel; #define UNINITIALISED ((void *)&amp;uninit_sentinel) </code></pre> <p>It's guaranteed to have a single, unique address across your program.</p>
8,101,492
Set maximum frame rate with AVFoundation in iOS 5
<p>I believe this used to be done with <code>captureOutput.minFrameDuration</code>. However, this is deprecated in iOS 5.</p> <p>Instead I apparently need to use <code>AVCaptureConnection</code>'s <code>video.minFrameDuration</code>. So I have my input, my output, I add them both the the capture session - where can I get access to the capture connection? I think it is created for me by the session, but where?</p> <p>I could try adding the I/O using <code>addInputWithNoConnections</code> and <code>addOutputWithNoConnections</code> and then maybe creating the connection manually. But this seems like a bit of hassle just to set a maximum frame rate. Plus, Xcode complains that these methods don't exist.</p>
8,212,403
4
0
null
2011-11-12 00:25:49.103 UTC
8
2016-05-09 19:13:02.013 UTC
2011-11-12 03:42:17.087 UTC
null
287,954
null
1,025,041
null
1
18
ios|avfoundation
17,840
<p>Chris, I think I have solved this problem:</p> <p><em>(Edit -- See Tomas Camin's comment below on correct way of checking whether videoMinFrameDuration videoMaxFrameDuration are supported, although below code worked fine when posted)</em></p> <p>The line below gives access to the <code>AVCaptureConnection</code> object associated with the <code>AVCaptureVideoDataOutput</code> object:</p> <pre><code>AVCaptureConnection *conn = [output connectionWithMediaType:AVMediaTypeVideo]; CMTimeShow(conn.videoMinFrameDuration); CMTimeShow(conn.videoMaxFrameDuration); if (conn.isVideoMinFrameDurationSupported) conn.videoMinFrameDuration = CMTimeMake(1, CAPTURE_FRAMES_PER_SECOND); if (conn.isVideoMaxFrameDurationSupported) conn.videoMaxFrameDuration = CMTimeMake(1, CAPTURE_FRAMES_PER_SECOND); CMTimeShow(conn.videoMinFrameDuration); CMTimeShow(conn.videoMaxFrameDuration); </code></pre> <p>If you're using (as I am), the <code>didOutputSampleBuffer</code> delegate, you can confirm that the video frame rate in the <code>fromConnection</code> AVCaptureConnection * value passed in to the delegate has been correctly set and "remembered" by the above code. </p> <p>Note that you need to set <strong>both</strong> <code>videoMinFrameDuration</code> and <code>videoMaxFrameDuration</code> to the same value to successfully clamp the frame rate -- setting min on its own did not seem to work when testing on an iPhone 4s. This doesn't seem to be documented.</p> <p>Josh</p>
7,863,554
Is it ok to have an `<a>` inside another `<a>`?
<p>If I had a link to another page, and another link was put inside it, would that be ok to do? Is it allowed in HTML5 and if so, which browsers support it?</p> <p>Trying this in Chrome 14.0.835.202, I see the text on the left gets linked, followed by the <code>#1</code> link, but the rest doesn't get linked.</p> <p>Example:</p> <pre><code>&lt;p&gt; &lt;a href="download?file=2"&gt;Example file.txt&lt;/a&gt; [ &lt;a href="revision?file=2&amp;id=8"&gt;This is an example revision that fixes bug &lt;a href="bug?file=2&amp;id=1"&gt;#1&lt;/a&gt;. Version number updated. &lt;/a&gt; ] &lt;/p&gt; </code></pre>
7,863,582
4
3
null
2011-10-23 00:32:35.43 UTC
null
2011-10-23 00:43:26.13 UTC
2011-10-23 00:37:55.42 UTC
null
451,969
null
709,376
null
1
30
html
19,752
<p>According to the <a href="http://www.w3.org/TR/html5/text-level-semantics.html#the-a-element" rel="noreferrer">W3C specification for links HTML5</a>: No.</p> <blockquote> <p><strong>Content model:</strong><br> <a href="http://www.w3.org/TR/html5/content-models.html#transparent" rel="noreferrer">Transparent</a>, but there must be no <a href="http://www.w3.org/TR/html5/content-models.html#interactive-content" rel="noreferrer">interactive content</a> descendant.</p> </blockquote>
8,004,591
How to test class methods in RSPEC
<p>I wrote a simple class method <code>Buy.get_days(string)</code>, and is trying to test it with different text string inputs. However I feel it is very verbose.</p> <ul> <li>Is there any more concise way to test the following? </li> <li>Is there a equivalent of <code>subject</code> for <strong>methods</strong> which I can just keep passing different parameters in and check the results? </li> <li>Is there a way to avoid the unnecessary description at each <code>it</code>?</li> </ul> <p>thanks</p> <pre><code> describe Buy do describe '.get_days' do it 'should get days' do Buy.get_days('Includes a 1-weeknight stay for up to 4 people') .should == 1 end it 'should get days' do Buy.get_days('Includes a 1-night stay in a King Studio Room with stone fireplace') .should == 1 end it 'should get days' do Buy.get_days('Includes 4 nights/5 days at the Finisterra Hotel for up to two adults and two children (staying in the same room)') .should == 4 end end end </code></pre>
10,522,984
5
4
null
2011-11-04 03:28:22.117 UTC
2
2015-03-18 17:28:32.507 UTC
null
null
null
null
474,597
null
1
26
ruby|testing|rspec|rspec2
40,794
<p><a href="http://posterous.timocracy.com/a-pattern-for-testing-class-methods-in-ruby-w" rel="nofollow">This</a> is an interesting though perhaps more obtuse way to use the 'subject' block with Class methods.</p> <p>Edit: The broken <a href="http://wayback.archive.org/web/20120917073754/http://posterous.timocracy.com/a-pattern-for-testing-class-methods-in-ruby-w" rel="nofollow">link</a> as reported by the Wayback Archive which I suppose is susceptible to the same problem.</p>
7,852,731
C++ memory allocation mechanism performance comparison (tcmalloc vs. jemalloc)
<p>I have an application which allocates lots of memory and I am considering using a better memory allocation mechanism than malloc.</p> <p>My main options are: jemalloc and tcmalloc. Is there any benefits in using any of them over the other?</p> <p>There is a good comparison between some mechanisms (including the author's proprietary mechanism -- lockless) in <a href="http://locklessinc.com/benchmarks.shtml" rel="noreferrer">http://locklessinc.com/benchmarks.shtml</a> and it mentions some pros and cons of each of them.</p> <p>Given that both of the mechanisms are active and constantly improving. Does anyone have any insight or experience about the relative performance of these two?</p>
7,853,060
6
8
null
2011-10-21 16:57:36.057 UTC
26
2018-01-05 05:45:51.1 UTC
null
null
null
null
830,681
null
1
28
c++|linux|malloc|tcmalloc
23,113
<p>If I remember correctly, the main difference was with multi-threaded projects.</p> <p>Both libraries try to de-contention memory acquire by having threads pick the memory from different caches, but they have different strategies:</p> <ul> <li><code>jemalloc</code> (used by Facebook) maintains a cache per thread</li> <li><code>tcmalloc</code> (from Google) maintains a pool of caches, and threads develop a "natural" affinity for a cache, but may change</li> </ul> <p>This led, once again if I remember correctly, to an important difference in term of thread management.</p> <ul> <li><code>jemalloc</code> is faster if threads are static, for example using pools</li> <li><code>tcmalloc</code> is faster when threads are created/destructed</li> </ul> <p>There is also the problem that since <code>jemalloc</code> spin new caches to accommodate new thread ids, having a sudden spike of threads will leave you with (mostly) empty caches in the subsequent calm phase.</p> <p>As a result, I would recommend <code>tcmalloc</code> in the general case, and reserve <code>jemalloc</code> for very specific usages (low variation on the number of threads during the lifetime of the application).</p>
8,332,338
Autocompletion in the MySQL command-line client
<p>In Linux, and many other systems, when navigating the terminal you can press <kbd>Tab</kbd> to auto complete a directory or file name.</p> <p>I'm wondering if there is anything like that in the MySQL terminal. For example, if I want to get the description of <code>someTableWithRidiculousLongName</code> I could type <code>describe someTableW</code> then <kbd>Tab</kbd> and it would auto-complete the rest.</p> <p>Does anything like that exist in the MySQL terminal?</p>
9,736,256
7
1
null
2011-11-30 20:13:17.097 UTC
43
2019-06-19 12:27:18.087 UTC
2013-08-29 15:43:42.897 UTC
user212218
null
null
848,926
null
1
88
mysql|autocomplete|console
49,036
<p>Edit or create a file called <code>.my.cnf</code> in your home directory, containing:</p> <pre><code>[mysql] auto-rehash </code></pre>
4,818,236
Compiling/ running Javascript in Notepad++ [beginner question]
<p>I am a beginner programmer. I have a limited knowledge of javascript, but I have only worked in an IDE. I am currently following Lifehacker's programming series which teaches javascript. I have downloaded Notepad++ and have completed a program, but I am not sure of the steps to run it. In the video, the user is able to just send the program to a browser and the code runs from there.</p> <p>Here is the video for reference: <a href="http://bit.ly/gUsMd3" rel="noreferrer">http://bit.ly/gUsMd3</a></p> <p>Thanks! (note: i am a beginner to both programming and this site so any constructive criticism is welcome)</p>
4,818,277
4
4
null
2011-01-27 15:23:34.47 UTC
6
2020-09-09 10:13:31.33 UTC
2011-01-27 15:53:09.083 UTC
null
592,438
null
592,438
null
1
7
javascript|notepad++
93,850
<p>Javascript does not need to be compiled, you can put it between <code>&lt;script&gt;</code> and <code>&lt;/script&gt;</code> in a file, save it as something.html and open it in your browser.</p> <p>Java needs to be compiled, but that is something completely different.</p>
4,705,298
Unable to cast object of type 'System.Double' to type 'System.String'
<pre><code>SqlDataReader reader; String sqlreadcom = "SELECT Balance FROM IncomeGenerator"; using (reader = new SqlCommand(sqlreadcom,sqlCon).ExecuteReader()) { if(reader.HasRows) { while(reader.Read()) { String value = reader.GetString(reader.GetOrdinal("Balance")); txtbalance.Text = Convert.ToString(value); } } } </code></pre> <p>My <code>Balance</code> field data type is <code>float</code>. I need to convert it to string. </p> <p>This is the message I'm getting </p> <blockquote> <p>Unable to cast object of type 'System.Double' to type 'System.String'</p> </blockquote> <p>Can someone guide me to make this error free</p>
4,705,312
5
0
null
2011-01-16 12:22:13.057 UTC
null
2011-01-16 12:52:16.617 UTC
2011-01-16 12:30:40.973 UTC
null
13,302
null
284,454
null
1
3
c#|sql|string|casting|double
43,864
<p>Try it with</p> <pre><code>object value = reader.GetValue(reader.GetOrdinal("Balance")); txtbalance.Text = value.ToString(); </code></pre> <p>If there are many rows to read, you should do the <code>GetOrdinal</code> outside of the loop like</p> <pre><code>int idxBalance = reader.GetOrdinal("Balance"); </code></pre> <p>and use <code>idxBalance</code> later.</p>
4,070,110
How unique is uniqid?
<p>This question isn't really a problem looking for a solution, it's more just a matter of simple curiosity. The PHP uniqid function has a more entropy flag, to make the output "more unique". This got me wondering, just how likely is it for this function to produce the same result more than once when more_entropy is true, versus when it isn't. In other words, how unique is uniqid when more_entropy is enabled, versus when it is disabled? Are there any drawbacks to having more_entropy enabled all the time? </p>
4,070,142
5
4
null
2010-11-01 15:08:12.407 UTC
21
2016-07-23 23:55:47.28 UTC
2010-11-01 15:15:25.723 UTC
null
356
null
477,127
null
1
77
php
59,218
<p><strong>Update, March 2014:</strong></p> <p>Firstly, it is important to note that <code>uniqid</code> is a bit of a misnomer as it doesnt guarantee a unique ID.</p> <p>Per the <a href="http://php.net/uniqid" rel="noreferrer">PHP documentation</a>:</p> <blockquote> <p><strong>WARNING!</strong></p> <p>This function does not create random nor unpredictable string. This function must not be used for security purposes. Use cryptographically secure random function/generator and cryptographically secure hash functions to create unpredictable secure ID.</p> </blockquote> <p>And</p> <blockquote> <p>This function does not generate cryptographically secure tokens, in fact without being passed any additional parameters the return value is little different from <a href="http://www.php.net/manual/en/function.microtime.php" rel="noreferrer">microtime()</a>. If you need to generate cryptographically secure tokens use <a href="http://www.php.net/manual/en/function.openssl-random-pseudo-bytes.php" rel="noreferrer">openssl_random_pseudo_bytes()</a>.</p> </blockquote> <hr> <p>Setting more-entropy to true generates a more unique value, however the execution time is longer (though to a tiny degree), according to the docs:</p> <blockquote> <p>If set to TRUE, uniqid() will add additional entropy (using the combined linear congruential generator) at the end of the return value, which increases the likelihood that the result will be unique.</p> </blockquote> <p>Note the line <code>increases the likelihood that the result will be unique</code> and not that is will <em>guarantee</em> uniqueness.</p> <p>You can 'endlessly' strive for uniqueness, up to a point, and enhance using any number of encryption routines, adding <a href="http://en.wikipedia.org/wiki/Salt_%28cryptography%29" rel="noreferrer">salts</a> and the like- it depends on the purpose.</p> <p>I'd recommend looking at the comments on the main PHP topic, notably:</p> <p><a href="http://www.php.net/manual/en/function.uniqid.php#96898" rel="noreferrer">http://www.php.net/manual/en/function.uniqid.php#96898</a></p> <p><a href="http://www.php.net/manual/en/function.uniqid.php#96549" rel="noreferrer">http://www.php.net/manual/en/function.uniqid.php#96549</a></p> <p><a href="http://www.php.net/manual/en/function.uniqid.php#95001" rel="noreferrer">http://www.php.net/manual/en/function.uniqid.php#95001</a></p> <p>What I'd recommend is working out <em>why</em> you need uniqueness, is it for security (i.e. to add to an encryption/scrambling routine)? Also, <em>How</em> unique does it need to be? Finally, look at the speed consideration. Suitability will change with the underlying considerations.</p>
4,823,177
Reading a file character by character in C
<p>I'm writing a BF interpreter in C and I've run into a problem reading files. I used to use <code>scanf</code> in order to read the first string, but then you couldn't have spaces or comments in your BF code.</p> <p>Right now here is what I have.</p> <pre><code>char *readFile(char *fileName) { FILE *file; char *code = malloc(1000 * sizeof(char)); file = fopen(fileName, "r"); do { *code++ = (char)fgetc(file); } while(*code != EOF); return code; } </code></pre> <p>I know the problem arises in how I'm assigning the next char in the file to the code pointer but I'm just not sure what that is.<br> My pointer knowledge is lacking which is the point of this exercise. The interpreter works fine, all using pointers, I'm just having a problem reading files in to it.</p> <p>(I'm going to implement only reading <code>+-&gt;&lt;[].,</code> into the file later, although if anyone has a good way to do it, it would be great if you'd let me know!)</p>
4,823,209
7
0
null
2011-01-27 23:27:06.54 UTC
22
2020-05-31 23:19:34.02 UTC
2020-05-31 12:58:12.687 UTC
null
10,851,804
null
472,974
null
1
38
c|file-io|io|iostream
227,817
<p>There are a number of things wrong with your code:</p> <pre><code>char *readFile(char *fileName) { FILE *file; char *code = malloc(1000 * sizeof(char)); file = fopen(fileName, "r"); do { *code++ = (char)fgetc(file); } while(*code != EOF); return code; } </code></pre> <ol> <li>What if the file is greater than 1,000 bytes?</li> <li>You are increasing <code>code</code> each time you read a character, and you return <code>code</code> back to the caller (even though it is no longer pointing at the first byte of the memory block as it was returned by <code>malloc</code>).</li> <li>You are casting the result of <code>fgetc(file)</code> to <code>char</code>. You need to check for <code>EOF</code> before casting the result to <code>char</code>.</li> </ol> <p>It is important to maintain the original pointer returned by <code>malloc</code> so that you can free it later. If we disregard the file size, we can achieve this still with the following:</p> <pre><code>char *readFile(char *fileName) { FILE *file = fopen(fileName, "r"); char *code; size_t n = 0; int c; if (file == NULL) return NULL; //could not open file code = malloc(1000); while ((c = fgetc(file)) != EOF) { code[n++] = (char) c; } // don't forget to terminate with the null character code[n] = '\0'; return code; } </code></pre> <p>There are various system calls that will give you the size of a file; a common one is <a href="http://pubs.opengroup.org/onlinepubs/009695399/functions/stat.html" rel="noreferrer"><code>stat</code></a>.</p>
4,148,765
Get values from other sheet using VBA
<p>I want to get values from other sheets. </p> <p>I have some values in Excel (sheet2) for example:</p> <pre><code> A B C D - - - - 1 | 2 5 9 12 2 | 5 8 4 5 3 | 3 1 2 6 </code></pre> <p>I sum each column in row 4.</p> <p>I'm working with these values in sheet2 but I want to get the result in sheet1.</p> <p>When using my code in sheet2 I get the correct answer but when I try to use it in a different sheet I get the result of the values corresponding to the current sheet cells and not to sheet2.</p> <p>I'm using <code>With Application.WorksheetFunction</code>.</p> <p>How can I set sheet2 as the active sheet?</p>
4,148,797
7
0
null
2010-11-10 20:29:08.093 UTC
7
2020-07-24 20:31:55.957 UTC
2019-07-17 13:52:06.213 UTC
null
-1
null
495,296
null
1
39
excel|vba|worksheet-function
503,276
<p>Try</p> <pre><code> ThisWorkbook.Sheets("name of sheet 2").Range("A1") </code></pre> <p>to access a range in sheet 2 independently of where your code is or which sheet is currently active. To make sheet 2 the active sheet, try</p> <pre><code> ThisWorkbook.Sheets("name of sheet 2").Activate </code></pre> <p>If you just need the sum of a row in a different sheet, there is no need for using VBA at all. Enter a formula like this in sheet 1:</p> <pre><code>=SUM([Name-Of-Sheet2]!A1:D1) </code></pre>
4,642,596
How do I check whether this user is anonymous or actually a user on my system?
<pre><code>def index(request): the_user = request.user </code></pre> <p>In Django, how do I know if it's a real user or not? I tried:</p> <p><code>if the_user:</code> but "AnonymousUser" is there even if no one logs in. So, it always returns true and this doesn't work.</p>
4,642,607
7
0
null
2011-01-09 23:40:36.467 UTC
12
2022-09-19 11:28:45.367 UTC
null
null
null
null
179,736
null
1
106
python|django|http|authentication
64,987
<p>You can check if <a href="https://docs.djangoproject.com/en/stable/ref/contrib/auth/#django.contrib.auth.models.User.is_anonymous" rel="noreferrer"><code>request.user.is_anonymous</code></a> returns <code>True</code>.</p>
4,520,184
How to detect the character encoding of a text file?
<p>I try to detect which character encoding is used in my file.</p> <p>I try with this code to get the standard encoding </p> <pre><code>public static Encoding GetFileEncoding(string srcFile) { // *** Use Default of Encoding.Default (Ansi CodePage) Encoding enc = Encoding.Default; // *** Detect byte order mark if any - otherwise assume default byte[] buffer = new byte[5]; FileStream file = new FileStream(srcFile, FileMode.Open); file.Read(buffer, 0, 5); file.Close(); if (buffer[0] == 0xef &amp;&amp; buffer[1] == 0xbb &amp;&amp; buffer[2] == 0xbf) enc = Encoding.UTF8; else if (buffer[0] == 0xfe &amp;&amp; buffer[1] == 0xff) enc = Encoding.Unicode; else if (buffer[0] == 0 &amp;&amp; buffer[1] == 0 &amp;&amp; buffer[2] == 0xfe &amp;&amp; buffer[3] == 0xff) enc = Encoding.UTF32; else if (buffer[0] == 0x2b &amp;&amp; buffer[1] == 0x2f &amp;&amp; buffer[2] == 0x76) enc = Encoding.UTF7; else if (buffer[0] == 0xFE &amp;&amp; buffer[1] == 0xFF) // 1201 unicodeFFFE Unicode (Big-Endian) enc = Encoding.GetEncoding(1201); else if (buffer[0] == 0xFF &amp;&amp; buffer[1] == 0xFE) // 1200 utf-16 Unicode enc = Encoding.GetEncoding(1200); return enc; } </code></pre> <p>My five first byte are 60, 118, 56, 46 and 49.</p> <p>Is there a chart that shows which encoding matches those five first bytes?</p>
4,522,251
9
7
null
2010-12-23 15:40:15.823 UTC
44
2021-09-25 12:36:49.787 UTC
2010-12-23 15:45:45.777 UTC
null
50,079
null
82,595
null
1
80
c#|encoding|character-encoding|byte-order-mark
126,565
<p>You can't depend on the file having a BOM. UTF-8 doesn't require it. And non-Unicode encodings don't even have a BOM. There are, however, other ways to detect the encoding.</p> <h2>UTF-32</h2> <p>BOM is 00 00 FE FF (for BE) or FF FE 00 00 (for LE).</p> <p>But UTF-32 is easy to detect even without a BOM. This is because the Unicode code point range is restricted to U+10FFFF, and thus UTF-32 units always have the pattern 00 {00-10} xx xx (for BE) or xx xx {00-10} 00 (for LE). If the data has a length that's a multiple of 4, and follows one of these patterns, you can safely assume it's UTF-32. False positives are nearly impossible due to the rarity of 00 bytes in byte-oriented encodings.</p> <h2>US-ASCII</h2> <p>No BOM, but you don't need one. ASCII can be easily identified by the lack of bytes in the 80-FF range.</p> <h2>UTF-8</h2> <p>BOM is EF BB BF. But you can't rely on this. Lots of UTF-8 files don't have a BOM, especially if they originated on non-Windows systems.</p> <p>But you can safely assume that if a file validates as UTF-8, it <em>is</em> UTF-8. False positives are rare.</p> <p>Specifically, given that the data is not ASCII, the false positive rate for a 2-byte sequence is only 3.9% (1920/49152). For a 7-byte sequence, it's less than 1%. For a 12-byte sequence, it's less than 0.1%. For a 24-byte sequence, it's less than 1 in a million.</p> <h2>UTF-16</h2> <p>BOM is FE FF (for BE) or FF FE (for LE). Note that the UTF-16LE BOM is found at the start of the UTF-32LE BOM, so check UTF-32 first.</p> <p>If you happen to have a file that consists mainly of ISO-8859-1 characters, having half of the file's bytes be 00 would also be a strong indicator of UTF-16.</p> <p>Otherwise, the only reliable way to recognize UTF-16 without a BOM is to look for surrogate pairs (D[8-B]xx D[C-F]xx), but non-BMP characters are too rarely-used to make this approach practical.</p> <h2>XML</h2> <p>If your file starts with the bytes 3C 3F 78 6D 6C (i.e., the ASCII characters "&lt;?xml"), then look for an <code>encoding=</code> declaration. If present, then use that encoding. If absent, then assume UTF-8, which is the default XML encoding.</p> <p>If you need to support EBCDIC, also look for the equivalent sequence 4C 6F A7 94 93.</p> <p>In general, if you have a file format that contains an encoding declaration, then look for that declaration rather than trying to guess the encoding.</p> <h2>None of the above</h2> <p>There are hundreds of other encodings, which require more effort to detect. I recommend trying <a href="http://www.mozilla.org/projects/intl/chardet.html" rel="noreferrer">Mozilla's charset detector</a> or <a href="http://code.google.com/p/chardetsharp/" rel="noreferrer">a .NET port of it</a>.</p> <h2>A reasonable default</h2> <p>If you've ruled out the UTF encodings, and don't have an encoding declaration or statistical detection that points to a different encoding, assume <a href="https://en.wikipedia.org/wiki/ISO/IEC_8859-1" rel="noreferrer">ISO-8859-1</a> or the closely related <a href="https://en.wikipedia.org/wiki/Windows-1252" rel="noreferrer">Windows-1252</a>. (Note that the latest HTML standard <em>requires</em> a “ISO-8859-1” declaration to be interpreted as Windows-1252.) Being Windows' default code page for English (and other popular languages like Spanish, Portuguese, German, and French), it's the most commonly encountered encoding other than UTF-8.</p>
4,749,021
List<T> readonly with a private set
<p>How can I expose a <code>List&lt;T&gt;</code> so that it is readonly, but can be set privately?</p> <p>This doesn't work:</p> <pre><code>public List&lt;string&gt; myList {readonly get; private set; } </code></pre> <p>Even if you do:</p> <pre><code>public List&lt;string&gt; myList {get; private set; } </code></pre> <p>You can still do this:</p> <pre><code>myList.Add("TEST"); //This should not be allowed </code></pre> <p>I guess you could have:</p> <pre><code>public List&lt;string&gt; myList {get{ return otherList;}} private List&lt;string&gt; otherList {get;set;} </code></pre>
4,749,057
15
0
null
2011-01-20 15:30:22.59 UTC
13
2016-08-02 09:07:02.73 UTC
2016-08-02 09:07:02.73 UTC
null
63,550
null
84,539
null
1
54
c#|.net|generics|c#-3.0
34,457
<p>I think you are mixing concepts.</p> <pre><code>public List&lt;string&gt; myList {get; private set;} </code></pre> <p><em>is</em> already "read-only". That is, outside this class, nothing can set <code>myList</code> to a different instance of <code>List&lt;string&gt;</code></p> <p>However, if you want a readonly list as in "I don't want people to be able to modify the list <em>contents</em>", then you need to expose a <code>ReadOnlyCollection&lt;string&gt;</code>. You can do this via:</p> <pre><code>private List&lt;string&gt; actualList = new List&lt;string&gt;(); public ReadOnlyCollection&lt;string&gt; myList { get{ return actualList.AsReadOnly();} } </code></pre> <p>Note that in the first code snippet, others can manipulate the List, but can not change what list you have. In the second snippet, others will get a read-only list that they can not modify.</p>
14,837,185
How can we dynamically allocate and grow an array
<p>I am working on a project, but I cannot use any existing java data structures (ie, ArraysList, trees, etc)</p> <p>I can only use arrays. Therefore, I need to dynamically update an array with new memory.</p> <p>I am reading from a text file, and I pre-allocate 100 for the arrays memory:</p> <pre><code> String [] wordList; int wordCount = 0; int occurrence = 1; int arraySize = 100; wordList = new String[arraySize]; while ((strLine = br.readLine()) != null) { // Store the content into an array Scanner s = new Scanner(strLine); while(s.hasNext()) { wordList[wordCount] = s.next(); wordCount++; } } </code></pre> <p>Now this works fine for under 100 list items. br.readline is the buffered reader going through each line of a textfile. I have it then store each word into list and then increment my index (wordCount).</p> <p>However, once I have a text file with more than 100 items, I get an allocation error.</p> <p>How can I dynamically update this array (and thereby sort of reinvent the wheel)?</p> <p>Thanks!</p>
14,837,262
8
3
null
2013-02-12 16:29:50.393 UTC
7
2017-09-15 14:23:19.287 UTC
2013-02-12 16:49:46.713 UTC
null
1,208,445
null
588,055
null
1
10
java|arrays|word-count
108,799
<p>You can do something like this:</p> <pre><code>String [] wordList; int wordCount = 0; int occurrence = 1; int arraySize = 100; int arrayGrowth = 50; wordList = new String[arraySize]; while ((strLine = br.readLine()) != null) { // Store the content into an array Scanner s = new Scanner(strLine); while(s.hasNext()) { if (wordList.length == wordCount) { // expand list wordList = Arrays.copyOf(wordList, wordList.length + arrayGrowth); } wordList[wordCount] = s.next(); wordCount++; } } </code></pre> <p>Using <code>java.util.Arrays.copyOf(String[])</code> is basically doing the same thing as:</p> <pre><code>if (wordList.length == wordCount) { String[] temp = new String[wordList.length + arrayGrowth]; System.arraycopy(wordList, 0, temp, 0, wordList.length); wordList = temp; } </code></pre> <p>except it is one line of code instead of three. :)</p>
14,680,121
Include JUST files in scandir array?
<p>I have an array I'm getting back from scandir, but it contains <code>"."</code> and <code>".."</code> and I don't want it to.</p> <p>My code:</p> <pre><code>$indir = scandir('../pages'); $fileextensions = array(".", "php", "html", "htm", "shtml"); $replaceextensions = str_replace($fileextensions, "", $indir); </code></pre> <p>I am doing a string replace on the file extensions, thus causing [0] and [1] to appear empty, but they are <code>"."</code> and <code>".."</code></p> <pre><code>array(4) { [0]=&gt; string(0) "" [1]=&gt; string(0) "" [2]=&gt; string(4) "test" [3]=&gt; string(4) "home" } </code></pre> <p>How would I remove the <code>"."</code> and <code>".."</code> from the array?</p>
14,680,164
8
1
null
2013-02-04 03:55:38.553 UTC
7
2022-08-23 12:24:40.6 UTC
2015-05-30 22:42:06.513 UTC
null
1,709,587
null
2,038,451
null
1
28
php|scandir
40,650
<p>You can use <a href="http://php.net/manual/en/function.array-filter.php" rel="noreferrer">array_filter</a>.</p> <pre><code>$indir = array_filter(scandir('../pages'), function($item) { return !is_dir('../pages/' . $item); }); </code></pre> <p>Note this filters out all directories and leaves only files and symlinks. If you really want to only exclude only files (and directories) starting with <code>.</code>, then you could do something like:</p> <pre><code>$indir = array_filter(scandir('../pages'), function($item) { return $item[0] !== '.'; }); </code></pre>
14,784,841
TileProvider using local tiles
<p>I would like to use the new <code>TileProvider</code> functionality of the latest Android Maps API (v2) to overlay some custom tiles on the <code>GoogleMap</code>. However as my users will not have internet a lot of the time, I want to keep the tiles stored in a zipfile/folder structure on the device. I will be generating my tiles using <code>Maptiler</code> with <code>geotiffs</code>. My questions are:</p> <ol> <li>What would be the best way to store the tiles on the device?</li> <li>How would I go about creating a TileProvider that returns local tiles?</li> </ol>
14,833,256
3
3
null
2013-02-09 04:06:30.06 UTC
91
2022-01-20 16:54:28.783 UTC
2015-08-20 14:01:25.163 UTC
null
685,933
null
1,848,904
null
1
73
android|google-maps|android-maps-v2
67,157
<ol> <li><p>You can put tiles into assets folder (if it is acceptable for the app size) or download them all on first start and put them into device storage (SD card).</p></li> <li><p>You can implement TileProvider like this:</p></li> </ol> <hr> <pre><code>public class CustomMapTileProvider implements TileProvider { private static final int TILE_WIDTH = 256; private static final int TILE_HEIGHT = 256; private static final int BUFFER_SIZE = 16 * 1024; private AssetManager mAssets; public CustomMapTileProvider(AssetManager assets) { mAssets = assets; } @Override public Tile getTile(int x, int y, int zoom) { byte[] image = readTileImage(x, y, zoom); return image == null ? null : new Tile(TILE_WIDTH, TILE_HEIGHT, image); } private byte[] readTileImage(int x, int y, int zoom) { InputStream in = null; ByteArrayOutputStream buffer = null; try { in = mAssets.open(getTileFilename(x, y, zoom)); buffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[BUFFER_SIZE]; while ((nRead = in.read(data, 0, BUFFER_SIZE)) != -1) { buffer.write(data, 0, nRead); } buffer.flush(); return buffer.toByteArray(); } catch (IOException e) { e.printStackTrace(); return null; } catch (OutOfMemoryError e) { e.printStackTrace(); return null; } finally { if (in != null) try { in.close(); } catch (Exception ignored) {} if (buffer != null) try { buffer.close(); } catch (Exception ignored) {} } } private String getTileFilename(int x, int y, int zoom) { return "map/" + zoom + '/' + x + '/' + y + ".png"; } } </code></pre> <p>And now you can use it with your GoogleMap instance:</p> <pre><code>private void setUpMap() { mMap.setMapType(GoogleMap.MAP_TYPE_NONE); mMap.addTileOverlay(new TileOverlayOptions().tileProvider(new CustomMapTileProvider(getResources().getAssets()))); CameraUpdate upd = CameraUpdateFactory.newLatLngZoom(new LatLng(LAT, LON), ZOOM); mMap.moveCamera(upd); } </code></pre> <p>In my case I also had a problem with y coordinate of tiles generated by MapTiler, but I managed it by adding this method into CustomMapTileProvider:</p> <pre><code>/** * Fixing tile's y index (reversing order) */ private int fixYCoordinate(int y, int zoom) { int size = 1 &lt;&lt; zoom; // size = 2^zoom return size - 1 - y; } </code></pre> <p>and callig it from getTile() method like this:</p> <pre><code>@Override public Tile getTile(int x, int y, int zoom) { y = fixYCoordinate(y, zoom); ... } </code></pre> <p><strong>[Upd]</strong></p> <p>If you know exac area of your custom map, you should return <code>NO_TILE</code> for missing tiles from <code>getTile(...)</code> method.</p> <p>This is how I did it:</p> <pre><code>private static final SparseArray&lt;Rect&gt; TILE_ZOOMS = new SparseArray&lt;Rect&gt;() {{ put(8, new Rect(135, 180, 135, 181 )); put(9, new Rect(270, 361, 271, 363 )); put(10, new Rect(541, 723, 543, 726 )); put(11, new Rect(1082, 1447, 1086, 1452)); put(12, new Rect(2165, 2894, 2172, 2905)); put(13, new Rect(4330, 5789, 4345, 5810)); put(14, new Rect(8661, 11578, 8691, 11621)); }}; @Override public Tile getTile(int x, int y, int zoom) { y = fixYCoordinate(y, zoom); if (hasTile(x, y, zoom)) { byte[] image = readTileImage(x, y, zoom); return image == null ? null : new Tile(TILE_WIDTH, TILE_HEIGHT, image); } else { return NO_TILE; } } private boolean hasTile(int x, int y, int zoom) { Rect b = TILE_ZOOMS.get(zoom); return b == null ? false : (b.left &lt;= x &amp;&amp; x &lt;= b.right &amp;&amp; b.top &lt;= y &amp;&amp; y &lt;= b.bottom); } </code></pre>
50,038,286
git tag fails with $'\226git': command not found
<p>I'm using Git BASH in windows 7 and I try to create a tag:</p> <pre><code>git tag -a v2.44.13 -m "[before prod] bla bla bla" </code></pre> <p>and fails with:</p> <pre><code>$'\226git': command not found </code></pre> <p>Same command works with Git CMD. Why this happens and how to solve it?</p> <p><em>git version 2.11.0.windows.1</em></p>
57,939,415
4
3
null
2018-04-26 08:28:31.16 UTC
4
2021-11-28 09:53:49.06 UTC
null
null
null
null
4,681,265
null
1
29
git-bash|git-tag
33,948
<p>I have faced same issue and it was because of copy-paste. Typing by hand solves the issue. If you don't want type all the command by hand try to go at the starting of the command after pasting it to the console and click backspace button multiple times. This should remove hidden characters and should work also.</p>
44,783,702
What is the use of @Html.AntiForgeryToken()?
<p>Why we need to use <code>@Html.AntiForgeryToken()</code>? I searched but I didn't get satisfactory answer.</p>
44,783,928
4
0
null
2017-06-27 15:03:02.59 UTC
17
2021-03-08 18:19:55.823 UTC
2017-06-28 01:58:11.073 UTC
user3559349
null
null
7,862,418
null
1
54
asp.net-mvc|html.beginform
64,735
<p>This is a security feature to help protect your application against cross-site request forgery.</p> <p>Example:</p> <p>Let's assume you have a register functionality in your web app. You have an <code>AccountController</code> (<code>example.com/account/register</code>) where you expect people to submit their info. Normally before someone posts the registration information needs to visit the actual (<code>example.com/account/register</code>) than submit the form.</p> <p>Let say I am a bad guy and I want to flood your server with junk info all I need to do is just keep posting directly to (<code>example.com/account/register</code>) without visiting your site. So in order to stop me you implement AntiForgeryToken so you can make it sure I visited the page before I submitted the registration information.</p> <p>Another example is <a href="http://www.binaryintellect.net/articles/20e546b4-3ae9-416b-878e-5b12434fe7a6.aspx" rel="noreferrer">http://www.binaryintellect.net/articles/20e546b4-3ae9-416b-878e-5b12434fe7a6.aspx</a>.</p>
42,917,566
What is this question mark operator about?
<p>I'm reading <a href="https://doc.rust-lang.org/std/fs/struct.File.html" rel="noreferrer">the documentation for <code>File</code></a>:</p> <pre><code>//.. let mut file = File::create("foo.txt")?; //.. </code></pre> <p>What is the <code>?</code> in this line? I do not recall seeing it in the Rust Book before.</p>
42,921,174
3
1
null
2017-03-21 02:50:31.793 UTC
25
2022-06-15 07:42:06.177 UTC
2018-02-09 22:45:23.713 UTC
null
155,423
null
4,140,572
null
1
215
rust
61,707
<p>As you may have noticed, Rust does not have exceptions. It has panics, but their use for error-handling is discouraged (they are meant for unrecoverable errors).</p> <p>In Rust, error handling uses <a href="https://doc.rust-lang.org/std/result/enum.Result.html" rel="noreferrer"><code>Result</code></a>. A typical example would be:</p> <pre><code>fn halves_if_even(i: i32) -&gt; Result&lt;i32, Error&gt; { if i % 2 == 0 { Ok(i / 2) } else { Err(/* something */) } } fn do_the_thing(i: i32) -&gt; Result&lt;i32, Error&gt; { let i = match halves_if_even(i) { Ok(i) =&gt; i, Err(e) =&gt; return Err(e), }; // use `i` } </code></pre> <p>This is great because:</p> <ul> <li>when writing the code you cannot accidentally forget to deal with the error,</li> <li>when reading the code you can immediately see that there is a potential for error right here.</li> </ul> <p>It's less than ideal, however, in that it is very verbose. This is where the question mark operator <code>?</code> comes in.</p> <p>The above can be rewritten as:</p> <pre><code>fn do_the_thing(i: i32) -&gt; Result&lt;i32, Error&gt; { let i = halves_if_even(i)?; // use `i` } </code></pre> <p>which is much more concise.</p> <p>What <code>?</code> does here is equivalent to the <code>match</code> statement above with an addition. In short:</p> <ol> <li>It unpacks the <code>Result</code> if OK</li> <li>It <em>returns</em> the error if not, calling <a href="https://doc.rust-lang.org/std/convert/trait.From.html#tymethod.from" rel="noreferrer"><code>From::from</code></a> on the error value to potentially convert it to another type.</li> </ol> <p>It's a bit magic, but error handling needs some magic to cut down the boilerplate, and unlike exceptions it is immediately visible which function calls may or may not error out: those that are adorned with <code>?</code>.</p> <p>One example of the magic is that this also works for <code>Option</code>:</p> <pre><code>// Assume // fn halves_if_even(i: i32) -&gt; Option&lt;i32&gt; fn do_the_thing(i: i32) -&gt; Option&lt;i32&gt; { let i = halves_if_even(i)?; // use `i` } </code></pre> <p>The <code>?</code> operator, <a href="https://github.com/rust-lang/rust/pull/31954" rel="noreferrer">stabilized in Rust version 1.13.0</a> is powered by the (unstable) <a href="https://doc.rust-lang.org/std/ops/trait.Try.html" rel="noreferrer"><code>Try</code></a> trait.</p> <p>See also:</p> <ul> <li><a href="https://stackoverflow.com/q/40545332/155423">Is the question mark operator ? equivalent to the try! macro?</a></li> <li><a href="https://stackoverflow.com/q/30555477/155423">Why do try!() and ? not compile when used in a function that doesn&#39;t return Option or Result?</a></li> </ul>
42,994,337
Navigation Error in angular2
<p>I have updated the angular packages version from 2.4.10 to 4.0.0 after updating i am getting the following errors while navigating.</p> <pre><code>ERROR Error: Uncaught (in promise): Error: Found the synthetic property @transformPlaceholder. Please include either "BrowserAnimationsModule" or "NoopAnimationsModule" in your application. Error: Found the synthetic property @transformPlaceholder. Please include either "BrowserAnimationsModule" or "NoopAnimationsModule" in your application </code></pre> <p>And i changed the webpack.common.js configuration. see the below code</p> <pre><code> new webpack.ContextReplacementPlugin( // The (\\|\/) piece accounts for path separators in *nix and Windows /angular(\\|\/)core(\\|\/)@angular/, helpers.root('./src'), // location of your src {} // a map of your routes ), </code></pre>
42,996,008
5
1
null
2017-03-24 08:05:26.49 UTC
13
2018-02-08 08:45:41.017 UTC
2017-07-31 05:32:18.993 UTC
null
7,749,909
null
7,749,909
null
1
40
node.js|angular|webpack-2|typescript2.1
11,821
<p>I have fixed the issue. I added a new package: <code>@angular/animations</code>.</p> <pre><code>import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; </code></pre> <p>And I imported the module:</p> <pre><code>@NgModule({ imports: [ BrowserAnimationsModule ] }) </code></pre>
21,128,478
Run grunt build command on Travis CI
<p>I am using Travis CI to test and build my project and as part of it I want travis to run <code>grunt build</code> i have tried the following but have had no luck.</p> <ul> <li><code>script: "grunt build"</code></li> <li><code>script: "./node_modules/grunt build"</code></li> <li><code>script: "./node_modules/grunt/grunt build"</code></li> <li><code>script: "./node_modules/grunt/grunt.js build"</code></li> </ul>
21,133,609
4
0
null
2014-01-15 03:15:19.467 UTC
13
2017-03-04 06:48:13.473 UTC
2017-03-04 06:48:13.473 UTC
null
3,357,935
user2693845
null
null
1
43
node.js|gruntjs|travis-ci
11,210
<p>Have you made sure to install <code>grunt-cli</code> globally on your Travis node?</p> <p>My Travis CI config looks like:</p> <pre><code>language: node_js node_js: - "0.8" before_install: npm install -g grunt-cli install: npm install before_script: grunt build </code></pre> <p>And my package.json:</p> <pre><code>{ ... "scripts": { "test": "grunt test" }, ... } </code></pre> <p>I will explain the flow of steps that Travis will execute:</p> <ol> <li>The first step to be executed is the <code>before_install</code>. My only prerequisite (besides node.js) is <code>grunt-cli</code> so I use this step to install it.</li> <li>Next is the <code>install</code> step, in my case this will simply install my npm modules</li> <li>The <code>before script</code> is then executed, running <code>grunt build</code></li> <li>Lastly Travis will look for scripts in the package.json, there I indicated the test step should run <code>grunt test</code></li> </ol> <p>I'd like to note that this is my own opinion on how to configure Travis. I'm certainly not inclining you should use exactly the same approach.</p>
38,707,133
Google Firebase sign out and forget user in Android app
<p>When I call <code>mFirebaseAuth.signOut()</code> or <code>mFirebaseUser.delete()</code> my <code>FirebaseAuth.AuthStateListener()</code> works correctly and returns <code>null</code> as <code>FirebaseUser</code> instance in <code>onAuthStateChanged</code>, I refresh UI and show "Sign in with Google" button.</p> <p>But when I want to log in again, I don't see the dialog with users (I have 2 users on my device, attached the image). The app shows this dialog only in first sign in, after that it uses the same user. If I clear app's data on the settings screen I will be able to see this dialog again.</p> <p>My question is how to show this dialog after every sign out.</p> <p><a href="https://i.stack.imgur.com/kyaAV.png" rel="noreferrer"><img src="https://i.stack.imgur.com/kyaAV.png" alt="enter image description here"></a></p> <p>I run this code when press Sign In button:</p> <pre><code>// in onCreate() GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken(getString(R.string.default_web_client_id)) .requestEmail() .build(); mGoogleApiClient = new GoogleApiClient.Builder(this) .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */) .addApi(Auth.GOOGLE_SIGN_IN_API, gso) .build(); // in OnClickListener Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient); startActivityForResult(signInIntent, FirebaseActivity.REQUEST_SIGN_IN); </code></pre> <p>In <code>onActivityResult()</code>, I get an instance of <code>GoogleSignInResult</code> so everything I need happens after I call <code>startActivityForResult()</code>.</p>
38,707,954
11
6
null
2016-08-01 19:59:34.46 UTC
9
2022-08-11 18:43:34.95 UTC
2019-05-14 19:22:27.663 UTC
null
2,311,651
null
2,311,651
null
1
38
android|firebase|google-play-services|firebase-authentication
36,666
<p>In the <a href="https://github.com/firebase/quickstart-android/blob/master/auth/app/src/main/java/com/google/firebase/quickstart/auth/java/GoogleSignInActivity.java#L160-L172" rel="noreferrer">Firebase Auth Quickstart sample code</a>, the sign-out for Google provider includes these steps. Are you calling <code>GoogleSignInClient.signOut()</code> when you sign-out?</p> <pre><code>private void signOut() { // Firebase sign out mAuth.signOut(); // Google sign out mGoogleSignInClient.signOut().addOnCompleteListener(this, new OnCompleteListener&lt;Void&gt;() { @Override public void onComplete(@NonNull Task&lt;Void&gt; task) { updateUI(null); } }); } </code></pre>
2,552,579
Ruby method Array#<< not updating the array in hash
<p>Inspired by <a href="https://stackoverflow.com/questions/2552363/how-can-i-marshal-a-hash-with-arrays">How can I marshal a hash with arrays?</a> I wonder what's the reason that <code>Array#&lt;&lt;</code> won't work properly in the following code:</p> <pre><code>h = Hash.new{Array.new} #=&gt; {} h[0] #=&gt; [] h[0] &lt;&lt; 'a' #=&gt; ["a"] h[0] #=&gt; [] # why?! h[0] += ['a'] #=&gt; ["a"] h[0] #=&gt; ["a"] # as expected </code></pre> <p>Does it have to do with the fact that <code>&lt;&lt;</code> changes the array in-place, while <code>Array#+</code> creates a new instance?</p>
2,552,946
3
1
null
2010-03-31 11:49:50.847 UTC
9
2012-02-27 21:39:18.457 UTC
2017-05-23 10:27:35.063 UTC
null
-1
null
82,592
null
1
15
ruby|arrays|hash
1,634
<p>If you create a <code>Hash</code> using the block form of <code>Hash.new</code>, the block gets executed every time you try to access an element which doesn't actually exist. So, let's just look at what happens:</p> <pre><code>h = Hash.new { [] } h[0] &lt;&lt; 'a' </code></pre> <p>The first thing that gets evaluated here, is the expression</p> <pre><code>h[0] </code></pre> <p>What happens when it gets evaluated? Well, the block gets run:</p> <pre><code>[] </code></pre> <p>That's not very exciting: the block simply creates an empty array and returns it. It doesn't do anything else. In particular, it doesn't change <code>h</code> in any way: <code>h</code> is still empty.</p> <p>Next, the message <code>&lt;&lt;</code> with one argument <code>'a'</code> gets sent to the result of <code>h[0]</code> which is the result of the block, which is simply an empty array:</p> <pre><code>[] &lt;&lt; 'a' </code></pre> <p>What does this do? It adds the element <code>'a'</code> to an empty array, but since the array doesn't actually get assigned to any variable, it is immediately garbage collected and goes away.</p> <p>Now, if you evaluate <code>h[0]</code> again:</p> <pre><code>h[0] # =&gt; [] </code></pre> <p><code>h</code> is <em>still</em> empty, since nothing ever got assigned to it, therefore the key <code>0</code> is still non-existent, which means the block gets run <em>again</em>, which means it <em>again</em> returns an empty array (but note that it is a completely new, <em>different</em> empty array now).</p> <pre><code>h[0] += ['a'] </code></pre> <p>What happens here? First, the operator assign gets desugared to </p> <pre><code>h[0] = h[0] + ['a'] </code></pre> <p>Now, the <code>h[0]</code> on the <em>right</em> side gets evaluated. And what does it return? We already went over this: <code>h[0]</code> doesn't exist, therefore the block gets run, the block returns an empty array. Again, this is a completely new, <em>third</em> empty array now. This empty array gets sent the message <code>+</code> with the argument <code>['a']</code>, which causes it to return yet <em>another</em> new array which is the array <code>['a']</code>. This array then gets assigned to <code>h[0]</code>.</p> <p>Lastly, at this point:</p> <pre><code>h[0] # =&gt; ['a'] </code></pre> <p>Now you have <em>finally</em> actually put something into <code>h[0]</code> so, obviously, you get out what you put in.</p> <p>So, to answer the question you probably had, why don't you get out what you put in? You <em>didn't</em> put anything in in the first place!</p> <p>If you actually want to <em>assign</em> to the hash inside the block, you have to, well assign to the hash inside the block:</p> <pre><code>h = Hash.new {|this_hash, nonexistent_key| this_hash[nonexistent_key] = [] } h[0] &lt;&lt; 'a' h[0] # =&gt; ['a'] </code></pre> <p>It's actually fairly easy to see what is going on in your code example, if you look at the identities of the objects involved. Then you can see that everytime you call <code>h[0]</code>, you get a <em>different</em> array.</p>
2,457,514
Understanding max JVM heap size - 32bit vs 64bit
<p>I've <a href="https://stackoverflow.com/questions/171205/java-maximum-memory-on-windows-xp">read</a> the max heap size on 32bit Windows is ~1.5GB which is due to the fact that the JVM requires contiguous memory. Can someone explain the concept of "contiguous memory" and why you only have max 1.5GB on Windows?</p> <p>Secondly, what then is the max heap size on 64 bit Windows and why is this different than what's available on 32 bit?</p>
2,457,542
3
2
null
2010-03-16 19:40:09.483 UTC
10
2021-11-08 13:33:32.993 UTC
2021-11-08 13:33:32.993 UTC
null
5,459,839
null
47,281
null
1
33
java|jvm|heap-memory
73,069
<p>The 32-bit/64-bit part is unrelated to Java</p> <p>It turns out that memory locations in a 32-bit system are referenced by 32-bit unsigned integers. This allows up to 2^32 possible memory locations. Since each location stores 1 byte you get 2^32 bytes or 4 GB if you prefer. </p> <p>On a 64 bit system there are 2^64 locations, or 16 exabytes.</p> <p>Now, in Windows, the contiguous part becomes a big issue, but that is just how Windows does things. The idea is that you need to have an entire "uninterrupted" range for your heap. Sadly, Windows allocates some memory somewhere in the middle. This basically leaves you with about half the left side or half the right side, about 1.5-2GB chunks, to allocate your heap.</p> <p>Check out <a href="https://stackoverflow.com/questions/132930/32-vs-64-bits-whats-the-big-deal">this question</a> for more details on 32 vs 64 bit.</p> <p>Edit: Thanks mrjoltcola for the exa prefix!</p>
2,831,345
Is there a way to check if a variable is a Date in JavaScript?
<p>I was wondering if there is any way to check if an object is specifically a Date in JavaScript. isType returns object for Date, which isn't enough for this scenario. Any ideas? Thanks!</p>
2,831,365
4
0
null
2010-05-14 01:37:14.04 UTC
8
2010-05-14 03:51:51.487 UTC
2010-05-14 01:39:11.92 UTC
null
155,537
null
140,448
null
1
104
javascript|date|typechecking
74,845
<p>Use instanceof</p> <pre><code>(myvar instanceof Date) // returns true or false </code></pre>
2,962,296
vb6 ADODB connection string to sql server 2008
<p>I recently migrated a database from sql server 2005 to 2008 on windows server 2008. Clients connect fine from their XP machines and so does the SQL Management Studio 2008. I have also tested a remote connection using LINQPad which worked fine. </p> <p>However on my VB6 app, the connection string seems to give me problems. Any ideas what I'm doing wrong? </p> <pre><code> Dim strUserName As String Dim strPassword As String Dim sProc As String sProc = "Class_clsAdoFnx_Initialize" Me.DatabaseName = "db_app" 'Connect to SQL Server strUserName = "admin" strPassword = "mudslinger" Set cSQLConn = New ADODB.Connection '**Original connection String 'cSQLConn.CommandTimeout = 0 'cSQLConn.ConnectionString = " PROVIDER=SQLOLEDB" &amp; _ ' ";SERVER=NET-BRAIN" &amp; _ ' ";UID=" &amp; strUserName &amp; _ ' ";PWD=" &amp; strPassword &amp; _ ' ";DATABASE=" &amp; Me.DatabaseName '***First attempt, no dice 'cSQLConn.ConnectionString = "Provider=sqloledb;" &amp; _ ' "Data Source=NET-BRAIN;" &amp; _ ' "Initial Catalog=DB_APP;" &amp; _ ' "User Id=admin;" &amp; _ ' "Password=mudslinger" 'cSQLConn.Open '***3rd attempt, no dice cSQLConn.Open "Provider=sqloledb;" &amp; _ "Data Source=NET-BRAIN;" &amp; _ "Initial Catalog=db_app;" &amp; _ "User Id=admin;" &amp; _ "Password=mudslinger", "admin", "mudslinger" </code></pre> <p>thanks in advance.</p> <p>UPDATE: Here is the string I generated using my test.UL file</p> <p><strong>[ODBC] Provider</strong></p> <p>Provider=MSDASQL.1;Password=logmein;Persist Security Info=True;User ID=sa;Extended Properties="DSN=NET-BRAIN;UID=admin;PWD=mudslinger;APP=Microsoft® Windows® Operating System;WSID=BPOOR-16D68FBC7D;DATABASE=DB_App;Network=DBMSSOCN";Initial Catalog=DB_App</p> <p>Here is the same UL file using the <strong>SQL Native provider</strong>: </p> <p>"Provider=SQLNCLI10.1;Integrated Security="";Persist Security Info=False;User ID=admin;Initial Catalog=DB_APP;Data Source=NET-BRAIN;Initial File Name="";Server SPN="""</p> <p>--received the error: Error in Ado Call... There was an error in Class_clasAdoFnx_initialize 3001 Arguments are of the wrong type, are out of acceptable range, or are in conflict with one another. --Error: Class_clsAdoFnx_Initialize 3709 Requested operation requires an OLE DB Session object, which is not supported by current provider. </p> <p><strong>tried [oledb] for sql server provider option</strong> "Provider=SQLOLEDB.1;Password=mudslinger;Persist Security Info=True;User ID=admin;Initial Catalog=db_app;Data Source=net-brain"</p> <p>error: -2147217900 Login failed for user 'admin' </p> <p><strong>UPDATE2 :</strong> After isolating the open connection string, it turns out the connection is opening and the stored procedure I was using to test with was failing. </p>
2,962,362
1
5
null
2010-06-02 23:14:36.28 UTC
1
2011-08-28 10:21:47.933 UTC
2010-06-03 21:32:18.57 UTC
null
18,853
null
18,853
null
1
3
sql|sql-server-2008|connection-string
80,594
<p>Following <a href="http://msdn.microsoft.com/en-us/library/ms130978.aspx" rel="nofollow noreferrer">Using ADO with SQL Server Native Client</a> to enable the usage of SQL Server Native Client, ADO applications will need to implement the following keywords in their connection strings:</p> <blockquote> <p>Provider=SQLNCLI10<br> DataTypeCompatibility=80</p> </blockquote> <pre><code>Dim con As New ADODB.Connection con.ConnectionString = "Provider=SQLNCLI10;" _ &amp; "SERVER=NET-BRAIN;" _ &amp; "Database=DB_APP;" _ &amp; "DataTypeCompatibility=80;" _ &amp; "User Id=admin;" _ &amp; "Password=mudslinger;" con.Open </code></pre>
50,544,730
How do I split a custom dataset into training and test datasets?
<pre><code>import pandas as pd import numpy as np import cv2 from torch.utils.data.dataset import Dataset class CustomDatasetFromCSV(Dataset): def __init__(self, csv_path, transform=None): self.data = pd.read_csv(csv_path) self.labels = pd.get_dummies(self.data['emotion']).as_matrix() self.height = 48 self.width = 48 self.transform = transform def __getitem__(self, index): pixels = self.data['pixels'].tolist() faces = [] for pixel_sequence in pixels: face = [int(pixel) for pixel in pixel_sequence.split(' ')] # print(np.asarray(face).shape) face = np.asarray(face).reshape(self.width, self.height) face = cv2.resize(face.astype('uint8'), (self.width, self.height)) faces.append(face.astype('float32')) faces = np.asarray(faces) faces = np.expand_dims(faces, -1) return faces, self.labels def __len__(self): return len(self.data) </code></pre> <p>This is what I could manage to do by using references from other repositories. However, I want to split this dataset into train and test. </p> <p>How can I do that inside this class? Or do I need to make a separate class to do that?</p>
50,544,887
7
0
null
2018-05-26 16:16:04.99 UTC
50
2022-06-18 12:44:51.89 UTC
2019-01-07 14:42:32.06 UTC
null
3,924,118
null
4,229,637
null
1
98
python|deep-learning|pytorch
146,272
<p>Using Pytorch's <a href="https://pytorch.org/docs/master/data.html#torch.utils.data.SubsetRandomSampler" rel="noreferrer"><code>SubsetRandomSampler</code></a>:</p> <pre class="lang-python prettyprint-override"><code>import torch import numpy as np from torchvision import datasets from torchvision import transforms from torch.utils.data.sampler import SubsetRandomSampler class CustomDatasetFromCSV(Dataset): def __init__(self, csv_path, transform=None): self.data = pd.read_csv(csv_path) self.labels = pd.get_dummies(self.data['emotion']).as_matrix() self.height = 48 self.width = 48 self.transform = transform def __getitem__(self, index): # This method should return only 1 sample and label # (according to "index"), not the whole dataset # So probably something like this for you: pixel_sequence = self.data['pixels'][index] face = [int(pixel) for pixel in pixel_sequence.split(' ')] face = np.asarray(face).reshape(self.width, self.height) face = cv2.resize(face.astype('uint8'), (self.width, self.height)) label = self.labels[index] return face, label def __len__(self): return len(self.labels) dataset = CustomDatasetFromCSV(my_path) batch_size = 16 validation_split = .2 shuffle_dataset = True random_seed= 42 # Creating data indices for training and validation splits: dataset_size = len(dataset) indices = list(range(dataset_size)) split = int(np.floor(validation_split * dataset_size)) if shuffle_dataset : np.random.seed(random_seed) np.random.shuffle(indices) train_indices, val_indices = indices[split:], indices[:split] # Creating PT data samplers and loaders: train_sampler = SubsetRandomSampler(train_indices) valid_sampler = SubsetRandomSampler(val_indices) train_loader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, sampler=train_sampler) validation_loader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, sampler=valid_sampler) # Usage Example: num_epochs = 10 for epoch in range(num_epochs): # Train: for batch_index, (faces, labels) in enumerate(train_loader): # ... </code></pre>
49,724,537
Intl.NumberFormat either 0 or two fraction digits
<p>My formatter looks like this</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const formatter = new Intl.NumberFormat('en-NZ', { style: 'currency', currency: 'NZD', minimumFractionDigits: 2, });</code></pre> </div> </div> </p> <p>How can I adjust this so that whole numbers have 0 fraction digits</p> <pre><code>formatter.format(4); // want output "$4" </code></pre> <p>whilst fractions always show two digits?</p> <pre><code>formatter.format(4.1); // want output "$4.10" </code></pre>
49,724,581
4
0
null
2018-04-09 01:48:50.483 UTC
10
2021-01-07 18:38:23.783 UTC
null
null
null
null
449,045
null
1
54
javascript
49,530
<p>You could try something like this:</p> <pre><code>formatter.format(amount).replace(/\D00$/, ''); </code></pre> <p>Update:</p> <p>In response to the many-months-later comment by @Marek, the above regex already handles differing decimal symbols (either <code>.</code> or <code>,</code>), but it's true that it doesn't handle trailing currency symbols. That can be fixed this way:</p> <pre><code>formatter.format(amount).replace(/\D00(?=\D*$)/, ''); </code></pre>
34,923,444
Does Xamarin.Forms support periodic background tasks?
<p>I am having a difficult time finding documentation on background tasks support for Xamarin.Forms. Does Xamarin.Forms provide support for periodic background tasks?</p> <p>I need to implement this for both Windows Phone 10 and Android.</p>
34,924,150
3
0
null
2016-01-21 12:09:08.577 UTC
9
2017-08-25 01:15:09.86 UTC
null
null
null
null
492,701
null
1
10
xamarin|backgroundworker|xamarin.forms
12,318
<p>XF has no implementation for background tasks. You will need to implement these natively. Below are examples on how to do it for each type of project.</p> <p><strong>UWP</strong></p> <p><a href="https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/BackgroundTask" rel="noreferrer">https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/BackgroundTask</a></p> <p><strong>Android</strong> <a href="https://developer.xamarin.com/guides/android/application_fundamentals/backgrounding/part_2_android_services/" rel="noreferrer">https://developer.xamarin.com/guides/android/application_fundamentals/backgrounding/part_2_android_services/</a></p> <p><strong>WinRT</strong></p> <p><a href="https://visualstudiomagazine.com/articles/2013/05/01/background-tasks-in-windows-store-apps.aspx" rel="noreferrer">https://visualstudiomagazine.com/articles/2013/05/01/background-tasks-in-windows-store-apps.aspx</a></p> <p><strong>iOS</strong></p> <p>Just for those that want iOS as well. <a href="https://developer.xamarin.com/guides/ios/application_fundamentals/backgrounding/part_3_ios_backgrounding_techniques/" rel="noreferrer">https://developer.xamarin.com/guides/ios/application_fundamentals/backgrounding/part_3_ios_backgrounding_techniques/</a></p> <p><strong>Xamarin.Forms</strong></p> <p>Going into more detail for each section is <a href="https://xamarinhelp.com/xamarin-background-tasks/" rel="noreferrer">https://xamarinhelp.com/xamarin-background-tasks/</a></p>
42,628,660
What does terraform refresh really do?
<p>While using terraform to deploy a fairly large infrastructure in AWS, our remote <code>tfstate</code> got corrupted and was deleted.</p> <p>From the documentation, I gather that <code>terraform refresh</code> should query AWS to get the real state of the infrastructure and update the tfstate accordigly, but that does not happen: my tfstate is untouched and plan + apply give a lot of <code>Already existing</code> errors.</p> <p>What does <code>terraform refresh</code> really do?</p>
42,630,201
4
0
null
2017-03-06 14:53:21.93 UTC
7
2020-12-22 17:17:15.237 UTC
null
null
null
null
2,938,149
null
1
37
amazon-web-services|terraform
36,659
<p><a href="https://www.terraform.io/docs/commands/refresh.html" rel="noreferrer"><code>terraform refresh</code></a> attempts to find any resources held in the state file and update with any drift that has happened in the provider outside of Terraform since it was last ran.</p> <p>For example, lets say your state file contains 3 EC2 instances with instance ids of <code>i-abc123</code>, <code>i-abc124</code>, <code>i-abc125</code> and then you delete <code>i-abc124</code> outside of Terraform. After running <code>terraform refresh</code>, a <code>plan</code> would show that it needs to create the second instance while a destroy plan would show that it only needs to destroy the first and third instances (and not fail to destroy the missing second instance).</p> <p>Terraform makes a very specific decision to not interfere with things that aren't being managed by Terraform. That means if the resource doesn't exist in its state file then it absolutely will not touch it in any way. This enables you to run Terraform alongside other tools as well as making manual changes in the AWS console. It also means that you can run Terraform in different contexts simply by providing a different state file to use, allowing you to split your infrastructure up into multiple state files and save yourself from catastrophic state file corruption.</p> <p>To get yourself out of your current hole I suggest you use <a href="https://www.terraform.io/docs/import/" rel="noreferrer"><code>terraform import</code></a> liberally to get things back into your state file or, if possible, manually destroy everything outside of Terraform and start from scratch.</p> <p>In future I would suggest both splitting out state files to apply for more granular contexts and also to store your remote state in an S3 bucket with versioning enabled. You could also look towards tools like <a href="https://github.com/gruntwork-io/terragrunt" rel="noreferrer">Terragrunt</a> to lock your state file to help avoid corruption or wait for the native state file locking in the upcoming 0.9 release of Terraform. </p>
50,201,874
xampp phpmyadmin, Incorrect format parameter
<p>Im trying to import the database of my client side (wordpress platform) to localhost (using xampp). </p> <p>Other clients' sites work OK, except for this one particular site. When I want to import it, it just showed "phpMyAdmin - Error. Incorrect format parameter". <a href="https://i.stack.imgur.com/Q0zyd.jpg" rel="noreferrer">The error image</a></p> <p>I tried googled it, but it's like no one having this error when importing a database.</p> <p>Do you guys have any idea? Feel free to ask anything, I'm not sure what information I need to provide since I just using quick exporting and the import setting I just let it remain default.</p>
50,271,270
7
0
null
2018-05-06 16:15:54.92 UTC
17
2022-08-14 19:17:46.273 UTC
null
null
null
null
8,754,221
null
1
34
database|import|phpmyadmin|xampp
72,624
<p>I had the same problem recently.</p> <p>I did these 3 things and it worked:</p> <ol> <li><p>Made sure the Collation of the exported database is the same as the newly created one.</p></li> <li><p>Made these changes in my php.ini(xampp/php/php.ini) file</p> <pre><code>max_execution_time = 5000 max_input_time = 5000 memory_limit = 1000M post_max_size = 750M upload_max_filesize = 750M </code></pre></li> <li><p>Made this change in my \phpmyadmin\libraries\config.default.php file:</p></li> </ol> <p>change </p> <pre><code>$cfg['ExecTimeLimit'] = 300; </code></pre> <p>to </p> <pre><code>$cfg['ExecTimeLimit'] = 0; </code></pre> <p>(So there is no limit)</p>
49,997,025
Check whether the ARReferenceImage is no longer visible in the camera's view
<p>I would like to check whether the <a href="https://developer.apple.com/documentation/arkit/arreferenceimage" rel="noreferrer">ARReferenceImage</a> is no longer visible in the camera's view. At the moment I can check if the image's node is in the camera's view, but this node is still visible in the camera's view when the <a href="https://developer.apple.com/documentation/arkit/arreferenceimage" rel="noreferrer">ARReferenceImage</a> is covered with another image or when the image is removed. </p> <pre><code>func renderer(_ renderer: SCNSceneRenderer, updateAtTime time: TimeInterval) { guard let node = self.currentImageNode else { return } if let pointOfView = sceneView.pointOfView { let isVisible = sceneView.isNode(node, insideFrustumOf: pointOfView) print("Is node visible: \(isVisible)") } } </code></pre> <p>So I need to check if the image is no longer visible instead of the image's node visibility. But I can't find out if this is possible. The first screenshot shows three boxes that are added when the image beneath is found. When the found image is covered (see screenshot 2) I would like to remove the boxes.</p> <p><a href="https://i.stack.imgur.com/tOonF.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/tOonF.jpg" alt="Found image with boxes"></a></p> <p><a href="https://i.stack.imgur.com/qTB1D.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/qTB1D.jpg" alt="Convered image with boxes"></a></p>
50,151,200
7
0
null
2018-04-24 08:37:58.45 UTC
11
2019-07-20 21:45:00.197 UTC
2018-04-24 11:26:23.573 UTC
null
6,345,920
null
6,345,920
null
1
19
swift|xcode|scenekit|arkit|aranchor
7,359
<p>I managed to fix the problem! Used a little bit of Maybe1's code and his concept to solving the problem, but in a different way. The following line of code is still used to reactivate the image recognition.</p> <pre><code>// Delete anchor from the session to reactivate the image recognition sceneView.session.remove(anchor: anchor) </code></pre> <p>Let me explain. First we need to add some variables.</p> <pre><code>// The scnNodeBarn variable will be the node to be added when the barn image is found. Add another scnNode when you have another image. var scnNodeBarn: SCNNode = SCNNode() // This variable holds the currently added scnNode (in this case scnNodeBarn when the barn image is found) var currentNode: SCNNode? = nil // This variable holds the UUID of the found Image Anchor that is used to add a scnNode var currentARImageAnchorIdentifier: UUID? // This variable is used to call a function when there is no new anchor added for 0.6 seconds var timer: Timer! </code></pre> <p>The complete code with comments below.</p> <pre><code>/// - Tag: ARImageAnchor-Visualizing func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) { guard let imageAnchor = anchor as? ARImageAnchor else { return } let referenceImage = imageAnchor.referenceImage // The following timer fires after 0.6 seconds, but everytime when there found an anchor the timer is stopped. // So when there is no ARImageAnchor found the timer will be completed and the current scene node will be deleted and the variable will set to nil DispatchQueue.main.async { if(self.timer != nil){ self.timer.invalidate() } self.timer = Timer.scheduledTimer(timeInterval: 0.6 , target: self, selector: #selector(self.imageLost(_:)), userInfo: nil, repeats: false) } // Check if there is found a new image on the basis of the ARImageAnchorIdentifier, when found delete the current scene node and set the variable to nil if(self.currentARImageAnchorIdentifier != imageAnchor.identifier &amp;&amp; self.currentARImageAnchorIdentifier != nil &amp;&amp; self.currentNode != nil){ //found new image self.currentNode!.removeFromParentNode() self.currentNode = nil } updateQueue.async { //If currentNode is nil, there is currently no scene node if(self.currentNode == nil){ switch referenceImage.name { case "barn": self.scnNodeBarn.transform = node.transform self.sceneView.scene.rootNode.addChildNode(self.scnNodeBarn) self.currentNode = self.scnNodeBarn default: break } } self.currentARImageAnchorIdentifier = imageAnchor.identifier // Delete anchor from the session to reactivate the image recognition self.sceneView.session.remove(anchor: anchor) } } </code></pre> <p>Delete the node when the timer is finished indicating that there was no new ARImageAnchor found.</p> <pre><code>@objc func imageLost(_ sender:Timer){ self.currentNode!.removeFromParentNode() self.currentNode = nil } </code></pre> <p>In this way the currently added scnNode wil be deleted when the image is covered or when there is found a new image. </p> <p><a href="https://i.stack.imgur.com/RrKb7.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/RrKb7.gif" alt="enter image description here"></a></p> <p>This solution does unfortunately not solve the positioning problem of images because of the following:</p> <blockquote> <p>ARKit doesn’t track changes to the position or orientation of each detected image.</p> </blockquote>
22,855,710
Play Framework - add a field to JSON object
<p>I have a problem with adding a field to Json object in Play Framework using Scala:</p> <p>I have a case class containing data. For example:</p> <pre><code>case class ClassA(a:Int,b:Int) </code></pre> <p>and I am able to create a Json object using Json Writes:</p> <pre><code>val classAObject = ClassA(1,2) implicit val classAWrites= Json.writes[ClassA] val jsonObject = Json.toJson(classAObject) </code></pre> <p>and the Json would look like:</p> <pre><code>{ a:1, b:2 } </code></pre> <p>Let's suppose I would like to add an additional 'c' field to the Json object. Result:</p> <pre><code>{ a:1, b:2, c:3 } </code></pre> <p>How do I do that without creating a new case class or creating my Json object myself using Json.obj? I am looking for something like:</p> <pre><code>jsonObject.merge({c:3}) </code></pre> <p>Any help appreciated!</p>
22,856,358
3
0
null
2014-04-04 06:57:13.55 UTC
9
2015-05-23 09:29:02.647 UTC
null
null
null
null
2,868,443
null
1
42
json|scala|playframework|playframework-2.0
22,110
<p><code>JsObject</code> has a <code>+</code> method that allows you to add fields to an object, but unfortunately your <code>jsonObject</code> is statically typed as a <code>JsValue</code>, not a <code>JsObject</code>. You can get around this in a couple of ways. The first is to use <code>as</code>:</p> <pre><code> scala&gt; jsonObject.as[JsObject] + ("c" -&gt; Json.toJson(3)) res0: play.api.libs.json.JsObject = {"a":1,"b":2,"c":3} </code></pre> <p>With <code>as</code> you're essentially downcasting—you're telling the compiler, "you only know that this is a <code>JsValue</code>, but believe me, it's also a <code>JsObject</code>". This is safe in this case, but it's not a good idea. A more principled approach is to use the <code>OWrites</code> directly:</p> <pre><code>scala&gt; val jsonObject = classAWrites.writes(classAObject) jsonObject: play.api.libs.json.JsObject = {"a":1,"b":2} scala&gt; jsonObject + ("c" -&gt; Json.toJson(3)) res1: play.api.libs.json.JsObject = {"a":1,"b":2,"c":3} </code></pre> <p>Maybe someday the <code>Json</code> object will have a <code>toJsonObject</code> method that will require a <code>OWrites</code> instance and this overly explicit approach won't be necessary.</p>
27,201,359
What kind of Certifcate and Provisioning Profile is needed for an iOS Apple TestFlight release?
<p>I'm planning to release a beta version of my iPhone app on iOS 8 devices through the new Apple TestFlight app. What kind of Certifcate and Provisioning Profile is needed for that? Do I need a <em>Production</em> certificate and <em>Distribution</em> provisioning profile?</p> <p>Available are these:</p> <pre><code>Certificate: - Pending - Development - Production Provisioning Profile: - Development - Distribution </code></pre>
27,237,386
3
0
null
2014-11-29 10:47:07.583 UTC
18
2021-03-17 03:25:38.363 UTC
null
null
null
null
974,925
null
1
64
ios|iphone|testflight|beta
43,316
<p>I believe you need a Production certificate with a Distribution profile for "App Store". I just submit my app which is now in review for external beta testers. The first time I submit the app I was using an Ad Hoc profile as we always did while using the original Testflight. That profile caused the app to be rejected before it even got to the review processes. Once I changed to using an App Store profile it passed into the review process. So, Production cert, Distribution App Store provisioning profile worked for me. </p> <p>The <a href="https://developer.apple.com/library/ios/documentation/IDEs/Conceptual/AppDistributionGuide/TestingYouriOSApp/TestingYouriOSApp.html">Apple developer site</a> has some information on beta testing options for ios. It discusses both Ad Hoc and iTunes connect distribution.</p> <p>You can also <a href="http://code.tutsplus.com/tutorials/ios-8-beta-testing-with-testflight--cms-22224">check out this tutorial</a>, which goes through the processes using xcode to submit your build for testing.</p> <p>Hope that helps.</p>
40,652,327
"module not found : Error: Cannot resolve module 'react/lib/ReactMount' "
<p>I used Reactjs and webpack to start a project, and when I run the "node server" in the command prompt, there is an error like this:</p> <p><a href="https://i.stack.imgur.com/JtLvh.png" rel="noreferrer"><img src="https://i.stack.imgur.com/JtLvh.png" alt="enter image description here"></a></p> <p>And the chrome explorer opened successful but also have problems as follows:</p> <p><a href="https://i.stack.imgur.com/sjsoZ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/sjsoZ.png" alt="enter image description here"></a></p> <p>The github is: (github.com/Yangqin0607/gallery)</p> <p>Here is the package.json</p> <pre><code> { "private": true, "version": "0.0.1", "description": "YOUR DESCRIPTION - Generated by generator-react-webpack", "main": "", "scripts": { "clean": "rimraf dist/*", "copy": "copyfiles -f ./src/index.html ./src/favicon.ico ./dist", "dist": "npm run copy &amp; webpack --env=dist", "lint": "eslint ./src", "posttest": "npm run lint", "release:major": "npm version major &amp;&amp; npm publish &amp;&amp; git push --follow-tags", "release:minor": "npm version minor &amp;&amp; npm publish &amp;&amp; git push --follow-tags", "release:patch": "npm version patch &amp;&amp; npm publish &amp;&amp; git push --follow-tags", "serve": "node server.js --env=dev", "serve:dist": "node server.js --env=dist", "start": "node server.js --env=dev", "test": "karma start", "test:watch": "karma start --autoWatch=true --singleRun=false" }, "repository": "", "keywords": [], "author": "Your name here", "devDependencies": { "babel-core": "^6.0.0", "babel-eslint": "^6.0.0", "babel-loader": "^6.0.0", "babel-polyfill": "^6.3.14", "babel-preset-es2015": "^6.0.15", "babel-preset-react": "^6.0.15", "babel-preset-stage-0": "^6.5.0", "bower-webpack-plugin": "^0.1.9", "chai": "^3.2.0", "copyfiles": "^1.0.0", "css-loader": "^0.23.0", "eslint": "^3.0.0", "eslint-loader": "^1.0.0", "eslint-plugin-react": "^6.0.0", "file-loader": "^0.9.0", "glob": "^7.0.0", "isparta-instrumenter-loader": "^1.0.0", "karma": "^1.0.0", "karma-chai": "^0.1.0", "karma-coverage": "^1.0.0", "karma-mocha": "^1.0.0", "karma-mocha-reporter": "^2.0.0", "karma-phantomjs-launcher": "^1.0.0", "karma-sourcemap-loader": "^0.3.5", "karma-webpack": "^1.7.0", "minimist": "^1.2.0", "mocha": "^3.0.0", "null-loader": "^0.1.1", "open": "0.0.5", "phantomjs-prebuilt": "^2.0.0", "react-addons-test-utils": "^15.0.0", "react-hot-loader": "^1.2.9", "rimraf": "^2.4.3", "style-loader": "^0.13.0", "url-loader": "^0.5.6", "webpack": "^1.12.0", "webpack-dev-server": "^1.12.0" }, "dependencies": { "core-js": "^2.0.0", "normalize.css": "^4.0.0", "react": "^15.0.0", "react-dom": "^15.0.0" } } </code></pre>
40,661,900
10
3
null
2016-11-17 10:24:28.41 UTC
4
2020-05-27 12:19:13.66 UTC
2016-11-17 14:29:30.813 UTC
null
7,172,276
null
7,172,276
null
1
27
reactjs|webpack
41,293
<p>This issue is related to the <code>react-hot-loader</code> package. You are using an old version that relies on the <code>ReactMount.js</code> file being present in the <code>node_modules/react/lib</code> folder.</p> <p>There is no easy one way fix for that but you have a few options which are:</p> <ol> <li><p>Try to follow the instructions here: <a href="https://github.com/gaearon/react-hot-loader/blob/v3.0.0-beta.6/docs/README.md#usage-with-external-react" rel="noreferrer">https://github.com/gaearon/react-hot-loader/blob/v3.0.0-beta.6/docs/README.md#usage-with-external-react</a> (but I have been unlucky so far)</p></li> <li><p>Remove the hot reloader for react (in your <code>webpack.config</code> remove the <code>'react-hot'</code> loader)</p></li> <li><p>Update the <code>react-hot-loader</code> package to version 3 (here is how to do so: <a href="https://github.com/gaearon/redux-devtools/commit/64f58b7010a1b2a71ad16716eb37ac1031f93915" rel="noreferrer">https://github.com/gaearon/redux-devtools/commit/64f58b7010a1b2a71ad16716eb37ac1031f93915</a>). But note that this package has been in alpha for a while now...</p></li> <li><p>Rollback your react version to one that includes the <code>ReactMount.js</code> in the lib folder (15.0.1 used to have this file not sure when it stopped).</p></li> </ol> <p><strong>Update:</strong> React Hot Loader 3 is now in beta with a more comprehensive upgrade guide: <a href="https://github.com/gaearon/react-hot-loader/tree/v3.0.0-beta.7/docs#migration-to-30" rel="noreferrer">https://github.com/gaearon/react-hot-loader/tree/v3.0.0-beta.7/docs#migration-to-30</a></p>
38,688,111
Kotlin: Iterate over components of object
<p>Each data class object has a component for each property like component1, component2, etc.. I was wondering if there is any way in Kotlin to iterate over each component of a class. Say I have class:</p> <pre><code>data class User(age:Int, name:String) </code></pre> <p>Could I do something like:</p> <pre><code>for(component in aUserObject){ //do some stuff with age or name } </code></pre> <p>?</p>
38,688,203
5
1
null
2016-07-31 20:26:04.27 UTC
12
2022-04-19 09:09:38.143 UTC
2020-09-26 10:04:15.95 UTC
null
1,295,419
null
1,295,419
null
1
47
kotlin
36,266
<p>First of all, the <code>componentN</code> properties are available only on data classes, not on every object.</p> <p>There is no API specifically for iterating over the components, but you can use the <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.reflect.full/member-properties.html" rel="noreferrer">Kotlin reflection</a> to iterate over properties of any class:</p> <pre><code>class User(val age: Int, val name: String) fun main(args: Array&lt;String&gt;) { val user = User(25, "Bob") for (prop in User::class.memberProperties) { println("${prop.name} = ${prop.get(user)}") } } </code></pre>
31,249,112
Allow docker container to connect to a local/host postgres database
<p>I've recently been playing around with Docker and QGIS and have installed a container following the instructions in <a href="http://kartoza.com/qgis-desktop-in-docker/" rel="noreferrer">this tutorial</a>.</p> <p>Everything works great, although I am unable to connect to a localhost postgres database that contains all my GIS data. I figure this is because my postgres database is not configured to accept remote connections and have been editing the postgres conf files to allow remote connections using the instructions in <a href="http://blog.jsinh.in/how-to-enable-remote-access-to-postgresql-database-server/#.VZqPgnXInK5" rel="noreferrer">this article</a>.</p> <p>I'm still getting an error message when I try and connect to my database running QGIS in Docker: could not connect to server: <code>Connection refused Is the server running on host "localhost" (::1) and accepting TCP/IP connections to port 5433?</code> The postgres server is running, and I've edited my <strong>pg_hba.conf</strong> file to allow connections from a range of IP addresses (172.17.0.0/32). I had previously queried the IP address of the docker container using <code>docker ps</code> and although the IP address changes, it has so far always been in the range 172.17.0.x</p> <p>Any ideas why I can't connect to this database? Probably something very simple I imagine!</p> <p>I'm running Ubuntu 14.04; Postgres 9.3</p>
31,249,288
14
0
null
2015-07-06 14:57:41.92 UTC
89
2022-02-14 11:34:36.6 UTC
2018-06-26 14:52:28.797 UTC
null
5,380,322
null
2,609,232
null
1
237
ubuntu|docker|postgresql-9.3|qgis
259,791
<h3>TL;DR</h3> <ol> <li>Use <code>172.17.0.0/16</code> as IP address range, not <code>172.17.0.0/32</code>.</li> <li>Don't use <code>localhost</code> to connect to the PostgreSQL database on your host, but the host's IP instead. To keep the container portable, start the container with the <code>--add-host=database:&lt;host-ip&gt;</code> flag and use <code>database</code> as hostname for connecting to PostgreSQL.</li> <li>Make sure PostgreSQL is configured to listen for connections on all IP addresses, not just on <code>localhost</code>. Look for the setting <code>listen_addresses</code> in PostgreSQL's configuration file, typically found in <code>/etc/postgresql/9.3/main/postgresql.conf</code> (credits to @DazmoNorton).</li> </ol> <h3>Long version</h3> <p><code>172.17.0.0/32</code> is not a <em>range</em> of IP addresses, but a single address (namly <code>172.17.0.0</code>). No Docker container will ever get that address assigned, because it's the network address of the Docker bridge (<code>docker0</code>) interface.</p> <p>When Docker starts, it will create a new bridge network interface, that you can easily see when calling <code>ip a</code>:</p> <pre><code>$ ip a ... 3: docker0: &lt;NO-CARRIER,BROADCAST,MULTICAST,UP&gt; mtu 1500 qdisc noqueue state DOWN link/ether 56:84:7a:fe:97:99 brd ff:ff:ff:ff:ff:ff inet 172.17.42.1/16 scope global docker0 valid_lft forever preferred_lft forever </code></pre> <p>As you can see, in my case, the <code>docker0</code> interface has the IP address <code>172.17.42.1</code> with a netmask of <code>/16</code> (or <code>255.255.0.0</code>). This means that the network address is <code>172.17.0.0/16</code>.</p> <p>The IP address is randomly assigned, but without any additional configuration, it will always be in the <code>172.17.0.0/16</code> network. For each Docker container, a random address from that range will be assigned.</p> <p>This means, if you want to grant access from all possible containers to your database, use <code>172.17.0.0/16</code>.</p>
5,881,872
Domain Driven Design - how the layers should be organized?
<p>I'm very much new to software development. I think layered architecture is a great way to reduce the complexities that arise in the process of object oriented software development and, not to mention, to keep your code organized. </p> <p>I'm interested to learn about Domain Driven Design approach and I've run into some problems to get myself introduced to it (of course, beginner level ones).<br> Here it is - </p> <p>I want to build an application to save person related data in database and display person details in a WPF <code>DataGrid</code> (I know, DDD is definitely not for the apps of such scale, but just to keep things simple for an amateur like me). So, I created a domain class "Person", something like – </p> <pre class="lang-cs prettyprint-override"><code> public class Person { public Person(dataType paramA) { this.PropertyA = paramA; } private dataType _fieldA; public dataType PropertyA { //encapsulates _fieldA } public dataType PropertyX { //some code that manipulates private field } private dataType MethodPQR(dataType param) { //some code } } </code></pre> <p>Now, my understanding of DDD says the architecture (the simplest version of it) should be as follows (please, correct me if I'm wrong) -<br> <img src="https://i.stack.imgur.com/jYvXp.png" alt="enter image description here"> </p> <p>Note:</p> <ol> <li><p>I want the <code>DataGrid</code> to be bound to some <code>ObservableCollection</code>, to reflect any kind of changes instantly. </p></li> <li><p>It's a WPF application but not necessarily be in MVVM pattern and I deliberately want to use the code behind.</p></li> </ol> <p>My questions are -</p> <ol> <li><p>What kind of codes belong to the <code>Application Layer</code>? </p></li> <li><p>My guess is, I should definitely not bind an <code>ObservableColletion</code> of my domain object (i.e. <code>Person</code>) as the <code>ItmsSource</code> of the <code>DataGrid</code>. What type of object then I should extract from the domain object, and how? </p></li> <li><p>To keep a decoupling between <code>Presentation Layer</code> and <code>Domain Layer</code> probably there's a convention like <code>never instantiate domain objects directly in the presentation layer</code>. What are the <code>non-direct</code> approaches then? </p></li> <li><p>If the code-behind talks to the <code>Application Layer</code> then should the <code>Application Layer</code> talk to the <code>Data Repository</code>? But what if some kind of domain access is needed which is <em>not</em> data access related (may be not in this app, but it may occur, right?) In that scenario, who's that <code>X</code> guy (sub-layer/module) in <code>Domain Layer</code> that the <code>Application Layer</code> should talk to?</p></li> </ol> <p>I know my questions are of very much amateur level, but they are questions indeed, raised from problems I'm facing to get a clear picture. So, if anybody has time, any response will be appreciated.</p> <p><strong>EDIT :</strong> I'm not sure if <code>Data Repository</code> should have a reference of <code>Domain Model</code>.</p>
5,897,440
1
2
null
2011-05-04 10:20:00.933 UTC
31
2020-12-22 13:35:02.13 UTC
2019-11-18 00:19:01.553 UTC
null
446,519
null
446,519
null
1
44
domain-driven-design|repository|code-organization|project-organization|layer
24,315
<p>Speaking in terms of more &quot;classical&quot; DDD, yes domain objects are typically not allowed anywhere outside of the domain. But it is not an absolute rule that domain objects are not used in the presentation layer. For example, Naked Objects represents a school of thought where domain objects are used directly. I myself adhere mostly to a philosophy where domain objects are not used directly, so I am not familiar with all the practices they suggest, I personally would think binding to a domain object directly would be ill-advised, but ... Just keep in mind not everyone views this as a requirement.</p> <p>If you do not allow domain objects outside of the domain itself, you would typically use DTO or Data Transfer Objects which are simply classes only with properties and such DTO classes do not have domain behaviors. DTOs often mirror the domain model structure exactly but do not have to.</p> <p>Business logic is supposed to be implemented in the domain model, so much of what is in the application layer is involved with coordinating various services, typically to bring the data to and from the client applications. Many people use some form of SOA or at least web services for this. These call the repositories but also require other components such as assemblers to take the domain objects returned from repository calls and copy the property values into DTOs, which are then serializable and returned to the caller. The caller is often a presenter or controller but if you are not using MVC or MVP the caller would still be in the presentation layer. The reverse trip is more complex - the UI may send back DTOs that represent updates or DTOs that represent new objects to be added. The prime purpose of the application layer is mediating these back and forth activities.</p> <p>As far as &quot;non-data access&quot; of the domain layer, there are a couple of typical examples. Most people usually refer to the &quot;X&quot; component you may be thinking of as a Domain Service. A Domain service differs from an Application Service by it's proximity to the domain model and the presence of actual business logic.</p> <p>For example, if an application involves some kind of order placement, there are actually two concerns - order placement and order fulfillment. Application Services mediate the transfer of the data needed to formulate an order placement to the UI and then return the order that the user wishes to place. But that is only mediating data transfer and that is where Application Services end. A Domain Service may then be needed to apply business rules and construct additional domain objects that are needed to actually fulfill that order.</p> <p>In general, I find that to be a useful concept or metaphor that can be applied to many scenarios - an Application Service facilitates a request of some sort, in terms of the request <strong>submission</strong> only. A Domain Service on the other hand facilitates the actual request <strong>fulfillment</strong>.</p> <p>The only other mode of &quot;access&quot; other than data-oriented I have encountered or can readily imagine is process-oriented functionality. This is not encountered in every application but is prevalent in certain fields. For example in healthcare where I work you may want applications that incorporate significant elements of managing both the clinical data as well as the clinical process. I solve this problem by not making that process emphasis a part of my domain model and using different tools for that instead.</p> <p>OOP techniques are not well suited for an actual process itself, they are useful for providing data to and capturing data from a process. Object-oriented is after all also primarily noun-oriented. For real-time process management you need &quot;verb oriented programming&quot; more than &quot;noun oriented programming&quot;. Workflow tools are &quot;verb oriented&quot; tools that can be complementary to Domain-driven models for applications that are both data-intensive and process-intensive. I do a lot of work that involves both C# DDD models and Workflow Foundation models, but again this is only needed for certain types of applications. Many typical business apps only require domain models and services.</p> <p><em><strong>Finally the most important aspect of DDD is not any technique or architecture. The real heart of it revolves around the Ubiquitous Language and interaction with (in my strong opinion DIRECT interaction with) domain experts to distill out critical domain knowledge. (Most companies that claim to do DDD in my opinion do not because so many companies refuse to allow the business and development to interact directly, but that is another topic... ) It is the extractions and incorporation of domain knowledge, rather than any technique that actually separates DDD from conventional OOP and that is where the real value of DDD arises.</strong></em></p> <p>EDIT</p> <p>As far as repository use goes, the diagram is correct. Typically the application layer always goes through a repository for domain objects. First of all, you have to be able to bring data to the application, and most applications also need some level of query ability.</p> <p>The domain layer OTOH usually does <em>not</em> interact with repositories. Typically you want the domain model to be self-contained and decoupled from any specific technology, i.e it should represent &quot;pure domain knowledge&quot;. Persistence is inherently tightly coupled to some sort of specific technology, so in general, people strive to make their domain models free of any persistence implementation. You have repositories but you typically do not want to call repository methods in the domain model.</p> <p>Within the domain model itself, objects are obtained either as new objects (which may be instantiated directly or through a factory) or else reached by traversing associations. Sometimes when creating a new object it is impractical to pass everything needed into a constructor, so this is one case where you might need some sort of data access within the domain model itself. Usually what people do is pass in a data service via an interface so that the domain model may be provided with data access but remains decoupled from the data layer implementation. But for the most part, domain objects act and interact with other domain objects that are already instantiated.</p>
37,860,183
Occasional svn: E170013: Unable to connect to a repository at URL 'https://svn.....' svn: E730054: Error running context
<p>I need help with svn errors E170013 and E730054:</p> <p>When executing the command "svn checkout..." in command line, I get the error </p> <pre><code>svn: E170013: Unable to connect to a repository at URL 'https://svn.....' svn: E730054: Error running context: An existing connection was forcibly closed by the remote host. </code></pre> <p>However, if I run the same command right after (only in the next 3 minutes), the command is executed successfully without errors, and the source code is checked out successfully.</p> <p>Otherwise after 3 minutes (approximately), if I want to checkout again I need to run the svn checkout command, get the errors <code>E170013 and E730054</code>, then run the same command again and the svn checkout works again.</p> <p>It seems to me that after a certain period of time (3min in my case) the socket between the svn client and svn server is closed, and trying to checkout and/or getting these errors is what actually triggers the connection to be reopened again. </p> <p>In other words, my issue is that in order to perform an svn checkout, the first will always fail, and only next trys will succeed. After a period of time I need to repeat the same steps again and always do two "<strong>svn checkout</strong>" so the second one works.</p> <p>My interpretation may be wrong but this is the behavior I get. I hope you got my issue.</p> <p>I would like please to understand why such svn behavior, what causes these errors and how can I solve the issue.</p> <pre><code>SVN server version: 1.8.13 (r1667537) compiled Mar 20 2015, 11:32:18 on x86_64-unknown-linux-gnu SVN client version: 1.9.3 (r1718519) compiled Dec 22 2015, 09:12:06 on x86_64-microsoft-windows6.2.9200 SVN Client running on Windows Server 2008 R2 and SVN server in linux machine. </code></pre> <p>Please feel free to ask any question. I would be happy to provide you more information.</p> <p>Thank you so much in advance.</p>
40,426,740
5
0
null
2016-06-16 13:06:41.203 UTC
0
2020-08-02 19:42:21.257 UTC
2016-06-16 14:42:45.84 UTC
null
5,558,072
null
6,474,717
null
1
6
svn|version-control|tortoisesvn
52,285
<p>I finally found the solution.</p> <p>Instead of writing down the link <a href="https://svn" rel="noreferrer">https://svn</a>..... in the svncheckout command, I used the numeric IP address (e.g. 192.168.73.39) of the server instead of its hostname and it worked.</p> <p>I hope this helps someone.</p>
28,635,671
Using SQL Server stored procedures from Python (pyodbc)
<p>I'm have a stored procedure, code:</p> <pre><code>DECLARE @RC int DECLARE @id varchar(13) DECLARE @pw varchar(13) DECLARE @depart varchar(32) DECLARE @class varchar(12) DECLARE @name varchar(12) DECLARE @birthday varchar(10) DECLARE @grade int DECLARE @subgrade int SELECT @id = 'test' SELECT @pw = '12345' SELECT @depart = 'none' SELECT @class = 'GM' SELECT @name = 'name' SELECT @birthday = 'None' SELECT @grade = 3 SELECT @subgrade = 2 EXEC @RC = [my_database].[dbo].[my_table] @id, @pw, @depart, @class, @name, @birthday, @grade, @subgrade DECLARE @PrnLine nvarchar(4000) PRINT 'Stored Procedure: my_database.dbo.my_table' SELECT @PrnLine = ' Return Code = ' + CONVERT(nvarchar, @RC) </code></pre> <p>How i can make a raw sql query to create account using this procedure? I'm using flask and pyodbc.</p>
28,636,308
7
0
null
2015-02-20 18:22:06.683 UTC
9
2021-03-15 15:26:28.443 UTC
2017-02-02 18:01:57.8 UTC
null
2,144,390
null
4,189,396
null
1
30
python|sql-server|pyodbc
91,407
<p>From the <a href="https://code.google.com/p/pyodbc/wiki/StoredProcedures" rel="noreferrer">pyodbc documentation</a></p> <blockquote> <p>To call a stored procedure right now, pass the call to the execute method using either a format your database recognizes or using the <a href="http://msdn.microsoft.com/en-us/library/ms131685.aspx" rel="noreferrer">ODBC call escape format</a>. (The ODBC driver will then reformat the call for you to match the given database.)</p> <p>For SQL Server you would use something like this:</p> </blockquote> <pre><code># SQL Server format cursor.execute(&quot;exec sp_dosomething(123, 'abc')&quot;) # ODBC format cursor.execute(&quot;{call sp_dosomething(123, 'abc')}&quot;) </code></pre> <p>So to call your procedure</p> <pre><code>id_ = 'test' pw = '12345' depart = 'none' class_ = 'GM' name = 'name' birthday = 'None' grade = 3 subgrade = 2 sql = 'exec [my_database].[dbo].[my_table](?, ?, ?, ?, ?, ?, ?, ?)' values = (id_, pw, depart, class_, name, birthday, grade, subgrade) cursor.execute(sql, (values)) </code></pre>
40,676,085
Why can't I use a starred expression?
<p>My code </p> <pre><code>$ python Python 3.5.2 |Continuum Analytics, Inc.| (default, Jul 2 2016, 17:53:06) [GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; a = (1, 2) &gt;&gt;&gt; '%d %d %d' % (0, *a) '0 1 2' &gt;&gt;&gt; '%d %d %d' % (*a, 3) '1 2 3' &gt;&gt;&gt; '%d %d' % (*a) File "&lt;stdin&gt;", line 1 SyntaxError: can't use starred expression here &gt;&gt;&gt; </code></pre> <p>My question, why?</p> <p>In a more serious tone: I'd like an answer, or a reference, that details all the ins and outs of using a starred expression, as it happens that I am sometimes surprised from its behaviours...</p> <h3>Addendum</h3> <p>To reflect some of the enlightening comments that immediately followed my question I add the following code</p> <pre><code>&gt;&gt;&gt; '%d %d' % (, *a) File "&lt;stdin&gt;", line 1 '%d %d' % (, *a) ^ SyntaxError: invalid syntax &gt;&gt;&gt; '%d %d' % (*a,) '1 2' &gt;&gt;&gt; </code></pre> <p>(I had tried the <code>(, a)</code> part before posting the original question but I've omitted it 'cause the error was not related to the starring.)</p> <p>There is a syntax, in python ≥ 3.5, that "just works" but nevertheless I would like some understanding.</p>
40,676,282
3
7
null
2016-11-18 11:34:20.647 UTC
18
2021-11-19 11:23:27.367 UTC
2020-06-19 15:03:59.797 UTC
null
2,146,491
null
2,749,397
null
1
49
python|python-3.x|python-2.x
50,344
<p>It's because this:</p> <pre><code>(a) </code></pre> <p>Is just a value surrounded by parenthesis. It's not a new tuple object. So your expression:</p> <pre><code>&gt;&gt;&gt; '%d %d' % (*a) </code></pre> <p>will get translated to:</p> <pre><code>&gt;&gt;&gt; '%d %d' % * a </code></pre> <p>which is obviously wrong in terms of python syntax.</p> <p>In order to create a new tuple, with one expression as an initializer, you need to add a '<code>,</code>' after it:</p> <pre><code>&gt;&gt;&gt; '%d %d' % (*a,) </code></pre> <p><em>Note: unless <code>a</code> is a generator, in this particular situation you could just type:</em></p> <pre><code>&gt;&gt;&gt; '%d %d' % a </code></pre> <p>Also, if I may suggest something: you could start using new-style formating expressions. They are great!</p> <pre><code>&gt;&gt;&gt; &quot;{} {}&quot;.format(*a) </code></pre> <p>You can read more about them in those <a href="https://docs.python.org/3/library/string.html#custom-string-formatting" rel="noreferrer" title="Python Documentation: custom string formatting">t</a>w<a href="https://docs.python.org/3/library/string.html#format-string-syntax" rel="noreferrer" title="Python Documentation: format string syntax">o</a> paragraphs of python documentation, also there is <a href="https://pyformat.info/" rel="noreferrer">this</a> great website. The line above uses argument unpacking mechanism described below.</p> <p><em>Update: since python 3.6, you could also use string interpolation - f-strings! These are described in <a href="https://www.python.org/dev/peps/pep-0498/" rel="noreferrer">PEP-498</a>, and some examples can be found in <a href="https://docs.python.org/3/reference/lexical_analysis.html#f-strings" rel="noreferrer">Python documentation</a>.</em></p> <h2>Starred Expressions</h2> <p>There are many more uses to starred expression than just creating a new list/tuple/dictionary. Most of them are described in <a href="https://www.python.org/dev/peps/pep-3132/" rel="noreferrer" title="PEP 3132">PEP 3132</a>, and <a href="https://www.python.org/dev/peps/pep-0448/" rel="noreferrer" title="PEP 448">PEP 448</a>.</p> <p>All of them come down to two kinds:</p> <p>R-value unpacking:</p> <pre><code>&gt;&gt;&gt; a, *b, c = range(5) # a = 0 # b = [1, 2, 3] # c = 4 &gt;&gt;&gt; 10, *range(2) (10, 0, 1) </code></pre> <p>Iterable / dictionary object initialization <em>(notice that you can unpack dictionaries inside lists too!)</em>:</p> <pre><code>&gt;&gt;&gt; [1, 2, *[3, 4], *[5], *(6, 7)] [1, 2, 3, 4, 5, 6, 7] &gt;&gt;&gt; (1, *[2, 3], *{&quot;a&quot;: 1}) (1, 2, 3, 'a') &gt;&gt;&gt; {&quot;a&quot;: 1, **{&quot;b&quot;: 2, &quot;c&quot;: 3}, **{&quot;c&quot;: &quot;new 3&quot;, &quot;d&quot;: 4}} {'a': 1, 'b': 2, 'c': 'new 3', 'd': 4} </code></pre> <p>Of course, the most often seen use is arguments unpacking:</p> <pre><code>positional_arguments = [12, &quot;a string&quot;, (1, 2, 3), other_object] keyword_arguments = {&quot;hostname&quot;: &quot;localhost&quot;, &quot;port&quot;: 8080} send(*positional_arguments, **keyword_arguments) </code></pre> <p>which would translate to this:</p> <pre><code>send(12, &quot;a string&quot;, (1, 2, 3), other_object, hostname=&quot;localhost&quot;, port=8080) </code></pre> <p>This topic has already been covered to a substantial extent in <a href="https://stackoverflow.com/questions/3394835/args-and-kwargs">another Stack Overflow question</a>.</p>
49,160,206
Does GridSearchCV perform cross-validation?
<p>I'm currently working on a problem which compares three different machine learning algorithms performance on the same data-set. I divided the data-set into 70/30 training/testing sets and then performed grid search for the best parameters of each algorithm using GridSearchCV and <code>X_train, y_train</code>.</p> <p>First question, am I suppose to perform grid search on the training set or is it suppose to be on the whole data-set?</p> <p>Second question, I know that GridSearchCV uses K-fold in its' implementation, does it mean that I performed cross-validation if I used the same <code>X_train, y_train</code> for all three algorithms I compare in the GridSearchCV?</p> <p>Any answer would be appreciated, thank you.</p>
49,165,571
2
0
null
2018-03-07 19:56:01.623 UTC
14
2018-12-28 16:45:53.55 UTC
2018-12-28 16:45:53.55 UTC
null
3,374,996
null
9,321,447
null
1
23
python|machine-learning|scikit-learn|cross-validation|grid-search
12,177
<p>All estimators in scikit where name ends with <code>CV</code> perform cross-validation. But you need to keep a separate test set for measuring the performance.</p> <p>So you need to split your whole data to train and test. Forget about this test data for a while. </p> <p>And then pass this train data only to grid-search. GridSearch will split this train data further into train and test to tune the hyper-parameters passed to it. And finally fit the model on the whole train data with best found parameters.</p> <p>Now you need to test this model on the test data you kept aside in the beginning. This will give you the near real world performance of model. </p> <p>If you use the whole data into GridSearchCV, then there would be leakage of test data into parameter tuning and then the final model may not perform that well on newer unseen data.</p> <p>You can look at my other answers which describe the GridSearch in more detail:</p> <ul> <li><a href="https://stackoverflow.com/questions/42362027/model-help-using-scikit-learn-when-using-gridsearch/42364900#42364900">Model help using Scikit-learn when using GridSearch</a></li> <li><a href="https://stackoverflow.com/questions/42228735/scikit-learn-gridsearchcv-with-multiple-repetitions/42230764#42230764">scikit-learn GridSearchCV with multiple repetitions</a></li> </ul>
2,992,234
Java/JAXB: Unmarshall Xml to specific subclass based on an attribute
<p>Is it possible to use JAXB to unmarshall xml to a specific Java class based on an attribute of the xml?</p> <pre><code>&lt;shapes&gt; &lt;shape type="square" points="4" square-specific-attribute="foo" /&gt; &lt;shape type="triangle" points="3" triangle-specific-attribute="bar" /&gt; &lt;/shapes&gt; </code></pre> <p>I would like to have a List of Shape objects containing a triangle and a square, each with their own shape-specific attribute. IE:</p> <pre><code>abstract class Shape { int points; //...etc } class Square extends Shape { String square-specific-attribute; //...etc } class Triangle extends Shape { String triangle-specific-attribute; //...etc } </code></pre> <p>I'm currently just putting all attributes in one big "Shape" class and it's less than ideal.</p> <p>I could get this to work if the shapes were properly named xml elements, but unfortunately I don't have control of the xml I'm retrieving.</p> <p>Thanks!</p>
3,181,871
5
0
null
2010-06-07 18:53:28.317 UTC
8
2016-04-26 21:13:34.097 UTC
2010-08-02 15:00:57.57 UTC
null
383,861
null
72,899
null
1
31
java|inheritance|jaxb|eclipselink
23,147
<p>JAXB is a spec, specific implementations will provide extension points to do things such as this. If you are using <a href="http://www.eclipse.org/eclipselink/moxy.php" rel="noreferrer">EclipseLink JAXB (MOXy)</a> you could modify the Shape class as follows:</p> <pre><code>import javax.xml.bind.annotation.XmlAttribute; import org.eclipse.persistence.oxm.annotations.XmlCustomizer; @XmlCustomizer(ShapeCustomizer.class) public abstract class Shape { int points; @XmlAttribute public int getPoints() { return points; } public void setPoints(int points) { this.points = points; } } </code></pre> <p>Then using the MOXy @XMLCustomizer you could access the InheritancePolicy and change the class indicator field from "@xsi:type" to just "type":</p> <pre><code>import org.eclipse.persistence.config.DescriptorCustomizer; import org.eclipse.persistence.descriptors.ClassDescriptor; public class ShapeCustomizer implements DescriptorCustomizer { @Override public void customize(ClassDescriptor descriptor) throws Exception { descriptor.getInheritancePolicy().setClassIndicatorFieldName("@type"); } } </code></pre> <p>You will need to ensure that you have a jaxb.properties file in with you model classes (Shape, Square, etc) with the following entry specifying the EclipseLink MOXy JAXB implementation:</p> <pre><code>javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory </code></pre> <p>Below is the rest of the model classes:</p> <p>Shapes</p> <pre><code>import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class Shapes { private List&lt;Shape&gt; shape = new ArrayList&lt;Shape&gt;();; public List&lt;Shape&gt; getShape() { return shape; } public void setShape(List&lt;Shape&gt; shape) { this.shape = shape; } } </code></pre> <p>Square</p> <pre><code>import javax.xml.bind.annotation.XmlAttribute; public class Square extends Shape { private String squareSpecificAttribute; @XmlAttribute(name="square-specific-attribute") public String getSquareSpecificAttribute() { return squareSpecificAttribute; } public void setSquareSpecificAttribute(String s) { this.squareSpecificAttribute = s; } } </code></pre> <p>Triangle</p> <pre><code>import javax.xml.bind.annotation.XmlAttribute; public class Triangle extends Shape { private String triangleSpecificAttribute; @XmlAttribute(name="triangle-specific-attribute") public String getTriangleSpecificAttribute() { return triangleSpecificAttribute; } public void setTriangleSpecificAttribute(String t) { this.triangleSpecificAttribute = t; } } </code></pre> <p>Below is a demo program to check that everything works:</p> <pre><code>import java.io.StringReader; import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; public class Demo { public static void main(String[] args) throws Exception { JAXBContext jaxbContext = JAXBContext.newInstance(Shapes.class, Triangle.class, Square.class); StringReader xml = new StringReader("&lt;shapes&gt;&lt;shape square-specific-attribute='square stuff' type='square'&gt;&lt;points&gt;4&lt;/points&gt;&lt;/shape&gt;&lt;shape triangle-specific-attribute='triangle stuff' type='triangle'&gt;&lt;points&gt;3&lt;/points&gt;&lt;/shape&gt;&lt;/shapes&gt;"); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); Shapes root = (Shapes) unmarshaller.unmarshal(xml); Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.marshal(root, System.out); } } </code></pre> <p>I hope this helps.</p> <p>For more information on EclipseLink MOXy see:</p> <ul> <li><a href="http://www.eclipse.org/eclipselink/moxy.php" rel="noreferrer">http://www.eclipse.org/eclipselink/moxy.php</a></li> </ul> <p><strong>EDIT</strong></p> <p>In EclipseLink 2.2 we're making this easier to configure, check out the following article for more information:</p> <ul> <li><a href="http://bdoughan.blogspot.com/2010/11/jaxb-and-inheritance-moxy-extension.html" rel="noreferrer">http://bdoughan.blogspot.com/2010/11/jaxb-and-inheritance-moxy-extension.html</a></li> </ul>
2,629,612
Writing String to Stream and reading it back does not work
<p>I want to write a String to a Stream (a MemoryStream in this case) and read the bytes one by one. </p> <pre><code>stringAsStream = new MemoryStream(); UnicodeEncoding uniEncoding = new UnicodeEncoding(); String message = "Message"; stringAsStream.Write(uniEncoding.GetBytes(message), 0, message.Length); Console.WriteLine("This:\t\t" + (char)uniEncoding.GetBytes(message)[0]); Console.WriteLine("Differs from:\t" + (char)stringAsStream.ReadByte()); </code></pre> <p>The (undesired) result I get is:</p> <pre><code>This: M Differs from: ? </code></pre> <p>It <em>looks</em> like it's not being read correctly, as the first char of "Message" is 'M', which works when getting the bytes from the UnicodeEncoding instance but not when reading them back from the stream.</p> <p>What am I doing wrong?</p> <hr> <p>The bigger picture: I have an algorithm which will work on the bytes of a Stream, I'd like to be as general as possible and work with any Stream. I'd like to convert an ASCII-String into a MemoryStream, or maybe use another method to be able to work on the String as a Stream. The algorithm in question will work on the bytes of the Stream.</p>
2,629,628
5
5
null
2010-04-13 12:53:24.943 UTC
4
2013-03-12 17:31:12.8 UTC
2010-04-13 13:56:11.593 UTC
null
246,390
null
246,390
null
1
49
c#|stream
123,967
<p>After you write to the <code>MemoryStream</code> and before you read it back, you need to <code>Seek</code> back to the beginning of the <code>MemoryStream</code> so you're not reading from the end.</p> <p><strong>UPDATE</strong></p> <p>After seeing your update, I think there's a more reliable way to build the stream:</p> <pre><code>UnicodeEncoding uniEncoding = new UnicodeEncoding(); String message = "Message"; // You might not want to use the outer using statement that I have // I wasn't sure how long you would need the MemoryStream object using(MemoryStream ms = new MemoryStream()) { var sw = new StreamWriter(ms, uniEncoding); try { sw.Write(message); sw.Flush();//otherwise you are risking empty stream ms.Seek(0, SeekOrigin.Begin); // Test and work with the stream here. // If you need to start back at the beginning, be sure to Seek again. } finally { sw.Dispose(); } } </code></pre> <p>As you can see, this code uses a StreamWriter to write the entire string (with proper encoding) out to the <code>MemoryStream</code>. This takes the hassle out of ensuring the entire byte array for the string is written.</p> <p><strong>Update:</strong> I stepped into issue with empty stream several time. It's enough to call <strong>Flush</strong> right after you've finished writing.</p>
2,769,371
404 header - HTTP 1.0 or 1.1?
<p>Why does almost every example I can find (including <a href="https://stackoverflow.com/questions/437256/sending-a-404-error-in-php">this question</a> from about a year ago) say that a 404 header should be <code>HTTP/1.0 404 Not Found</code> when we've really been using HTTP 1.1 for over a decade? Is there any reason not to send <code>HTTP/1.1 404 Not Found</code> instead?</p> <p>(Not that it matters all that much... I'm mostly just curious.)</p>
2,769,417
6
2
null
2010-05-04 22:25:06.633 UTC
6
2021-08-26 09:04:49.953 UTC
2017-05-23 10:28:33.457 UTC
null
-1
null
212,443
null
1
23
http|http-status-code-404|header
61,253
<p>The usage of HTTP version can be based on the following factors:</p> <ul> <li>Your web server support for HTTP 1.0 or 1.1</li> <li>The web browser's support for HTTP 1.0 or 1.1</li> <li>Your preference as a web developer on which protocol version to use</li> </ul> <p>Modern browsers can support both 1.0 and 1.1 well, and both the client and server will settle for the highest version both can support together. The key differences between the 2 protocol can be found: <a href="http://www8.org/w8-papers/5c-protocols/key/key.html" rel="nofollow noreferrer">http://www8.org/w8-papers/5c-protocols/key/key.html</a></p> <p>However there's no key differences in the usage of 404 Not Found. However do be consistent for your whole website. i.e. if you use HTTP/1.1, you use it throughout your website.</p>
2,751,603
How to get error text in controller from BindingResult
<p>I have an controller that returns JSON. It takes a form, which validates itself via spring annotations. I can get FieldError list from BindingResult, but they don't contain the text that a JSP would display in the tag. How can I get the error text to send back in JSON?</p> <pre><code>@RequestMapping(method = RequestMethod.POST) public @ResponseBody JSONResponse submit(@Valid AnswerForm answerForm, BindingResult result, Model model, HttpServletRequest request, HttpServletResponse response) { if (result.hasErrors()) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); JSONResponse r = new JSONResponse(); r.setStatus(JSONResponseStatus.ERROR); //HOW DO I GET ERROR MESSAGES OUT OF BindingResult??? } else { JSONResponse r = new JSONResponse(); r.setStatus(JSONResponseStatus.OK); return r; } } </code></pre> <p>JSONREsponse class is just a POJO</p> <pre><code>public class JSONResponse implements Serializable { private JSONResponseStatus status; private String error; private Map&lt;String,String&gt; errors; private Map&lt;String,Object&gt; data; ...getters and setters... } </code></pre> <p>Calling BindingResult.getAllErrors() returns an array of FieldError objects, but it doesn't have the actual errors. </p>
2,752,421
6
0
null
2010-05-01 21:28:35.863 UTC
15
2021-02-09 05:14:40.527 UTC
2010-05-01 21:40:31.123 UTC
null
188,666
null
188,666
null
1
36
java|json|spring|spring-mvc|spring-annotations
79,473
<p>Disclaimer: I still do not use Spring-MVC 3.0 </p> <p>But i think the same approach used by Spring 2.5 can fullfil your needs</p> <pre><code>for (Object object : bindingResult.getAllErrors()) { if(object instanceof FieldError) { FieldError fieldError = (FieldError) object; System.out.println(fieldError.getCode()); } if(object instanceof ObjectError) { ObjectError objectError = (ObjectError) object; System.out.println(objectError.getCode()); } } </code></pre> <p>I hope it can be useful to you</p> <p><strong>UPDATE</strong></p> <p>If you want to get the message provided by your resource bundle, you need a registered messageSource instance (It <strong>must</strong> be called messageSource)</p> <pre><code>&lt;bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"&gt; &lt;property name="basenames" value="ValidationMessages"/&gt; &lt;/bean&gt; </code></pre> <p>Inject your MessageSource instance inside your View</p> <pre><code>@Autowired private MessageSource messageSource; </code></pre> <p>And to get your message, do as follows</p> <pre><code>for (Object object : bindingResult.getAllErrors()) { if(object instanceof FieldError) { FieldError fieldError = (FieldError) object; /** * Use null as second parameter if you do not use i18n (internationalization) */ String message = messageSource.getMessage(fieldError, null); } } </code></pre> <p>Your Validator should looks like</p> <pre><code>/** * Use null as fourth parameter if you do not want a default message */ errors.rejectValue("&lt;FIELD_NAME_GOES_HERE&gt;", "answerform.questionId.invalid", new Object [] {"123"}, null); </code></pre>
2,931,630
How are negative numbers represented in 32-bit signed integer?
<p>How are negative number represented in 32-bit signed integer? Is it two's or one's complement? or the last bit on the left is like a flag? For example: (-10)</p>
2,931,646
7
2
null
2010-05-28 18:39:59.527 UTC
1
2019-04-02 01:14:40.077 UTC
null
null
null
null
132,640
null
1
17
binary|numbers
40,516
<p>Most computers these days use <a href="http://en.wikipedia.org/wiki/Two&#39;s_complement" rel="noreferrer">two's complement</a> for signed integers, but it can vary by hardware architecture, programming language, or other platform-specific issues.</p> <p>For a two's-complement representation, the most-significant ("leftmost") bit is referred to as the <em>sign bit</em>, and it will be set for a negative integer and clear for a non-negative integer. However, it is more than just a "flag". See the <a href="http://en.wikipedia.org/wiki/Two&#39;s_complement" rel="noreferrer">Wikipedia article</a> for more information.</p>
2,784,291
Good implementation of weak dictionary in .Net
<p>Where can I find good implementation of <code>IDictionary</code> which uses weak references inside?</p> <p>Dictionary should be holding only weak references to values and eventually clean up itself of dead references.</p> <p>Or should I just write it myself?</p>
12,929,019
7
5
null
2010-05-06 20:34:52.507 UTC
6
2021-08-29 04:51:27.3 UTC
null
null
null
null
1,423,922
null
1
34
.net|dictionary|weak-references
17,177
<p><a href="http://msdn.microsoft.com/en-us/library/dd287757.aspx" rel="noreferrer">ConditionalWeakTable Class</a> uses weak keys and automatically removes the key/value entry as soon as no other references to a key exist outside the table.</p>
3,136,338
Uses for Haskell id function
<p>Which are the uses for <a href="http://www.zvon.org/other/haskell/Outputprelude/id_f.html" rel="noreferrer">id function</a> in Haskell?</p>
3,136,376
9
1
null
2010-06-28 21:39:06.76 UTC
22
2016-10-26 20:48:29.48 UTC
null
null
null
null
145,349
null
1
63
function|haskell|functional-programming
24,933
<p>It's useful as an argument to <a href="http://www.haskell.org/haskellwiki/Higher_order_function#Definition" rel="noreferrer">higher order functions</a> (functions which take functions as arguments), where you want some particular value left unchanged.</p> <p><strong>Example 1</strong>: Leave a value alone if it is in a Just, otherwise, return a default of 7.</p> <pre><code>Prelude Data.Maybe&gt; :t maybe maybe :: b -&gt; (a -&gt; b) -&gt; Maybe a -&gt; b Prelude Data.Maybe&gt; maybe 7 id (Just 2) 2 </code></pre> <p><strong>Example 2</strong>: building up a function via a fold:</p> <pre><code>Prelude Data.Maybe&gt; :t foldr (.) id [(+2), (*7)] :: (Num a) =&gt; a -&gt; a Prelude Data.Maybe&gt; let f = foldr (.) id [(+2), (*7)] Prelude Data.Maybe&gt; f 7 51 </code></pre> <p>We built a new function <code>f</code> by folding a list of functions together with <code>(.)</code>, using <code>id</code> as the base case.</p> <p><strong>Example 3</strong>: the base case for functions as monoids (simplified).</p> <pre><code>instance Monoid (a -&gt; a) where mempty = id f `mappend` g = (f . g) </code></pre> <p>Similar to our example with fold, functions can be treated as concatenable values, with <code>id</code> serving for the empty case, and <code>(.)</code> as append.</p> <p><strong>Example 4</strong>: a trivial hash function.</p> <pre><code>Data.HashTable&gt; h &lt;- new (==) id :: IO (HashTable Data.Int.Int32 Int) Data.HashTable&gt; insert h 7 2 Data.HashTable&gt; Data.HashTable.lookup h 7 Just 2 </code></pre> <p>Hashtables require a hashing function. But what if your key is already hashed? Then pass the id function, to fill in as your hashing method, with zero performance overhead.</p>
2,622,017
Suppressing deprecated warnings in Xcode
<p>With all the SDKs floating around, it's handy to be able to build for multiple SDKs and platforms. However, bouncing from 3.2 to 3.0 and even occasionally 2.x, I frequently get deprecated warnings involving methods that have changed or been superseded:</p> <pre><code>warning: 'UIKeyboardBoundsUserInfoKey' is deprecated. </code></pre> <p>Since I still want to maintain compatibility with older OSes, and I'm also striving to remove 'noise' when building, is there a way to turn off or disable these warnings?</p>
2,622,039
9
1
null
2010-04-12 12:33:32.5 UTC
36
2020-08-26 17:18:29.987 UTC
null
null
null
null
6,694
null
1
141
iphone|xcode|macos|warnings
72,693
<p>Try <code>-Wno-deprecated-declarations</code>, or its corresponding setting in Xcode, <code>GCC_WARN_ABOUT_DEPRECATED_FUNCTIONS</code> (pro tip: just type in "deprecated" in the build settings to find the specific setting for this warning).</p> <p>Current versions of Xcode (e.g. Xcode 9.2):</p> <p><a href="https://i.stack.imgur.com/HYs8J.png" rel="noreferrer"><img src="https://i.stack.imgur.com/HYs8J.png" alt="enter image description here"></a></p> <hr> <p>Ancient versions of Xcode (e.g. Xcode 2.x, 3.x):</p> <p><a href="https://i.stack.imgur.com/FlOCG.png" rel="noreferrer"><img src="https://i.stack.imgur.com/FlOCG.png" alt="enter image description here"></a></p>
2,934,844
Unable to convert MySQL date/time value to System.DateTime
<p>I am using ibatis and C#. i get a result from a select query that has CreatedDate as one of the field. The Datatype of CreatedDate in Mysql is Date. I assign the result set of the select query to a Ilist&lt; DeliveryClass>. </p> <p>Here the DeliveryClass CreatedDate as DateTime. When i run the application, i get <strong>Unable to convert MySQL date/time value to System.DateTime</strong>. What could be the problem?</p>
16,618,723
10
0
null
2010-05-29 11:39:02.307 UTC
9
2022-04-28 16:52:02.3 UTC
null
null
null
null
2,922,388
null
1
23
c#|mysql|datetime|date|ibatis
88,500
<pre><code>MySqlConnection connect = new MySqlConnection("server=localhost; database=luttop; user=root; password=1234; pooling = false; convert zero datetime=True"); </code></pre> <p>Adding <code>convert zero datetime=True</code> to the connection string will automatically convert <code>0000-00-00</code> Date values to <code>DateTime.MinValue()</code>.</p> <p>that's SOLVED</p>
2,679,330
Catching java.lang.OutOfMemoryError?
<p><a href="http://java.sun.com/javase/6/docs/api/java/lang/Error.html" rel="noreferrer">Documentation</a> for <code>java.lang.Error</code> says:</p> <blockquote> <p>An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch</p> </blockquote> <p>But as <code>java.lang.Error</code> is a subclass of <code>java.lang.Throwable</code>, I can catch this type of Throwable.</p> <p>I understand why it's not a good idea to catch this sort of exception. As far as I understand, if we decide to catch it, the catch handler should not allocate any memory by itself. Otherwise <code>OutOfMemoryError</code> will be thrown again.</p> <p>So, my question is:</p> <ol> <li>Are there any real world scenarios when catching <code>java.lang.OutOfMemoryError</code> might be a good idea?</li> <li>If we decide to catch <code>java.lang.OutOfMemoryError</code>, how can we make sure the catch handler doesn't allocate any memory by itself (any tools or best practices)?</li> </ol>
2,680,784
14
4
null
2010-04-20 23:11:57.193 UTC
34
2021-07-24 05:21:21.55 UTC
2019-07-03 05:40:20.173 UTC
null
9,540,257
null
53,658
null
1
119
java|try-catch|out-of-memory
97,144
<p>There are a number of scenarios where you may wish to catch an <code>OutOfMemoryError</code> and in my experience (on Windows and Solaris JVMs), only very infrequently is <code>OutOfMemoryError</code> the death-knell to a JVM.</p> <p>There is only one good reason to catch an <code>OutOfMemoryError</code> and that is to close down gracefully, cleanly releasing resources and logging the reason for the failure best you can (if it is still possible to do so).</p> <p>In general, the <code>OutOfMemoryError</code> occurs due to a block memory allocation that cannot be satisfied with the remaining resources of the heap.</p> <p>When the <code>Error</code> is thrown the heap contains the same amount of allocated objects as before the unsuccessful allocation and now is the time to drop references to run-time objects to free even more memory that may be required for cleanup. In these cases, it may even be possible to continue but that would definitely be a bad idea as you can never be 100% certain that the JVM is in a reparable state.</p> <p>Demonstration that <code>OutOfMemoryError</code> does not mean that the JVM is out of memory in the catch block:</p> <pre><code>private static final int MEGABYTE = (1024*1024); public static void runOutOfMemory() { MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean(); for (int i=1; i &lt;= 100; i++) { try { byte[] bytes = new byte[MEGABYTE*500]; } catch (Exception e) { e.printStackTrace(); } catch (OutOfMemoryError e) { MemoryUsage heapUsage = memoryBean.getHeapMemoryUsage(); long maxMemory = heapUsage.getMax() / MEGABYTE; long usedMemory = heapUsage.getUsed() / MEGABYTE; System.out.println(i+ &quot; : Memory Use :&quot; + usedMemory + &quot;M/&quot; +maxMemory+&quot;M&quot;); } } } </code></pre> <p>Output of this code:</p> <pre><code>1 : Memory Use :0M/247M .. .. .. 98 : Memory Use :0M/247M 99 : Memory Use :0M/247M 100 : Memory Use :0M/247M </code></pre> <p>If running something critical, I usually catch the <code>Error</code>, log it to syserr, then log it using my logging framework of choice, then proceed to release resources and close down in a clean fashion. What's the worst that can happen? The JVM is dying (or already dead) anyway and by catching the <code>Error</code> there is at least a chance of cleanup.</p> <p>The caveat is that you have to target the catching of these types of errors only in places where cleanup is possible. Don't blanket <code>catch(Throwable t) {}</code> everywhere or nonsense like that.</p>
2,628,672
What should every JavaScript programmer know?
<p>Is there a set of things that every JavaScript programmer should know to be able to say "I know JavaScript"?</p>
2,629,004
29
0
2010-06-15 08:01:34.493 UTC
2010-04-13 10:13:21.7 UTC
899
2011-09-04 22:32:17.763 UTC
2010-04-22 19:20:35.187 UTC
null
21,677
null
26,143
null
1
368
javascript|programming-languages
81,488
<p><em>Not jQuery. Not YUI. Not (etc. etc.)</em></p> <p>Frameworks may be useful, but they are often hiding the sometimes-ugly details of how JavaScript and the DOM actually work from you. If your aim is to be able to say “I know JavaScript”, then investing a lot of time in a framework is opposed to that.</p> <p>Here are some JavaScript language features that you should know to grok what it's doing and not get caught out, but which aren't immediately obvious to many people:</p> <ul> <li><p>That <code>object.prop</code> and <code>object['prop']</code> are the same thing (so can you please stop using <code>eval</code>, thanks); that object properties are always strings (even for arrays); <a href="http://bonsaiden.github.com/JavaScript-Garden/#object.forinloop" rel="nofollow noreferrer">what <code>for</code>...<code>in</code> is for</a> (and <a href="http://bonsaiden.github.com/JavaScript-Garden/#array.general" rel="nofollow noreferrer">what it isn't</a>).</p></li> <li><p>Property-sniffing; what <code>undefined</code> is (and <a href="https://stackoverflow.com/questions/2235622/setting-a-variable-to-undefined/2236186#2236186">why it smells</a>); why the seemingly-little-known <code>in</code> operator is beneficial and different from <code>typeof</code>/<code>undefined</code> checks; <code>hasOwnProperty</code>; the purpose of <code>delete</code>.</p></li> <li><p>That the <code>Number</code> datatype is really a float; the language-independent difficulties of using floats; avoiding the <code>parseInt</code> octal trap.</p></li> <li><p>Nested function scoping; the necessity of using <code>var</code> in the scope you want to avoid accidental globals; how scopes can be used for closures; the <a href="https://stackoverflow.com/questions/2568966/how-do-i-pass-the-value-not-the-reference-of-a-js-variable-to-a-function">closure loop problem</a>.</p></li> <li><p>How global variables and <code>window</code> properties collide; how global variables and document elements shouldn't collide but do in IE; the necessity of using <code>var</code> in global scope too to avoid this.</p></li> <li><p>How the <code>function</code> statement acts to ‘<a href="https://stackoverflow.com/questions/1710424/referencing-a-javascript-value-before-it-is-declared-can-someone-explain-this/1710509#1710509">hoist</a>’ a definition before code preceding it; the difference between function statements and function expressions; why named function expressions <a href="http://kangax.github.com/nfe/#jscript-bugs" rel="nofollow noreferrer">should not be used</a>.</p></li> <li><p>How constructor functions, the <code>prototype</code> property and the <code>new</code> operator really work; <a href="https://stackoverflow.com/questions/1595611/how-to-properly-create-a-custom-object-in-javascript">methods</a> of exploiting this to create the normal class/subclass/instance system you actually wanted; when you might want to use closure-based objects instead of prototyping. (Most JS tutorial material is absolutely terrible on this; it took me years to get it straight in my head.)</p></li> <li><p>How <code>this</code> is determined at call-time, not bound; how consequently method-passing <a href="https://stackoverflow.com/questions/1544735/js-object-this-method-breaks-via-jquery#1544893">doesn't work like you expect</a> from other languages; how closures or <code>Function#bind</code> may be used to get around that.</p></li> <li><p>Other ECMAScript Fifth Edition features like <code>indexOf</code>, <code>forEach</code> and the functional-programming <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Working_with_Arrays#Introduced_in_JavaScript_1.6" rel="nofollow noreferrer">methods on <code>Array</code></a>; how to fix up older browsers to ensure you can use them; using them with inline anonymous function expressions to get compact, readable code.</p></li> <li><p>The flow of control between the browser and user code; synchronous and asynchronous execution; events that fire inside the flow of control (eg. focus) vs. events and timeouts that occur when control returns; how calling a supposedly-synchronous builtin like <code>alert</code> can end up causing potentially-disastrous re-entrancy.</p></li> <li><p>How cross-window scripting affects <code>instanceof</code>; how cross-window scripting affects the control flow across different documents; how <code>postMessage</code> will hopefully fix this.</p></li> </ul> <p>See <a href="https://stackoverflow.com/questions/2734025/is-javascript-guaranteed-to-be-single-threaded/2734311#2734311">this answer</a> regarding the last two items.</p> <p>Most of all, you should be viewing JavaScript critically, acknowledging that it is for historical reasons an imperfect language (even more than most languages), and avoiding its worst troublespots. Crockford's work on this front is definitely worth reading (although I don't 100% agree with him on which the “Good Parts” are).</p>
45,354,940
Wait for observable to complete
<p>I have series of methods which are dependent on completion of other methods. </p> <pre><code>process1(data: string) : Observable&lt;string&gt; { this.dataservice.process(data).subscribe( (response) =&gt; { return response.data; } ); } main(data: string) : string { var process1Data: string = process1(data); // I would like to wait for process1 method to complete before running process2 // I do not want to include process2 inside subscribe of process1 because I have to make few more method calls var process2Data: string = process2(process1Data); var process3Data: string = process3(process2Data); ... } </code></pre> <p>How can I wait for an observable to complete before calling next method (process2, process3)? (similar like await in c#)</p>
45,356,178
5
0
null
2017-07-27 15:21:26.493 UTC
3
2022-05-24 12:20:03.98 UTC
2017-07-27 15:57:48.387 UTC
null
1,955,609
null
1,955,609
null
1
13
javascript|angular|typescript|rxjs|observable
49,599
<p>You might try something like this...</p> <pre><code>main(data: string) : string { process1Data$: Observable&lt;string&gt; = process1(data) .take(1) .switchMap((process1Data) =&gt; return process2(process1Data); . . . } </code></pre> <p>Obviously, <code>take(1)</code> assumes that <code>process1(...)</code> resolves to single value and stops. After that it <code>switchMap</code>s to <code>process2</code> which means it starts emitting whatever observable from <code>process2</code> gives. If, on the other hand, you want <code>process2</code> to be ran of each result emitted from <code>process1</code> then just remove <code>take(1)</code>.</p>
10,730,233
CSS bar graph - very simple
<p>I have some very basic code and it works except everything aligns to the top...ideally the bars would align to the bottom. I suppose I could use fixed positioning as the dimensions are squared at 50px by 50px but I'd prefer something a little less "fixed".</p> <pre><code> &lt;div style="border: 1px solid #aeaeae; background-color: #eaeaea; width: 50px; height: 50px;"&gt; &lt;div style="position: relative; bottom: 0; float: left; width: 8px; height: 22px; background-color: #aeaeae; margin: 1px;"&gt;&lt;/div&gt; &lt;div style="position: relative; bottom: 0; float: left; width: 8px; height: 11px; background-color: #aeaeae; margin: 1px;"&gt;&lt;/div&gt; &lt;div style="position: relative; bottom: 0; float: left; width: 8px; height: 6px; background-color: #aeaeae; margin: 1px;"&gt;&lt;/div&gt; &lt;div style="position: relative; bottom: 0; float: left; width: 8px; height: 49px; background-color: #aeaeae; margin: 1px;"&gt;&lt;/div&gt; &lt;div style="position: relative; bottom: 0; float: left; width: 8px; height: 28px; background-color: #aeaeae; margin: 1px;"&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p>I don't want to use a library or JS add on. Keeping this light weight is mission critical.</p> <p>Also I'd prefer the bars were vertical. Any CSS guru care to shed the bit of light I seem to be missing? I've googled and most examples are far to complicated/sophisticated,</p>
10,730,325
5
0
null
2012-05-24 02:07:40.47 UTC
3
2018-02-26 21:38:54.403 UTC
null
null
null
null
897,075
null
1
7
css|charts
47,133
<p>First of all, separate your CSS from your HTML. You're repeating too much code when you could just use a bar class for your inner divs.</p> <p><code>bottom: 0</code> doesn't change anything for relatively positioned div.</p> <p>If you wish to use relative positioning, get rid of float and bottom and use <code>display: inline-block</code> and <code>vertical-align: baseline;</code>. Also, in this case, you need to get rid of any space in the HTML between the inner divs (newline).</p> <p>Like this (you can see the demo at <a href="http://dabblet.com/gist/2779082" rel="noreferrer">http://dabblet.com/gist/2779082</a> ):</p> <p><strong>HTML</strong></p> <pre><code>&lt;div class="graph"&gt; &lt;div style="height: 22px;" class="bar"&gt;&lt;/div&gt;&lt;!-- --&gt;&lt;div style="height: 11px;" class="bar"&gt;&lt;/div&gt;&lt;!-- --&gt;&lt;div style="height: 6px;" class="bar"&gt;&lt;/div&gt;&lt;!-- --&gt;&lt;div style="height: 49px;" class="bar"&gt;&lt;/div&gt;&lt;!-- --&gt;&lt;div style="height: 28px;" class="bar"&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p><strong>CSS</strong></p> <pre><code>.graph { width: 50px; height: 50px; border: 1px solid #aeaeae; background-color: #eaeaea; } .bar { width: 8px; margin: 1px; display: inline-block; position: relative; background-color: #aeaeae; vertical-align: baseline; } </code></pre>
10,752,456
How to enable contrib modules on Heroku Postgres database
<p>I'm trying to use contrib modules in the new Postgres 9 shared databases on Heroku. More specifically, the <strong>pg_trgm</strong> and <strong>fuzzystrmatch</strong> modules. In the <a href="https://devcenter.heroku.com/articles/full-text-search" rel="noreferrer">documentation</a> it says </p> <blockquote> <p>In addition, many complimentary extensions are available such as fuzzystrmatch, pg_trgm, and unaccent.</p> </blockquote> <p>I can't seem to find any documentation on HOW to actually enable these modules on a shared Heroku database. <em>See answer below.</em></p> <p><strong>NOTE:</strong></p> <p>I tried adding them by connecting to the database with</p> <pre><code>heroku pg:psql HEROKU_POSTGRESQL_BROWN </code></pre> <p>and running</p> <pre><code>create extension pg_trgm create extension fuzzystrmatch </code></pre> <p>but after trying to use it with</p> <pre><code>SELECT levenshtein('tests', 'test'); </code></pre> <p>it still said</p> <pre><code>ERROR: function levenshtein(unknown, unknown) does not existLINE 1: SELECT levenshtein('tests', 'test'); ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts. </code></pre> <p>Anybody know why this happens?</p>
10,752,620
2
0
null
2012-05-25 10:07:45.45 UTC
13
2014-05-06 03:06:52.8 UTC
2012-05-25 10:20:11.14 UTC
null
162,034
null
162,034
null
1
13
ruby-on-rails|postgresql|heroku
3,836
<p>Found answer <a href="https://stackoverflow.com/questions/10648774/how-to-use-postgres-extensions-on-heroku-and-how-to-handle-their-migrations">here</a> while scouring Stack Overflow. Don't know why it didn't come up in any of my Google searches. Going to leave the question here if anybody else uses the same wording to search for this.</p> <p>To enable modules, you need to add them to a migration as follows:</p> <pre><code>def up execute "create extension fuzzystrmatch" execute "create extension pg_trgm" end </code></pre>
10,513,360
polyline snap to road using google maps api v3
<p>In google maps api v2 it was easy, </p> <pre><code>var map = new GMap2(document.getElementById("map")); map.setCenter(new GLatLng(53.7877, -2.9832),13) // map.addControl(new GLargeMapControl()); // map.addControl(new GMapTypeControl()); var dirn = new GDirections(); // var firstpoint = true; var gmarkers = []; var gpolys = []; var dist = 0; // == When the user clicks on a the map, get directiobns from that point to itself == gmarkers.push(new google.maps.LatLng(53.7877, -2.9832)); gmarkers.push(new google.maps.LatLng(53.9007, -2.9832)); gmarkers.push(new GLatLng(53.600, -2.700)); for (var i = 0; i &lt; gmarkers.length-1; i++) { console.log(gmarkers[i]); dirn.loadFromWaypoints([gmarkers[i].toUrlValue(6),gmarkers[i+1].toUrlValue(6)],{getPolyline:true}); } // == when the load event completes, plot the point on the street == GEvent.addListener(dirn,"load", function() { // snap to last vertex in the polyline var n = dirn.getPolyline().getVertexCount(); map.addOverlay(dirn.getPolyline()); gpolys.push(dirn.getPolyline()); dist += dirn.getPolyline().getDistance(); document.getElementById("distance").innerHTML="Path length: "+(dist/1000).toFixed(2)+" km. "+(dist/1609.344).toFixed(2)+" miles."; }); GEvent.addListener(dirn,"error", function() { GLog.write("Failed: "+dirn.getStatus().code); }); console.log(dirn); </code></pre> <p>In google api V3 this way simple doesnt work. There is something like directions service but I dont have any idea how I can draw polyline through my points and polyline will be snaped to road.</p>
10,515,516
2
0
null
2012-05-09 09:30:49.75 UTC
36
2017-01-03 14:01:39.943 UTC
2013-12-30 07:33:25.817 UTC
null
881,229
null
1,013,752
null
1
26
javascript|google-maps|google-maps-api-3
57,005
<p>You were on the right track with the directions service. Here's sample code:</p> <pre><code>var map, path = new google.maps.MVCArray(), service = new google.maps.DirectionsService(), poly; function Init() { var myOptions = { zoom: 17, center: new google.maps.LatLng(37.2008385157313, -93.2812106609344), mapTypeId: google.maps.MapTypeId.HYBRID, mapTypeControlOptions: { mapTypeIds: [google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.HYBRID, google.maps.MapTypeId.SATELLITE] }, disableDoubleClickZoom: true, scrollwheel: false, draggableCursor: "crosshair" } map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); poly = new google.maps.Polyline({ map: map }); google.maps.event.addListener(map, "click", function(evt) { if (path.getLength() === 0) { path.push(evt.latLng); poly.setPath(path); } else { service.route({ origin: path.getAt(path.getLength() - 1), destination: evt.latLng, travelMode: google.maps.DirectionsTravelMode.DRIVING }, function(result, status) { if (status == google.maps.DirectionsStatus.OK) { for (var i = 0, len = result.routes[0].overview_path.length; i &lt; len; i++) { path.push(result.routes[0].overview_path[i]); } } }); } }); } </code></pre> <p>Also, see my working example: <a href="http://people.missouristate.edu/chadkillingsworth/mapsexamples/snaptoroad.htm" rel="noreferrer">http://people.missouristate.edu/chadkillingsworth/mapsexamples/snaptoroad.htm</a></p>
10,442,099
TFS Power Tools: Shell Extension : Context Menu Quirky and TFS Icons on Files/Folders missing
<p>I've used <a href="http://visualstudiogallery.msdn.microsoft.com/c255a1e4-04ba-4f68-8f4e-cd473d6b971f">TFS Power Tools</a> on a daily basis for several months. I particularly depend on Windows Shell Extension.</p> <p>For about a week now, two issues have come up:</p> <hr> <h1>Issue 1</h1> <p>Every time I enter a directory under TFS control, I have to right-click twice to see the TFS context menu <img src="https://i.stack.imgur.com/MTQP9.jpg" alt="enter image description here"></p> <hr> <h1>Issue 2</h1> <p>My pretty TFS Green indicators on files/folders are gone:</p> <p><img src="https://i.stack.imgur.com/9JuFs.jpg" alt="enter image description here"></p> <p>I've downloaded and reinstalled the Power Tools, but I still have these two issues. </p> <p>Any thoughts on how to fix this?</p> <hr> <h1>**UPDATE**</h1> <p>Dave gave me the answer via link. Just in case that link goes bad, here is the answer:</p> <ol> <li>Open the registry</li> <li>Go to : HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\explorer \ShellIconOverlayIdentifiers</li> <li>Prefix any "Tfs" folder with numbers (“1TfsOverlayAdd” , “2TfsOverlayEdit” etc.). This allows them to take priority over other icon overlays. </li> <li><p>Restart the machine or kill explorer.exe and restart it</p> <p><img src="https://i.stack.imgur.com/SRDWe.jpg" alt="enter image description here"></p></li> </ol> <p>As far as the delay issue is concerned, I'm not experiencing that this morning; which is odd. I question that the solution for the overlay was also the solution for the right-clicking. </p> <p>Everything's back to normal now so I am good to go.</p>
10,448,725
1
0
null
2012-05-04 02:58:33.503 UTC
6
2013-06-15 02:29:27.167 UTC
2013-06-15 02:29:27.167 UTC
null
163,921
null
250,385
null
1
34
tfs|tfs-power-tools
39,763
<p>The missing green icons can be explained <a href="http://blogs.msdn.com/b/youhana/archive/2012/01/09/why-am-i-not-seeing-the-icon-overlays-in-shell-extensions-tfs-power-tools.aspx" rel="noreferrer">here</a>. It is because Windows has a limit of overlay icons it supports. The details on how to fix it are in that blog post.</p> <p>How long are you waiting after entering a folder before you perform the first Right Click? It sometimes takes a while for the <code>TfsComProviderSvr.exe</code> to check if the local folder is a workspace and register the shell extension.</p>
19,385,698
How to change a class CSS with a Greasemonkey/Tampermonkey script?
<p>I'm trying to set the background image of the body, but only where it uses the class <code>banner_url</code>. The HTML is as follows:</p> <pre><code>&lt;body id="app_body" class="banner_url desktopapp" data-backdrop-limit="1"&gt; </code></pre> <p>Basically, I would like to force the page to use the following CSS instead:</p> <pre><code>.banner_url { background: url('http://www.pxleyes.com/images/contests/kiwis/fullsize/sourceimage.jpg') no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; } </code></pre> <p>I am trying to do this using Greasemonkey if it makes any difference. Does anyone know how I can go about this? I started with the following, however haven't had much luck: </p> <pre><code>function randomBG(){ document.getElementsByClassName("banner_url").style.backgroundImage="url('http://www.pxleyes.com/images/contests/kiwis/fullsize/sourceimage.jpg')no-repeat center center fixed;"; } randomBG(); </code></pre>
19,392,142
2
0
null
2013-10-15 15:54:56.823 UTC
22
2018-09-08 05:01:03.627 UTC
2018-05-26 18:14:05.843 UTC
null
331,508
null
2,776,284
null
1
65
javascript|css|greasemonkey|userscripts|tampermonkey
65,929
<p>For this, just use the CSS cascade. Add a style sheet to the page with <code>GM_addStyle()</code>.<br> Note: </p> <ul> <li>We use the <code>!important</code> flag to cover certain potential conflicts.</li> <li>Use <code>@run-at document-start</code> <sup><sub>(or use Stylus, see below)</sub></sup> to minimize "flicker" associated with changing styles after the initial render.</li> </ul> <p><strong>A complete script:</strong></p> <pre><code>// ==UserScript== // @name _Override banner_url styles // @include http://YOUR_SERVER.COM/YOUR_PATH/* // @grant GM_addStyle // @run-at document-start // ==/UserScript== GM_addStyle ( ` .banner_url { background: url('http://www.pxleyes.com/images/contests/kiwis/fullsize/sourceimage.jpg') no-repeat center center fixed !important; -webkit-background-size: cover !important; -moz-background-size: cover !important; -o-background-size: cover !important; background-size: cover !important; } ` ); </code></pre> <hr> <p>Note that <strong>if you are using Greasemonkey 4</strong>, it has busted <code>GM_addStyle()</code> <sup>(and a great many other things)</sup>.<br> It is <strong>strongly recommended that you switch to Tampermonkey or Violentmonkey.</strong><br> In fact, Greasemonkey's controlling developer <a href="https://www.greasespot.net/2017/09/greasemonkey-4-for-users.html" rel="noreferrer">says as much himself</a>.</p> <p>In the mean time, here's a shim for those masochists that persist with GM4:</p> <pre><code>function GM_addStyle (cssStr) { var D = document; var newNode = D.createElement ('style'); newNode.textContent = cssStr; var targ = D.getElementsByTagName ('head')[0] || D.body || D.documentElement; targ.appendChild (newNode); } </code></pre> <hr> <p><strong>Also, for pure CSS manipulation, the <del>Stylish</del> <a href="https://add0n.com/stylus.html" rel="noreferrer">Stylus extension</a> is a better choice than Greasemonkey/Tampermonkey.</strong></p>
32,504,355
Error Itms-90339: This bundle is invalid . The info.plist contains an invalid key 'CFBundleResourceSpecification’ in app bundle
<p>I am trying to upload my application on iTunes for iOS 9. I used Xcode 7 beta 6 to build my IPA , but iTunes failed to upload my IPA by following error message .<a href="https://i.stack.imgur.com/OeYSD.png" rel="noreferrer"><img src="https://i.stack.imgur.com/OeYSD.png" alt="enter image description here"></a></p>
32,515,734
6
0
null
2015-09-10 14:15:09.617 UTC
23
2015-12-15 13:07:02.093 UTC
2015-09-23 09:42:58.38 UTC
null
1,838,025
null
1,838,025
null
1
44
ios|xcode
32,190
<p>Project settings under Build Settings > Code Signing > Code Signing Resource Rules Path - Delete the value for Code Signing Resource Rules Path. That fixed issue for me</p>
20,956,424
How do I generate and open an Outlook email with Python (but do not send)
<p>I have a script that automatically creates and sends emails sends emails using the simple function below:</p> <pre><code>def Emailer(text, subject, recipient): import win32com.client as win32 outlook = win32.Dispatch('outlook.application') mail = outlook.CreateItem(0) mail.To = recipient mail.Subject = subject mail.HtmlBody = text mail.send </code></pre> <p>But how do I open this email in an Outlook window so that it can be manually edited and sent?</p> <p>Ideally, I'd like something like this:</p> <pre><code>def __Emailer(text, subject, recipient, auto=True): import win32com.client as win32 outlook = win32.Dispatch('outlook.application') mail = outlook.CreateItem(0) mail.To = recipient mail.Subject = subject mail.HtmlBody = text if auto: mail.send else: mail.open # or whatever the correct code is </code></pre>
20,956,653
4
0
null
2014-01-06 18:11:01.59 UTC
18
2021-12-01 03:19:12.19 UTC
2020-02-04 15:53:06.423 UTC
null
996,815
null
2,084,656
null
1
34
python|email|outlook
57,585
<p>Call <code>mail.Display(True)</code> instead of <code>mail.send</code>.</p>
20,964,372
how to write file to parent folder with fs of nodejs?
<p>I want to write a file to the current script folder's parent folder (and sometimes subdirectories to that parent folder)?</p> <p>How should I write the path?</p> <p>Can this work?</p> <pre><code>fs.writeFile(__dirname + '../sibling_dir/file.txt', 'test'); </code></pre>
20,964,427
3
1
null
2014-01-07 05:11:36.78 UTC
2
2021-06-14 13:25:13.013 UTC
null
null
null
null
1,661,640
null
1
17
node.js
38,723
<p>Yes, that should work fine. The main issue I see is that you have no <code>/</code> between the dirname and the path.</p> <p>So what you have now is more like:</p> <pre><code>fs.writeFile('/tmp/module../sibling_dir/file.txt', 'test'); </code></pre> <p>try this:</p> <pre><code>fs.writeFile(__dirname + '/../sibling_dir/file.txt', 'test'); </code></pre>
21,616,041
How to force Intellij to highlight file with no extension as Bash?
<p>I'm editing Linux <code>init.d</code> scripts with Intellij IDEA 12 Ultimate and would like it to use Bash syntax highlighting. I already have the Bash syntax highlighting plugin, and it works great for files ending in <code>.sh</code>. The problem with the init.d scripts is they have no extension, and it seems the only way to get Intellij to recognize a files type (Preferences -> File Types -> Registered Patterns) is by extension. If Registered Pattern supported paths (like <code>*/etc/rc.d/init.d/*</code>) that would be swell, but that doesn't seem to work.</p> <p>The only workaround I've found for now is to add the name of each script I want to edit to Registered Patterns. Better than nothing, but does is there a better way? Thanks!</p>
21,620,735
7
0
null
2014-02-06 23:06:23.3 UTC
1
2018-11-20 21:05:09.3 UTC
null
null
null
null
296,829
null
1
34
intellij-idea
11,902
<p>You can use the <code>*.</code> pattern. Though it's registered for <code>Text files</code> type by default.</p>
36,937,276
Replacement of AssemblyBuilder.DefineDynamicAssembly in .NET Core
<p>How do I port the following code to .NET Core?</p> <pre class="lang-cs prettyprint-override"><code>AppDomain.CurrentDomain.DefineDynamicAssembly( new AssemblyName( Guid.NewGuid().ToString()), AssemblyBuilderAccess.RunAndSave); </code></pre> <p>Is it possible?</p>
36,937,598
1
0
null
2016-04-29 11:32:48.203 UTC
4
2022-09-09 12:05:36.88 UTC
2020-10-20 00:25:14.953 UTC
null
1,402,846
null
4,353,378
null
1
68
asp.net-core|asp.net-core-mvc|.net-core|asp.net-core-1.0
21,917
<p>Add this to your <code>project.json</code>:</p> <pre class="lang-json prettyprint-override"><code>&quot;dependencies&quot;: { &quot;System.Reflection.Emit&quot;: &quot;4.0.1&quot; }, </code></pre> <p>and use:</p> <pre class="lang-cs prettyprint-override"><code>AssemblyBuilder.DefineDynamicAssembly(new AssemblyName(Guid.NewGuid().ToString()), AssemblyBuilderAccess.Run); </code></pre> <p><code>AssemblyBuilderAccess.RunAndSave</code> is not supported at the moment - <a href="https://github.com/dotnet/runtime/blob/main/src/libraries/System.Private.CoreLib/src/System/Reflection/Emit/AssemblyBuilderAccess.cs" rel="noreferrer">link to source</a>.</p> <hr /> <p>For new <code>.csproj</code> projects, use:</p> <pre class="lang-xml prettyprint-override"><code>&lt;ItemGroup&gt; &lt;PackageReference Include=&quot;System.Reflection.Emit&quot; Version=&quot;4.3.0&quot; /&gt; &lt;/ItemGroup&gt; </code></pre>
46,896,362
How to install google maps through npm?
<p>Is there any package available on npm for google maps? Or am I really supposed to paste this</p> <pre><code>&lt;script src="https://maps.googleapis.com/maps/api/jskey=YOUR_API_KEY"&gt; &lt;/script&gt; </code></pre> <p>to my index.html and download this js file on every refresh?</p> <p>This is super annoying, because sometimes I get <code>ReferenceError: google is not defined</code>.</p>
58,295,576
6
1
null
2017-10-23 18:43:37.14 UTC
1
2022-05-18 14:03:17.597 UTC
null
null
null
null
6,372,449
null
1
29
javascript|npm|maps
24,679
<blockquote> <p>Or am I really supposed to paste this to my index.html and download this js file on every refresh?</p> </blockquote> <p><strong>Yes</strong>. This is the only way to do so. There are some packages to dynamically do this for you, but the behavior is the same.</p> <p>To reiterate, there is no official package for loading the Google Maps JavaScript for the web environment on NPM. The <code>@google/maps</code> referenced by others is for <strong>node only</strong>.</p> <p><strong>google is not defined</strong> errors can be avoided by using the callback query parameter when loading the google maps script.</p> <p><strong>Update - 2020/01/17</strong></p> <p>I wrote <a href="https://www.npmjs.com/package/@googlemaps/js-api-loader" rel="nofollow noreferrer">@googlemaps/js-api-loader</a> to help load the script dynamically and support promises.</p> <pre class="lang-js prettyprint-override"><code>import { Loader } from '@googlemaps/js-api-loader'; const loader = new Loader({ apiKey: &quot;&quot;, version: &quot;weekly&quot;, libraries: [] }); loader .load() .then(() =&gt; { new google.maps.Map(div, mapOptions); }) .catch(e =&gt; { // do something }); </code></pre>
8,593,816
Diff command to compare files on different servers--Unix
<p>Can I use the diff command to compare files on two different servers? If not, is there any other option?</p>
8,593,891
5
0
null
2011-12-21 17:25:39.37 UTC
7
2017-06-30 20:49:11.27 UTC
2016-09-22 07:06:36.06 UTC
null
3,885,376
null
1,013,086
null
1
19
linux|unix|diff
46,387
<p>You can copy the file over from the other server using <code>scp</code> and then use <code>diff</code>.</p> <p>Or <code>ssh</code> to the remote host and <code>diff</code> using a single command like this:</p> <pre><code>ssh user@remote "cat /path/to/remote/file" | diff - /path/to/local/file </code></pre>
26,700,598
Matplotlib showing x-tick labels overlapping
<p>Have a look at the graph below: <img src="https://i.stack.imgur.com/paHpG.png" alt="enter image description here"></p> <p>It's a subplot of this larger figure: <img src="https://i.stack.imgur.com/q8M8w.png" alt="enter image description here"></p> <p>I see two problems with it. First, the x-axis labels overlap with one another (this is my major issue). Second. the location of the x-axis minor gridlines seems a bit wonky. On the left of the graph, they look properly spaced. But on the right, they seem to be crowding the major gridlines...as if the major gridline locations aren't proper multiples of the minor tick locations.</p> <p>My setup is that I have a DataFrame called <code>df</code> which has a <code>DatetimeIndex</code> on the rows and a column called <code>value</code> which contains floats. I can provide an example of the <code>df</code> contents in a gist if necessary. A dozen or so lines of <code>df</code> are at the bottom of this post for reference.</p> <p>Here's the code that produces the figure:</p> <pre><code>now = dt.datetime.now() fig, axes = plt.subplots(2, 2, figsize=(15, 8), dpi=200) for i, d in enumerate([360, 30, 7, 1]): ax = axes.flatten()[i] earlycut = now - relativedelta(days=d) data = df.loc[df.index&gt;=earlycut, :] ax.plot(data.index, data['value']) ax.xaxis_date() ax.get_xaxis().set_minor_locator(mpl.ticker.AutoMinorLocator()) ax.get_yaxis().set_minor_locator(mpl.ticker.AutoMinorLocator()) ax.grid(b=True, which='major', color='w', linewidth=1.5) ax.grid(b=True, which='minor', color='w', linewidth=0.75) </code></pre> <p>What is my best option here to get the x-axis labels to stop overlapping each other (in each of the four subplots)? Also, separately (but less urgently), what's up with the minor tick issue in the top-left subplot?</p> <p>I am on Pandas 0.13.1, numpy 1.8.0, and matplotlib 1.4.x.</p> <p>Here's a small snippet of <code>df</code> for reference:</p> <pre><code> id scale tempseries_id value timestamp 2014-11-02 14:45:10.302204+00:00 7564 F 1 68.0000 2014-11-02 14:25:13.532391+00:00 7563 F 1 68.5616 2014-11-02 14:15:12.102229+00:00 7562 F 1 68.9000 2014-11-02 14:05:13.252371+00:00 7561 F 1 69.0116 2014-11-02 13:55:11.792191+00:00 7560 F 1 68.7866 2014-11-02 13:45:10.782227+00:00 7559 F 1 68.6750 2014-11-02 13:35:10.972248+00:00 7558 F 1 68.4500 2014-11-02 13:25:10.362213+00:00 7557 F 1 68.1116 2014-11-02 13:15:10.822247+00:00 7556 F 1 68.2250 2014-11-02 13:05:10.102200+00:00 7555 F 1 68.5616 2014-11-02 12:55:10.292217+00:00 7554 F 1 69.0116 2014-11-02 12:45:10.382226+00:00 7553 F 1 69.3500 2014-11-02 12:35:10.642245+00:00 7552 F 1 69.2366 2014-11-02 12:25:12.642255+00:00 7551 F 1 69.1250 2014-11-02 12:15:11.122382+00:00 7550 F 1 68.7866 2014-11-02 12:05:11.332224+00:00 7549 F 1 68.5616 2014-11-02 11:55:11.662311+00:00 7548 F 1 68.2250 2014-11-02 11:45:11.122193+00:00 7547 F 1 68.4500 2014-11-02 11:35:11.162271+00:00 7546 F 1 68.7866 2014-11-02 11:25:12.102211+00:00 7545 F 1 69.2366 2014-11-02 11:15:10.422226+00:00 7544 F 1 69.4616 2014-11-02 11:05:11.412216+00:00 7543 F 1 69.3500 2014-11-02 10:55:10.772212+00:00 7542 F 1 69.1250 2014-11-02 10:45:11.332220+00:00 7541 F 1 68.7866 2014-11-02 10:35:11.332232+00:00 7540 F 1 68.5616 2014-11-02 10:25:11.202411+00:00 7539 F 1 68.2250 2014-11-02 10:15:11.932326+00:00 7538 F 1 68.5616 2014-11-02 10:05:10.922229+00:00 7537 F 1 68.9000 2014-11-02 09:55:11.602357+00:00 7536 F 1 69.3500 </code></pre> <p>Edit: Trying <code>fig.autofmt_xdate()</code>: I don't think this going to do the trick. This seems to use the same x-tick labels for both graphs on the left and also for both graphs on the right. Which is not correct given my data. Please see the problematic output below:</p> <p><img src="https://i.stack.imgur.com/cY6po.png" alt="enter image description here"></p>
26,707,813
3
0
null
2014-11-02 14:48:43.03 UTC
19
2021-08-31 08:49:26.727 UTC
2020-08-04 06:55:00.403 UTC
null
4,230,591
null
2,501,018
null
1
60
python|pandas|matplotlib|axis-labels
131,443
<p>Ok, finally got it working. The trick was to use <code>plt.setp</code> to manually rotate the tick labels. Using <code>fig.autofmt_xdate()</code> did not work as it does some unexpected things when you have multiple subplots in your figure. Here's the working code with its output:</p> <pre><code>for i, d in enumerate([360, 30, 7, 1]): ax = axes.flatten()[i] earlycut = now - relativedelta(days=d) data = df.loc[df.index&gt;=earlycut, :] ax.plot(data.index, data['value']) ax.get_xaxis().set_minor_locator(mpl.ticker.AutoMinorLocator()) ax.get_yaxis().set_minor_locator(mpl.ticker.AutoMinorLocator()) ax.grid(b=True, which='major', color='w', linewidth=1.5) ax.grid(b=True, which='minor', color='w', linewidth=0.75) plt.setp(ax.get_xticklabels(), rotation=30, horizontalalignment='right') fig.tight_layout() </code></pre> <p><img src="https://i.stack.imgur.com/8OOK8.jpg" alt="enter image description here"></p> <p>By the way, the comment earlier about some matplotlib things taking forever is very interesting here. I'm using a raspberry pi to act as a weather station at a remote location. It's collecting the data and serving the results via the web. And boy oh boy, it's really wheezing trying to put out these graphics.</p>
346,362
How can xsl:apply-templates match only templates I have defined?
<p>I have several templates that match various nodes in an xml document. If I do just an<br> &lt;xsl:apply-templates/> it somehow recursively outputs the text of all the nodes beneath. I just want it to recursively match any template I have defined. How do I do that ? </p>
346,444
3
0
null
2008-12-06 15:10:46.093 UTC
16
2008-12-06 17:53:44.623 UTC
null
null
null
null
43,940
null
1
26
xslt
19,306
<blockquote> <p>This is happening because of the built-in templates in XSLT. XSLT has a couple of built in templates, which say:</p> <ul> <li>when you apply templates to an element, process its child elements</li> <li>when you apply templates to a text node, give its value</li> </ul> <p>Together, it means that if you apply templates to an element but don't have an explicit template for that element, then its content gets processed and eventually you end up with the text that the element contains.</p> </blockquote> <p>Read the full explanation here: <a href="http://www.dpawson.co.uk/xsl/sect2/defaultrule.html" rel="noreferrer">http://www.dpawson.co.uk/xsl/sect2/defaultrule.html</a></p> <p>You can override the default templates for text nodes by defining your own template and have it do nothing.</p> <pre><code>&lt;xsl:template match="text()" /&gt; </code></pre>
164,342
Should repositories implement IQueryable<T>?
<p>I'm considering one of two IRepository interfaces, one that is a descendant of IQueryable and one that contains IQueryable. </p> <p>Like this:</p> <pre><code>public interface IRepository&lt;T&gt; : IQueryable&lt;T&gt; { T Save(T entity); void Delete(T entity); } </code></pre> <p>Or this:</p> <pre><code>public interface IRepository&lt;T&gt; { T Save(T entity); void Delete(T entity); IQueryable&lt;T&gt; Query(); } </code></pre> <p>LINQ usage would be:</p> <pre><code>from dos in ServiceLocator.Current.GetInstance&lt;IRepository&lt;DomainObject&gt;&gt;() where dos.Id == id select dos </code></pre> <p>Or...</p> <pre><code>from dos in ServiceLocator.Current.GetInstance&lt;IRepository&lt;DomainObject&gt;&gt;().Query where dos.Id == id select dos </code></pre> <p>I kinda like the first one, but it's problematic to mock. How have other people implemented LINQable, mockable repositories?</p>
164,380
3
1
null
2008-10-02 20:13:27.783 UTC
10
2011-03-16 00:25:32.89 UTC
2008-10-02 20:14:34.083 UTC
bdukes
2,688
Andy S
3,759
null
1
27
.net|linq|design-patterns
5,324
<p>Depends on if you want a Has-A or an Is-A relationship.</p> <p>The first one is an Is-A relationship. The IRepository interface is a IQueryable interface. The second is a has-a. The IRepository has an IQueryable interface. In the process of writing this, I actually like the second better then the first, simply because when use your second IRepository, I can give the Query() method ANYTHING that returns IQueryable. To me, that is more flexible then the first implementation.</p>
39,574,096
How to delete pages from pdf file using Python?
<p>I have some .pdf files with more than 500 pages, but I need only a few pages in each file. It is necessary to preserve document`s title pages. I know exactly the numbers of the pages that program should remove. How I can do it using Python 2.7 Environment, which is installed upon MS Visual Studio?</p>
39,574,231
2
0
null
2016-09-19 13:12:17.31 UTC
10
2022-07-02 10:17:15.173 UTC
2016-09-19 13:15:12.48 UTC
null
2,308,683
null
6,194,150
null
1
32
python|pdf
21,967
<p>Try using <a href="https://pypi.python.org/pypi/PyPDF2/" rel="nofollow noreferrer">PyPDF2</a>.</p> <p>Instead of deleting pages, create a new document and add all pages which you don't want to delete.</p> <p>Some sample code (originally adapted from BinPress which is dead, archived <a href="https://reachtim.com/articles/PDF-Manipulation.html#delete" rel="nofollow noreferrer">here</a>).</p> <pre><code>from PyPDF2 import PdfWriter, PdfReader pages_to_keep = [1, 2, 10] # page numbering starts from 0 infile = PdfReader('source.pdf', 'rb') output = PdfWriter() for i in pages_to_keep: p = infile.pages[i] output.add_page(p) with open('newfile.pdf', 'wb') as f: output.write(f) </code></pre> <p>or</p> <pre><code>from PyPDF2 import PdfWriter, PdfReader pages_to_delete = [3, 4, 5] # page numbering starts from 0 infile = PdfReader('source.pdf', 'rb') output = PdfWriter() for i in range(len(infile.pages) ): if i not in pages_to_delete: p = infile.get_page(i) output.add_page(p) with open('newfile.pdf', 'wb') as f: output.write(f) </code></pre>
22,226,718
accessor must be more restrictive than the property or indexer
<p>I have the folowing class:</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.Odbc; namespace Framework { public class OracleProvider { private OdbcConnection db { get; private set; } private String dbUsername = Settings.Default.Username; private String dbPassword = Settings.Default.Password; public OracleProvider() { connect(); } public void connect() { db = new OdbcConnection("Driver={Microsoft ODBC for Oracle};Server=CTIR; UID="+dbUsername+";PWD="+dbPassword+";"); } } } </code></pre> <p>Now I get the following error:</p> <blockquote> <p>Error 11: The accessibility modifier of the 'Framework.OracleProvider.db.set' accessor must be more restrictive than the property or indexer 'Framework.OracleProvider.db'</p> </blockquote> <p>I've been looking at similar questions but haven't really found an answer.</p> <p>Can anyone explain to me why this is happening? I really want to learn.</p>
22,226,762
2
0
null
2014-03-06 14:00:00.87 UTC
6
2021-04-09 06:25:10.177 UTC
2021-04-09 06:25:10.177 UTC
null
2,319,407
null
1,647,457
null
1
35
c#|properties
15,037
<p>This is the problem:</p> <pre><code>private OdbcConnection db { get; private set; } </code></pre> <p>Assuming you really want both the getter and setter to be private, this should be:</p> <pre><code>private OdbcConnection db { get; set; } </code></pre> <p>The setter is <em>already</em> <code>private</code>, as that's the accessibility of the overall property.</p> <p>Alternatively, if you want the getter to be non-private and the setter to be private, you need to specify some other modifier, e.g.</p> <pre><code>internal OdbcConnection db { get; set; } </code></pre> <p>Basically, if you're going to specify an access modifier on the <code>get;</code> or <code>set;</code> part of a property, it has to be more restrictive than it would otherwise be.</p> <p>From section 10.7.2 of the C# specification:</p> <blockquote> <p>The <em>accessor-modifier</em> must declare an accessibility that is strictly more restrictive than the declared accessibility of the property or indexer itself. To be precise:</p> <ul> <li>If the property or indexer has a declared accessibility of <code>public</code>, the <em>accessor-modifier</em> may be either <code>protected internal</code>, <code>internal</code>, <code>protected</code>, or <code>private</code>.</li> <li>If the property or indexer has a declared accessibility of <code>protected internal</code>, the <em>accessor-modifier</em> may be either <code>internal</code>, <code>protected</code>, or <code>private</code>.</li> <li>If the property or indexer has a declared accessibility of <code>internal</code> or <code>protected</code>, the <em>accessor-modifier</em> must be <code>private</code>.</li> <li>If the property or indexer has a declared accessibility of <code>private</code>, no <em>accessor-modifier</em> may be used.</li> </ul> </blockquote> <p>(As an aside, if it's private for both reading and writing, it would probably be better just to use a field. Most of the benefits of using a property are only present if it's exposed beyond the current class. And if you <em>do</em> keep it as a property, consider renaming it to follow normal .NET naming conventions.)</p>
28,544,800
Create circular reveal for pre-Lollipop devices (Android)
<p>Is it possible to get this new Animator for pre-Lollipop devices?</p> <p>I am newbie and I am trying to get the java files from its official <a href="https://developer.android.com/reference/android/view/ViewAnimationUtils.html#createCircularReveal(android.view.View,%20int,%20int,%20float,%20float)" rel="noreferrer">documentation</a>, but I am really lost, I don't know how to find it, etc.</p>
28,604,515
7
1
null
2015-02-16 15:28:51.117 UTC
5
2021-08-30 01:23:46.34 UTC
2016-08-06 20:36:27.68 UTC
null
5,180,017
null
3,262,021
null
1
29
android|animation|material-design|animator
30,367
<p>I find a library for you. <a href="https://github.com/ozodrukh/CircularReveal">Circular reveal</a>, is compatible with 2.3 devices.</p> <p>Hope it helps for you!!</p>
28,764,438
What The Difference between stdio.h and iostream?
<pre><code>#include&lt;stdio.h&gt; int main () { // code } return 0 ; </code></pre> <pre><code>#include&lt;iostream&gt; int main () { // code } </code></pre> <p>Which library is best to use?</p> <p>What is the best and why? And when I code what is the difference in function between them?</p>
28,764,520
3
1
null
2015-02-27 11:49:02.617 UTC
9
2015-03-01 14:18:59.383 UTC
2015-03-01 14:18:59.383 UTC
null
3,425,536
null
4,612,285
null
1
9
c++
57,822
<p><code>stdio.h</code> is the header file in the C standard library. It is used for input/output</p> <p><code>iostream</code> is the input output class in C++</p> <p>So if you're using C++ just use <code>#include &lt;iostream&gt;</code></p>